diff --git a/native/ios/Cargo.lock b/native/ios/Cargo.lock index 2707f6bd..68a5374d 100644 --- a/native/ios/Cargo.lock +++ b/native/ios/Cargo.lock @@ -56,6 +56,26 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f09c37bc0e9f0924b7dae9988265ef3c76c88538f41a3b06caf4bed07cee5226" +[[package]] +name = "bincode" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36eaf5d7b090263e8150820482d5d93cd964a81e4019913c972f4edcc6edb740" +dependencies = [ + "bincode_derive", + "serde", + "unty", +] + +[[package]] +name = "bincode_derive" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf95709a440f45e986983918d0e8a1f30a9b1df04918fc828670606804ac3c09" +dependencies = [ + "virtue", +] + [[package]] name = "bit-set" version = "0.9.1" @@ -115,11 +135,20 @@ dependencies = [ "wgpu", ] +[[package]] +name = "bloom-scene-format" +version = "0.1.0" +dependencies = [ + "bincode", + "sha2", +] + [[package]] name = "bloom-shared" version = "0.1.0" dependencies = [ "bloom-geometry-format", + "bloom-scene-format", "bytemuck", "cmake", "earcutr", @@ -132,8 +161,10 @@ dependencies = [ "libc", "log", "minimp3", + "naga", "raw-window-handle", "serde_json", + "sha2", "web-sys", "wgpu", ] @@ -820,6 +851,7 @@ dependencies = [ "log", "num-traits", "once_cell", + "pp-rs", "rustc-hash", "spirv", "thiserror 2.0.18", @@ -996,6 +1028,15 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "pp-rs" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb458bb7f6e250e6eb79d5026badc10a3ebb8f9a15d1fff0f13d17c71f4d6dee" +dependencies = [ + "unicode-xid", +] + [[package]] name = "presser" version = "0.3.1" @@ -1312,6 +1353,18 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "unty" +version = "0.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d49784317cd0d1ee7ec5c716dd598ec5b4483ea832a2dced265471cc0f690ae" + [[package]] name = "urlencoding" version = "2.1.3" @@ -1324,6 +1377,12 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "virtue" +version = "0.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "051eb1abcf10076295e815102942cc58f9d5e3b4560e46e53c21e8ff6f3af7b1" + [[package]] name = "wasm-bindgen" version = "0.2.122" diff --git a/native/ios/src/lib.rs b/native/ios/src/lib.rs index a5952fbc..9d001b5c 100644 --- a/native/ios/src/lib.rs +++ b/native/ios/src/lib.rs @@ -104,6 +104,25 @@ unsafe impl RefEncode for CGRect { const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING); } +#[repr(C)] +#[derive(Copy, Clone)] +struct UIEdgeInsets { + top: f64, + left: f64, + bottom: f64, + right: f64, +} + +unsafe impl Encode for UIEdgeInsets { + const ENCODING: Encoding = Encoding::Struct( + "UIEdgeInsets", + &[Encoding::Double, Encoding::Double, Encoding::Double, Encoding::Double], + ); +} +unsafe impl RefEncode for UIEdgeInsets { + const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING); +} + // ============================================================ // ObjC runtime // ============================================================ @@ -444,7 +463,10 @@ unsafe extern "C" fn scene_will_connect( .unwrap_or(surface_caps.formats[0]); let surface_config = wgpu::SurfaceConfiguration { - usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + // COPY_SRC (where the surface offers it, as Metal does): bloom_take_screenshot reads + // the swapchain back, and without the flag the copy is a validation error that aborts. + usage: wgpu::TextureUsages::RENDER_ATTACHMENT + | (surface_caps.usages & wgpu::TextureUsages::COPY_SRC), format, width: pixel_width, height: pixel_height, @@ -609,7 +631,10 @@ pub unsafe extern "C" fn perry_scene_will_connect(scene: *const c_void) { .unwrap_or(surface_caps.formats[0]); let surface_config = wgpu::SurfaceConfiguration { - usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + // COPY_SRC (where the surface offers it, as Metal does): bloom_take_screenshot reads + // the swapchain back, and without the flag the copy is a validation error that aborts. + usage: wgpu::TextureUsages::RENDER_ATTACHMENT + | (surface_caps.usages & wgpu::TextureUsages::COPY_SRC), format, width: pixel_width, height: pixel_height, @@ -968,6 +993,26 @@ pub extern "C" fn bloom_begin_drawing() { let view_ptr = Retained::as_ptr(view); let layer: Retained = msg_send![&*view_ptr, layer]; let view_bounds: CGRect = msg_send![&*view_ptr, bounds]; + // The view's own display scale and safe area, not UIScreen.mainScreen's: + // on a device with two displays (iPhone Duo) the main screen is + // ambiguous, and the safe area follows rotation, split view and the + // device opening or closing. Published for getDisplayScale() / + // getSafeAreaInset(), in the pixels getScreenWidth() reports. + let traits: *const AnyObject = msg_send![&*view_ptr, traitCollection]; + if !traits.is_null() { + let display_scale: f64 = msg_send![&*traits, displayScale]; + if display_scale.is_finite() && display_scale > 0.0 { + SCREEN_SCALE = display_scale; + } + } + let insets: UIEdgeInsets = msg_send![&*view_ptr, safeAreaInsets]; + bloom_shared::display::set_display_scale(SCREEN_SCALE); + bloom_shared::display::set_safe_area_insets( + insets.top * SCREEN_SCALE, + insets.right * SCREEN_SCALE, + insets.bottom * SCREEN_SCALE, + insets.left * SCREEN_SCALE, + ); let scale = SCREEN_SCALE; let pw = (view_bounds.size.width * scale) as u32; let ph = (view_bounds.size.height * scale) as u32; diff --git a/native/shared/build.rs b/native/shared/build.rs index b047397e..b4e6bb35 100644 --- a/native/shared/build.rs +++ b/native/shared/build.rs @@ -139,9 +139,17 @@ fn build_jolt() { // 2. The Jolt build is expensive and identical across every cargo target // hash — caching it once per profile lets `cargo clean` not nuke a // multi-minute compile. + // Apple simulators share target_os/target_arch with the device (only the + // "sim" ABI tells them apart), so they need their own cache: a shared one + // hands simulator objects to a device link and ld rejects the platform. + let sim_suffix = if std::env::var("CARGO_CFG_TARGET_ABI").as_deref() == Ok("sim") { + "-sim" + } else { + "" + }; let dst = shim_dir .join("build") - .join(format!("{}-{}", target_os, target_arch)); + .join(format!("{}-{}{}", target_os, target_arch, sim_suffix)); let lib_ext = if target_os == "windows" { "lib" } else { "a" }; let lib_prefix = if target_os == "windows" { "" } else { "lib" }; diff --git a/native/shared/src/display.rs b/native/shared/src/display.rs new file mode 100644 index 00000000..6acf7ddc --- /dev/null +++ b/native/shared/src/display.rs @@ -0,0 +1,59 @@ +//! What the platform knows about the display beyond the window's size: its +//! scale (physical pixels per point) and the safe-area insets (the part of the +//! window the Dynamic Island, a notch, rounded corners, the home indicator or +//! a foldable's status-bar column cover). +//! +//! Platforms that have these values report them every frame (iOS from the +//! view's trait collection and `safeAreaInsets`, which follow rotation, split +//! view and an iPhone Duo opening or closing); everywhere else the scale is 1 +//! and the insets are 0. The insets are in the units of `getScreenWidth()` +//! (pixels on iOS, points on macOS — see EN-024). +//! +//! Plain atomics, not EngineState: iOS writes them from the frame, the FFI +//! reads them from the game thread, and neither needs the engine to exist. +use std::sync::atomic::{AtomicU64, Ordering}; + +static SCALE: AtomicU64 = AtomicU64::new(0); +static INSETS: [AtomicU64; 4] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]; + +/// Edges, in the order `getSafeAreaInset(edge)` takes them. +pub const TOP: usize = 0; +pub const RIGHT: usize = 1; +pub const BOTTOM: usize = 2; +pub const LEFT: usize = 3; + +pub fn set_display_scale(scale: f64) { + if scale.is_finite() && scale > 0.0 { + SCALE.store(scale.to_bits(), Ordering::Relaxed); + } +} + +/// Physical pixels per point; 1 where the platform doesn't report it. +pub fn display_scale() -> f64 { + let v = f64::from_bits(SCALE.load(Ordering::Relaxed)); + if v > 0.0 { v } else { 1.0 } +} + +/// tvOS: whether the Siri Remote's Menu button leaves the app (hands the press to UIKit, which +/// goes back to the Home screen) instead of reaching the game. Apple requires that at the app's +/// top level (its title screen); everywhere else Menu is the game's "back". +static MENU_EXITS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +pub fn set_menu_exits(on: bool) { + MENU_EXITS.store(on, Ordering::Relaxed); +} + +pub fn menu_exits() -> bool { + MENU_EXITS.load(Ordering::Relaxed) +} + +pub fn set_safe_area_insets(top: f64, right: f64, bottom: f64, left: f64) { + for (slot, v) in INSETS.iter().zip([top, right, bottom, left]) { + slot.store(if v.is_finite() && v > 0.0 { v } else { 0.0 }.to_bits(), Ordering::Relaxed); + } +} + +/// One edge's inset (TOP, RIGHT, BOTTOM, LEFT); 0 for an unknown edge. +pub fn safe_area_inset(edge: usize) -> f64 { + INSETS.get(edge).map_or(0.0, |v| f64::from_bits(v.load(Ordering::Relaxed))) +} diff --git a/native/shared/src/ffi_core/game_loop.rs b/native/shared/src/ffi_core/game_loop.rs index 3e919bf6..d6d112eb 100644 --- a/native/shared/src/ffi_core/game_loop.rs +++ b/native/shared/src/ffi_core/game_loop.rs @@ -38,6 +38,29 @@ macro_rules! __bloom_ffi_game_loop { $crate::ffi::guard("bloom_get_fps", move || engine().get_fps()) } + // bloom_get_display_scale [source: ios] + #[no_mangle] + pub extern "C" fn bloom_get_display_scale() -> f64 { + $crate::ffi::guard("bloom_get_display_scale", move || $crate::display::display_scale()) + } + + // bloom_get_safe_area_inset [source: ios] + #[no_mangle] + pub extern "C" fn bloom_get_safe_area_inset(edge: f64) -> f64 { + $crate::ffi::guard("bloom_get_safe_area_inset", move || { + if edge >= 0.0 { $crate::display::safe_area_inset(edge as usize) } else { 0.0 } + }) + } + + // bloom_set_menu_button_exits [source: tvos] + #[no_mangle] + pub extern "C" fn bloom_set_menu_button_exits(on: f64) -> f64 { + $crate::ffi::guard("bloom_set_menu_button_exits", move || { + $crate::display::set_menu_exits(on != 0.0); + 1.0 + }) + } + // bloom_get_screen_width [source: macos] #[no_mangle] pub extern "C" fn bloom_get_screen_width() -> f64 { diff --git a/native/shared/src/ffi_core/visual.rs b/native/shared/src/ffi_core/visual.rs index 78f7ed7e..9960a6a1 100644 --- a/native/shared/src/ffi_core/visual.rs +++ b/native/shared/src/ffi_core/visual.rs @@ -413,6 +413,14 @@ macro_rules! __bloom_ffi_visual { }) } + // bloom_set_camera_clip_planes [source: macos] + #[no_mangle] + pub extern "C" fn bloom_set_camera_clip_planes(near: f64, far: f64) -> f64 { + $crate::ffi::guard_applied("bloom_set_camera_clip_planes", move || { + engine().renderer.set_camera_clip_planes(near as f32, far as f32); + }) + } + // bloom_set_taa_enabled [source: macos] #[no_mangle] pub extern "C" fn bloom_set_taa_enabled(on: f64) -> f64 { diff --git a/native/shared/src/input.rs b/native/shared/src/input.rs index 49e2312b..7d5f48b9 100644 --- a/native/shared/src/input.rs +++ b/native/shared/src/input.rs @@ -64,6 +64,12 @@ pub struct InputState { mouse_down: [bool; MAX_MOUSE_BUTTONS], mouse_released: [bool; MAX_MOUSE_BUTTONS], prev_mouse_down: [bool; MAX_MOUSE_BUTTONS], + // A press / release seen since the last begin_frame. iOS delivers touches + // (synthesized into mouse button 0) on the UI thread while the game thread + // renders, so a whole tap can start and end between two begin_frames; + // these latches keep its edges for the next frame to report. + mouse_press_latch: [bool; MAX_MOUSE_BUTTONS], + mouse_release_latch: [bool; MAX_MOUSE_BUTTONS], // Gamepad pub gamepad_available: bool, @@ -131,6 +137,8 @@ impl InputState { mouse_down: [false; MAX_MOUSE_BUTTONS], mouse_released: [false; MAX_MOUSE_BUTTONS], prev_mouse_down: [false; MAX_MOUSE_BUTTONS], + mouse_press_latch: [false; MAX_MOUSE_BUTTONS], + mouse_release_latch: [false; MAX_MOUSE_BUTTONS], gamepad_available: false, gamepad_axes: [0.0; MAX_GAMEPAD_AXES], gamepad_buttons_down: [false; MAX_GAMEPAD_BUTTONS], @@ -190,9 +198,22 @@ impl InputState { self.repeat_pending[i] = false; } for i in 0..MAX_MOUSE_BUTTONS { - self.mouse_pressed[i] = self.mouse_down[i] && !self.prev_mouse_down[i]; - self.mouse_released[i] = !self.mouse_down[i] && self.prev_mouse_down[i]; + self.mouse_pressed[i] = + (self.mouse_down[i] && !self.prev_mouse_down[i]) || self.mouse_press_latch[i]; + self.mouse_released[i] = + (!self.mouse_down[i] && self.prev_mouse_down[i]) || self.mouse_release_latch[i]; + self.mouse_press_latch[i] = false; + self.mouse_release_latch[i] = false; } + // The state these edges were computed from is the previous state for + // the next frame. Taking it here rather than in end_frame matters when + // input arrives from another thread (iOS touches): a change landing + // between begin_frame and end_frame was otherwise copied into prev_* + // without any frame ever reporting its edge, so a released finger never + // produced a release and a tap never produced a click. + self.prev_keys_down = self.keys_down; + self.prev_mouse_down = self.mouse_down; + self.prev_gamepad_buttons = self.gamepad_buttons_down; for i in 0..MAX_GAMEPAD_BUTTONS { self.gamepad_buttons_pressed[i] = self.gamepad_buttons_down[i] && !self.prev_gamepad_buttons[i]; @@ -202,9 +223,6 @@ impl InputState { } pub fn end_frame(&mut self) { - self.prev_keys_down = self.keys_down; - self.prev_mouse_down = self.mouse_down; - self.prev_gamepad_buttons = self.gamepad_buttons_down; self.prev_mouse_x = self.mouse_x; self.prev_mouse_y = self.mouse_y; let mut flushed = false; @@ -308,11 +326,17 @@ impl InputState { pub fn set_mouse_button_down(&mut self, button: usize) { if button < MAX_MOUSE_BUTTONS { + if !self.mouse_down[button] { + self.mouse_press_latch[button] = true; + } self.mouse_down[button] = true; } } pub fn set_mouse_button_up(&mut self, button: usize) { if button < MAX_MOUSE_BUTTONS { + if self.mouse_down[button] { + self.mouse_release_latch[button] = true; + } self.mouse_down[button] = false; } } diff --git a/native/shared/src/lib.rs b/native/shared/src/lib.rs index 6ea49679..bb3e5340 100644 --- a/native/shared/src/lib.rs +++ b/native/shared/src/lib.rs @@ -10,6 +10,7 @@ pub mod audio; pub mod cooked_scene_store; #[cfg(all(feature = "image-extras", not(target_arch = "wasm32")))] pub mod cooked_texture_store; +pub mod display; pub mod ffi; #[cfg(not(target_arch = "wasm32"))] pub mod ffi_core; diff --git a/native/shared/src/renderer/mod.rs b/native/shared/src/renderer/mod.rs index 029fe96b..1ff4c236 100644 --- a/native/shared/src/renderer/mod.rs +++ b/native/shared/src/renderer/mod.rs @@ -794,6 +794,11 @@ pub struct Renderer { /// 1 = TAA on (default). When off the renderer behaves exactly /// as the pre-TAA pipeline did. pub taa_enabled: bool, + /// Perspective/orthographic clip planes for begin_mode_3d. Defaults keep + /// the historical 0.01..1000; a scene viewed from ~15 units away needs a + /// larger near plane, or surfaces a millimetre apart z-fight. + pub camera_near: f32, + pub camera_far: f32, /// True only after TAA wrote a current history in the active radiance /// domain. Separate from the jitter counter so ownership changes can /// replace history without restarting the sample sequence. @@ -8126,6 +8131,8 @@ impl Renderer { taa_reactive_bind_group_cache_keys: [None, None], taa_frame_index: 0, taa_enabled: true, + camera_near: 0.01, + camera_far: 1000.0, taa_history_valid: false, taa_history_written: false, taa_history_pt_owned: false, @@ -9123,6 +9130,21 @@ impl Renderer { ]; } + /// Set the 3D camera's near and far clip planes (used from the next + /// begin_mode_3d). Depth precision depends on the near plane: at 15 units + /// from the camera, near 0.01 resolves only about a millimetre. Changing + /// them invalidates temporal history, so it only happens on a change. + pub fn set_camera_clip_planes(&mut self, near: f32, far: f32) { + if !(near > 0.0) || !(far > near * 1.0001) || !far.is_finite() { + return; + } + if (near - self.camera_near).abs() > f32::EPSILON || (far - self.camera_far).abs() > f32::EPSILON * far { + self.camera_near = near; + self.camera_far = far; + self.taa_history_valid = false; + } + } + /// Toggle TAA on/off. Resolution is an independent quality control: /// this never changes `render_scale` or reallocates render targets. pub fn set_taa_enabled(&mut self, enabled: bool) { @@ -13779,11 +13801,12 @@ impl Renderer { projection: f32, ) { let aspect = self.surface_config.width as f32 / self.surface_config.height as f32; + let (near, far) = (self.camera_near, self.camera_far); let mut proj = if projection < 0.5 { - mat4_perspective(fovy.to_radians(), aspect, 0.01, 1000.0) + mat4_perspective(fovy.to_radians(), aspect, near, far) } else { let top = fovy / 2.0; - mat4_ortho(-top * aspect, top * aspect, -top, top, 0.01, 1000.0) + mat4_ortho(-top * aspect, top * aspect, -top, top, near, far) }; // Capture the pre-jitter projection for shadow cascade fitting. // TAA's sub-pixel nudge would otherwise change the cascade VPs diff --git a/native/shared/src/string_header.rs b/native/shared/src/string_header.rs index f05a3211..c160e1ff 100644 --- a/native/shared/src/string_header.rs +++ b/native/shared/src/string_header.rs @@ -53,8 +53,12 @@ const _: () = { assert!(std::mem::offset_of!(StringHeader, flags) == 16); }; -/// All flag bits Perry currently defines. -const KNOWN_FLAGS: u32 = 1; // STRING_FLAG_HAS_LONE_SURROGATES +/// Flag bit that changes how the payload must be decoded. Perry also sets +/// runtime-internal hint bits (JSON_ESCAPE_FREE = 2, WTF8_VALIDATED = 4, and +/// more in 0.5.1663: 0x1c is common on literals); they do not change the +/// layout or the payload, so they are not treated as an ABI mismatch. +#[allow(dead_code)] +const STRING_FLAG_HAS_LONE_SURROGATES: u32 = 1; /// Sanity-check a header against invariants that hold for every string the /// current Perry runtime produces. A failed check means either a corrupt @@ -65,7 +69,9 @@ fn header_looks_valid(h: &StringHeader) -> bool { && h.capacity < (1 << 31) // utf16 length is never larger than the utf8 byte length && h.utf16_len <= h.byte_len - && (h.flags & !KNOWN_FLAGS) == 0 + // flags are hints (see above); only a value too large to be flag + // bits suggests the fields shifted + && h.flags < (1 << 16) } fn abi_mismatch_warn_once(what: &str) { diff --git a/native/tvos/Cargo.lock b/native/tvos/Cargo.lock index fa34a4e3..8e805491 100644 --- a/native/tvos/Cargo.lock +++ b/native/tvos/Cargo.lock @@ -56,6 +56,26 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f09c37bc0e9f0924b7dae9988265ef3c76c88538f41a3b06caf4bed07cee5226" +[[package]] +name = "bincode" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36eaf5d7b090263e8150820482d5d93cd964a81e4019913c972f4edcc6edb740" +dependencies = [ + "bincode_derive", + "serde", + "unty", +] + +[[package]] +name = "bincode_derive" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf95709a440f45e986983918d0e8a1f30a9b1df04918fc828670606804ac3c09" +dependencies = [ + "virtue", +] + [[package]] name = "bit-set" version = "0.9.1" @@ -103,11 +123,20 @@ dependencies = [ "sha2", ] +[[package]] +name = "bloom-scene-format" +version = "0.1.0" +dependencies = [ + "bincode", + "sha2", +] + [[package]] name = "bloom-shared" version = "0.1.0" dependencies = [ "bloom-geometry-format", + "bloom-scene-format", "bytemuck", "cmake", "earcutr", @@ -120,8 +149,10 @@ dependencies = [ "libc", "log", "minimp3", + "naga", "raw-window-handle", "serde_json", + "sha2", "web-sys", "wgpu", ] @@ -820,6 +851,7 @@ dependencies = [ "log", "num-traits", "once_cell", + "pp-rs", "rustc-hash", "spirv", "thiserror 2.0.18", @@ -996,6 +1028,15 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "pp-rs" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb458bb7f6e250e6eb79d5026badc10a3ebb8f9a15d1fff0f13d17c71f4d6dee" +dependencies = [ + "unicode-xid", +] + [[package]] name = "presser" version = "0.3.1" @@ -1312,6 +1353,18 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "unty" +version = "0.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d49784317cd0d1ee7ec5c716dd598ec5b4483ea832a2dced265471cc0f690ae" + [[package]] name = "urlencoding" version = "2.1.3" @@ -1324,6 +1377,12 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "virtue" +version = "0.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "051eb1abcf10076295e815102942cc58f9d5e3b4560e46e53c21e8ff6f3af7b1" + [[package]] name = "wasm-bindgen" version = "0.2.118" diff --git a/native/tvos/src/lib.rs b/native/tvos/src/lib.rs index 8509c869..4900e06c 100644 --- a/native/tvos/src/lib.rs +++ b/native/tvos/src/lib.rs @@ -50,6 +50,39 @@ static mut UI_VIEW: Option> = None; static mut TOUCH_MAP: [*const c_void; 10] = [std::ptr::null(); 10]; static mut BUNDLE_PATH: Option = None; static mut SCREEN_SCALE: f64 = 1.0; +/// The Menu tap recognizer that keeps Menu from leaving the app, and the root view controller: +/// both switch over when the game lets Menu leave (setMenuButtonExits). +static mut MENU_TAP: Option> = None; +static mut ROOT_VC: Option> = None; +static MENU_EXITS_APPLIED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// On the main thread: Menu leaves the app (recognizer off, controller events to UIKit, as a +/// GCEventViewController does at a game's top level) or reaches the game. +extern "C" fn apply_menu_exits(_ctx: *mut c_void) { + let exits = bloom_shared::display::menu_exits(); + unsafe { + if let Some(tap) = MENU_TAP.as_ref() { + let _: () = msg_send![&**tap, setEnabled: Bool::new(!exits)]; + } + if let Some(vc) = ROOT_VC.as_ref() { + let responds: Bool = msg_send![&**vc, respondsToSelector: sel!(setControllerUserInteractionEnabled:)]; + if responds.as_bool() { + let _: () = msg_send![&**vc, setControllerUserInteractionEnabled: Bool::new(exits)]; + } + } + } +} + +/// From the frame: apply a change of setMenuButtonExits on the main thread. +fn sync_menu_exits() { + let want = bloom_shared::display::menu_exits(); + if MENU_EXITS_APPLIED.swap(want, std::sync::atomic::Ordering::Relaxed) == want { return; } + extern "C" { + static _dispatch_main_q: c_void; + fn dispatch_async_f(queue: *const c_void, context: *mut c_void, work: extern "C" fn(*mut c_void)); + } + unsafe { dispatch_async_f(&_dispatch_main_q as *const c_void, std::ptr::null_mut(), apply_menu_exits); } +} static SCENE_PTR: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); // Atomic key event buffer: main thread writes, game thread reads before begin_frame @@ -171,6 +204,44 @@ unsafe impl RefEncode for CGRect { const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING); } +#[repr(C)] +#[derive(Copy, Clone)] +struct UIEdgeInsets { top: f64, left: f64, bottom: f64, right: f64 } + +unsafe impl Encode for UIEdgeInsets { + const ENCODING: Encoding = Encoding::Struct( + "UIEdgeInsets", + &[Encoding::Double, Encoding::Double, Encoding::Double, Encoding::Double], + ); +} +unsafe impl RefEncode for UIEdgeInsets { + const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING); +} + +/// Whether a set of presses holds the Menu button (UIPressType 5). +unsafe fn has_menu_press(presses: *const AnyObject) -> bool { + if presses.is_null() { return false; } + let enumerator: Retained = msg_send![&*presses, objectEnumerator]; + loop { + let press: *const AnyObject = msg_send![&*enumerator, nextObject]; + if press.is_null() { return false; } + let send_i64: unsafe extern "C" fn(*const AnyObject, Sel) -> i64 = + std::mem::transmute(objc_msgSend as unsafe extern "C" fn()); + if send_i64(press, Sel::register(c"type")) == 5 { return true; } + } +} + +/// Hand a presses message to the superclass's implementation (UIKit's), as `super` would. +unsafe fn presses_to_super(this: *mut c_void, sel: Sel, presses: *const AnyObject, event: *const AnyObject) { + extern "C" { fn objc_msgSendSuper(); fn object_getClass(obj: *const c_void) -> *const c_void; fn class_getSuperclass(cls: *const c_void) -> *const c_void; } + #[repr(C)] + struct Super { receiver: *mut c_void, super_class: *const c_void } + let sup = Super { receiver: this, super_class: class_getSuperclass(object_getClass(this)) }; + let send: unsafe extern "C" fn(*const Super, Sel, *const AnyObject, *const AnyObject) = + std::mem::transmute(objc_msgSendSuper as unsafe extern "C" fn()); + send(&sup, sel, presses, event); +} + // ============================================================ // ObjC runtime // ============================================================ @@ -290,6 +361,11 @@ unsafe extern "C" fn bloom_can_become_focused(_this: *mut c_void, _sel: Sel) -> // UIPressType values: 0=UpArrow, 1=DownArrow, 2=LeftArrow, 3=RightArrow, // 4=Select, 5=Menu, 6=PlayPause unsafe extern "C" fn bloom_presses_began(_this: *mut c_void, _sel: Sel, presses: *const AnyObject, _event: *const AnyObject) { + // At the game's top level Menu goes to UIKit, which leaves the app (Apple requires it). + if bloom_shared::display::menu_exits() && has_menu_press(presses) { + presses_to_super(_this, _sel, presses, _event); + return; + } // Log to file since stderr doesn't always capture static PRESS_COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); let n = PRESS_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); @@ -299,6 +375,10 @@ unsafe extern "C" fn bloom_presses_began(_this: *mut c_void, _sel: Sel, presses: } unsafe extern "C" fn bloom_presses_ended(_this: *mut c_void, _sel: Sel, presses: *const AnyObject, _event: *const AnyObject) { + if bloom_shared::display::menu_exits() && has_menu_press(presses) { + presses_to_super(_this, _sel, presses, _event); + return; + } handle_presses(presses, false); } @@ -549,7 +629,14 @@ unsafe extern "C" fn bloom_window_send_event(this: *mut c_void, sel: Sel, event: } } - return; // Don't call super for type 3 — we extracted keys above + // Don't call super for type 3 — we extracted keys above. Except a Menu press while Menu + // leaves the app: that one goes on through the responder chain to UIKit. + if !(event_type == 3 && bloom_shared::display::menu_exits() && { + let all: *const AnyObject = msg_send![&*event, allPresses]; + has_menu_press(all) + }) { + return; + } } // For other events, call super @@ -1119,6 +1206,8 @@ pub unsafe extern "C" fn perry_scene_will_connect(scene: *const c_void) { let press_types_arr: Retained = msg_send![arr_cls, arrayWithObject: &*menu_num]; let _: () = msg_send![&*menu_tap, setAllowedPressTypes: &*press_types_arr]; let _: () = msg_send![&*view, addGestureRecognizer: &*menu_tap]; + MENU_TAP = Some(menu_tap.clone()); + ROOT_VC = Some(vc.clone()); // Trigger focus let _: () = msg_send![&*vc, setNeedsFocusUpdate]; @@ -1623,6 +1712,21 @@ pub extern "C" fn bloom_begin_drawing() { } } } + // The view's display scale and safe area (on a TV: the overscan-safe region), for + // getDisplayScale() / getSafeAreaInset(), in the pixels getScreenWidth() reports. + unsafe { + if let Some(view) = UI_VIEW.as_ref() { + let traits: *const AnyObject = msg_send![&**view, traitCollection]; + if !traits.is_null() { + let s: f64 = msg_send![&*traits, displayScale]; + if s.is_finite() && s > 0.0 { bloom_shared::display::set_display_scale(s); } + } + let insets: UIEdgeInsets = msg_send![&**view, safeAreaInsets]; + let s = bloom_shared::display::display_scale(); + bloom_shared::display::set_safe_area_insets(insets.top * s, insets.right * s, insets.bottom * s, insets.left * s); + } + } + sync_menu_exits(); // Drain pending key events from main thread BEFORE begin_frame snapshots drain_pending_keys(engine()); diff --git a/native/watchos/src/ffi_stubs.rs b/native/watchos/src/ffi_stubs.rs index c1ea7acd..99147038 100644 --- a/native/watchos/src/ffi_stubs.rs +++ b/native/watchos/src/ffi_stubs.rs @@ -336,6 +336,12 @@ #[no_mangle] pub extern "C" fn bloom_set_material_binding_tier_override(_p0: f64) -> f64 { 0.0 } +#[no_mangle] pub extern "C" fn bloom_get_display_scale() -> f64 { 1.0 } +#[no_mangle] pub extern "C" fn bloom_set_menu_button_exits(_p0: f64) -> f64 { 1.0 } +#[no_mangle] pub extern "C" fn bloom_get_safe_area_inset(_p0: f64) -> f64 { 0.0 } +#[no_mangle] pub extern "C" fn bloom_set_camera_clip_planes(_p0: f64, _p1: f64) -> f64 { + 0.0 +} #[no_mangle] pub extern "C" fn bloom_set_taa_enabled(_p0: f64) -> f64 { 0.0 } diff --git a/native/web/src/lib.rs b/native/web/src/lib.rs index c38ef61d..bb4bb1e5 100644 --- a/native/web/src/lib.rs +++ b/native/web/src/lib.rs @@ -297,6 +297,25 @@ pub fn bloom_get_fps() -> f64 { engine().get_fps() } +/// tvOS's Menu-leaves-the-app switch: nothing to do in a browser. +#[wasm_bindgen] +pub fn bloom_set_menu_button_exits(on: f64) -> f64 { + bloom_shared::display::set_menu_exits(on != 0.0); + 1.0 +} + +/// Physical pixels per point: the page's devicePixelRatio is the browser's business here. +#[wasm_bindgen] +pub fn bloom_get_display_scale() -> f64 { + bloom_shared::display::display_scale() +} + +/// Safe-area insets: none reported on the web (CSS env(safe-area-inset-*) covers pages). +#[wasm_bindgen] +pub fn bloom_get_safe_area_inset(edge: f64) -> f64 { + if edge >= 0.0 { bloom_shared::display::safe_area_inset(edge as usize) } else { 0.0 } +} + #[wasm_bindgen] pub fn bloom_get_screen_width() -> f64 { engine().screen_width() diff --git a/native/web/src/render_settings.rs b/native/web/src/render_settings.rs index b419cd94..0f82ba6b 100644 --- a/native/web/src/render_settings.rs +++ b/native/web/src/render_settings.rs @@ -69,6 +69,11 @@ pub fn bloom_set_manual_exposure(value: f64) -> f64 { 1.0 } #[wasm_bindgen] +pub fn bloom_set_camera_clip_planes(near: f64, far: f64) -> f64 { + engine().renderer.set_camera_clip_planes(near as f32, far as f32); + 1.0 +} +#[wasm_bindgen] pub fn bloom_set_taa_enabled(on: f64) -> f64 { engine().renderer.set_taa_enabled(on != 0.0); 1.0 diff --git a/package.json b/package.json index 1cb96953..76b56f49 100644 --- a/package.json +++ b/package.json @@ -242,6 +242,25 @@ "params": [], "returns": "f64" }, + { + "name": "bloom_set_menu_button_exits", + "params": [ + "f64" + ], + "returns": "f64" + }, + { + "name": "bloom_get_display_scale", + "params": [], + "returns": "f64" + }, + { + "name": "bloom_get_safe_area_inset", + "params": [ + "f64" + ], + "returns": "f64" + }, { "name": "bloom_get_screen_width", "params": [], @@ -1766,6 +1785,14 @@ ], "returns": "f64" }, + { + "name": "bloom_set_camera_clip_planes", + "params": [ + "f64", + "f64" + ], + "returns": "f64" + }, { "name": "bloom_set_taa_enabled", "params": [ diff --git a/src/core/index.ts b/src/core/index.ts index 26dd17db..63ef48f6 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -47,6 +47,7 @@ declare function bloom_get_active_transparency_composition_mode(): number; declare function bloom_set_material_binding_tier_override(tier: number): number; declare function bloom_set_sun_shafts(strength: number, decay: number, r: number, g: number, b: number): number; declare function bloom_set_auto_exposure(on: number): number; +declare function bloom_set_camera_clip_planes(near: number, far: number): number; declare function bloom_set_taa_enabled(on: number): number; declare function bloom_set_occlusion_culling(on: number): number; declare function bloom_set_render_scale(scale: number): number; @@ -127,6 +128,9 @@ declare function bloom_set_direct_2d_mode(on: number): void; declare function bloom_get_delta_time(): number; declare function bloom_get_fps(): number; declare function bloom_get_screen_width(): number; +declare function bloom_get_display_scale(): number; +declare function bloom_set_menu_button_exits(on: number): number; +declare function bloom_get_safe_area_inset(edge: number): number; declare function bloom_get_screen_height(): number; declare function bloom_is_key_pressed(key: number): number; declare function bloom_is_key_repeated(key: number): number; @@ -600,6 +604,17 @@ export function setOcclusionCulling(on: boolean): boolean { return bloom_set_occlusion_culling(on ? 1 : 0) !== 0; } +/** + * Near and far clip planes of the 3D camera (default 0.01 and 1000), used from + * the next `beginMode3D`. Depth precision follows the near plane: at 15 units + * away, 0.01 resolves only about a millimetre, so nearly coplanar surfaces + * (a decal, a board on its frame) z-fight. Pick the largest near plane the + * scene allows, as with three.js's PerspectiveCamera(fov, aspect, near, far). + */ +export function setCameraClipPlanes(near: number, far: number): boolean { + return bloom_set_camera_clip_planes(near, far) !== 0; +} + /** Toggle temporal anti-aliasing without changing render resolution. */ export function setTaaEnabled(on: boolean): boolean { return bloom_set_taa_enabled(on ? 1 : 0) !== 0; @@ -1092,6 +1107,33 @@ export function getTime(): number { // Screen +/** + * Physical pixels per point (UIKit's displayScale): 2 or 3 on iPhone and iPad, + * 1 where the platform doesn't report one. On iOS `getScreenWidth()` is in + * pixels, so `getScreenWidth() / getDisplayScale()` is the width in points. + */ +export function getDisplayScale(): number { return bloom_get_display_scale(); } + +/** + * tvOS: whether the Siri Remote's Menu button leaves the app (back to the Home screen) instead of + * reaching the game as Escape. Apple requires it at the app's top level, so turn it on while the + * title screen shows and off everywhere Menu means "back" or "pause". No effect elsewhere. + */ +export function setMenuButtonExits(on: boolean): void { bloom_set_menu_button_exits(on ? 1 : 0); } + +/** Edges for `getSafeAreaInset`. */ +export const SafeAreaEdge = { TOP: 0, RIGHT: 1, BOTTOM: 2, LEFT: 3 } as const; + +/** + * How much of one edge of the window the system covers: the Dynamic Island or + * notch, rounded corners, the home indicator, the status-bar column of an + * iPhone Duo. In the units of `getScreenWidth()`; 0 where the platform has no + * safe area. Keep buttons and text inside it, let the 3D view run underneath. + * It changes with rotation and when a foldable opens or closes, so read it + * per frame. + */ +export function getSafeAreaInset(edge: number): number { return bloom_get_safe_area_inset(edge); } + export function getScreenWidth(): number { return bloom_get_screen_width(); } diff --git a/src/textures/index.ts b/src/textures/index.ts index ffad2e66..6ca64ae8 100644 --- a/src/textures/index.ts +++ b/src/textures/index.ts @@ -67,11 +67,13 @@ export function createTextureRgba8( bloom_mesh_scratch_reset(); for (let i = 0; i < texelCount; i++) { const offset = i * 4; - bloom_mesh_scratch_push_u32( + // `>>> 0`: with alpha >= 128, `a << 24` makes the packed value negative + // (JS bitwise ops are signed 32-bit), which the u32 FFI slot saturates to 0. + bloom_mesh_scratch_push_u32(( (rgba[offset] & 255) | ((rgba[offset + 1] & 255) << 8) | ((rgba[offset + 2] & 255) << 16) - | ((rgba[offset + 3] & 255) << 24), + | ((rgba[offset + 3] & 255) << 24)) >>> 0, ); } const id = bloom_load_texture_rgba8_scratch(width, height, kind); diff --git a/tools/validate-ffi.js b/tools/validate-ffi.js index 7e08dafe..6e78b9c0 100644 --- a/tools/validate-ffi.js +++ b/tools/validate-ffi.js @@ -72,6 +72,7 @@ const RENDERER_STATUS_FUNCTIONS = new Set([ 'bloom_set_transparency_composition_mode', 'bloom_set_sun_shafts', 'bloom_set_auto_exposure', + 'bloom_set_camera_clip_planes', 'bloom_set_taa_enabled', 'bloom_set_occlusion_culling', 'bloom_set_render_scale',