diff --git a/crates/horizon-client/src/fog.rs b/crates/horizon-client/src/fog.rs index 4146de4f6..dffcf7280 100644 --- a/crates/horizon-client/src/fog.rs +++ b/crates/horizon-client/src/fog.rs @@ -68,8 +68,30 @@ pub struct FogState { pub water_vision_time: i32, /// `AtmosphericFogEnvironment.rainFogMultiplier`. pub rain_fog_multiplier: f32, + /// `LightmapRenderStateExtractor.blockLightFlicker`. + pub block_light_flicker: f32, + flicker_seed: u64, } impl FogState { + fn next_float(&mut self) -> f32 { + // splitmix64: the vanilla source is unseeded `RandomSource.create()`. + self.flicker_seed = self.flicker_seed.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.flicker_seed; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + ((z ^ (z >> 31)) >> 40) as f32 / (1u32 << 24) as f32 + } + /// `LightmapRenderStateExtractor.tick`: the torch light flickers. + pub fn tick_flicker(&mut self) { + let (a, b, c, d) = ( + self.next_float(), + self.next_float(), + self.next_float(), + self.next_float(), + ); + self.block_light_flicker += (a - b) * c * d * 0.1; + self.block_light_flicker *= 0.9; + } /// `LocalPlayer.aiStep`: water vision ramps up while the eye is in water. pub fn tick(&mut self, eye_in_water: bool) { self.water_vision_time = if eye_in_water { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 882905617..5c1422098 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -32,6 +32,7 @@ mod functions; mod game_mode; mod golems; mod growth; +mod health_hud; mod jukebox; mod lightning; mod loom; @@ -525,6 +526,7 @@ struct Game<'a> { fps_frames: u64, fps_at: Instant, ticks: u64, + health_hud: health_hud::HealthHud, error: Option, message: Option<(String, Instant)>, save: Arc, @@ -2928,7 +2930,7 @@ impl Game<'_> { let atlas = &self.res.atlas; if !self.creative && !spectator - && let Some(p) = &self.player + && let Some(p) = &mut self.player { // Experience bar and hearts/food (Gui.renderPlayerHealth). let saddled_mount = mounted @@ -2964,33 +2966,37 @@ impl Game<'_> { } batch.text(atlas, &text, x, y, rgba(128, 255, 32, 255), false); } - let health = p.health.health().ceil() as i32; - let top = h - 39.0; - for i in 0..10 { - let x = w / 2.0 - 91.0 + i as f32 * 8.0; - let y = if health <= 4 { - top + ((self.ticks + i as u64 * 7) % 3) as f32 - 1.0 - } else { - top - }; - batch.sprite(atlas, "gui/sprites/hud/heart/container", x, y); - let v = health - i * 2; - if v >= 2 { - batch.sprite(atlas, "gui/sprites/hud/heart/full", x, y); - } else if v == 1 { - batch.sprite(atlas, "gui/sprites/hud/heart/half", x, y); - } - } - let food = p.health.food.food; - for i in (0..10).filter(|_| !mounted) { - let x = w / 2.0 + 91.0 - i as f32 * 8.0 - 9.0; - batch.sprite(atlas, "gui/sprites/hud/food_empty", x, top); - let v = food - i * 2; - if v >= 2 { - batch.sprite(atlas, "gui/sprites/hud/food_full", x, top); - } else if v == 1 { - batch.sprite(atlas, "gui/sprites/hud/food_half", x, top); - } + let effects = &self.potions.effects; + let kind = if effects.get("poison").is_some() { + health_hud::HeartKind::Poisoned + } else if effects.get("wither").is_some() { + health_hud::HeartKind::Withered + } else { + health_hud::HeartKind::Normal + }; + let inputs = health_hud::HealthInputs { + tick: self.ticks, + health: p.health.health(), + max_health: p.attribute("minecraft:max_health").unwrap_or(20.0) as f32, + absorption: p.health.absorption(), + armor: p + .attribute("minecraft:armor") + .or_else(|_| p.attribute("armor")) + .unwrap_or(0.0) as i32, + food: p.health.food.food, + saturation: p.health.food.saturation, + kind, + regeneration: effects.get("regeneration").is_some(), + hunger: effects.get("hunger").is_some(), + hardcore: self.level.hardcore, + damage_cooldown: p.health.hurt.cooldown > 0, + show_food: !mounted, + }; + for (name, x, y) in + self.health_hud + .layout(&inputs, w as i32, h as i32, std::time::Instant::now()) + { + batch.sprite(atlas, &name, x as f32, y as f32); } } if self.debug { @@ -4220,10 +4226,13 @@ impl Game<'_> { return 11; } if self.dim == Dim::End { - let sky = self.res.end_environment.sample(self.world.day_time, 0, 0); + let sky = self + .res + .end_environment + .sample(self.world.day_time, None, None); return (15.0 - 15.0 * sky.sky_light_level).round() as i32; } - let mut sky = self.res.environment.sample(self.world.day_time, 0, 0); + let mut sky = self.res.environment.sample(self.world.day_time, None, None); let (rain, thunder) = self.world.weather.levels(1.0); horizon_client::environment::apply_weather(&mut sky, rain, thunder); // Level.updateSkyBrightness: darkening from the sky light level. @@ -6923,6 +6932,8 @@ impl Game<'_> { game_time: self.world.game_time as f32, ticks: self.ticks, darkness: self.darkness_lighting(alpha as f32), + night_vision: self.night_vision_intensity(), + block_flicker: self.res.fog.state.block_light_flicker, }; self.renderer.as_mut().ok_or("renderer")?.render(&frame) } @@ -7749,6 +7760,7 @@ pub fn run() -> Result<()> { screen: Screen::Playing, window: None, renderer: None, + health_hud: health_hud::HealthHud::default(), started: now, previous: now, frames: 0, diff --git a/crates/horizon-client/src/game/health_hud.rs b/crates/horizon-client/src/game/health_hud.rs new file mode 100644 index 000000000..4e9aaee0a --- /dev/null +++ b/crates/horizon-client/src/game/health_hud.rs @@ -0,0 +1,226 @@ +//! `Hud.extractPlayerHealth`: armour, hearts, food. The layout is computed as +//! a list of sprites so it can be tested without drawing. +use std::time::Instant; + +/// `java.util.Random`, for the HUD's per-tick jitter. +pub(super) struct JavaRandom(i64); +impl JavaRandom { + pub fn new(seed: i64) -> Self { + Self((seed ^ 0x5_DEEC_E66D) & ((1 << 48) - 1)) + } + fn next(&mut self, bits: u32) -> i32 { + self.0 = (self.0.wrapping_mul(0x5_DEEC_E66D).wrapping_add(0xB)) & ((1 << 48) - 1); + (self.0 >> (48 - bits)) as i32 + } + pub fn next_int(&mut self, bound: i32) -> i32 { + let mut r = self.next(31); + let m = bound - 1; + if bound & m == 0 { + return ((i64::from(bound) * i64::from(r)) >> 31) as i32; + } + let mut u = r; + loop { + r = u % bound; + if u.wrapping_sub(r).wrapping_add(m) >= 0 { + return r; + } + u = self.next(31); + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum HeartKind { + Normal, + Poisoned, + Withered, + Absorbing, +} +impl HeartKind { + fn prefix(self) -> &'static str { + match self { + Self::Normal => "", + Self::Poisoned => "poisoned_", + Self::Withered => "withered_", + Self::Absorbing => "absorbing_", + } + } +} + +/// State kept between frames (`Hud.lastHealth`, `displayHealth`, ...). +pub(super) struct HealthHud { + last_health: i32, + display_health: i32, + last_health_time: Instant, + health_blink_time: i64, +} +impl Default for HealthHud { + fn default() -> Self { + Self { + last_health: 0, + display_health: 0, + last_health_time: Instant::now(), + health_blink_time: 0, + } + } +} + +pub(super) struct HealthInputs { + pub tick: u64, + pub health: f32, + pub max_health: f32, + pub absorption: f32, + pub armor: i32, + pub food: i32, + pub saturation: f32, + pub kind: HeartKind, + pub regeneration: bool, + pub hunger: bool, + pub hardcore: bool, + /// `damageCooldownTime > 0`. + pub damage_cooldown: bool, + /// A mount with its own hearts replaces the food bar. + pub show_food: bool, +} + +fn heart_sprite(kind: HeartKind, hardcore: bool, half: bool, blink: bool) -> String { + let (hc, h) = ( + if hardcore { "hardcore_" } else { "" }, + if half { "half" } else { "full" }, + ); + let b = if blink { "_blinking" } else { "" }; + format!("gui/sprites/hud/heart/{}{hc}{h}{b}", kind.prefix()) +} + +impl HealthHud { + /// Sprites (name, x, y) in draw order for a screen of `w` x `h` GUI pixels. + pub fn layout( + &mut self, + i: &HealthInputs, + w: i32, + h: i32, + now: Instant, + ) -> Vec<(String, i32, i32)> { + let mut out = Vec::new(); + let tick = i64::try_from(i.tick).unwrap_or(i64::MAX); + let current = i.health.ceil() as i32; + let blink = self.health_blink_time > tick && (self.health_blink_time - tick) / 3 % 2 == 1; + if current < self.last_health && i.damage_cooldown { + self.last_health_time = now; + self.health_blink_time = tick + 20; + } else if current > self.last_health && i.damage_cooldown { + self.last_health_time = now; + self.health_blink_time = tick + 10; + } + if now.duration_since(self.last_health_time).as_millis() > 1000 { + self.display_health = current; + self.last_health_time = now; + } + self.last_health = current; + let old = self.display_health; + let mut random = JavaRandom::new(i64::from((i.tick as i32).wrapping_mul(312_871))); + let (x_left, x_right, y_base) = (w / 2 - 91, w / 2 + 91, h - 39); + let max_health = i.max_health.max(old.max(current) as f32); + let absorption = i.absorption.ceil() as i32; + let rows = ((max_health + absorption as f32) / 2.0 / 10.0).ceil() as i32; + let row_height = (10 - (rows - 2)).max(3); + let offset_index = if i.regeneration { + (i.tick as i32).rem_euclid((max_health + 5.0).ceil() as i32) + } else { + -1 + }; + if i.armor > 0 { + let y = y_base - (rows - 1) * row_height - 10; + for n in 0..10 { + let name = match (n * 2 + 1).cmp(&i.armor) { + std::cmp::Ordering::Less => "armor_full", + std::cmp::Ordering::Equal => "armor_half", + std::cmp::Ordering::Greater => "armor_empty", + }; + out.push((format!("gui/sprites/hud/{name}"), x_left + n * 8, y)); + } + } + let containers = (max_health / 2.0).ceil() as i32; + let absorb_containers = (absorption as f32 / 2.0).ceil() as i32; + let container = |hardcore: bool, blink: bool| { + format!( + "gui/sprites/hud/heart/container{}{}", + if hardcore { "_hardcore" } else { "" }, + if blink { "_blinking" } else { "" } + ) + }; + for c in (0..containers + absorb_containers).rev() { + let (row, column) = (c / 10, c % 10); + let x = x_left + column * 8; + let mut y = y_base - row * row_height; + if current + absorption <= 4 { + y += random.next_int(2); + } + if c < containers && c == offset_index { + y -= 2; + } + out.push((container(i.hardcore, blink), x, y)); + let halves = c * 2; + if c >= containers { + let ah = halves - containers * 2; + if ah < absorption { + let kind = if i.kind == HeartKind::Withered { + i.kind + } else { + HeartKind::Absorbing + }; + out.push(( + heart_sprite(kind, i.hardcore, ah + 1 == absorption, false), + x, + y, + )); + } + } + if blink && halves < old { + out.push(( + heart_sprite(i.kind, i.hardcore, halves + 1 == old, true), + x, + y, + )); + } + if halves < current { + out.push(( + heart_sprite(i.kind, i.hardcore, halves + 1 == current, false), + x, + y, + )); + } + } + if i.show_food { + let suffix = if i.hunger { "_hunger" } else { "" }; + for n in 0..10 { + let mut y = y_base; + if i.saturation <= 0.0 && (i.tick as i32).rem_euclid(i.food * 3 + 1) == 0 { + y += random.next_int(3) - 1; + } + let x = x_right - n * 8 - 9; + out.push((format!("gui/sprites/hud/food_empty{suffix}"), x, y)); + if n * 2 + 1 < i.food { + out.push((format!("gui/sprites/hud/food_full{suffix}"), x, y)); + } + if n * 2 + 1 == i.food { + out.push((format!("gui/sprites/hud/food_half{suffix}"), x, y)); + } + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn java_random_matches_reference() { + // new Random(42).nextInt(10) sequence: 0, 3, 8, 4, 0. + let mut r = JavaRandom::new(42); + let v: Vec = (0..5).map(|_| r.next_int(10)).collect(); + assert_eq!(v, [0, 3, 8, 4, 0]); + } +} diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index c13973e95..c7605f257 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -172,6 +172,7 @@ impl Game<'_> { lightmap_brightness(if self.dim == Dim::Nether { 0.1 } else { 0.0 }, raw) } pub(super) fn tick_particles(&mut self) { + self.res.fog.state.tick_flicker(); let eye = self.eye_position(); if let Some(e) = eye { let brightness = self.eye_brightness(e); diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index e2d985417..07fbfcfac 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -1096,6 +1096,29 @@ impl Game<'_> { (modifier, pulse.max(0.0)) } + /// `LightmapRenderStateExtractor`: the night vision effect's intensity + /// (`GameRenderer.nightVisionScale`), or conduit power's water vision. + pub(super) fn night_vision_intensity(&self) -> f32 { + use horizon_client::fog::FogType; + if let Some(e) = self.potions.effects.get("night_vision") { + // MobEffectInstance.endsWithin(200); -1 is infinite. + return if e.duration < 0 || e.duration > 200 { + 1.0 + } else { + 0.7 + (e.duration as f32 * std::f32::consts::PI * 0.2).sin() * 0.3 + }; + } + if self.potions.effects.get("conduit_power").is_some() + && let Some(eye) = self.eye_position() + { + let in_water = + horizon_client::fog::fog_type(&self.world, &self.res.facts, eye, self.forward()) + == FogType::Water; + return self.res.fog.state.water_vision(in_water); + } + 0.0 + } + /// `Warden.applyDarknessAround` / `MobEffectUtil.addEffectToPlayersAround`. pub(super) fn apply_darkness(&mut self, at: [f64; 3], radius: f64) { if self.creative || self.spectator() { diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index ce51c2475..d58550502 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -80,6 +80,10 @@ pub struct Frame<'a> { /// The darkness effect on the lightmap: the brightness it takes off the /// gamma option and the pulsing scale subtracted from the light. pub darkness: (f32, f32), + /// Night vision (or conduit water vision) intensity on the lightmap. + pub night_vision: f32, + /// Torch flicker added to the block light factor of 1.4. + pub block_flicker: f32, } pub struct Renderer { instance: wgpu::Instance, @@ -1077,7 +1081,14 @@ impl Renderer { * bob * Mat4::look_to_rh(Vec3::ZERO, forward, Vec3::Y) } - fn update_lightmap(&self, sky: &Sky, darkness: f32, gamma: f32) { + fn update_lightmap( + &self, + sky: &Sky, + darkness: f32, + gamma: f32, + night_vision: f32, + flicker: f32, + ) { // lightmap.fsh: per (block, sky) level. let brightness = |level: f32| level / (4.0 - 3.0 * level); let mut pixels = [0u8; 16 * 16 * 4]; @@ -1085,9 +1096,11 @@ impl Renderer { for b in 0..16 { let block_level = b as f32 / 15.0; let sky_level = s as f32 / 15.0; - let block_brightness = brightness(block_level) * 1.4; + let block_brightness = brightness(block_level) * (1.4 + flicker); let sky_brightness = brightness(sky_level) * sky.sky_light_factor; - let mut color = Vec3::from(sky.ambient_light_color); + // NightVisionColor defaults to 0x999999. + let mut color = + Vec3::from(sky.ambient_light_color).max(Vec3::splat(0.6 * night_vision)); color += Vec3::from(sky.sky_light_color) * sky_brightness; let parabolic = (2.0 * block_level - 1.0).powi(2); let block_color = Vec3::from(sky.block_light_tint).lerp(Vec3::ONE, 0.9 * parabolic); @@ -1193,6 +1206,8 @@ impl Renderer { &frame.sky, frame.darkness.1, (self.gamma - frame.darkness.0).max(0.0), + frame.night_vision, + frame.block_flicker, ); let view_proj = self.view_projection(frame); let aspect = self.config.width as f32 / self.config.height.max(1) as f32;