At a glance
| What it is | A Rust-like language for writing mods for Bevy games |
|---|---|
| File extension | .ox |
| Compiles to | WebAssembly, run by Wasmtime with fuel limits (or, in a game built for the web, by the browser’s own engine) |
| Used from a game through | The oxeon crate, a Bevy plugin (OxeonPlugin) |
| Bevy version | 0.20 |
| Implemented in | Rust |
| License | MIT OR Apache-2.0 |
| Source code | github.com/kcuwashere/oxeon |
| Editor support | A VS Code extension (oxeon.oxeon) and a language server (oxeon-lsp) |
| Status | Early development (version 0.0.x); not ready for production use |
Oxeon isn’t a Rust compiler, and it can’t use crates from crates.io. A mod can use the language, its small built-in prelude, and whatever types the game exposes. Oxeon is an independent project, not affiliated with or endorsed by the Bevy project.
A first mod
The game adds the plugin and chooses which of its components mods may use:
use bevy::prelude::*;
use oxeon::prelude::*;
#[derive(Component, Reflect)]
#[reflect(Component)]
struct Health {
current: f32,
max: f32,
}
#[derive(Component, Reflect)]
#[reflect(Component)]
struct Regen {
per_sec: f32,
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(OxeonPlugin::default())
.expose_to_mods::<Health>()
.expose_to_mods::<Regen>()
.add_systems(Startup, load_mods)
.run();
}
fn load_mods(mut commands: Commands, assets: Res<AssetServer>) {
commands.spawn(OxeonMod(assets.load("mods/regen.ox")));
}The mod uses Health, Regen and Time without declaring them. They come from the game, and the compiler type-checks the mod against their real fields:
// assets/mods/regen.ox
fn regen(time: Res<Time>, mut q: Query<(&mut Health, &Regen)>) {
for (mut hp, regen) in &mut q {
if hp.current < hp.max {
hp.current += regen.per_sec * time.delta_secs();
if hp.current > hp.max {
hp.current = hp.max;
}
}
}
}
pub fn plugin(app: &mut App) {
app.add_systems(Update, regen);
}Every mod has a pub fn plugin(app: &mut App) entry point, the same shape as a Bevy plugin function. Systems are ordinary functions whose parameters are system parameters, registered with add_systems. The repository has this as a runnable demo: cargo run -p oxeon --example regen.
How a mod runs
- Loading. A
.oxfile is a Bevy asset. Spawning an entity withOxeonMod(handle)loads a mod. The asset loader only reads the source text. - Bindings. Once every plugin is added, Oxeon reads the game’s
TypeRegistryand generates Oxeon declarations for each component and resource exposed withexpose_to_mods, and each message type exposed withexpose_message_to_mods. Nobody writes bindings by hand. An exposed type needs#[derive(Reflect)](with#[reflect(Component)]or#[reflect(Resource)]), and its fields must be numbers,bool,char, or structs of those, such asTransformwith itsVec3andQuat(declared too). WithOxeonPlugin’sbindings_fileset, the plugin also writes the bindings to a file, so editors know the game’s types. - Compiling. Each mod is compiled together with the bindings. Errors are reported with source snippets, like rustc’s. An error inside the bindings is reported as a problem with the game, not with the mod.
- Running. Each frame, in
Update, Oxeon copies the system’s resources, messages and the rows eachQuerymatches into the mod’s WebAssembly memory, converting values through reflection. It calls each system with a fresh fuel budget, then writes back what the system took as&mut(only values that actually changed, soChangedfilters stay accurate), sends the messages it wrote and applies itsCommands.Startupsystems run once each time the mod loads. - Failures. A mod that traps or runs out of fuel is disabled, and the game keeps running. A call that fails writes nothing back.
- Hot reload. With the
hot-reloadfeature, editing a.oxfile recompiles the mod. If the new version has errors, the previous one keeps running. Game state lives in the ECS, so nothing is lost, and components the mod defines are kept if their layout didn’t change.
What works today
Language
- Integer types,
f32,f64,boolandchar let,mut, shadowing, assignment and compound assignment (+=and others). Integer arithmetic wraps on overflow, like Rust’s release buildsif/elseas an expression,while,loopwith break values and labels, andforover ranges- Functions, constants and
const fn - Structs (named, tuple and unit), enums whose variants carry data, and tuples, all passed by value; references
implblocks with associated functions and methodsmatchwith guards,@bindings and ranges;if let,while letandlet ... else. Every pattern form works except slice patterns- Generic functions, structs and enums, compiled once for each set of type arguments they’re used with (monomorphization)
- Traits, implemented with
impl Trait for Type: methods through bounds (T: Shape,T: A + B), default methods, and&dyn Traitfor values of different types behind one reference type, with a check that the trait can be used that way - Closures, which capture by reference (
&, or&mutfor variables they change) or by value withmove. They can be called directly or passed to generic functions withFn,FnMutandFnOncebounds, and their parameter types are inferred from those bounds, so|v| v + 1needs no annotations OptionandResult, with methods such asis_some,unwrap_or,ok_or,ok,map,and_then,map_or,unwrap_or_else,is_some_andandmap_err, and the?operator.?doesn’t convert errors withFromyet, so both sides must have the same error type- Bevy’s math types, in every mod:
Vec2,Vec3,Vec4andQuat, with glam’s constants (Vec3::ZERO,Quat::IDENTITY), methods (length,normalize,dot,cross,lerp,Quat::from_rotation_z,slerp, ...) and operators (a + b,v * 2.0,rotation * v). WithTransformexposed, mods also get its methods:from_xyz,rotate_z,forward,transform_pointand more - Operators on your own types, through Rust’s
std::opstraits:impl Add for Vec2 { type Output = Vec2; fn add(self, o: Vec2) -> Vec2 { .. } }makesa + bwork, andimpl Mul<f32> for Vec2next toimpl Mul<Vec2> for Vec2are told apart by the operand types.+=and the other compound assignments useAddAssignand so on, and-vusesNeg Box<T>andBox<dyn Trait>, so a list can own values of different types:Vec<Box<dyn Shape>>. Branches ofifandmatch, and function arguments, become aBox<dyn Trait>where one is expected, as in RustVec<T>, withvec![a, b],vec![x; n],push,pop,get,get_mut,first,last,len,is_empty,capacity,clear, indexing (v[i], which traps when out of range) andfor x in &vor&mut v. Memory comes from an arena that’s freed after each system call, and each mod’s memory is capped- A borrow checker like Rust’s: moves (including partial moves) and
Copytypes,mutand&mut, and conflicting borrows with non-lexical lifetimes. Its errors appear in the editor as you type - Rust’s methods on the primitive types, each compiled to its WebAssembly instruction where there is one:
count_ones,leading_zeros,rotate_left,pow,abs,min,maxandclampon integers;sqrt,floor,round,copysign,min,max,is_nan,powiandto_bitson floats - The float functions WebAssembly has no instructions for, in software:
sin,cos,tan,asin,acos,atan,atan2,exp,exp2,ln,log2,log10,powf,cbrt,hypot, the hyperbolic functions and more.f32results match Rust’s, andf64results are within 2 ULP of them panic!, which traps the mod- Random numbers, like the
randcrate’s:rand::random::<T>()for integers,f32andf64(at least 0 and less than 1) andbool;rand::random_range(1..=6)andrand::random_range(-1.0..1.0), with the range written in the call; andrand::random_bool(p). The game seeds them, differently for each mod unless it setsRuntimeConfig::random_seed - Traits’ associated functions through a generic bound:
T::new(..)infn make<T: Shape>() -> T, for your own types and for primitive types with animpl - Logging with Rust’s format strings:
info!,warn!,error!,debug!andtrace!go to the game’s log, andprintln!andeprintln!too. Arguments can be numbers,bool,char,Entity, tuples and structs with#[derive(Debug)](which includes the game’s types and the math types), with captured variables ("{x}"), positions ({0}), names ({n}withn = ..) and formatting options ({:>8.2},{:#x},{:?},{:#?}). The game formats the message, and it also sees it as aModLogmessage. Text arguments andformat!need strings, which come later - Inline
modblocks andusedeclarations within a file
Bevy
Res<Time>(delta_secs()andelapsed_secs()), andRes<T>andResMut<T>for the game’s exposed resourcesQueryparameters over exposed components and components the mod defines, such asQuery<&mut Health>orQuery<(Entity, &mut Health, &Regen)>, iterated withfor ... in &mut qorfor ... in &q- Query filters:
With<T>,Without<T>,Changed<T>andAdded<T>, alone or in a tuple Commands:commands.spawn(component)orspawn((a, b)),.insert(..),commands.entity(e).insert(..)andcommands.entity(e).despawn(), applied after the system returns- Messages:
MessageReader<M>(for m in reader.read()) andMessageWriter<M>(writer.write(m)), for the game’s exposed message types and for message structs the mod declares. Mods that declare the same message type the same way share it - Components defined by the mod with
#[derive(Component)]. They become dynamic Bevy components named after the mod - Resources defined by the mod with
#[derive(Resource)], added inpluginwithapp.init_resource::<T>()(which needs#[derive(Default)]and starts at zero) orapp.insert_resource(T { .. }), and used withRes<T>andResMut<T>. Only the mod that declares a resource sees it. A hot reload keeps a resource thatinit_resourceadded and replaces one thatinsert_resourceadded, as in Bevy app.add_systems(Startup, ...)andapp.add_systems(Update, ...)in the mod’spluginfunction, with one system, a tuple of systems or(a, b).chain(). A system can have no parameters. A mod’s systems run one at a time, not in parallel- A fuel limit on every call, disabling of mods that trap, and hot reloading. With
OxeonPlugin { restart_on_reload: true, .. }, reloading or removing a mod also despawns what it spawned and removes its resources, so each version starts from scratch, as in the playground - Oxeon code from the game (
app.add_mod_source(..)): methods on its exposed types, constants and enums, for mods to use - Mods from source text instead of files (
LoadModSource), for an editor inside the game, with aModReportmessage for each: loaded, doesn’t compile, or disabled, and why, and aModLogmessage for each line a mod logs
Tools
- The playground: write mods for a small game and play it in your browser. The compiler, the sandbox, the language server and the game all run on the page
- The
oxeoncommand-line tool:check(report errors),build(write a.wasmfile),run(call one function in the sandbox, as inoxeon run math.ox fib 10, printing what it logs),fmt(format files in place;--checklists the ones that aren’t formatted), pluslex,parseandmirto print the compiler’s intermediate results for debugging.oxeon completions <shell>sets up Tab completion, which also lists a file’s functions foroxeon run oxeon-lsp, a language server with diagnostics, go to definition, find references, completion, rename, hover with types and docs, signature help, inlay hints, semantic tokens and quick fixes. It formats files in Rust’s style (only whitespace changes; lines aren’t joined or split, except to put the braces of a block that spans lines on lines of their own). It knows the built-in prelude and Bevy’s types, and the game’s types from anoxeon-bindings.oxfile next to the mod or in a folder above it- A VS Code extension, on the VS Code Marketplace and Open VSX, which includes the language server. It formats
.oxfiles when you save them ("[oxeon]": { "editor.formatOnSave": false }turns that off)
When the compiler can’t compile a function yet, it skips it with a note that says why, such as "isn’t compiled to WebAssembly yet: it uses a string". The rest of the mod still compiles.
Not yet implemented
These parts of the design are planned. Code that uses them parses and gets editor support, but doesn’t compile to WebAssembly yet:
- Strings and slices:
&str,Stringand&[T] - Iterators and iterator chains such as
(1..=5).map(..).collect() - Traits: associated types, supertraits, blanket implementations (
impl<T: A> B for T) andimpl Trait - Lifetimes in signatures. Until then, references returned from functions or stored in structs are checked conservatively
Drop- Modules in other files (
mod name;) and the rest ofstd, such asHashMap - Exhaustiveness checking for
match. For now, a value that no arm matches traps at run time - In Bevy: components, resources and messages with fields that are enums, strings,
Vecs, boxes or references; schedules other thanStartupandUpdate(a mod that uses one gets a warning); run conditions (.run_if(..)is accepted but ignored); and mod systems as real Bevy systems that run in parallel with the game’s - Sandbox: per-mod capabilities and a fuel budget per frame
- Mod state carried across hot reloads, through reflection
async/.await, with the host’s executor doing the work- Macros:
macro_rules!, and procedural macros compiled to WebAssembly that run sandboxed core::arch::wasm32: SIMD and memory intrinsics, with Rust’s namesmul_add, which must round once, so it needs a software version- Oxeon-only extensions: compile-time evaluation beyond
const fn
The examples show what code using these features is meant to look like. Each one says which parts work today.
How Oxeon differs from Rust
- A subset of Rust. Oxeon’s syntax is a strict subset of Rust’s. A mod that sticks to the core language and the mod API is meant to also compile as a native Bevy plugin, through the
oxeon-shimcrate. - The game’s types come from bindings. A mod doesn’t declare or import the game’s components. It uses them by name, and the compiler gets their definitions from the game’s type registry.
- No crates. A mod can’t depend on crates from crates.io or link native code. Everything it can reach is the language, its prelude and what the game exposes.
- Panics don’t unwind. A panic, a trap or running out of fuel stops that one mod, and the game keeps going.
- Wrapping arithmetic. Integer overflow wraps, as in Rust’s release builds, rather than panicking as in debug builds.
- Canonical NaNs. NaN values are canonicalized, which removes one source of differences between platforms.
- Planned extensions that make a file invalid Rust: procedural macros that run sandboxed, and wider compile-time evaluation. They’re opt-in. WebAssembly instructions don’t need one: they’re reached through Rust’s primitive methods and
core::arch::wasm32, as in Rust.
Sandbox
- Isolation. Each mod has its own instance and linear memory: a Wasmtime store natively, a WebAssembly instance in the browser.
- Fuel. Each call into a mod gets a fuel budget. A mod in an infinite loop runs out of fuel and is disabled, instead of freezing the game. The compiler counts fuel in the module itself, so this works in browsers too, which have no fuel of their own.
- Capabilities. A mod gets no imports by default. It sees only the components the game exposes and the data passed to its systems. Granting access to other resources, messages, assets, time and randomness per mod is planned.
- Determinism. Designed in from the start: no ambient time or randomness, and canonical NaNs.
Architecture
.ox source ─lex→ tokens ─parse→ AST ─check→ typed AST ─lower→ MIR ─codegen→ .wasm
│
Bevy app ── OxeonPlugin ── oxeon-runtime (Wasmtime) ◄┘The compiler is a set of crates that don’t depend on Bevy: oxeon-syntax (a lexer built with logos and a hand-written parser), oxeon-types (name resolution and type checking), oxeon-mir (a control-flow graph per function), oxeon-codegen (WebAssembly through wasm-encoder, with structured control flow rebuilt using Ramsey’s "Beyond Relooper" algorithm) and oxeon-compiler, which drives them. oxeon-runtime wraps Wasmtime. Only the oxeon crate, the Bevy plugin, depends on Bevy. Keeping Bevy out of the compiler keeps it fast to build, lets the CLI and language server work without Bevy, and confines Bevy’s breaking changes to one crate.
Frequently asked questions
Is Oxeon just Rust? No. It looks like Rust and follows Rust’s semantics, but it’s a separate language with its own compiler, and it runs sandboxed as WebAssembly. Code written for Oxeon uses the game’s exposed types and Oxeon’s prelude, not Rust’s standard library or crates.
Why not embed Lua or another existing scripting language? Mods written in Oxeon are statically typed against the game’s real Bevy types, and they use the same ECS concepts as the game’s own code. Bevy developers don’t need to learn a second language or write bindings by hand.
Can a mod crash or freeze the game? It’s designed not to. A trap, a panic or running out of fuel disables that mod, and the game keeps running.
Can Oxeon be used outside Bevy? Not as a goal. The compiler and runtime don’t depend on Bevy, but the language and its mod API are designed around Bevy’s ECS.
Is it ready for use? Not yet. Mods run in Bevy today with the subset of the language described in What works today. The roadmap tracks the rest.