mod asset;
mod bindings;
mod bridge;
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::{OxeonAppExt, OxeonMod, OxeonPlugin, OxeonSource};
}
#[derive(Default)]
pub struct OxeonPlugin {
pub runtime: RuntimeConfig,
}
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_asset::<OxeonSource>()
.register_asset_loader(OxeonSourceLoader)
.register_type::<OxeonMod>()
.add_systems(Update, (compile_mods, run_mods).chain());
}
fn finish(&self, app: &mut App) {
let exposed = app.world().resource::<ExposedTypes>().0.clone();
let registry = app.world().resource::<AppTypeRegistry>().clone();
let (bindings, problems) = bindings::generate(®istry.read(), &exposed);
for problem in problems {
bevy_log::warn!("{problem}");
}
app.insert_resource(bindings);
}
}
pub trait OxeonAppExt {
fn expose_to_mods<T: Component + Reflect + 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
}
}
#[derive(Resource, Clone)]
pub struct OxeonRuntime(pub Runtime);
#[derive(Component, Reflect, Clone)]
pub struct OxeonMod(pub Handle<OxeonSource>);
#[derive(Resource, Default)]
struct LoadedMods(HashMap<AssetId<OxeonSource>, LoadedMod>);
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>,
) {
let mut changed = Vec::new();
for event in events.read() {
match event {
AssetEvent::LoadedWithDependencies { id } => {
if !changed.contains(id) {
changed.push(*id);
}
}
AssetEvent::Removed { id } | AssetEvent::Unused { id } => {
mods.0.remove(id);
changed.retain(|c| c != id);
}
_ => {}
}
}
for id in changed {
let Some(source) = sources.get(id) else {
continue;
};
let path = 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())
);
}
if mods.0.contains_key(&id) {
bevy_log::warn!(
"{path}: keeping the previous version until the errors are fixed"
);
}
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());
let layouts = compiled
.layouts
.iter()
.map(|l| (l.name.clone(), l.clone()))
.collect();
mods.0.insert(
id,
LoadedMod {
path,
instance,
systems: compiled.systems,
layouts,
started: false,
failed: false,
},
);
}
Err(e) => bevy_log::error!("{path}: {e}"),
}
}
}
fn run_mods(world: &mut World) {
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;
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
);
m.failed = true;
break;
}
}
}
});
}