From e5cbfd70f682aa82743b337baff72067ad9c9458 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ralph=20K=C3=BCpper?= Date: Wed, 25 Nov 2026 11:40:38 +0100 Subject: [PATCH 1/2] Model loads read only what they keep: mapped files, a borrowed GLB chunk, streamed textures copied from their resident level - loadModel memory-maps the file (Unix; a whole read elsewhere): only the pages the load touches come in from disk, as clean file pages that iOS does not count against the app. - The GLB binary chunk is borrowed from the file, not copied by the gltf crate (Cow buffers). - The model cache knows a file on disk by its size, time of change, inode and device, instead of hashing every byte. - A streamed texture is copied out of its KTX2 only from the level it is created at (all levels were copied, then trimmed); CompressedImage::from_ktx2_from. - Raising or lowering a streamed texture reads the KTX2 header and the range of the levels kept, not the whole chain. Jonah (Mac, the cold open and Nineveh, streaming on and off): resident memory 300 to 500 MB lower, the city's load 2.1-2.2 s -> 1.7-2.0 s, frames equal within run-to-run noise. Co-Authored-By: Claude --- native/shared/src/compressed_texture.rs | 53 +++++++++- native/shared/src/ffi_core/models.rs | 3 +- native/shared/src/file_map.rs | 99 +++++++++++++++++++ native/shared/src/lib.rs | 1 + native/shared/src/models_gltf.rs | 47 +++++---- native/shared/src/models_gltf_anim_file.rs | 6 +- native/shared/src/models_gltf_bake.rs | 4 +- native/shared/src/models_gltf_parse.rs | 31 ++++++ native/shared/src/models_gltf_texture_io.rs | 3 +- native/shared/src/models_source_cache.rs | 67 ++++++++++++- .../shared/src/renderer/texture_streaming.rs | 68 +++++++++---- 11 files changed, 332 insertions(+), 50 deletions(-) create mode 100644 native/shared/src/file_map.rs diff --git a/native/shared/src/compressed_texture.rs b/native/shared/src/compressed_texture.rs index b5a3799e..d5ac15fe 100644 --- a/native/shared/src/compressed_texture.rs +++ b/native/shared/src/compressed_texture.rs @@ -152,6 +152,15 @@ impl CompressedImage { /// Parse a KTX2 file. `None` for anything that is not a plain 2D ASTC or /// BC7 texture without supercompression, or whose levels are truncated. pub fn from_ktx2(bytes: &[u8]) -> Option { + Self::from_ktx2_from(bytes, 0) + } + + /// As [`Self::from_ktx2`], but only the levels from `first_level` down are + /// copied: the image is the same texture with its largest levels left + /// out (`width`, `height` those of `first_level`, clamped to the last + /// level). Every level is still checked. `u32::MAX` copies none and keeps + /// the full size: the shape only, with one empty level per level. + pub fn from_ktx2_from(bytes: &[u8], first_level: u32) -> Option { if !is_ktx2(bytes) { return None; } @@ -173,6 +182,8 @@ impl CompressedImage { if supercompression != 0 || level_count > u32::BITS - width.max(height).leading_zeros() { return None; } + let shape_only = first_level == u32::MAX; + let first = (first_level as usize).min(level_count as usize - 1); let mut levels = Vec::with_capacity(level_count as usize); for index in 0..level_count as usize { let entry = 80 + index * 24; @@ -182,12 +193,26 @@ impl CompressedImage { if length != format.level_bytes(level_width, level_height) { return None; } - levels.push(bytes.get(offset..offset.checked_add(length)?)?.to_vec()); + let level = bytes.get(offset..offset.checked_add(length)?)?; + if shape_only { + levels.push(Vec::new()); + } else if index >= first { + levels.push(level.to_vec()); + } + } + if shape_only { + return Some(Self { + format, + width, + height, + srgb, + levels, + }); } Some(Self { format, - width, - height, + width: (width >> first).max(1), + height: (height >> first).max(1), srgb, levels, }) @@ -363,6 +388,28 @@ mod tests { } } + #[test] + fn reading_from_a_level_equals_trimming_the_whole_read() { + let format = BlockFormat::Astc { + width: 4, + height: 4, + }; + let image = sample(format, true); + let bytes = image.to_ktx2().expect("serialises"); + let whole = CompressedImage::from_ktx2(&bytes).expect("parses"); + for level in 0..whole.levels.len() as u32 + 2 { + let part = CompressedImage::from_ktx2_from(&bytes, level).expect("parses"); + let trimmed = crate::renderer::texture_streaming::sub_image(&whole, level); + assert_eq!((part.width, part.height), (trimmed.width, trimmed.height)); + assert_eq!(part.levels, trimmed.levels, "level {level}"); + } + let shape = CompressedImage::from_ktx2_from(&bytes, u32::MAX).expect("parses"); + assert_eq!((shape.width, shape.height), (whole.width, whole.height)); + assert_eq!(shape.levels.len(), whole.levels.len()); + assert!(shape.levels.iter().all(Vec::is_empty)); + assert!(CompressedImage::from_ktx2_from(&bytes[..bytes.len() - 1], 3).is_none()); + } + #[test] fn truncated_or_foreign_files_are_rejected() { let bytes = sample( diff --git a/native/shared/src/ffi_core/models.rs b/native/shared/src/ffi_core/models.rs index e71cfff3..e66bf5a2 100644 --- a/native/shared/src/ffi_core/models.rs +++ b/native/shared/src/ffi_core/models.rs @@ -18,7 +18,8 @@ macro_rules! __bloom_ffi_models { let path = $crate::string_header::str_from_header(path_ptr); let resolved =bloom_resolve_asset_path(path); let resolved_path = std::path::Path::new(resolved.as_ref()); - match std::fs::read(resolved_path) { + // mapped, not read: only the pages the load touches come in from disk + match $crate::file_map::read(resolved_path) { Ok(data) => { let eng = engine(); let $crate::engine::EngineState { ref mut models, ref mut renderer, .. } = *eng; diff --git a/native/shared/src/file_map.rs b/native/shared/src/file_map.rs new file mode 100644 index 00000000..da06417c --- /dev/null +++ b/native/shared/src/file_map.rs @@ -0,0 +1,99 @@ +//! A file's bytes for loading, memory-mapped where the platform allows. +//! +//! A model file is mostly texture levels, and with texture streaming on most +//! of those are never uploaded (only the small levels are, the rest is read +//! later and only when needed). Reading the whole file brought every byte in +//! from disk and held it in memory for the load. A read-only mapping brings +//! in only the pages the loader touches, and those are clean file pages: +//! iOS does not count them against the app's memory limit. +//! +//! The mapping lives as long as the `FileBytes` (the load), so a file must not +//! be truncated while it is being loaded (reading past its new end would +//! fault). Elsewhere (Windows, the web) the file is read whole as before. + +use std::ops::Deref; +use std::path::Path; + +pub enum FileBytes { + #[cfg(unix)] + Mapped { + ptr: *const u8, + len: usize, + }, + Owned(Vec), +} + +impl Deref for FileBytes { + type Target = [u8]; + fn deref(&self) -> &[u8] { + match self { + #[cfg(unix)] + FileBytes::Mapped { ptr, len } => { + // SAFETY: ptr/len describe a live read-only mapping owned by self. + unsafe { std::slice::from_raw_parts(*ptr, *len) } + } + FileBytes::Owned(bytes) => bytes, + } + } +} + +impl Drop for FileBytes { + fn drop(&mut self) { + #[cfg(unix)] + if let FileBytes::Mapped { ptr, len } = *self { + // SAFETY: the mapping was made by `read` with this address and length. + unsafe { + libc::munmap(ptr as *mut libc::c_void, len); + } + } + } +} + +/// The bytes of the file at `path`: mapped on Unix-like systems (falling back +/// to a read when the mapping fails), read whole elsewhere. +pub fn read(path: &Path) -> std::io::Result { + #[cfg(unix)] + { + use std::os::unix::io::AsRawFd; + let file = std::fs::File::open(path)?; + let len = file.metadata()?.len() as usize; + if len > 0 { + // SAFETY: a private read-only mapping of an open file; the fd may be + // closed afterwards, the mapping keeps the file. + let ptr = unsafe { + libc::mmap( + std::ptr::null_mut(), + len, + libc::PROT_READ, + libc::MAP_PRIVATE, + file.as_raw_fd(), + 0, + ) + }; + if ptr != libc::MAP_FAILED { + return Ok(FileBytes::Mapped { + ptr: ptr as *const u8, + len, + }); + } + } + } + std::fs::read(path).map(FileBytes::Owned) +} + +#[cfg(test)] +mod tests { + #[test] + fn a_mapped_file_reads_as_its_bytes() { + let dir = std::env::temp_dir().join(format!("bloom-file-map-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("bytes.bin"); + let bytes: Vec = (0..100_000u32).map(|i| (i * 31 % 251) as u8).collect(); + std::fs::write(&path, &bytes).unwrap(); + assert_eq!(&*super::read(&path).unwrap(), &bytes[..]); + std::fs::write(&path, b"").unwrap(); + assert!(super::read(&path).unwrap().is_empty()); + assert!(super::read(&dir.join("missing")).is_err()); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/native/shared/src/lib.rs b/native/shared/src/lib.rs index 5233777c..7ecc011a 100644 --- a/native/shared/src/lib.rs +++ b/native/shared/src/lib.rs @@ -16,6 +16,7 @@ pub mod emoji; pub mod ffi; #[cfg(not(target_arch = "wasm32"))] pub mod ffi_core; +pub mod file_map; pub mod handles; pub mod input; pub mod locale; diff --git a/native/shared/src/models_gltf.rs b/native/shared/src/models_gltf.rs index 09ff8b22..67196edb 100644 --- a/native/shared/src/models_gltf.rs +++ b/native/shared/src/models_gltf.rs @@ -7,6 +7,7 @@ //! animation update, procedural mesh gen) stays in `models.rs`. use super::*; +use std::borrow::Cow; #[path = "models_gltf_layered_pbr.rs"] mod layered_pbr_import; @@ -98,7 +99,7 @@ fn walk_scene_collect_instances( fn read_accessor_f32( _gltf: &gltf::Gltf, - buffer_data: &[Vec], + buffer_data: &[Cow<[u8]>], accessor: &gltf::Accessor, ) -> Vec { let view = match accessor.view() { @@ -148,17 +149,21 @@ fn read_accessor_f32( /// of a load). Inline base64 buffers are decoded; an external `.bin` next to /// the file is read from `base_dir` (with `strict`, a missing one fails the /// load; otherwise it is an empty buffer). -fn take_buffers( +fn take_buffers<'a>( gltf: &mut gltf::Gltf, + glb_bin: Option<&'a [u8]>, base_dir: Option<&std::path::Path>, strict: bool, -) -> Option>> { - let mut bin = gltf.blob.take(); - let mut buffer_data: Vec> = Vec::new(); +) -> Option>> { + let mut bin: Option> = match glb_bin { + Some(b) => Some(Cow::Borrowed(b)), + None => gltf.blob.take().map(Cow::Owned), + }; + let mut buffer_data: Vec> = Vec::new(); for buffer in gltf.buffers() { - let bytes = match buffer.source() { + let bytes: Cow<'a, [u8]> = match buffer.source() { gltf::buffer::Source::Bin => bin.take().unwrap_or_default(), - gltf::buffer::Source::Uri(uri) => { + gltf::buffer::Source::Uri(uri) => Cow::Owned({ if let Some(encoded) = uri.strip_prefix("data:application/octet-stream;base64,") { let mut decoded = Vec::new(); let _ = base64_decode(encoded, &mut decoded); @@ -172,7 +177,7 @@ fn take_buffers( } else { Vec::new() } - } + }), }; buffer_data.push(bytes); } @@ -180,8 +185,8 @@ fn take_buffers( } pub fn load_gltf_animation(data: &[u8]) -> Option { - let mut gltf = parse::parse_gltf(data)?; - let buffer_data = take_buffers(&mut gltf, None, false)?; + let (mut gltf, glb_bin) = parse::parse_borrowed(data)?; + let buffer_data = take_buffers(&mut gltf, glb_bin, None, false)?; animation_from(&gltf, &buffer_data) } @@ -195,7 +200,7 @@ pub fn load_gltf_animation_file(path: &std::path::Path) -> Option]) -> Option { +fn animation_from(gltf: &gltf::Gltf, buffer_data: &[Cow<[u8]>]) -> Option { // Parse skeleton from the first skin let skeleton = if let Some(skin) = gltf.skins().next() { let joints_nodes: Vec<_> = skin.joints().collect(); @@ -360,7 +365,7 @@ fn animation_from(gltf: &gltf::Gltf, buffer_data: &[Vec]) -> Option, source_label: Option<&str>, ) -> Option { - let mut gltf = parse::parse_gltf(data)?; + let (mut gltf, glb_bin) = parse::parse_borrowed(data)?; emit_unsupported_material_extension_diagnostics(&gltf, source_label.unwrap_or("")); // Get buffer data - let buffer_data = take_buffers(&mut gltf, base_dir, false)?; + let buffer_data = take_buffers(&mut gltf, glb_bin, base_dir, false)?; let source_geometry_sha256 = complete_geometry_source_hash(data, &gltf, &buffer_data); // Pre-walk materials to identify which image indices are normal @@ -791,7 +796,7 @@ pub(super) fn load_gltf_with_textures( continue; } let reader = - primitive.reader(|buf| buffer_data.get(buf.index()).map(|d| d.as_slice())); + primitive.reader(|buf| buffer_data.get(buf.index()).map(|d| d.as_ref())); let positions: Vec<[f32; 3]> = match reader.read_positions() { Some(iter) => iter.collect(), None => continue, @@ -1072,10 +1077,10 @@ fn load_gltf_staged_impl( ) -> Option { use crate::staging::{StagedModel, StagedTexture}; - let mut gltf = parse::parse_gltf(data)?; + let (mut gltf, glb_bin) = parse::parse_borrowed(data)?; emit_unsupported_material_extension_diagnostics(&gltf, source_label); - let buffer_data = take_buffers(&mut gltf, base_dir, true)?; + let buffer_data = take_buffers(&mut gltf, glb_bin, base_dir, true)?; let source_geometry_sha256 = complete_geometry_source_hash(data, &gltf, &buffer_data); // Pre-walk materials for the image indices used as normal maps — they @@ -1222,7 +1227,7 @@ fn load_gltf_staged_impl( let morph_slots = morph::morph_slots(&gltf); for mesh in gltf.meshes() { for primitive in mesh.primitives() { - let reader = primitive.reader(|buf| buffer_data.get(buf.index()).map(|d| d.as_slice())); + let reader = primitive.reader(|buf| buffer_data.get(buf.index()).map(|d| d.as_ref())); let positions: Vec<[f32; 3]> = match reader.read_positions() { Some(iter) => iter.collect(), None => continue, @@ -1508,11 +1513,11 @@ fn stage_image_variants( } pub(super) fn load_gltf(data: &[u8]) -> Option { - let mut gltf = parse::parse_gltf(data)?; + let (mut gltf, glb_bin) = parse::parse_borrowed(data)?; emit_unsupported_material_extension_diagnostics(&gltf, ""); // Get buffer data (for .glb, embedded; for .gltf, inline base64) - let buffer_data = take_buffers(&mut gltf, None, false)?; + let buffer_data = take_buffers(&mut gltf, glb_bin, None, false)?; let source_geometry_sha256 = complete_geometry_source_hash(data, &gltf, &buffer_data); let mut source_meshes: Vec> = @@ -1521,7 +1526,7 @@ pub(super) fn load_gltf(data: &[u8]) -> Option { let morph_slots = morph::morph_slots(&gltf); for mesh in gltf.meshes() { for primitive in mesh.primitives() { - let reader = primitive.reader(|buf| buffer_data.get(buf.index()).map(|d| d.as_slice())); + let reader = primitive.reader(|buf| buffer_data.get(buf.index()).map(|d| d.as_ref())); let positions: Vec<[f32; 3]> = match reader.read_positions() { Some(iter) => iter.collect(), diff --git a/native/shared/src/models_gltf_anim_file.rs b/native/shared/src/models_gltf_anim_file.rs index 3bc9f2ff..efdad29d 100644 --- a/native/shared/src/models_gltf_anim_file.rs +++ b/native/shared/src/models_gltf_anim_file.rs @@ -76,7 +76,11 @@ pub(super) fn load(path: &Path) -> Option> { f.seek(SeekFrom::Start(bin_off + o as u64)).ok()?; f.read_exact(&mut bin[o..o + l]).ok()?; } - let buffer_data = if bin_len > 0 { vec![bin] } else { Vec::new() }; + let buffer_data = if bin_len > 0 { + vec![std::borrow::Cow::Owned(bin)] + } else { + Vec::new() + }; Some(super::animation_from(&gltf, &buffer_data)) } diff --git a/native/shared/src/models_gltf_bake.rs b/native/shared/src/models_gltf_bake.rs index daa70ecb..45915267 100644 --- a/native/shared/src/models_gltf_bake.rs +++ b/native/shared/src/models_gltf_bake.rs @@ -24,7 +24,7 @@ pub fn require_source_geometry_hash() { pub(super) fn complete_geometry_source_hash( source_bytes: &[u8], gltf: &gltf::Gltf, - buffers: &[Vec], + buffers: &[std::borrow::Cow<[u8]>], ) -> Option<[u8; 32]> { if !cfg!(test) && !SOURCE_HASH_REQUIRED.load(std::sync::atomic::Ordering::Relaxed) @@ -41,7 +41,7 @@ pub(super) fn complete_geometry_source_hash( { return None; } - let slices = buffers.iter().map(Vec::as_slice).collect::>(); + let slices = buffers.iter().map(|b| b.as_ref()).collect::>(); Some(bloom_geometry_format::geometry_source_sha256( source_bytes, &slices, diff --git a/native/shared/src/models_gltf_parse.rs b/native/shared/src/models_gltf_parse.rs index a000b3c1..61df1d3e 100644 --- a/native/shared/src/models_gltf_parse.rs +++ b/native/shared/src/models_gltf_parse.rs @@ -11,6 +11,37 @@ //! loader already treats as "nothing" (zero deltas). Anything else is still //! rejected, now with a line saying why. +/// A GLB's JSON chunk and binary chunk, both borrowed from `data`; `None` +/// when `data` is not a GLB (a glTF JSON file, say). +pub(super) fn split_glb(data: &[u8]) -> Option<(&[u8], Option<&[u8]>)> { + let word = |at: usize| -> Option { + Some(u32::from_le_bytes(data.get(at..at + 4)?.try_into().ok()?) as usize) + }; + if data.get(0..4)? != b"glTF" || data.get(16..20)? != b"JSON" { + return None; + } + let json_end = 20usize.checked_add(word(12)?)?; + let json = data.get(20..json_end)?; + let bin = match data.get(json_end + 4..json_end + 8) { + Some(b"BIN\0") => { + let start = json_end + 8; + Some(data.get(start..start.checked_add(word(json_end)?)?)?) + } + _ => None, + }; + Some((json, bin)) +} + +/// The document, and for a GLB its binary chunk borrowed from `data`, not +/// copied (the gltf crate copies it: a model's whole file, read again). With +/// a memory-mapped file the texture levels nobody uploads are then never read. +pub(super) fn parse_borrowed(data: &[u8]) -> Option<(gltf::Gltf, Option<&[u8]>)> { + match split_glb(data) { + Some((json, bin)) => Some((parse_gltf(json)?, bin)), + None => Some((parse_gltf(data)?, None)), + } +} + pub(super) fn parse_gltf(data: &[u8]) -> Option { match gltf::Gltf::from_slice(data) { Ok(document) => Some(document), diff --git a/native/shared/src/models_gltf_texture_io.rs b/native/shared/src/models_gltf_texture_io.rs index c9f6c090..0344b954 100644 --- a/native/shared/src/models_gltf_texture_io.rs +++ b/native/shared/src/models_gltf_texture_io.rs @@ -18,10 +18,9 @@ pub(super) fn register_compressed_image( if feeds_alpha_mask { return None; } - let image = CompressedImage::from_ktx2(bytes)?; // `file_range`: where these bytes are in the file being imported, when // known. The renderer may then keep only the small levels resident. - renderer.register_compressed_streamed(&image, is_normal, is_srgb, file_range) + renderer.register_compressed_streamed(bytes, is_normal, is_srgb, file_range) } /// Staged (no renderer yet) counterpart of [`decode_texture_bytes`]: a KTX2 diff --git a/native/shared/src/models_source_cache.rs b/native/shared/src/models_source_cache.rs index 35040c27..9e88beba 100644 --- a/native/shared/src/models_source_cache.rs +++ b/native/shared/src/models_source_cache.rs @@ -67,13 +67,46 @@ fn fingerprint(file_data: &[u8]) -> u64 { h ^ (h >> 32) } +/// What tells a changed file from the one loaded before: its size, time of +/// change and (on Unix) inode and device when the file can be asked, else the +/// bytes. Hashing the bytes read every page of a mapped file, most of them +/// texture levels the load would otherwise never touch. +fn file_identity(source_path: &Path, file_data: &[u8]) -> u64 { + let Ok(meta) = std::fs::metadata(source_path) else { + return fingerprint(file_data); + }; + if meta.len() != file_data.len() as u64 { + return fingerprint(file_data); + } + let changed = meta + .modified() + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|d| d.as_nanos() as u64) + .unwrap_or(0); + #[cfg(unix)] + let (ino, dev) = { + use std::os::unix::fs::MetadataExt; + (meta.ino(), meta.dev()) + }; + #[cfg(not(unix))] + let (ino, dev) = (0u64, 0u64); + let mut id = Vec::with_capacity(32); + for v in [meta.len(), changed, ino, dev] { + id.extend_from_slice(&v.to_le_bytes()); + } + fingerprint(&id) +} + impl SourceModelCache { /// A model sharing the earlier import of `source_path`, if that file was /// loaded before with the same bytes and its meshes are still alive. pub fn share(&mut self, source_path: &Path, file_data: &[u8]) -> Option { let key = source_path.display().to_string(); let entry = self.entries.get(&key)?; - if entry.byte_len != file_data.len() || entry.fingerprint != fingerprint(file_data) { + if entry.byte_len != file_data.len() + || entry.fingerprint != file_identity(source_path, file_data) + { return None; } let meshes: Option>> = entry.meshes.iter().map(Weak::upgrade).collect(); @@ -97,7 +130,7 @@ impl SourceModelCache { source_path.display().to_string(), Entry { byte_len: file_data.len(), - fingerprint: fingerprint(file_data), + fingerprint: file_identity(source_path, file_data), meshes: model.meshes.iter().map(Arc::downgrade).collect(), mesh_transforms: model.mesh_transforms.clone(), mesh_cast_shadows: model.mesh_cast_shadows.clone(), @@ -155,6 +188,36 @@ mod tests { assert_ne!(fingerprint(&[0u8; 64]), fingerprint(&[0u8; 65])); } + #[test] + fn a_file_on_disk_is_known_by_its_size_and_time_of_change() { + let mut models = ModelManager::new(); + let handle = models.gen_mesh_cube(1.0, 1.0, 1.0); + let dir = std::env::temp_dir().join(format!("bloom-source-cache-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("actor.glb"); + std::fs::write(&path, b"file bytes").unwrap(); + let mut cache = SourceModelCache::default(); + cache.remember(&path, b"file bytes", models.get(handle).unwrap()); + assert!( + cache.share(&path, b"file bytes").is_some(), + "same file shares" + ); + // the same length, rewritten later: a new import + std::fs::write(&path, b"edited byt").unwrap(); + let later = std::time::SystemTime::now() + std::time::Duration::from_secs(5); + std::fs::File::options() + .write(true) + .open(&path) + .unwrap() + .set_modified(later) + .unwrap(); + assert!( + cache.share(&path, b"edited byt").is_none(), + "changed file reimports" + ); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn repeated_load_shares_meshes_until_the_file_changes_or_is_unloaded() { let mut models = ModelManager::new(); diff --git a/native/shared/src/renderer/texture_streaming.rs b/native/shared/src/renderer/texture_streaming.rs index 4cc4987d..2a820fc5 100644 --- a/native/shared/src/renderer/texture_streaming.rs +++ b/native/shared/src/renderer/texture_streaming.rs @@ -234,8 +234,15 @@ struct StreamedTexture { } /// The bytes of `image`'s chain from each level down. +/// The bytes of each level and all smaller ones, of the image whose shape +/// `image` is (its levels may be empty): they follow from the format and size. fn chain_bytes(image: &CompressedImage) -> Vec { - let mut sizes: Vec = image.levels.iter().map(|l| l.len() as u64).collect(); + let mut sizes: Vec = (0..image.levels.len() as u32) + .map(|l| { + let (w, h) = ((image.width >> l).max(1), (image.height >> l).max(1)); + image.format.level_bytes(w, h) as u64 + }) + .collect(); for at in (0..sizes.len().saturating_sub(1)).rev() { sizes[at] += sizes[at + 1]; } @@ -274,9 +281,35 @@ struct LevelReader { /// The texture in `source` from `level` down (moved to the nearest larger /// level that is whole blocks), with the level it starts at. fn load_levels(source: &StreamSource, level: u32) -> Option<(u32, CompressedImage)> { - let image = CompressedImage::from_ktx2(&read_source(source)?)?; - let level = block_aligned_level(&image, level)?; - Some((level, sub_image(&image, level))) + let mut file = std::fs::File::open(&source.path).ok()?; + // The image's header and level index first, in a zeroed buffer of the + // image's size (pages never written cost nothing), then only the bytes of + // the levels kept: KTX2 stores the smallest level first, so those are one + // range. The whole chain was read for every raise and every lowering. + let length = usize::try_from(source.length).ok()?; + let mut bytes = vec![0u8; length]; + let read_at = |file: &mut std::fs::File, bytes: &mut [u8], from: usize, to: usize| { + file.seek(SeekFrom::Start(source.offset + from as u64)) + .ok()?; + file.read_exact(bytes.get_mut(from..to)?).ok() + }; + read_at(&mut file, &mut bytes, 0, 80.min(length))?; + let count = u32::from_le_bytes(bytes.get(40..44)?.try_into().ok()?).max(1) as usize; + let index_end = 80usize.checked_add(count.checked_mul(24)?)?; + read_at(&mut file, &mut bytes, 80, index_end)?; + let shape = CompressedImage::from_ktx2_from(&bytes, u32::MAX)?; + let level = block_aligned_level(&shape, level)?; + let range = |at: usize| -> Option { + usize::try_from(u64::from_le_bytes(bytes.get(at..at + 8)?.try_into().ok()?)).ok() + }; + let (mut from, mut to) = (usize::MAX, 0usize); + for l in level as usize..count { + let (offset, len) = (range(80 + l * 24)?, range(88 + l * 24)?); + from = from.min(offset); + to = to.max(offset.checked_add(len)?); + } + read_at(&mut file, &mut bytes, from, to)?; + Some((level, CompressedImage::from_ktx2_from(&bytes, level)?)) } impl LevelReader { @@ -386,6 +419,7 @@ pub(crate) fn every_level_is_whole_blocks(image: &CompressedImage, floor: u32) - } /// `image` from `level` down: the same texture with its largest levels left out. +#[cfg(test)] pub(crate) fn sub_image(image: &CompressedImage, level: u32) -> CompressedImage { let level = (level as usize).min(image.levels.len().saturating_sub(1)); CompressedImage { @@ -397,25 +431,21 @@ pub(crate) fn sub_image(image: &CompressedImage, level: u32) -> CompressedImage } } -fn read_source(source: &StreamSource) -> Option> { - let mut file = std::fs::File::open(&source.path).ok()?; - file.seek(SeekFrom::Start(source.offset)).ok()?; - let mut bytes = vec![0u8; usize::try_from(source.length).ok()?]; - file.read_exact(&mut bytes).ok()?; - Some(bytes) -} - impl Renderer { - /// Register a KTX2 image found at `file_range` (offset, length) of the - /// file being imported. With streaming on and the image larger than the - /// floor, only its small levels are uploaded and the rest stays on disk. + /// Register the KTX2 image `ktx2` found at `file_range` (offset, length) + /// of the file being imported. With streaming on and the image larger + /// than the floor, only its small levels are uploaded and the rest stays + /// on disk: only those levels are copied out of `ktx2` (the larger ones + /// were copied and thrown away, most of a model's bytes). pub(crate) fn register_compressed_streamed( &mut self, - image: &CompressedImage, + ktx2: &[u8], is_normal: bool, srgb: bool, file_range: Option<(u64, u64)>, ) -> Option { + // the shape only (one empty level per level): no level is copied yet + let image = &CompressedImage::from_ktx2_from(ktx2, u32::MAX)?; let source = if self .texture_streaming .enabled @@ -443,9 +473,11 @@ impl Renderer { .unwrap_or(0); let streamable = level > 0 && every_level_is_whole_blocks(image, level); let Some(source) = source.filter(|_| streamable) else { - return self.register_texture_compressed(image, is_normal, srgb); + let whole = CompressedImage::from_ktx2(ktx2)?; + return self.register_texture_compressed(&whole, is_normal, srgb); }; - let index = self.register_texture_compressed(&sub_image(image, level), is_normal, srgb)?; + let resident = CompressedImage::from_ktx2_from(ktx2, level)?; + let index = self.register_texture_compressed(&resident, is_normal, srgb)?; self.texture_streaming.entries.insert( index, StreamedTexture { From f0576577716f00d3ba3be46991c047f3d5e6b651 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ralph=20K=C3=BCpper?= Date: Wed, 25 Nov 2026 11:53:39 +0100 Subject: [PATCH 2/2] Review: the mapping is private to file_map and read() is unsafe (the file must not change while mapped); split_glb checks the GLB version and length; times before 1970 stay distinct Co-Authored-By: Claude --- native/shared/src/ffi_core/models.rs | 3 +- native/shared/src/file_map.rs | 35 ++++++++++++++++-------- native/shared/src/models_gltf_parse.rs | 7 ++++- native/shared/src/models_source_cache.rs | 14 ++++++---- 4 files changed, 39 insertions(+), 20 deletions(-) diff --git a/native/shared/src/ffi_core/models.rs b/native/shared/src/ffi_core/models.rs index e66bf5a2..1c85a296 100644 --- a/native/shared/src/ffi_core/models.rs +++ b/native/shared/src/ffi_core/models.rs @@ -19,7 +19,8 @@ macro_rules! __bloom_ffi_models { let resolved =bloom_resolve_asset_path(path); let resolved_path = std::path::Path::new(resolved.as_ref()); // mapped, not read: only the pages the load touches come in from disk - match $crate::file_map::read(resolved_path) { + // SAFETY: an asset file, not rewritten while one model loads from it. + match unsafe { $crate::file_map::read(resolved_path) } { Ok(data) => { let eng = engine(); let $crate::engine::EngineState { ref mut models, ref mut renderer, .. } = *eng; diff --git a/native/shared/src/file_map.rs b/native/shared/src/file_map.rs index da06417c..3490fbc9 100644 --- a/native/shared/src/file_map.rs +++ b/native/shared/src/file_map.rs @@ -14,7 +14,10 @@ use std::ops::Deref; use std::path::Path; -pub enum FileBytes { +/// The bytes of a file (see [`read`]). The mapping is private to this module. +pub struct FileBytes(Inner); + +enum Inner { #[cfg(unix)] Mapped { ptr: *const u8, @@ -26,13 +29,13 @@ pub enum FileBytes { impl Deref for FileBytes { type Target = [u8]; fn deref(&self) -> &[u8] { - match self { + match &self.0 { #[cfg(unix)] - FileBytes::Mapped { ptr, len } => { + Inner::Mapped { ptr, len } => { // SAFETY: ptr/len describe a live read-only mapping owned by self. unsafe { std::slice::from_raw_parts(*ptr, *len) } } - FileBytes::Owned(bytes) => bytes, + Inner::Owned(bytes) => bytes, } } } @@ -40,7 +43,7 @@ impl Deref for FileBytes { impl Drop for FileBytes { fn drop(&mut self) { #[cfg(unix)] - if let FileBytes::Mapped { ptr, len } = *self { + if let Inner::Mapped { ptr, len } = self.0 { // SAFETY: the mapping was made by `read` with this address and length. unsafe { libc::munmap(ptr as *mut libc::c_void, len); @@ -51,7 +54,14 @@ impl Drop for FileBytes { /// The bytes of the file at `path`: mapped on Unix-like systems (falling back /// to a read when the mapping fails), read whole elsewhere. -pub fn read(path: &Path) -> std::io::Result { +/// +/// # Safety +/// +/// While the returned `FileBytes` lives, the file must not be truncated or +/// rewritten by anyone: a mapping is not a snapshot, and reading a page past +/// a new end of file faults. Engine loads hold it only for the load of one +/// model from the game's own assets. +pub unsafe fn read(path: &Path) -> std::io::Result { #[cfg(unix)] { use std::os::unix::io::AsRawFd; @@ -71,14 +81,14 @@ pub fn read(path: &Path) -> std::io::Result { ) }; if ptr != libc::MAP_FAILED { - return Ok(FileBytes::Mapped { + return Ok(FileBytes(Inner::Mapped { ptr: ptr as *const u8, len, - }); + })); } } } - std::fs::read(path).map(FileBytes::Owned) + std::fs::read(path).map(|bytes| FileBytes(Inner::Owned(bytes))) } #[cfg(test)] @@ -90,10 +100,11 @@ mod tests { let path = dir.join("bytes.bin"); let bytes: Vec = (0..100_000u32).map(|i| (i * 31 % 251) as u8).collect(); std::fs::write(&path, &bytes).unwrap(); - assert_eq!(&*super::read(&path).unwrap(), &bytes[..]); + // SAFETY (all three): the test's own files, not changed while mapped. + assert_eq!(&*unsafe { super::read(&path) }.unwrap(), &bytes[..]); std::fs::write(&path, b"").unwrap(); - assert!(super::read(&path).unwrap().is_empty()); - assert!(super::read(&dir.join("missing")).is_err()); + assert!(unsafe { super::read(&path) }.unwrap().is_empty()); + assert!(unsafe { super::read(&dir.join("missing")) }.is_err()); let _ = std::fs::remove_dir_all(&dir); } } diff --git a/native/shared/src/models_gltf_parse.rs b/native/shared/src/models_gltf_parse.rs index 61df1d3e..70110fb3 100644 --- a/native/shared/src/models_gltf_parse.rs +++ b/native/shared/src/models_gltf_parse.rs @@ -17,7 +17,12 @@ pub(super) fn split_glb(data: &[u8]) -> Option<(&[u8], Option<&[u8]>)> { let word = |at: usize| -> Option { Some(u32::from_le_bytes(data.get(at..at + 4)?.try_into().ok()?) as usize) }; - if data.get(0..4)? != b"glTF" || data.get(16..20)? != b"JSON" { + if data.get(0..4)? != b"glTF" || word(4)? != 2 || data.get(16..20)? != b"JSON" { + return None; + } + // the header's total length must fit the data (a truncated file is the + // gltf crate's to reject, with its message) + if word(8)? > data.len() { return None; } let json_end = 20usize.checked_add(word(12)?)?; diff --git a/native/shared/src/models_source_cache.rs b/native/shared/src/models_source_cache.rs index 9e88beba..94a9fecd 100644 --- a/native/shared/src/models_source_cache.rs +++ b/native/shared/src/models_source_cache.rs @@ -78,12 +78,14 @@ fn file_identity(source_path: &Path, file_data: &[u8]) -> u64 { if meta.len() != file_data.len() as u64 { return fingerprint(file_data); } - let changed = meta - .modified() - .ok() - .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) - .map(|d| d.as_nanos() as u64) - .unwrap_or(0); + // nanoseconds from the epoch, before it (the high bit set) or after + let changed = match meta.modified() { + Ok(t) => match t.duration_since(std::time::UNIX_EPOCH) { + Ok(after) => after.as_nanos() as u64, + Err(before) => (before.duration().as_nanos() as u64) | 1 << 63, + }, + Err(_) => 0, + }; #[cfg(unix)] let (ino, dev) = { use std::os::unix::fs::MetadataExt;