oxeon 0.0.5

Rust-like scripting language for modding Bevy games, compiled to sandboxed WebAssembly.
Documentation
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
//! Oxeon: a Rust-like scripting language for modding Bevy games.
//!
//! Mods are `.ox` files loaded through Bevy's asset system, compiled to
//! WebAssembly and run sandboxed in Wasmtime. Their systems use Bevy's own
//! ECS: the game decides which components mods may see, and mod systems run
//! on the game's schedule.
//!
//! ```no_run
//! use bevy_app::{App, Startup, TaskPoolPlugin};
//! use bevy_asset::{AssetPlugin, AssetServer};
//! use bevy_ecs::prelude::*;
//! use bevy_reflect::Reflect;
//! use bevy_time::TimePlugin;
//! use oxeon::prelude::*;
//!
//! #[derive(Component, Reflect)]
//! #[reflect(Component)]
//! struct Health(f32);
//!
//! fn load_mods(mut commands: Commands, assets: Res<AssetServer>) {
//!     commands.spawn(OxeonMod(assets.load("mods/regen.ox")));
//! }
//!
//! App::new()
//!     .add_plugins((TaskPoolPlugin::default(), TimePlugin, AssetPlugin::default()))
//!     .add_plugins(OxeonPlugin::default())
//!     .expose_to_mods::<Health>()
//!     .add_systems(Startup, load_mods)
//!     .run();
//! ```
//!
//! A mod can then use `Health` like its own type:
//!
//! ```text
//! fn heal(time: Res<Time>, mut q: Query<&mut Health>) {
//!     for mut hp in &mut q {
//!         hp.0 += 1.0 * time.delta_secs();
//!     }
//! }
//!
//! pub fn plugin(app: &mut App) {
//!     app.add_systems(Update, heal);
//! }
//! ```
//!
//! **Status:** early development. Mod systems can use `Res`/`ResMut` of
//! exposed resources, `Commands` (spawn, insert, despawn),
//! `MessageReader`/`MessageWriter` (the game's messages and their own), and
//! `Query`s over exposed components and components the mod defines, with
//! `Entity` and `With`, `Without`, `Changed` and `Added` filters, and run in
//! `Startup` and `Update`. Fields must be numbers, `bool`, `char`, or
//! structs of those, such as `Transform`.

mod asset;
mod bindings;
mod bridge;
mod components;
mod messages;

pub use asset::{OxeonSource, OxeonSourceLoader};
pub use bindings::OxeonBindings;

use std::collections::HashMap;

use bevy_app::{App, Plugin, Update};
use bevy_asset::prelude::*;
use bevy_ecs::prelude::*;
use bevy_ecs::reflect::AppTypeRegistry;
use bevy_reflect::{GetTypeRegistration, Reflect, TypePath};
use oxeon_diagnostics::RenderOptions;
use oxeon_runtime::{Runtime, RuntimeConfig};

use bindings::ExposedTypes;
use bridge::LoadedMod;

pub mod prelude {
    pub use crate::{
        LoadModSource, LogLevel, ModLog, ModReport, OxeonAppExt, OxeonMod, OxeonPlugin,
        OxeonSource, UnloadMod,
    };
}

/// Adds Oxeon mods to a Bevy app. Requires Bevy's `AssetPlugin`, and its
/// `TimePlugin` for mods that use `Res<Time>`.
#[derive(Default)]
pub struct OxeonPlugin {
    pub runtime: RuntimeConfig,
    /// Where to write the game's bindings (the Oxeon declarations of the
    /// types it exposes) at startup, for editors. The language server reads
    /// a file named `oxeon-bindings.ox` next to a mod or in a folder above
    /// it, so `assets/oxeon-bindings.ox` covers every mod under `assets/`
    /// (keep it out of a folder you load mods from as a whole).
    pub bindings_file: Option<std::path::PathBuf>,
}

impl Plugin for OxeonPlugin {
    fn build(&self, app: &mut App) {
        let runtime =
            Runtime::new(self.runtime.clone()).expect("failed to create the Oxeon runtime");
        app.insert_resource(OxeonRuntime(runtime))
            .init_resource::<ExposedTypes>()
            .init_resource::<OxeonBindings>()
            .init_resource::<LoadedMods>()
            .init_resource::<SourceMods>()
            .init_asset::<OxeonSource>()
            .register_asset_loader(OxeonSourceLoader)
            .register_type::<OxeonMod>()
            .add_message::<LoadModSource>()
            .add_message::<UnloadMod>()
            .add_message::<ModReport>()
            .add_message::<ModLog>()
            .add_systems(Update, (apply_mod_sources, compile_mods, run_mods).chain());
    }

