diff --git a/crates/horizon-client/examples/camera_probe.rs b/crates/horizon-client/examples/camera_probe.rs new file mode 100644 index 000000000..889c1020a --- /dev/null +++ b/crates/horizon-client/examples/camera_probe.rs @@ -0,0 +1,338 @@ +#![forbid(unsafe_code)] +//! Runs the JSON-lines scenarios of tools/test_camera_parity.py through the +//! Rust camera, field-of-view, avatar bob and view/hurt bobbing code. +use horizon_client::{ + Result, + camera::{ + AvatarBob, BobState, Camera, CameraEntity, CameraFluid, CameraType, FovPlayer, HurtBob, + LivingCamera, UseItem, bob_matrix, field_of_view_modifier, + }, +}; +use horizon_core::{ + geometry::{Aabb, ShapeOp, Vec3, VoxelShape}, + position::BlockPos, +}; +use horizon_world::world_ray::{RayBlockMode, RayFluidMode, RayWorld, clip_world}; +use serde_json::Value; +use std::{ + collections::HashMap, + convert::Infallible, + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, +}; + +fn fl(v: &Value) -> f32 { + f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) +} +fn db(v: &Value) -> f64 { + f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) +} +fn fb(v: f32) -> String { + format!("{:08x}", if v.is_nan() { 0x7fc0_0000 } else { v.to_bits() }) +} +fn dbs(v: f64) -> String { + format!( + "{:016x}", + if v.is_nan() { + 0x7ff8_0000_0000_0000 + } else { + v.to_bits() + } + ) +} +fn b(v: &Value) -> bool { + v.as_bool().unwrap() +} +fn vec3(v: &Value) -> [f64; 3] { + [db(&v[0]), db(&v[1]), db(&v[2])] +} + +fn fov_player(c: &Value) -> FovPlayer { + FovPlayer { + flying: b(&c["flying"]), + walking_speed: fl(&c["ws"]), + movement_speed: db(&c["speed"]), + using: c["use"].as_array().map(|u| { + let item = match u[0].as_str().unwrap() { + "bow" => UseItem::Bow, + "spyglass" => UseItem::Spyglass, + _ => UseItem::Other, + }; + (item, u[1].as_i64().unwrap() as i32) + }), + } +} + +/// A level of visual shapes keyed by cell, without fluids. +struct Cells { + shapes: Vec, + index: HashMap, +} +impl RayWorld for Cells { + type Error = Infallible; + type Block = usize; + type Fluid = (); + fn block_state(&mut self, p: BlockPos) -> std::result::Result { + Ok(self.index.get(&p).copied().unwrap_or(0)) + } + fn fluid_state(&mut self, _: BlockPos) -> std::result::Result<(), Infallible> { + Ok(()) + } + fn block_shape( + &mut self, + s: usize, + _: BlockPos, + _: RayBlockMode, + ) -> std::result::Result { + Ok(self.shapes[s].clone()) + } + fn interaction_shape(&mut self, _: usize, _: BlockPos) -> std::result::Result { + Ok(VoxelShape::empty()) + } + fn fluid_is_source(&mut self, _: ()) -> std::result::Result { + Ok(false) + } + fn fluid_is_empty(&mut self, _: ()) -> std::result::Result { + Ok(true) + } + fn fluid_is_water(&mut self, _: ()) -> std::result::Result { + Ok(false) + } + fn fluid_shape(&mut self, _: (), _: BlockPos) -> std::result::Result { + Ok(VoxelShape::empty()) + } +} + +fn cells(c: &Value) -> Result { + let mut world = Cells { + shapes: vec![VoxelShape::empty()], + index: HashMap::new(), + }; + for (key, boxes) in c["cells"].as_object().unwrap() { + let at: Vec = key.split(' ').map(|v| v.parse().unwrap()).collect(); + let mut shape = VoxelShape::empty(); + for a in boxes.as_array().unwrap() { + shape = shape.join( + &VoxelShape::from_box(Aabb::new( + Vec3::new(db(&a[0]), db(&a[1]), db(&a[2])), + Vec3::new(db(&a[3]), db(&a[4]), db(&a[5])), + ))?, + ShapeOp::OR, + )?; + } + world.index.insert(BlockPos::new(at[0], at[1], at[2]), world.shapes.len()); + world.shapes.push(shape); + } + Ok(world) +} + +fn camera_type(v: &Value) -> CameraType { + [ + CameraType::FirstPerson, + CameraType::ThirdPersonBack, + CameraType::ThirdPersonFront, + ][v.as_u64().unwrap() as usize] +} + +/// The camera entity and, for players, what the field of view reads. +fn entity(s: &Value) -> (CameraEntity, Option) { + let player = s["kind"] == "player"; + let living = player.then(|| LivingCamera { + scale: db(&s["scale_attr"]) as f32, + camera_distance: db(&s["dist"]), + sleeping: s["sleeping"].as_array().map(|a| { + a[0].as_u64() + .map(|d| [0.0f32, 90.0, 180.0, 270.0][d as usize]) + }), + dead: s["dead"].as_i64().map(|t| t as i32), + }); + let mount = if player { + s["mount"] + .as_array() + .map(|a| (db(&a[0]) as f32, db(&a[1]))) + } else { + None + }; + ( + CameraEntity { + position: vec3(&s["pos"]), + previous: vec3(&s["prev"]), + x_rot: fl(&s["xr"]), + y_rot: fl(&s["yr"]), + x_rot_o: fl(&s["xro"]), + y_rot_o: fl(&s["yro"]), + eye_height: fl(&s["eye"]), + living, + mount, + }, + player.then(|| fov_player(s)), + ) +} + +fn camera(c: &Value, out: &mut impl Write) -> Result<()> { + let mut world = cells(c)?; + let fov_option = c["fov"].as_i64().unwrap() as i32; + let effect = db(&c["effect"]) as f32; + let mut kind = camera_type(&c["type"]); + let mut camera = Camera::default(); + let mut current: Option<(CameraEntity, Option)> = None; + for op in c["ops"].as_array().unwrap() { + match op[0].as_str().unwrap() { + "entity" => { + current = Some(entity(&op[1])); + writeln!(out, "entity")?; + } + "type" => { + kind = camera_type(&op[1]); + writeln!(out, "type")?; + } + "tick" => { + let target = current + .as_ref() + .and_then(|(_, p)| p.as_ref()) + .map_or(1.0, |p| { + field_of_view_modifier(p, kind.is_first_person(), effect) + }); + camera.tick(current.as_ref().map(|(e, _)| e.eye_height), target); + writeln!( + out, + "tick {} {} {} {}", + fb(camera.eye_height), + fb(camera.eye_height_old), + fb(camera.fov_modifier), + fb(camera.old_fov_modifier) + )?; + } + "frame" => { + let pt = fl(&op[1]); + let fluid = [ + CameraFluid::None, + CameraFluid::Water, + CameraFluid::Lava, + CameraFluid::PowderSnow, + ][op[2].as_u64().unwrap() as usize]; + let panoramic = b(&op[3]); + let (e, _) = current.as_ref().expect("entity"); + camera.align_with_entity(e, pt, kind, |from, to| { + let Ok(hit) = clip_world( + &mut world, + Vec3::new(from[0], from[1], from[2]), + Vec3::new(to[0], to[1], to[2]), + RayBlockMode::Visual, + RayFluidMode::None, + usize::MAX, + ) else { + panic!("ray") + }; + (!hit.miss).then(|| { + let l = hit.hit.location; + [l.x, l.y, l.z] + }) + }); + let dead = e.living.and_then(|l| l.dead); + let fov = camera.calculate_fov(pt, fov_option, effect, dead, fluid, panoramic); + let hud = camera.calculate_hud_fov(pt, effect, dead, fluid); + let p = camera.position; + let q = camera.rotation; + let v = |a: [f32; 3]| format!("{} {} {}", fb(a[0]), fb(a[1]), fb(a[2])); + writeln!( + out, + "frame {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}", + dbs(p[0]), + dbs(p[1]), + dbs(p[2]), + fb(camera.x_rot), + fb(camera.y_rot), + fb(q.x), + fb(q.y), + fb(q.z), + fb(q.w), + v(camera.forwards), + v(camera.up), + v(camera.left), + camera.detached, + fb(fov), + fb(hud) + )?; + } + other => panic!("{other}"), + } + } + Ok(()) +} + +fn bob(c: &Value, out: &mut impl Write) -> Result<()> { + let state = BobState { + living: (!c["living"].is_null()).then(|| { + let l = &c["living"]; + HurtBob { + hurt_time: fl(&l["hurt"]), + hurt_duration: l["duration"].as_i64().unwrap() as i32, + hurt_dir: fl(&l["dir"]), + death_time: (!l["death"].is_null()).then(|| fl(&l["death"])), + } + }), + player: c["player"].as_array().map(|p| (fl(&p[0]), fl(&p[1]))), + }; + let m = bob_matrix(&state, db(&c["tilt"]), b(&c["view"])); + let mut line = String::from("bob"); + for v in m.m { + line.push(' '); + line.push_str(&fb(v)); + } + writeln!(out, "{line} {}", m.properties)?; + Ok(()) +} + +fn avatar(c: &Value, out: &mut impl Write) -> Result<()> { + let mut state = AvatarBob::default(); + for op in c["ops"].as_array().unwrap() { + let name = op[0].as_str().unwrap(); + match name { + "tick" => state.tick(), + "move" => state.add_walked(fl(&op[1]), fl(&op[2])), + "bob" => state.update_bob(b(&op[1]) && !b(&op[2]) && !b(&op[3]), vec3(&op[4])), + "reset" => state.reset_bob(), + "frame" => { + let pt = fl(&op[1]); + writeln!( + out, + "frame {} {}", + fb(state.interpolated_bob(pt)), + fb(state.backwards_interpolated_walk_distance(pt)) + )?; + continue; + } + other => panic!("{other}"), + } + writeln!(out, "{name}")?; + } + Ok(()) +} + +fn main() -> Result<()> { + let args: Vec = std::env::args().collect(); + let input = BufReader::new(File::open(&args[1])?); + let mut out = BufWriter::new(File::create(&args[2])?); + for (n, line) in input.lines().enumerate() { + let c: Value = serde_json::from_str(&line?)?; + writeln!(out, "== {n}")?; + match c["t"].as_str().unwrap() { + "fov" => writeln!( + out, + "{}", + fb(field_of_view_modifier( + &fov_player(&c), + b(&c["fp"]), + fl(&c["scale"]) + )) + )?, + "camera" => camera(&c, &mut out)?, + "bob" => bob(&c, &mut out)?, + "avatar" => avatar(&c, &mut out)?, + other => panic!("{other}"), + } + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-client/src/camera.rs b/crates/horizon-client/src/camera.rs new file mode 100644 index 000000000..329ae3e86 --- /dev/null +++ b/crates/horizon-client/src/camera.rs @@ -0,0 +1,776 @@ +//! The camera (`Camera.tick`, `tickFov`, `calculateFov`, `alignWithEntity`, +//! `getMaxZoom`, `setRotation`, `move`), view and hurt bobbing +//! (`GameRenderer.bobView`, `bobHurt`), the walk and bob history they read +//! (`ClientAvatarState`), and `AbstractClientPlayer.getFieldOfViewModifier`. +//! +//! The float arithmetic follows vanilla and JOML's default (non-FMA, +//! non-fast-math) code paths operation by operation. +use horizon_core::geometry::trig; + +/// `(float) Math.PI`. +const PI: f32 = std::f32::consts::PI; +/// `(float) (Math.PI / 180.0)`. +const DEG_TO_RAD: f32 = trig::DEG_TO_RAD; + +/// `Math.min(float, float)`: NaN wins and -0.0 is below 0.0. +pub fn java_min(a: f32, b: f32) -> f32 { + if a.is_nan() || b.is_nan() { + f32::NAN + } else if a == 0.0 && b == 0.0 { + f32::from_bits(a.to_bits() | b.to_bits()) + } else if a <= b { + a + } else { + b + } +} +/// `Math.max(float, float)`. +pub fn java_max(a: f32, b: f32) -> f32 { + if a.is_nan() || b.is_nan() { + f32::NAN + } else if a == 0.0 && b == 0.0 { + f32::from_bits(a.to_bits() & b.to_bits()) + } else if a >= b { + a + } else { + b + } +} +/// `Mth.lerp(float, float, float)`. +pub fn lerp(alpha: f32, p0: f32, p1: f32) -> f32 { + p0 + alpha * (p1 - p0) +} +/// `Mth.lerp(double, double, double)`. +pub fn lerp_d(alpha: f64, p0: f64, p1: f64) -> f64 { + p0 + alpha * (p1 - p0) +} +/// `Mth.wrapDegrees(float)`. +pub fn wrap_degrees(angle: f32) -> f32 { + let mut normalized = angle % 360.0; + if normalized >= 180.0 { + normalized -= 360.0; + } + if normalized < -180.0 { + normalized += 360.0; + } + normalized +} +/// `Mth.clamp(float, float, float)`. +pub fn clamp(value: f32, min: f32, max: f32) -> f32 { + if value < min { min } else { java_min(value, max) } +} + +/// JOML's float trigonometry (`org.joml.Math` without fast math). +pub mod joml { + use super::PI; + const TAU: f32 = std::f32::consts::TAU; + const HALF_PI: f32 = std::f32::consts::FRAC_PI_2; + + /// `Math.sin(float)`: `java.lang.Math.sin` narrowed. + pub fn sin(rad: f32) -> f32 { + f64::from(rad).sin() as f32 + } + /// `Math.cosFromSin(float, float)`. + pub fn cos_from_sin(sin: f32, angle: f32) -> f32 { + let cos = (1.0 - sin * sin).sqrt(); + let a = angle + HALF_PI; + let mut b = a - (a / TAU) as i32 as f32 * TAU; + if f64::from(b) < 0.0 { + b += TAU; + } + if b >= PI { -cos } else { cos } + } + + /// A JOML `Quaternionf` (x, y, z, w). + #[derive(Clone, Copy, Debug, PartialEq)] + pub struct Quat { + pub x: f32, + pub y: f32, + pub z: f32, + pub w: f32, + } + impl Quat { + pub const IDENTITY: Self = Self { + x: 0.0, + y: 0.0, + z: 0.0, + w: 1.0, + }; + /// `Quaternionf.rotationYXZ(angleY, angleX, angleZ)`. + pub fn rotation_yxz(angle_y: f32, angle_x: f32, angle_z: f32) -> Self { + let sx = sin(angle_x * 0.5); + let cx = cos_from_sin(sx, angle_x * 0.5); + let sy = sin(angle_y * 0.5); + let cy = cos_from_sin(sy, angle_y * 0.5); + let sz = sin(angle_z * 0.5); + let cz = cos_from_sin(sz, angle_z * 0.5); + let x = cy * sx; + let y = sy * cx; + let z = sy * sx; + let w = cy * cx; + Self { + x: x * cz + y * sz, + y: y * cz - x * sz, + z: w * sz - z * cz, + w: w * cz + z * sz, + } + } + /// `Quaternionf.transform(x, y, z, dest)` (`Vector3f.rotate`). + pub fn transform(&self, v: [f32; 3]) -> [f32; 3] { + let [x, y, z] = v; + let xx = self.x * self.x; + let yy = self.y * self.y; + let zz = self.z * self.z; + let ww = self.w * self.w; + let xy = self.x * self.y; + let xz = self.x * self.z; + let yz = self.y * self.z; + let xw = self.x * self.w; + let zw = self.z * self.w; + let yw = self.y * self.w; + let k = 1.0 / (xx + yy + zz + ww); + [ + (xx - yy - zz + ww) * k * x + + (2.0 * (xy - zw) * k * y + 2.0 * (xz + yw) * k * z), + 2.0 * (xy + zw) * k * x + + ((yy - xx - zz + ww) * k * y + 2.0 * (yz - xw) * k * z), + 2.0 * (xz - yw) * k * x + + (2.0 * (yz + xw) * k * y + (zz - xx - yy + ww) * k * z), + ] + } + } + + const PERSPECTIVE: u8 = 1; + const IDENTITY: u8 = 4; + const TRANSLATION: u8 = 8; + + /// A JOML `Matrix4f` with its property flags, which select the code + /// paths (and so the rounding) of later operations. `m[column * 4 + row]`. + #[derive(Clone, Copy, Debug, PartialEq)] + pub struct Mat4 { + pub m: [f32; 16], + pub properties: u8, + } + impl Default for Mat4 { + fn default() -> Self { + Self::IDENTITY + } + } + impl Mat4 { + /// `new Matrix4f()`. + pub const IDENTITY: Self = Self { + m: [ + 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, + ], + properties: 30, + }; + fn get(&self, column: usize, row: usize) -> f32 { + self.m[column * 4 + row] + } + fn set(&mut self, column: usize, row: usize, v: f32) { + self.m[column * 4 + row] = v; + } + fn reset_unless_identity(&mut self) { + if self.properties & IDENTITY == 0 { + self.m = Self::IDENTITY.m; + } + } + /// `Matrix4f.translation(x, y, z)`. + pub fn translation(&mut self, x: f32, y: f32, z: f32) { + self.reset_unless_identity(); + self.set(3, 0, x); + self.set(3, 1, y); + self.set(3, 2, z); + self.properties = 26; + } + /// `Matrix4f.setTranslation(x, y, z)`. + pub fn set_translation(&mut self, x: f32, y: f32, z: f32) { + self.set(3, 0, x); + self.set(3, 1, y); + self.set(3, 2, z); + self.properties &= !(PERSPECTIVE | IDENTITY); + } + /// `Matrix4f.translate(x, y, z)`. + pub fn translate(&mut self, x: f32, y: f32, z: f32) { + if self.properties & IDENTITY != 0 { + self.translation(x, y, z); + return; + } + for row in 0..4 { + let v = self.get(0, row) * x + + (self.get(1, row) * y + (self.get(2, row) * z + self.get(3, row))); + self.set(3, row, v); + } + self.properties &= !(PERSPECTIVE | IDENTITY); + } + fn rotation_axis(&mut self, axis: usize, ang: f32) { + let sin = sin(ang); + let cos = cos_from_sin(sin, ang); + self.reset_unless_identity(); + match axis { + 0 => { + self.set(1, 1, cos); + self.set(1, 2, sin); + self.set(2, 1, -sin); + self.set(2, 2, cos); + } + 1 => { + self.set(0, 0, cos); + self.set(0, 2, -sin); + self.set(2, 0, sin); + self.set(2, 2, cos); + } + _ => { + self.set(0, 0, cos); + self.set(0, 1, sin); + self.set(1, 0, -sin); + self.set(1, 1, cos); + } + } + self.properties = 18; + } + /// `Matrix4f.rotateX/rotateY/rotateZ(ang)`, with the identity and + /// pure-translation shortcuts. + fn rotate_axis(&mut self, axis: usize, ang: f32) { + if self.properties & IDENTITY != 0 { + self.rotation_axis(axis, ang); + return; + } + if self.properties & TRANSLATION != 0 { + let (x, y, z) = (self.get(3, 0), self.get(3, 1), self.get(3, 2)); + self.rotation_axis(axis, ang); + self.set_translation(x, y, z); + return; + } + let sin = sin(ang); + let cos = cos_from_sin(sin, ang); + let s = *self; + match axis { + 0 => { + for row in 0..4 { + let (l1, l2) = (s.get(1, row), s.get(2, row)); + self.set(2, row, l1 * -sin + l2 * cos); + self.set(1, row, l1 * cos + l2 * sin); + } + } + 1 => { + for row in 0..4 { + let (l0, l2) = (s.get(0, row), s.get(2, row)); + self.set(0, row, l0 * cos + l2 * -sin); + self.set(2, row, l0 * sin + l2 * cos); + } + } + _ => { + // rotateTowardsXY(sin, cos). + let (dx, dy) = (sin, cos); + for row in 0..4 { + let (l0, l1) = (s.get(0, row), s.get(1, row)); + self.set(0, row, l0 * dy + l1 * dx); + self.set(1, row, l0 * -dx + l1 * dy); + } + } + } + self.properties &= !(PERSPECTIVE | IDENTITY | TRANSLATION); + } + pub fn rotate_x(&mut self, ang: f32) { + self.rotate_axis(0, ang); + } + pub fn rotate_y(&mut self, ang: f32) { + self.rotate_axis(1, ang); + } + pub fn rotate_z(&mut self, ang: f32) { + // rotateTowardsXY also short-cuts on identity, but rotateZ has + // already taken that branch. + self.rotate_axis(2, ang); + } + } +} +use joml::{Mat4, Quat}; + +/// `CameraType`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum CameraType { + #[default] + FirstPerson, + ThirdPersonBack, + ThirdPersonFront, +} +impl CameraType { + pub fn is_first_person(self) -> bool { + self == Self::FirstPerson + } + pub fn is_mirrored(self) -> bool { + self == Self::ThirdPersonFront + } + /// `CameraType.cycle` (F5). + pub fn cycle(self) -> Self { + match self { + Self::FirstPerson => Self::ThirdPersonBack, + Self::ThirdPersonBack => Self::ThirdPersonFront, + Self::ThirdPersonFront => Self::FirstPerson, + } + } +} + +/// What `AbstractClientPlayer.getFieldOfViewModifier` reads. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FovPlayer { + /// `Abilities.flying`. + pub flying: bool, + /// `Abilities.getWalkingSpeed()`. + pub walking_speed: f32, + /// `getAttributeValue(MOVEMENT_SPEED)`. + pub movement_speed: f64, + /// The item in use and its use ticks, when using one. + pub using: Option<(UseItem, i32)>, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum UseItem { + Bow, + Spyglass, + Other, +} +/// `AbstractClientPlayer.getFieldOfViewModifier(firstPerson, effectScale)`. +pub fn field_of_view_modifier(p: &FovPlayer, first_person: bool, effect_scale: f32) -> f32 { + let mut modifier = 1.0f32; + if p.flying { + modifier *= 1.1; + } + let walking_speed = p.walking_speed; + if walking_speed != 0.0 { + let speed_factor = p.movement_speed as f32 / walking_speed; + modifier *= (speed_factor + 1.0) / 2.0; + } + if let Some((item, ticks)) = p.using { + match item { + UseItem::Bow => { + let scale = java_min(ticks as f32 / 20.0, 1.0); + modifier *= 1.0 - scale * scale * 0.15; + } + // isScoping: using a spyglass. + UseItem::Spyglass if first_person => return 0.1, + _ => {} + } + } + lerp(effect_scale, 1.0, modifier) +} + +/// The camera entity as `Camera.alignWithEntity` and the field-of-view +/// death and hurt effects see it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CameraEntity { + pub position: [f64; 3], + /// `xo`, `yo`, `zo`. + pub previous: [f64; 3], + pub x_rot: f32, + pub y_rot: f32, + pub x_rot_o: f32, + pub y_rot_o: f32, + /// `Entity.getEyeHeight()`. + pub eye_height: f32, + /// A living entity's `getScale()` and camera distance attribute. + pub living: Option, + /// The vehicle's scale and camera distance when it is living. + pub mount: Option<(f32, f64)>, +} +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct LivingCamera { + pub scale: f32, + pub camera_distance: f64, + /// `isSleeping()` with `getBedOrientation()` as its `toYRot()`. + pub sleeping: Option>, + /// `isDeadOrDying()` and `deathTime`. + pub dead: Option, +} +impl CameraEntity { + /// `Entity.getXRot(partialTicks)`. + pub fn view_x_rot(&self, partial: f32) -> f32 { + if partial == 1.0 { + self.x_rot + } else { + lerp(partial, self.x_rot_o, self.x_rot) + } + } + /// `LocalPlayer.getViewYRot` (`getYRot(partialTicks)`, a `Mth.rotLerp`). + pub fn view_y_rot(&self, partial: f32) -> f32 { + if partial == 1.0 { + self.y_rot + } else { + self.y_rot_o + partial * wrap_degrees(self.y_rot - self.y_rot_o) + } + } +} + +/// The fluid `Camera.getFluidInCamera` reports, as the field of view sees it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum CameraFluid { + #[default] + None, + Water, + Lava, + PowderSnow, +} + +/// `Camera`: the eye-height and field-of-view easing and the view placement. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Camera { + pub eye_height: f32, + pub eye_height_old: f32, + pub fov_modifier: f32, + pub old_fov_modifier: f32, + pub position: [f64; 3], + pub x_rot: f32, + pub y_rot: f32, + pub rotation: Quat, + pub forwards: [f32; 3], + pub up: [f32; 3], + pub left: [f32; 3], + pub detached: bool, +} +impl Default for Camera { + fn default() -> Self { + Self { + eye_height: 0.0, + eye_height_old: 0.0, + fov_modifier: 0.0, + old_fov_modifier: 0.0, + position: [0.0; 3], + x_rot: 0.0, + y_rot: 0.0, + rotation: Quat::IDENTITY, + forwards: [0.0, 0.0, -1.0], + up: [0.0, 1.0, 0.0], + left: [-1.0, 0.0, 0.0], + detached: false, + } + } +} +impl Camera { + /// `Camera.tick`: the eye height eases halfway toward the entity's + /// (with a level and an entity), then `tickFov` with the camera entity's + /// field-of-view modifier target (1 when it is not a player). + pub fn tick(&mut self, entity_eye_height: Option, target_fov_modifier: f32) { + if let Some(eye) = entity_eye_height { + self.eye_height_old = self.eye_height; + self.eye_height += (eye - self.eye_height) * 0.5; + } + self.old_fov_modifier = self.fov_modifier; + self.fov_modifier += (target_fov_modifier - self.fov_modifier) * 0.5; + self.fov_modifier = clamp(self.fov_modifier, 0.1, 1.5); + } + /// `Camera.setRotation`. + pub fn set_rotation(&mut self, y_rot: f32, x_rot: f32) { + self.x_rot = x_rot; + self.y_rot = y_rot; + self.rotation = Quat::rotation_yxz(PI - y_rot * DEG_TO_RAD, -x_rot * DEG_TO_RAD, 0.0); + self.forwards = self.rotation.transform([0.0, 0.0, -1.0]); + self.up = self.rotation.transform([0.0, 1.0, 0.0]); + self.left = self.rotation.transform([-1.0, 0.0, 0.0]); + } + /// `Camera.move(forwards, up, right)`. + pub fn move_by(&mut self, forwards: f32, up: f32, right: f32) { + let offset = self.rotation.transform([right, up, -forwards]); + self.position = [ + self.position[0] + f64::from(offset[0]), + self.position[1] + f64::from(offset[1]), + self.position[2] + f64::from(offset[2]), + ]; + } + /// `Camera.alignWithEntity` (not riding a minecart with the new + /// movement): the entity's view rotation and interpolated eye, then a + /// detached camera backed off along the view (`getMaxZoom`) or a sleeping + /// one turned to the bed. `clip` is `Level.clip` with + /// `ClipContext.Block.VISUAL` and no fluids; it returns the hit location + /// unless the ray misses. + pub fn align_with_entity( + &mut self, + entity: &CameraEntity, + partial: f32, + camera_type: CameraType, + mut clip: impl FnMut([f64; 3], [f64; 3]) -> Option<[f64; 3]>, + ) { + self.set_rotation(entity.view_y_rot(partial), entity.view_x_rot(partial)); + let p = f64::from(partial); + self.position = [ + lerp_d(p, entity.previous[0], entity.position[0]), + lerp_d(p, entity.previous[1], entity.position[1]) + + f64::from(lerp(partial, self.eye_height_old, self.eye_height)), + lerp_d(p, entity.previous[2], entity.position[2]), + ]; + self.detached = !camera_type.is_first_person(); + if self.detached { + if camera_type.is_mirrored() { + self.set_rotation(self.y_rot + 180.0, -self.x_rot); + } + let (mut distance, mut scale) = (4.0f32, 1.0f32); + if let Some(living) = &entity.living { + scale = living.scale; + distance = living.camera_distance as f32; + } + let (mut mount_scale, mut mount_distance) = (scale, distance); + if let Some((s, d)) = entity.mount { + mount_scale = s; + mount_distance = d as f32; + } + let zoom = self.max_zoom( + java_max(scale * distance, mount_scale * mount_distance), + &mut clip, + ); + self.move_by(-zoom, 0.0, 0.0); + } else if let Some(LivingCamera { + sleeping: Some(bed), + .. + }) = entity.living + { + self.set_rotation(bed.map_or(0.0, |yaw| yaw - 180.0), 0.0); + self.move_by(0.0, 0.15, 0.0); + } + } + /// `Camera.getMaxZoom`: eight rays from the corners of a 0.2 cube about + /// the eye, shortening the distance to the nearest visual-shape hit. + pub fn max_zoom( + &self, + mut distance: f32, + clip: &mut impl FnMut([f64; 3], [f64; 3]) -> Option<[f64; 3]>, + ) -> f32 { + let at = self.position; + for i in 0..8 { + let offset = [ + ((i & 1) * 2 - 1) as f32, + ((i >> 1 & 1) * 2 - 1) as f32, + ((i >> 2 & 1) * 2 - 1) as f32, + ]; + let from: [f64; 3] = std::array::from_fn(|a| at[a] + f64::from(offset[a] * 0.1)); + let back = f64::from(-distance); + let to: [f64; 3] = + std::array::from_fn(|a| from[a] + f64::from(self.forwards[a]) * back); + if let Some(hit) = clip(from, to) { + let d = [hit[0] - at[0], hit[1] - at[1], hit[2] - at[2]]; + let dist_sq = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]) as f32; + if dist_sq < distance * distance { + distance = dist_sq.sqrt(); + } + } + } + distance + } + /// `Camera.calculateFov`: the option scaled by the eased modifier, then + /// the death and fluid effects. + pub fn calculate_fov( + &self, + partial: f32, + fov_option: i32, + effect_scale: f32, + dead: Option, + fluid: CameraFluid, + panoramic: bool, + ) -> f32 { + if panoramic { + return 90.0; + } + let fov = + fov_option as f32 * lerp(partial, self.old_fov_modifier, self.fov_modifier); + modify_fov_based_on_death_or_fluid(partial, fov, effect_scale, dead, fluid) + } + /// `Camera.calculateHudFov`. + pub fn calculate_hud_fov( + &self, + partial: f32, + effect_scale: f32, + dead: Option, + fluid: CameraFluid, + ) -> f32 { + modify_fov_based_on_death_or_fluid(partial, 70.0, effect_scale, dead, fluid) + } +} +/// `Camera.modifyFovBasedOnDeathOrFluid`. `dead` is the camera entity's +/// `deathTime` while it is a living entity that is dead or dying. +pub fn modify_fov_based_on_death_or_fluid( + partial: f32, + mut fov: f32, + effect_scale: f32, + dead: Option, + fluid: CameraFluid, +) -> f32 { + if let Some(death_time) = dead { + let duration = java_min(death_time as f32 + partial, 20.0); + fov /= (1.0 - 500.0 / (duration + 500.0)) * 2.0 + 1.0; + } + if matches!(fluid, CameraFluid::Lava | CameraFluid::Water) { + fov *= lerp(effect_scale, 1.0, 0.857_142_87); + } + fov +} + +/// `ClientAvatarState`: the walked distance and view bob of a player. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct AvatarBob { + pub walk_dist: f32, + pub walk_dist_o: f32, + pub bob: f32, + pub bob_o: f32, +} +impl AvatarBob { + /// `ClientAvatarState.tick` (at the start of `AbstractClientPlayer.tick`). + pub fn tick(&mut self) { + self.walk_dist_o = self.walk_dist; + } + /// `LocalPlayer.move`: `addWalkedDistance(Mth.length(dx, dz) * 0.6F)` + /// with the float horizontal displacement. + pub fn add_walked(&mut self, dx: f32, dz: f32) { + self.walk_dist += (dx * dx + dz * dz).sqrt() * 0.6; + } + /// `AbstractClientPlayer.updateBob`: toward the horizontal speed (at most + /// 0.1) on the ground, toward 0 otherwise. + pub fn update_bob(&mut self, on_ground_alive_not_swimming: bool, velocity: [f64; 3]) { + let target = if on_ground_alive_not_swimming { + java_min( + 0.1, + (velocity[0] * velocity[0] + velocity[2] * velocity[2]).sqrt() as f32, + ) + } else { + 0.0 + }; + self.bob_o = self.bob; + self.bob += (target - self.bob) * 0.4; + } + /// `ClientAvatarState.resetBob` (`AbstractClientPlayer.rideTick`). + pub fn reset_bob(&mut self) { + self.bob_o = self.bob; + self.bob = 0.0; + } + pub fn interpolated_bob(&self, partial: f32) -> f32 { + lerp(partial, self.bob_o, self.bob) + } + pub fn backwards_interpolated_walk_distance(&self, partial: f32) -> f32 { + let wda = self.walk_dist - self.walk_dist_o; + -(self.walk_dist + wda * partial) + } +} + +/// The parts of `CameraRenderState.entityRenderState` the bobbing reads. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct BobState { + /// A living camera entity: `hurtTime - partial`, `hurtDuration`, + /// `getHurtDir()`, and `deathTime + partial` when dead or dying. + pub living: Option, + /// A player camera entity: the backwards-interpolated walk distance and + /// the interpolated bob. + pub player: Option<(f32, f32)>, +} +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct HurtBob { + pub hurt_time: f32, + pub hurt_duration: i32, + pub hurt_dir: f32, + pub death_time: Option, +} +/// `PoseStack.rotateDegrees` on the pose with an `Axis`. +fn rotate_degrees(m: &mut Mat4, axis: usize, degrees: f32) { + let ang = degrees * DEG_TO_RAD; + match axis { + 0 => m.rotate_x(ang), + 1 => m.rotate_y(ang), + _ => m.rotate_z(ang), + } +} +/// `GameRenderer.bobHurt`. +pub fn bob_hurt(state: &BobState, damage_tilt_strength: f64, pose: &mut Mat4) { + let Some(living) = state.living else { return }; + let mut hurt = living.hurt_time; + if let Some(death_time) = living.death_time { + let duration = java_min(death_time, 20.0); + rotate_degrees(pose, 2, 40.0 - 8000.0 / (duration + 200.0)); + } + if hurt < 0.0 { + return; + } + hurt /= living.hurt_duration as f32; + hurt = trig::sin(f64::from(hurt * hurt * hurt * hurt * PI)); + let rr = living.hurt_dir; + rotate_degrees(pose, 1, -rr); + let tilt = (f64::from(-hurt) * 14.0 * damage_tilt_strength) as f32; + rotate_degrees(pose, 2, tilt); + rotate_degrees(pose, 1, rr); +} +/// `GameRenderer.bobView`. +pub fn bob_view(state: &BobState, pose: &mut Mat4) { + let Some((walk, bob)) = state.player else { + return; + }; + pose.translate( + trig::sin(f64::from(walk * PI)) * bob * 0.5, + -(trig::cos(f64::from(walk * PI)) * bob).abs(), + 0.0, + ); + rotate_degrees(pose, 2, trig::sin(f64::from(walk * PI)) * bob * 3.0); + rotate_degrees(pose, 0, (trig::cos(f64::from(walk * PI - 0.2)) * bob).abs() * 5.0); +} +/// The bob matrix `GameRenderer.renderLevel` multiplies into the projection +/// (and `renderItemInHand` into the hand's pose). +pub fn bob_matrix(state: &BobState, damage_tilt_strength: f64, bob_view_option: bool) -> Mat4 { + let mut pose = Mat4::IDENTITY; + bob_hurt(state, damage_tilt_strength, &mut pose); + if bob_view_option { + bob_view(state, &mut pose); + } + pose +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn camera_eases_eye_height_and_fov() { + let mut camera = Camera::default(); + camera.tick(Some(1.62), 1.0); + assert_eq!(camera.eye_height, 0.81); + assert_eq!(camera.fov_modifier, 0.5); + camera.tick(None, 1.0); + assert_eq!(camera.eye_height, 0.81); + assert_eq!(camera.fov_modifier, 0.75); + } + #[test] + fn rotation_faces_south_at_zero_yaw() { + let mut camera = Camera::default(); + camera.set_rotation(0.0, 0.0); + assert!((camera.forwards[2] - 1.0).abs() < 1e-6); + camera.set_rotation(90.0, 0.0); + assert!((camera.forwards[0] + 1.0).abs() < 1e-6); + } + #[test] + fn detached_camera_backs_off_until_blocked() { + let entity = CameraEntity { + position: [0.0; 3], + previous: [0.0; 3], + x_rot: 0.0, + y_rot: 0.0, + x_rot_o: 0.0, + y_rot_o: 0.0, + eye_height: 1.62, + living: None, + mount: None, + }; + let mut camera = Camera::default(); + camera.align_with_entity(&entity, 1.0, CameraType::ThirdPersonBack, |_, _| None); + assert!((camera.position[2] + 4.0).abs() < 1e-6); + camera.align_with_entity(&entity, 1.0, CameraType::ThirdPersonBack, |_, _| { + Some([0.0, 0.0, -1.0]) + }); + assert!(camera.position[2] > -1.1 && camera.position[2] < -0.9); + } + #[test] + fn fov_modifier_combines_speed_flight_and_bow() { + let mut p = FovPlayer { + flying: false, + walking_speed: 0.1, + movement_speed: 0.13, + using: None, + }; + assert_eq!(field_of_view_modifier(&p, true, 1.0), (0.13f32 / 0.1 + 1.0) / 2.0); + assert_eq!(field_of_view_modifier(&p, true, 0.0), 1.0); + p.using = Some((UseItem::Spyglass, 3)); + assert_eq!(field_of_view_modifier(&p, true, 1.0), 0.1); + assert_ne!(field_of_view_modifier(&p, false, 1.0), 0.1); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index b81c403fd..23162566b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -615,7 +615,8 @@ struct Game<'a> { /// Item being used (eaten): hotbar slot and ticks used. using: Option<(usize, u32)>, /// Camera.oldFovModifier / fovModifier. - fov_modifier: [f32; 2], + /// `Camera` (eye height and field-of-view easing, view placement). + view: horizon_client::camera::Camera, /// Hud.scopeScale (spyglass overlay size). scope_scale: f32, /// Duration of the last frame in ticks (GUI easing). @@ -645,8 +646,8 @@ struct Game<'a> { /// Where the options screen returns: true = title, false = pause menu. options_from_title: bool, dragging: bool, - walk: (f32, f32), - bob: (f32, f32), + /// `ClientAvatarState`: walked distance and view bob. + avatar: horizon_client::camera::AvatarBob, flash: u32, /// Sleeping in a bed: (bed head position, ticks asleep). sleeping: Option<([i32; 3], u32)>, @@ -2536,6 +2537,11 @@ impl Game<'_> { .and_then(|s| self.res.items.get(&s.item)) .map(|i| i.use_speed); let grounded = player.ground.on_ground; + let before = ( + grounded, + [player.velocity.x, player.velocity.y, player.velocity.z], + [player.position.x, player.position.y, player.position.z], + ); if !riding { MotionWorld { player, @@ -2562,6 +2568,7 @@ impl Game<'_> { self.previous_eye = self.eye; self.eye += (player.dimensions.eye_height - self.eye) * 0.5; let crouching = player.pose == horizon_client::pose::Pose::Crouching; + self.tick_avatar(before, riding); self.record_combat(&events); for event in events { match event { @@ -2706,23 +2713,6 @@ impl Game<'_> { self.tick_falling()?; self.tick_tnt()?; } - 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; - } if running { self.tick_block_entities()?; self.tick_sculk()?; @@ -7387,16 +7377,8 @@ impl Game<'_> { return Ok(false); }; let alpha = self.clock.fraction(); - let (camera, underwater, view_yaw, view_pitch) = match &self.player { - Some(p) => { - let (a, b) = (self.previous_position, p.position); - let eye = self.previous_eye + alpha as f32 * (self.eye - self.previous_eye); - let c = glam::DVec3::new( - a.x + (b.x - a.x) * alpha, - a.y + (b.y - a.y) * alpha + f64::from(eye), - a.z + (b.z - a.z) * alpha, - ); - let (c, yaw, pitch) = self.camera_view(c); + let (camera, underwater, view_yaw, view_pitch) = match self.camera_view(alpha as f32) { + Some((c, yaw, pitch)) => { let s = self.world .block(c.x.floor() as i32, c.y.floor() as i32, c.z.floor() as i32); @@ -7534,13 +7516,11 @@ impl Game<'_> { } else { self.fov_degrees(alpha as f32, camera.to_array()) }, - 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, - ) - }), + bob: if title { + glam::Mat4::IDENTITY + } else { + self.bob_matrix(alpha as f32) + }, sky, distance: (self.streaming.radius * 16) as f32, underwater, @@ -8523,7 +8503,7 @@ pub fn run() -> Result<()> { last_hurt_by_player: HashSet::new(), chest_open: HashMap::new(), using: None, - fov_modifier: [1.0, 1.0], + view: Default::default(), scope_scale: 0.5, frame_ticks: 0.0, title: None, @@ -8544,8 +8524,7 @@ pub fn run() -> Result<()> { settings, options_from_title: false, dragging: false, - walk: (0.0, 0.0), - bob: (0.0, 0.0), + avatar: Default::default(), flash: 0, sleeping: None, dim: Dim::Overworld, diff --git a/crates/horizon-client/src/game/fov.rs b/crates/horizon-client/src/game/fov.rs index a40be8a13..faf0f0924 100644 --- a/crates/horizon-client/src/game/fov.rs +++ b/crates/horizon-client/src/game/fov.rs @@ -1,16 +1,18 @@ //! Field of view (`Camera.tickFov`, `calculateFov`, -//! `AbstractClientPlayer.getFieldOfViewModifier`) and the spyglass -//! (`SpyglassItem`, `Hud.extractSpyglassOverlay`). +//! `AbstractClientPlayer.getFieldOfViewModifier`), view and hurt bobbing +//! (`GameRenderer.bobHurt`, `bobView`) and the spyglass (`SpyglassItem`, +//! `Hud.extractSpyglassOverlay`). The arithmetic is `horizon_client::camera`. use super::Game; use horizon_client::{ + camera::{ + BobState, CameraFluid, FovPlayer, HurtBob, UseItem, bob_matrix, field_of_view_modifier, + }, fog::{FogType, fog_type}, hud::{HudBatch, rgba}, }; /// `Abilities.walkingSpeed`. const WALKING_SPEED: f32 = 0.1; -/// `options.fovEffectScale` (vanilla default 1). -const FOV_EFFECT_SCALE: f32 = 1.0; impl Game<'_> { /// `Player.isScoping`: using a spyglass. @@ -19,54 +21,115 @@ impl Game<'_> { .and_then(|(slot, _)| self.stack_in(slot)) .is_some_and(|s| &*s.item == "minecraft:spyglass") } - /// `AbstractClientPlayer.getFieldOfViewModifier` (first person). - fn fov_target(&self) -> f32 { - let Some(p) = &self.player else { return 1.0 }; - let mut modifier = 1.0f32; - // Movement speed (sprinting, speed and slowness) relative to walking. - modifier *= (p.speed / WALKING_SPEED + 1.0) / 2.0; - if let Some((slot, ticks)) = self.using - && let Some(stack) = self.stack_in(slot) - { - match &*stack.item { - "minecraft:bow" => { - let scale = (ticks as f32 / 20.0).min(1.0); - modifier *= 1.0 - scale * scale * 0.15; - } - "minecraft:spyglass" => return 0.1, - _ => {} - } - } - 1.0 + (modifier - 1.0) * FOV_EFFECT_SCALE + /// `options.fovEffectScale`. + pub(super) fn fov_effect_scale(&self) -> f32 { + self.settings.file.double("fovEffectScale") as f32 } - /// `Camera.tickFov`. + /// What `AbstractClientPlayer.getFieldOfViewModifier` reads. + fn fov_player(&self) -> Option { + let p = self.player.as_ref()?; + let using = self.using.and_then(|(slot, ticks)| { + let stack = self.stack_in(slot)?; + let item = match &*stack.item { + "minecraft:bow" => UseItem::Bow, + "minecraft:spyglass" => UseItem::Spyglass, + _ => UseItem::Other, + }; + Some((item, ticks as i32)) + }); + Some(FovPlayer { + flying: p.flying, + walking_speed: WALKING_SPEED, + // Player.aiStep keeps `speed` as the float movement speed attribute. + movement_speed: f64::from(p.speed), + using, + }) + } + /// `Camera.tick`: the eye height and the field-of-view modifier ease + /// halfway toward the player's each tick. pub(super) fn tick_fov(&mut self) { - let target = self.fov_target(); - let [_, current] = self.fov_modifier; - let next = (current + (target - current) * 0.5).clamp(0.1, 1.5); - self.fov_modifier = [current, next]; + let first_person = self.camera_type.first_person(); + let effect = self.fov_effect_scale(); + let target = self + .fov_player() + .map_or(1.0, |p| field_of_view_modifier(&p, first_person, effect)); + let eye = self.player.as_ref().map(|p| p.dimensions.eye_height); + self.view.tick(eye, target); + } + /// The player's `deathTime` while dead or dying. + fn death_time(&self) -> Option { + let p = self.player.as_ref()?; + p.health.dead_or_dying().then(|| { + self.ui + .died_at + .map_or(0, |t| (t.elapsed().as_secs_f32() * 20.0) as i32) + }) + } + /// The fluid at the camera, as `Camera.getFluidInCamera` reports it. + fn camera_fluid(&self, camera: [f64; 3]) -> CameraFluid { + match fog_type(&self.world, &self.res.facts, camera, self.forward()) { + FogType::Water => CameraFluid::Water, + FogType::Lava => CameraFluid::Lava, + FogType::PowderSnow => CameraFluid::PowderSnow, + FogType::Atmospheric => CameraFluid::None, + } } /// `Camera.calculateFov` with `modifyFovBasedOnDeathOrFluid`. pub(super) fn fov_degrees(&self, partial: f32, camera: [f64; 3]) -> f32 { - let [old, new] = self.fov_modifier; - let mut fov = self.settings.fov * (old + (new - old) * partial); - if let Some(p) = &self.player - && p.health.dead_or_dying() - { - let ticks = self - .ui - .died_at - .map_or(0.0, |t| t.elapsed().as_secs_f32() * 20.0); - let duration = (ticks + partial).min(20.0); - fov /= (1.0 - 500.0 / (duration + 500.0)) * 2.0 + 1.0; + self.view.calculate_fov( + partial, + self.settings.fov as i32, + self.fov_effect_scale(), + self.death_time(), + self.camera_fluid(camera), + false, + ) + } + /// The pose `GameRenderer.renderLevel` multiplies into the projection: + /// `bobHurt`, then `bobView` with the View Bobbing option. + pub(super) fn bob_matrix(&self, partial: f32) -> glam::Mat4 { + let Some(p) = self.player.as_ref() else { + return glam::Mat4::IDENTITY; + }; + let hurt = &p.health.hurt; + let state = BobState { + living: Some(HurtBob { + hurt_time: hurt.hurt_time as f32 - partial, + hurt_duration: hurt.hurt_duration, + hurt_dir: 0.0, + death_time: self.death_time().map(|t| t as f32 + partial), + }), + player: Some(( + self.avatar.backwards_interpolated_walk_distance(partial), + self.avatar.interpolated_bob(partial), + )), + }; + let tilt = self.settings.file.double("damageTiltStrength"); + glam::Mat4::from_cols_array(&bob_matrix(&state, tilt, self.settings.view_bobbing).m) + } + /// `AbstractClientPlayer.tick` and `aiStep` (`ClientAvatarState.tick`, + /// `updateBob`), `rideTick`'s `resetBob` and `LocalPlayer.move`'s walked + /// distance, after the player's movement this tick. `before` is the + /// ground state, velocity and position at the start of the tick. + pub(super) fn tick_avatar(&mut self, before: (bool, [f64; 3], [f64; 3]), riding: bool) { + let Some(p) = self.player.as_ref() else { + return; + }; + let (ground, velocity, start) = before; + let swimming = p.pose == horizon_client::pose::Pose::Swimming; + let alive = !p.health.dead_or_dying(); + let (dx, dz) = ( + (p.position.x - start[0]) as f32, + (p.position.z - start[2]) as f32, + ); + self.avatar.tick(); + self.avatar + .update_bob(ground && alive && !swimming, velocity); + if riding { + self.avatar.reset_bob(); + } else { + self.avatar.add_walked(dx, dz); } - if matches!( - fog_type(&self.world, &self.res.facts, camera, self.forward()), - FogType::Water | FogType::Lava - ) { - fov *= 1.0 + (0.857_142_87 - 1.0) * FOV_EFFECT_SCALE; - } - fov } /// `SpyglassItem.use`: start scoping. pub(super) fn use_spyglass(&mut self) { diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index c175733bb..ee60887dc 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -8,8 +8,100 @@ use horizon_client::{ mobs::{Anim, Brain, Mob, MobType}, pose::Pose, }; -use horizon_core::geometry::Vec3; -use std::{path::Path, sync::Arc}; +use horizon_client::{ + blocks::BlockFacts, + camera::{CameraEntity, LivingCamera}, + collisions::SceneCollisions, +}; +use horizon_core::{ + geometry::{Aabb, ShapeOp, Vec3, VoxelShape}, + position::BlockPos, +}; +use horizon_world::{ + collision_context::{CollisionContext, CollisionEntity, CollisionItem}, + entity_obstruction::EntityIdentity, + registry::BlockStateId, + world_ray::{RayBlockMode, RayFluidMode, RayWorld, clip_world}, +}; +use std::{io, path::Path, sync::Arc}; + +/// `Level.clip` with `ClipContext.Block.VISUAL` and no fluids: +/// `BlockBehaviour.getVisualShape` is the collision shape except for the +/// blocks that override it. +struct VisualRays<'a, 'r> { + scene: SceneCollisions<'a, 'r>, + facts: &'a BlockFacts, + context: CollisionContext<'static>, +} +impl RayWorld for VisualRays<'_, '_> { + type Error = io::Error; + type Block = BlockStateId; + type Fluid = (); + fn block_state(&mut self, p: BlockPos) -> io::Result { + Ok(self.scene.world.block(p.x, p.y, p.z)) + } + fn fluid_state(&mut self, _: BlockPos) -> io::Result<()> { + Ok(()) + } + fn block_shape( + &mut self, + state: BlockStateId, + p: BlockPos, + _: RayBlockMode, + ) -> io::Result { + let facts = self.facts.get(state); + let name = &*facts.name; + // TransparentBlock (glass, stained and tinted glass, copper grates), + // IronBarsBlock (bars and panes) and PowderSnowBlock: nothing; + // SoulSandBlock and MudBlock: a full block; SnowLayerBlock and + // FenceBlock: their outline. + if name.ends_with("glass") + || name.ends_with("glass_pane") + || name.ends_with("_bars") + || name.ends_with("copper_grate") + || name == "minecraft:powder_snow" + { + return Ok(VoxelShape::empty()); + } + if name == "minecraft:soul_sand" || name == "minecraft:mud" { + return Ok(VoxelShape::block()); + } + if name == "minecraft:snow" || name.ends_with("_fence") { + let mut shape = VoxelShape::empty(); + for b in facts.outline.iter() { + let b = b.map(f64::from); + let part = VoxelShape::from_box(Aabb::new( + Vec3::new(b[0], b[1], b[2]), + Vec3::new(b[3], b[4], b[5]), + )) + .map_err(|e| io::Error::other(format!("{e:?}")))?; + shape = shape + .join(&part, ShapeOp::OR) + .map_err(|e| io::Error::other(format!("{e:?}")))?; + } + return Ok(shape); + } + let binding = self.scene.binding; + binding + .collision_shape_with_context(&mut self.scene, state, p, &self.context) + .map_err(|e| io::Error::other(format!("{e:?}"))) + } + fn interaction_shape(&mut self, _: BlockStateId, _: BlockPos) -> io::Result { + Ok(VoxelShape::empty()) + } + fn fluid_is_source(&mut self, _: ()) -> io::Result { + Ok(false) + } + fn fluid_is_empty(&mut self, _: ()) -> io::Result { + Ok(true) + } + fn fluid_is_water(&mut self, _: ()) -> io::Result { + Ok(false) + } + fn fluid_shape(&mut self, _: (), _: BlockPos) -> io::Result { + Ok(VoxelShape::empty()) + } +} #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(super) enum CameraType { @@ -95,34 +187,95 @@ impl Game<'_> { pub(super) fn cycle_camera(&mut self) { self.camera_type = self.camera_type.cycle(); } - /// `Camera.setup`: the eye, or a point up to four blocks behind (or in - /// front of) it, pulled in where blocks are in the way. Returns the + /// `Camera.update` (`alignWithEntity` and `getMaxZoom`): the + /// interpolated eye, or a point up to the camera distance behind (or in + /// front of) it, pulled in where visual shapes are in the way. Returns the /// position, yaw and pitch to render from. - pub(super) fn camera_view(&self, eye: glam::DVec3) -> (glam::DVec3, f32, f32) { - let (mut yaw, mut pitch) = (self.yaw, self.pitch); - if self.camera_type.first_person() || self.player.is_none() || self.sleeping.is_some() { - return (eye, yaw, pitch); - } - if self.camera_type == CameraType::ThirdPersonFront { - yaw += 180.0; - pitch = -pitch; - } - let f = super::view_vector(yaw, pitch); - let mut dist = 4.0f64; - for i in 0..8 { - let o = [ - f64::from((i & 1) * 2 - 1) * 0.1, - f64::from((i >> 1 & 1) * 2 - 1) * 0.1, - f64::from((i >> 2 & 1) * 2 - 1) * 0.1, - ]; - let from = [eye.x + o[0], eye.y + o[1], eye.z + o[2]]; - let back = [-f[0], -f[1], -f[2]]; - if let Some(hit) = self.clip_ray(from, back, dist) { - let d = glam::DVec3::from_array(hit.point) - eye; - dist = dist.min(d.length()); - } - } - (eye - glam::DVec3::from_array(f) * dist, yaw, pitch) + pub(super) fn camera_view(&mut self, partial: f32) -> Option<(glam::DVec3, f32, f32)> { + let (scale, distance) = { + let p = self.player.as_mut()?; + ( + p.attribute("minecraft:scale").unwrap_or(1.0) as f32, + p.attribute("minecraft:camera_distance").unwrap_or(4.0), + ) + }; + let p = self.player.as_ref()?; + let sleeping = self.sleeping.map(|(head, _)| { + let state = self.world.block(head[0], head[1], head[2]); + let props = self.res.assets.registry.state(state).map(|s| &s.properties); + // BedBlock.getBedOrientation as Direction.toYRot. + props.and_then(|props| match props.get("facing").map(String::as_str) { + Some("south") => Some(0.0), + Some("west") => Some(90.0), + Some("north") => Some(180.0), + Some("east") => Some(270.0), + _ => None, + }) + }); + // A living mount at the default scale and camera distance. + let mount = self + .riding + .and_then(|id| self.mobs.iter().find(|m| m.id == id)) + .map(|_| (1.0, 4.0)); + let entity = CameraEntity { + position: [p.position.x, p.position.y, p.position.z], + previous: [ + self.previous_position.x, + self.previous_position.y, + self.previous_position.z, + ], + // Entity.turn moves the old rotation with the new: the mouse + // turns the view every frame without interpolation. + x_rot: self.pitch, + y_rot: self.yaw, + x_rot_o: self.pitch, + y_rot_o: self.yaw, + eye_height: p.dimensions.eye_height, + living: Some(LivingCamera { + scale, + camera_distance: distance, + sleeping, + dead: None, + }), + mount, + }; + let mut view = self.view; + let kind = match self.camera_type { + CameraType::FirstPerson => horizon_client::camera::CameraType::FirstPerson, + CameraType::ThirdPersonBack => horizon_client::camera::CameraType::ThirdPersonBack, + CameraType::ThirdPersonFront => horizon_client::camera::CameraType::ThirdPersonFront, + }; + let context = CollisionContext::for_entity( + CollisionEntity { + identity: EntityIdentity(0), + y: p.position.y, + descending: p.shift_key_down, + main_hand: Some(CollisionItem::EMPTY), + }, + false, + ); + let mut rays = VisualRays { + scene: SceneCollisions { + world: &self.world, + binding: self.collision, + }, + facts: &self.res.facts, + context, + }; + view.align_with_entity(&entity, partial, kind, |from, to| { + let hit = clip_world( + &mut rays, + Vec3::new(from[0], from[1], from[2]), + Vec3::new(to[0], to[1], to[2]), + RayBlockMode::Visual, + RayFluidMode::None, + 4096, + ) + .ok()?; + (!hit.miss).then(|| [hit.hit.location.x, hit.hit.location.y, hit.hit.location.z]) + }); + self.view = view; + Some((glam::DVec3::from_array(view.position), view.y_rot, view.x_rot)) } /// Keep the player's model in step with the player (`LivingEntity.tick` /// body turning, `WalkAnimationState`, the swing and the pose). diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index ab9585758..472c8d24b 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1309,6 +1309,11 @@ impl Game<'_> { | u8::from(keys.shift) << 5 | u8::from(keys.sprint) << 6; self.previous_position = player.position; + let before = ( + player.ground.on_ground, + [player.velocity.x, player.velocity.y, player.velocity.z], + [player.position.x, player.position.y, player.position.z], + ); player.yaw = self.yaw; let dead = self.screen == Screen::Dead; if !dead { @@ -1337,18 +1342,7 @@ impl Game<'_> { } // The server owns health and hunger: undo local food/fall changes. self.apply_remote_health(); - if let Some(p) = &self.player { - 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 { speed } else { 0.0 }; - self.bob.1 += (target - self.bob.1) * 0.4; - } + self.tick_avatar(before, false); if !dead { self.remote_mining(); if self.right && self.use_delay == 0 && playing { diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 264b10d32..9654d9ca3 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -40,8 +40,9 @@ 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)>, + /// The `GameRenderer.bobHurt`/`bobView` pose multiplied into the + /// projection (`crate::camera::bob_matrix`). + pub bob: Mat4, pub sky: Sky, /// Render distance in blocks (fog end). pub distance: f32, @@ -1074,14 +1075,7 @@ impl Renderer { 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(), - ) - }); + let bob = frame.bob; Mat4::perspective_rh(frame.fov_degrees.to_radians(), aspect, 0.05, far) * bob * Mat4::look_to_rh(Vec3::ZERO, forward, Vec3::Y) diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index e5080ea4a..5bb313406 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -14,6 +14,7 @@ pub mod block_entity_render; pub mod block_transform; pub mod blocks; pub mod bossbar; +pub mod camera; pub mod brewing; pub mod cauldron; pub mod chat; diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCameraOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCameraOracle.java new file mode 100644 index 000000000..9d276cbe7 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCameraOracle.java @@ -0,0 +1,419 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import com.mojang.blaze3d.vertex.PoseStack; +import java.io.*; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.*; +import net.minecraft.client.entity.ClientAvatarState; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.client.renderer.state.GameRenderState; +import net.minecraft.client.renderer.state.level.CameraRenderState; +import net.minecraft.core.*; +import net.minecraft.util.Mth; +import net.minecraft.world.attribute.EnvironmentAttributeProbe; +import net.minecraft.world.entity.*; +import net.minecraft.world.entity.ai.attributes.*; +import net.minecraft.world.entity.player.*; +import net.minecraft.world.item.*; +import net.minecraft.world.level.*; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.*; +import net.minecraft.world.phys.*; +import net.minecraft.world.phys.shapes.*; +import org.joml.Matrix4f; + +/** + * Drives the real Camera (tick, tickFov, alignWithEntity with getMaxZoom over + * Level.clip, calculateFov, calculateHudFov), AbstractClientPlayer + * .getFieldOfViewModifier and updateBob, ClientAvatarState and + * GameRenderer.bobHurt/bobView with scripted entity states, and prints every + * observable bit-exactly. Entities, the level and the renderer are + * uninitialised shells (Unsafe) with controlled queries; block visual shapes + * come from the case. + */ +public final class VanillaCameraOracle { + static Object unsafe; + static Method allocate; + + @SuppressWarnings("unchecked") + static T make(Class type) throws Exception { + return (T) allocate.invoke(unsafe, type); + } + + static Field field(Class type, String name) throws Exception { + Field f = type.getDeclaredField(name); + f.setAccessible(true); + return f; + } + + static Method method(Class type, String name, Class... args) throws Exception { + Method m = type.getDeclaredMethod(name, args); + m.setAccessible(true); + return m; + } + + static float f(JsonElement v) { + return Float.intBitsToFloat(Integer.parseUnsignedInt(v.getAsString(), 16)); + } + + static double d(JsonElement v) { + return Double.longBitsToDouble(Long.parseUnsignedLong(v.getAsString(), 16)); + } + + static String fb(float v) { + return String.format("%08x", Float.isNaN(v) ? 0x7fc00000 : Float.floatToRawIntBits(v)); + } + + static String db(double v) { + return String.format("%016x", Double.isNaN(v) ? 0x7ff8000000000000L : Double.doubleToRawLongBits(v)); + } + + static Vec3 vec(JsonElement v) { + var a = v.getAsJsonArray(); + return new Vec3(d(a.get(0)), d(a.get(1)), d(a.get(2))); + } + + // ---- level with controlled visual shapes ---------------------------------------------- + static final class State extends BlockState { + VoxelShape visual; + + State() { + super(null, null, null); + } + + @Override public VoxelShape getVisualShape(BlockGetter w, BlockPos p, CollisionContext c) { return visual; } + @Override public VoxelShape getInteractionShape(BlockGetter w, BlockPos p) { return Shapes.empty(); } + } + + static final class Level extends net.minecraft.server.level.ServerLevel { + Map cells = new HashMap<>(); + State air; + + Level() { + super(null, null, null, null, null, null, false, 0L, List.of(), false); + } + + @Override public BlockState getBlockState(BlockPos p) { return cells.getOrDefault(p, air); } + @Override public FluidState getFluidState(BlockPos p) { return Fluids.EMPTY.defaultFluidState(); } + } + + static final class NoProbe extends EnvironmentAttributeProbe { + @Override public void tick(net.minecraft.world.level.Level level, Vec3 position) { } + } + + static final class StubCamera extends Camera { + net.minecraft.world.level.material.FogType fluid = net.minecraft.world.level.material.FogType.NONE; + + @Override public net.minecraft.world.level.material.FogType getFluidInCamera() { return fluid; } + } + + // ---- camera entities ---------------------------------------------------------------- + static final class StubPlayer extends LocalPlayer { + AttributeMap attributes; + boolean using, dead, sleeping, swimming, ground; + ItemStack useItem = ItemStack.EMPTY; + int useTicks; + Direction bed; + Vec3 motion = Vec3.ZERO; + + StubPlayer() { + super(null, null, null, null, null, Input.EMPTY, false, null, null); + } + + @Override public AttributeMap getAttributes() { return attributes; } + @Override public boolean isUsingItem() { return using; } + @Override public ItemStack getUseItem() { return useItem; } + @Override public int getTicksUsingItem() { return useTicks; } + @Override public boolean isDeadOrDying() { return dead; } + @Override public boolean isSleeping() { return sleeping; } + @Override public Direction getBedOrientation() { return bed; } + @Override public boolean isDescending() { return false; } + @Override public ItemStack getMainHandItem() { return ItemStack.EMPTY; } + @Override public boolean isSwimming() { return swimming; } + @Override public boolean onGround() { return ground; } + @Override public Vec3 getDeltaMovement() { return motion; } + @Override public boolean isSpectator() { return false; } + } + + static final class StubMarker extends Marker { + StubMarker() { + super(null, null); + } + + @Override public boolean isDescending() { return false; } + } + + static Minecraft shell; + static Options options; + static Field position, xRot, yRot, eyeHeight, vehicle, abilities; + static Constructor stack; + + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + var u = Class.forName("sun.misc.Unsafe"); + unsafe = field(u, "theUnsafe").get(null); + allocate = u.getMethod("allocateInstance", Class.class); + shell = make(Minecraft.class); + field(Minecraft.class, "fixerUpper").set(shell, net.minecraft.util.datafix.DataFixers.getDataFixer()); + field(Minecraft.class, "instance").set(null, shell); + options = new Options(shell, Files.createTempDirectory("opts").toFile()); + field(Minecraft.class, "options").set(shell, options); + position = field(Entity.class, "position"); + xRot = field(Entity.class, "xRot"); + yRot = field(Entity.class, "yRot"); + eyeHeight = field(Entity.class, "eyeHeight"); + vehicle = field(Entity.class, "vehicle"); + abilities = field(Player.class, "abilities"); + stack = ItemStack.class.getDeclaredConstructor(Holder.class, int.class, net.minecraft.core.component.PatchedDataComponentMap.class); + stack.setAccessible(true); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8)); + var lines = Files.lines(Path.of(args[0]))) { + int n = 0; + for (var line : (Iterable) lines::iterator) { + var c = JsonParser.parseString(line).getAsJsonObject(); + out.println("== " + n++); + switch (c.get("t").getAsString()) { + case "fov" -> out.println(fb(player(c).getFieldOfViewModifier(c.get("fp").getAsBoolean(), f(c.get("scale"))))); + case "camera" -> camera(c, out); + case "bob" -> bob(c, out); + case "avatar" -> avatar(c, out); + default -> throw new IllegalArgumentException(line); + } + } + } + System.exit(0); + } + + static AttributeMap attributes(double scale, double distance, double speed) { + var map = new AttributeMap(Player.createAttributes().build()); + map.getInstance(Attributes.SCALE).setBaseValue(scale); + map.getInstance(Attributes.CAMERA_DISTANCE).setBaseValue(distance); + map.getInstance(Attributes.MOVEMENT_SPEED).setBaseValue(speed); + return map; + } + + /** A player shell from the "fov" fields of a case or an entity op. */ + static StubPlayer player(JsonObject c) throws Exception { + StubPlayer p = make(StubPlayer.class); + fill(p, c); + return p; + } + + static void fill(StubPlayer p, JsonObject c) throws Exception { + var a = new Abilities(); + a.flying = c.get("flying").getAsBoolean(); + a.setWalkingSpeed(f(c.get("ws"))); + abilities.set(p, a); + double scale = c.has("scale_attr") ? d(c.get("scale_attr")) : 1.0; + double distance = c.has("dist") ? d(c.get("dist")) : 4.0; + p.attributes = attributes(scale, distance, d(c.get("speed"))); + var use = c.get("use"); + p.using = !use.isJsonNull(); + if (p.using) { + var u = use.getAsJsonArray(); + Item item = switch (u.get(0).getAsString()) { + case "bow" -> Items.BOW; + case "spyglass" -> Items.SPYGLASS; + default -> Items.STICK; + }; + p.useItem = stack.newInstance(Holder.direct(item), 1, + new net.minecraft.core.component.PatchedDataComponentMap(net.minecraft.core.component.DataComponentMap.EMPTY)); + p.useTicks = u.get(1).getAsInt(); + } + } + + static void camera(JsonObject c, PrintWriter out) throws Exception { + var level = make(Level.class); + level.cells = new HashMap<>(); + level.air = make(State.class); + level.air.visual = Shapes.empty(); + for (var e : c.getAsJsonObject("cells").entrySet()) { + var at = e.getKey().split(" "); + var s = make(State.class); + VoxelShape shape = Shapes.empty(); + for (var b : e.getValue().getAsJsonArray()) { + var a = b.getAsJsonArray(); + shape = Shapes.or(shape, Shapes.box(d(a.get(0)), d(a.get(1)), d(a.get(2)), d(a.get(3)), d(a.get(4)), d(a.get(5)))); + } + s.visual = shape; + level.cells.put(new BlockPos(Integer.parseInt(at[0]), Integer.parseInt(at[1]), Integer.parseInt(at[2])), s); + } + options.fov().set(c.get("fov").getAsInt()); + options.fovEffectScale().set(d(c.get("effect"))); + options.setCameraType(CameraType.values()[c.get("type").getAsInt()]); + var camera = new StubCamera(); + field(Camera.class, "attributeProbe").set(camera, new NoProbe()); + field(Camera.class, "level").set(camera, level); + GameRenderer renderer = make(GameRenderer.class); + field(GameRenderer.class, "mainCamera").set(renderer, camera); + field(Minecraft.class, "gameRenderer").set(shell, renderer); + var align = method(Camera.class, "alignWithEntity", float.class); + var fov = method(Camera.class, "calculateFov", float.class); + var hud = method(Camera.class, "calculateHudFov", float.class); + var panoramic = field(Camera.class, "isPanoramicMode"); + var eye = field(Camera.class, "eyeHeight"); + var eyeOld = field(Camera.class, "eyeHeightOld"); + var mod = field(Camera.class, "fovModifier"); + var modOld = field(Camera.class, "oldFovModifier"); + Entity entity = null; + for (var e : c.getAsJsonArray("ops")) { + var op = e.getAsJsonArray(); + switch (op.get(0).getAsString()) { + case "entity" -> { + var s = op.get(1).getAsJsonObject(); + entity = entity(s, entity); + camera.setEntity(entity); + out.println("entity"); + } + case "type" -> { + options.setCameraType(CameraType.values()[op.get(1).getAsInt()]); + out.println("type"); + } + case "tick" -> { + camera.tick(); + out.println("tick " + fb(eye.getFloat(camera)) + " " + fb(eyeOld.getFloat(camera)) + " " + + fb(mod.getFloat(camera)) + " " + fb(modOld.getFloat(camera))); + } + case "frame" -> { + float pt = f(op.get(1)); + camera.fluid = net.minecraft.world.level.material.FogType.valueOf( + new String[] {"NONE", "WATER", "LAVA", "POWDER_SNOW"}[op.get(2).getAsInt()]); + panoramic.setBoolean(camera, op.get(3).getAsBoolean()); + align.invoke(camera, pt); + float fv = (float) fov.invoke(camera, pt); + float hv = (float) hud.invoke(camera, pt); + var p = camera.position(); + var q = camera.rotation(); + var fw = camera.forwardVector(); + var up = camera.upVector(); + var left = camera.leftVector(); + out.println("frame " + db(p.x) + " " + db(p.y) + " " + db(p.z) + " " + fb(camera.xRot()) + " " + fb(camera.yRot()) + + " " + fb(q.x) + " " + fb(q.y) + " " + fb(q.z) + " " + fb(q.w) + + " " + fb(fw.x()) + " " + fb(fw.y()) + " " + fb(fw.z()) + + " " + fb(up.x()) + " " + fb(up.y()) + " " + fb(up.z()) + + " " + fb(left.x()) + " " + fb(left.y()) + " " + fb(left.z()) + + " " + camera.isDetached() + " " + fb(fv) + " " + fb(hv)); + } + default -> throw new IllegalArgumentException(op.toString()); + } + } + } + + /** Applies an entity op: a player (with fov fields) or a non-living marker. */ + static Entity entity(JsonObject s, Entity previous) throws Exception { + Entity entity; + if (s.get("kind").getAsString().equals("player")) { + StubPlayer p = previous instanceof StubPlayer old ? old : make(StubPlayer.class); + fill(p, s); + p.dead = !s.get("dead").isJsonNull(); + if (p.dead) { + p.deathTime = s.get("dead").getAsInt(); + } + p.sleeping = !s.get("sleeping").isJsonNull(); + p.bed = null; + if (p.sleeping && !s.get("sleeping").getAsJsonArray().get(0).isJsonNull()) { + p.bed = Direction.from2DDataValue(s.get("sleeping").getAsJsonArray().get(0).getAsInt()); + } + var mount = s.get("mount"); + if (mount.isJsonNull()) { + vehicle.set(p, null); + } else { + StubPlayer m = make(StubPlayer.class); + var a = mount.getAsJsonArray(); + m.attributes = attributes(d(a.get(0)), d(a.get(1)), 0.1); + vehicle.set(p, m); + } + entity = p; + } else { + entity = previous instanceof StubMarker old ? old : make(StubMarker.class); + } + position.set(entity, vec(s.get("pos"))); + var prev = vec(s.get("prev")); + entity.xo = prev.x; + entity.yo = prev.y; + entity.zo = prev.z; + xRot.setFloat(entity, f(s.get("xr"))); + yRot.setFloat(entity, f(s.get("yr"))); + entity.xRotO = f(s.get("xro")); + entity.yRotO = f(s.get("yro")); + eyeHeight.setFloat(entity, f(s.get("eye"))); + return entity; + } + + static void bob(JsonObject c, PrintWriter out) throws Exception { + GameRenderer renderer = make(GameRenderer.class); + var state = new GameRenderState(); + field(GameRenderer.class, "gameRenderState").set(renderer, state); + state.optionsRenderState.damageTiltStrength = d(c.get("tilt")); + state.optionsRenderState.bobView = c.get("view").getAsBoolean(); + var camera = new CameraRenderState(); + var es = camera.entityRenderState; + var living = c.get("living"); + es.isLiving = !living.isJsonNull(); + if (es.isLiving) { + var l = living.getAsJsonObject(); + es.hurtTime = f(l.get("hurt")); + es.hurtDuration = l.get("duration").getAsInt(); + es.hurtDir = f(l.get("dir")); + es.isDeadOrDying = !l.get("death").isJsonNull(); + if (es.isDeadOrDying) { + es.deathTime = f(l.get("death")); + } + } + var player = c.get("player"); + es.isPlayer = !player.isJsonNull(); + if (es.isPlayer) { + es.backwardsInterpolatedWalkDistance = f(player.getAsJsonArray().get(0)); + es.bob = f(player.getAsJsonArray().get(1)); + } + var stack = new PoseStack(); + method(GameRenderer.class, "bobHurt", CameraRenderState.class, PoseStack.class).invoke(renderer, camera, stack); + if (state.optionsRenderState.bobView) { + method(GameRenderer.class, "bobView", CameraRenderState.class, PoseStack.class).invoke(renderer, camera, stack); + } + Matrix4f m = stack.last().pose(); + var sb = new StringBuilder("bob"); + for (int col = 0; col < 4; col++) { + for (int row = 0; row < 4; row++) { + sb.append(' ').append(fb(m.get(col, row))); + } + } + sb.append(' ').append(m.properties()); + out.println(sb); + } + + static void avatar(JsonObject c, PrintWriter out) throws Exception { + StubPlayer p = make(StubPlayer.class); + var state = new ClientAvatarState(); + field(net.minecraft.client.player.AbstractClientPlayer.class, "clientAvatarState").set(p, state); + var updateBob = method(net.minecraft.client.player.AbstractClientPlayer.class, "updateBob"); + for (var e : c.getAsJsonArray("ops")) { + var op = e.getAsJsonArray(); + switch (op.get(0).getAsString()) { + case "tick" -> state.tick(Vec3.ZERO, Vec3.ZERO); + case "move" -> state.addWalkDistance(Mth.length(f(op.get(1)), f(op.get(2))) * 0.6F); + case "bob" -> { + p.ground = op.get(1).getAsBoolean(); + p.dead = op.get(2).getAsBoolean(); + p.swimming = op.get(3).getAsBoolean(); + p.motion = vec(op.get(4)); + updateBob.invoke(p); + } + case "reset" -> state.resetBob(); + case "frame" -> { + float pt = f(op.get(1)); + out.println("frame " + fb(state.getInterpolatedBob(pt)) + " " + fb(state.getBackwardsInterpolatedWalkDistance(pt))); + continue; + } + default -> throw new IllegalArgumentException(op.toString()); + } + out.println(op.get(0).getAsString()); + } + } +} diff --git a/tools/test_camera_parity.py b/tools/test_camera_parity.py new file mode 100644 index 000000000..07c0ad242 --- /dev/null +++ b/tools/test_camera_parity.py @@ -0,0 +1,199 @@ +#!/usr/bin/env python3 +"""Compare the camera with the pinned client: Camera.tick (eye height and +field-of-view easing), alignWithEntity (view rotation quaternion and basis, +interpolated eye, third person back and front, camera distance and scale +attributes with mounts, getMaxZoom clipping against visual shapes, sleeping), +calculateFov/calculateHudFov (option, modifier, death and fluid effects, +panoramic mode), AbstractClientPlayer.getFieldOfViewModifier (flight, speed +attribute against walking speed, bow draw, spyglass), the walk and bob +history (ClientAvatarState, updateBob) and GameRenderer.bobHurt/bobView, +driven tick by tick and frame by frame with identical scripted states.""" +import json +import random +import struct + +try: + from . import lab, oracle_harness as harness +except ImportError: + import lab, oracle_harness as harness + + +def fbits(v): + return struct.pack('>f', v).hex() + + +def dbits(v): + return struct.pack('>d', v).hex() + + +def f32(v): + return struct.unpack('>f', struct.pack('>f', v))[0] + + +WALK = [0.1, 0.0, 0.05, 0.2, 1e-3, -0.1, 0.15] +SPEED = [f32(0.1), f32(0.1) * 1.3, 0.0, 0.03, 0.5, 1024.0, 0.13, f32(0.1) * 0.85, f32(0.1) * 1.4] +TICKS = [0, 1, 5, 10, 19, 20, 21, 72000, -5, 3] + + +def fov_fields(rng): + use = rng.choice([None, None, ['bow', rng.choice(TICKS)], ['spyglass', rng.choice(TICKS)], ['other', rng.choice(TICKS)]]) + return dict(flying=rng.random() < 0.3, ws=fbits(rng.choice(WALK + [rng.uniform(-0.3, 0.3)])), + speed=dbits(rng.choice(SPEED + [rng.uniform(0, 2)])), use=use) + + +def fov_cases(rng): + for flying in (False, True): + for ws in WALK: + for speed in SPEED: + for use in [None, ['bow', 0], ['bow', 7], ['bow', 20], ['bow', 40], ['spyglass', 2], ['other', 5]]: + for fp in (False, True): + for scale in (0.0, 0.5, 1.0): + yield dict(t='fov', flying=flying, ws=fbits(ws), speed=dbits(speed), use=use, fp=fp, scale=fbits(scale)) + for _ in range(3000): + yield dict(t='fov', **fov_fields(rng), fp=rng.random() < 0.6, scale=fbits(rng.choice([0.0, 1.0, rng.random()]))) + + +FULL = [[0, 0, 0, 1, 1, 1]] +SHAPES = [FULL, FULL, [[0, 0, 0, 1, 0.5, 1]], [[0, 0.5, 0, 1, 1, 1]], [[0, 0, 0, 1, 1, 0.125]], [[0.375, 0, 0.375, 0.625, 1, 0.625]], + [[0, 0, 0, 0.5, 1, 1], [0.5, 0, 0.5, 1, 1, 1]], []] + + +def world(rng, center): + cells = {} + cx, cy, cz = center + for _ in range(rng.choice([0, 3, 10, 40, 120])): + p = (cx + rng.randint(-6, 6), cy + rng.randint(-3, 5), cz + rng.randint(-6, 6)) + cells[f'{p[0]} {p[1]} {p[2]}'] = [[dbits(v) for v in box] for box in rng.choice(SHAPES)] + return cells + + +ANGLES = [0.0, 90.0, -90.0, 180.0, -180.0, 45.0, 360.0, 720.5, -33.3, 1e-3, 89.9] + + +def angle(rng): + return rng.choice(ANGLES + [rng.uniform(-90, 90), rng.uniform(-400, 400)]) + + +def entity_state(rng, center): + pos = [center[i] + rng.uniform(0, 1) for i in range(3)] + prev = [p - rng.choice([0, 0, 0.1, 0.3, 1.0, rng.uniform(-1, 1)]) for p in pos] + kind = 'player' if rng.random() < 0.85 else 'marker' + xr, yr = angle(rng), angle(rng) + s = dict(kind=kind, pos=[dbits(v) for v in pos], prev=[dbits(v) for v in prev], xr=fbits(xr), yr=fbits(yr), + xro=fbits(rng.choice([xr, xr - 5, angle(rng)])), yro=fbits(rng.choice([yr, yr + 10, angle(rng)])), + eye=fbits(rng.choice([1.62, 1.27, 0.4, 0.2, 0.81, 3.24, rng.uniform(0, 4)]))) + s.update(fov_fields(rng)) + s.update(scale_attr=dbits(rng.choice([1.0, 1.0, 0.5, 2.0, 0.0625, 16.0, rng.uniform(0.0625, 3)])), + dist=dbits(rng.choice([4.0, 4.0, 0.0, 1.0, 10.0, 32.0, rng.uniform(0, 32)])), + sleeping=rng.choice([None] * 6 + [[None], [0], [1], [2], [3]]), + dead=rng.choice([None] * 6 + [0, 1, 5, 19, 20, 25]), + mount=rng.choice([None] * 4 + [[dbits(rng.choice([1.0, 2.0, 0.5])), dbits(rng.choice([4.0, 8.0, 1.0]))]])) + return s + + +def camera_cases(rng): + for n in range(2500): + center = rng.choice([(0, 64, 0), (-10, -60, 7), (1000, 120, -3000), (0, 0, 0)]) + ops = [] + for _ in range(rng.randrange(1, 40)): + kind = rng.choice(['entity', 'tick', 'tick', 'tick', 'frame', 'frame', 'frame', 'type']) + if not ops: + kind = 'entity' + if kind == 'entity': + ops.append(['entity', entity_state(rng, center)]) + elif kind == 'tick': + ops.append(['tick']) + elif kind == 'frame': + pt = rng.choice([0.0, 1.0, 0.5, 0.25, 0.999, rng.random()]) + ops.append(['frame', fbits(pt), rng.choice([0, 0, 0, 1, 2, 3]), rng.random() < 0.05]) + else: + ops.append(['type', rng.randrange(3)]) + yield dict(t='camera', fov=rng.choice([70, 30, 110, 90, rng.randint(30, 110)]), + effect=dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])), type=rng.choice([0, 1, 1, 2]), + cells=world(rng, center), ops=ops) + # A walled-in third-person camera stepping through every distance bound. + for dist in [0.0, 0.5, 1.0, 2.0, 4.0, 8.0, 32.0]: + for wall in range(0, 6): + for yaw in [0.0, 90.0, 180.0, 270.0, 45.0]: + cells = {} + for dx in range(-6, 7): + for dy in range(62, 68): + cells[f'{dx} {dy} {-wall - 1}'] = [[dbits(v) for v in box] for box in FULL] + cells[f'{dx} {dy} {wall + 1}'] = [[dbits(v) for v in box] for box in FULL] + s = dict(kind='player', pos=[dbits(0.5), dbits(64.0), dbits(0.5)], prev=[dbits(0.5), dbits(64.0), dbits(0.5)], + xr=fbits(15.0), yr=fbits(yaw), xro=fbits(15.0), yro=fbits(yaw), eye=fbits(1.62), flying=False, + ws=fbits(0.1), speed=dbits(f32(0.1)), use=None, scale_attr=dbits(1.0), dist=dbits(dist), + sleeping=None, dead=None, mount=None) + ops = [['entity', s]] + [['tick']] * 6 + [['frame', fbits(pt), 0, False] for pt in (0.0, 0.5, 1.0)] + yield dict(t='camera', fov=70, effect=dbits(1.0), type=1 + (wall % 2), cells=cells, ops=ops) + + +def bob_cases(rng): + for n in range(6000): + living = None + if rng.random() < 0.8: + living = dict(hurt=fbits(rng.choice([-1.0, -0.5, 0.0, 10.0, 9.5, 5.25, 1.0, rng.uniform(-2, 11)])), + duration=rng.choice([10, 10, 0, 5, 20]), dir=fbits(rng.choice([0.0, 90.0, -45.0, 180.0, rng.uniform(-360, 360)])), + death=rng.choice([None, None, None, fbits(rng.choice([0.0, 0.5, 19.5, 20.0, 25.0, rng.uniform(0, 30)]))])) + player = None + if rng.random() < 0.8: + player = [fbits(rng.choice([0.0, -0.3, -1.7, -100.25, rng.uniform(-1000, 0)])), + fbits(rng.choice([0.0, 0.1, 0.05, 0.0999, rng.uniform(0, 0.1)]))] + yield dict(t='bob', living=living, player=player, tilt=dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])), + view=rng.random() < 0.8) + + +def avatar_cases(rng): + for n in range(1500): + ops = [] + for _ in range(rng.randrange(1, 60)): + kind = rng.choice(['tick', 'move', 'move', 'bob', 'bob', 'frame', 'frame', 'reset']) + if kind == 'tick': + ops.append(['tick']) + elif kind == 'move': + ops.append(['move', fbits(rng.choice([0.0, 0.2158, -0.1, rng.uniform(-1, 1)])), fbits(rng.choice([0.0, 0.2806, rng.uniform(-1, 1)]))]) + elif kind == 'bob': + v = [rng.choice([0.0, 0.05, -0.2, rng.uniform(-0.5, 0.5)]), rng.uniform(-1, 1), rng.choice([0.0, 0.08, rng.uniform(-0.5, 0.5)])] + ops.append(['bob', rng.random() < 0.7, rng.random() < 0.1, rng.random() < 0.1, [dbits(x) for x in v]]) + elif kind == 'frame': + ops.append(['frame', fbits(rng.choice([0.0, 1.0, 0.5, rng.random()]))]) + else: + ops.append(['reset']) + yield dict(t='avatar', ops=ops) + + +def make_cases(build): + rng = random.Random(0x43414d45) + path = build / 'cases.jsonl' + cases = build / 'cases' + cases.mkdir(exist_ok=True) + count = 0 + with path.open('w') as out: + for generator in (fov_cases, camera_cases, bob_cases, avatar_cases): + for case in generator(rng): + text = json.dumps(case, separators=(',', ':')) + out.write(text + '\n') + if count < 20000: + (cases / str(count)).write_text(text) + count += 1 + return path, count + + +def main(): + scope = ('Real Camera.tick, tickFov, alignWithEntity (setRotation quaternion and forwards/up/left basis, move, ' + 'interpolated eye with eye-height easing, first person, third person back and mirrored front, scale and ' + 'camera_distance attributes including a living mount, getMaxZoom over the actual Level.clip with ' + 'ClipContext.Block.VISUAL against controlled visual shapes, sleeping bed orientation), calculateFov and ' + 'calculateHudFov (option, eased modifier, death, water/lava with the effect scale, panoramic), ' + 'AbstractClientPlayer.getFieldOfViewModifier with real Abilities, attribute maps and item stacks, ' + 'ClientAvatarState walk/bob history with AbstractClientPlayer.updateBob, and GameRenderer.bobHurt/bobView ' + 'as the full JOML pose matrix with its property flags. The camera entity is a shell with controlled ' + 'queries; getFluidInCamera is supplied (the fog harnesses cover fluid detection) and the new-minecart ' + 'interpolation branch is not exercised.') + harness.differential( + 'rust-camera-parity', 'VanillaCameraOracle', 'camera_probe', make_cases, scope, + sources=[lab.ROOT / 'crates/horizon-client/src/camera.rs']) + + +if __name__ == '__main__': + main()