Mods in the game: load the ones turned on, hooks, HUD panels, Options > Mods
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Generated
+1
@@ -1239,6 +1239,7 @@ dependencies = [
|
||||
"horizon-bench",
|
||||
"horizon-core",
|
||||
"horizon-friends",
|
||||
"horizon-mods",
|
||||
"horizon-protocol",
|
||||
"horizon-telemetry",
|
||||
"horizon-theme",
|
||||
|
||||
@@ -13,6 +13,8 @@ horizon-core = { path = "../horizon-core" }
|
||||
horizon-world = { path = "../horizon-world" }
|
||||
horizon-protocol = { path = "../horizon-protocol" }
|
||||
horizon-friends = { path = "../horizon-friends" }
|
||||
# Horizon mods: sandboxed WebAssembly components, off unless installed and turned on (docs/mods.md).
|
||||
horizon-mods = { path = "../horizon-mods" }
|
||||
wgpu = { version = "30.0.1", default-features = false, features = ["std", "parking_lot", "vulkan", "metal", "wgsl"] }
|
||||
winit = "0.30.13"
|
||||
pollster = "0.4"
|
||||
|
||||
@@ -129,6 +129,32 @@ pub fn draw_fps(
|
||||
);
|
||||
}
|
||||
|
||||
/// A box of text lines (a mod's HUD panel): `(text, 0xRRGGBB)` each.
|
||||
pub fn draw_lines(
|
||||
batch: &mut HudBatch,
|
||||
atlas: &HudAtlas,
|
||||
corners: &mut Corners,
|
||||
corner: Corner,
|
||||
lines: &[(&str, u32)],
|
||||
) {
|
||||
if lines.is_empty() {
|
||||
return;
|
||||
}
|
||||
let w = lines
|
||||
.iter()
|
||||
.map(|(text, _)| HudBatch::text_width(atlas, text))
|
||||
.fold(0.0, f32::max)
|
||||
+ 4.0;
|
||||
let h = 10.0 * lines.len() as f32 + 2.0;
|
||||
let (x, y) = corners.place(corner, w, h);
|
||||
batch.fill(atlas, x, y, w, h, BACKGROUND);
|
||||
for (i, (text, color)) in lines.iter().enumerate() {
|
||||
let [_, r, g, b] = color.to_be_bytes();
|
||||
let y = y + 2.0 + 10.0 * i as f32;
|
||||
batch.text(atlas, text, x + 2.0, y, rgba(r, g, b, 255), true);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the keystroke overlay shows.
|
||||
pub struct Keystrokes {
|
||||
/// Forward, left, back, right: held, and the bound key's name.
|
||||
|
||||
@@ -69,6 +69,7 @@ mod maps;
|
||||
mod minecarts;
|
||||
mod mob_blocks;
|
||||
mod mob_gear;
|
||||
mod mods;
|
||||
mod mount_menu;
|
||||
mod mounts;
|
||||
mod music;
|
||||
@@ -224,6 +225,8 @@ struct Options {
|
||||
dedicated: Option<Vec<String>>,
|
||||
/// `--benchmark SCENARIO`: run the benchmark, write its report and quit.
|
||||
benchmark: Option<String>,
|
||||
/// `--dev-mod PATH` (repeatable): mods always on and reloaded when rebuilt.
|
||||
dev_mods: Vec<PathBuf>,
|
||||
}
|
||||
impl Options {
|
||||
/// The name to join servers with: the one given, else the offline name kept
|
||||
@@ -273,6 +276,7 @@ impl Options {
|
||||
.filter(|n| !n.is_empty()),
|
||||
dedicated: None,
|
||||
benchmark: None,
|
||||
dev_mods: Vec::new(),
|
||||
};
|
||||
let mut session_file = std::env::var("HORIZON_SESSION_FILE").ok();
|
||||
let mut args = std::env::args().skip(1);
|
||||
@@ -280,7 +284,7 @@ impl Options {
|
||||
match arg.as_str() {
|
||||
"--help" | "-h" => {
|
||||
println!(
|
||||
"Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause."
|
||||
"Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause."
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -322,6 +326,7 @@ impl Options {
|
||||
"--smoke-report" => o.report = Some(value.into()),
|
||||
"--screenshot-after" => o.screenshot_after = Some(value.parse()?),
|
||||
"--world" => o.world = Some(value),
|
||||
"--dev-mod" => o.dev_mods.push(std::path::absolute(&value)?),
|
||||
"--benchmark" => {
|
||||
if horizon_client::benchmark::scenes(&value).is_none() {
|
||||
return Err(format!(
|
||||
@@ -940,6 +945,8 @@ struct Game<'a> {
|
||||
frame_graph: horizon_client::perf_overlay::FrameGraph,
|
||||
/// Horizon's extras (zoom, FPS counter, keystrokes): `game/extras.rs`.
|
||||
extras: extras::ExtrasState,
|
||||
/// Horizon mods (`game/mods.rs`), none running unless turned on.
|
||||
mods: mods::ModsState,
|
||||
/// Meshed sections waiting for an upload budget (Horizon settings).
|
||||
pending_uploads: Vec<((i32, i32, i32), horizon_client::mesher::SectionMesh)>,
|
||||
/// This frame's view frustum, for culling entities and block entities.
|
||||
@@ -2940,6 +2947,7 @@ impl Game<'_> {
|
||||
self.apply_totem();
|
||||
self.update_totem_ready();
|
||||
self.tick_command_extras();
|
||||
self.tick_mods();
|
||||
let camera_eye = self.camera_eye_height();
|
||||
let stick = self.pad_move();
|
||||
if self.riding.is_some() && self.player.is_some() {
|
||||
@@ -9265,6 +9273,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
}
|
||||
}
|
||||
self.extras_frame(elapsed);
|
||||
self.mods_frame(elapsed);
|
||||
self.extras_retry()?;
|
||||
self.apply_mouse_look();
|
||||
self.pad_look(elapsed.as_secs_f32());
|
||||
@@ -9822,6 +9831,7 @@ pub fn run() -> Result<()> {
|
||||
pending_uploads: Vec::new(),
|
||||
frame_graph: Default::default(),
|
||||
extras: Default::default(),
|
||||
mods: Default::default(),
|
||||
sky_darken_memo: Default::default(),
|
||||
persist: Default::default(),
|
||||
remote: None,
|
||||
@@ -9878,6 +9888,11 @@ pub fn run() -> Result<()> {
|
||||
game.options.no_pause = true;
|
||||
}
|
||||
game.apply_settings();
|
||||
// Benchmarks measure the game alone.
|
||||
if game.options.benchmark.is_none() {
|
||||
game.mods.dev = game.options.dev_mods.clone();
|
||||
game.start_mods();
|
||||
}
|
||||
if let Some(path) = &game.options.control {
|
||||
let server = horizon_client::control::Server::start(path)
|
||||
.map_err(|e| format!("control socket {}: {e}", path.display()))?;
|
||||
|
||||
@@ -408,6 +408,7 @@ impl Game<'_> {
|
||||
return;
|
||||
}
|
||||
let focused = self.screen == Screen::Chat;
|
||||
let heard = self.mods.mods.is_running().then(|| text.plain());
|
||||
self.ui.chat.add(
|
||||
&self.res.atlas,
|
||||
text,
|
||||
@@ -415,6 +416,9 @@ impl Game<'_> {
|
||||
self.ticks,
|
||||
focused,
|
||||
);
|
||||
if let Some(line) = heard {
|
||||
self.mods_chat(&line);
|
||||
}
|
||||
}
|
||||
/// Keys while the chat screen is open.
|
||||
pub(super) fn chat_key(&mut self, event: &KeyEvent) {
|
||||
@@ -511,9 +515,13 @@ impl Game<'_> {
|
||||
&[Text::literal(PLAYER_NAME), Text::literal(message)],
|
||||
);
|
||||
let focused = self.screen == Screen::Chat;
|
||||
let heard = self.mods.mods.is_running().then(|| line.plain());
|
||||
self.ui
|
||||
.chat
|
||||
.add(&self.res.atlas, line, None, self.ticks, focused);
|
||||
if let Some(line) = heard {
|
||||
self.mods_chat(&line);
|
||||
}
|
||||
self.lan_host_chat(message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,6 +78,9 @@ fn format_double(v: f64) -> String {
|
||||
impl Game<'_> {
|
||||
/// Commands.performCommand for a line without its slash.
|
||||
pub(super) fn run_command(&mut self, command: &str) {
|
||||
if self.mod_command(command) {
|
||||
return;
|
||||
}
|
||||
let d = vanilla::game_dispatcher();
|
||||
let parse = d.parse(command, &self.ui.registries);
|
||||
let result = match parse.executable() {
|
||||
|
||||
@@ -233,7 +233,8 @@ impl Game<'_> {
|
||||
/// the caller). The top left corner gives way to the debug screen.
|
||||
pub(super) fn draw_extras(&mut self, batch: &mut HudBatch) {
|
||||
let e = &self.settings.extras;
|
||||
if !e.fps && !e.keystrokes && !e.minimap {
|
||||
let mod_panels = self.mods.mods.panels().next().is_some();
|
||||
if !e.fps && !e.keystrokes && !e.minimap && !mod_panels {
|
||||
return;
|
||||
}
|
||||
let (fps_on, fps_corner, lows) = (e.fps, e.fps_corner, e.fps_lows);
|
||||
@@ -287,6 +288,9 @@ impl Game<'_> {
|
||||
};
|
||||
extras_hud::draw_keystrokes(batch, &self.res.atlas, &mut corners, keys_corner, &k);
|
||||
}
|
||||
if mod_panels {
|
||||
self.draw_mod_panels(batch, &mut corners);
|
||||
}
|
||||
}
|
||||
/// The height the status effect icons take at the top right
|
||||
/// (`Hud.extractEffects`: beneficial at y 1, harmful at y 26).
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
//! Horizon mods in the game (`docs/mods.md`): loading the ones turned on,
|
||||
//! their tick, frame, chat and command hooks, their HUD panels and what
|
||||
//! they print. With no mod on, `horizon_mods::Mods` holds no engine and
|
||||
//! every hook here returns after one check.
|
||||
use super::{Game, Screen};
|
||||
use horizon_client::{
|
||||
extras::Corner,
|
||||
extras_hud::{self, Corners},
|
||||
hud::HudBatch,
|
||||
mod_list::{self, Installed},
|
||||
text::{self, Text},
|
||||
};
|
||||
use horizon_mods::{Clock, Mods, Output, Player, Snapshot, Status};
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct ModsState {
|
||||
pub(super) mods: Mods,
|
||||
/// `--dev-mod PATH`: always on, reloaded when rebuilt.
|
||||
pub(super) dev: Vec<PathBuf>,
|
||||
/// When dev mods were last checked for a rebuild.
|
||||
checked: Option<Instant>,
|
||||
}
|
||||
/// How often dev mods are checked for a rebuild.
|
||||
const RELOAD_CHECK: Duration = Duration::from_secs(1);
|
||||
|
||||
/// A vanilla command name: mods may not take it.
|
||||
fn vanilla_command(name: &str) -> bool {
|
||||
let d = horizon_client::command::vanilla::game_dispatcher();
|
||||
d.nodes[0]
|
||||
.children
|
||||
.iter()
|
||||
.any(|&c| d.nodes[c].name() == name)
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// Reads `horizon-mods/` and the dev mods, and starts the ones turned on.
|
||||
pub(super) fn start_mods(&mut self) {
|
||||
let dir = Self::options_path().with_file_name(mod_list::DIR);
|
||||
let dev = &self.mods.dev;
|
||||
let mut paths = horizon_mods::find(&dir);
|
||||
paths.retain(|p| !dev.contains(p));
|
||||
paths.extend(dev.iter().cloned());
|
||||
// A dev mod is on whatever the list says.
|
||||
let dev_ids: Vec<String> = dev
|
||||
.iter()
|
||||
.filter_map(|p| horizon_mods::Package::read(p).ok())
|
||||
.map(|p| p.manifest.id)
|
||||
.collect();
|
||||
let enabled = &self.settings.mods.enabled;
|
||||
let on = |id: &str| enabled.contains(id) || dev_ids.iter().any(|d| d == id);
|
||||
let mods = Mods::load(&paths, on, vanilla_command);
|
||||
self.mods.mods = mods;
|
||||
self.list_mods();
|
||||
self.show_mod_output();
|
||||
}
|
||||
/// The Mods page's rows, from what loaded.
|
||||
fn list_mods(&mut self) {
|
||||
let dev = &self.mods.dev;
|
||||
self.settings.mods.installed = self
|
||||
.mods
|
||||
.mods
|
||||
.entries()
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let file = e.path.file_name().unwrap_or_default().to_string_lossy();
|
||||
let problem = match &e.status {
|
||||
Status::Failed(reason) => Some(format!("Stopped: {reason}")),
|
||||
_ => None,
|
||||
};
|
||||
let Some(m) = &e.manifest else {
|
||||
return Installed {
|
||||
id: String::new(),
|
||||
title: file.into_owned(),
|
||||
description: String::new(),
|
||||
problem,
|
||||
dev: false,
|
||||
};
|
||||
};
|
||||
// What it may do first: the row cuts long descriptions.
|
||||
let may: Vec<&str> = m.capabilities.iter().map(|c| c.describe()).collect();
|
||||
let may = if may.is_empty() {
|
||||
"Asks for nothing.".to_owned()
|
||||
} else {
|
||||
format!("May {}.", may.join(", "))
|
||||
};
|
||||
Installed {
|
||||
id: m.id.clone(),
|
||||
title: format!("{} {}", m.name, m.version),
|
||||
description: format!("{may} {}", m.description).trim().to_owned(),
|
||||
problem,
|
||||
dev: dev.contains(&e.path),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
/// After the options changed: restart the mods if the list of the ones
|
||||
/// turned on did.
|
||||
pub(super) fn sync_mods(&mut self) {
|
||||
let running: Vec<&str> = self
|
||||
.mods
|
||||
.mods
|
||||
.entries()
|
||||
.iter()
|
||||
.filter(|e| e.status != Status::Off)
|
||||
.filter_map(|e| Some(e.manifest.as_ref()?.id.as_str()))
|
||||
.collect();
|
||||
let wanted: Vec<&str> = self
|
||||
.settings
|
||||
.mods
|
||||
.installed
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|&(i, _)| self.settings.mods.is_on(i))
|
||||
.map(|(_, m)| m.id.as_str())
|
||||
.collect();
|
||||
if running != wanted {
|
||||
self.start_mods();
|
||||
}
|
||||
}
|
||||
/// What mods read this tick.
|
||||
fn mod_snapshot(&self) -> Snapshot {
|
||||
let player = self.player.as_ref().map(|p| Player {
|
||||
x: p.position.x,
|
||||
y: p.position.y,
|
||||
z: p.position.z,
|
||||
yaw: self.yaw,
|
||||
pitch: self.pitch,
|
||||
health: p.health.health(),
|
||||
food: p.health.food.food.max(0) as u32,
|
||||
dimension: self.dim.id().to_owned(),
|
||||
});
|
||||
let clock = player.is_some().then(|| Clock {
|
||||
game_time: self.world.game_time.max(0) as u64,
|
||||
day_time: self.world.day_time.max(0) as u64,
|
||||
});
|
||||
Snapshot { player, clock }
|
||||
}
|
||||
/// A game tick.
|
||||
pub(super) fn tick_mods(&mut self) {
|
||||
if !self.mods.mods.is_running() {
|
||||
return;
|
||||
}
|
||||
let snapshot = self.mod_snapshot();
|
||||
self.mods.mods.set_snapshot(snapshot);
|
||||
self.mods.mods.tick(self.ticks);
|
||||
self.show_mod_output();
|
||||
}
|
||||
/// Once per frame: the frame hook, and dev mods' rebuilds.
|
||||
pub(super) fn mods_frame(&mut self, elapsed: Duration) {
|
||||
if !self.mods.dev.is_empty()
|
||||
&& self
|
||||
.mods
|
||||
.checked
|
||||
.is_none_or(|t| t.elapsed() >= RELOAD_CHECK)
|
||||
{
|
||||
self.mods.checked = Some(Instant::now());
|
||||
if self.mods.mods.reload_changed(vanilla_command) {
|
||||
self.list_mods();
|
||||
self.system_message(Text::literal("Mods reloaded").with_color(text::GRAY));
|
||||
}
|
||||
}
|
||||
if !self.mods.mods.is_running() {
|
||||
return;
|
||||
}
|
||||
self.mods.mods.frame(elapsed.as_secs_f32());
|
||||
self.show_mod_output();
|
||||
}
|
||||
/// `/command` typed in chat: true when a mod owns it.
|
||||
pub(super) fn mod_command(&mut self, command: &str) -> bool {
|
||||
if !self.mods.mods.is_running() {
|
||||
return false;
|
||||
}
|
||||
// The command may follow a teleport in the same tick.
|
||||
let snapshot = self.mod_snapshot();
|
||||
self.mods.mods.set_snapshot(snapshot);
|
||||
if !self.mods.mods.command(command) {
|
||||
return false;
|
||||
}
|
||||
self.show_mod_output();
|
||||
true
|
||||
}
|
||||
/// A chat line the player received.
|
||||
pub(super) fn mods_chat(&mut self, line: &str) {
|
||||
self.mods.mods.chat(line);
|
||||
self.show_mod_output();
|
||||
}
|
||||
/// Chat lines, command feedback and stopped mods, into the chat.
|
||||
fn show_mod_output(&mut self) {
|
||||
for output in self.mods.mods.drain() {
|
||||
let line = match output {
|
||||
Output::Chat { name, text } => {
|
||||
let mut line = Text::literal(format!("[{name}] ")).with_color(text::GRAY);
|
||||
line.push(Text::literal(text));
|
||||
line
|
||||
}
|
||||
Output::Feedback { text, error: false } => Text::literal(text),
|
||||
Output::Feedback { text, error: true } => Text::literal(text).with_color(text::RED),
|
||||
Output::Stopped { name, reason } => {
|
||||
self.list_mods();
|
||||
Text::literal(format!("Mod {name} stopped: {reason}")).with_color(text::RED)
|
||||
}
|
||||
};
|
||||
// Not through system_message: a mod must not hear its own lines.
|
||||
let focused = self.screen == Screen::Chat;
|
||||
self.ui
|
||||
.chat
|
||||
.add(&self.res.atlas, line, None, self.ticks, focused);
|
||||
}
|
||||
}
|
||||
/// The mods' HUD panels, stacked with the extras in their corners.
|
||||
pub(super) fn draw_mod_panels(&self, batch: &mut HudBatch, corners: &mut Corners) {
|
||||
for panel in self.mods.mods.panels() {
|
||||
let corner = match panel.corner {
|
||||
horizon_mods::Corner::TopLeft => Corner::TopLeft,
|
||||
horizon_mods::Corner::TopRight => Corner::TopRight,
|
||||
horizon_mods::Corner::BottomLeft => Corner::BottomLeft,
|
||||
horizon_mods::Corner::BottomRight => Corner::BottomRight,
|
||||
};
|
||||
// F3 takes the top left, as it does from the extras.
|
||||
if self.debug && corner == Corner::TopLeft {
|
||||
continue;
|
||||
}
|
||||
let lines: Vec<(&str, u32)> = panel
|
||||
.lines
|
||||
.iter()
|
||||
.map(|l| (l.text.as_str(), l.color))
|
||||
.collect();
|
||||
extras_hud::draw_lines(batch, &self.res.atlas, corners, corner, &lines);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -193,6 +193,7 @@ impl Game<'_> {
|
||||
Event::Changed => {
|
||||
self.settings.save(&Self::options_path());
|
||||
self.apply_settings();
|
||||
self.sync_mods();
|
||||
}
|
||||
Event::Close => {
|
||||
self.settings.save(&Self::options_path());
|
||||
|
||||
@@ -100,6 +100,7 @@ pub mod mesher;
|
||||
pub mod minimap;
|
||||
pub mod mipmap;
|
||||
pub mod mobs;
|
||||
pub mod mod_list;
|
||||
mod model_library;
|
||||
pub mod models;
|
||||
pub mod motion;
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
//! Which of the installed Horizon mods are on (`docs/mods.md`), kept in
|
||||
//! `horizon-mods.txt` beside `options.txt` as `mod.<id>:true` lines. Every
|
||||
//! mod is off until the player turns it on in Options > Mods.
|
||||
use std::{collections::BTreeSet, fs, path::Path};
|
||||
|
||||
pub const FILE: &str = "horizon-mods.txt";
|
||||
/// The folder holding `.hmod` files, beside `options.txt`.
|
||||
pub const DIR: &str = "horizon-mods";
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ModList {
|
||||
/// Ids of the mods the player turned on.
|
||||
pub enabled: BTreeSet<String>,
|
||||
/// What the Mods page shows, filled by the game from the mods it found.
|
||||
pub installed: Vec<Installed>,
|
||||
}
|
||||
|
||||
/// One installed mod as the Mods page shows it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Installed {
|
||||
pub id: String,
|
||||
/// `Name 1.0` (the file name when the manifest is unreadable).
|
||||
pub title: String,
|
||||
pub description: String,
|
||||
/// Why it is not running, when it failed.
|
||||
pub problem: Option<String>,
|
||||
/// Loaded with `--dev-mod`: always on, reloaded when rebuilt.
|
||||
pub dev: bool,
|
||||
}
|
||||
|
||||
impl ModList {
|
||||
pub fn load(dir: &Path) -> Self {
|
||||
fs::read_to_string(dir.join(FILE))
|
||||
.map(|t| Self::parse(&t))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
pub fn parse(text: &str) -> Self {
|
||||
let enabled = text
|
||||
.lines()
|
||||
.filter_map(|l| l.split_once(':'))
|
||||
.filter(|(_, v)| v.trim() == "true")
|
||||
.filter_map(|(k, _)| k.trim().strip_prefix("mod."))
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
Self {
|
||||
enabled,
|
||||
installed: Vec::new(),
|
||||
}
|
||||
}
|
||||
pub fn serialize(&self) -> String {
|
||||
self.enabled
|
||||
.iter()
|
||||
.map(|id| format!("mod.{id}:true\n"))
|
||||
.collect()
|
||||
}
|
||||
pub fn save(&self, dir: &Path) {
|
||||
let path = dir.join(FILE);
|
||||
if self.enabled.is_empty() && !path.exists() {
|
||||
return;
|
||||
}
|
||||
let _ = fs::write(path, self.serialize());
|
||||
}
|
||||
pub fn is_on(&self, i: usize) -> bool {
|
||||
self.installed
|
||||
.get(i)
|
||||
.is_some_and(|m| m.dev || self.enabled.contains(&m.id))
|
||||
}
|
||||
/// Turns installed mod `i` on or off (a dev mod stays on).
|
||||
pub fn toggle(&mut self, i: usize) {
|
||||
let Some(m) = self.installed.get(i).filter(|m| !m.dev) else {
|
||||
return;
|
||||
};
|
||||
if !self.enabled.remove(&m.id) {
|
||||
self.enabled.insert(m.id.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn round_trips_and_ignores_the_rest() {
|
||||
let list = ModList::parse("mod.coords_hud:true\nmod.other:false\nzoom:true\n");
|
||||
assert_eq!(list.enabled.iter().collect::<Vec<_>>(), ["coords_hud"]);
|
||||
assert_eq!(ModList::parse(&list.serialize()), list);
|
||||
assert_eq!(ModList::default().serialize(), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggles_installed_mods_but_not_dev_ones() {
|
||||
let installed = |id: &str, dev| Installed {
|
||||
id: id.into(),
|
||||
title: id.into(),
|
||||
description: String::new(),
|
||||
problem: None,
|
||||
dev,
|
||||
};
|
||||
let mut list = ModList {
|
||||
installed: vec![installed("a", false), installed("b", true)],
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!list.is_on(0) && list.is_on(1));
|
||||
list.toggle(0);
|
||||
list.toggle(1);
|
||||
assert!(list.is_on(0) && list.is_on(1));
|
||||
assert_eq!(list.serialize(), "mod.a:true\n");
|
||||
list.toggle(0);
|
||||
assert!(!list.is_on(0));
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,8 @@ pub enum HRow {
|
||||
Graphics(Item, Cost, &'static str),
|
||||
/// One of Horizon's extras (`extras`), off by default.
|
||||
Extra(extras::Item),
|
||||
/// Installed mod `i` (`settings.mods.installed`) and its switch.
|
||||
Mod(usize),
|
||||
}
|
||||
/// A sidebar section: name, description, rows.
|
||||
pub struct Section {
|
||||
@@ -184,6 +186,18 @@ pub const SECTIONS: &[Section] = &[
|
||||
.collect()
|
||||
},
|
||||
},
|
||||
Section {
|
||||
name: "Mods",
|
||||
blurb: "Mods made for Horizon, from the horizon-mods folder. Each runs in a sandbox and stays off until you turn it on; check what it may do first.",
|
||||
rows: |s| {
|
||||
if s.mods.installed.is_empty() {
|
||||
return vec![HRow::Header(
|
||||
"No mods: put .hmod files in the horizon-mods folder",
|
||||
)];
|
||||
}
|
||||
(0..s.mods.installed.len()).map(HRow::Mod).collect()
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const NAV: u64 = id("options.nav", 0);
|
||||
@@ -405,6 +419,20 @@ impl OptionsUi {
|
||||
);
|
||||
}
|
||||
}
|
||||
HRow::Mod(m) => {
|
||||
let installed = &s.mods.installed[m];
|
||||
let cost = match (&installed.problem, installed.dev) {
|
||||
(Some(_), _) => (3, "Stopped"),
|
||||
(None, true) => (1, "Dev"),
|
||||
(None, false) => (0, ""),
|
||||
};
|
||||
let text = installed
|
||||
.problem
|
||||
.as_deref()
|
||||
.unwrap_or(&installed.description);
|
||||
ui.described_row(x, y, &installed.title, "", 0.0, cost, text, cw - 60.0);
|
||||
ui.switch(ROW + i as u64, control_x, y + ROW_H / 2.0, s.mods.is_on(m));
|
||||
}
|
||||
HRow::Extra(item) => {
|
||||
let cy = y + ROW_H / 2.0;
|
||||
let id = ROW + i as u64;
|
||||
@@ -609,6 +637,10 @@ impl OptionsUi {
|
||||
item.cycle(&mut s.extras, right);
|
||||
events.push(Event::Changed);
|
||||
}
|
||||
Some(HRow::Mod(m)) => {
|
||||
s.mods.toggle(*m);
|
||||
events.push(Event::Changed);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,6 +181,8 @@ pub struct Settings {
|
||||
pub controller: crate::gamepad::PadSettings,
|
||||
/// Horizon's optional extras (`horizon-extras.txt`), all off by default.
|
||||
pub extras: crate::extras::Extras,
|
||||
/// The Horizon mods turned on (`horizon-mods.txt`), all off by default.
|
||||
pub mods: crate::mod_list::ModList,
|
||||
}
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
@@ -252,6 +254,7 @@ impl Default for Settings {
|
||||
horizon: Default::default(),
|
||||
controller: Default::default(),
|
||||
extras: Default::default(),
|
||||
mods: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -300,17 +303,23 @@ impl Settings {
|
||||
.parent()
|
||||
.map(crate::extras::Extras::load)
|
||||
.unwrap_or_default();
|
||||
let mods = path
|
||||
.parent()
|
||||
.map(crate::mod_list::ModList::load)
|
||||
.unwrap_or_default();
|
||||
let settings = match fs::read(path) {
|
||||
Ok(bytes) => Self {
|
||||
horizon,
|
||||
controller,
|
||||
extras,
|
||||
mods,
|
||||
..Self::parse(&String::from_utf8_lossy(&bytes))
|
||||
},
|
||||
Err(_) => Self {
|
||||
horizon,
|
||||
controller,
|
||||
extras,
|
||||
mods,
|
||||
..Self::default()
|
||||
},
|
||||
};
|
||||
@@ -411,6 +420,7 @@ impl Settings {
|
||||
horizon: Default::default(),
|
||||
controller: Default::default(),
|
||||
extras: Default::default(),
|
||||
mods: Default::default(),
|
||||
auto_jump: f.bool("autoJump"),
|
||||
language: f.string("lang"),
|
||||
force_unicode: f.bool("forceUnicodeFont"),
|
||||
@@ -545,6 +555,7 @@ impl Settings {
|
||||
self.horizon.save(dir);
|
||||
self.controller.save(dir);
|
||||
self.extras.save(dir);
|
||||
self.mods.save(dir);
|
||||
}
|
||||
}
|
||||
/// Volume of a sound source (master excluded).
|
||||
|
||||
Reference in New Issue
Block a user