    /// Bindings are generated once every plugin has exposed its types.
    fn finish(&self, app: &mut App) {
        let exposed = app.world().resource::<ExposedTypes>().0.clone();
        let messages = app
            .world()
            .get_resource::<bindings::ExposedMessages>()
            .map(|m| m.0.clone())
            .unwrap_or_default();
        let registry = app.world().resource::<AppTypeRegistry>().clone();
        let (bindings, problems) = bindings::generate(&registry.read(), &exposed, &messages);
        for problem in problems {
            bevy_log::warn!("{problem}");
        }
        if let Some(path) = &self.bindings_file {
            let text = format!(
                "// The types this game exposes to mods, for editors. Generated by\n\
                 // `OxeonPlugin` at startup: don't edit, it's rewritten.\n\n{}",
                bindings.declarations
            );
            // Only rewrite when it changed, so file watchers stay quiet.
            if std::fs::read_to_string(path).ok().as_deref() != Some(text.as_str())
                && let Err(e) = std::fs::write(path, text)
            {
                bevy_log::warn!("couldn't write the bindings file {}: {e}", path.display());
            }
        }
        app.insert_resource(bindings);
    }
}

/// Lets a game choose which of its types mods can use.
pub trait OxeonAppExt {
    /// Makes a component or resource available to mods, under its type
    /// name. Its fields must be numbers, `bool`, `char`, or structs of those
    /// (like `Transform`'s `Vec3`s, which are declared too), and it needs
    /// `#[derive(Reflect)]` with `#[reflect(Component)]` (or
    /// `#[reflect(Resource)]`).
    fn expose_to_mods<T: Component + Reflect + GetTypeRegistration + TypePath>(
        &mut self,
    ) -> &mut Self;

    /// Lets mods read and send a message type with `MessageReader<M>` and
    /// `MessageWriter<M>`. Add it to the app as usual too (`add_message`).
    /// Its fields must be numbers, `bool`, `char`, or structs of those, and it
    /// needs
    /// `#[derive(Reflect)]`.
    fn expose_message_to_mods<
        M: bevy_ecs::message::Message
            + Reflect
            + bevy_reflect::FromReflect
            + GetTypeRegistration
            + TypePath,
    >(
        &mut self,
    ) -> &mut Self;
}

impl OxeonAppExt for App {
    fn expose_to_mods<T: Component + Reflect + GetTypeRegistration + TypePath>(
        &mut self,
    ) -> &mut Self {
        self.register_type::<T>();
        self.world_mut()
            .get_resource_or_init::<ExposedTypes>()
            .0
            .push(std::any::TypeId::of::<T>());
        self
    }

    fn expose_message_to_mods<
        M: bevy_ecs::message::Message
            + Reflect
            + bevy_reflect::FromReflect
            + GetTypeRegistration
            + TypePath,
    >(
        &mut self,
    ) -> &mut Self {
        self.register_type::<M>();
        let id = std::any::TypeId::of::<M>();
        let world = self.world_mut();
        world
            .get_resource_or_init::<bindings::ExposedMessages>()
            .0
            .push(id);
        world
            .get_resource_or_init::<messages::MessageFnsMap>()
            .0
            .insert(id, messages::MessageFns::of::<M>());
        self
    }
}

/// The shared Wasmtime engine used for every mod.
#[derive(Resource, Clone)]
pub struct OxeonRuntime(pub Runtime);

/// Marks an entity as an Oxeon mod, backed by a `.ox` source asset. Keeping
/// the handle keeps the mod loaded.
#[derive(Component, Reflect, Clone)]
pub struct OxeonMod(pub Handle<OxeonSource>);

/// Mods that compiled, by source asset.
#[derive(Resource, Default)]
struct LoadedMods(HashMap<AssetId<OxeonSource>, LoadedMod>);

/// Adds a mod from its source text, not a file: for editors and
/// playgrounds that hold the source themselves. A mod with the same name
/// is replaced, which recompiles it the way a hot reload does: if the new
/// source doesn't compile, the previous version keeps running.
#[derive(bevy_ecs::message::Message, Clone, Debug)]
pub struct LoadModSource {
    pub name: String,
    pub source: String,
}

