-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathlib.rs
192 lines (167 loc) · 6.06 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
use crate::{
assets::{LuaFile, LuaLoader},
docs::LuaDocFragment,
};
use bevy::{ecs::schedule::ScheduleLabel, prelude::*};
use bevy_mod_scripting_core::{prelude::*, systems::*, world::WorldPointerGuard};
use std::fmt;
use std::marker::PhantomData;
use std::sync::Mutex;
use tealr::mlu::mlua::{prelude::*, Function};
pub mod assets;
pub mod docs;
pub mod util;
pub use tealr;
pub mod prelude {
pub use crate::{
assets::{LuaFile, LuaLoader},
docs::{LuaDocFragment, TypeWalkerBuilder},
tealr::{
self,
mlu::{
mlua::{self, prelude::*, Value},
TealData,
},
},
LuaEvent, LuaScriptHost,
};
}
pub trait LuaArg: for<'lua> ToLuaMulti<'lua> + Clone + Sync + Send + 'static {}
impl<T: for<'lua> ToLuaMulti<'lua> + Clone + Sync + Send + 'static> LuaArg for T {}
#[derive(Clone, Event)]
/// A Lua Hook. The result of creating this event will be
/// a call to the lua script with the hook_name and the given arguments
pub struct LuaEvent<A: LuaArg> {
pub hook_name: String,
pub args: A,
pub recipients: Recipients,
}
impl<A: LuaArg> fmt::Debug for LuaEvent<A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("LuaEvent")
.field("hook_name", &self.hook_name)
.field("recipients", &self.recipients)
.finish()
}
}
impl<A: LuaArg> ScriptEvent for LuaEvent<A> {
fn recipients(&self) -> &crate::Recipients {
&self.recipients
}
}
#[derive(Resource)]
/// Lua script host, enables Lua scripting.
pub struct LuaScriptHost<A: LuaArg> {
_ph: PhantomData<A>,
}
impl<A: LuaArg> Default for LuaScriptHost<A> {
fn default() -> Self {
Self {
_ph: Default::default(),
}
}
}
impl<A: LuaArg> ScriptHost for LuaScriptHost<A> {
type ScriptContext = Mutex<Lua>;
type APITarget = Mutex<Lua>;
type ScriptEvent = LuaEvent<A>;
type ScriptAsset = LuaFile;
type DocTarget = LuaDocFragment;
fn register_with_app_in_set(app: &mut App, schedule: impl ScheduleLabel, set: impl SystemSet) {
app.add_priority_event::<Self::ScriptEvent>()
.add_asset::<LuaFile>()
.init_asset_loader::<LuaLoader>()
.init_resource::<CachedScriptState<Self>>()
.init_resource::<ScriptContexts<Self::ScriptContext>>()
.init_resource::<APIProviders<Self>>()
.register_type::<ScriptCollection<Self::ScriptAsset>>()
.register_type::<Script<Self::ScriptAsset>>()
.register_type::<Handle<LuaFile>>()
// handle script insertions removal first
// then update their contexts later on script asset changes
.add_systems(
schedule,
(
script_add_synchronizer::<Self>,
script_remove_synchronizer::<Self>,
script_hot_reload_handler::<Self>,
)
.chain()
.in_set(set),
);
}
fn load_script(
&mut self,
script: &[u8],
script_data: &ScriptData,
providers: &mut APIProviders<Self>,
) -> Result<Self::ScriptContext, ScriptError> {
#[cfg(feature = "unsafe_lua_modules")]
let lua = unsafe { Lua::unsafe_new() };
#[cfg(not(feature = "unsafe_lua_modules"))]
let lua = Lua::new();
lua.load(script)
.set_name(script_data.name)
.and_then(|c| c.exec())
.map_err(|e| ScriptError::FailedToLoad {
script: script_data.name.to_owned(),
msg: e.to_string(),
})?;
let mut lua = Mutex::new(lua);
providers.attach_all(&mut lua)?;
Ok(lua)
}
fn setup_script(
&mut self,
script_data: &ScriptData,
ctx: &mut Self::ScriptContext,
providers: &mut APIProviders<Self>,
) -> Result<(), ScriptError> {
// safety: this is fine, world will only ever be accessed
providers.setup_all(script_data, ctx)
}
fn handle_events<'a>(
&mut self,
world: &mut World,
events: &[Self::ScriptEvent],
ctxs: impl Iterator<Item = (ScriptData<'a>, &'a mut Self::ScriptContext)>,
providers: &mut APIProviders<Self>,
) {
// safety:
// - we have &mut World access
// - we do not use the original reference again anywhere in this function
let world = unsafe { WorldPointerGuard::new(world) };
ctxs.for_each(|(script_data, ctx)| {
providers
.setup_runtime_all(world.clone(), &script_data, ctx)
.expect("Could not setup script runtime");
let ctx = ctx.get_mut().expect("Poison error in context");
// event order is preserved, but scripts can't rely on any temporal
// guarantees when it comes to other scripts callbacks,
// at least for now.
let globals = ctx.globals();
for event in events {
// check if this script should handle this event
if !event.recipients().is_recipient(&script_data) {
continue;
}
let f: Function = match globals.raw_get(event.hook_name.clone()) {
Ok(f) => f,
Err(_) => continue, // not subscribed to this event
};
if let Err(error) = f.call::<_, ()>(event.args.clone()) {
let mut world = world.write();
let mut state: CachedScriptState<Self> = world.remove_resource().unwrap();
let (_, mut error_wrt, _) = state.event_state.get_mut(&mut world);
let error = ScriptError::RuntimeError {
script: script_data.name.to_owned(),
msg: error.to_string(),
};
error!("{}", error);
error_wrt.send(ScriptErrorEvent { error });
world.insert_resource(state);
}
}
});
}
}