-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathevent_recipients.rs
134 lines (113 loc) · 3.94 KB
/
event_recipients.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
use bevy::prelude::*;
use bevy_mod_scripting::prelude::*;
use rand::prelude::SliceRandom;
use std::sync::atomic::Ordering::Relaxed;
use std::sync::{atomic::AtomicU32, Mutex};
#[derive(Clone)]
pub struct MyLuaArg(usize);
impl<'lua> IntoLua<'lua> for MyLuaArg {
fn into_lua(self, lua: &'lua Lua) -> mlua::Result<Value<'lua>> {
self.0.into_lua(lua)
}
}
#[derive(Default)]
pub struct LuaAPIProvider;
/// the custom Lua api, world is provided via a global pointer,
/// and callbacks are defined only once at script creation
impl APIProvider for LuaAPIProvider {
type APITarget = Mutex<Lua>;
type DocTarget = LuaDocFragment;
type ScriptContext = Mutex<Lua>;
fn attach_api(&mut self, ctx: &mut Self::APITarget) -> Result<(), ScriptError> {
// callbacks can receive any `ToLuaMulti` arguments, here '()' and
// return any `FromLuaMulti` arguments, here a `usize`
// check the Rlua documentation for more details
let ctx = ctx.get_mut().unwrap();
ctx.globals()
.set(
"print",
ctx.create_function(|_ctx, msg: String| {
info!("{}", msg);
Ok(())
})
.map_err(ScriptError::new_other)?,
)
.map_err(ScriptError::new_other)?;
Ok(())
}
fn setup_script(
&mut self,
script_data: &ScriptData,
ctx: &mut Self::ScriptContext,
) -> Result<(), ScriptError> {
let ctx = ctx.get_mut().unwrap();
let globals = ctx.globals();
globals
.set("script_id", script_data.sid)
.map_err(ScriptError::new_other)?;
Ok(())
}
}
static COUNTER: AtomicU32 = AtomicU32::new(0);
/// utility for generating random events from a list
fn fire_random_event(w: &mut PriorityEventWriter<LuaEvent<MyLuaArg>>, events: &[ScriptEventData]) {
let mut rng = rand::thread_rng();
let id = COUNTER.fetch_add(1, Relaxed);
let arg = MyLuaArg(id as usize);
let event = events
.choose(&mut rng)
.map(|v| LuaEvent {
hook_name: v.0.to_string(),
args: arg,
recipients: v.1.clone(),
})
.unwrap();
info!(
"\t - event: {},\t recipients: {:?},\t id: {}",
event.hook_name, event.recipients, id
);
w.send(event, 0);
}
fn do_update(mut w: PriorityEventWriter<LuaEvent<MyLuaArg>>) {
info!("Update, firing:");
let all_events = [
ScriptEventData("on_event", Recipients::All),
ScriptEventData("on_event", Recipients::ScriptID(0)),
ScriptEventData("on_event", Recipients::ScriptID(1)),
ScriptEventData(
"on_event",
Recipients::ScriptName("scripts/event_recipients.lua".to_owned()),
),
];
// fire random event, for any of the system sets
fire_random_event(&mut w, &all_events);
}
#[derive(Clone)]
pub struct ScriptEventData(&'static str, Recipients);
fn load_our_scripts(server: Res<AssetServer>, mut commands: Commands) {
// spawn two identical scripts
// id's will be 0 and 1
let path = "scripts/event_recipients.lua";
let handle = server.load::<LuaFile>(path);
let scripts = (0..2)
.map(|_| Script::<LuaFile>::new(path.to_string(), handle.clone()))
.collect();
commands
.spawn(())
.insert(ScriptCollection::<LuaFile> { scripts });
}
fn main() -> std::io::Result<()> {
let mut app = App::new();
app.add_plugins(DefaultPlugins)
.add_plugins(ScriptingPlugin)
.add_systems(Startup, load_our_scripts)
// randomly fire events for either all scripts,
// the script with id 0
// or the script with id 1
.add_systems(Update, do_update)
.add_script_handler::<LuaScriptHost<MyLuaArg>, 0, 0>(PostUpdate)
.add_script_host::<LuaScriptHost<MyLuaArg>>(PostUpdate)
.add_api_provider::<LuaScriptHost<MyLuaArg>>(Box::new(LuaAPIProvider));
app.run();
Ok(())
}