/// Removes a mod added with [`LoadModSource`].
#[derive(bevy_ecs::message::Message, Clone, Debug)]
pub struct UnloadMod {
    pub name: String,
}

/// What happened to a mod, for showing it to whoever wrote it. A mod is
/// named by its asset path, or by the name it was loaded with.
#[derive(bevy_ecs::message::Message, Clone, Debug, PartialEq)]
pub enum ModReport {
    /// It compiled and runs (again, after a reload).
    Loaded { name: String, systems: Vec<String> },
    /// It doesn't compile. `kept_previous` says whether an earlier version
    /// keeps running.
    CompileFailed {
        name: String,
        errors: Vec<String>,
        kept_previous: bool,
    },
    /// A system trapped or ran out of fuel, so the mod stopped.
    Disabled {
        name: String,
        system: String,
        error: String,
    },
}

/// A message a mod logged with `info!`, `println!` and the like. It's also
/// written to Bevy's log (`println!` at the info level, `eprintln!` at the
/// error level), prefixed with the mod's name.
#[derive(bevy_ecs::message::Message, Clone, Debug, PartialEq)]
pub struct ModLog {
    pub name: String,
    pub level: LogLevel,
    pub text: String,
}

pub use oxeon_compiler::format::Level as LogLevel;

/// Mods added from source text, by name.
#[derive(Resource, Default)]
struct SourceMods(HashMap<String, (Handle<OxeonSource>, Entity)>);

/// Applies [`LoadModSource`] and [`UnloadMod`].
fn apply_mod_sources(
    mut commands: Commands,
    mut loads: MessageReader<LoadModSource>,
    mut unloads: MessageReader<UnloadMod>,
    mut sources: ResMut<Assets<OxeonSource>>,
    mut mods: ResMut<SourceMods>,
) {
    for LoadModSource { name, source } in loads.read() {
        if let Some((handle, _)) = mods.0.get(name)
            && let Some(mut existing) = sources.get_mut(handle)
        {
            existing.source = source.clone();
            continue;
        }
        let handle = sources.add(OxeonSource {
            source: source.clone(),
            name: Some(name.clone()),
        });
        let entity = commands.spawn(OxeonMod(handle.clone())).id();
        mods.0.insert(name.clone(), (handle, entity));
    }
    for UnloadMod { name } in unloads.read() {
        // Dropping the last handles unloads the mod.
        if let Some((_, entity)) = mods.0.remove(name) {
            commands.entity(entity).despawn();
        }
    }
}

