1use crate::prelude::*;
2
3use bevy_tasks::{ComputeTaskPool, TaskPool, ThreadExecutor};
4use bones_asset::dashmap::mapref::one::{MappedRef, MappedRefMut};
5use bones_lib::ecs::utils::*;
6
7use parking_lot::Mutex;
8pub use piccolo;
9use piccolo::{
10 compiler::{LineNumber, ParseError},
11 registry::{Fetchable, Stashable},
12 Closure, Context, Executor, FromValue, Lua, PrototypeError, StashedClosure, Table, UserData,
13 Value,
14};
15use send_wrapper::SendWrapper;
16use std::{any::Any, rc::Rc, sync::Arc};
17
18#[macro_use]
19mod freeze;
20use freeze::*;
21
22mod asset;
23pub use asset::*;
24
25mod ext;
26pub use ext::*;
27
28pub mod bindings;
29
30pub fn lua_game_plugin(game: &mut Game) {
32 LuaScript::register_schema();
34
35 bindings::register_lua_typedata();
37
38 game.init_shared_resource::<LuaEngine>();
40}
41
42pub struct LuaPluginLoaderSessionPlugin(pub Arc<Vec<Handle<LuaPlugin>>>);
44
45#[derive(HasSchema, Deref, DerefMut, Default, Clone)]
47pub struct LuaPlugins(pub Arc<Vec<Handle<LuaPlugin>>>);
48
49impl SessionPlugin for LuaPluginLoaderSessionPlugin {
50 fn install(self, session: &mut Session) {
51 session.add_startup_resource(LuaPlugins(self.0));
52
53 for lua_stage in [
54 CoreStage::Startup,
55 CoreStage::First,
56 CoreStage::PreUpdate,
57 CoreStage::Update,
58 CoreStage::PostUpdate,
59 CoreStage::Last,
60 ] {
61 session.stages.add_system_to_stage(
62 lua_stage,
63 move |engine: Res<LuaEngine>,
64 asset_server: Res<AssetServer>,
65 lua_plugins: Res<LuaPlugins>,
66 world: &World| {
67 engine.exec(|lua| {
68 Frozen::<Freeze![&'freeze World]>::in_scope(world, |world| {
69 lua.enter(|ctx| {
70 let env = ctx.singletons().get(ctx, bindings::env);
71 let worldref = WorldRef(world);
72 worldref.add_to_env(ctx, env);
73 });
74
75 for plugin_handle in lua_plugins.iter() {
76 let Some(plugin) = asset_server.try_get(*plugin_handle) else {
77 return;
78 };
79 let plugin = plugin.unwrap();
80
81 if !plugin.has_loaded() {
83 if let Err(e) = plugin.load(engine.executor.clone(), lua) {
84 tracing::error!("Error loading lua plugin: {e}");
85 }
86 }
87
88 let mut systems = plugin.systems.borrow_mut();
89 let systems = systems.as_loaded_mut();
90
91 for (stage, closure) in &systems.core_stages {
92 if stage == &lua_stage {
93 let executor = lua.enter(|ctx| {
94 let closure = ctx.registry().fetch(closure);
95 let ex = Executor::start(ctx, closure.into(), ());
96 ctx.registry().stash(&ctx, ex)
97 });
98 if let Err(e) = lua.execute::<()>(&executor) {
99 tracing::error!("Error running lua plugin system: {e}");
100 }
101 }
102 }
103 }
104 })
105 });
106 },
107 );
108 }
109 }
110}
111
112#[derive(Deref, DerefMut, Clone)]
116pub struct WorldRef(Frozen<Freeze![&'freeze World]>);
117impl Default for WorldRef {
118 fn default() -> Self {
119 Self(Frozen::new())
120 }
121}
122impl<'gc> FromValue<'gc> for &'gc WorldRef {
123 fn from_value(_ctx: Context<'gc>, value: Value<'gc>) -> Result<Self, piccolo::TypeError> {
124 value.as_static_user_data::<WorldRef>()
125 }
126}
127
128impl WorldRef {
129 pub fn into_userdata(self, ctx: Context<'_>) -> UserData<'_> {
131 let data = UserData::new_static(&ctx, self);
132 data.set_metatable(
133 &ctx,
134 Some(ctx.singletons().get(ctx, bindings::world::metatable)),
135 );
136 data
137 }
138
139 fn add_to_env<'gc>(&self, ctx: Context<'gc>, env: Table<'gc>) {
141 ctx.globals()
142 .set(ctx, "world", self.clone().into_userdata(ctx))
143 .unwrap();
144 for (name, metatable) in [
145 ("world", bindings::world::metatable as fn(Context) -> Table),
146 ("components", bindings::components::metatable),
147 ("resources", bindings::resources::metatable),
148 ("assets", bindings::assets::metatable),
149 ] {
150 let data = UserData::new_static(&ctx, self.clone());
151 data.set_metatable(&ctx, Some(ctx.singletons().get(ctx, metatable)));
152 env.set(ctx, name, data).unwrap();
153 }
154 }
155}
156
157#[derive(HasSchema, Clone)]
159#[schema(no_default)]
160pub struct LuaEngine {
161 executor: Arc<ThreadExecutor<'static>>,
164 state: Arc<SendWrapper<EngineState>>,
166}
167
168struct EngineState {
170 lua: Mutex<Lua>,
172 data: LuaSingletons,
175 compiled_scripts: Mutex<HashMap<Cid, StashedClosure>>,
177}
178
179pub struct LuaSingletons {
188 singletons: Rc<AtomicCell<HashMap<usize, Box<dyn Any>>>>,
189}
190impl Default for LuaSingletons {
191 fn default() -> Self {
192 Self {
193 singletons: Rc::new(AtomicCell::new(HashMap::default())),
194 }
195 }
196}
197impl LuaSingletons {
198 fn get<
202 'gc,
203 S: Fetchable<'gc, Fetched = T> + 'static,
204 T: Stashable<'gc, Stashed = S> + Clone + Copy + 'gc,
205 >(
206 &self,
207 ctx: Context<'gc>,
208 singleton: fn(Context<'gc>) -> T,
209 ) -> T {
210 let map = self.singletons.borrow_mut();
211 let id = singleton as usize;
212 if let Some(entry) = map.get(&id) {
213 let stashed = entry.downcast_ref::<S>().expect(
214 "Encountered two functions with different return types and \
215 the same function pointer.",
216 );
217 ctx.registry().fetch(stashed)
218 } else {
219 drop(map); let v = singleton(ctx);
221 let stashed = ctx.registry().stash(&ctx, v);
222 self.singletons.borrow_mut().insert(id, Box::new(stashed));
223 v
224 }
225 }
226}
227
228impl Default for EngineState {
229 fn default() -> Self {
230 let mut lua = Lua::core();
232 lua.try_enter(|ctx| {
233 ctx.globals().set(
235 ctx,
236 "luasingletons",
237 UserData::new_static(&ctx, LuaSingletons::default()),
238 )?;
239 Ok(())
240 })
241 .unwrap();
242 Self {
243 lua: Mutex::new(lua),
244 data: default(),
245 compiled_scripts: default(),
246 }
247 }
248}
249
250impl Default for LuaEngine {
251 fn default() -> Self {
253 ComputeTaskPool::init(TaskPool::new);
255
256 #[cfg(not(target_arch = "wasm32"))]
257 let executor = {
258 let (send, recv) = async_channel::bounded(1);
259
260 let pool = ComputeTaskPool::get();
262 pool.spawn_local(async move {
263 let executor = Arc::new(ThreadExecutor::new());
264 send.try_send(executor.clone()).unwrap();
265
266 let ticker = (*executor).ticker().unwrap();
267 loop {
268 ticker.tick().await;
269 }
270 })
271 .detach();
272 pool.with_local_executor(|local| while local.try_tick() {});
273
274 recv.try_recv().unwrap()
275 };
276
277 #[cfg(target_arch = "wasm32")]
278 let executor = Arc::new(ThreadExecutor::new());
279
280 LuaEngine {
281 executor,
282 state: Arc::new(SendWrapper::new(default())),
283 }
284 }
285}
286
287impl LuaEngine {
288 pub fn exec<'a, F: FnOnce(&mut Lua) + Send + 'a>(&self, f: F) {
290 let pool = ComputeTaskPool::get();
291
292 pool.scope_with_executor(false, Some(&self.executor), |scope| {
294 scope.spawn_on_external(async {
295 f(&mut self.state.lua.lock());
296 });
297 });
298 }
299
300 pub fn run_script_system(&self, world: &World, script: Handle<LuaScript>) {
302 self.exec(|lua| {
303 Frozen::<Freeze![&'freeze World]>::in_scope(world, |world| {
304 let worldref = WorldRef(world);
306
307 let executor = lua.try_enter(|ctx| {
308 let env = self.state.data.get(ctx, bindings::env);
310
311 let closure = worldref.with(|world| {
313 let asset_server = world.resource::<AssetServer>();
314 let cid = *asset_server
315 .store
316 .asset_ids
317 .get(&script.untyped())
318 .ok_or_else(|| {
319 tracing::warn!("Script asset not loaded.");
320 PrototypeError::Parser(ParseError {
321 kind: piccolo::compiler::ParseErrorKind::EndOfStream {
322 expected: None,
323 },
324 line_number: LineNumber(0),
325 })
326 })?;
327
328 let mut compiled_scripts = self.state.compiled_scripts.lock();
329 let closure = compiled_scripts.get(&cid);
330
331 Ok::<_, PrototypeError>(match closure {
332 Some(closure) => ctx.registry().fetch(closure),
333 None => {
334 let asset = asset_server.store.assets.get(&cid).unwrap();
335 let source = &asset.data.cast_ref::<LuaScript>().source;
336 let closure =
338 Closure::load_with_env(ctx, None, source.as_bytes(), env)?;
339 compiled_scripts.insert(cid, ctx.registry().stash(&ctx, closure));
340
341 closure
342 }
343 })
344 })?;
345
346 worldref.add_to_env(ctx, env);
348
349 let ex = Executor::start(ctx, closure.into(), ());
350 let ex = ctx.registry().stash(&ctx, ex);
351 Ok(ex)
352 });
353
354 if let Err(e) = executor.and_then(|ex| lua.execute::<()>(&ex)) {
355 tracing::error!("{e}");
356 }
357 });
358 });
359 }
360}