oxeon 0.0.4

Rust-like scripting language for modding Bevy games, compiled to sandboxed WebAssembly.
Documentation
//! The components mods use: the game's, through reflection, or the mod's
//! own, stored as the mod's bytes.
//!
//! A struct a mod declares and uses as a component (in a query or a
//! command) becomes a dynamic Bevy component named `{mod path}::{Name}`,
//! laid out exactly as the mod lays it out, so its bytes are copied as they
//! are. Reloading a mod with the same layout reuses the component, so the
//! data survives hot reloads; a changed layout gets a new component.

use std::alloc::Layout as MemoryLayout;
use std::any::TypeId;
use std::borrow::Cow;
use std::ptr::NonNull;

use bevy_ecs::component::{ComponentCloneBehavior, ComponentDescriptor, ComponentId, StorageType};
use bevy_ecs::prelude::*;
use bevy_ecs::ptr::OwningPtr;
use bevy_ecs::reflect::ReflectComponent;
use bevy_ecs::world::EntityRef;
use bevy_reflect::TypeRegistry;
use oxeon_compiler::Layout;

use crate::bindings::OxeonBindings;

/// Dynamic components registered for mods, by name and layout.
#[derive(Resource, Default)]
pub(crate) struct ModComponents(Vec<(String, Layout, ComponentId)>);

/// A component a mod refers to by name.
#[derive(Clone)]
pub(crate) enum ComponentRef {
    /// One of the game's, exposed with `expose_to_mods`.
    Host {
        type_id: TypeId,
        reflect: ReflectComponent,
        id: Option<ComponentId>,
    },
    /// Declared by the mod.
    Mod { id: ComponentId, size: usize },
}

impl ComponentRef {
    /// Finds (or, for the mod's own, registers) the component `name`.
    pub fn resolve(
        world: &mut World,
        registry: &TypeRegistry,
        bindings: &OxeonBindings,
        mod_path: &str,
        layouts: &std::collections::HashMap<String, Layout>,
        name: &str,
    ) -> Result<ComponentRef, String> {
        if let Some(&type_id) = bindings.components.get(name) {
            let reflect = registry
                .get_type_data::<ReflectComponent>(type_id)
                .ok_or_else(|| format!("`{name}` isn't reflected as a component"))?
                .clone();
            let id = world.components().get_id(type_id);
            return Ok(ComponentRef::Host {
                type_id,
                reflect,
                id,
            });
        }
        let layout = layouts.get(name).ok_or_else(|| {
            format!("`{name}` isn't one of the game's components or a struct the mod declares")
        })?;
        let qualified = format!("{mod_path}::{name}");
        let id = mod_component(world, &qualified, layout)?;
        Ok(ComponentRef::Mod {
            id,
            size: layout.size as usize,
        })
    }

    /// The Bevy component id, if the component is registered.
    pub fn id(&self) -> Option<ComponentId> {
        match self {
            ComponentRef::Host { id, .. } => *id,
            ComponentRef::Mod { id, .. } => Some(*id),
        }
    }

    pub fn contains(&self, entity: EntityRef) -> bool {
        match self {
            ComponentRef::Host { reflect, .. } => reflect.contains(entity),
            ComponentRef::Mod { id, .. } => entity.contains_id(*id),
        }
    }
}

/// The dynamic component for a mod's struct, registering it the first time.
fn mod_component(world: &mut World, name: &str, layout: &Layout) -> Result<ComponentId, String> {
    world.init_resource::<ModComponents>();
    if let Some((_, _, id)) = world
        .resource::<ModComponents>()
        .0
        .iter()
        .find(|(n, l, _)| n == name && l == layout)
    {
        return Ok(*id);
    }
    let memory = MemoryLayout::from_size_align(layout.size as usize, layout.align.max(1) as usize)
        .map_err(|e| format!("`{name}` has an invalid layout: {e}"))?
        .pad_to_align();
    // SAFETY: the component is plain bytes (numbers, `bool`, `char`): no drop
    // function is needed, it's Send and Sync, and it has no relationships.
    let descriptor = unsafe {
        ComponentDescriptor::new_with_layout(
            Cow::Owned(name.to_owned()),
            StorageType::Table,
            memory,
            None,
            true,
            false,
            ComponentCloneBehavior::Default,
            None,
        )
    };
    let id = world.register_component_with_descriptor(descriptor);
    world
        .resource_mut::<ModComponents>()
        .0
        .push((name.to_owned(), layout.clone(), id));
    Ok(id)
}

/// A mod component's bytes on `entity`.
pub(crate) fn read_bytes(
    world: &World,
    entity: Entity,
    id: ComponentId,
    size: usize,
) -> Option<Vec<u8>> {
    let ptr = world.get_by_id(entity, id)?;
    // SAFETY: the component was registered with a layout of `size` bytes.
    Some(unsafe { std::slice::from_raw_parts(ptr.as_ptr(), size) }.to_vec())
}

/// Overwrites a mod component on `entity` (marking it changed).
pub(crate) fn write_bytes(
    world: &mut World,
    entity: Entity,
    id: ComponentId,
    bytes: &[u8],
) -> bool {
    let Some(value) = world.get_mut_by_id(entity, id) else {
        return false;
    };
    // SAFETY: `bytes` was read with this component's size, and the
    // component is plain bytes.
    unsafe {
        std::ptr::copy_nonoverlapping(bytes.as_ptr(), value.into_inner().as_ptr(), bytes.len());
    }
    true
}

/// Adds (or replaces) a mod component on `entity` from its bytes.
pub(crate) fn insert_bytes(world: &mut World, entity: Entity, id: ComponentId, bytes: &[u8]) {
    // An 8-byte aligned copy: the component's alignment is at most 8.
    let mut storage = vec![0u64; bytes.len().div_ceil(8).max(1)];
    // SAFETY: `storage` holds at least `bytes.len()` bytes.
    unsafe {
        std::ptr::copy_nonoverlapping(
            bytes.as_ptr(),
            storage.as_mut_ptr().cast::<u8>(),
            bytes.len(),
        );
    }
    let ptr = NonNull::new(storage.as_mut_ptr().cast::<u8>()).expect("a Vec's pointer isn't null");
    // SAFETY: the pointer is aligned and holds a valid value of the
    // component's layout (plain bytes). Ownership moves into the world;
    // `storage` is only freed, never dropped as a value.
    unsafe {
        world
            .entity_mut(entity)
            .insert_by_id(id, OwningPtr::new(ptr));
    }
}