523c855b09
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3133 lines
115 KiB
Rust
3133 lines
115 KiB
Rust
//! Loading and calling mods with wasmtime's component model.
|
||
use crate::manifest::{Manifest, Package, Side};
|
||
use server_bindings::{
|
||
HorizonServerMod,
|
||
exports::horizon::mods::server_events::Registration as ServerRegistration,
|
||
horizon::mods::{players, world as mod_world},
|
||
};
|
||
use std::{
|
||
path::{Path, PathBuf},
|
||
sync::{Arc, Mutex},
|
||
time::{Duration, Instant, SystemTime},
|
||
};
|
||
use wasmtime::{
|
||
Config, Engine, Store, StoreLimits, StoreLimitsBuilder, Trap,
|
||
component::{Component, HasSelf, Linker},
|
||
};
|
||
|
||
mod bindings {
|
||
wasmtime::component::bindgen!({
|
||
path: "../horizon-mod-sdk/wit",
|
||
world: "horizon-mod",
|
||
});
|
||
}
|
||
/// The server mods' world: `log` and `storage` are the client world's.
|
||
mod server_bindings {
|
||
wasmtime::component::bindgen!({
|
||
path: "../horizon-mod-sdk/wit",
|
||
world: "horizon-server-mod",
|
||
additional_derives: [PartialEq],
|
||
with: {
|
||
"horizon:mods/log": super::bindings::horizon::mods::log,
|
||
"horizon:mods/storage": super::bindings::horizon::mods::storage,
|
||
},
|
||
});
|
||
}
|
||
/// Capability `ui`'s world beyond `horizon-mod` (docs/mods.md): a second
|
||
/// world, so mods built before it (no `ui-events` export) still instantiate
|
||
/// as `horizon-mod` and simply hear nothing of their widgets.
|
||
mod ui_bindings {
|
||
wasmtime::component::bindgen!({
|
||
path: "../horizon-mod-sdk/wit",
|
||
world: "ui-host",
|
||
});
|
||
}
|
||
pub use bindings::horizon::mods::{
|
||
command::{
|
||
NodeKind as TreeNodeKind, TreeNode, TreeOption, TreeOptions, ValueKind as TreeValueKind,
|
||
},
|
||
game::{Clock, Hit, Player},
|
||
hud::{Corner, Line},
|
||
};
|
||
use bindings::{
|
||
HorizonMod,
|
||
exports::horizon::mods::events::Registration,
|
||
horizon::mods::{chat, command, game, hud, log as mod_log, storage},
|
||
};
|
||
pub use server_bindings::{
|
||
exports::horizon::mods::server_events::{
|
||
Argument, ArgumentKind, ArgumentValue, BlockPos, ServerCommand,
|
||
},
|
||
horizon::mods::players::{GameMode, Player as ServerPlayer},
|
||
horizon::mods::world::BlockChange,
|
||
};
|
||
type ClientEvents = bindings::exports::horizon::mods::events::Guest;
|
||
type ServerEvents = server_bindings::exports::horizon::mods::server_events::Guest;
|
||
/// The widget model a `ui` screen or settings page shows (WIT `interface
|
||
/// ui`), for the game to draw with its menus' own widgets.
|
||
pub use ui_bindings::horizon::mods::ui::{
|
||
ButtonWidget, ItemWidget, ListWidget, Screen as UiScreen, TextWidget, Widget as UiWidget,
|
||
};
|
||
use ui_bindings::{UiHost, horizon::mods::ui};
|
||
/// Capability `render`'s imports (docs/mods.md): the game draws the shapes.
|
||
mod render_bindings {
|
||
wasmtime::component::bindgen!({
|
||
path: "../horizon-mod-sdk/wit",
|
||
world: "render-host",
|
||
additional_derives: [PartialEq],
|
||
});
|
||
}
|
||
use render_bindings::horizon::mods::input;
|
||
/// Capability `input`'s records (WIT `interface input`).
|
||
pub use render_bindings::horizon::mods::input::{Event as InputEvent, HeldItem, ItemUse};
|
||
/// What capability `render` asks the game to draw (WIT `interface render`).
|
||
pub use render_bindings::horizon::mods::render::{
|
||
CameraView, CaptureOptions, CapturePhase, CaptureState, Changes as WorldChanges,
|
||
Corner as RenderCorner, FarTerrain as ModFarTerrain, FillShape, FrameRate, ItemShape,
|
||
Lighting as ModLighting, Minimap as ModMinimap, ModelInstance, ModelInstanceId, ParticleSpawn,
|
||
Point as RenderPoint, PointLight, Policy as WorldPolicy, QuadShape, Ray as WorldRay,
|
||
RayAnswer as WorldRayAnswer, Rect as RenderRect, Section as WorldSection, SectionFill, Shape,
|
||
SmokeSegment, SourceOp, SourceOpKind, SpotLight, SpriteShape, TextShape, Verdict as WorldVerdict, ViewShape,
|
||
Zoom as ModZoom,
|
||
};
|
||
use render_bindings::{RenderHost, horizon::mods::render};
|
||
/// Capability `recipes`'s imports (docs/mods.md): the game's recipes and items.
|
||
mod recipes_bindings {
|
||
wasmtime::component::bindgen!({
|
||
path: "../horizon-mod-sdk/wit",
|
||
world: "recipes-host",
|
||
});
|
||
}
|
||
/// Capability `ui`'s recipe viewer panel (WIT `interface browser`).
|
||
pub use recipes_bindings::horizon::mods::browser::{
|
||
Click as BrowserClick, Event as BrowserEvent, ItemKey as BrowserItemKey,
|
||
Layout as BrowserLayout, RecipeView as BrowserRecipe, SlotClick as BrowserSlotClick,
|
||
Stack as BrowserStack,
|
||
};
|
||
/// What capability `recipes` reads (WIT `interface recipes`).
|
||
pub use recipes_bindings::horizon::mods::recipes::{
|
||
Item as RecipeItem, Kind as RecipeKind, Recipe, Stack as RecipeStack,
|
||
};
|
||
use recipes_bindings::{RecipesHost, horizon::mods::browser, horizon::mods::recipes};
|
||
|
||
/// A mod's linear memory cap.
|
||
const MEMORY: usize = 64 << 20;
|
||
/// Fuel (about one unit per WebAssembly instruction) per call: a bound on
|
||
/// runaway loops, far above the hooks' time budgets.
|
||
const FUEL_INIT: u64 = 2_000_000_000;
|
||
const FUEL_TICK: u64 = 300_000_000;
|
||
const FUEL_FRAME: u64 = 10_000_000;
|
||
const FUEL_EVENT: u64 = 1_000_000_000;
|
||
/// Segments a mod may trace per tick (`render.query-rays`).
|
||
pub const RAYS_PER_TICK: usize = 256;
|
||
/// Sections a mod may ask the contents of per tick (`render.query-sections`).
|
||
pub const SECTIONS_PER_TICK: usize = 64;
|
||
/// What a mod asked of the world in a tick (capability `render`, AirDef fork).
|
||
pub struct WorldQueries {
|
||
pub rays: Vec<WorldRay>,
|
||
/// Segments asked beyond the budget: to be answered unknown.
|
||
pub over: Vec<u32>,
|
||
pub sections: Vec<(WorldPolicy, Vec<(i32, i32, i32)>)>,
|
||
}
|
||
/// Blocks a mod may set per `world.set-blocks` call.
|
||
pub const BLOCKS_PER_CALL: usize = 4096;
|
||
/// Chat lines a mod may show per call, HUD lines and their length.
|
||
const CHAT_PER_CALL: usize = 8;
|
||
/// `command.run-quiet` lines one call of a mod may queue (a quiet payload's
|
||
/// cap, `horizon_protocol::quiet::MAX_LINES`).
|
||
const QUIET_PER_CALL: usize = 256;
|
||
/// How far `game.raycast` sees, in blocks.
|
||
pub const RAYCAST_MAX: f32 = 1024.0;
|
||
const HUD_LINES: usize = 16;
|
||
const LINE_CHARS: usize = 256;
|
||
/// Total bytes a mod's `storage` may hold on disk, across all its keys.
|
||
const STORAGE_QUOTA: u64 = 4 << 20;
|
||
/// Distinct keys a mod's `storage` may hold: `STORAGE_QUOTA` alone doesn't
|
||
/// bound a flood of zero- or near-zero-byte files (each still a file name,
|
||
/// a directory entry and an inode).
|
||
const STORAGE_MAX_KEYS: usize = 64;
|
||
/// Bytes `storage::set` may write across one hook call: fuel bounds a
|
||
/// mod's CPU time per call, not the time a synchronous disk write takes, so
|
||
/// a cheap-in-fuel loop replacing one key with large payloads needs its own
|
||
/// cap, separate from the on-disk quota it would otherwise stay under.
|
||
const STORAGE_WRITE_BUDGET: u64 = 1 << 20;
|
||
|
||
/// What mods may read of the game, copied once per tick by the game.
|
||
#[derive(Clone, Debug, Default)]
|
||
pub struct Snapshot {
|
||
pub player: Option<Player>,
|
||
pub clock: Option<Clock>,
|
||
/// The screen in GUI pixels (capability `render`'s `gui-size`).
|
||
pub gui_size: (f32, f32),
|
||
/// The main hand's stack (capability `input`'s `held`).
|
||
pub held: Option<HeldItem>,
|
||
/// The game's frame counter: fps, min, 1% low (`render.frame-stats`).
|
||
pub frame: (u32, u32, u32),
|
||
/// The movement and click mappings `input.mapping` answers for:
|
||
/// (mapping, the bound key's label, held).
|
||
pub mappings: Vec<(&'static str, String, bool)>,
|
||
/// Attack and use clicks in the last second.
|
||
pub cps: (u32, u32),
|
||
/// The HUD font's advance per character from U+0000
|
||
/// (`render.text-width`); empty: 6 each.
|
||
pub font_widths: Arc<[f32]>,
|
||
/// The players on the server, for server mods.
|
||
pub players: Vec<ServerPlayer>,
|
||
/// The first block along the player's view within [`RAYCAST_MAX`] and
|
||
/// its distance from the eye, for `game.raycast`; the game works it out
|
||
/// only while a mod calls it ([`Mods::wants_raycast`]).
|
||
pub view_hit: Option<(f32, Hit)>,
|
||
/// Every item and recipe, for capability `recipes`; the game makes them
|
||
/// once, and only while a mod reads them ([`Mods::wants_recipes`]).
|
||
pub recipes: Option<Arc<Recipes>>,
|
||
/// The `book-id`s of the recipes the player's book holds.
|
||
pub known_recipes: Arc<[i32]>,
|
||
/// The open screen takes recipes (`recipes.place`).
|
||
pub placing: bool,
|
||
/// The player is in creative mode (`recipes.give`).
|
||
pub creative: bool,
|
||
/// The open world (`game.world-id`, AirDef fork).
|
||
pub world: Option<String>,
|
||
}
|
||
|
||
/// Capability `recipes`'s tables: `items` in the registry's order, which
|
||
/// each [`RecipeStack::item`] indexes.
|
||
#[derive(Clone, Debug, Default)]
|
||
pub struct Recipes {
|
||
pub items: Vec<RecipeItem>,
|
||
pub recipes: Vec<Recipe>,
|
||
}
|
||
|
||
/// Which mods a game starts: the window's game the client mods, the game
|
||
/// simulating the world the server mods, single player in the frame both.
|
||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||
pub enum Runs {
|
||
Client,
|
||
Server,
|
||
Both,
|
||
}
|
||
impl Runs {
|
||
fn starts(self, side: Side) -> bool {
|
||
match self {
|
||
Runs::Both => true,
|
||
Runs::Client => side != Side::Server,
|
||
Runs::Server => side == Side::Server,
|
||
}
|
||
}
|
||
}
|
||
|
||
/// What mods asked the game to show since the last [`Mods::drain`].
|
||
#[derive(Clone, Debug, PartialEq)]
|
||
pub enum Output {
|
||
/// `chat.show`: a line after the mod's name.
|
||
Chat { name: String, text: String },
|
||
/// A mod command's feedback, red when `error`.
|
||
Feedback { text: String, error: bool },
|
||
/// `command.run`: a vanilla command line, without its slash, to run as
|
||
/// the player.
|
||
Command { line: String },
|
||
/// `command.run-quiet`: vanilla command lines to run as the player with
|
||
/// nothing in the chat (`horizon_protocol::quiet` on a server).
|
||
QuietCommands { mod_id: String, lines: Vec<String> },
|
||
/// The mod was turned off: it trapped, overran or failed to start.
|
||
Stopped { name: String, reason: String },
|
||
/// `players.tell`: a line after the mod's name, to the player with this id.
|
||
Tell {
|
||
name: String,
|
||
player: String,
|
||
text: String,
|
||
},
|
||
/// `players.broadcast`: a line after the mod's name, to every player.
|
||
Broadcast { name: String, text: String },
|
||
/// A server mod command's feedback, to the player who typed it.
|
||
Reply {
|
||
player: String,
|
||
text: String,
|
||
error: bool,
|
||
},
|
||
/// `world.set-blocks`: changes to make in `dimension`, in order, each
|
||
/// state checked by the [`WorldView`] lent for the call.
|
||
SetBlocks {
|
||
name: String,
|
||
dimension: String,
|
||
blocks: Vec<BlockChange>,
|
||
},
|
||
/// `ui.open-screen`: the mod's entry in `entries()`; what it shows is
|
||
/// [`Mods::screen`].
|
||
OpenScreen { owner: usize },
|
||
/// `ui.close-screen`: the mod closed its own screen (no `closed` back).
|
||
CloseScreen { owner: usize },
|
||
/// `render.shake`: strength 0 to 1, fading out over `seconds` (≤ 10).
|
||
Shake { strength: f32, seconds: f32 },
|
||
/// `render.spawn-particles` (AirDef fork): particles to make on this client.
|
||
Particles { particles: Vec<ParticleSpawn> },
|
||
/// `render.play-sound` (AirDef fork): a sound event at a point on this client.
|
||
Sound {
|
||
event: String,
|
||
at: [f64; 3],
|
||
volume: f32,
|
||
pitch: f32,
|
||
},
|
||
/// `recipes.place`: the recipe book's click on this display id, all of
|
||
/// it when `all`.
|
||
PlaceRecipe { book_id: i32, all: bool },
|
||
/// `recipes.give`: a stack for a creative player.
|
||
Give {
|
||
item: String,
|
||
count: u32,
|
||
components: String,
|
||
},
|
||
}
|
||
|
||
/// The game's world as capability `world` reads it during a call: the
|
||
/// game lends one with [`Mods::lend_world`] and takes it back after.
|
||
pub trait WorldView: std::any::Any + Send {
|
||
/// The block state at a position, `minecraft:oak_log[axis=y]`; `None`
|
||
/// where no chunk of that dimension is loaded.
|
||
fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String>;
|
||
/// The biome at a position, `minecraft:plains`; `None` as for blocks.
|
||
fn biome(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String>;
|
||
/// Whether `dimension` is one the server has.
|
||
fn has_dimension(&self, dimension: &str) -> bool;
|
||
/// `Err` (why) for a state string that names no block state.
|
||
fn check_state(&self, state: &str) -> Result<(), String>;
|
||
}
|
||
|
||
/// The view lent for the current calls, shared by every mod's store.
|
||
type WorldSlot = Arc<Mutex<Option<Box<dyn WorldView>>>>;
|
||
|
||
/// How the game turns a block state name into a handle (`render.model-id`):
|
||
/// None for a name that is no state of its registry.
|
||
pub type ModelResolver = Box<dyn Fn(&str) -> Option<u32> + Send>;
|
||
|
||
/// The handles of `render.model-id`: the game's registry decides which names
|
||
/// have one, so nothing grows with what mods ask; `generation` moves on
|
||
/// when the registry changes and the handles with it.
|
||
#[derive(Default)]
|
||
pub struct ModelTable {
|
||
key: usize,
|
||
generation: u32,
|
||
resolve: Option<ModelResolver>,
|
||
/// The renderer draws the mods' smoke (`render.set-smoke` says so to the mod).
|
||
smoke_active: bool,
|
||
/// The renderer draws the mods' spot lights and their beams (`render.set-spot-lights`).
|
||
spot_active: bool,
|
||
/// `render.capture-start`: the request the game has not taken yet.
|
||
capture_request: Option<CaptureOptions>,
|
||
/// `render.capture-stop`: asked, with whether to throw the file away.
|
||
capture_stop: Option<bool>,
|
||
/// The game's note of the capture (`render.capture-status`).
|
||
capture_state: Option<CaptureState>,
|
||
/// `render.set-film-quality`.
|
||
film_quality: bool,
|
||
/// `render.world-log-start`: the id of the log a mod asked for, if one runs.
|
||
world_log: Option<u32>,
|
||
/// What the game says the log covers: (id, earliest tick, tick now).
|
||
world_log_state: Option<(u32, u64, u64)>,
|
||
/// `render.set-world-time-view`: (log id, tick).
|
||
time_view: Option<(u32, u64)>,
|
||
/// `render.sound-source-generation`: moves on when the game released every source.
|
||
source_generation: u32,
|
||
/// `render.acoustics`: the game muffles sounds itself.
|
||
acoustics: bool,
|
||
}
|
||
|
||
/// The ids of block-change logs: never reused in a run of the game.
|
||
static WORLD_LOG_IDS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);
|
||
|
||
type ModelSlot = Arc<Mutex<ModelTable>>;
|
||
|
||
/// A model as a mod set it: by name, or by a handle of the [`ModelTable`].
|
||
#[derive(Clone, Debug)]
|
||
pub enum ModelRef {
|
||
Name(String),
|
||
Handle(u32),
|
||
}
|
||
|
||
/// One world model (`render.set-models` or `set-models-by-id`).
|
||
#[derive(Clone, Debug)]
|
||
pub struct HostModel {
|
||
pub id: u32,
|
||
pub model: ModelRef,
|
||
pub x: f64,
|
||
pub y: f64,
|
||
pub z: f64,
|
||
pub rotation: (f32, f32, f32, f32),
|
||
pub scale: f32,
|
||
pub glow: bool,
|
||
}
|
||
|
||
/// A mod's text panel, drawn every frame until it changes.
|
||
#[derive(Clone, Debug)]
|
||
pub struct Panel {
|
||
pub corner: Corner,
|
||
pub lines: Vec<Line>,
|
||
}
|
||
|
||
#[derive(Clone, Debug, PartialEq)]
|
||
pub enum Status {
|
||
/// Installed and turned off by the player.
|
||
Off,
|
||
Running,
|
||
/// Turned on, and run by another game: a server mod in the window while
|
||
/// the world runs on its server thread.
|
||
Elsewhere,
|
||
/// Could not load or start, or stopped while running.
|
||
Failed(String),
|
||
}
|
||
|
||
/// One installed mod, for the Mods page.
|
||
pub struct Entry {
|
||
pub path: PathBuf,
|
||
/// None when the manifest could not be read (`status` says why).
|
||
pub manifest: Option<Manifest>,
|
||
pub status: Status,
|
||
/// The mod's average time per call of its busiest hook.
|
||
pub cost: Duration,
|
||
run: Option<Running>,
|
||
modified: Option<SystemTime>,
|
||
}
|
||
impl Entry {
|
||
/// The running mod has a settings page (capability `ui` set widgets
|
||
/// with `ui.set-settings`, or `input` registered keys the player may
|
||
/// bind there): its row in Options > Mods gains a button.
|
||
pub fn has_ui_settings(&self) -> bool {
|
||
self.run.as_ref().is_some_and(|r| {
|
||
let d = r.store.data();
|
||
!d.ui.settings.is_empty() || !d.input.keys.is_empty()
|
||
})
|
||
}
|
||
}
|
||
|
||
struct Running {
|
||
store: Store<State>,
|
||
/// The mod's `ui-events` export; none for a mod built before `ui`, or a
|
||
/// server mod.
|
||
ui: Option<UiHost>,
|
||
hooks: Hooks,
|
||
/// It imports `game.raycast`.
|
||
raycasts: bool,
|
||
/// It imports capability `recipes`.
|
||
reads_recipes: bool,
|
||
}
|
||
|
||
/// A running mod's exports and the hooks its `init` asked for.
|
||
enum Hooks {
|
||
Client(HorizonMod, Registration),
|
||
Server(HorizonServerMod, ServerRegistration),
|
||
}
|
||
impl Hooks {
|
||
fn client(&self) -> Option<&Registration> {
|
||
match self {
|
||
Hooks::Client(_, r) => Some(r),
|
||
Hooks::Server(..) => None,
|
||
}
|
||
}
|
||
fn server(&self) -> Option<&ServerRegistration> {
|
||
match self {
|
||
Hooks::Server(_, r) => Some(r),
|
||
Hooks::Client(..) => None,
|
||
}
|
||
}
|
||
fn commands(&self) -> Vec<&str> {
|
||
match self {
|
||
Hooks::Client(_, r) => r.commands.iter().map(String::as_str).collect(),
|
||
Hooks::Server(_, r) => r.commands.iter().map(|c| c.name.as_str()).collect(),
|
||
}
|
||
}
|
||
}
|
||
|
||
/// What capability `ui` pushed since the hooks last ran.
|
||
#[derive(Default)]
|
||
struct UiState {
|
||
/// The screen `ui.open-screen` last pushed, until `ui.close-screen`.
|
||
screen: Option<UiScreen>,
|
||
/// The widgets `ui.set-settings` last pushed (the mod's page in
|
||
/// Options > Mods).
|
||
settings: Vec<UiWidget>,
|
||
/// The calls since the last hook ended, for [`Output`].
|
||
open: bool,
|
||
close: bool,
|
||
}
|
||
|
||
/// Capability `ui`'s panel beside container screens (`browser`).
|
||
#[derive(Default)]
|
||
struct BrowserState {
|
||
items: Vec<BrowserStack>,
|
||
/// Which `set-items` or `set-recipes` call the panel is from, unique
|
||
/// across mods and reloads, so the game converts them once.
|
||
version: u64,
|
||
/// `set-recipes`' title and recipes, shown instead of the items.
|
||
recipes: Option<RecipePage>,
|
||
events: std::collections::VecDeque<BrowserEvent>,
|
||
}
|
||
/// What `browser.set-recipes` shows: a title, tabs (`tab` the selected
|
||
/// one) and the recipes.
|
||
#[derive(Clone, Debug)]
|
||
pub struct RecipePage {
|
||
pub title: String,
|
||
pub tabs: Vec<BrowserStack>,
|
||
pub tab: u32,
|
||
pub recipes: Vec<BrowserRecipe>,
|
||
}
|
||
static BROWSER_VERSION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||
/// Items a panel may hold, and events kept for `browser.poll`.
|
||
const BROWSER_ITEMS: usize = 8192;
|
||
/// `recipes.place` and `give` calls a hook call may make.
|
||
const RECIPE_ACTIONS: usize = 36;
|
||
/// Recipes `set-recipes` may show, slots in one, and stacks a slot cycles.
|
||
const BROWSER_RECIPES: usize = 256;
|
||
const RECIPE_SLOTS: usize = 9;
|
||
const RECIPE_TABS: usize = 16;
|
||
const SLOT_STACKS: usize = 64;
|
||
const BROWSER_EVENTS: usize = 256;
|
||
impl BrowserState {
|
||
fn push(&mut self, event: BrowserEvent) {
|
||
if self.events.len() == BROWSER_EVENTS {
|
||
self.events.pop_front();
|
||
}
|
||
self.events.push_back(event);
|
||
}
|
||
}
|
||
|
||
struct State {
|
||
name: String,
|
||
id: String,
|
||
snapshot: Arc<Snapshot>,
|
||
out: Vec<Output>,
|
||
panel: Option<Panel>,
|
||
ui: UiState,
|
||
/// Capability `render`'s HUD shapes, drawn until replaced.
|
||
shapes: Vec<Shape>,
|
||
/// Capability `render`'s corner panel.
|
||
corner: Option<CornerPanel>,
|
||
/// Capability `render`'s zoom, when the mod zooms.
|
||
zoom: Option<ModZoom>,
|
||
/// Capability `render`'s minimap, when the mod shows one.
|
||
minimap: Option<ModMinimap>,
|
||
/// Capability `render`'s far terrain, when the mod draws one.
|
||
far_terrain: Option<ModFarTerrain>,
|
||
/// Capability `render`'s world models (AirDef fork), drawn until replaced.
|
||
models: Vec<HostModel>,
|
||
/// The game's block state names -> handles, shared by every mod's store.
|
||
model_table: ModelSlot,
|
||
/// `render.query-ground`'s columns, answered before the next tick.
|
||
ground_queries: Vec<(i32, i32)>,
|
||
/// `render.load-chunks`: the chunks asked for since the game last took them.
|
||
chunk_requests: Vec<(i32, i32)>,
|
||
/// The game's answers to them.
|
||
ground: Vec<(i32, i32, i32)>,
|
||
/// `render.query-rays`' segments, answered before the next tick.
|
||
ray_queries: Vec<WorldRay>,
|
||
/// Ids of segments asked beyond the budget.
|
||
ray_over: Vec<u32>,
|
||
rays: Vec<WorldRayAnswer>,
|
||
/// Whether the mod ever used the world queries.
|
||
world_seen: bool,
|
||
/// `render.query-sections`: the policy and the sections asked.
|
||
section_queries: Vec<(WorldPolicy, Vec<(i32, i32, i32)>)>,
|
||
sections_asked: usize,
|
||
sections: Vec<WorldSection>,
|
||
/// The game's note of what changed in the world last tick.
|
||
world_changes: Option<WorldChanges>,
|
||
/// `render.set-post`'s source, with a number that changes with it.
|
||
post: Option<(u64, String)>,
|
||
post_params: Vec<f32>,
|
||
/// `render.set-views`' cameras (AirDef fork).
|
||
views: Vec<CameraView>,
|
||
/// `render.set-main-view`: the camera the screen's world is rendered from.
|
||
main_view: Option<u32>,
|
||
/// `render.set-lights` and `render.set-lighting` (AirDef fork).
|
||
lights: Vec<PointLight>,
|
||
/// `render.set-spot-lights` (AirDef fork).
|
||
spots: Vec<SpotLight>,
|
||
/// `render.sound-sources` (AirDef fork): the changes the game has not taken, and this run's number.
|
||
sources: crate::sources::SourceBook,
|
||
run_serial: u64,
|
||
lighting: Option<ModLighting>,
|
||
/// `render.set-time-override` (AirDef fork).
|
||
time_override: Option<u64>,
|
||
/// `command.set-tree` (AirDef fork): the trees of the commands' arguments, by command.
|
||
trees: Vec<(String, Vec<TreeNode>)>,
|
||
/// `command.set-suggestions`: the lists `names` nodes suggest from.
|
||
lists: Vec<(String, Vec<String>)>,
|
||
/// Counts the changes of `trees` and `lists`.
|
||
tree_generation: u64,
|
||
/// `render.set-smoke` (AirDef fork): the segments, the clock of this call and of the one before.
|
||
smoke: Vec<SmokeSegment>,
|
||
smoke_clock: (f64, f64),
|
||
input: InputState,
|
||
browser: BrowserState,
|
||
/// Capability `storage`'s folder; made on first `set`.
|
||
data_dir: PathBuf,
|
||
/// Bytes `storage::set` may still write before this hook call ends
|
||
/// (reset per call in [`Mods::call`]): fuel bounds a mod's CPU time but
|
||
/// not disk I/O time, so a loop of small-fuel, large-payload `set`s
|
||
/// needs its own budget.
|
||
storage_budget: u64,
|
||
limits: StoreLimits,
|
||
world: WorldSlot,
|
||
}
|
||
|
||
/// The installed mods and the engine running them. `Mods::default()` is
|
||
/// the state with none: no engine, and every hook a no-op.
|
||
#[derive(Default)]
|
||
pub struct Mods {
|
||
engine: Option<(Engine, Linker<State>)>,
|
||
entries: Vec<Entry>,
|
||
snapshot: Arc<Snapshot>,
|
||
out: Vec<Output>,
|
||
world: WorldSlot,
|
||
model_table: ModelSlot,
|
||
/// Moves on whenever a mod starts or stops: the game resends the server
|
||
/// mods' commands to players when it changes.
|
||
generation: u64,
|
||
}
|
||
|
||
impl Mods {
|
||
/// Changes whenever the running mods (so their commands) change.
|
||
pub fn generation(&self) -> u64 {
|
||
self.generation
|
||
}
|
||
/// Whether a running mod may use capability `world`: only then is a
|
||
/// view worth lending.
|
||
pub fn wants_world(&self) -> bool {
|
||
self.entries.iter().any(|e| {
|
||
e.status == Status::Running
|
||
&& e.manifest
|
||
.as_ref()
|
||
.is_some_and(|m| m.capabilities.contains(&crate::Capability::World))
|
||
})
|
||
}
|
||
/// Lends the game's world to capability `world` for the calls until
|
||
/// [`Mods::take_world`]; with none lent, `get-block` finds nothing and
|
||
/// `set-blocks` checks only its count.
|
||
pub fn lend_world(&mut self, view: Box<dyn WorldView>) {
|
||
if let Ok(mut slot) = self.world.lock() {
|
||
*slot = Some(view);
|
||
}
|
||
}
|
||
/// The game's registry for `render.model-id`. `key` names the registry
|
||
/// (its address): the same key keeps the handles, another one makes
|
||
/// `model-generation` move on and drops every mod's models. `make` runs
|
||
/// only then.
|
||
pub fn set_model_resolver(&mut self, key: usize, make: impl FnOnce() -> ModelResolver) {
|
||
let Ok(mut t) = self.model_table.lock() else {
|
||
return;
|
||
};
|
||
if t.key != key || t.resolve.is_none() {
|
||
t.key = key;
|
||
t.generation = t.generation.wrapping_add(1);
|
||
t.resolve = Some(make());
|
||
drop(t);
|
||
for e in &mut self.entries {
|
||
if let Some(r) = e.run.as_mut() {
|
||
r.store.data_mut().models.clear();
|
||
}
|
||
}
|
||
}
|
||
}
|
||
/// The view [`Mods::lend_world`] lent, back to the game.
|
||
pub fn take_world(&mut self) -> Option<Box<dyn WorldView>> {
|
||
self.world.lock().ok()?.take()
|
||
}
|
||
|
||
/// Reads every mod at `paths` and starts those `enabled` says are on,
|
||
/// client and server mods alike. A command that `reserved` (vanilla's
|
||
/// commands) or an earlier mod already uses is refused.
|
||
pub fn load(
|
||
paths: &[PathBuf],
|
||
enabled: impl Fn(&str) -> bool,
|
||
reserved: impl Fn(&str) -> bool,
|
||
) -> Mods {
|
||
Mods::load_for(Runs::Both, paths, enabled, reserved)
|
||
}
|
||
/// [`Mods::load`], starting only the mods `runs` says this game runs; the
|
||
/// others that are on are [`Status::Elsewhere`].
|
||
pub fn load_for(
|
||
runs: Runs,
|
||
paths: &[PathBuf],
|
||
enabled: impl Fn(&str) -> bool,
|
||
reserved: impl Fn(&str) -> bool,
|
||
) -> Mods {
|
||
let mut mods = Mods::default();
|
||
for path in paths {
|
||
let modified = modified(path);
|
||
let mut entry = Entry {
|
||
path: path.clone(),
|
||
manifest: None,
|
||
status: Status::Off,
|
||
cost: Duration::ZERO,
|
||
run: None,
|
||
modified,
|
||
};
|
||
match Package::read(path) {
|
||
Err(e) => entry.status = Status::Failed(e),
|
||
Ok(package) => {
|
||
let on = enabled(&package.manifest.id);
|
||
entry.manifest = Some(package.manifest.clone());
|
||
if on && !runs.starts(package.manifest.side) {
|
||
entry.status = Status::Elsewhere;
|
||
} else if on {
|
||
// Content is read before the world loads; a mod whose
|
||
// content is refused stays off, with the reason.
|
||
let content = crate::Content::read(path, &package.manifest);
|
||
entry.status =
|
||
match content.and_then(|_| mods.start(path, &package, &reserved)) {
|
||
Ok(run) => {
|
||
entry.run = run;
|
||
Status::Running
|
||
}
|
||
Err(e) => Status::Failed(e),
|
||
};
|
||
}
|
||
}
|
||
}
|
||
if let (Status::Failed(reason), Some(m)) = (&entry.status, &entry.manifest) {
|
||
log::warn!("Horizon: mod {} did not start: {reason}", m.id);
|
||
}
|
||
mods.entries.push(entry);
|
||
}
|
||
mods
|
||
}
|
||
|
||
fn engine(&mut self) -> Result<&(Engine, Linker<State>), String> {
|
||
if self.engine.is_none() {
|
||
let mut config = Config::new();
|
||
config.wasm_component_model(true).consume_fuel(true);
|
||
let engine = Engine::new(&config).map_err(|e| e.to_string())?;
|
||
let mut linker = Linker::new(&engine);
|
||
HorizonMod::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
|
||
.map_err(|e| e.to_string())?;
|
||
players::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
|
||
.map_err(|e| e.to_string())?;
|
||
mod_world::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
|
||
.map_err(|e| e.to_string())?;
|
||
UiHost::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
|
||
.map_err(|e| e.to_string())?;
|
||
RenderHost::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
|
||
.map_err(|e| e.to_string())?;
|
||
RecipesHost::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
|
||
.map_err(|e| e.to_string())?;
|
||
self.engine = Some((engine, linker));
|
||
}
|
||
Ok(self.engine.as_ref().expect("made above"))
|
||
}
|
||
|
||
/// Starts a mod's code; `Ok(None)` for a content-only mod, which has
|
||
/// nothing to run (the game reads its content before the world loads).
|
||
/// `path` is the mod's own `.hmod` or folder, for capability `storage`'s
|
||
/// per-mod directory.
|
||
fn start(
|
||
&mut self,
|
||
path: &Path,
|
||
package: &Package,
|
||
reserved: &dyn Fn(&str) -> bool,
|
||
) -> Result<Option<Running>, String> {
|
||
let m = &package.manifest;
|
||
let Some(wasm) = &package.wasm else {
|
||
return Ok(None);
|
||
};
|
||
// Two running mods with the same id would share one `data_dir`
|
||
// (capability `storage`): the first loaded keeps the id.
|
||
if self
|
||
.entries
|
||
.iter()
|
||
.any(|e| e.run.is_some() && e.manifest.as_ref().is_some_and(|other| other.id == m.id))
|
||
{
|
||
return Err(format!("another running mod already uses id {}", m.id));
|
||
}
|
||
let server = m.side == Side::Server;
|
||
let taken: Vec<String> = self
|
||
.entries
|
||
.iter()
|
||
.filter_map(|e| e.run.as_ref())
|
||
.filter(|r| r.hooks.server().is_some() == server)
|
||
.flat_map(|r| r.hooks.commands())
|
||
.map(str::to_owned)
|
||
.collect();
|
||
let snapshot = self.snapshot.clone();
|
||
let world = self.world.clone();
|
||
let model_table = self.model_table.clone();
|
||
let (engine, linker) = self.engine()?;
|
||
let component =
|
||
Component::new(engine, wasm).map_err(|e| format!("not a component: {e}"))?;
|
||
let ty = component.component_type();
|
||
let imports: Vec<String> = ty
|
||
.imports(engine)
|
||
.map(|(name, _)| name.to_string())
|
||
.collect();
|
||
m.check_imports(imports.iter().map(String::as_str))?;
|
||
// A function this Horizon doesn't have: say so, not wasmtime's linking error.
|
||
let functions = crate::api_level::imports(wasm)?;
|
||
let (level, function) = crate::api_level::needed(functions.iter().map(String::as_str));
|
||
if let Some(why) = crate::api_level::too_new(level, function) {
|
||
return Err(why);
|
||
}
|
||
let data_dir = path
|
||
.parent()
|
||
.unwrap_or(Path::new("."))
|
||
.join(crate::manifest::STORAGE_DIR)
|
||
.join(&m.id);
|
||
let state = State {
|
||
name: m.name.clone(),
|
||
id: m.id.clone(),
|
||
snapshot,
|
||
out: Vec::new(),
|
||
panel: None,
|
||
ui: UiState::default(),
|
||
shapes: Vec::new(),
|
||
corner: None,
|
||
zoom: None,
|
||
minimap: None,
|
||
far_terrain: None,
|
||
models: Vec::new(),
|
||
model_table: model_table.clone(),
|
||
ground_queries: Vec::new(),
|
||
chunk_requests: Vec::new(),
|
||
ground: Vec::new(),
|
||
ray_queries: Vec::new(),
|
||
ray_over: Vec::new(),
|
||
world_seen: false,
|
||
rays: Vec::new(),
|
||
section_queries: Vec::new(),
|
||
sections_asked: 0,
|
||
sections: Vec::new(),
|
||
world_changes: None,
|
||
post: None,
|
||
post_params: Vec::new(),
|
||
views: Vec::new(),
|
||
main_view: None,
|
||
lights: Vec::new(),
|
||
spots: Vec::new(),
|
||
sources: Default::default(),
|
||
run_serial: {
|
||
static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||
SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
|
||
},
|
||
lighting: None,
|
||
time_override: None,
|
||
trees: Vec::new(),
|
||
lists: Vec::new(),
|
||
tree_generation: 0,
|
||
smoke: Vec::new(),
|
||
smoke_clock: (0.0, 0.0),
|
||
input: InputState::default(),
|
||
browser: BrowserState::default(),
|
||
data_dir,
|
||
storage_budget: STORAGE_WRITE_BUDGET,
|
||
limits: StoreLimitsBuilder::new()
|
||
.memory_size(MEMORY)
|
||
.instances(16)
|
||
.build(),
|
||
world,
|
||
};
|
||
let mut store = Store::new(engine, state);
|
||
store.limiter(|s| &mut s.limits);
|
||
store.set_fuel(FUEL_INIT).map_err(|e| e.to_string())?;
|
||
let instance = linker
|
||
.instantiate(&mut store, &component)
|
||
.map_err(|e| reason(&e))?;
|
||
let (mut hooks, ui) = if server {
|
||
let exports = HorizonServerMod::new(&mut store, &instance).map_err(|e| reason(&e))?;
|
||
let r = exports
|
||
.horizon_mods_server_events()
|
||
.call_init(&mut store)
|
||
.map_err(|e| reason(&e))??;
|
||
(Hooks::Server(exports, r), None)
|
||
} else {
|
||
let exports = HorizonMod::new(&mut store, &instance).map_err(|e| reason(&e))?;
|
||
// `ui-events` is a mod built since `ui`'s; older mods have no export
|
||
// and stay callable through `events` alone.
|
||
let ui = UiHost::new(&mut store, &instance).ok();
|
||
let r = exports
|
||
.horizon_mods_events()
|
||
.call_init(&mut store)
|
||
.map_err(|e| reason(&e))??;
|
||
(Hooks::Client(exports, r), ui)
|
||
};
|
||
let free = |c: &str| {
|
||
let free = !reserved(c) && !taken.iter().any(|t| t == c);
|
||
if !free {
|
||
log::warn!("Horizon: mod {} cannot take /{c}: already a command", m.id);
|
||
}
|
||
free
|
||
};
|
||
match &mut hooks {
|
||
Hooks::Client(_, r) => r.commands.retain(|c| free(c)),
|
||
Hooks::Server(_, r) => {
|
||
r.commands.retain(|c| free(&c.name));
|
||
for c in &mut r.commands {
|
||
if let Err(e) = check_arguments(&c.arguments) {
|
||
log::warn!(
|
||
"Horizon: mod {}'s /{}: {e}; it takes free text",
|
||
m.id,
|
||
c.name
|
||
);
|
||
c.arguments.clear();
|
||
}
|
||
}
|
||
}
|
||
}
|
||
self.generation += 1;
|
||
self.out.append(&mut store.data_mut().out);
|
||
Ok(Some(Running {
|
||
store,
|
||
ui,
|
||
hooks,
|
||
raycasts: functions.iter().any(|f| f == "game.raycast"),
|
||
reads_recipes: functions.iter().any(|f| f.starts_with("recipes.")),
|
||
}))
|
||
}
|
||
|
||
/// True when at least one mod runs: the game skips its mod work otherwise.
|
||
pub fn is_running(&self) -> bool {
|
||
self.entries.iter().any(|e| e.run.is_some())
|
||
}
|
||
/// True when a server mod runs: the server skips its mod work otherwise.
|
||
pub fn runs_server(&self) -> bool {
|
||
self.entries
|
||
.iter()
|
||
.any(|e| e.run.as_ref().is_some_and(|r| r.hooks.server().is_some()))
|
||
}
|
||
pub fn entries(&self) -> &[Entry] {
|
||
&self.entries
|
||
}
|
||
/// What mods read until the next snapshot.
|
||
pub fn set_snapshot(&mut self, snapshot: Snapshot) {
|
||
self.snapshot = Arc::new(snapshot);
|
||
}
|
||
|
||
/// Calls `f` on every running mod whose hooks `wants`, with `fuel`.
|
||
fn each(
|
||
&mut self,
|
||
fuel: u64,
|
||
wants: impl Fn(&Hooks) -> bool,
|
||
mut f: impl FnMut(&mut Running) -> wasmtime::Result<()>,
|
||
) {
|
||
for i in 0..self.entries.len() {
|
||
if self.entries[i]
|
||
.run
|
||
.as_ref()
|
||
.is_some_and(|r| wants(&r.hooks))
|
||
{
|
||
self.call(i, fuel, &mut f);
|
||
}
|
||
}
|
||
}
|
||
/// [`Mods::each`] over the client mods.
|
||
fn each_client(
|
||
&mut self,
|
||
fuel: u64,
|
||
wants: impl Fn(&Registration) -> bool,
|
||
mut f: impl FnMut(&ClientEvents, &mut Store<State>) -> wasmtime::Result<()>,
|
||
) {
|
||
self.each(
|
||
fuel,
|
||
|h| h.client().is_some_and(&wants),
|
||
|run| match &run.hooks {
|
||
Hooks::Client(m, _) => f(m.horizon_mods_events(), &mut run.store),
|
||
Hooks::Server(..) => Ok(()),
|
||
},
|
||
);
|
||
}
|
||
/// [`Mods::each`] over the server mods.
|
||
fn each_server(
|
||
&mut self,
|
||
fuel: u64,
|
||
wants: impl Fn(&ServerRegistration) -> bool,
|
||
mut f: impl FnMut(&ServerEvents, &mut Store<State>) -> wasmtime::Result<()>,
|
||
) {
|
||
self.each(
|
||
fuel,
|
||
|h| h.server().is_some_and(&wants),
|
||
|run| match &run.hooks {
|
||
Hooks::Server(m, _) => f(m.horizon_mods_server_events(), &mut run.store),
|
||
Hooks::Client(..) => Ok(()),
|
||
},
|
||
);
|
||
}
|
||
|
||
/// One call into mod `i`; a trap or an overrun turns the mod off.
|
||
fn call<R>(
|
||
&mut self,
|
||
i: usize,
|
||
fuel: u64,
|
||
f: impl FnOnce(&mut Running) -> wasmtime::Result<R>,
|
||
) -> Option<R> {
|
||
let entry = &mut self.entries[i];
|
||
let run = entry.run.as_mut()?;
|
||
run.store.data_mut().snapshot = self.snapshot.clone();
|
||
run.store.data_mut().storage_budget = STORAGE_WRITE_BUDGET;
|
||
let started = Instant::now();
|
||
let result = run.store.set_fuel(fuel).and_then(|()| f(run));
|
||
// An average over about the last 64 calls.
|
||
entry.cost = (entry.cost * 63 + started.elapsed()) / 64;
|
||
let data = run.store.data_mut();
|
||
let (open, close) = (
|
||
std::mem::take(&mut data.ui.open),
|
||
std::mem::take(&mut data.ui.close),
|
||
);
|
||
self.out.append(&mut data.out);
|
||
if open {
|
||
self.out.push(Output::OpenScreen { owner: i });
|
||
}
|
||
if close {
|
||
self.out.push(Output::CloseScreen { owner: i });
|
||
}
|
||
match result {
|
||
Ok(r) => Some(r),
|
||
Err(e) => {
|
||
let reason = reason(&e);
|
||
log::warn!("Horizon: mod {} stopped: {reason}", run.store.data().id);
|
||
let name = run.store.data().name.clone();
|
||
self.out.push(Output::Stopped {
|
||
name,
|
||
reason: reason.clone(),
|
||
});
|
||
entry.status = Status::Failed(reason);
|
||
entry.run = None;
|
||
self.generation += 1;
|
||
None
|
||
}
|
||
}
|
||
}
|
||
|
||
/// A game tick.
|
||
pub fn tick(&mut self, tick: u64) {
|
||
self.each_client(FUEL_TICK, |h| h.tick, |m, s| m.call_tick(s, tick));
|
||
}
|
||
/// A rendered frame, `seconds` after the last.
|
||
pub fn frame(&mut self, seconds: f32) {
|
||
self.each_client(FUEL_FRAME, |h| h.frame, |m, s| m.call_frame(s, seconds));
|
||
}
|
||
/// A chat line the player received, as plain text.
|
||
pub fn chat(&mut self, text: &str) {
|
||
self.each_client(FUEL_EVENT, |h| h.chat, |m, s| m.call_chat(s, text));
|
||
}
|
||
/// Whether a running client mod owns `/name`.
|
||
pub fn has_command(&self, name: &str) -> bool {
|
||
self.command_owner(false, name).is_some()
|
||
}
|
||
fn command_owner(&self, server: bool, name: &str) -> Option<usize> {
|
||
self.entries.iter().position(|e| {
|
||
e.run.as_ref().is_some_and(|r| {
|
||
r.hooks.server().is_some() == server && r.hooks.commands().contains(&name)
|
||
})
|
||
})
|
||
}
|
||
/// Runs `line` (without its slash) if a client mod owns its command;
|
||
/// false when none does.
|
||
pub fn command(&mut self, line: &str) -> bool {
|
||
let (name, args) = line.split_once(' ').unwrap_or((line, ""));
|
||
let Some(i) = self.command_owner(false, name) else {
|
||
return false;
|
||
};
|
||
let result = self.call(i, FUEL_EVENT, |run| match &run.hooks {
|
||
Hooks::Client(m, _) => m
|
||
.horizon_mods_events()
|
||
.call_command(&mut run.store, name, args),
|
||
Hooks::Server(..) => Ok(Ok(None)),
|
||
});
|
||
match result {
|
||
Some(Ok(Some(text))) => self.out.push(Output::Feedback { text, error: false }),
|
||
Some(Err(text)) => self.out.push(Output::Feedback { text, error: true }),
|
||
Some(Ok(None)) | None => {}
|
||
}
|
||
true
|
||
}
|
||
/// The commands running client mods own, for suggestions.
|
||
pub fn commands(&self) -> impl Iterator<Item = &str> {
|
||
self.owned_commands(false)
|
||
}
|
||
fn owned_commands(&self, server: bool) -> impl Iterator<Item = &str> {
|
||
self.entries
|
||
.iter()
|
||
.filter_map(|e| e.run.as_ref())
|
||
.filter(move |r| r.hooks.server().is_some() == server)
|
||
.flat_map(|r| r.hooks.commands())
|
||
}
|
||
|
||
/// A server tick.
|
||
pub fn server_tick(&mut self, tick: u64) {
|
||
self.each_server(FUEL_TICK, |h| h.tick, |m, s| m.call_tick(s, tick));
|
||
}
|
||
/// `player` joined the server (they are in the snapshot's players).
|
||
pub fn player_joined(&mut self, player: &ServerPlayer) {
|
||
self.each_server(
|
||
FUEL_EVENT,
|
||
|h| h.joins,
|
||
|m, s| m.call_player_joined(s, player),
|
||
);
|
||
}
|
||
/// `player` left the server (they are no longer in the snapshot's players).
|
||
pub fn player_left(&mut self, player: &ServerPlayer) {
|
||
self.each_server(
|
||
FUEL_EVENT,
|
||
|h| h.joins,
|
||
|m, s| m.call_player_left(s, player),
|
||
);
|
||
}
|
||
/// A chat message `player` sent, as plain text.
|
||
pub fn player_chat(&mut self, player: &ServerPlayer, text: &str) {
|
||
self.each_server(FUEL_EVENT, |h| h.chat, |m, s| m.call_chat(s, player, text));
|
||
}
|
||
/// `player` broke `state` at `pos`.
|
||
pub fn block_broken(&mut self, player: &ServerPlayer, pos: BlockPos, state: &str) {
|
||
self.each_server(
|
||
FUEL_EVENT,
|
||
|h| h.blocks,
|
||
|m, s| m.call_block_broken(s, player, pos, state),
|
||
);
|
||
}
|
||
/// `player` placed `state` at `pos`.
|
||
pub fn block_placed(&mut self, player: &ServerPlayer, pos: BlockPos, state: &str) {
|
||
self.each_server(
|
||
FUEL_EVENT,
|
||
|h| h.blocks,
|
||
|m, s| m.call_block_placed(s, player, pos, state),
|
||
);
|
||
}
|
||
/// The commands running server mods own and their arguments, for the
|
||
/// server's command tree.
|
||
pub fn server_commands(&self) -> impl Iterator<Item = &ServerCommand> {
|
||
self.entries
|
||
.iter()
|
||
.filter_map(|e| e.run.as_ref()?.hooks.server())
|
||
.flat_map(|r| r.commands.iter())
|
||
}
|
||
/// Runs `line` (without its slash), typed by `player`, if a server mod
|
||
/// owns its command; its feedback is an [`Output::Reply`]. False when
|
||
/// none does.
|
||
pub fn server_command(&mut self, player: &ServerPlayer, line: &str) -> bool {
|
||
let (name, args) = line.split_once(' ').unwrap_or((line, ""));
|
||
let Some(i) = self.command_owner(true, name) else {
|
||
return false;
|
||
};
|
||
let reply = |text, error| Output::Reply {
|
||
player: player.id.clone(),
|
||
text,
|
||
error,
|
||
};
|
||
let arguments = self.entries[i]
|
||
.run
|
||
.as_ref()
|
||
.and_then(|r| r.hooks.server())
|
||
.and_then(|r| r.commands.iter().find(|c| c.name == name))
|
||
.map(|c| c.arguments.as_slice())
|
||
.unwrap_or_default();
|
||
let values = match crate::commands::parse(arguments, args, player, &self.snapshot.players) {
|
||
Ok(values) => values,
|
||
Err(e) => {
|
||
self.out.push(reply(e, true));
|
||
return true;
|
||
}
|
||
};
|
||
let result = self.call(i, FUEL_EVENT, |run| match &run.hooks {
|
||
Hooks::Server(m, _) => m.horizon_mods_server_events().call_command(
|
||
&mut run.store,
|
||
player,
|
||
name,
|
||
args,
|
||
&values,
|
||
),
|
||
Hooks::Client(..) => Ok(Ok(None)),
|
||
});
|
||
match result {
|
||
Some(Ok(Some(text))) => self.out.push(reply(text, false)),
|
||
Some(Err(text)) => self.out.push(reply(text, true)),
|
||
Some(Ok(None)) | None => {}
|
||
}
|
||
true
|
||
}
|
||
/// The running mods' HUD panels.
|
||
pub fn panels(&self) -> impl Iterator<Item = &Panel> {
|
||
self.entries
|
||
.iter()
|
||
.filter_map(|e| e.run.as_ref()?.store.data().panel.as_ref())
|
||
}
|
||
/// The running mods' corner panels (capability `render`), in load order.
|
||
pub fn corner_panels(&self) -> impl Iterator<Item = &CornerPanel> {
|
||
self.entries
|
||
.iter()
|
||
.filter_map(|e| e.run.as_ref()?.store.data().corner.as_ref())
|
||
}
|
||
/// Some running mod calls `game.raycast`: the snapshot needs a
|
||
/// [`Snapshot::view_hit`].
|
||
pub fn wants_raycast(&self) -> bool {
|
||
self.entries
|
||
.iter()
|
||
.any(|e| e.run.as_ref().is_some_and(|r| r.raycasts))
|
||
}
|
||
/// The panel beside container screens (`browser.set-items`): the first
|
||
/// running mod with items or recipes, its index, the panel's version and
|
||
/// the items.
|
||
pub fn browser_items(&self) -> Option<(usize, u64, &[BrowserStack])> {
|
||
self.entries.iter().enumerate().find_map(|(i, e)| {
|
||
let b = &e.run.as_ref()?.store.data().browser;
|
||
(!b.items.is_empty() || b.recipes.is_some()).then_some((
|
||
i,
|
||
b.version,
|
||
b.items.as_slice(),
|
||
))
|
||
})
|
||
}
|
||
/// What mod `owner`'s panel shows instead of its items
|
||
/// (`browser.set-recipes`).
|
||
pub fn browser_recipes(&self, owner: usize) -> Option<&RecipePage> {
|
||
let b = &self.entries.get(owner)?.run.as_ref()?.store.data().browser;
|
||
b.recipes.as_ref()
|
||
}
|
||
/// The player did `event` on mod `owner`'s panel.
|
||
pub fn browser_event(&mut self, owner: usize, event: BrowserEvent) {
|
||
if let Some(run) = self.entries.get_mut(owner).and_then(|e| e.run.as_mut()) {
|
||
run.store.data_mut().browser.push(event);
|
||
}
|
||
}
|
||
/// The key `key` went down with the pointer on `stack` in a container
|
||
/// screen: each mod with a key on it hears its own name for it.
|
||
pub fn browser_key(&mut self, key: &str, stack: &BrowserStack) {
|
||
for run in self.entries.iter_mut().filter_map(|e| e.run.as_mut()) {
|
||
let data = run.store.data_mut();
|
||
let names: Vec<String> = data
|
||
.input
|
||
.keys
|
||
.iter()
|
||
.filter(|k| k.key == key)
|
||
.map(|k| k.name.clone())
|
||
.collect();
|
||
for key in names {
|
||
data.browser.push(BrowserEvent::Key(BrowserItemKey {
|
||
key,
|
||
stack: stack.clone(),
|
||
}));
|
||
}
|
||
}
|
||
}
|
||
/// Some running mod reads capability `recipes`: the snapshot needs
|
||
/// [`Snapshot::recipes`] and [`Snapshot::known_recipes`].
|
||
pub fn wants_recipes(&self) -> bool {
|
||
self.entries
|
||
.iter()
|
||
.any(|e| e.run.as_ref().is_some_and(|r| r.reads_recipes))
|
||
}
|
||
/// Some running mod has a `frame` hook: the game refreshes the snapshot
|
||
/// every frame for it.
|
||
pub fn wants_frames(&self) -> bool {
|
||
self.entries.iter().any(|e| {
|
||
e.run
|
||
.as_ref()
|
||
.is_some_and(|r| r.hooks.client().is_some_and(|h| h.frame))
|
||
})
|
||
}
|
||
/// Some running mod claimed items (capability `input`).
|
||
pub fn claims_any(&self) -> bool {
|
||
self.inputs().any(|i| !i.claimed.is_empty())
|
||
}
|
||
/// Some running mod claimed the item `id`.
|
||
pub fn claims(&self, id: &str) -> bool {
|
||
self.inputs().any(|i| i.claimed.iter().any(|c| c == id))
|
||
}
|
||
/// Some running mod registered a key.
|
||
pub fn has_keys(&self) -> bool {
|
||
self.inputs().any(|i| !i.keys.is_empty())
|
||
}
|
||
/// The mods' keys: (mod name, key name, label, key), for Controls.
|
||
pub fn mod_keys(&self) -> impl Iterator<Item = (&str, &ModKey)> {
|
||
self.entries
|
||
.iter()
|
||
.filter_map(|e| e.run.as_ref())
|
||
.flat_map(|r| {
|
||
let d = r.store.data();
|
||
d.input.keys.iter().map(move |k| (d.name.as_str(), k))
|
||
})
|
||
}
|
||
/// Mod `i`'s keys, as it registered them (with the player's choices).
|
||
pub fn keys_of(&self, i: usize) -> &[ModKey] {
|
||
self.entries
|
||
.get(i)
|
||
.and_then(|e| e.run.as_ref())
|
||
.map_or(&[], |r| r.store.data().input.keys.as_slice())
|
||
}
|
||
/// The keys the player chose (`ui`'s key widget), by mod id: each
|
||
/// running mod's `name → key`. They replace the defaults registered
|
||
/// so far and later ones. Keys that aren't keys are skipped.
|
||
pub fn set_bindings<'a>(&mut self, chosen: impl Fn(&str) -> Vec<(&'a str, &'a str)>) {
|
||
for e in &mut self.entries {
|
||
let (Some(m), Some(run)) = (&e.manifest, e.run.as_mut()) else {
|
||
continue;
|
||
};
|
||
let input = &mut run.store.data_mut().input;
|
||
input.bindings = chosen(&m.id)
|
||
.into_iter()
|
||
.filter(|(_, key)| key_ok(key))
|
||
.map(|(n, k)| (n.to_owned(), k.to_owned()))
|
||
.collect();
|
||
for (name, key) in input.bindings.clone() {
|
||
input.rebind(&name, key);
|
||
}
|
||
}
|
||
}
|
||
/// The player binds mod `i`'s key `name` to `key` (`key.keyboard.x`,
|
||
/// `key.mouse.4`, `key.keyboard.unknown` for none). False when the mod
|
||
/// has no such key or `key` isn't one.
|
||
pub fn rebind(&mut self, i: usize, name: &str, key: &str) -> bool {
|
||
let Some(run) = self.entries.get_mut(i).and_then(|e| e.run.as_mut()) else {
|
||
return false;
|
||
};
|
||
let input = &mut run.store.data_mut().input;
|
||
if !key_ok(key) || !input.keys.iter().any(|k| k.name == name) {
|
||
return false;
|
||
}
|
||
input.bindings.retain(|(n, _)| n != name);
|
||
input.bindings.push((name.to_owned(), key.to_owned()));
|
||
input.rebind(name, key.to_owned());
|
||
true
|
||
}
|
||
/// The use button went down with `item`: `use-start` to each mod that
|
||
/// claimed it.
|
||
pub fn use_start(&mut self, item: &HeldItem) {
|
||
let event = InputEvent::UseStart(ItemUse {
|
||
item: item.clone(),
|
||
ticks: 0,
|
||
});
|
||
self.push_input(|i| i.claimed.contains(&item.id), &event);
|
||
}
|
||
/// The claimed use ended after `ticks`.
|
||
pub fn use_stop(&mut self, item: &HeldItem, ticks: u32) {
|
||
let event = InputEvent::UseStop(ItemUse {
|
||
item: item.clone(),
|
||
ticks,
|
||
});
|
||
self.push_input(|i| i.claimed.contains(&item.id), &event);
|
||
}
|
||
/// The key `key` (`key.keyboard.r`) went down or up: each mod with a
|
||
/// key on it hears its own name for it.
|
||
pub fn key(&mut self, key: &str, down: bool) {
|
||
for run in self.entries.iter_mut().filter_map(|e| e.run.as_mut()) {
|
||
let input = &mut run.store.data_mut().input;
|
||
let names: Vec<String> = input
|
||
.keys
|
||
.iter()
|
||
.filter(|k| k.key == key)
|
||
.map(|k| k.name.clone())
|
||
.collect();
|
||
for name in names {
|
||
let held = input.down.iter().position(|n| *n == name);
|
||
match (down, held) {
|
||
(true, None) => input.down.push(name.clone()),
|
||
(false, Some(i)) => {
|
||
input.down.swap_remove(i);
|
||
}
|
||
// Already let go when a screen opened.
|
||
(false, None) => continue,
|
||
(true, Some(_)) => {}
|
||
}
|
||
input.push(if down {
|
||
InputEvent::KeyDown(name)
|
||
} else {
|
||
InputEvent::KeyUp(name)
|
||
});
|
||
}
|
||
}
|
||
}
|
||
/// A screen opened, or the game stopped playing: every mod key held
|
||
/// lets go (`key-up`), so a key needs a new press afterwards.
|
||
pub fn release_keys(&mut self) {
|
||
for run in self.entries.iter_mut().filter_map(|e| e.run.as_mut()) {
|
||
let input = &mut run.store.data_mut().input;
|
||
for name in std::mem::take(&mut input.down) {
|
||
input.push(InputEvent::KeyUp(name));
|
||
}
|
||
}
|
||
}
|
||
/// Some running mod holds the mouse wheel.
|
||
pub fn wheel_claimed(&self) -> bool {
|
||
self.inputs().any(|i| i.wheel)
|
||
}
|
||
/// Wheel steps while playing: `wheel` to the mods holding it; false
|
||
/// when none does (the hotbar takes them).
|
||
pub fn wheel(&mut self, steps: f32) -> bool {
|
||
let event = InputEvent::Wheel(steps);
|
||
let claimed = self.wheel_claimed();
|
||
self.push_input(|i| i.wheel, &event);
|
||
claimed
|
||
}
|
||
/// The strongest zoom a running mod asks for (capability `render`).
|
||
pub fn zoom(&self) -> Option<ModZoom> {
|
||
self.entries
|
||
.iter()
|
||
.filter_map(|e| e.run.as_ref()?.store.data().zoom)
|
||
.max_by(|a, b| a.factor.total_cmp(&b.factor))
|
||
}
|
||
/// The minimap the first running mod shows (capability `render`).
|
||
pub fn minimap(&self) -> Option<ModMinimap> {
|
||
self.entries
|
||
.iter()
|
||
.find_map(|e| e.run.as_ref()?.store.data().minimap)
|
||
}
|
||
/// Every running mod's world models (AirDef fork), with the mod's index
|
||
/// so ids of different mods don't meet.
|
||
pub fn models(&self) -> impl Iterator<Item = (usize, &HostModel)> {
|
||
self.entries.iter().enumerate().flat_map(|(i, e)| {
|
||
e.run
|
||
.iter()
|
||
.flat_map(move |r| r.store.data().models.iter().map(move |m| (i, m)))
|
||
})
|
||
}
|
||
/// Every running mod's cameras (AirDef fork), with the mod's index.
|
||
pub fn views(&self) -> impl Iterator<Item = (usize, &CameraView)> {
|
||
self.entries.iter().enumerate().flat_map(|(i, e)| {
|
||
e.run
|
||
.iter()
|
||
.flat_map(move |r| r.store.data().views.iter().map(move |v| (i, v)))
|
||
})
|
||
}
|
||
/// Every running mod's lights (AirDef fork), with the mod's index.
|
||
pub fn lights(&self) -> impl Iterator<Item = (usize, &PointLight)> {
|
||
self.entries.iter().enumerate().flat_map(|(i, e)| {
|
||
e.run
|
||
.iter()
|
||
.flat_map(move |r| r.store.data().lights.iter().map(move |l| (i, l)))
|
||
})
|
||
}
|
||
/// Moves the generation `render.sound-source-generation` reports (the game released
|
||
/// every source): the mods' pending source changes go with the old one.
|
||
pub fn set_source_generation(&mut self, generation: u32) {
|
||
let Ok(mut t) = self.model_table.lock() else {
|
||
return;
|
||
};
|
||
if t.source_generation == generation {
|
||
return;
|
||
}
|
||
t.source_generation = generation;
|
||
drop(t);
|
||
for e in &mut self.entries {
|
||
if let Some(r) = e.run.as_mut() {
|
||
r.store.data_mut().sources.clear();
|
||
}
|
||
}
|
||
}
|
||
/// Whether the game muffles sounds itself (`render.acoustics`).
|
||
pub fn set_acoustics(&mut self, on: bool) {
|
||
if let Ok(mut t) = self.model_table.lock() {
|
||
t.acoustics = on;
|
||
}
|
||
}
|
||
/// The source changes every running mod made since the last call, tagged with the
|
||
/// number of the mod's run ([`Mods::source_runs`]).
|
||
pub fn take_source_changes(&mut self) -> Vec<(u64, crate::sources::SourceChange)> {
|
||
let mut out = Vec::new();
|
||
for e in &mut self.entries {
|
||
if let Some(r) = e.run.as_mut() {
|
||
let d = r.store.data_mut();
|
||
let serial = d.run_serial;
|
||
out.extend(d.sources.take().into_iter().map(|c| (serial, c)));
|
||
}
|
||
}
|
||
out
|
||
}
|
||
/// The runs that are alive: the game releases the sources of any other.
|
||
pub fn source_runs(&self) -> Vec<u64> {
|
||
self.entries
|
||
.iter()
|
||
.filter_map(|e| e.run.as_ref().map(|r| r.store.data().run_serial))
|
||
.collect()
|
||
}
|
||
/// Every running mod's spot lights (AirDef fork), with the mod's index.
|
||
pub fn spot_lights(&self) -> impl Iterator<Item = (usize, &SpotLight)> {
|
||
self.entries.iter().enumerate().flat_map(|(i, e)| {
|
||
e.run
|
||
.iter()
|
||
.flat_map(move |r| r.store.data().spots.iter().map(move |l| (i, l)))
|
||
})
|
||
}
|
||
/// Tells the mods whether the renderer draws their spot lights (the answer of `render.set-spot-lights`).
|
||
pub fn set_spot_active(&mut self, on: bool) {
|
||
if let Ok(mut t) = self.model_table.lock() {
|
||
t.spot_active = on;
|
||
}
|
||
}
|
||
/// The capture a mod asked to start since the last call (`render.capture-start`).
|
||
pub fn take_capture_request(&self) -> Option<CaptureOptions> {
|
||
self.model_table.lock().ok()?.capture_request.take()
|
||
}
|
||
/// A capture stop asked since the last call; true to cancel (throw the file away).
|
||
pub fn take_capture_stop(&self) -> Option<bool> {
|
||
self.model_table.lock().ok()?.capture_stop.take()
|
||
}
|
||
/// The game's note of where the capture is (`render.capture-status`).
|
||
pub fn set_capture_state(&self, state: CaptureState) {
|
||
if let Ok(mut t) = self.model_table.lock() {
|
||
t.capture_state = Some(state);
|
||
}
|
||
}
|
||
/// The block-change log a mod asked for (`render.world-log-start`), if any.
|
||
pub fn world_log_wanted(&self) -> Option<u32> {
|
||
self.model_table.lock().ok()?.world_log
|
||
}
|
||
/// The game's note of what the log covers: (id, earliest tick, tick now), or none.
|
||
pub fn set_world_log_state(&self, state: Option<(u32, u64, u64)>) {
|
||
if let Ok(mut t) = self.model_table.lock() {
|
||
t.world_log_state = state;
|
||
}
|
||
}
|
||
/// The world a mod asked to be shown at a tick (`render.set-world-time-view`): (log id, tick).
|
||
pub fn time_view(&self) -> Option<(u32, u64)> {
|
||
self.model_table.lock().ok()?.time_view
|
||
}
|
||
/// Whether a mod asked for the best picture (`render.set-film-quality`).
|
||
pub fn film_quality(&self) -> bool {
|
||
self.model_table.lock().is_ok_and(|t| t.film_quality)
|
||
}
|
||
/// The first running mod's lighting, if it set one.
|
||
pub fn lighting(&self) -> Option<ModLighting> {
|
||
self.entries
|
||
.iter()
|
||
.find_map(|e| e.run.as_ref()?.store.data().lighting)
|
||
}
|
||
/// Every running mod's smoke segments (AirDef fork).
|
||
pub fn smoke(&self) -> impl Iterator<Item = &SmokeSegment> {
|
||
self.entries
|
||
.iter()
|
||
.flat_map(|e| e.run.iter().flat_map(|r| r.store.data().smoke.iter()))
|
||
}
|
||
/// The clocks (ticks) of the first mod that set smoke: of its last call and of the one before.
|
||
pub fn smoke_clock(&self) -> Option<(f64, f64)> {
|
||
self.entries
|
||
.iter()
|
||
.find_map(|e| e.run.as_ref().filter(|r| !r.store.data().smoke.is_empty()))
|
||
.map(|r| r.store.data().smoke_clock)
|
||
}
|
||
/// Tells the mods whether the renderer draws their smoke (the answer of `render.set-smoke`).
|
||
pub fn set_smoke_active(&mut self, on: bool) {
|
||
if let Ok(mut t) = self.model_table.lock() {
|
||
t.smoke_active = on;
|
||
}
|
||
}
|
||
/// The camera the first running mod asked the screen's world from, if any.
|
||
pub fn main_view(&self) -> Option<u32> {
|
||
self.entries
|
||
.iter()
|
||
.find_map(|e| e.run.as_ref()?.store.data().main_view)
|
||
}
|
||
/// The argument trees running client mods gave their registered commands
|
||
/// (`command.set-tree`), for the chat to colour and complete; a tree
|
||
/// for a name the mod did not register is left out.
|
||
pub fn command_trees(&self) -> Vec<CommandTree<'_>> {
|
||
let mut out = Vec::new();
|
||
for e in &self.entries {
|
||
let Some(run) = e.run.as_ref() else { continue };
|
||
let Some(registration) = run.hooks.client() else {
|
||
continue;
|
||
};
|
||
let state = run.store.data();
|
||
for (name, nodes) in &state.trees {
|
||
if registration.commands.contains(name) {
|
||
out.push(CommandTree {
|
||
name,
|
||
nodes,
|
||
lists: &state.lists,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
out
|
||
}
|
||
/// Changes whenever a mod's tree or suggestion list does (and when mods
|
||
/// start or stop), so the chat knows to rebuild its tree.
|
||
pub fn tree_generation(&self) -> u64 {
|
||
self.entries
|
||
.iter()
|
||
.filter_map(|e| e.run.as_ref())
|
||
.map(|r| r.store.data().tree_generation + 1)
|
||
.sum()
|
||
}
|
||
/// The time of day the first running mod asked to show, if any.
|
||
pub fn time_override(&self) -> Option<u64> {
|
||
self.entries
|
||
.iter()
|
||
.find_map(|e| e.run.as_ref()?.store.data().time_override)
|
||
}
|
||
/// The columns each running mod asked the ground height of, taken.
|
||
pub fn take_ground_queries(&mut self) -> Vec<(usize, Vec<(i32, i32)>)> {
|
||
// The last answers are read once: a mod that asked nothing since gets none (not the same again).
|
||
for run in self.entries.iter_mut().filter_map(|e| e.run.as_mut()) {
|
||
run.store.data_mut().ground.clear();
|
||
}
|
||
self.entries
|
||
.iter_mut()
|
||
.enumerate()
|
||
.filter_map(|(i, e)| {
|
||
let q = std::mem::take(&mut e.run.as_mut()?.store.data_mut().ground_queries);
|
||
(!q.is_empty()).then_some((i, q))
|
||
})
|
||
.collect()
|
||
}
|
||
/// The chunks the running mods asked the game to load (`render.load-chunks`), taken.
|
||
pub fn take_chunk_requests(&mut self) -> Vec<(i32, i32)> {
|
||
self.entries
|
||
.iter_mut()
|
||
.filter_map(|e| Some(std::mem::take(&mut e.run.as_mut()?.store.data_mut().chunk_requests)))
|
||
.flatten()
|
||
.collect()
|
||
}
|
||
/// The first running mod's post pass (version, WGSL) and its parameters.
|
||
pub fn post(&self) -> Option<(u64, &str, &[f32])> {
|
||
self.entries.iter().find_map(|e| {
|
||
let d = e.run.as_ref()?.store.data();
|
||
let (v, src) = d.post.as_ref()?;
|
||
Some((*v, src.as_str(), d.post_params.as_slice()))
|
||
})
|
||
}
|
||
/// What each running mod asked of the world this tick: segments and
|
||
/// sections (`render.query-rays`, `render.query-sections`), taken.
|
||
pub fn take_world_queries(&mut self) -> Vec<(usize, WorldQueries)> {
|
||
self.entries
|
||
.iter_mut()
|
||
.enumerate()
|
||
.filter_map(|(i, e)| {
|
||
let d = e.run.as_mut()?.store.data_mut();
|
||
d.sections_asked = 0;
|
||
let q = WorldQueries {
|
||
rays: std::mem::take(&mut d.ray_queries),
|
||
over: std::mem::take(&mut d.ray_over),
|
||
sections: std::mem::take(&mut d.section_queries),
|
||
};
|
||
(d.world_seen || !q.rays.is_empty() || !q.sections.is_empty()).then_some((i, q))
|
||
})
|
||
.collect()
|
||
}
|
||
/// Mod `i`'s answers to its world queries and the note of what changed,
|
||
/// for its next calls (what it was not answered, it gets again empty).
|
||
pub fn answer_world(
|
||
&mut self,
|
||
i: usize,
|
||
rays: Vec<WorldRayAnswer>,
|
||
sections: Vec<WorldSection>,
|
||
changes: WorldChanges,
|
||
) {
|
||
if let Some(run) = self.entries.get_mut(i).and_then(|e| e.run.as_mut()) {
|
||
let d = run.store.data_mut();
|
||
d.rays = rays;
|
||
d.sections = sections;
|
||
d.world_changes = Some(changes);
|
||
}
|
||
}
|
||
/// Mod `i`'s answers to its ground queries, for its next calls.
|
||
pub fn answer_ground(&mut self, i: usize, ground: Vec<(i32, i32, i32)>) {
|
||
if let Some(run) = self.entries.get_mut(i).and_then(|e| e.run.as_mut()) {
|
||
run.store.data_mut().ground = ground;
|
||
}
|
||
}
|
||
/// The far terrain the first running mod draws (capability `render`).
|
||
pub fn far_terrain(&self) -> Option<ModFarTerrain> {
|
||
self.entries
|
||
.iter()
|
||
.find_map(|e| e.run.as_ref()?.store.data().far_terrain)
|
||
}
|
||
fn inputs(&self) -> impl Iterator<Item = &InputState> {
|
||
self.entries
|
||
.iter()
|
||
.filter_map(|e| Some(&e.run.as_ref()?.store.data().input))
|
||
}
|
||
fn push_input(&mut self, to: impl Fn(&InputState) -> bool, event: &InputEvent) {
|
||
for run in self.entries.iter_mut().filter_map(|e| e.run.as_mut()) {
|
||
let input = &mut run.store.data_mut().input;
|
||
if to(input) {
|
||
input.push(event.clone());
|
||
}
|
||
}
|
||
}
|
||
/// The running mods' HUD shapes (capability `render`), each mod's in
|
||
/// its own order, mods in load order.
|
||
pub fn hud_shapes(&self) -> impl Iterator<Item = &Shape> {
|
||
self.entries
|
||
.iter()
|
||
.filter_map(|e| e.run.as_ref())
|
||
.flat_map(|r| &r.store.data().shapes)
|
||
}
|
||
/// The screen mod `i` last pushed with `ui.open-screen`, while it is up.
|
||
pub fn screen(&self, i: usize) -> Option<&UiScreen> {
|
||
self.entries
|
||
.get(i)?
|
||
.run
|
||
.as_ref()?
|
||
.store
|
||
.data()
|
||
.ui
|
||
.screen
|
||
.as_ref()
|
||
}
|
||
/// The widgets `ui.set-settings` pushed: mod `i`'s page in
|
||
/// Options > Mods. Empty while it has none.
|
||
pub fn settings_widgets(&self, i: usize) -> &[UiWidget] {
|
||
self.entries
|
||
.get(i)
|
||
.and_then(|e| e.run.as_ref())
|
||
.map_or(&[], |r| &r.store.data().ui.settings)
|
||
}
|
||
/// A `list` widget's row was picked on a surface of mod `i`.
|
||
pub fn ui_select(&mut self, i: usize, id: u32, row: u32) {
|
||
self.ui_event(i, |ui, s| {
|
||
ui.horizon_mods_ui_events().call_select(s, id, row)
|
||
});
|
||
}
|
||
/// The player left mod `i`'s screen (Esc or Done).
|
||
pub fn ui_closed(&mut self, i: usize) {
|
||
self.ui_event(i, |ui, s| ui.horizon_mods_ui_events().call_closed(s));
|
||
}
|
||
/// The player opened mod `i`'s settings page.
|
||
pub fn ui_settings_opened(&mut self, i: usize) {
|
||
self.ui_event(i, |ui, s| {
|
||
ui.horizon_mods_ui_events().call_settings_opened(s)
|
||
});
|
||
}
|
||
/// A `ui-events` call on mod `i`; no export, no call (mods built
|
||
/// before `ui` have none).
|
||
fn ui_event(
|
||
&mut self,
|
||
i: usize,
|
||
f: impl FnOnce(&UiHost, &mut Store<State>) -> wasmtime::Result<()>,
|
||
) {
|
||
let has_ui = self
|
||
.entries
|
||
.get(i)
|
||
.and_then(|e| e.run.as_ref())
|
||
.is_some_and(|r| r.ui.is_some());
|
||
if has_ui {
|
||
self.call(i, FUEL_EVENT, |run| {
|
||
f(run.ui.as_ref().expect("checked above"), &mut run.store)
|
||
});
|
||
}
|
||
}
|
||
/// What mods asked to show since the last call.
|
||
pub fn drain(&mut self) -> Vec<Output> {
|
||
std::mem::take(&mut self.out)
|
||
}
|
||
|
||
/// Restarts the mods whose file changed since they loaded (mod
|
||
/// development: rebuild, and the game picks it up). True when any did.
|
||
pub fn reload_changed(&mut self, reserved: impl Fn(&str) -> bool) -> bool {
|
||
let mut any = false;
|
||
for i in 0..self.entries.len() {
|
||
let entry = &self.entries[i];
|
||
let now = modified(&entry.path);
|
||
let was_on = !matches!(entry.status, Status::Off | Status::Elsewhere);
|
||
if now == entry.modified || !was_on {
|
||
continue;
|
||
}
|
||
any = true;
|
||
self.generation += 1;
|
||
self.entries[i].modified = now;
|
||
self.entries[i].run = None;
|
||
let path = self.entries[i].path.clone();
|
||
let started = Package::read(&path).and_then(|p| {
|
||
self.entries[i].manifest = Some(p.manifest.clone());
|
||
self.start(&path, &p, &reserved)
|
||
});
|
||
let entry = &mut self.entries[i];
|
||
let id = entry.manifest.as_ref().map_or("?", |m| m.id.as_str());
|
||
match started {
|
||
Ok(run) => {
|
||
log::info!("Horizon: mod {id} reloaded");
|
||
entry.run = run;
|
||
entry.status = Status::Running;
|
||
}
|
||
Err(e) => {
|
||
log::warn!("Horizon: mod {id} did not reload: {e}");
|
||
entry.status = Status::Failed(e);
|
||
}
|
||
}
|
||
}
|
||
any
|
||
}
|
||
}
|
||
|
||
/// A command's arguments are well formed: names given and distinct,
|
||
/// optional ones last, free text only last.
|
||
fn check_arguments(arguments: &[Argument]) -> Result<(), String> {
|
||
for (i, a) in arguments.iter().enumerate() {
|
||
if a.name.is_empty()
|
||
|| !a
|
||
.name
|
||
.chars()
|
||
.all(|c| c.is_ascii_alphanumeric() || c == '_')
|
||
{
|
||
return Err(format!("argument name '{}' isn't [A-Za-z0-9_]+", a.name));
|
||
}
|
||
if arguments[..i].iter().any(|b| b.name == a.name) {
|
||
return Err(format!("two arguments are named {}", a.name));
|
||
}
|
||
if i > 0 && arguments[i - 1].optional && !a.optional {
|
||
return Err(format!("{} is required after an optional argument", a.name));
|
||
}
|
||
if a.kind == ArgumentKind::Text && i + 1 < arguments.len() {
|
||
return Err(format!(
|
||
"{} takes the rest of the line, so it must be last",
|
||
a.name
|
||
));
|
||
}
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
fn modified(path: &Path) -> Option<SystemTime> {
|
||
let meta = std::fs::metadata(path).ok()?;
|
||
if meta.is_dir() {
|
||
// A folder mod changes when its component does.
|
||
return std::fs::metadata(path.join(crate::manifest::WASM))
|
||
.ok()?
|
||
.modified()
|
||
.ok();
|
||
}
|
||
meta.modified().ok()
|
||
}
|
||
|
||
/// A trap or error, as the player reads it.
|
||
fn reason(e: &wasmtime::Error) -> String {
|
||
match e.downcast_ref::<Trap>() {
|
||
Some(Trap::OutOfFuel) => "it took too long (an endless loop?)".into(),
|
||
Some(Trap::UnreachableCodeReached) => "it crashed (a panic)".into(),
|
||
Some(trap) => format!("it crashed: {trap}"),
|
||
None => format!("{e:#}"),
|
||
}
|
||
}
|
||
|
||
/// The models a mod set, limited: finite, normalised, at most [`MODELS`].
|
||
fn clean_models(models: impl Iterator<Item = HostModel>) -> Vec<HostModel> {
|
||
let finite = |v: f64| v.is_finite() && v.abs() < 30_000_000.0;
|
||
models
|
||
.filter(|m| finite(m.x) && finite(m.y) && finite(m.z))
|
||
.take(MODELS)
|
||
.map(|mut m| {
|
||
let (x, y, z, w) = m.rotation;
|
||
let len = (x * x + y * y + z * z + w * w).sqrt();
|
||
m.rotation = if len.is_finite() && len > 1e-6 {
|
||
(x / len, y / len, z / len, w / len)
|
||
} else {
|
||
(0.0, 0.0, 0.0, 1.0)
|
||
};
|
||
m.scale = if m.scale.is_finite() {
|
||
m.scale.clamp(0.0, MODEL_SCALE)
|
||
} else {
|
||
1.0
|
||
};
|
||
m
|
||
})
|
||
.collect()
|
||
}
|
||
fn clip(text: String) -> String {
|
||
clip_to(text, LINE_CHARS)
|
||
}
|
||
fn clip_to(text: String, chars: usize) -> String {
|
||
match text.char_indices().nth(chars) {
|
||
Some((at, _)) => text[..at].to_string(),
|
||
None => text,
|
||
}
|
||
}
|
||
|
||
/// Widgets on a `ui` screen or settings page, and rows on one `list`.
|
||
const WIDGETS: usize = 64;
|
||
const LIST_ROWS: usize = 512;
|
||
|
||
fn clip_widgets(widgets: Vec<UiWidget>) -> Vec<UiWidget> {
|
||
widgets
|
||
.into_iter()
|
||
.take(WIDGETS)
|
||
.map(|w| match w {
|
||
UiWidget::Text(mut t) => {
|
||
t.text = clip(t.text);
|
||
UiWidget::Text(t)
|
||
}
|
||
UiWidget::Button(mut b) => {
|
||
b.label = clip(b.label);
|
||
UiWidget::Button(b)
|
||
}
|
||
UiWidget::Item(mut i) => {
|
||
i.item = clip(i.item);
|
||
i.name = clip(i.name);
|
||
UiWidget::Item(i)
|
||
}
|
||
UiWidget::List(mut l) => {
|
||
l.rows = l.rows.into_iter().take(LIST_ROWS).map(clip).collect();
|
||
l.selected = l.selected.filter(|&s| (s as usize) < l.rows.len());
|
||
UiWidget::List(l)
|
||
}
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
impl mod_log::Host for State {
|
||
fn write(&mut self, level: mod_log::Level, message: String) {
|
||
let level = match level {
|
||
mod_log::Level::Debug => log::Level::Debug,
|
||
mod_log::Level::Info => log::Level::Info,
|
||
mod_log::Level::Warn => log::Level::Warn,
|
||
mod_log::Level::Error => log::Level::Error,
|
||
};
|
||
log::log!(level, "[mod {}] {}", self.id, clip(message));
|
||
}
|
||
}
|
||
impl game::Host for State {
|
||
fn get_player(&mut self) -> Option<Player> {
|
||
self.snapshot.player.clone()
|
||
}
|
||
fn get_clock(&mut self) -> Option<Clock> {
|
||
self.snapshot.clock
|
||
}
|
||
fn world_id(&mut self) -> Option<String> {
|
||
self.snapshot.world.clone()
|
||
}
|
||
fn raycast(&mut self, distance: f32) -> Option<Hit> {
|
||
let (at, hit) = self.snapshot.view_hit.as_ref()?;
|
||
// NaN compares false: no hit.
|
||
(*at <= distance.min(RAYCAST_MAX) && !distance.is_nan()).then(|| hit.clone())
|
||
}
|
||
}
|
||
impl browser::Host for State {
|
||
fn set_items(&mut self, items: Vec<BrowserStack>) {
|
||
self.browser.items = items
|
||
.into_iter()
|
||
.take(BROWSER_ITEMS)
|
||
.map(|s| BrowserStack {
|
||
item: clip(s.item),
|
||
components: clip_to(s.components, 4096),
|
||
..s
|
||
})
|
||
.collect();
|
||
self.browser.version = BROWSER_VERSION.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||
}
|
||
fn set_recipes(
|
||
&mut self,
|
||
title: String,
|
||
tabs: Vec<BrowserStack>,
|
||
tab: u32,
|
||
recipes: Vec<BrowserRecipe>,
|
||
) {
|
||
let stack = |s: BrowserStack| BrowserStack {
|
||
item: clip(s.item),
|
||
components: clip_to(s.components, 4096),
|
||
..s
|
||
};
|
||
let cycle = |list: Vec<BrowserStack>| -> Vec<BrowserStack> {
|
||
list.into_iter().take(SLOT_STACKS).map(stack).collect()
|
||
};
|
||
self.browser.recipes = (!recipes.is_empty()).then(|| {
|
||
let recipes = recipes
|
||
.into_iter()
|
||
.take(BROWSER_RECIPES)
|
||
.map(|r| BrowserRecipe {
|
||
width: r.width.clamp(1, 3),
|
||
height: r.height.clamp(1, 3),
|
||
slots: r.slots.into_iter().take(RECIPE_SLOTS).map(cycle).collect(),
|
||
results: cycle(r.results),
|
||
note: clip(r.note),
|
||
..r
|
||
})
|
||
.collect();
|
||
RecipePage {
|
||
title: clip(title),
|
||
tabs: tabs.into_iter().take(RECIPE_TABS).map(stack).collect(),
|
||
tab,
|
||
recipes,
|
||
}
|
||
});
|
||
self.browser.version = BROWSER_VERSION.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||
}
|
||
fn poll(&mut self) -> Vec<BrowserEvent> {
|
||
self.browser.events.drain(..).collect()
|
||
}
|
||
}
|
||
impl recipes::Host for State {
|
||
fn items(&mut self) -> Vec<RecipeItem> {
|
||
self.snapshot
|
||
.recipes
|
||
.as_ref()
|
||
.map_or_else(Vec::new, |r| r.items.clone())
|
||
}
|
||
fn all(&mut self) -> Vec<Recipe> {
|
||
self.snapshot
|
||
.recipes
|
||
.as_ref()
|
||
.map_or_else(Vec::new, |r| r.recipes.clone())
|
||
}
|
||
fn known(&mut self) -> Vec<i32> {
|
||
self.snapshot.known_recipes.to_vec()
|
||
}
|
||
fn place(&mut self, book_id: i32, all: bool) -> Result<(), String> {
|
||
self.recipe_action()?;
|
||
if !self.snapshot.placing {
|
||
return Err("no screen that takes recipes is open".into());
|
||
}
|
||
if !self.snapshot.known_recipes.contains(&book_id) {
|
||
return Err(format!(
|
||
"recipe {book_id} is not in the player's recipe book"
|
||
));
|
||
}
|
||
self.out.push(Output::PlaceRecipe { book_id, all });
|
||
Ok(())
|
||
}
|
||
fn give(&mut self, stack: RecipeStack) -> Result<(), String> {
|
||
self.recipe_action()?;
|
||
if !self.snapshot.creative {
|
||
return Err("only in creative mode".into());
|
||
}
|
||
let item = self
|
||
.snapshot
|
||
.recipes
|
||
.as_ref()
|
||
.and_then(|r| r.items.get(stack.item as usize))
|
||
.ok_or_else(|| format!("no item {}", stack.item))?
|
||
.id
|
||
.clone();
|
||
self.out.push(Output::Give {
|
||
item,
|
||
count: stack.count.clamp(1, 99),
|
||
components: clip_to(stack.components, 4096),
|
||
});
|
||
Ok(())
|
||
}
|
||
}
|
||
impl State {
|
||
/// `recipes.place` and `give` take at most [`RECIPE_ACTIONS`] a call.
|
||
fn recipe_action(&self) -> Result<(), String> {
|
||
let done = self
|
||
.out
|
||
.iter()
|
||
.filter(|o| matches!(o, Output::PlaceRecipe { .. } | Output::Give { .. }))
|
||
.count();
|
||
if done < RECIPE_ACTIONS {
|
||
Ok(())
|
||
} else {
|
||
Err(format!("at most {RECIPE_ACTIONS} places and gives a call"))
|
||
}
|
||
}
|
||
}
|
||
impl State {
|
||
/// Queues a chat line unless the call already sent [`CHAT_PER_CALL`].
|
||
fn say(&mut self, line: impl FnOnce(String) -> Output) -> bool {
|
||
let shown = self
|
||
.out
|
||
.iter()
|
||
.filter(|o| {
|
||
matches!(
|
||
o,
|
||
Output::Chat { .. } | Output::Tell { .. } | Output::Broadcast { .. }
|
||
)
|
||
})
|
||
.count();
|
||
if shown < CHAT_PER_CALL {
|
||
let name = self.name.clone();
|
||
self.out.push(line(name));
|
||
}
|
||
shown < CHAT_PER_CALL
|
||
}
|
||
}
|
||
impl chat::Host for State {
|
||
fn show(&mut self, text: String) {
|
||
self.say(|name| Output::Chat {
|
||
name,
|
||
text: clip(text),
|
||
});
|
||
}
|
||
}
|
||
impl mod_world::Host for State {
|
||
fn get_block(&mut self, dimension: String, x: i32, y: i32, z: i32) -> Option<String> {
|
||
let view = self.world.lock().ok()?;
|
||
view.as_ref()?.block(&dimension, x, y, z)
|
||
}
|
||
fn get_biome(&mut self, dimension: String, x: i32, y: i32, z: i32) -> Option<String> {
|
||
let view = self.world.lock().ok()?;
|
||
view.as_ref()?.biome(&dimension, x, y, z)
|
||
}
|
||
fn set_blocks(&mut self, dimension: String, blocks: Vec<BlockChange>) -> Result<(), String> {
|
||
if blocks.len() > BLOCKS_PER_CALL {
|
||
return Err(format!(
|
||
"{} blocks: at most {BLOCKS_PER_CALL} per call",
|
||
blocks.len()
|
||
));
|
||
}
|
||
if let Some(view) = self.world.lock().ok().as_ref().and_then(|v| v.as_ref()) {
|
||
if !view.has_dimension(&dimension) {
|
||
return Err(format!("no dimension {dimension}"));
|
||
}
|
||
for b in &blocks {
|
||
view.check_state(&b.state)?;
|
||
}
|
||
}
|
||
if !blocks.is_empty() {
|
||
self.out.push(Output::SetBlocks {
|
||
name: self.name.clone(),
|
||
dimension,
|
||
blocks,
|
||
});
|
||
}
|
||
Ok(())
|
||
}
|
||
}
|
||
impl players::Host for State {
|
||
fn online(&mut self) -> Vec<ServerPlayer> {
|
||
self.snapshot.players.clone()
|
||
}
|
||
fn tell(&mut self, player: String, text: String) -> bool {
|
||
self.snapshot.players.iter().any(|p| p.id == player)
|
||
&& self.say(|name| Output::Tell {
|
||
name,
|
||
player,
|
||
text: clip(text),
|
||
})
|
||
}
|
||
fn broadcast(&mut self, text: String) {
|
||
self.say(|name| Output::Broadcast {
|
||
name,
|
||
text: clip(text),
|
||
});
|
||
}
|
||
}
|
||
/// A key a mod registered (capability `input`).
|
||
#[derive(Clone, Debug, PartialEq)]
|
||
pub struct ModKey {
|
||
/// The mod's own name for it, echoed in `key-down`.
|
||
pub name: String,
|
||
/// What it does, for Controls.
|
||
pub label: String,
|
||
/// `key.keyboard.r`.
|
||
pub key: String,
|
||
}
|
||
|
||
/// What capability `input` holds for one mod.
|
||
#[derive(Default)]
|
||
struct InputState {
|
||
claimed: Vec<String>,
|
||
keys: Vec<ModKey>,
|
||
events: std::collections::VecDeque<InputEvent>,
|
||
/// The mod's keys held now, by name.
|
||
down: Vec<String>,
|
||
/// It holds the mouse wheel.
|
||
wheel: bool,
|
||
/// The keys the player chose, `name → key`: they win over
|
||
/// `register-key`'s.
|
||
bindings: Vec<(String, String)>,
|
||
}
|
||
/// Events kept for `poll`, items claimed and keys, per mod.
|
||
const INPUT_EVENTS: usize = 256;
|
||
const CLAIMS: usize = 64;
|
||
const KEYS: usize = 16;
|
||
|
||
/// `key.keyboard.<name>` or `key.mouse.<name>`, as options.txt writes keys;
|
||
/// the game knows which names exist and ignores a key it has none for.
|
||
fn key_ok(key: &str) -> bool {
|
||
let rest = key
|
||
.strip_prefix("key.keyboard.")
|
||
.or_else(|| key.strip_prefix("key.mouse."));
|
||
rest.is_some_and(|r| {
|
||
(1..=32).contains(&r.len())
|
||
&& r.bytes()
|
||
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'.')
|
||
})
|
||
}
|
||
|
||
impl InputState {
|
||
/// Key `name` is `key` now; held, it lets go first.
|
||
fn rebind(&mut self, name: &str, key: String) {
|
||
let Some(k) = self.keys.iter_mut().find(|k| k.name == name) else {
|
||
return;
|
||
};
|
||
k.key = key;
|
||
if let Some(i) = self.down.iter().position(|n| n == name) {
|
||
let name = self.down.swap_remove(i);
|
||
self.push(InputEvent::KeyUp(name));
|
||
}
|
||
}
|
||
fn push(&mut self, event: InputEvent) {
|
||
if self.events.len() == INPUT_EVENTS {
|
||
self.events.pop_front();
|
||
}
|
||
self.events.push_back(event);
|
||
}
|
||
}
|
||
|
||
impl input::Host for State {
|
||
fn claim_items(&mut self, ids: Vec<String>) {
|
||
self.input.claimed = ids.into_iter().take(CLAIMS).map(clip).collect();
|
||
}
|
||
fn register_key(&mut self, name: String, label: String, key: String) -> Result<(), String> {
|
||
if !key_ok(&key) {
|
||
return Err(format!(
|
||
"{key:?} is not a key as options.txt writes them (key.keyboard.r)"
|
||
));
|
||
}
|
||
let (name, label) = (clip(name), clip(label));
|
||
let key = match self.input.bindings.iter().find(|(n, _)| *n == name) {
|
||
Some((_, chosen)) => chosen.clone(),
|
||
None => key,
|
||
};
|
||
if let Some(k) = self.input.keys.iter_mut().find(|k| k.name == name) {
|
||
(k.label, k.key) = (label, key);
|
||
return Ok(());
|
||
}
|
||
if self.input.keys.len() == KEYS {
|
||
return Err(format!("a mod may register {KEYS} keys"));
|
||
}
|
||
self.input.keys.push(ModKey { name, label, key });
|
||
Ok(())
|
||
}
|
||
fn held(&mut self) -> Option<HeldItem> {
|
||
self.snapshot.held.clone()
|
||
}
|
||
fn poll(&mut self) -> Vec<InputEvent> {
|
||
self.input.events.drain(..).collect()
|
||
}
|
||
fn mapping(&mut self, name: String) -> Option<input::MappingState> {
|
||
let (_, label, down) = self.snapshot.mappings.iter().find(|m| m.0 == name)?;
|
||
Some(input::MappingState {
|
||
label: label.clone(),
|
||
down: *down,
|
||
})
|
||
}
|
||
fn clicks_per_second(&mut self) -> (u32, u32) {
|
||
self.snapshot.cps
|
||
}
|
||
fn claim_wheel(&mut self, on: bool) {
|
||
self.input.wheel = on;
|
||
}
|
||
}
|
||
|
||
/// HUD shapes one mod may keep (capability `render`).
|
||
const SHAPES: usize = 1024;
|
||
/// The longest jolt `render.shake` makes, in seconds.
|
||
const SHAKE_SECONDS: f32 = 10.0;
|
||
/// `render.set-zoom`'s limits: `Camera.tickFov` keeps the modifier at 0.1
|
||
/// or more, and turning never stops.
|
||
const ZOOM_MAX: f32 = 10.0;
|
||
const TURN_MIN: f32 = 0.05;
|
||
/// `set-minimap`'s side in GUI pixels and its blocks per map pixel.
|
||
const MINIMAP_SIZE: (f32, f32) = (16.0, 256.0);
|
||
const MINIMAP_SCALE: (f32, f32) = (0.5, 4.0);
|
||
/// `set-far-terrain`'s distance in chunks, as the LOD Distance setting's.
|
||
const FAR_TERRAIN_DISTANCE: (u32, u32) = (64, 1024);
|
||
/// `set-models`' most models a mod keeps, and their largest scale.
|
||
const MODELS: usize = 4096;
|
||
const MODEL_SCALE: f32 = 64.0;
|
||
/// `spawn-particles`' most spawns a call and particles a spawn.
|
||
const PARTICLE_SPAWNS: usize = 512;
|
||
const PARTICLES_PER_SPAWN: u32 = 256;
|
||
|
||
/// A mod's corner panel: shapes in a `width` × `height` box the game
|
||
/// places in `corner`, stacked with the other overlays.
|
||
#[derive(Clone, Debug)]
|
||
pub struct CornerPanel {
|
||
pub corner: RenderCorner,
|
||
pub width: f32,
|
||
pub height: f32,
|
||
pub shapes: Vec<Shape>,
|
||
}
|
||
|
||
fn clip_shapes(shapes: Vec<Shape>) -> Vec<Shape> {
|
||
shapes
|
||
.into_iter()
|
||
.take(SHAPES)
|
||
.map(|shape| match shape {
|
||
Shape::Sprite(mut s) => {
|
||
s.sprite = clip(s.sprite);
|
||
Shape::Sprite(s)
|
||
}
|
||
Shape::Item(mut i) => {
|
||
i.item = clip(i.item);
|
||
i.scale = if i.scale.is_finite() {
|
||
i.scale.clamp(0.0, 16.0)
|
||
} else {
|
||
1.0
|
||
};
|
||
Shape::Item(i)
|
||
}
|
||
Shape::Text(mut t) => {
|
||
t.text = clip(t.text);
|
||
t.color &= 0xFF_FFFF;
|
||
Shape::Text(t)
|
||
}
|
||
other => other,
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
impl render::Host for State {
|
||
fn set_hud(&mut self, shapes: Vec<Shape>) {
|
||
self.shapes = clip_shapes(shapes);
|
||
}
|
||
fn set_corner(&mut self, corner: RenderCorner, width: f32, height: f32, shapes: Vec<Shape>) {
|
||
let size = |v: f32| {
|
||
if v.is_finite() {
|
||
v.clamp(0.0, 1024.0)
|
||
} else {
|
||
0.0
|
||
}
|
||
};
|
||
self.corner = Some(CornerPanel {
|
||
corner,
|
||
width: size(width),
|
||
height: size(height),
|
||
shapes: clip_shapes(shapes),
|
||
});
|
||
}
|
||
fn clear_corner(&mut self) {
|
||
self.corner = None;
|
||
}
|
||
fn text_width(&mut self, text: String) -> f32 {
|
||
let widths = &self.snapshot.font_widths;
|
||
text.chars()
|
||
.map(|c| widths.get(c as usize).copied().unwrap_or(6.0))
|
||
.sum::<f32>()
|
||
.ceil()
|
||
}
|
||
fn set_zoom(&mut self, zoom: ModZoom) {
|
||
let finite = |v: f32, lo: f32, hi: f32| if v.is_finite() { v.clamp(lo, hi) } else { lo };
|
||
let factor = finite(zoom.factor, 1.0, ZOOM_MAX);
|
||
self.zoom = (factor > 1.0).then(|| ModZoom {
|
||
factor,
|
||
smooth: zoom.smooth,
|
||
turn: if zoom.turn.is_finite() {
|
||
zoom.turn.clamp(TURN_MIN, 1.0)
|
||
} else {
|
||
1.0
|
||
},
|
||
});
|
||
}
|
||
fn set_minimap(&mut self, minimap: Option<ModMinimap>) {
|
||
let finite = |v: f32, lo: f32, hi: f32| if v.is_finite() { v.clamp(lo, hi) } else { lo };
|
||
self.minimap = minimap.map(|m| ModMinimap {
|
||
size: finite(m.size, MINIMAP_SIZE.0, MINIMAP_SIZE.1),
|
||
blocks_per_pixel: finite(m.blocks_per_pixel, MINIMAP_SCALE.0, MINIMAP_SCALE.1),
|
||
..m
|
||
});
|
||
}
|
||
fn set_far_terrain(&mut self, far_terrain: Option<ModFarTerrain>) {
|
||
self.far_terrain = far_terrain.map(|f| ModFarTerrain {
|
||
distance: f
|
||
.distance
|
||
.clamp(FAR_TERRAIN_DISTANCE.0, FAR_TERRAIN_DISTANCE.1),
|
||
..f
|
||
});
|
||
}
|
||
fn frame_stats(&mut self) -> FrameRate {
|
||
let (fps, min, low) = self.snapshot.frame;
|
||
FrameRate { fps, min, low }
|
||
}
|
||
fn gui_size(&mut self) -> (f32, f32) {
|
||
self.snapshot.gui_size
|
||
}
|
||
fn shake(&mut self, strength: f32, seconds: f32) {
|
||
let ok = |v: f32, max: f32| {
|
||
if v.is_finite() {
|
||
v.clamp(0.0, max)
|
||
} else {
|
||
0.0
|
||
}
|
||
};
|
||
let (strength, seconds) = (ok(strength, 1.0), ok(seconds, SHAKE_SECONDS));
|
||
if strength > 0.0 && seconds > 0.0 {
|
||
self.out.push(Output::Shake { strength, seconds });
|
||
}
|
||
}
|
||
fn set_models(&mut self, models: Vec<ModelInstance>) {
|
||
let models = models.into_iter().map(|m| HostModel {
|
||
id: m.id,
|
||
model: ModelRef::Name(clip(m.model)),
|
||
x: m.x,
|
||
y: m.y,
|
||
z: m.z,
|
||
rotation: m.rotation,
|
||
scale: m.scale,
|
||
glow: m.glow,
|
||
});
|
||
self.models = clean_models(models);
|
||
}
|
||
fn model_id(&mut self, model: String) -> Option<u32> {
|
||
let t = self.model_table.lock().ok()?;
|
||
(t.resolve.as_ref()?)(&model)
|
||
}
|
||
fn model_generation(&mut self) -> u32 {
|
||
self.model_table.lock().map_or(0, |t| t.generation)
|
||
}
|
||
fn set_models_by_id(&mut self, generation: u32, models: Vec<ModelInstanceId>) -> bool {
|
||
if self
|
||
.model_table
|
||
.lock()
|
||
.map_or(true, |t| t.generation != generation)
|
||
{
|
||
return false;
|
||
}
|
||
let models = models.into_iter().map(|m| HostModel {
|
||
id: m.id,
|
||
model: ModelRef::Handle(m.model),
|
||
x: m.x,
|
||
y: m.y,
|
||
z: m.z,
|
||
rotation: m.rotation,
|
||
scale: m.scale,
|
||
glow: m.glow,
|
||
});
|
||
self.models = clean_models(models);
|
||
true
|
||
}
|
||
fn spawn_particles(&mut self, particles: Vec<ParticleSpawn>) {
|
||
let particles: Vec<ParticleSpawn> = particles
|
||
.into_iter()
|
||
.filter(|p| p.x.is_finite() && p.y.is_finite() && p.z.is_finite())
|
||
.take(PARTICLE_SPAWNS)
|
||
.map(|mut p| {
|
||
p.count = p.count.clamp(1, PARTICLES_PER_SPAWN);
|
||
p.particle = clip(p.particle);
|
||
p
|
||
})
|
||
.collect();
|
||
if !particles.is_empty() {
|
||
self.out.push(Output::Particles { particles });
|
||
}
|
||
}
|
||
fn set_post(&mut self, wgsl: String) {
|
||
static VERSION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||
let v = VERSION.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||
self.post = Some((v, clip_to(wgsl, 256 * 1024)));
|
||
}
|
||
fn clear_post(&mut self) {
|
||
self.post = None;
|
||
}
|
||
fn set_params(&mut self, params: Vec<f32>) {
|
||
self.post_params = params
|
||
.into_iter()
|
||
.take(1024)
|
||
.map(|v| if v.is_finite() { v } else { 0.0 })
|
||
.collect();
|
||
}
|
||
fn set_views(&mut self, views: Vec<CameraView>) {
|
||
let finite = |v: f64| v.is_finite() && v.abs() < 30_000_000.0;
|
||
let angle = |v: f32| if v.is_finite() { v } else { 0.0 };
|
||
self.views = views
|
||
.into_iter()
|
||
.filter(|v| finite(v.x) && finite(v.y) && finite(v.z))
|
||
.take(8)
|
||
.map(|mut v| {
|
||
v.yaw = angle(v.yaw);
|
||
v.pitch = angle(v.pitch).clamp(-90.0, 90.0);
|
||
v.fov = if v.fov.is_finite() {
|
||
v.fov.clamp(1.0, 110.0)
|
||
} else {
|
||
70.0
|
||
};
|
||
v.width = v.width.clamp(16, 3840);
|
||
v.height = v.height.clamp(16, 2160);
|
||
v
|
||
})
|
||
.collect();
|
||
}
|
||
fn set_main_view(&mut self, view: Option<u32>) {
|
||
self.main_view = view;
|
||
}
|
||
fn set_lights(&mut self, lights: Vec<PointLight>) {
|
||
let finite = |v: f64| v.is_finite() && v.abs() < 30_000_000.0;
|
||
let unit = |v: f32| {
|
||
if v.is_finite() {
|
||
v.clamp(0.0, 1.0)
|
||
} else {
|
||
0.0
|
||
}
|
||
};
|
||
self.lights = lights
|
||
.into_iter()
|
||
.filter(|l| finite(l.x) && finite(l.y) && finite(l.z))
|
||
.take(512)
|
||
.map(|mut l| {
|
||
l.color = (unit(l.color.0), unit(l.color.1), unit(l.color.2));
|
||
l.intensity = if l.intensity.is_finite() {
|
||
l.intensity.clamp(0.0, 100_000.0)
|
||
} else {
|
||
0.0
|
||
};
|
||
l.radius = if l.radius.is_finite() {
|
||
l.radius.clamp(1.0, 256.0)
|
||
} else {
|
||
1.0
|
||
};
|
||
l
|
||
})
|
||
.collect();
|
||
}
|
||
fn set_spot_lights(&mut self, lights: Vec<SpotLight>) -> bool {
|
||
let finite = |v: f64| v.is_finite() && v.abs() < 30_000_000.0;
|
||
let num = |v: f32, lo: f32, hi: f32, default: f32| {
|
||
if v.is_finite() {
|
||
v.clamp(lo, hi)
|
||
} else {
|
||
default
|
||
}
|
||
};
|
||
self.spots = lights
|
||
.into_iter()
|
||
.filter(|l| {
|
||
finite(l.x)
|
||
&& finite(l.y)
|
||
&& finite(l.z)
|
||
&& [l.dx, l.dy, l.dz].into_iter().all(f32::is_finite)
|
||
&& (l.dx * l.dx + l.dy * l.dy + l.dz * l.dz) > 1e-12
|
||
})
|
||
.take(32)
|
||
.map(|mut l| {
|
||
let len = (l.dx * l.dx + l.dy * l.dy + l.dz * l.dz).sqrt();
|
||
(l.dx, l.dy, l.dz) = (l.dx / len, l.dy / len, l.dz / len);
|
||
l.color = (
|
||
num(l.color.0, 0.0, 1.0, 0.0),
|
||
num(l.color.1, 0.0, 1.0, 0.0),
|
||
num(l.color.2, 0.0, 1.0, 0.0),
|
||
);
|
||
l.intensity = num(l.intensity, 0.0, 100_000.0, 0.0);
|
||
l.range = num(l.range, 1.0, 1024.0, 1.0);
|
||
l.inner_angle = num(l.inner_angle, 0.005, 1.2, 0.05);
|
||
l.outer_angle = num(
|
||
l.outer_angle,
|
||
l.inner_angle + 0.002,
|
||
1.4,
|
||
l.inner_angle + 0.05,
|
||
);
|
||
l.beam = num(l.beam, 0.0, 1.0, 0.0);
|
||
l
|
||
})
|
||
.collect();
|
||
self.model_table.lock().is_ok_and(|t| t.spot_active)
|
||
}
|
||
fn capture_start(&mut self, mut options: CaptureOptions) -> Result<(), String> {
|
||
let folder_ok = |f: &str| {
|
||
!f.is_empty()
|
||
&& f.len() <= 120
|
||
&& !f.starts_with('/')
|
||
&& !f.ends_with('/')
|
||
&& f.split('/').all(|part| {
|
||
!part.is_empty()
|
||
&& part != "."
|
||
&& part != ".."
|
||
&& part
|
||
.chars()
|
||
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
|
||
})
|
||
};
|
||
let name_ok = |n: &str| {
|
||
!n.is_empty()
|
||
&& n.len() <= 80
|
||
&& !n.starts_with('.')
|
||
&& n.chars()
|
||
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
|
||
};
|
||
if !folder_ok(&options.folder) {
|
||
return Err("capture folder: letters, digits, - _ and / under the game's home".into());
|
||
}
|
||
if !name_ok(&options.name) {
|
||
return Err("capture name: letters, digits, - _ and . (no leading dot)".into());
|
||
}
|
||
if (options.width == 0) != (options.height == 0)
|
||
|| options.width > 7680
|
||
|| options.height > 4320
|
||
{
|
||
return Err("capture size: both 0 (the window's) or both up to 7680 x 4320".into());
|
||
}
|
||
if options.width != 0 && (options.width < 16 || options.height < 16) {
|
||
return Err("capture size: at least 16 x 16".into());
|
||
}
|
||
// H.264 in 4:2:0 needs even sides.
|
||
options.width &= !1;
|
||
options.height &= !1;
|
||
options.fps = options.fps.clamp(1, 120);
|
||
options.crf = options.crf.min(51);
|
||
options.warmup = options.warmup.min(32);
|
||
let Ok(mut t) = self.model_table.lock() else {
|
||
return Err("the game is busy".into());
|
||
};
|
||
let running = t.capture_request.is_some()
|
||
|| t.capture_state.as_ref().is_some_and(|s| {
|
||
matches!(
|
||
s.phase,
|
||
CapturePhase::Arming | CapturePhase::Recording | CapturePhase::Encoding
|
||
)
|
||
});
|
||
if running {
|
||
return Err("a capture is already running".into());
|
||
}
|
||
t.capture_request = Some(options);
|
||
// Until the game answers, the request is the state.
|
||
t.capture_state = Some(CaptureState {
|
||
phase: CapturePhase::Arming,
|
||
frames: 0,
|
||
width: 0,
|
||
height: 0,
|
||
file: String::new(),
|
||
message: String::new(),
|
||
});
|
||
Ok(())
|
||
}
|
||
fn capture_stop(&mut self, cancel: bool) {
|
||
if let Ok(mut t) = self.model_table.lock() {
|
||
// A request the game has not seen is simply withdrawn.
|
||
if t.capture_request.take().is_some() {
|
||
t.capture_state = Some(CaptureState {
|
||
phase: CapturePhase::Failed,
|
||
frames: 0,
|
||
width: 0,
|
||
height: 0,
|
||
file: String::new(),
|
||
message: "cancelled".into(),
|
||
});
|
||
} else {
|
||
t.capture_stop = Some(cancel || t.capture_stop == Some(true));
|
||
}
|
||
}
|
||
}
|
||
fn capture_status(&mut self) -> CaptureState {
|
||
self.model_table
|
||
.lock()
|
||
.ok()
|
||
.and_then(|t| t.capture_state.clone())
|
||
.unwrap_or(CaptureState {
|
||
phase: CapturePhase::Idle,
|
||
frames: 0,
|
||
width: 0,
|
||
height: 0,
|
||
file: String::new(),
|
||
message: String::new(),
|
||
})
|
||
}
|
||
fn world_log_start(&mut self) -> u32 {
|
||
let Ok(mut t) = self.model_table.lock() else {
|
||
return 0;
|
||
};
|
||
*t.world_log.get_or_insert_with(|| {
|
||
WORLD_LOG_IDS.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
|
||
})
|
||
}
|
||
fn world_log_stop(&mut self, id: u32) {
|
||
if let Ok(mut t) = self.model_table.lock()
|
||
&& t.world_log == Some(id)
|
||
{
|
||
t.world_log = None;
|
||
t.time_view = None;
|
||
}
|
||
}
|
||
fn world_log_range(&mut self, id: u32) -> Option<(u64, u64)> {
|
||
let t = self.model_table.lock().ok()?;
|
||
t.world_log_state
|
||
.filter(|s| s.0 == id && t.world_log == Some(id))
|
||
.map(|s| (s.1, s.2))
|
||
}
|
||
fn set_world_time_view(&mut self, view: Option<(u32, u64)>) {
|
||
if let Ok(mut t) = self.model_table.lock() {
|
||
t.time_view = view.filter(|v| t.world_log == Some(v.0));
|
||
}
|
||
}
|
||
fn set_film_quality(&mut self, on: bool) {
|
||
if let Ok(mut t) = self.model_table.lock() {
|
||
t.film_quality = on;
|
||
}
|
||
}
|
||
fn set_lighting(&mut self, mut lighting: ModLighting) {
|
||
lighting.exposure = if lighting.exposure.is_finite() {
|
||
lighting.exposure.clamp(0.05, 8.0)
|
||
} else {
|
||
1.0
|
||
};
|
||
lighting.bloom = if lighting.bloom.is_finite() {
|
||
lighting.bloom.clamp(0.0, 1.0)
|
||
} else {
|
||
0.0
|
||
};
|
||
self.lighting = Some(lighting);
|
||
}
|
||
fn set_smoke(&mut self, clock: f64, segments: Vec<SmokeSegment>) -> bool {
|
||
let finite = |v: f64| v.is_finite() && v.abs() < 30_000_000.0;
|
||
let num = |v: f32, lo: f32, hi: f32, default: f32| {
|
||
if v.is_finite() {
|
||
v.clamp(lo, hi)
|
||
} else {
|
||
default
|
||
}
|
||
};
|
||
let clock = if clock.is_finite() { clock } else { 0.0 };
|
||
self.smoke_clock = (self.smoke_clock.1, clock);
|
||
self.smoke = segments
|
||
.into_iter()
|
||
.filter(|s| {
|
||
[s.ax, s.ay, s.az, s.bx, s.by, s.bz].into_iter().all(finite) && s.born.is_finite()
|
||
})
|
||
.take(4096)
|
||
.map(|mut s| {
|
||
s.life = num(s.life, 1.0, 72_000.0, 1.0);
|
||
s.radius_start = num(s.radius_start, 0.0, 64.0, 1.0);
|
||
s.radius_end = num(s.radius_end, 0.0, 64.0, 1.0);
|
||
s.density = num(s.density, 0.0, 8.0, 0.0);
|
||
s.heat = num(s.heat, 0.0, 1.0, 0.0);
|
||
s.soot = num(s.soot, 0.0, 1.0, 0.5);
|
||
s.rise = num(s.rise, -64.0, 64.0, 0.0);
|
||
s.clear = num(s.clear, 0.0, 64.0, 0.0);
|
||
s
|
||
})
|
||
.collect();
|
||
self.model_table.lock().is_ok_and(|t| t.smoke_active)
|
||
}
|
||
fn set_time_override(&mut self, day_time: Option<u64>) {
|
||
self.time_override = day_time.map(|t| t.min(1 << 40));
|
||
}
|
||
fn query_ground(&mut self, columns: Vec<(i32, i32)>) {
|
||
let room = 512usize.saturating_sub(self.ground_queries.len());
|
||
self.ground_queries.extend(columns.into_iter().take(room));
|
||
}
|
||
fn load_chunks(&mut self, chunks: Vec<(i32, i32)>) {
|
||
let room = 64usize.saturating_sub(self.chunk_requests.len());
|
||
self.chunk_requests.extend(chunks.into_iter().take(room));
|
||
}
|
||
fn ground(&mut self) -> Vec<(i32, i32, i32)> {
|
||
self.ground.clone()
|
||
}
|
||
fn query_rays(&mut self, rays: Vec<WorldRay>) {
|
||
let room = RAYS_PER_TICK.saturating_sub(self.ray_queries.len());
|
||
let mut over = rays.into_iter();
|
||
self.ray_queries.extend(over.by_ref().take(room));
|
||
// Over the budget: unknown, never clear.
|
||
self.ray_over.extend(over.take(RAYS_PER_TICK).map(|r| r.id));
|
||
self.world_seen = true;
|
||
}
|
||
fn rays(&mut self) -> Vec<WorldRayAnswer> {
|
||
self.rays.clone()
|
||
}
|
||
fn query_sections(&mut self, policy: WorldPolicy, sections: Vec<(i32, i32, i32)>) {
|
||
self.world_seen = true;
|
||
let room = SECTIONS_PER_TICK.saturating_sub(self.sections_asked);
|
||
let sections: Vec<_> = sections.into_iter().take(room).collect();
|
||
self.sections_asked += sections.len();
|
||
if !sections.is_empty() {
|
||
self.section_queries.push((policy, sections));
|
||
}
|
||
}
|
||
fn sections(&mut self) -> Vec<WorldSection> {
|
||
self.sections.clone()
|
||
}
|
||
fn world_changes(&mut self) -> WorldChanges {
|
||
self.world_seen = true;
|
||
self.world_changes.clone().unwrap_or(WorldChanges {
|
||
epoch: 0,
|
||
revision: 0,
|
||
overflow: false,
|
||
sections: Vec::new(),
|
||
})
|
||
}
|
||
fn acoustics(&mut self) -> bool {
|
||
self.model_table.lock().is_ok_and(|t| t.acoustics)
|
||
}
|
||
fn sound_source_generation(&mut self) -> u32 {
|
||
self.model_table.lock().map_or(0, |t| t.source_generation)
|
||
}
|
||
fn sound_sources(&mut self, generation: u32, ops: Vec<SourceOp>) -> bool {
|
||
if self
|
||
.model_table
|
||
.lock()
|
||
.map_or(true, |t| t.source_generation != generation)
|
||
{
|
||
return false;
|
||
}
|
||
use crate::sources::{OPS_PER_CALL, SourceKind, SourceParams};
|
||
for (i, o) in ops.into_iter().enumerate() {
|
||
let kind = match o.kind {
|
||
SourceOpKind::Start => SourceKind::Start,
|
||
SourceOpKind::Update => SourceKind::Update,
|
||
SourceOpKind::Stop => SourceKind::Stop,
|
||
};
|
||
// Past the call's count only stops are read: a limit never loses one.
|
||
if i >= OPS_PER_CALL && kind != SourceKind::Stop {
|
||
continue;
|
||
}
|
||
let params = (kind != SourceKind::Stop)
|
||
.then(|| {
|
||
SourceParams::new(
|
||
&o.event,
|
||
[o.x, o.y, o.z],
|
||
[o.vx, o.vy, o.vz],
|
||
o.gain,
|
||
o.pitch,
|
||
o.looping,
|
||
o.priority,
|
||
o.attack,
|
||
o.release,
|
||
o.doppler,
|
||
o.loop_from,
|
||
o.loop_to,
|
||
)
|
||
})
|
||
.flatten();
|
||
self.sources.apply(kind, o.id, params);
|
||
}
|
||
true
|
||
}
|
||
fn play_sound(&mut self, event: String, x: f64, y: f64, z: f64, volume: f32, pitch: f32) {
|
||
if !(x.is_finite() && y.is_finite() && z.is_finite()) {
|
||
return;
|
||
}
|
||
let ok = |v: f32, max: f32| {
|
||
if v.is_finite() {
|
||
v.clamp(0.0, max)
|
||
} else {
|
||
1.0
|
||
}
|
||
};
|
||
let sounds = self
|
||
.out
|
||
.iter()
|
||
.filter(|o| matches!(o, Output::Sound { .. }))
|
||
.count();
|
||
if sounds < 64 {
|
||
self.out.push(Output::Sound {
|
||
event: clip(event),
|
||
at: [x, y, z],
|
||
volume: ok(volume, 16.0),
|
||
pitch: ok(pitch, 2.0),
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
/// The most nodes a command's tree may have, words a list may hold and
|
||
/// characters in one word (`command.set-tree`).
|
||
const TREE_NODES: usize = 512;
|
||
const TREE_WORDS: usize = 256;
|
||
const TREE_WORD_CHARS: usize = 64;
|
||
|
||
/// A command's tree as `command.set-tree` gave it, with the mod's lists.
|
||
pub struct CommandTree<'a> {
|
||
pub name: &'a str,
|
||
pub nodes: &'a [TreeNode],
|
||
pub lists: &'a [(String, Vec<String>)],
|
||
}
|
||
impl CommandTree<'_> {
|
||
/// The words of a `names` list, empty for one the mod never set.
|
||
pub fn list(&self, list: &str) -> &[String] {
|
||
self.lists
|
||
.iter()
|
||
.find(|(n, _)| n == list)
|
||
.map_or(&[], |(_, v)| v.as_slice())
|
||
}
|
||
}
|
||
|
||
fn check_word(word: &str, what: &str) -> Result<(), String> {
|
||
if word.is_empty() || word.chars().count() > TREE_WORD_CHARS || word.contains(char::is_whitespace)
|
||
{
|
||
return Err(format!("{what} {word:?}: one to {TREE_WORD_CHARS} characters, no spaces"));
|
||
}
|
||
Ok(())
|
||
}
|
||
fn check_words(words: &[String], what: &str) -> Result<(), String> {
|
||
if words.len() > TREE_WORDS {
|
||
return Err(format!("{what}: at most {TREE_WORDS} words"));
|
||
}
|
||
words.iter().try_for_each(|w| check_word(w, what))
|
||
}
|
||
fn check_value(kind: &TreeValueKind) -> Result<(), String> {
|
||
match kind {
|
||
TreeValueKind::Word(words) => check_words(words, "word suggestion"),
|
||
TreeValueKind::Choice(words) if words.is_empty() => Err("a choice needs a word".into()),
|
||
TreeValueKind::Choice(words) => check_words(words, "choice"),
|
||
TreeValueKind::Names(list) => check_word(list, "list name"),
|
||
TreeValueKind::Integer((min, max)) if matches!((min, max), (Some(a), Some(b)) if a > b) => {
|
||
Err("integer bounds: min above max".into())
|
||
}
|
||
TreeValueKind::Number((min, max)) => {
|
||
let ok = |b: &Option<f64>| b.is_none_or(f64::is_finite);
|
||
if !ok(min) || !ok(max) {
|
||
return Err("number bounds must be finite".into());
|
||
}
|
||
match (min, max) {
|
||
(Some(a), Some(b)) if a > b => Err("number bounds: min above max".into()),
|
||
_ => Ok(()),
|
||
}
|
||
}
|
||
TreeValueKind::Integer(_) | TreeValueKind::BlockPos => Ok(()),
|
||
}
|
||
}
|
||
|
||
/// Whether `nodes` is a tree the chat can use: at most [`TREE_NODES`],
|
||
/// children after their parent and each reached once, literals that are
|
||
/// single words, text only as a last node, kinds within their limits.
|
||
pub fn check_tree(nodes: &[TreeNode]) -> Result<(), String> {
|
||
if nodes.is_empty() || nodes.len() > TREE_NODES {
|
||
return Err(format!("a tree has 1 to {TREE_NODES} nodes"));
|
||
}
|
||
let mut parent = vec![None; nodes.len()];
|
||
for (i, n) in nodes.iter().enumerate() {
|
||
let what = format!("node {i} ({:?})", n.name);
|
||
if i > 0 {
|
||
check_word(&n.name, "node name").map_err(|e| format!("{what}: {e}"))?;
|
||
}
|
||
match &n.kind {
|
||
Some(TreeNodeKind::Value(v)) => check_value(v).map_err(|e| format!("{what}: {e}"))?,
|
||
Some(TreeNodeKind::Text) if !n.children.is_empty() => {
|
||
return Err(format!("{what}: text is the rest of the line: nothing follows it"));
|
||
}
|
||
Some(TreeNodeKind::Options(o)) => {
|
||
if !n.children.is_empty() {
|
||
return Err(format!("{what}: options take the rest of the line: nothing follows them"));
|
||
}
|
||
if o.entries.len() > TREE_WORDS {
|
||
return Err(format!("{what}: too many options"));
|
||
}
|
||
for (j, e) in o.entries.iter().enumerate() {
|
||
check_word(&e.key, "option key").map_err(|e| format!("{what}: {e}"))?;
|
||
if e.key.contains('=') || o.entries[..j].iter().any(|b| b.key == e.key) {
|
||
return Err(format!("{what}: option {:?} twice or with an =", e.key));
|
||
}
|
||
match &e.value {
|
||
Some(TreeValueKind::BlockPos) => {
|
||
return Err(format!("{what}: an option value is one word"));
|
||
}
|
||
Some(v) => check_value(v).map_err(|e| format!("{what}: {e}"))?,
|
||
None => {}
|
||
}
|
||
}
|
||
if let Some(free) = &o.free {
|
||
check_words(free, "free word").map_err(|e| format!("{what}: {e}"))?;
|
||
}
|
||
}
|
||
Some(TreeNodeKind::Text) | None => {}
|
||
}
|
||
for &c in &n.children {
|
||
let c = c as usize;
|
||
if c <= i || c >= nodes.len() {
|
||
return Err(format!("{what}: child {c} must come after it, within the list"));
|
||
}
|
||
if parent[c].replace(i).is_some() {
|
||
return Err(format!("{what}: child {c} has two parents"));
|
||
}
|
||
}
|
||
}
|
||
// A name once among a node's children.
|
||
for (i, n) in nodes.iter().enumerate() {
|
||
for (a, &x) in n.children.iter().enumerate() {
|
||
if n.children[..a]
|
||
.iter()
|
||
.any(|&y| nodes[y as usize].name == nodes[x as usize].name)
|
||
{
|
||
return Err(format!("node {i}: two children named {:?}", nodes[x as usize].name));
|
||
}
|
||
}
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
impl command::Host for State {
|
||
fn set_tree(&mut self, name: String, nodes: Vec<TreeNode>) -> Result<(), String> {
|
||
check_tree(&nodes)?;
|
||
let known = self.trees.iter().position(|(n, _)| *n == name);
|
||
match known {
|
||
Some(i) => self.trees[i].1 = nodes,
|
||
None if self.trees.len() < 64 => self.trees.push((name, nodes)),
|
||
None => return Err("at most 64 commands have a tree".into()),
|
||
}
|
||
self.tree_generation += 1;
|
||
Ok(())
|
||
}
|
||
fn set_suggestions(&mut self, topic: String, values: Vec<String>) {
|
||
let values: Vec<String> = values
|
||
.into_iter()
|
||
.filter(|w| check_word(w, "").is_ok())
|
||
.take(TREE_WORDS)
|
||
.collect();
|
||
let known = self.lists.iter().position(|(n, _)| *n == topic);
|
||
match known {
|
||
Some(i) if self.lists[i].1 == values => return,
|
||
Some(i) => self.lists[i].1 = values,
|
||
None if self.lists.len() < 64 && check_word(&topic, "").is_ok() => {
|
||
self.lists.push((topic, values));
|
||
}
|
||
None => return,
|
||
}
|
||
self.tree_generation += 1;
|
||
}
|
||
fn run(&mut self, line: String) {
|
||
let queued = self
|
||
.out
|
||
.iter()
|
||
.filter(|o| matches!(o, Output::Command { .. }))
|
||
.count();
|
||
if queued < CHAT_PER_CALL {
|
||
self.out.push(Output::Command { line: clip(line) });
|
||
}
|
||
}
|
||
fn run_quiet(&mut self, lines: Vec<String>) {
|
||
let queued: usize = self
|
||
.out
|
||
.iter()
|
||
.map(|o| match o {
|
||
Output::QuietCommands { lines, .. } => lines.len(),
|
||
_ => 0,
|
||
})
|
||
.sum();
|
||
let room = QUIET_PER_CALL.saturating_sub(queued);
|
||
if room > 0 && !lines.is_empty() {
|
||
self.out.push(Output::QuietCommands {
|
||
mod_id: self.id.clone(),
|
||
lines: lines.into_iter().take(room).map(clip).collect(),
|
||
});
|
||
}
|
||
}
|
||
}
|
||
impl hud::Host for State {
|
||
fn set_panel(&mut self, corner: Corner, lines: Vec<Line>) {
|
||
let lines = lines
|
||
.into_iter()
|
||
.take(HUD_LINES)
|
||
.map(|l| Line {
|
||
text: clip(l.text),
|
||
color: l.color & 0xFF_FFFF,
|
||
})
|
||
.collect();
|
||
self.panel = Some(Panel { corner, lines });
|
||
}
|
||
fn clear(&mut self) {
|
||
self.panel = None;
|
||
}
|
||
}
|
||
impl ui::Host for State {
|
||
fn open_screen(&mut self, mut screen: ui::Screen) {
|
||
screen.title = clip(screen.title);
|
||
screen.widgets = clip_widgets(screen.widgets);
|
||
self.ui.screen = Some(screen);
|
||
self.ui.open = true;
|
||
}
|
||
fn close_screen(&mut self) {
|
||
self.ui.screen = None;
|
||
self.ui.close = true;
|
||
}
|
||
fn set_settings(&mut self, widgets: Vec<ui::Widget>) {
|
||
self.ui.settings = clip_widgets(widgets);
|
||
}
|
||
}
|
||
impl storage::Host for State {
|
||
fn get(&mut self, key: String) -> Option<Vec<u8>> {
|
||
storage_key_ok(&key)
|
||
.then(|| std::fs::read(self.data_dir.join(&key)).ok())
|
||
.flatten()
|
||
}
|
||
fn set(&mut self, key: String, value: Vec<u8>) -> Result<(), String> {
|
||
if !storage_key_ok(&key) {
|
||
return Err(format!("{key:?} is not [a-z0-9_.-]{{1,64}}"));
|
||
}
|
||
let len = value.len() as u64;
|
||
if len > self.storage_budget {
|
||
return Err("too much storage traffic in one call".into());
|
||
}
|
||
// Everything already on disk but the file this call replaces.
|
||
let existing: Vec<std::fs::DirEntry> = std::fs::read_dir(&self.data_dir)
|
||
.into_iter()
|
||
.flatten()
|
||
.flatten()
|
||
.filter(|e| e.file_name().to_string_lossy() != key)
|
||
.collect();
|
||
if existing.len() >= STORAGE_MAX_KEYS {
|
||
return Err(format!("would hold over {STORAGE_MAX_KEYS} keys"));
|
||
}
|
||
let used: u64 = existing
|
||
.iter()
|
||
.filter_map(|e| e.metadata().ok())
|
||
.map(|m| m.len())
|
||
.sum();
|
||
if used + len > STORAGE_QUOTA {
|
||
return Err(format!(
|
||
"would use over {} MiB of storage",
|
||
STORAGE_QUOTA >> 20
|
||
));
|
||
}
|
||
std::fs::create_dir_all(&self.data_dir).map_err(|e| e.to_string())?;
|
||
std::fs::write(self.data_dir.join(&key), value).map_err(|e| e.to_string())?;
|
||
self.storage_budget -= len;
|
||
Ok(())
|
||
}
|
||
fn delete(&mut self, key: String) {
|
||
if storage_key_ok(&key) {
|
||
let _ = std::fs::remove_file(self.data_dir.join(&key));
|
||
}
|
||
}
|
||
}
|
||
|
||
/// A storage key: one path segment of `[a-z0-9_.-]{1,64}`, not `.` or `..`.
|
||
/// No `/`, so a key can never leave the mod's own directory.
|
||
fn storage_key_ok(key: &str) -> bool {
|
||
let chars_ok = (1..=64).contains(&key.len())
|
||
&& key
|
||
.bytes()
|
||
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_.-".contains(&b));
|
||
chars_ok && key != "." && key != ".."
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tree_tests {
|
||
use super::*;
|
||
|
||
fn lit(name: &str, children: &[u32]) -> TreeNode {
|
||
TreeNode {
|
||
name: name.into(),
|
||
kind: None,
|
||
children: children.to_vec(),
|
||
runs: true,
|
||
}
|
||
}
|
||
fn value(name: &str, kind: TreeValueKind) -> TreeNode {
|
||
TreeNode {
|
||
name: name.into(),
|
||
kind: Some(TreeNodeKind::Value(kind)),
|
||
children: Vec::new(),
|
||
runs: true,
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn a_tree_is_checked_before_a_mod_may_set_it() {
|
||
let ok = vec![
|
||
lit("", &[1, 2]),
|
||
lit("wave", &[3]),
|
||
lit("menu", &[]),
|
||
value("count", TreeValueKind::Integer((Some(1), Some(80)))),
|
||
];
|
||
assert_eq!(check_tree(&ok), Ok(()));
|
||
assert!(check_tree(&[]).is_err());
|
||
// A loop, a child out of range, two parents, two children with a name.
|
||
let mut bad = ok.clone();
|
||
bad[3].children = vec![1];
|
||
assert!(check_tree(&bad).unwrap_err().contains("after it"));
|
||
let mut bad = ok.clone();
|
||
bad[1].children = vec![9];
|
||
assert!(check_tree(&bad).is_err());
|
||
let mut bad = ok.clone();
|
||
bad[2].children = vec![3];
|
||
assert!(check_tree(&bad).unwrap_err().contains("two parents"));
|
||
let mut bad = ok.clone();
|
||
bad[2].name = "wave".into();
|
||
assert!(check_tree(&bad).unwrap_err().contains("two children"));
|
||
// Words: one, short, no spaces; bounds the right way round.
|
||
let mut bad = ok.clone();
|
||
bad[2].name = "two words".into();
|
||
assert!(check_tree(&bad).is_err());
|
||
let mut bad = ok.clone();
|
||
bad[3] = value("count", TreeValueKind::Integer((Some(5), Some(1))));
|
||
assert!(check_tree(&bad).is_err());
|
||
let mut bad = ok.clone();
|
||
bad[3] = value("n", TreeValueKind::Number((Some(f64::NAN), None)));
|
||
assert!(check_tree(&bad).is_err());
|
||
let mut bad = ok.clone();
|
||
bad[3] = value("kind", TreeValueKind::Choice(Vec::new()));
|
||
assert!(check_tree(&bad).is_err());
|
||
// Text and options end the line.
|
||
let mut bad = ok.clone();
|
||
bad[3].kind = Some(TreeNodeKind::Text);
|
||
bad[3].children = vec![];
|
||
assert_eq!(check_tree(&bad), Ok(()));
|
||
bad[1].kind = Some(TreeNodeKind::Text);
|
||
assert!(check_tree(&bad).unwrap_err().contains("nothing follows"));
|
||
let too_many: Vec<TreeNode> = (0..=TREE_NODES).map(|_| lit("x", &[])).collect();
|
||
assert!(check_tree(&too_many).is_err());
|
||
}
|
||
}
|