diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 48a7f8f04..641aa8044 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -25,6 +25,7 @@ use horizon_client::{ sprint::Keys, streaming::{Streaming, WorkerContext}, save::{Level, Persistent, SaveDir}, + settings::Settings, title::{Action, Title}, testgen::TestTerrain, vanillagen::VanillaTerrain, @@ -49,6 +50,7 @@ use winit::{ struct Options { resources: PathBuf, distance: i32, + distance_override: Option, seed: i64, creative: bool, test_terrain: bool, @@ -73,6 +75,7 @@ impl Options { PathBuf::from(".local/horizon-client/26.3") }, distance: 12, + distance_override: None, seed: 0, creative: false, test_terrain: false, @@ -101,6 +104,7 @@ impl Options { "--resources" => o.resources = value.into(), "--render-distance" | "--radius" => { o.distance = value.parse()?; + o.distance_override = Some(o.distance); if !(2..=64).contains(&o.distance) { return Err("render distance must be 2..64".into()); } @@ -136,6 +140,7 @@ impl Options { enum Screen { Playing, Paused, + Options, Inventory, Dead, } @@ -249,6 +254,12 @@ struct Game<'a> { /// Main-hand equip height (previous, current) and the item it shows. hand_height: (f32, f32), hand_item: Option, + settings: Settings, + /// Where the options screen returns: true = title, false = pause menu. + options_from_title: bool, + dragging: bool, + walk: (f32, f32), + bob: (f32, f32), } fn view_vector(yaw: f32, pitch: f32) -> [f64; 3] { let (y, p) = (f64::from(yaw).to_radians(), f64::from(pitch).to_radians()); @@ -1084,6 +1095,16 @@ impl Game<'_> { self.tick_mobs()?; self.tick_experience(); self.tick_hand(); + if let Some(p) = &self.player { + // Player.aiStep bob and Entity.walkDist (0.6 per block). + let (dx, dz) = (p.position.x - self.previous_position.x, p.position.z - self.previous_position.z); + let speed = ((dx * dx + dz * dz).sqrt() as f32).min(0.1); + self.walk.0 = self.walk.1; + self.walk.1 += (dx * dx + dz * dz).sqrt() as f32 * 0.6; + self.bob.0 = self.bob.1; + let target = if p.ground.on_ground && !p.health.dead_or_dying() { speed } else { 0.0 }; + self.bob.1 += (target - self.bob.1) * 0.4; + } self.tick_block_entities()?; let facts = &self.res.facts; let world = &self.world; @@ -1244,6 +1265,10 @@ impl Game<'_> { fn hud(&mut self, size: [u32; 2]) -> HudBatch { let mut batch = HudBatch::new(size); let (w, h) = (batch.width, batch.height); + if self.screen == Screen::Options { + self.settings.draw(&self.res.atlas, &mut batch, self.cursor); + return batch; + } if let Some(title) = &self.title { title.draw(&self.res.atlas, &mut batch, self.cursor); return batch; @@ -1366,7 +1391,7 @@ impl Game<'_> { let title = "Game Menu"; let tw = HudBatch::text_width(atlas, title); batch.text(atlas, title, (w - tw) / 2.0, 40.0, u32::MAX, true); - for (i, label) in ["Back to Game", "Save and Quit to Title"].iter().enumerate() { + for (i, label) in ["Back to Game", "Options...", "Save and Quit to Title"].iter().enumerate() { let (bx, by) = (w / 2.0 - 100.0, h / 4.0 + 24.0 + i as f32 * 24.0 + 16.0); let hover = self.cursor.0 >= bx && self.cursor.0 < bx + 200.0 && self.cursor.1 >= by && self.cursor.1 < by + 20.0; let sprite = if hover { "gui/sprites/widget/button_highlighted" } else { "gui/sprites/widget/button" }; @@ -1389,7 +1414,7 @@ impl Game<'_> { Screen::Inventory => { self.draw_inventory(&mut batch); } - Screen::Playing => {} + Screen::Playing | Screen::Options => {} } batch } @@ -2519,7 +2544,7 @@ impl Game<'_> { })?); Streaming::new(Arc::new(Persistent { inner, save: save.clone(), registry: res.assets.clone(), biomes: res.biomes.clone() }), res.context.clone(), res.threads) }; - streaming.radius = self.options.distance; + streaming.radius = self.settings.render_distance; let mut world = World::new(self.res.facts.air, level.seed); world.game_time = level.time; world.day_time = self.options.time.unwrap_or(level.day_time); @@ -2565,6 +2590,7 @@ impl Game<'_> { if let Some(r) = self.renderer.as_mut() { r.clear_sections(); } + self.apply_settings(); // New worlds get their level.dat right away. if !save_root.join("level.dat").exists() { self.level.write(&save_root)?; @@ -3119,6 +3145,11 @@ impl Game<'_> { } out } + fn apply_settings(&mut self) { + self.streaming.radius = self.settings.render_distance; + self.audio.master = self.settings.master_volume; + horizon_client::hud::GUI_SCALE.store(self.settings.gui_scale, std::sync::atomic::Ordering::Relaxed); + } fn save_game(&mut self) -> Result<()> { let keys: Vec<_> = self.world.modified.drain().collect(); let chunks: Vec<_> = keys @@ -3215,7 +3246,11 @@ impl Game<'_> { camera, yaw, pitch, - fov_degrees: if title { 85.0 } else { 70.0 }, + fov_degrees: if title { 85.0 } else { self.settings.fov }, + bob: (self.settings.view_bobbing && !title && self.player.is_some()).then(|| { + let a = alpha as f32; + (self.walk.0 + (self.walk.1 - self.walk.0) * a, self.bob.0 + (self.bob.1 - self.bob.0) * a) + }), sky, distance: (self.streaming.radius * 16) as f32, underwater, @@ -3331,8 +3366,12 @@ impl ApplicationHandler for Game<'_> { } WindowEvent::CursorMoved { position, .. } => { if let Some(r) = &self.renderer { - let scale = HudBatch::new([r.config.width, r.config.height]).scale; - self.cursor = (position.x as f32 / scale, position.y as f32 / scale); + let b = HudBatch::new([r.config.width, r.config.height]); + self.cursor = (position.x as f32 / b.scale, position.y as f32 / b.scale); + if self.dragging && self.screen == Screen::Options { + self.settings.click(self.cursor.0, self.cursor.1, (b.width, b.height), true); + self.apply_settings(); + } } } WindowEvent::MouseWheel { delta, .. } => { @@ -3344,6 +3383,19 @@ impl ApplicationHandler for Game<'_> { self.selected = (self.selected as i32 - d.signum() as i32).rem_euclid(9) as usize; } } + WindowEvent::MouseInput { state, button: MouseButton::Left, .. } if self.screen == Screen::Options => { + self.dragging = state == ElementState::Pressed; + if self.dragging { + let size = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]).unwrap_or([1, 1]); + let b = HudBatch::new(size); + if self.settings.click(self.cursor.0, self.cursor.1, (b.width, b.height), false) { + self.settings.save(&std::env::current_dir()?.join("options.txt")); + self.screen = if self.options_from_title { Screen::Playing } else { Screen::Paused }; + self.dragging = false; + } + self.apply_settings(); + } + } WindowEvent::MouseInput { state, button: MouseButton::Left, .. } if self.title.is_some() && state == ElementState::Pressed => { @@ -3352,6 +3404,10 @@ impl ApplicationHandler for Game<'_> { let action = self.title.as_mut().map_or(Action::None, |t| t.click(self.cursor.0, self.cursor.1, (b.width, b.height))); match action { Action::Quit => event_loop.exit(), + Action::Options => { + self.screen = Screen::Options; + self.options_from_title = true; + } Action::Play { folder } => self.open_world(&folder, None, None, false)?, Action::Create { folder, name, seed, creative } => self.open_world(&folder, Some(&name), seed, creative)?, Action::None => {} @@ -3401,12 +3457,15 @@ impl ApplicationHandler for Game<'_> { Screen::Paused if pressed => { let size = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]).unwrap_or([1, 1]); let b = HudBatch::new(size); - for i in 0..2 { + for i in 0..3 { let (bx, by) = (b.width / 2.0 - 100.0, b.height / 4.0 + 24.0 + i as f32 * 24.0 + 16.0); if self.cursor.0 >= bx && self.cursor.0 < bx + 200.0 && self.cursor.1 >= by && self.cursor.1 < by + 20.0 { if i == 0 { self.screen = Screen::Playing; self.capture(true); + } else if i == 1 { + self.screen = Screen::Options; + self.options_from_title = false; } else { self.close_world()?; } @@ -3450,6 +3509,10 @@ impl ApplicationHandler for Game<'_> { } match key { KeyCode::Escape => match self.screen { + Screen::Options => { + self.settings.save(&std::env::current_dir()?.join("options.txt")); + self.screen = if self.options_from_title { Screen::Playing } else { Screen::Paused }; + } Screen::Playing => { self.screen = Screen::Paused; self.capture(false); @@ -3542,7 +3605,7 @@ impl ApplicationHandler for Game<'_> { && let DeviceEvent::MouseMotion { delta: (x, y) } = event { // MouseHandler.turnPlayer at default sensitivity 0.5: 0.15 degrees per count. - let s = 0.5_f64 * 0.6 + 0.2; + let s = f64::from(self.settings.sensitivity) * 0.6 + 0.2; let f = s * s * s * 8.0; self.yaw += (x * f * 0.15) as f32; self.pitch = (self.pitch + (y * f * 0.15) as f32).clamp(-90.0, 90.0); @@ -3643,6 +3706,10 @@ pub fn run() -> Result<()> { }; let inventory = vec![None; 36]; let now = Instant::now(); + let mut settings = Settings::load(&std::env::current_dir()?.join("options.txt")); + if let Some(d) = options.distance_override { + settings.render_distance = d; + } let look = options.look; let mut game = Game { res: &mut resources, @@ -3713,6 +3780,11 @@ pub fn run() -> Result<()> { swing_anim: (0.0, 0.0), hand_height: (1.0, 1.0), hand_item: None, + settings, + options_from_title: false, + dragging: false, + walk: (0.0, 0.0), + bob: (0.0, 0.0), }; match game.options.world.clone() { Some(folder) => { diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 5a1477367..a960dfc4f 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -36,6 +36,8 @@ pub struct Frame<'a> { pub yaw: f32, pub pitch: f32, pub fov_degrees: f32, + /// GameRenderer.bobView: (walk distance, bob amount), interpolated. + pub bob: Option<(f32, f32)>, pub sky: Sky, /// Render distance in blocks (fog end). pub distance: f32, @@ -814,7 +816,14 @@ impl Renderer { // Minecraft yaw: 0 = +Z (south), 90 = -X (west); pitch positive looks down. let forward = Vec3::new(-yaw.sin() * pitch.cos(), -pitch.sin(), yaw.cos() * pitch.cos()); let far = (frame.distance * 4.0).max(1024.0); + let bob = frame.bob.map_or(Mat4::IDENTITY, |(walk, bob)| { + let f = -walk * std::f32::consts::PI; + Mat4::from_translation(Vec3::new(f.sin() * bob * 0.5, -(f.cos() * bob).abs(), 0.0)) + * Mat4::from_rotation_z((f.sin() * bob * 3.0).to_radians()) + * Mat4::from_rotation_x(((f - 0.2).cos() * bob).abs().mul_add(5.0, 0.0).to_radians()) + }); Mat4::perspective_rh(frame.fov_degrees.to_radians(), aspect, 0.05, far) + * bob * Mat4::look_to_rh(Vec3::ZERO, forward, Vec3::Y) } fn update_lightmap(&self, sky: &Sky, darkness: f32, gamma: f32) { diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 1dd19c3fc..fa6a0f20e 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -245,6 +245,8 @@ pub struct HudVertex { pub uv: [f32; 2], pub color: u32, } +/// The GUI Scale option (0 = auto). +pub static GUI_SCALE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); /// One frame of overlay geometry in GUI pixels. pub struct HudBatch { pub vertices: Vec, @@ -256,10 +258,12 @@ pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> u32 { u32::from(a) << 24 | u32::from(b) << 16 | u32::from(g) << 8 | u32::from(r) } impl HudBatch { - /// Vanilla's automatic GUI scale: the largest scale keeping >= 320x240 GUI pixels. + /// Window.calculateScale: the largest scale keeping >= 320x240 GUI pixels, + /// capped by the GUI Scale option (0 = auto). pub fn new(window: [u32; 2]) -> Self { + let limit = GUI_SCALE.load(std::sync::atomic::Ordering::Relaxed); let mut scale = 1; - while window[0] / (scale + 1) >= 320 && window[1] / (scale + 1) >= 240 { + while (limit == 0 || scale < limit) && window[0] / (scale + 1) >= 320 && window[1] / (scale + 1) >= 240 { scale += 1; } Self { diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index e83d1a3c4..eafe22a77 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -28,6 +28,7 @@ pub mod motion; pub mod particles; pub mod pose; pub mod save; +pub mod settings; pub mod sprint; pub mod sprites; pub mod streaming; diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs new file mode 100644 index 000000000..55a729382 --- /dev/null +++ b/crates/horizon-client/src/settings.rs @@ -0,0 +1,128 @@ +//! Player settings persisted in `options.txt` with vanilla's keys, and the +//! options screen (sliders and toggles in OptionsScreen's two-column layout). +use crate::hud::{HudAtlas, HudBatch, rgba}; +use std::{fs, path::Path}; + +#[derive(Clone, Debug)] +pub struct Settings { + /// Degrees, 30..=110 (vanilla stores the slider value). + pub fov: f32, + /// Chunks, 2..=32. + pub render_distance: i32, + /// 0..1, vanilla default 0.5. + pub sensitivity: f32, + /// 0..1. + pub master_volume: f32, + /// 0 = auto. + pub gui_scale: u32, + pub view_bobbing: bool, +} +impl Default for Settings { + fn default() -> Self { + Self { fov: 70.0, render_distance: 12, sensitivity: 0.5, master_volume: 1.0, gui_scale: 0, view_bobbing: true } + } +} +impl Settings { + pub fn load(path: &Path) -> Self { + let mut s = Self::default(); + let Ok(text) = fs::read_to_string(path) else { return s }; + for line in text.lines() { + let Some((k, v)) = line.split_once(':') else { continue }; + match k { + // Options.fov is stored as (fov - 70) / 40. + "fov" => s.fov = v.parse::().map_or(70.0, |f| (70.0 + f * 40.0).clamp(30.0, 110.0)), + "renderDistance" => s.render_distance = v.parse().unwrap_or(12).clamp(2, 32), + "mouseSensitivity" => s.sensitivity = v.parse().unwrap_or(0.5f32).clamp(0.0, 1.0), + "soundCategory_master" => s.master_volume = v.parse().unwrap_or(1.0f32).clamp(0.0, 1.0), + "guiScale" => s.gui_scale = v.parse().unwrap_or(0), + "bobView" => s.view_bobbing = v == "true", + _ => {} + } + } + s + } + pub fn save(&self, path: &Path) { + let text = format!( + "version:4793\nfov:{}\nrenderDistance:{}\nmouseSensitivity:{}\nsoundCategory_master:{}\nguiScale:{}\nbobView:{}\n", + (self.fov - 70.0) / 40.0, + self.render_distance, + self.sensitivity, + self.master_volume, + self.gui_scale, + self.view_bobbing + ); + let _ = fs::write(path, text); + } + fn rows(&self) -> Vec<(String, Option)> { + vec![ + (format!("FOV: {}", if self.fov.round() == 70.0 { "Normal".into() } else if self.fov >= 110.0 { "Quake Pro".into() } else { format!("{:.0}", self.fov) }), Some((self.fov - 30.0) / 80.0)), + (format!("Render Distance: {} chunks", self.render_distance), Some((self.render_distance - 2) as f32 / 30.0)), + (format!("Sensitivity: {}", if self.sensitivity == 0.0 { "*yawn*".into() } else if self.sensitivity >= 1.0 { "HYPERSPEED!!!".into() } else { format!("{:.0}%", self.sensitivity * 200.0) }), Some(self.sensitivity)), + (format!("Master Volume: {}", if self.master_volume == 0.0 { "OFF".into() } else { format!("{:.0}%", self.master_volume * 100.0) }), Some(self.master_volume)), + (format!("GUI Scale: {}", if self.gui_scale == 0 { "Auto".into() } else { self.gui_scale.to_string() }), None), + (format!("View Bobbing: {}", if self.view_bobbing { "ON" } else { "OFF" }), None), + ] + } + fn layout(w: f32, i: usize) -> (f32, f32) { + (w / 2.0 - 155.0 + (i % 2) as f32 * 160.0, 48.0 + (i / 2) as f32 * 24.0) + } + pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, cursor: (f32, f32)) { + let (w, h) = (batch.width, batch.height); + batch.fill(atlas, 0.0, 0.0, w, h, rgba(0, 0, 0, 150)); + let title = "Options"; + let tw = HudBatch::text_width(atlas, title); + batch.text(atlas, title, (w - tw) / 2.0, 15.0, u32::MAX, true); + let mut rows = self.rows(); + rows.push(("Done".into(), None)); + for (i, (label, slider)) in rows.iter().enumerate() { + let (x, y) = if i == rows.len() - 1 { (w / 2.0 - 100.0, h / 6.0 + 168.0) } else { Self::layout(w, i) }; + let width = if i == rows.len() - 1 { 200.0 } else { 150.0 }; + let hover = cursor.0 >= x && cursor.0 < x + width && cursor.1 >= y && cursor.1 < y + 20.0; + let sprite = match (slider, hover) { + (Some(_), _) => "gui/sprites/widget/slider", + (None, true) => "gui/sprites/widget/button_highlighted", + (None, false) => "gui/sprites/widget/button", + }; + if let Some(r) = atlas.sprites.get(sprite).copied() { + let half = width / 2.0; + let mut left = r; + left.u1 = r.u0 + (r.u1 - r.u0) * (half / r.w as f32); + batch.rect_uv(x, y, half, 20.0, left, u32::MAX); + let mut right = r; + right.u0 = r.u1 - (r.u1 - r.u0) * (half / r.w as f32); + batch.rect_uv(x + half, y, half, 20.0, right, u32::MAX); + } + if let Some(v) = slider { + let handle = if hover { "gui/sprites/widget/slider_handle_highlighted" } else { "gui/sprites/widget/slider_handle" }; + batch.sprite_scaled(atlas, handle, x + v.clamp(0.0, 1.0) * (width - 8.0), y, 8.0, 20.0, u32::MAX); + } + let tw = HudBatch::text_width(atlas, label); + batch.text(atlas, label, x + (width - tw) / 2.0, y + 6.0, u32::MAX, true); + } + } + /// Handle a click or drag; returns true when Done was pressed. + pub fn click(&mut self, x: f32, y: f32, size: (f32, f32), drag: bool) -> bool { + let (w, h) = size; + let rows = self.rows().len(); + if !drag && x >= w / 2.0 - 100.0 && x < w / 2.0 + 100.0 && y >= h / 6.0 + 168.0 && y < h / 6.0 + 188.0 { + return true; + } + for i in 0..rows { + let (bx, by) = Self::layout(w, i); + if !(x >= bx && x < bx + 150.0 && y >= by && y < by + 20.0) { + continue; + } + let v = ((x - bx - 4.0) / 142.0).clamp(0.0, 1.0); + match i { + 0 => self.fov = (30.0 + v * 80.0).round(), + 1 => self.render_distance = 2 + (v * 30.0).round() as i32, + 2 => self.sensitivity = (v * 100.0).round() / 100.0, + 3 => self.master_volume = (v * 100.0).round() / 100.0, + 4 if !drag => self.gui_scale = (self.gui_scale + 1) % 5, + 5 if !drag => self.view_bobbing = !self.view_bobbing, + _ => {} + } + } + false + } +} diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index e20159e21..ba53902ea 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -23,6 +23,7 @@ pub enum Mode { pub enum Action { None, Quit, + Options, Play { folder: String }, Create { folder: String, name: String, seed: Option, creative: bool }, } @@ -80,7 +81,7 @@ impl Title { b(w / 2.0 - 100.0, y, 200.0, "Singleplayer", true, 1), b(w / 2.0 - 100.0, y + 24.0, 200.0, "Multiplayer", false, 0), b(w / 2.0 - 100.0, y + 48.0, 200.0, "Minecraft Realms", false, 0), - b(w / 2.0 - 100.0, y + 84.0, 98.0, "Options...", false, 0), + b(w / 2.0 - 100.0, y + 84.0, 98.0, "Options...", true, 3), b(w / 2.0 + 2.0, y + 84.0, 98.0, "Quit Game", true, 2), ] } @@ -192,6 +193,7 @@ impl Title { Action::None } (Mode::Main, Some(2)) => Action::Quit, + (Mode::Main, Some(3)) => Action::Options, (Mode::Select { worlds, selected }, Some(10)) => match selected.and_then(|i| worlds.get(i)) { Some(world) => Action::Play { folder: world.folder.clone() }, None => Action::None,