Files
horizon-airdef/crates/horizon-mod-sdk/src/lib.rs
T
socksprox af7a685b5c Mod API: capability ui — mod-owned screens and settings pages
New WIT interface `ui` (text, item and list widgets; open-screen,
close-screen, set-settings) plus a `ui-events` export (select, closed,
settings-opened), in a second world `horizon-ui-mod` so mods built before
it keep loading. The game lays out and draws the widgets with its own
menus' code: a screen the mod owns (Esc/Done to leave) and a Settings
button on the mod's Options > Mods row that opens its page.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-25 17:09:25 +01:00

176 lines
6.3 KiB
Rust

//! Write Horizon mods in Rust (`docs/mods.md`).
//!
//! A mod is a type implementing [`Mod`], exported with [`export_mod!`] from
//! a `cdylib` crate built for `wasm32-unknown-unknown`;
//! `cargo horizon-mod build` turns it into the component the game loads.
//!
//! ```ignore
//! use horizon_mod_sdk::{Mod, Registration, chat};
//!
//! struct Hello;
//! impl Mod for Hello {
//! fn init() -> Result<(Self, Registration), String> {
//! Ok((Hello, Registration::new().command("hello")))
//! }
//! fn command(&mut self, _name: &str, _args: &str) -> Result<Option<String>, String> {
//! chat::show("Hello from a mod!");
//! Ok(None)
//! }
//! }
//! horizon_mod_sdk::export_mod!(Hello);
//! ```
//!
//! Every interface but `log` is a capability: list the ones the mod uses in
//! `horizon-mod.toml` (`game-read`, `chat`, `hud`, `storage`, `ui`).
//!
//! Widgets (capability `ui`): a mod shows a screen it owns with
//! [`ui::open_screen`] and a page in Options > Mods with
//! [`ui::set_settings`]; what the player does with them comes back as
//! [`Mod::ui_select`], [`Mod::ui_closed`] and [`Mod::ui_settings_opened`].
wit_bindgen::generate!({
path: "wit",
world: "horizon-ui-mod",
pub_export_macro: true,
export_macro_name: "__export_horizon_mod",
default_bindings_module: "horizon_mod_sdk",
});
pub use exports::horizon::mods::events::{Guest as __Guest, Registration};
pub use exports::horizon::mods::ui_events::Guest as __UiEventsGuest;
pub use horizon::mods::{chat, game, hud, log, storage, ui};
/// The game's calls into a mod. Only the hooks [`Registration`] asks for
/// are called; the others may stay as their defaults.
pub trait Mod: Sized + 'static {
/// Once, after loading: the mod's state and the hooks it wants. An error
/// keeps the mod off and is shown to the player.
fn init() -> Result<(Self, Registration), String>;
/// Every game tick, when [`Registration::tick`] is set.
fn tick(&mut self, _tick: u64) {}
/// Every rendered frame, when [`Registration::frame`] is set.
fn frame(&mut self, _seconds: f32) {}
/// `/name args` for a command the mod registered. `Ok(Some(text))` is
/// shown as feedback, `Err(text)` in red.
fn command(&mut self, _name: &str, _args: &str) -> Result<Option<String>, String> {
Err("This command does nothing".into())
}
/// A chat line the player received, when [`Registration::chat`] is set.
fn chat(&mut self, _text: &str) {}
/// A row of one of the mod's `list` widgets was picked (capability
/// `ui`): the widget's `id` and the row.
fn ui_select(&mut self, _id: u32, _row: u32) {}
/// The player left the mod's screen (Esc or Done; capability `ui`).
fn ui_closed(&mut self) {}
/// The player opened the mod's settings page (capability `ui`): call
/// [`ui::set_settings`] for fresh widgets.
fn ui_settings_opened(&mut self) {}
}
impl Registration {
/// No commands and no hooks.
pub fn new() -> Self {
Self {
commands: Vec::new(),
tick: false,
frame: false,
chat: false,
}
}
/// Adds `/name`.
pub fn command(mut self, name: &str) -> Self {
self.commands.push(name.into());
self
}
pub fn on_tick(mut self) -> Self {
self.tick = true;
self
}
pub fn on_frame(mut self) -> Self {
self.frame = true;
self
}
pub fn on_chat(mut self) -> Self {
self.chat = true;
self
}
}
impl Default for Registration {
fn default() -> Self {
Self::new()
}
}
/// `log::write` at info level.
pub fn info(message: &str) {
log::write(log::Level::Info, message);
}
/// `log::write` at warn level.
pub fn warn(message: &str) {
log::write(log::Level::Warn, message);
}
/// Exports a [`Mod`] as the component's `events` interface. The state lives
/// in a thread local: a mod instance is single-threaded.
#[macro_export]
macro_rules! export_mod {
($t:ty) => {
const _: () = {
use ::std::cell::RefCell;
::std::thread_local! {
static STATE: RefCell<Option<$t>> = const { RefCell::new(None) };
}
fn with(f: impl FnOnce(&mut $t)) {
STATE.with(|s| {
if let Some(m) = s.borrow_mut().as_mut() {
f(m)
}
})
}
struct Export;
impl $crate::__Guest for Export {
fn init() -> Result<$crate::Registration, String> {
let (m, registration) = <$t as $crate::Mod>::init()?;
STATE.with(|s| *s.borrow_mut() = Some(m));
Ok(registration)
}
fn tick(tick: u64) {
with(|m| $crate::Mod::tick(m, tick))
}
fn frame(seconds: f32) {
with(|m| $crate::Mod::frame(m, seconds))
}
fn command(name: String, args: String) -> Result<Option<String>, String> {
let mut out = Err("The mod is not running".to_string());
with(|m| out = $crate::Mod::command(m, &name, &args));
out
}
fn chat(text: String) {
with(|m| $crate::Mod::chat(m, &text))
}
}
impl $crate::__UiEventsGuest for Export {
fn select(id: u32, row: u32) {
with(|m| $crate::Mod::ui_select(m, id, row))
}
fn closed() {
with(|m| $crate::Mod::ui_closed(m))
}
fn settings_opened() {
with(|m| $crate::Mod::ui_settings_opened(m))
}
}
// Only WebAssembly has the component's exports: a host build (cargo test or
// clippy on the workspace) checks the mod without them, which macOS
// couldn't link (its exported-symbols list cuts names at the `#`).
#[cfg(target_arch = "wasm32")]
$crate::__export_horizon_mod!(Export);
#[cfg(not(target_arch = "wasm32"))]
let _ = (
<Export as $crate::__Guest>::init,
<Export as $crate::__UiEventsGuest>::select,
);
};
};
}