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,
};
}
#[derive(Default)]
pub struct OxeonPlugin {
pub runtime: RuntimeConfig,
pub bindings_file: Option<std::path::PathBuf>,
pub restart_on_reload: bool,
}
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))
.insert_resource(RestartOnReload(self.restart_on_reload))
.init_resource::<ModSpawns>()
.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());
}
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 (mut bindings, problems) = bindings::generate(®istry.read(), &exposed, &messages);
if let Some(source) = app.world().get_resource::<ModSource>() {
for text in &source.0 {
let text = format!("\n{text}\n");
bindings.declarations.push_str(&text);
bindings.prelude.push_str(&text);
}
}
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
);
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);
}
}
pub trait OxeonAppExt {
fn expose_to_mods<T: Component + Reflect + GetTypeRegistration + TypePath>(
&mut self,
) -> &mut Self;
fn expose_message_to_mods<
M: bevy_ecs::message::Message
+ Reflect
+ bevy_reflect::FromReflect
+ GetTypeRegistration
+ TypePath,
>(
&mut self,
) -> &mut Self;
fn add_mod_source(&mut self, source: &str) -> &mut Self;
}
#[derive(Resource, Default)]
struct ModSource(Vec<String>);
impl OxeonAppExt for App {
fn add_mod_source(&mut self, source: &str) -> &mut Self {
self.world_mut()
.get_resource_or_init::<ModSource>()
.0
.push(source.to_owned());
self
}
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
}
}
#[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>);
#[derive(bevy_ecs::message::Message, Clone, Debug)]
pub struct LoadModSource {
pub name: String,
pub source: String,
}
#[derive(bevy_ecs::message::Message, Clone, Debug)]
pub struct UnloadMod {
pub name: String,
}
#[derive(bevy_ecs::message::Message, Clone, Debug, PartialEq)]
pub enum ModReport {
Loaded {
name: String,
systems: Vec<String>,
notes: Vec<String>,
},
CompileFailed {
name: String,
errors: Vec<String>,
kept_previous: bool,
},
Disabled {
name: String,
system: String,
error: String,
},
}
#[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;
#[derive(Resource)]
struct RestartOnReload(bool);
#[derive(Resource, Default)]
pub(crate) struct ModSpawns(pub HashMap<String, Vec<Entity>>);
impl ModSpawns {
pub(crate) fn add(&mut self, world_has: impl Fn(Entity) -> bool, path: &str, e: Entity) {
let list = self.0.entry(path.to_owned()).or_default();
if list.len() >= 256 && list.len().is_power_of_two() {
list.retain(|e| world_has(*e));
}
list.push(e);
}
}
fn restart_mod(world: &mut World, path: &str) {
let spawned = world
.resource_mut::<ModSpawns>()
.0
.remove(path)
.unwrap_or_default();
for e in spawned {
if world.get_entity(e).is_ok() {
world.despawn(e);
}
}
components::remove_mod_resources(world, path);
}
#[derive(Resource, Default)]
struct SourceMods(HashMap<String, (Handle<OxeonSource>, Entity)>);
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() {
if let Some((_, entity)) = mods.0.remove(name) {
commands.entity(entity).despawn();
}
}
}
#[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,
restart: Res<RestartOnReload>,
) {
let restart = restart.0;
let mut changed = Vec::new();
for event in events.read() {
match event {
AssetEvent::LoadedWithDependencies { id } => {
if !changed.contains(id) {
changed.push(*id);
}
}
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| {
if restart {
restart_mod(world, &m.path);
} else {
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(),
notes: compiled
.warnings
.iter()
.filter(|w| w.severity == oxeon_diagnostics::Severity::Note)
.map(|w| w.render_plain(&path, &source.source))
.collect(),
});
let layouts = compiled
.layouts
.iter()
.map(|l| (l.name.clone(), l.clone()))
.collect();
if restart && let Some(old) = mods.0.get(&id) {
let path = old.path.clone();
commands.queue(move |world: &mut World| restart_mod(world, &path));
}
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),
});
}
}
}
}
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;
}
}
}
});
}