/// Compiles mods when they load or change. Recompiling replaces the
/// running module; game state lives in the ECS, so nothing is lost. A
/// version that doesn't compile leaves the previous one running.
// A Bevy system: its parameters are what it uses.
#[allow(clippy::too_many_arguments)]
fn compile_mods(
    mut events: MessageReader<AssetEvent<OxeonSource>>,
    sources: Res<Assets<OxeonSource>>,
    server: Res<AssetServer>,
    bindings: Res<OxeonBindings>,
    runtime: Res<OxeonRuntime>,
    mut mods: ResMut<LoadedMods>,
    mut reports: MessageWriter<ModReport>,
    mut commands: Commands,
) {
    // A change can arrive as several events; handle each mod once.
    let mut changed = Vec::new();
    for event in events.read() {
        match event {
            // Sent on the first load and after every reload (as is `Modified`).
            AssetEvent::LoadedWithDependencies { id } => {
                if !changed.contains(id) {
                    changed.push(*id);
                }
            }
            // A source given as text only gets these. (A file gets them too,
            // a frame before `LoadedWithDependencies`: compiling it twice
            // would run its `Startup` systems twice.)
            AssetEvent::Added { id } | AssetEvent::Modified { id } => {
                if sources.get(*id).is_some_and(|s| s.name.is_some()) && !changed.contains(id) {
                    changed.push(*id);
                }
            }
            AssetEvent::Removed { id } | AssetEvent::Unused { id } => {
                if let Some(m) = mods.0.remove(id) {
                    commands.queue(move |world: &mut World| {
                        components::remove_mod_resources(world, &m.path);
                    });
                }
                changed.retain(|c| c != id);
            }
        }
    }
    for id in changed {
        let Some(source) = sources.get(id) else {
            continue;
        };
        let path = match &source.name {
            Some(name) => name.clone(),
            None => server
                .get_path(id)
                .map_or_else(|| "mod".to_owned(), |p| p.to_string()),
        };
        let compiled = match oxeon_compiler::compile_with_prelude(&source.source, &bindings.prelude)
        {
            Ok(compiled) => compiled,
            Err(errors) => {
                for e in &errors {
                    bevy_log::error!(
                        "{}",
                        e.render(&path, &source.source, RenderOptions::default())
                    );
                }
                let kept_previous = mods.0.contains_key(&id);
                if kept_previous {
                    bevy_log::warn!(
                        "{path}: keeping the previous version until the errors are fixed"
                    );
                }
                reports.write(ModReport::CompileFailed {
                    name: path.clone(),
                    errors: errors
                        .iter()
                        .map(|e| e.render_plain(&path, &source.source))
                        .collect(),
                    kept_previous,
                });
                continue;
            }
        };
        for w in &compiled.warnings {
            if w.severity == oxeon_diagnostics::Severity::Warning {
                bevy_log::warn!(
                    "{}",
                    w.render(&path, &source.source, RenderOptions::default())
                );
            } else {
                bevy_log::debug!("{}", w.render_plain(&path, &source.source));
            }
        }
        for s in &compiled.systems {
            if let Some(schedule) = &s.schedule
                && !matches!(schedule.as_str(), "Startup" | "Update")
            {
                bevy_log::warn!(
                    "{path}: `{}` uses the schedule `{schedule}`, which mods can't use yet",
                    s.name
                );
            }
        }
        let instance = runtime
            .0
            .load(&compiled.wasm)
            .and_then(|module| runtime.0.instantiate(&module));
        match instance {
            Ok(instance) => {
                bevy_log::info!("loaded {path} ({} system(s))", compiled.systems.len());
                reports.write(ModReport::Loaded {
                    name: path.clone(),
                    systems: compiled.systems.iter().map(|s| s.name.clone()).collect(),
                });
                let layouts = compiled
                    .layouts
                    .iter()
                    .map(|l| (l.name.clone(), l.clone()))
                    .collect();
                mods.0.insert(
                    id,
                    LoadedMod {
                        path,
                        instance,
                        systems: compiled.systems,
                        layouts,
                        command_components: compiled.command_components,
                        log_sites: compiled.log_sites,
                        has_plugin: compiled
                            .functions
                            .iter()
                            .any(|f| f.name == "plugin" && f.params.len() == 1),
                        last_run: HashMap::new(),
                        cursors: HashMap::new(),
                        messages_seen: HashMap::new(),
                        started: false,
                        failed: false,
                    },
                );
            }
            Err(e) => {
                bevy_log::error!("{path}: {e}");
                reports.write(ModReport::CompileFailed {
                    name: path.clone(),
                    errors: vec![e.to_string()],
                    kept_previous: mods.0.contains_key(&id),
                });
            }
        }
    }
}

/// Runs each loaded mod's systems for this frame. A mod whose system fails
/// (a trap, or running out of fuel) is disabled; the game keeps running.
fn run_mods(world: &mut World) {
    world
        .get_resource_or_init::<messages::ModMessages>()
        .new_frame();
    world.resource_scope(|world, mut mods: Mut<LoadedMods>| {
        let bindings = world.resource::<OxeonBindings>().clone();
        for m in mods.0.values_mut() {
            if m.failed {
                continue;
            }
            let first_run = !m.started;
            m.started = true;
            if first_run
                && m.has_plugin
                && let Err(e) = bridge::run_plugin(world, m)
            {
                bevy_log::error!("{}: `plugin` failed, so the mod is disabled: {e}", m.path);
                world.write_message(ModReport::Disabled {
                    name: m.path.clone(),
                    system: "plugin".to_owned(),
                    error: e,
                });
                m.failed = true;
                continue;
            }
            for system in m.systems.clone() {
                let runs = match system.schedule.as_deref() {
                    Some("Update") => true,
                    Some("Startup") => first_run,
                    _ => false,
                };
                if !runs {
                    continue;
                }
                if let Err(e) = bridge::run_system(world, &bindings, m, &system) {
                    bevy_log::error!(
                        "{}: `{}` failed, so the mod is disabled: {e}",
                        m.path,
                        system.name
                    );
                    world.write_message(ModReport::Disabled {
                        name: m.path.clone(),
                        system: system.name.clone(),
                        error: e,
                    });
                    m.failed = true;
                    break;
                }
            }
        }
    });
}