diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index c9b652428..cf642b036 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9059,6 +9059,11 @@ impl Game<'_> { ) -> Result<()> { world_loading::world_data_used(); self.mods.world_id = Some(format!("world:{folder}")); + // Another world's camera projects nothing here until its first frame. + #[cfg(feature = "mods")] + { + self.mods.camera = None; + } if self.defer_world_entry(PendingWorldEntry::Local { folder: folder.to_owned(), name: name.map(str::to_owned), @@ -12173,6 +12178,13 @@ impl Game<'_> { self.mods .mods .note_camera_frame(!frame.title, main_view, renderer.drawn_mod_views()); + // The camera mods project through (`render.project`): the one this + // frame was drawn from, the player's own view or a mod's main view, + // the bob and the spin included (the TAA jitter is sub-pixel). + self.mods.camera = (!frame.title).then(|| horizon_mods::Camera { + eye: frame.camera.to_array(), + view_projection: renderer.view_projection(&frame).to_cols_array(), + }); } // Restore storage even when rendering fails (for example, a lost surface). self.entity_vertices = entities; diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 736b302a8..a71bd8528 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -60,6 +60,10 @@ pub(super) struct ModsState { /// Capability `render`'s camera shakes. #[cfg(feature = "mods")] pub(super) shake: super::mod_render::Shake, + /// The camera the last drawn frame used (`render.project`, AirDef fork): + /// none on the title screen and before the first world frame. + #[cfg(feature = "mods")] + pub(super) camera: Option, /// What blocks are to capability `render`'s world queries (AirDef fork). #[cfg(feature = "mods")] pub(super) world_tables: Option>, @@ -589,6 +593,7 @@ impl Game<'_> { player, clock, gui_size: self.gui_size(), + camera: self.mods.camera, held: self.mod_held(), frame: self.frame_reading(), mappings, diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 9f938df59..446900302 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -345,6 +345,11 @@ impl Game<'_> { // A server's own world; joining the world this window hosts keeps its folder. if local.is_none() { self.mods.world_id = Some(format!("server:{address}")); + // Another world's camera projects nothing here until its first frame. + #[cfg(feature = "mods")] + { + self.mods.camera = None; + } } let root = self.options.resources.clone(); let builtin = Builtin::find(&root) diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index 586feb225..8428f89a3 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -459,6 +459,14 @@ interface render { set-hud: func(shapes: list); /// The screen's size in GUI pixels (width, height), as of this tick. gui-size: func() -> tuple; + /// Where a world point lands on the screen, in GUI pixels from the top + /// left, through the camera the last drawn frame used (AirDef fork, API + /// level 31): the player's own view, or the `set-main-view` camera when + /// one is up, at most a frame behind. None for a point behind the camera, + /// and with no world or drawn frame yet. A point off the screen still + /// projects, past its edges: the caller clips. For a mod's `set-hud` + /// markers over the world as the player sees it. + project: func(x: f64, y: f64, z: f64) -> option; /// Shakes the camera: a jolt of `strength` (0 to 1, 1 the hardest) that /// fades out over `seconds` (at most 10). Jolts add up to 1. The view /// turns, the player doesn't, and the player's Distortion Effects option diff --git a/crates/horizon-mods/src/api_level.rs b/crates/horizon-mods/src/api_level.rs index 15e5fafed..91f5b12e9 100644 --- a/crates/horizon-mods/src/api_level.rs +++ b/crates/horizon-mods/src/api_level.rs @@ -7,13 +7,13 @@ //! version's level so the launcher can tell before it installs. /// The newest level this Horizon serves. -pub const LEVEL: u32 = 30; +pub const LEVEL: u32 = 31; /// Every function the game offers mods, as `interface.function`, with its /// level. Level 0 is the contract of Horizon 0.2.67 to 0.2.69. A new /// function takes the next level and raises [`LEVEL`] (the `api_reference` /// test fails until it is listed here). -pub const FUNCTIONS: [(&str, u32); 97] = [ +pub const FUNCTIONS: [(&str, u32); 98] = [ ("log.write", 0), ("game.get-player", 0), ("game.get-clock", 0), @@ -126,6 +126,8 @@ pub const FUNCTIONS: [(&str, u32); 97] = [ ("render.point-lights-status", 28), ("render.sound-sources-status", 29), ("render.camera-status", 30), + // AirDef fork: a world point on the screen, through the last drawn frame's camera. + ("render.project", 31), ]; /// What the game's program carries so the launcher can read its level diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index 4a6c5371b..da298e0d1 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -153,6 +153,15 @@ const STORAGE_MAX_KEYS: usize = 64; /// cap, separate from the on-disk quota it would otherwise stay under. const STORAGE_WRITE_BUDGET: u64 = 1 << 20; +/// The camera a frame was drawn from, for `render.project` (AirDef fork): +/// the eye in world blocks and the view-projection matrix the world was drawn +/// with (column-major, as glam writes it), the bob and the spin included. +#[derive(Clone, Copy, Debug)] +pub struct Camera { + pub eye: [f64; 3], + pub view_projection: [f32; 16], +} + /// What mods may read of the game, copied once per tick by the game. #[derive(Clone, Debug, Default)] pub struct Snapshot { @@ -160,6 +169,9 @@ pub struct Snapshot { pub clock: Option, /// The screen in GUI pixels (capability `render`'s `gui-size`). pub gui_size: (f32, f32), + /// The last drawn frame's camera (capability `render`'s `project`, + /// AirDef fork): none on the title screen and before the first frame. + pub camera: Option, /// The main hand's stack (capability `input`'s `held`). pub held: Option, /// The game's frame counter: fps, min, 1% low (`render.frame-stats`). @@ -2701,6 +2713,40 @@ fn capture_owner_state(t: &ModelTable, run_serial: u64) -> render::CapabilitySta reason, } } +/// Where a world point lands in GUI pixels through the camera a frame was +/// drawn from (`render.project`, AirDef fork): the point relative to the eye, +/// through the view-projection, then clip space to the screen. None behind +/// the camera (or on it), and with no camera yet; a point off the screen +/// still projects, past its edges, for the caller to clip. +fn project_point(camera: Option, gui: (f32, f32), p: [f64; 3]) -> Option { + let cam = camera?; + if !p.iter().chain(cam.eye.iter()).all(|c| c.is_finite()) { + return None; + } + let m = &cam.view_projection; + if !m.iter().all(|c| c.is_finite()) { + return None; + } + // Camera-relative, as the world's geometry is drawn: f32 keeps the + // precision the renderer itself has far from the origin. + let rel = [ + (p[0] - cam.eye[0]) as f32, + (p[1] - cam.eye[1]) as f32, + (p[2] - cam.eye[2]) as f32, + ]; + // Column-major: clip_i = sum_j m[j * 4 + i] * v_j, with v = (rel, 1). + let clip: [f32; 4] = + std::array::from_fn(|i| m[i] * rel[0] + m[4 + i] * rel[1] + m[8 + i] * rel[2] + m[12 + i]); + if clip[3] <= 1e-6 { + return None; + } + let (x, y) = (clip[0] / clip[3], clip[1] / clip[3]); + if !x.is_finite() || !y.is_finite() { + return None; + } + Some(RenderPoint { x: (x + 1.0) * 0.5 * gui.0, y: (1.0 - y) * 0.5 * gui.1 }) +} + impl render::Host for State { fn set_hud(&mut self, shapes: Vec) { self.shapes = clip_shapes(shapes) @@ -2809,6 +2855,9 @@ impl render::Host for State { fn gui_size(&mut self) -> (f32, f32) { self.snapshot.gui_size } + fn project(&mut self, x: f64, y: f64, z: f64) -> Option { + project_point(self.snapshot.camera, self.snapshot.gui_size, [x, y, z]) + } fn shake(&mut self, strength: f32, seconds: f32) { let ok = |v: f32, max: f32| { if v.is_finite() { @@ -3901,3 +3950,170 @@ mod tree_tests { assert!(check_tree(&too_many).is_err()); } } + +#[cfg(test)] +mod project_tests { + use super::*; + + /// A camera as the game builds one for a frame, from the look basis alone + /// (an independent path to `camera::view_matrix`'s quaternion): yaw 0 + /// looks south (+z), pitch 90 down, the vertical fov in degrees. The + /// matrix is column-major, clip = vp * (point - eye). + fn camera(eye: [f64; 3], yaw: f32, pitch: f32, fov: f32, aspect: f32) -> Camera { + let (sy, cy) = (yaw.to_radians().sin(), yaw.to_radians().cos()); + let (sp, cp) = (pitch.to_radians().sin(), pitch.to_radians().cos()); + let forward = [-sy * cp, -sp, cy * cp]; + let up = [-sy * sp, cp, cy * sp]; + let right = [-cy, 0.0, sy]; + let h = (fov * 0.5).to_radians().tan(); + let (m0, m5) = (1.0 / (h * aspect), 1.0 / h); + let (near, far) = (0.05f32, 1000.0f32); + let (m10, m14) = (far / (near - far), far * near / (near - far)); + let mut m = [0.0f32; 16]; + for j in 0..3 { + m[j * 4] = m0 * right[j]; + m[j * 4 + 1] = m5 * up[j]; + m[j * 4 + 2] = -m10 * forward[j]; + m[j * 4 + 3] = forward[j]; + } + m[14] = m14; + Camera { eye, view_projection: m } + } + + const GUI: (f32, f32) = (800.0, 600.0); + + #[test] + fn a_point_ahead_lands_where_the_camera_looks() { + let cam = camera([0.0, 64.0, 0.0], 0.0, 0.0, 90.0, GUI.0 / GUI.1); + // Straight ahead on the horizon: the screen's centre. + let p = project_point(Some(cam), GUI, [0.0, 64.0, 10.0]).unwrap(); + assert!((p.x - 400.0).abs() < 0.01 && (p.y - 300.0).abs() < 0.01, "{p:?}"); + // Above the horizon: towards the top edge; a right-angle fov puts a + // point one block up per block ahead at 45 degrees, the top edge. + let p = project_point(Some(cam), GUI, [0.0, 74.0, 10.0]).unwrap(); + assert!(p.y.abs() < 0.01, "{p:?}"); + // Minecraft's yaw 0 looks south (+z) with west (-x) to the right. + let p = project_point(Some(cam), GUI, [-10.0, 64.0, 10.0]).unwrap(); + assert!(p.x > 400.0 && (p.y - 300.0).abs() < 0.01, "{p:?}"); + // Yaw 90 looks west: a point west is the centre now. + let cam = camera([0.0, 64.0, 0.0], 90.0, 0.0, 90.0, GUI.0 / GUI.1); + let p = project_point(Some(cam), GUI, [-10.0, 64.0, 0.0]).unwrap(); + assert!((p.x - 400.0).abs() < 0.01 && (p.y - 300.0).abs() < 0.01, "{p:?}"); + // Pitch 90 looks straight down: a point below is the centre. + let cam = camera([0.0, 64.0, 0.0], 0.0, 90.0, 90.0, GUI.0 / GUI.1); + let p = project_point(Some(cam), GUI, [0.0, 54.0, 0.0]).unwrap(); + assert!((p.x - 400.0).abs() < 0.01 && (p.y - 300.0).abs() < 0.01, "{p:?}"); + } + + #[test] + fn behind_the_camera_and_no_camera_have_no_place() { + let cam = camera([0.0, 64.0, 0.0], 0.0, 0.0, 90.0, GUI.0 / GUI.1); + assert!(project_point(Some(cam), GUI, [0.0, 64.0, -10.0]).is_none()); + // On the eye itself: no direction to project along. + assert!(project_point(Some(cam), GUI, [0.0, 64.0, 0.0]).is_none()); + assert!(project_point(None, GUI, [0.0, 64.0, 10.0]).is_none()); + assert!(project_point(Some(cam), GUI, [f64::NAN, 64.0, 10.0]).is_none()); + let mut bad = cam; + bad.view_projection[0] = f32::NAN; + assert!(project_point(Some(bad), GUI, [0.0, 64.0, 10.0]).is_none()); + } + + #[test] + fn off_screen_points_project_past_the_edges() { + let cam = camera([0.0, 64.0, 0.0], 0.0, 0.0, 90.0, GUI.0 / GUI.1); + // Far to the west: past the right edge, still a place (the caller clips). + let p = project_point(Some(cam), GUI, [-100.0, 64.0, 10.0]).unwrap(); + assert!(p.x > GUI.0 && p.y > 0.0 && p.y < GUI.1, "{p:?}"); + // Far below the horizon: past the bottom edge. + let p = project_point(Some(cam), GUI, [0.0, -100.0, 10.0]).unwrap(); + assert!(p.y > GUI.1, "{p:?}"); + } + + #[test] + fn the_eye_moves_the_picture_not_the_world() { + // The same world point through two eyes: the projection is relative + // to the camera, as the drawn world is. + let a = camera([0.0, 64.0, 0.0], 0.0, 0.0, 70.0, GUI.0 / GUI.1); + let b = camera([10.0, 64.0, 0.0], 0.0, 0.0, 70.0, GUI.0 / GUI.1); + let pa = project_point(Some(a), GUI, [0.0, 64.0, 100.0]).unwrap(); + let pb = project_point(Some(b), GUI, [0.0, 64.0, 100.0]).unwrap(); + // Facing south, west is to the right: an eye moved east sees the + // point further west of itself, further right on the screen. + assert!(pb.x > pa.x, "moving east must move the point right: {pa:?} {pb:?}"); + } + + /// A host state with this snapshot, for the wiring of `render.project`. + fn state(snapshot: Snapshot) -> State { + State { + name: "test".into(), + id: "test".into(), + snapshot: Arc::new(snapshot), + out: Vec::new(), + panel: None, + ui: UiState::default(), + shapes: Vec::new(), + corner: None, + canvas: CanvasState::default(), + zoom: None, + minimap: None, + far_terrain: None, + models: Vec::new(), + model_table: Arc::new(Mutex::new(ModelTable::default())), + ground_queries: Vec::new(), + chunk_requests: Vec::new(), + ground: Vec::new(), + ray_queries: Vec::new(), + ray_over: Vec::new(), + rays: Vec::new(), + world_seen: false, + section_queries: Vec::new(), + sections_asked: 0, + sections: Vec::new(), + world_changes: None, + post: None, + post_params: Vec::new(), + views: Vec::new(), + main_view: None, + views_request_generation: None, + views_prepared: Vec::new(), + lights: Vec::new(), + point_request_generation: None, + point_cached_generation: None, + point_prepared_generation: None, + spots: Vec::new(), + sources: Default::default(), + source_request: None, + source_taken: false, + source_prepared: false, + run_serial: 1, + lighting: None, + time_override: None, + trees: Vec::new(), + lists: Vec::new(), + tree_generation: 0, + smoke: Vec::new(), + smoke_clock: (0.0, 0.0), + smoke_request_generation: None, + acoustics_request: None, + input: InputState::default(), + browser: BrowserState::default(), + data_dir: PathBuf::from("."), + storage_budget: STORAGE_WRITE_BUDGET, + limits: StoreLimitsBuilder::new().memory_size(MEMORY).instances(16).build(), + world: Arc::new(Mutex::new(None)), + } + } + + #[test] + fn the_host_projects_through_the_snapshots_camera_and_gui() { + let cam = camera([5.0, 70.0, -3.0], 30.0, -10.0, 70.0, 1024.0 / 768.0); + let snapshot = Snapshot { camera: Some(cam), gui_size: (1024.0, 768.0), ..Default::default() }; + let mut s = state(snapshot); + let p = render::Host::project(&mut s, 20.0, 80.0, 40.0).unwrap(); + let want = project_point(Some(cam), (1024.0, 768.0), [20.0, 80.0, 40.0]).unwrap(); + assert_eq!((p.x, p.y), (want.x, want.y)); + // No camera in the snapshot (the title screen): no place anywhere. + let mut s = state(Snapshot { gui_size: (1024.0, 768.0), ..Default::default() }); + assert!(render::Host::project(&mut s, 20.0, 80.0, 40.0).is_none()); + } +} diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index cabf6f7af..f26b1d275 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -605,7 +605,7 @@ fn smoke_handshake_keeps_fallback_until_the_current_world_is_ready() { let functions = horizon_mods::api_level::imports(&wasm).unwrap(); assert_eq!( horizon_mods::api_level::needed(functions.iter().map(String::as_str)), - (30, Some("render.camera-status")) + (31, Some("render.project")) ); let mut mods = load("horizon_mods_test_ui_guest.hmod"); let snapshot = |world: &str| Snapshot { @@ -944,7 +944,7 @@ experimental = ["ui", "render", "input", "recipes"] needed(imports(&wasm).unwrap().iter().map(String::as_str)).0 }; assert_eq!(level("coords_hud.hmod"), 0); - // The UI guest calls the level-29 sound-source handshake. + // The UI guest calls the newest level's function (render.project). assert_eq!(level("horizon_mods_test_ui_guest.hmod"), LEVEL); } diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index c6e8b2141..5b7337b8c 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -141,6 +141,7 @@ impl Mod for Guest { "view_clear", "view_main", "camera_status", + "project", "recipes", "browser", "browser_poll", @@ -258,6 +259,10 @@ impl Mod for Guest { cameras.join(";") )); } + "project" => { + let p = render::project(1.0, 2.0, 3.0); + chat::show(&format!("{p:?}")); + } "cap_status" => { let a = render::acoustics_status(); let c = render::capture_owner_status(); diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index 365af3000..31b8aa889 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -907,6 +907,7 @@ Where a capture is. | --- | --- | --- | | `set-hud` | `func(shapes: list)` | Replaces the mod's HUD shapes: up to 1024, drawn every frame in order over the HUD (after the hotbar, under chat and screens), hidden with the HUD (F1). An empty list removes them. | | `gui-size` | `func() -> tuple` | The screen's size in GUI pixels (width, height), as of this tick. | +| `project` | `func(x: f64, y: f64, z: f64) -> option` | Where a world point lands on the screen, in GUI pixels from the top left, through the camera the last drawn frame used (AirDef fork, API level 31): the player's own view, or the `set-main-view` camera when one is up, at most a frame behind. None for a point behind the camera, and with no world or drawn frame yet. A point off the screen still projects, past its edges: the caller clips. For a mod's `set-hud` markers over the world as the player sees it. | | `shake` | `func(strength: f32, seconds: f32)` | Shakes the camera: a jolt of `strength` (0 to 1, 1 the hardest) that fades out over `seconds` (at most 10). Jolts add up to 1. The view turns, the player doesn't, and the player's Distortion Effects option scales it (0 turns it off). | | `set-corner` | `func(corner: corner, width: f32, height: f32, shapes: list)` | Replaces the mod's corner panel: shapes in GUI pixels from the top left of a `width` × `height` box that the game places in `corner`, stacked with the game's overlays and the other mods' panels (under the status effects at the top right), as `hud`'s panels are. | | `clear-corner` | `func()` | Removes the mod's corner panel. |