From 88bb851ae2b776e7b0a8d022657a1f484897bd89 Mon Sep 17 00:00:00 2001 From: leonidarider <358984476+leonidarider@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:37:49 +0100 Subject: [PATCH] refactor: introduce AppState.gta6 Gta6Session and eliminate 56 mutable statics (desloppify wave 6A-2a) - Introduce Gta6Session(Arc) in src/state/gta6/session.rs owned per AppState instance so background workers and &AppState callers operate on isolated session state instead of process-wide static Mutexes. - Eliminate all 56 mutable statics across 10 subsystems: gta6/anim (5), gta6/audio (7), gta6/bodies (5), gta6/particles (6), gta6/physics (7), gta6/textures (2), gta6/modding (7), gta6/install (8), ttpf_document (5), and document/gta6_script (4). --- src/photo/gta6.rs | 10 +- src/render/gta6_drawable/mod.rs | 64 +++-- src/render/gta6_drawable/wheels.rs | 2 +- src/render/gta6_fallback_tests.rs | 2 +- src/render/gta6_maps.rs | 2 +- src/render/gta6_meshlets/mod.rs | 5 +- src/render/gta6_shaded.rs | 5 +- src/render/particle_models.rs | 23 +- src/render/particles/gta6.rs | 26 +- src/render/viewport/bones.rs | 2 +- src/render/viewport/mod.rs | 3 +- src/state/capabilities.rs | 20 +- src/state/document/gta6_meta_names.rs | 17 +- src/state/document/gta6_script/build/mod.rs | 25 +- src/state/document/gta6_script/jobs.rs | 12 +- src/state/document/gta6_script/lists.rs | 13 +- src/state/document/gta6_script/mod.rs | 73 ++++-- src/state/document/gta6_script/tests.rs | 11 +- src/state/document/meta/mod.rs | 40 ++- src/state/document/mod.rs | 5 +- src/state/document_io.rs | 61 +++-- src/state/extract_job.rs | 27 +- src/state/file_io/mod.rs | 38 +-- src/state/gta6/anim/gta6_anim_edit/mod.rs | 5 +- src/state/gta6/anim/gta6_anim_play.rs | 4 +- src/state/gta6/anim/gta6_bone_edit/mod.rs | 38 ++- src/state/gta6/anim/gta6_clip_finding.rs | 34 ++- src/state/gta6/anim/gta6_entry_skeletons.rs | 69 ++++-- src/state/gta6/anim/gta6_expression_edit.rs | 13 +- src/state/gta6/anim/gta6_face/mod.rs | 53 ++-- src/state/gta6/anim/gta6_face/tests.rs | 9 +- src/state/gta6/anim/gta6_set_finding/mod.rs | 37 ++- src/state/gta6/anim/gta6_set_finding/tests.rs | 12 +- src/state/gta6/anim/mod.rs | 9 + src/state/gta6/audio/gta6_audio_links/mod.rs | 32 ++- .../gta6/audio/gta6_audio_links/tests.rs | 10 +- src/state/gta6/audio/gta6_dialogue/mod.rs | 186 +++++++++----- src/state/gta6/audio/gta6_dialogue/tests.rs | 34 +-- src/state/gta6/audio/mod.rs | 7 + .../gta6/bodies/gta6_other_bodies/mod.rs | 101 +++++--- .../gta6/bodies/gta6_other_bodies/nodes.rs | 84 +++++-- .../gta6/bodies/gta6_other_bodies_save/mod.rs | 8 +- src/state/gta6/bodies/gta6_resource.rs | 232 ++++++++---------- .../gta6_resource_save/awc_in_extent.rs | 20 +- .../gta6/bodies/gta6_resource_save/mod.rs | 24 +- src/state/gta6/bodies/gta6_save/mod.rs | 23 +- .../gta6/bodies/gta6_save/story_tests.rs | 7 +- src/state/gta6/bodies/mod.rs | 58 +++++ src/state/gta6/drawable/gta6_edit/mod.rs | 26 +- src/state/gta6/drawable/gta6_edit/tests.rs | 6 +- src/state/gta6/drawable/gta6_effects.rs | 32 ++- src/state/gta6/drawable/gta6_export.rs | 14 +- .../gta6/drawable/gta6_gltf_import/mod.rs | 7 +- .../gta6/drawable/gta6_gltf_import/tests.rs | 2 +- src/state/gta6/drawable/gta6_head.rs | 15 +- src/state/gta6/drawable/gta6_selected.rs | 8 +- src/state/gta6/drawable/gta6_shaders/tests.rs | 1 + src/state/gta6/drawable/gta6_weapon_parts.rs | 9 +- src/state/gta6/install/gta6_first_entry.rs | 60 +++-- .../gta6/install/gta6_install_harvest.rs | 31 ++- src/state/gta6/install/gta6_install_scan.rs | 64 +++-- src/state/gta6/install/gta6_key_words.rs | 37 +-- src/state/gta6/install/gta6_learned_names.rs | 21 +- src/state/gta6/install/gta6_names.rs | 107 ++++---- src/state/gta6/install/gta6_object_trees.rs | 14 +- src/state/gta6/install/gta6_small.rs | 18 +- src/state/gta6/install/mod.rs | 15 ++ src/state/gta6/mod.rs | 1 + src/state/gta6/modding/batch_export.rs | 45 +++- src/state/gta6/modding/mod.rs | 8 + src/state/gta6/modding/model_replace/mod.rs | 81 +++--- src/state/gta6/modding/model_replace/tests.rs | 10 +- src/state/gta6/modding/text_search/mod.rs | 84 ++++--- src/state/gta6/modding/text_search/tests.rs | 6 +- .../gta6/particles/gta6_particle_models.rs | 82 ++++--- .../gta6/particles/gta6_particles/mod.rs | 28 ++- .../gta6/particles/gta6_particles/spawners.rs | 24 +- .../gta6/particles/gta6_particles/sprites.rs | 24 +- .../gta6/particles/gta6_particles_save/mod.rs | 8 +- src/state/gta6/particles/mod.rs | 9 + src/state/gta6/physics/gta6_navmesh.rs | 84 ++++--- .../gta6/physics/gta6_navmesh_delete/links.rs | 81 +++--- .../gta6/physics/gta6_navmesh_delete/look.rs | 39 +-- .../gta6/physics/gta6_navmesh_delete/mod.rs | 56 +++-- src/state/gta6/physics/gta6_navmesh_edit.rs | 6 +- .../gta6_physics_edit/bound_reshape.rs | 62 +++-- .../gta6/physics/gta6_physics_edit/mod.rs | 20 +- src/state/gta6/physics/mod.rs | 8 + src/state/gta6/session.rs | 33 +++ .../gta6/textures/gta6_dictionary_index.rs | 9 +- .../textures/gta6_dictionary_write/mod.rs | 60 +++-- .../gta6/textures/gta6_embedded_edit/mod.rs | 82 ++++--- .../gta6/textures/gta6_embedded_edit/tests.rs | 19 +- src/state/gta6/textures/gta6_texture_index.rs | 21 +- .../gta6/textures/gta6_texture_names_file.rs | 3 +- .../gta6/textures/gta6_texture_naming.rs | 8 +- src/state/gta6/textures/gta6_textures.rs | 33 ++- src/state/gta6/textures/mod.rs | 7 + src/state/gta6/world/gta6_map/entity.rs | 15 +- src/state/gta6/world/gta6_map/links/mod.rs | 3 +- src/state/gta6/world/gta6_world/mod.rs | 7 +- .../world/gta6_world/worldview/model/mod.rs | 4 +- src/state/jobs.rs | 16 +- src/state/media_playback.rs | 2 +- src/state/mod.rs | 25 +- src/state/photo_documents.rs | 19 +- src/state/reload_open_file.rs | 3 +- src/state/rpf/rpf9_scan/ciphered/mod.rs | 24 +- src/state/rpf/rpf9_scan/mod.rs | 58 +++-- src/state/rpf/rpf9_scan/payload.rs | 38 ++- .../rpf9_table/gta6_archive_save/mod.rs | 16 +- .../rpf_archive_open/tree_open/bind/mod.rs | 16 +- .../rpf/rpf_archive_open/tree_open/mod.rs | 6 +- .../headerless_tests/saves_per_kind/mod.rs | 12 +- src/state/source_textures.rs | 7 +- src/state/tests/opening_a_gta_vi_body.rs | 5 +- src/state/texture_edit.rs | 9 +- src/state/texture_resolution.rs | 16 +- src/state/textures.rs | 27 +- src/state/ttpf_document/calibration.rs | 39 +-- src/state/ttpf_document/mod.rs | 132 +++++----- src/state/world_session/gta6.rs | 11 +- src/state/world_session/mod.rs | 2 +- src/ui/commands/tools_and_help.rs | 4 +- src/ui/panels/gallery.rs | 2 +- src/ui/panels/gxt2_table.rs | 5 +- src/ui/panels/hierarchy/drawable.rs | 4 +- src/ui/panels/hierarchy/files/folder_view.rs | 2 +- src/ui/panels/hierarchy/gta6/drawable.rs | 8 +- src/ui/panels/hierarchy/gta6/expressions.rs | 28 ++- src/ui/panels/hierarchy/gta6/install.rs | 15 +- src/ui/panels/hierarchy/gta6/mission/mod.rs | 13 +- src/ui/panels/hierarchy/gta6/mission/other.rs | 34 ++- src/ui/panels/hierarchy/gta6/save.rs | 2 +- src/ui/panels/hierarchy/gta6/script.rs | 4 +- src/ui/panels/hierarchy/rpf_tree.rs | 10 +- src/ui/panels/hierarchy/ttpf.rs | 7 +- src/ui/panels/hierarchy/ynv.rs | 2 +- src/ui/panels/inspector/awc.rs | 2 +- src/ui/panels/inspector/gta6/anim/face.rs | 4 +- src/ui/panels/inspector/gta6/anim/mod.rs | 7 +- src/ui/panels/inspector/gta6/anim/play.rs | 8 +- src/ui/panels/inspector/gta6/dialogue.rs | 22 +- .../inspector/gta6/drawable/bone_edit.rs | 2 +- src/ui/panels/inspector/gta6/drawable/head.rs | 2 +- .../inspector/gta6/drawable/material_edit.rs | 27 +- .../gta6/drawable/material_layout.rs | 18 +- src/ui/panels/inspector/gta6/drawable/mod.rs | 13 +- .../inspector/gta6/drawable/selected.rs | 2 +- src/ui/panels/inspector/gta6/move_network.rs | 24 +- src/ui/panels/inspector/gta6/particles.rs | 6 +- src/ui/panels/inspector/gta6/text.rs | 7 +- src/ui/panels/inspector/gta6/text_entries.rs | 6 +- src/ui/panels/inspector/rpf9.rs | 4 +- src/ui/panels/inspector/text.rs | 2 +- src/ui/panels/inspector/ttpf.rs | 4 +- src/ui/panels/maps/scanned.rs | 27 +- src/ui/panels/maps/world.rs | 2 +- src/ui/panels/meta_editor/ctx.rs | 2 + src/ui/panels/meta_editor/mod.rs | 1 + src/ui/panels/meta_editor/text_names.rs | 4 +- src/ui/panels/mod.rs | 4 +- src/ui/panels/status_bar.rs | 3 + src/ui/panels/texture_preview/mod.rs | 9 +- src/ui/panels/world_viewer/map.rs | 8 +- src/ui/panels/world_viewer/places.rs | 9 +- src/ui/panels/world_viewer/side.rs | 26 +- 167 files changed, 2625 insertions(+), 1405 deletions(-) create mode 100644 src/state/gta6/session.rs diff --git a/src/photo/gta6.rs b/src/photo/gta6.rs index 89b645b14..58b74b869 100644 --- a/src/photo/gta6.rs +++ b/src/photo/gta6.rs @@ -190,7 +190,13 @@ pub(super) fn photograph( None => None, }; let (models, kits) = super::timing::time("04 gta6: models", || { - crate::state::gta6_models_and_kits(&root, under, only.as_ref(), ctx.kits.as_ref()) + crate::state::gta6_models_and_kits( + &state.gta6.install, + &root, + under, + only.as_ref(), + ctx.kits.as_ref(), + ) })?; println!( "{} models under {under} in {}", @@ -198,7 +204,7 @@ pub(super) fn photograph( root.display() ); if ctx.wheels.is_some() { - let found = crate::state::gta6_models(&root, WHEELS_UNDER, None)?; + let found = crate::state::gta6_models(&state.gta6.install, &root, WHEELS_UNDER, None)?; println!("{} wheel models", found.len()); ctx.wheel_models = Some(found.into_iter().map(|m| (m.name.clone(), m)).collect()); } diff --git a/src/render/gta6_drawable/mod.rs b/src/render/gta6_drawable/mod.rs index 0253595e6..f1929a195 100644 --- a/src/render/gta6_drawable/mod.rs +++ b/src/render/gta6_drawable/mod.rs @@ -42,7 +42,7 @@ pub(crate) fn meshes(req: &GeometryRequest<'_>) -> Vec { let posed = crate::state::gta6_anim_play::gta6_posed(req.state); let own = posed .as_ref() - .and_then(|_| own_skeleton(req.doc, req.selection)); + .and_then(|_| own_skeleton(&req.state.gta6.anim, req.doc, req.selection)); let posing = (posed.as_ref()).map(|p| (p.skeleton, own.as_ref())); let (lod, channel) = ( req.state.preview_scene.lod, @@ -55,12 +55,16 @@ pub(crate) fn meshes(req: &GeometryRequest<'_>) -> Vec { let parts = parts_drawn(req.state, req.doc).filter(|_| posing.is_none()); let mut out = match &parts { Some(parts) => (parts.iter()) - .flat_map(|part| part_meshes(part, lod, channel, &srgb)) + .flat_map(|part| part_meshes(&req.state.gta6, part, lod, channel, &srgb)) .collect(), None => { - let mut own = meshes_at(drawable, lod, posing, channel, &srgb); + let mut own = meshes_at(&req.state.gta6, drawable, lod, posing, channel, &srgb); let beside = req.beside.into_iter().flatten(); - own.extend(beside.flat_map(|part| part_meshes(part, lod, channel, &srgb))); + own.extend( + beside.flat_map(|part| { + part_meshes(&req.state.gta6, part, lod, channel, &srgb) + }), + ); own } }; @@ -81,8 +85,16 @@ pub(crate) fn own_tone(state: &AppState, doc: &crate::state::Document) -> Option }; let drawable = drawable_of(resource, None)?; let srgb = |key: u64| srgb_key(state, doc.id, key); - (meshes_at(drawable, state.preview_scene.lod, None, None, &srgb).into_iter()) - .find_map(|mesh| mesh.texture_name.filter(|_| !mesh.bump)) + (meshes_at( + &state.gta6, + drawable, + state.preview_scene.lod, + None, + None, + &srgb, + ) + .into_iter()) + .find_map(|mesh| mesh.texture_name.filter(|_| !mesh.bump)) } /// The name of `doc`'s own GTA VI model as the game's documents state it. @@ -106,7 +118,7 @@ pub(crate) fn surfaced( let drawable = drawable_of(resource, None)?; let lod = state.preview_scene.lod; let srgb = |key: u64| srgb_key(state, doc.id, key); - let mut meshes = meshes_at(drawable, lod, None, None, &srgb); + let mut meshes = meshes_at(&state.gta6, drawable, lod, None, None, &srgb); for (mesh, ids) in meshes.iter_mut().zip(layer_colours(drawable, lod)) { let Some(ids) = ids else { continue; @@ -182,9 +194,9 @@ pub(crate) fn layered_parts( let drawable = drawable_of(&part.resource, None); let stated = drawable.and_then(|d| layers(model_name(&d.name))); let (Some(drawable), Some(stated)) = (drawable, stated) else { - return part_meshes(part, lod, None, &srgb); + return part_meshes(&state.gta6, part, lod, None, &srgb); }; - let mut meshes = part_meshes(part, lod, None, &srgb); + let mut meshes = part_meshes(&state.gta6, part, lod, None, &srgb); let stated_layers = layer_colours(drawable, lod); for (mesh, colours) in meshes.iter_mut().zip(stated_layers) { let named = colours.filter(|_| stated.per_vertex); @@ -215,16 +227,18 @@ pub(crate) fn parts_drawn( /// A part's meshes at `lod`, in the weapon's frame. fn part_meshes( + gta6: &crate::state::gta6::session::Gta6Session, part: &Part, lod: usize, channel: Option, srgb: &dyn Fn(u64) -> Option, ) -> Vec { - placed_at(&part.resource, part.place, lod, channel, srgb) + placed_at(gta6, &part.resource, part.place, lod, channel, srgb) } /// The meshes of `resource` at `lod`, each vertex taken through `place`. fn placed_at( + gta6: &crate::state::gta6::session::Gta6Session, resource: &Resource, place: Mat4, lod: usize, @@ -235,7 +249,7 @@ fn placed_at( return Vec::new(); }; let normals = Mat3::from_mat4(place).inverse().transpose(); - let mut meshes = meshes_at(drawable, lod, None, channel, srgb); + let mut meshes = meshes_at(gta6, drawable, lod, None, channel, srgb); for v in meshes.iter_mut().flat_map(|mesh| &mut mesh.vertices) { v.position = (place.transform_point3(Vec3::from(v.position))).to_array(); v.normal = (normals * Vec3::from(v.normal)) @@ -356,7 +370,11 @@ pub(crate) fn drawn_geometries( let mut out = Vec::new(); for (m, model) in drawable.levels[lod].iter().flatten().enumerate() { for (g, geometry) in model.geometries.iter().enumerate() { - if let Some(mesh) = geometry.as_ref().ok().and_then(|g| upload(&bases, g, None)) { + if let Some(mesh) = geometry + .as_ref() + .ok() + .and_then(|g| upload(&state.gta6, &bases, g, None)) + { out.push((m, g, mesh)); } } @@ -367,10 +385,11 @@ pub(crate) fn drawn_geometries( /// The skeleton of a scanned drawable or fragment, or of the dictionary entry `selection` is in, /// read when it opened. fn own_skeleton( + anim: &crate::state::gta6::anim::AnimSession, doc: &crate::state::Document, selection: Option, ) -> Option { - crate::state::gta6_entry_skeletons::shown(doc, selection) + crate::state::gta6_entry_skeletons::shown(anim, doc, selection) } /// The level of detail `lod`, or the first where that one has no models. @@ -392,6 +411,7 @@ fn drawn_level(drawable: &Drawable, lod: usize) -> impl Iterator } pub(crate) fn meshes_at( + gta6: &crate::state::gta6::session::Gta6Session, drawable: &Drawable, lod: usize, posing: Option>, @@ -402,7 +422,7 @@ pub(crate) fn meshes_at( let mut out = Vec::new(); for model in drawn_level(drawable, lod) { for g in model.geometries.iter().flatten() { - let Some(mut mesh) = upload(&bases, g, channel) else { + let Some(mut mesh) = upload(gta6, &bases, g, channel) else { continue; }; if let Some((skeleton, own)) = posing { @@ -429,6 +449,7 @@ pub(crate) fn meshes_at( /// Each geometry of the drawn level of `doc` that does not join `skeleton`: its model, its index and why. pub(crate) fn unjoined( + anim: &crate::state::gta6::anim::AnimSession, doc: &crate::state::Document, selection: Option, lod: usize, @@ -440,7 +461,7 @@ pub(crate) fn unjoined( let Some(drawable) = drawable_of(resource, selection) else { return Vec::new(); }; - let own = own_skeleton(doc, selection); + let own = own_skeleton(anim, doc, selection); let mut out = Vec::new(); for (m, model) in drawn_level(drawable, lod).enumerate() { for (g, geometry) in model.geometries.iter().enumerate() { @@ -472,7 +493,7 @@ const DIFFUSE_TEX: u32 = or_io::gta6::hash::name_hash32(b"DiffuseTex"); /// index, states an sRGB format for it, as colour data has: `false` too for a key no pack of its /// install holds, and `None` for one a pack not indexed or opened yet may hold. pub(crate) fn srgb_key(state: &AppState, doc: DocumentId, key: u64) -> Option { - let name = texture_name(key); + let name = texture_name(&state.gta6, key); let entry = crate::state::textures::open_pack_entry(state, &name); let code = (entry.map(|e| e.format_code)).or_else(|| state.indexed_texture_format(key)); let srgb = @@ -545,6 +566,7 @@ fn over_extent(reference: &[Option<[f32; 3]>]) -> Vec<[f32; 4]> { } fn upload( + gta6: &crate::state::gta6::session::Gta6Session, bases: &[DrawnTexture], geometry: &Geometry, channel: Option, @@ -587,7 +609,7 @@ fn upload( Some(MeshUpload { vertices, indices: corners.into_iter().map(u32::from).collect(), - texture_name: texture.map(|(key, _)| texture_name(key)), + texture_name: texture.map(|(key, _)| texture_name(gta6, key)), bump: texture.is_some_and(|(_, bump)| bump), skinning: None, palette_bones: Vec::new(), @@ -1077,7 +1099,9 @@ mod tests { d }; + let gta6 = crate::state::gta6::session::Gta6Session::default(); let mut meshes = meshes_at( + >a6, &with_palette(b"SKEL_Head"), 0, Some((&skeleton, None)), @@ -1099,9 +1123,10 @@ mod tests { "{moved}" ); - let unposed = meshes_at(&with_palette(b"SKEL_Head"), 0, None, None, &|_| None); + let unposed = meshes_at(>a6, &with_palette(b"SKEL_Head"), 0, None, None, &|_| None); assert!(unposed[0].skinning.is_none(), "no clip poses a skeleton"); let missing = meshes_at( + >a6, &with_palette(b"SKEL_Missing"), 0, Some((&skeleton, None)), @@ -1114,10 +1139,11 @@ mod tests { #[test] fn a_geometry_whose_positions_were_refused_draws_nothing() { + let gta6 = crate::state::gta6::session::Gta6Session::default(); let mut refused = geometry(vec![[0.0; 3]; 3], Vertices::default()); refused.positions = Err(or_io::gta6::headerless::HeaderlessError::Positions { why: "the decoded vertices do not reach the geometry's box", }); - assert!(meshes_at(&drawable(vec![refused]), 0, None, None, &|_| None).is_empty()); + assert!(meshes_at(>a6, &drawable(vec![refused]), 0, None, None, &|_| None).is_empty()); } } diff --git a/src/render/gta6_drawable/wheels.rs b/src/render/gta6_drawable/wheels.rs index 0c8ae87d6..4f6822d7f 100644 --- a/src/render/gta6_drawable/wheels.rs +++ b/src/render/gta6_drawable/wheels.rs @@ -156,7 +156,7 @@ pub(crate) fn wheels( let turn = (Vec3::new(*x, *y, *z).try_normalize()) .map_or(Mat4::IDENTITY, |axis| Mat4::from_axis_angle(axis, *angle)); let place = *bone_world * turn * Mat4::from_scale(Vec3::splat(*scale)); - let mut meshes = placed_at(resource, place, lod, None, &|_| None); + let mut meshes = placed_at(&state.gta6, resource, place, lod, None, &|_| None); for mesh in &mut meshes { for vertex in &mut mesh.vertices { vertex.colour = [linear(*r), linear(*g), linear(*b), 1.0]; diff --git a/src/render/gta6_fallback_tests.rs b/src/render/gta6_fallback_tests.rs index 879965474..68de4df02 100644 --- a/src/render/gta6_fallback_tests.rs +++ b/src/render/gta6_fallback_tests.rs @@ -83,7 +83,7 @@ fn a_geometry_the_pack_draws_nothing_of_is_left_out_before_its_material_is_made( }; let left = shaded_surfaces(&state, &session, &refused).expect("a drawable is open"); assert!(left.surfaces.is_empty() && left.decoding.is_empty()); - let effect = effect_name(0x0BAD_F00D); + let effect = effect_name(&state.gta6.bodies, 0x0BAD_F00D); assert_eq!(left.left_out, [(effect, "draws nothing".to_string())]); assert_eq!(made.get(), 1, "asked once a shader"); diff --git a/src/render/gta6_maps.rs b/src/render/gta6_maps.rs index de6fde235..f4ab139de 100644 --- a/src/render/gta6_maps.rs +++ b/src/render/gta6_maps.rs @@ -57,7 +57,7 @@ pub(super) fn stored( key: u64, ) -> Option { use crate::state::texture_resolution::probe; - let name = crate::state::gta6_resource::texture_name(key); + let name = crate::state::gta6_resource::texture_name(&state.gta6, key); let found = probe(state, None, selection, &name).found; let payload = found .and_then(|found| state.document(found.document)) diff --git a/src/render/gta6_meshlets/mod.rs b/src/render/gta6_meshlets/mod.rs index 6755cb101..1193983df 100644 --- a/src/render/gta6_meshlets/mod.rs +++ b/src/render/gta6_meshlets/mod.rs @@ -723,6 +723,7 @@ pub(crate) fn meshlets( let name = drawable.name.as_str(); let sources = Sources { shading: >a6_shaders::shading, + effect_name: &|hash| effect_name(&state.gta6.bodies, hash), map: &|key| session.decoded(key, || stored(key)), layered: &|| gta6_layer_index::worn_as(state, name, true), lost: &session.lost, @@ -782,6 +783,8 @@ pub(crate) struct Sources<'s> { /// The pass that draws a geometry of this vertex data with the effect of this hash /// ([`gta6_shaders::shading`]). pub shading: &'s dyn Fn(u32, &[u8]) -> gta6_shaders::Shading, + /// The effect name for a shader hash, else `hash_` and the hash. + pub effect_name: &'s dyn Fn(u32) -> String, /// The map of a key, decoded; `Err` while a worker decodes it. pub map: &'s dyn Fn(u64) -> Result>, ()>, /// The layered material the drawable wears, asked for by the first pass that reads a record. @@ -875,7 +878,7 @@ pub(crate) fn meshlets_of( .enumerate(); for (mesh, (model, geometry)) in geometries { let shader = drawable.shaders.get(usize::from(geometry.shader))?; - let effect = effect_name(shader.name_hash); + let effect = (from.effect_name)(shader.name_hash); // A windscreen's wiper mask is what the glass's program reads, and no surface of its own. if effect.eq_ignore_ascii_case(WIPER_MASK) { continue; diff --git a/src/render/gta6_shaded.rs b/src/render/gta6_shaded.rs index 66ad58647..a4301bdd4 100644 --- a/src/render/gta6_shaded.rs +++ b/src/render/gta6_shaded.rs @@ -48,7 +48,7 @@ pub(crate) fn shaded_surfaces( let mut decoding = Vec::new(); let materials: Vec<(String, Result)> = (drawable.shaders.iter()) .map(|shader| { - let effect = effect_name(shader.name_hash); + let effect = effect_name(&state.gta6.bodies, shader.name_hash); let made = draws(&effect).map(|()| { material( state, @@ -307,7 +307,8 @@ pub(super) fn stored_level( key: u64, ) -> Option { use or_io::codec::texture::TextureSource; - let resolved = texture_resolution::resolve(state, None, selection, &texture_name(key))?; + let resolved = + texture_resolution::resolve(state, None, selection, &texture_name(&state.gta6, key))?; let texture = &resolved.texture; let (format, size) = (texture.pixel_format(), texture.stored_size()); let level = format.mip_level_range(size.0, size.1, 0); diff --git a/src/render/particle_models.rs b/src/render/particle_models.rs index 2dd5382eb..dc47d9660 100644 --- a/src/render/particle_models.rs +++ b/src/render/particle_models.rs @@ -35,8 +35,9 @@ impl ParticleModelMeshCache { } } - pub fn get_or_build( + pub(crate) fn get_or_build( &mut self, + gta6: &crate::state::gta6::session::Gta6Session, asset: &PtxFxList, drawable_hash: u32, ) -> Option>> { @@ -51,8 +52,8 @@ impl ParticleModelMeshCache { let mut uploads = build_meshes_from_ypt_drawable(asset, drawable_hash); // A GTA VI list holds no drawable: the one its rule names is a search's find, if any. if uploads.is_empty() { - if let Some(found) = found_drawable(drawable_hash) { - uploads = meshes_at(&found, 0, None, None, &|_: u64| None); + if let Some(found) = found_drawable(>a6.particles, drawable_hash) { + uploads = meshes_at(gta6, &found, 0, None, None, &|_: u64| None); size = std::array::from_fn(|i| found.box_max[i] - found.box_min[i]); } } @@ -85,7 +86,8 @@ impl ParticleModelMeshCache { } } -pub fn build_model_batches( +pub(crate) fn build_model_batches( + gta6: &crate::state::gta6::session::Gta6Session, mesh_cache: &mut ParticleModelMeshCache, texture_cache: &mut ParticleTextureCache, asset: Option<&PtxFxList>, @@ -127,7 +129,7 @@ pub fn build_model_batches( continue; } let drawable_hash = rule.drawables[drawable_idx].hash_name.get(); - let Some(geoms) = mesh_cache.get_or_build(asset, drawable_hash) else { + let Some(geoms) = mesh_cache.get_or_build(gta6, asset, drawable_hash) else { continue; }; let instances = @@ -218,13 +220,18 @@ fn model_technique(lit: bool) -> String { mod tests { #[test] fn a_model_rule_draws_the_gta6_drawable_a_search_found_in_its_own_box() { + use crate::state::gta6::session::Gta6Session; use crate::state::gta6_particle_models::{found_for_tests, one_triangle}; const HASH: u32 = 0x3A0D_E15F; + let gta6 = Gta6Session::default(); let mut cache = super::ParticleModelMeshCache::new(); let list = or_io::gta5::PtxFxList::default(); - assert!(cache.get_or_build(&list, HASH).is_none(), "none found"); - found_for_tests(HASH, one_triangle([1.0, 2.0, 3.0])); - let drawn = cache.get_or_build(&list, HASH); + assert!( + cache.get_or_build(>a6, &list, HASH).is_none(), + "none found" + ); + found_for_tests(>a6.particles, HASH, one_triangle([1.0, 2.0, 3.0])); + let drawn = cache.get_or_build(>a6, &list, HASH); let geoms = drawn.expect("the found drawable is drawn"); assert_eq!(geoms.len(), 1); assert_eq!(geoms[0].geometry.indices.len(), 3); diff --git a/src/render/particles/gta6.rs b/src/render/particles/gta6.rs index 7556dd2dd..90ad36216 100644 --- a/src/render/particles/gta6.rs +++ b/src/render/particles/gta6.rs @@ -67,11 +67,12 @@ pub(crate) fn model_texture( /// `cache`, once each time the documents and names they resolve against change. pub(crate) fn prime(cache: &mut ParticleTextureCache, state: &AppState, doc: DocumentId) { let path = state.document(doc).and_then(|d| d.path.as_deref()); - let Some((path, kept)) = path.and_then(|p| Some((p, sprites::of(p)?))) else { + let Some((path, kept)) = path.and_then(|p| Some((p, sprites::of(&state.gta6.particles, p)?))) + else { return; }; let lines = drawable_lines_stamp(state); - let stamp = (lines, found_count()); + let stamp = (lines, found_count(&state.gta6.particles)); if cache.gta6.stamp == Some(stamp) { return; } @@ -84,10 +85,10 @@ pub(crate) fn prime(cache: &mut ParticleTextureCache, state: &AppState, doc: Doc cache.images.retain(|_, image| image.is_some()); let mut by_rule = HashMap::new(); for (rule, sprite) in kept.iter() { - let mut texture = format!("{}#{}", texture_name(sprite.key), sprite.slot); + let mut texture = format!("{}#{}", texture_name(&state.gta6, sprite.key), sprite.slot); let mut image = cached(&mut cache.images, &texture, || decoded(state, sprite)); if let (Some(shape), Some(ramp)) = (image.clone(), sprite.ramp) { - let coloured = format!("{texture}#{}", texture_name(ramp)); + let coloured = format!("{texture}#{}", texture_name(&state.gta6, ramp)); let tinted = cached(&mut cache.images, &coloured, || ramped(state, &shape, ramp)); // Grey until a pack holding the ramp is open. if tinted.is_some() { @@ -134,7 +135,7 @@ fn model_textures( (doc, path): (DocumentId, &Path), earlier: HashMap>>, ) -> HashMap>> { - let Some(named) = crate::state::gta6_particle_models::kept(path) else { + let Some(named) = crate::state::gta6_particle_models::kept(&state.gta6.particles, path) else { return HashMap::new(); }; let srgb = |key: u64| srgb_key(state, doc, key); @@ -144,14 +145,15 @@ fn model_textures( if out.contains_key(&hash) { continue; } - let Some(drawable) = found_drawable(hash) else { + let Some(drawable) = found_drawable(&state.gta6.particles, hash) else { continue; }; // The surfaces the particle preview draws, in its order: those with vertices and corners. - let names: Vec> = (meshes_at(&drawable, 0, None, None, &srgb).into_iter()) - .filter(|u| !u.vertices.is_empty() && !u.indices.is_empty()) - .map(|u| u.texture_name) - .collect(); + let names: Vec> = (meshes_at(&state.gta6, &drawable, 0, None, None, &srgb) + .into_iter()) + .filter(|u| !u.vertices.is_empty() && !u.indices.is_empty()) + .map(|u| u.texture_name) + .collect(); for name in names.iter().flatten() { cached(images, name, || { first_level(&resolved(state, name)?.texture) @@ -169,7 +171,7 @@ fn resolved<'a>(state: &'a AppState, name: &str) -> Option Option { - let found = resolved(state, &texture_name(sprite.key))?; + let found = resolved(state, &texture_name(&state.gta6, sprite.key))?; let mut image = first_level(&found.texture)?; shown_as(&mut image.rgba, sprite.slot); Some(image) @@ -178,7 +180,7 @@ fn decoded(state: &AppState, sprite: &Sprite) -> Option { /// The grey `shape` coloured through the ramp the key `ramp` resolves to; `None` where that /// texture is not a ramp. fn ramped(state: &AppState, shape: &Image, ramp: u64) -> Option { - let found = resolved(state, &texture_name(ramp))?; + let found = resolved(state, &texture_name(&state.gta6, ramp))?; let (format, height) = (found.texture.format(), found.texture.height()); if !is_ramp(format, height) { tracing::debug!( diff --git a/src/render/viewport/bones.rs b/src/render/viewport/bones.rs index 393d0db50..8abb4adc9 100644 --- a/src/render/viewport/bones.rs +++ b/src/render/viewport/bones.rs @@ -118,7 +118,7 @@ fn gta6_rest(state: &AppState) -> Option<(DocumentId, Named, Arc)> { let named = entry.map_or(Named::Drawable, Named::Entry); let data = entry.map_or(usize::MAX, |code| code as usize); let skeleton = kept((doc.id, doc.payload_epoch(), data), || { - let read = shown(doc, selection)?; + let read = shown(&state.gta6.anim, doc, selection)?; (!read.bones.is_empty()).then(|| or_anim::gta6::skeleton(&read)) })?; Some((doc.id, named, skeleton)) diff --git a/src/render/viewport/mod.rs b/src/render/viewport/mod.rs index ccc420a10..62f1c64e2 100644 --- a/src/render/viewport/mod.rs +++ b/src/render/viewport/mod.rs @@ -144,7 +144,7 @@ impl MeshCacheKey { garment_dictionary: state.garment_dictionary(doc), recooked: state.recooked, packs: crate::state::ttpf_document::packs_epoch(state), - texture_names: crate::state::ttpf_document::names_known(), + texture_names: crate::state::ttpf_document::names_known(&state.gta6.ttpf), ground: state.drivers.world_background.ground, gta6_posed_on: crate::state::gta6_anim_play::gta6_model_drawn(state).or_else(|| { crate::state::gta6_anim_play::gta6_posed(state).map(|p| (p.model, true)) @@ -316,6 +316,7 @@ impl RenderBridge { self.renderer.set_trail_batches(trail_batches); let model_batches = crate::render::particle_models::build_model_batches( + &state.gta6, &mut self.particles.model_meshes, &mut self.particles.textures, Some(asset), diff --git a/src/state/capabilities.rs b/src/state/capabilities.rs index a124c5689..219c37954 100644 --- a/src/state/capabilities.rs +++ b/src/state/capabilities.rs @@ -41,16 +41,22 @@ pub type TextureForSelectionFn = fn(&DocPayload, SelectionKey) -> TextureResolut pub type TextureAtFn = for<'p> fn(&'p DocPayload, TextureSource, &str) -> Option>; -pub type TextureNamedFn = - for<'p> fn(&'p DocPayload, Option, &str) -> Option>; +pub type TextureNamedFn = for<'p> fn( + &super::gta6::session::Gta6Session, + &'p DocPayload, + Option, + &str, +) -> Option>; pub type MeshSourcesFn = fn(DocumentId, &DocPayload, &str) -> Vec; pub type SkeletonSourcesFn = fn(DocumentId, &DocPayload) -> Vec; -pub type EditedSectionsFn = - fn(&super::Document) -> Option>; +pub type EditedSectionsFn = fn( + &super::Document, + &super::gta6::session::Gta6Session, +) -> Option>; pub type SkeletonDataFn = for<'p> fn(&'p DocPayload, super::SkeletonSource) -> Option<&'p or_io::gta5::CrSkeletonData>; @@ -498,7 +504,7 @@ static BUILTIN: &[FormatCapabilities] = &[ outline: Some(outline::gta6_anim), has_outline_children: Some(children::gta6_anim), inspector: Some(inspector::gta6_anim), - edited_sections: Some(|d| held(super::gta6_anim_edit::edited_sections(&d.payload))), + edited_sections: Some(|d, _| held(super::gta6_anim_edit::edited_sections(&d.payload))), ..FormatCapabilities::none(DocumentKind::Gta6Anim) }, // A drawable or a bound's triangles are drawn and the reader's facts shown; its materials edit in place, and a save writes them as a loose resource. @@ -521,7 +527,7 @@ static BUILTIN: &[FormatCapabilities] = &[ // Its texts edit in the centre, and a save writes them as a loose resource. FormatCapabilities { inspector: Some(inspector::gta6_text), - edited_sections: Some(|d| held(super::gta6_text::edited_sections(&d.payload))), + edited_sections: Some(|d, _| held(super::gta6_text::edited_sections(&d.payload))), ..FormatCapabilities::none(DocumentKind::Gta6Text) }, crate::ui::panels::inspector::gta6_text::AUDIO_DATA_CAPABILITIES, @@ -587,7 +593,7 @@ static BUILTIN: &[FormatCapabilities] = &[ mesh_sources: None, skeleton_sources: None, skeleton_data: None, - edited_sections: Some(|d| super::gta6_meta_save::edited_sections(&d.payload)), + edited_sections: Some(|d, _| super::gta6_meta_save::edited_sections(&d.payload)), }, FormatCapabilities { inspector: Some(inspector::hex), diff --git a/src/state/document/gta6_meta_names.rs b/src/state/document/gta6_meta_names.rs index ec32462c4..122ebb182 100644 --- a/src/state/document/gta6_meta_names.rs +++ b/src/state/document/gta6_meta_names.rs @@ -6,6 +6,8 @@ use or_io::meta::binary::hash_index::default_hash_index; use or_io::meta::binary::{ContainerLayout, MetaLayout}; use or_io::meta::instance::HashedString; +use crate::state::gta6::install::InstallSession; + /// Whether `layout` is GTA VI's table form, P-form or headerless resource. pub fn meta_names_from_the_text(layout: Option<&MetaLayout>) -> bool { match layout.map(|l| &l.container) { @@ -16,31 +18,32 @@ pub fn meta_names_from_the_text(layout: Option<&MetaLayout>) -> bool { } /// The name the vocabulary holds alone for `hash`, marked as from the text. -pub fn hash_text_name(hash: u32) -> Option { - let name = crate::state::gta6_names::name32(hash)?; +pub(crate) fn hash_text_name(install: &InstallSession, hash: u32) -> Option { + let name = crate::state::gta6_names::name32(install, hash)?; Some(tr!("{name} (from the text)", name = name)) } /// The marked vocabulary name of a hash value no table names. -pub fn meta_text_name(value: &HashedString) -> Option { +pub(crate) fn meta_text_name(install: &InstallSession, value: &HashedString) -> Option { match value.raw.is_empty() && value.hash != 0 { - true => hash_text_name(value.hash), + true => hash_text_name(install, value.hash), false => None, } } /// `hash`'s name in the tables, else its marked vocabulary name, else `hash_XXXXXXXX`. -pub fn hash_name_or_text(hash: u32) -> String { +pub(crate) fn hash_name_or_text(install: &InstallSession, hash: u32) -> String { let index = default_hash_index(); match index.lookup(hash) { Some(name) => name.to_string(), - None => hash_text_name(hash).unwrap_or_else(|| index.name_or_literal(hash)), + None => hash_text_name(install, hash).unwrap_or_else(|| index.name_or_literal(hash)), } } /// `xml` as the Text panel shows it: a GTA VI form's named hash values each take a comment, the /// document's own string first, and a 64-bit value one of its own strings hashes to takes one too. pub(super) fn shown_xml( + install: &InstallSession, xml: String, layout: Option<&MetaLayout>, strings: &super::gta6_meta_strings::DocumentStrings, @@ -51,7 +54,7 @@ pub(super) fn shown_xml( } let named = with_text_names(&xml, |hash| { (strings.name(hash).map(str::to_owned)) - .or_else(|| vocabulary.then(|| hash_text_name(hash)).flatten()) + .or_else(|| vocabulary.then(|| hash_text_name(install, hash)).flatten()) }); with_wide_names(&named, |hash| strings.name64(hash).map(str::to_owned)) } diff --git a/src/state/document/gta6_script/build/mod.rs b/src/state/document/gta6_script/build/mod.rs index acbd43f57..6c4cad0e7 100644 --- a/src/state/document/gta6_script/build/mod.rs +++ b/src/state/document/gta6_script/build/mod.rs @@ -7,7 +7,7 @@ use std::io::Read as _; use std::panic::{catch_unwind, AssertUnwindSafe}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::{Mutex, PoisonError}; +use std::sync::{Arc, Mutex, PoisonError}; use or_io::container::rpf::{Gta6Mount, GtaViKeys, RPF9_MAGIC}; use or_io::gta6::script::lift::Progress; @@ -25,7 +25,10 @@ const MAX_DEPTH: usize = 8; const PART_FILE: &str = ".project.json.part"; /// Held while a project is written: two builds at once would write one part file. -static WRITING: Mutex<()> = Mutex::new(()); +#[derive(Clone, Default)] +pub(in super::super) struct BuildState { + writing: Arc>, +} /// How far a build has come, as the thread doing it says. #[derive(Debug, Default)] @@ -68,6 +71,7 @@ pub(super) fn is_archive(path: &Path) -> bool { /// Builds the project of every program of the archive at `archive` and writes it into `folder` as `project.json`, in place of the one there; the file written. // ⚠ A worker's call, never the UI thread's: every enciphered entry is deciphered to tell. pub(super) fn build( + state: &BuildState, archive: &Path, folder: &Path, building: &Building, @@ -104,10 +108,11 @@ pub(super) fn build( if progress.stopped() { return Err(stopped()); } - let written = put(folder, &bytes)?; + let written = put(state, folder, &bytes)?; if derived.named > 0 || !names.methods.is_empty() { let slots = or_io::gta6::script::names::slots::table(&names); let _ = put_file( + state, folder, "slot-names.tsv", ".slot-names.tsv.part", @@ -319,13 +324,19 @@ fn each( } /// Writes `bytes` into `folder` as `project.json` in place of the one there, through a file the folder's reader passes over, so that no reader sees half of it. -fn put(folder: &Path, bytes: &[u8]) -> Result { - put_file(folder, PROJECT_FILE, PART_FILE, bytes) +fn put(state: &BuildState, folder: &Path, bytes: &[u8]) -> Result { + put_file(state, folder, PROJECT_FILE, PART_FILE, bytes) } /// Writes `bytes` into `folder` as `name` atomically via `part`. -fn put_file(folder: &Path, name: &str, part_name: &str, bytes: &[u8]) -> Result { - let _writing = WRITING.lock().unwrap_or_else(PoisonError::into_inner); +fn put_file( + state: &BuildState, + folder: &Path, + name: &str, + part_name: &str, + bytes: &[u8], +) -> Result { + let _writing = state.writing.lock().unwrap_or_else(PoisonError::into_inner); let failed = |at: &Path, e: std::io::Error| format!("{}: {e}", at.display()); std::fs::create_dir_all(folder).map_err(|e| failed(folder, e))?; let (part, file) = (folder.join(part_name), folder.join(name)); diff --git a/src/state/document/gta6_script/jobs.rs b/src/state/document/gta6_script/jobs.rs index 4b087e01f..8e51a1968 100644 --- a/src/state/document/gta6_script/jobs.rs +++ b/src/state/document/gta6_script/jobs.rs @@ -104,8 +104,9 @@ impl AppState { }; let script = Arc::clone(script); let asked = ask.clone(); + let session = self.gta6.script.clone(); let started = self.start_gta6_job(doc, ask, focus, None, move |progress| { - script.again(&asked, progress) + script.again(&session, &asked, progress) }); if let Err(e) = started { self.show_error_toast(tr!("The script was not decompiled: {e}", e = e)); @@ -131,10 +132,13 @@ impl AppState { let asked = ask.clone(); let building = Arc::new(Building::default()); let stage = Arc::clone(&building); + let session = self.gta6.script.clone(); let work = move |progress: &Progress| { - let built = super::guarded(|| build::build(&archive, &folder, &stage, progress)); + let built = super::guarded(|| { + build::build(&session.build, &archive, &folder, &stage, progress) + }); match built { - Ok(Ok(_)) => script.again(&asked, progress), + Ok(Ok(_)) => script.again(&session, &asked, progress), Ok(Err(e)) | Err(e) => Err(tr!("the project was not built: {e}", e = e)), } }; @@ -298,7 +302,7 @@ impl AppState { }; // The level chosen is the level the next script opens at, once a source at it exists. if script.level != was { - set_level(script.level); + set_level(&self.gta6.script, script.level); } let is_focus = |row: &super::OutlineRow| !row.class && focus.is_some() && row.at == focus; let row = script.outline.iter().position(is_focus); diff --git a/src/state/document/gta6_script/lists.rs b/src/state/document/gta6_script/lists.rs index 824a72f96..cc6dfc446 100644 --- a/src/state/document/gta6_script/lists.rs +++ b/src/state/document/gta6_script/lists.rs @@ -230,16 +230,17 @@ impl Found { } /// What is kept of the project files read. +#[derive(Default)] struct Kept { project: Option<(Stamp, Arc)>, refused: Vec<(Stamp, String)>, } /// The project read last, kept for the next script: a whole install's is hundreds of megabytes of text, read in seconds. -static KEPT: Mutex = Mutex::new(Kept { - project: None, - refused: Vec::new(), -}); +#[derive(Clone, Default)] +pub(super) struct ListsState { + kept: Arc>, +} /// The project of a file as its bytes read. fn read_project(file: &Path) -> Result { @@ -250,9 +251,9 @@ fn read_project(file: &Path) -> Result { /// The project of the first of `folders` that holds a `project.json` that reads; the one read last is not read again. // ⚠ A worker's call, never the UI thread's: the lock is held while a file is read, so that two // scripts opened together read it once. -pub fn project(folders: &[Option<&Path>]) -> Found { +pub(super) fn project(state: &ListsState, folders: &[Option<&Path>]) -> Found { let mut found = Found::default(); - let mut kept = KEPT.lock().unwrap_or_else(PoisonError::into_inner); + let mut kept = state.kept.lock().unwrap_or_else(PoisonError::into_inner); for folder in folders.iter().flatten() { let file = folder.join(PROJECT_FILE); let Ok(meta) = std::fs::metadata(&file) else { diff --git a/src/state/document/gta6_script/mod.rs b/src/state/document/gta6_script/mod.rs index 369ce410f..c3f0cddb3 100644 --- a/src/state/document/gta6_script/mod.rs +++ b/src/state/document/gta6_script/mod.rs @@ -65,30 +65,45 @@ const NOT_A_HEAD: &[&str] = &[ /// What a line that goes on with the head above it starts with past that head's indent. const CONTINUED: &str = " "; -/// The level the next script opens at, which the inspector's choice sets: the load worker sees no panel. -static LEVEL: Mutex = Mutex::new(Level::Source); +/// Session state for GTA VI script decompilation: the chosen level, whether guess labels are read, +/// the last parsed project file, and the lock serialising atomic project writes. +#[derive(Clone)] +pub(crate) struct ScriptSession { + level: Arc>, + labels: Arc, + lists: lists::ListsState, + pub(super) build: build::BuildState, +} + +impl Default for ScriptSession { + fn default() -> Self { + Self { + level: Arc::new(Mutex::new(Level::Source)), + labels: Arc::new(AtomicBool::new(false)), + lists: Default::default(), + build: Default::default(), + } + } +} /// The level a script opens at. -pub fn level() -> Level { - *LEVEL.lock().unwrap_or_else(PoisonError::into_inner) +pub(crate) fn level(script: &ScriptSession) -> Level { + *script.level.lock().unwrap_or_else(PoisonError::into_inner) } /// Have scripts open at `level` from now on. -pub fn set_level(level: Level) { - *LEVEL.lock().unwrap_or_else(PoisonError::into_inner) = level; +pub(crate) fn set_level(script: &ScriptSession, level: Level) { + *script.level.lock().unwrap_or_else(PoisonError::into_inner) = level; } -/// Whether the labels files of the names folder are read, which the inspector's choice sets: off at every start, since a label is a guess. -static LABELS: AtomicBool = AtomicBool::new(false); - /// Whether a script is decompiled with the labels files of the names folder. -pub fn labels_on() -> bool { - LABELS.load(Ordering::Relaxed) +pub(crate) fn labels_on(script: &ScriptSession) -> bool { + script.labels.load(Ordering::Relaxed) } /// Have scripts decompiled with the labels files of the names folder, or without them, from now on. -pub fn set_labels(on: bool) { - LABELS.store(on, Ordering::Relaxed); +pub(crate) fn set_labels(script: &ScriptSession, on: bool) { + script.labels.store(on, Ordering::Relaxed); } /// Where natives lists, names lists and a project for GTA VI scripts are read from, in the configuration directory. @@ -271,9 +286,15 @@ impl Gta6ScriptDocument { } /// The decompile of the same bytes as `ask` asks, on the calling thread: a worker's work. - pub fn again(&self, ask: &Ask, progress: &Progress) -> Result { + pub(crate) fn again( + &self, + script: &ScriptSession, + ask: &Ask, + progress: &Progress, + ) -> Result { let held = (Arc::clone(&self.program), self.stamp.clone()); written( + script, held, &self.bytes, ask, @@ -563,6 +584,7 @@ fn first_ask(program: &Program, level: Level) -> Ask { // ⚠ A project starts functions the program read alone does not show, so the program is read // again whenever the project found is another than the one it was read with. fn written( + script: &ScriptSession, held: (Arc, Option), bytes: &Arc<[u8]>, ask: &Ask, @@ -572,10 +594,10 @@ fn written( let folder = names_dir(); let shipped = or_io::container::rpf::shipped_script_names_dir(); let mut supplied = lists::supplied_over(shipped.as_deref(), folder.as_deref()); - if labels_on() { + if labels_on(script) { lists::labelled(&mut supplied, folder.as_deref()); } - let found = lists::project(&[beside, folder.as_deref()]); + let found = lists::project(&script.lists, &[beside, folder.as_deref()]); let project = found.project(); let stamp = found.stamp().cloned(); let program = match held { @@ -654,11 +676,18 @@ fn read(bytes: &[u8]) -> Result { } /// The document of a program the reader took: its source at `level`, or its bytes under the reason it does not decompile. -fn opened(program: Program, bytes: &[u8], level: Level) -> DocPayload { +fn opened(script: &ScriptSession, program: Program, bytes: &[u8], level: Level) -> DocPayload { let ask = first_ask(&program, level); let held: Arc<[u8]> = Arc::from(bytes); let folder = beside(); - match written((Arc::new(program), None), &held, &ask, folder.as_deref(), None) { + match written( + script, + (Arc::new(program), None), + &held, + &ask, + folder.as_deref(), + None, + ) { Ok(script) => DocPayload::Gta6Script(Arc::new(script)), Err(e) => DocPayload::Hex(HexDocument { bytes: bytes.to_vec(), @@ -673,17 +702,17 @@ fn opened(program: Program, bytes: &[u8], level: Level) -> DocPayload { /// The script `bytes` are, where they start as a deciphered program does and its reader takes them. // ⚠ Eight zero bytes only say the reader is worth asking: a body that starts so and is no // program opens as it did before there was a reader. -pub(crate) fn sniffed(bytes: &[u8]) -> Option { +pub(crate) fn sniffed(script: &ScriptSession, bytes: &[u8]) -> Option { if !bytes.starts_with(&[0u8; 8]) { return None; } let program = read(bytes).ok()?; - Some(opened(program, bytes, level())) + Some(opened(script, program, bytes, level(script))) } /// The script `bytes` are, refused in the reader's own words. -pub(crate) fn open(bytes: &[u8]) -> Result { - Ok(opened(read(bytes)?, bytes, level())) +pub(crate) fn open(script: &ScriptSession, bytes: &[u8]) -> Result { + Ok(opened(script, read(bytes)?, bytes, level(script))) } impl AppState { diff --git a/src/state/document/gta6_script/tests.rs b/src/state/document/gta6_script/tests.rs index f9abe8fe9..f9d4ef238 100644 --- a/src/state/document/gta6_script/tests.rs +++ b/src/state/document/gta6_script/tests.rs @@ -102,12 +102,13 @@ static partial class demo #[test] fn bytes_that_are_no_program_are_no_script() { + let script = ScriptSession::default(); // Eight zero bytes are where a program starts and are not a program. - assert!(sniffed(&[0u8; 64]).is_none()); - assert!(sniffed(b"RSC7\0\0\0\0\0\0\0\0").is_none()); - assert!(sniffed(&[]).is_none()); - assert!(open(&[0u8; 64]).is_err()); - assert!(open(&[]).is_err()); + assert!(sniffed(&script, &[0u8; 64]).is_none()); + assert!(sniffed(&script, b"RSC7\0\0\0\0\0\0\0\0").is_none()); + assert!(sniffed(&script, &[]).is_none()); + assert!(open(&script, &[0u8; 64]).is_err()); + assert!(open(&script, &[]).is_err()); } fn document(source: &str) -> Gta6ScriptDocument { diff --git a/src/state/document/meta/mod.rs b/src/state/document/meta/mod.rs index 17bbb111e..cceb6ddaa 100644 --- a/src/state/document/meta/mod.rs +++ b/src/state/document/meta/mod.rs @@ -82,6 +82,7 @@ pub struct MetaDocument { pub gta6_untyped: Option, /// The elements of a GTA VI data XML its library does not type, counted when its text is read. pub gta6_untyped_elements: usize, + install: crate::state::gta6::install::InstallSession, } /// GTA VI's library where `gta6` and one is installed, else the default. @@ -92,6 +93,13 @@ fn library_for(gta6: bool) -> &'static or_io::meta::SchemaLibrary { impl MetaDocument { pub fn from_bytes(bytes: Vec) -> Self { + Self::from_bytes_with(bytes, Default::default()) + } + + pub(crate) fn from_bytes_with( + bytes: Vec, + install: crate::state::gta6::install::InstallSession, + ) -> Self { use or_io::meta::binary::ContainerLayout; let parse_result = or_io::meta::MetaDocument::parse(meta_schema(), bytes.clone()); let layout = parse_result.as_ref().ok().and_then(|d| d.layout.as_ref()); @@ -101,7 +109,7 @@ impl MetaDocument { } _ => DocumentStrings::default(), }; - Self::from_parse(bytes, parse_result, strings) + Self::from_parse(bytes, parse_result, strings, install) } /// GTA VI data XML `bytes` as `instance` read through GTA VI's library, which lacks `untyped`. @@ -118,7 +126,12 @@ impl MetaDocument { source_format: or_io::meta::SourceFormat::Xml, }; let elements = or_io::meta::instance::parser::member_counts(&parsed.instance).1; - let doc = Self::from_parse(bytes, Ok(parsed), DocumentStrings::default()); + let doc = Self::from_parse( + bytes, + Ok(parsed), + DocumentStrings::default(), + Default::default(), + ); Self { gta6_library: true, gta6_untyped: untyped, @@ -133,7 +146,16 @@ impl MetaDocument { } /// A GTA VI headerless RBM resource, from its virtual and its physical section. + #[cfg(test)] pub fn from_gta_vi_headerless(virtual_section: &[u8], physical: &[u8]) -> Result { + Self::from_gta_vi_headerless_with(virtual_section, physical, Default::default()) + } + + pub(crate) fn from_gta_vi_headerless_with( + virtual_section: &[u8], + physical: &[u8], + install: crate::state::gta6::install::InstallSession, + ) -> Result { // The names of GTA VI's snapshot are installed by the first ask for the schema. meta_schema(); let (instance, layout) = or_io::meta::binary::rbm::gta6::open(virtual_section, physical) @@ -149,6 +171,7 @@ impl MetaDocument { virtual_section.to_vec(), Ok(parsed), DocumentStrings::default(), + install, )) } @@ -156,6 +179,7 @@ impl MetaDocument { bytes: Vec, parse_result: or_io::meta::Result, strings: DocumentStrings, + install: crate::state::gta6::install::InstallSession, ) -> Self { let (parsed, parse_error, source_format, layout) = match parse_result { Ok(parsed_doc) => ( @@ -179,7 +203,8 @@ impl MetaDocument { let text_bytes = match (&parsed, source_format) { (Some(p), fmt) if fmt.is_binary() => or_io::meta::write_meta(&p.instance) .map(|s| { - super::gta6_meta_names::shown_xml(s, layout.as_ref(), &strings).into_bytes() + super::gta6_meta_names::shown_xml(&install, s, layout.as_ref(), &strings) + .into_bytes() }) .unwrap_or_else(|_| bytes.clone()), _ => bytes.clone(), @@ -201,6 +226,7 @@ impl MetaDocument { gta6_library: false, gta6_untyped: None, gta6_untyped_elements: 0, + install, } } @@ -224,6 +250,7 @@ impl MetaDocument { gta6_library: false, gta6_untyped: None, gta6_untyped_elements: 0, + install: Default::default(), } } @@ -309,7 +336,12 @@ impl MetaDocument { .as_ref() .map(|p| or_io::meta::write_meta(&p.instance).unwrap_or_default()) .unwrap_or_default(); - let shown = super::gta6_meta_names::shown_xml(xml, self.layout.as_ref(), &self.strings); + let shown = super::gta6_meta_names::shown_xml( + &self.install, + xml, + self.layout.as_ref(), + &self.strings, + ); shown.into_bytes() }); self.text = TextDocument::decode(&xml); diff --git a/src/state/document/mod.rs b/src/state/document/mod.rs index 37334abd1..71321d2a5 100644 --- a/src/state/document/mod.rs +++ b/src/state/document/mod.rs @@ -86,9 +86,8 @@ mod gta6_meta_strings; pub use gta6_meta_strings::{DocumentStrings, STRING_NAMES_NEED_KEYS}; -pub use gta6_meta_names::{ - hash_name_or_text, hash_text_name, meta_names_from_the_text, meta_text_name, -}; +pub use gta6_meta_names::meta_names_from_the_text; +pub(crate) use gta6_meta_names::{hash_name_or_text, hash_text_name, meta_text_name}; mod rel; diff --git a/src/state/document_io.rs b/src/state/document_io.rs index 1d8fa7c24..88274fbbd 100644 --- a/src/state/document_io.rs +++ b/src/state/document_io.rs @@ -199,16 +199,20 @@ pub(super) fn described_for( } pub(super) fn parse_payload_from_path( + gta6: &super::gta6::session::Gta6Session, path: &std::path::Path, kind: DocumentKind, crypto: std::sync::Arc, ) -> std::result::Result<(DocPayload, Option>), String> { if let Some((archive, offset)) = super::rpf9_scan::scanned_body(path) { - return Ok((super::rpf9_scan::read_body(path, archive, offset)?, None)); + return Ok(( + super::rpf9_scan::read_body(gta6, path, archive, offset)?, + None, + )); } if matches!(kind, DocumentKind::Text) { let data = std::fs::read(path).map_err(|e| format!("Read error: {e}"))?; - return Ok((text_payload(path, data), None)); + return Ok((text_payload_with(gta6, path, data), None)); } // ⚠ Before the whole read: a GTA VI archive can be tens of gigabytes, and is scanned instead, as is the tab of one read again. if matches!(kind, DocumentKind::Rpf | DocumentKind::Rpf9) { @@ -224,12 +228,16 @@ pub(super) fn parse_payload_from_path( } // ⚠ Never read whole: a pack can be gigabytes, and a texture is read only when it is shown. if matches!(kind, DocumentKind::Ttpf) { - let ttpf = super::ttpf_document::TtpfDocument::open(path) - .map_err(|e| format!("Parse error: {e}"))?; + let ttpf = super::ttpf_document::TtpfDocument::open_with( + path, + gta6.ttpf.clone(), + gta6.install.clone(), + ) + .map_err(|e| format!("Parse error: {e}"))?; return Ok((DocPayload::Ttpf(Arc::new(ttpf)), None)); } let data = std::fs::read(path).map_err(|e| format!("Read error: {e}"))?; - let payload = parse_payload(path, kind, &data, crypto)?; + let payload = parse_payload_with(gta6, path, kind, &data, crypto)?; Ok((payload, resource_image_for(kind, &data))) } @@ -260,20 +268,31 @@ pub(super) fn parse_payload( kind: DocumentKind, data: &[u8], crypto: std::sync::Arc, +) -> std::result::Result { + parse_payload_with(&Default::default(), path, kind, data, crypto) +} + +pub(super) fn parse_payload_with( + gta6: &super::gta6::session::Gta6Session, + path: &std::path::Path, + kind: DocumentKind, + data: &[u8], + crypto: std::sync::Arc, ) -> std::result::Result { use or_io::container::rpf::RpfArchive; - if let Some(save) = sniffed_save(data) { + if let Some(save) = sniffed_save(>a6.bodies, data) { return Ok(save); } // A deciphered GTA VI script has no extension, so it arrives as a file no name claims. if matches!(kind, DocumentKind::Hex) { - if let Some(script) = document::gta6_script::sniffed(data) { + if let Some(script) = document::gta6_script::sniffed(>a6.script, data) { return Ok(script); } if or_io::meta::binary::classify(data).is_meta() { - return Ok(DocPayload::Meta(document::MetaDocument::from_bytes( + return Ok(DocPayload::Meta(document::MetaDocument::from_bytes_with( data.to_vec(), + gta6.install.clone(), ))); } } @@ -354,11 +373,12 @@ pub(super) fn parse_payload( .map(DocPayload::Dds) .map_err(|e| format!("Parse error: {e}")), DocumentKind::Text => Ok(text_or_hex(path, data.to_vec())), - DocumentKind::Meta => Ok(DocPayload::Meta(document::MetaDocument::from_bytes( + DocumentKind::Meta => Ok(DocPayload::Meta(document::MetaDocument::from_bytes_with( data.to_vec(), + gta6.install.clone(), ))), DocumentKind::Hex | DocumentKind::Gta6Save if gta6_save::is_save(data) => { - gta6_save::open(data) + gta6_save::open(>a6.bodies, data) } DocumentKind::Hex if is_text(data) => { Ok(DocPayload::Text(document::TextDocument::decode(data))) @@ -376,25 +396,36 @@ pub(super) fn parse_payload( DocumentKind::Gta6AudioData => Err(crate::i18n::tr(READ_ONLY_GTA6_AUDIO_DATA).to_string()), DocumentKind::Gta6Expressions => Err(crate::i18n::tr(EXPRESSIONS_FROM_SCAN).to_string()), DocumentKind::Gta6Save => Err(crate::i18n::tr(GTA6_SAVE_FROM_FILE).to_string()), - DocumentKind::Gta6Script => document::gta6_script::open(data), + DocumentKind::Gta6Script => document::gta6_script::open(>a6.script, data), other => Err(unhandled(other, "reader")), } } /// The GTA VI save `data` start as and read as, under whatever name they came: a save has no /// extension of its own, and one that does not read is left to the reader its name picks. -fn sniffed_save(data: &[u8]) -> Option { - (gta6_save::is_save(data).then(|| gta6_save::open(data).ok())).flatten() +fn sniffed_save(bodies: &super::gta6::bodies::BodiesSession, data: &[u8]) -> Option { + (gta6_save::is_save(data).then(|| gta6_save::open(bodies, data).ok())).flatten() } /// The text `bytes` decode to, or their hex view under the reason they are not text. /// Bytes a text extension names: a metadata document where they read as one, else text or bytes. pub(super) fn text_payload(path: &std::path::Path, data: Vec) -> DocPayload { - if let Some(save) = sniffed_save(&data) { + text_payload_with(&Default::default(), path, data) +} + +pub(super) fn text_payload_with( + gta6: &super::gta6::session::Gta6Session, + path: &std::path::Path, + data: Vec, +) -> DocPayload { + if let Some(save) = sniffed_save(>a6.bodies, &data) { return save; } match DocumentKind::Text.refine_with_bytes(&data) { - DocumentKind::Meta => DocPayload::Meta(document::MetaDocument::from_bytes(data)), + DocumentKind::Meta => DocPayload::Meta(document::MetaDocument::from_bytes_with( + data, + gta6.install.clone(), + )), _ => text_or_hex(path, data), } } diff --git a/src/state/extract_job.rs b/src/state/extract_job.rs index 7a610d808..972d3bd38 100644 --- a/src/state/extract_job.rs +++ b/src/state/extract_job.rs @@ -70,10 +70,7 @@ enum ExtractSource { Disk(PathBuf), Bytes(Arc>), /// A body a scan of the GTA VI archive at `archive` found at `offset`. - Scanned { - archive: PathBuf, - offset: u64, - }, + Scanned(PathBuf, u64, super::gta6::install::InstallSession), /// A GTA VI resource's sections, written as a loose resource. Sections(Arc), /// The body at `offset` of `archive` read again and edited, written as a loose resource. @@ -95,8 +92,13 @@ pub struct ExtractItem { impl ExtractItem { /// The body a scan of the GTA VI archive at `archive` found at `offset`, written as `rel_path`. - pub(super) fn scanned(rel_path: String, archive: PathBuf, offset: u64) -> Self { - let source = ExtractSource::Scanned { archive, offset }; + pub(super) fn scanned( + rel_path: String, + archive: PathBuf, + offset: u64, + install: super::gta6::install::InstallSession, + ) -> Self { + let source = ExtractSource::Scanned(archive, offset, install); Self { rel_path, source } } @@ -157,8 +159,8 @@ impl ExtractItem { match &self.source { ExtractSource::Bytes(bytes) => Ok((**bytes).clone()), ExtractSource::Disk(path) => std::fs::read(path).map_err(|e| e.to_string()), - ExtractSource::Scanned { archive, offset } => { - super::rpf9_scan::extracted_body(archive, *offset) + ExtractSource::Scanned(archive, offset, install) => { + super::rpf9_scan::extracted_body(install, archive, *offset) } ExtractSource::Sections(sections) => { or_io::container::rpf::write_rpf9_resource(sections).map_err(|e| e.to_string()) @@ -536,11 +538,11 @@ pub fn run_extraction( } } // A scanned body its list gave an end is copied as a range, never held whole. - if let (ExtractSource::Scanned { archive, offset }, false) = + if let (ExtractSource::Scanned(archive, offset, install), false) = (&item.source, on_clash == OnClash::Save) { let copy = super::gta6_first_entry::copied; - if let Some(step) = copy(archive, *offset, &target, &item.rel_path, &cancel) { + if let Some(step) = copy(install, archive, *offset, &target, &item.rel_path, &cancel) { return step; } } @@ -932,7 +934,7 @@ impl AppState { .filter_map(|item| match &item.source { ExtractSource::Archive { device, .. } => archive_file(device.archive()), ExtractSource::Disk(path) => Some(path.as_path()), - ExtractSource::Scanned { archive, .. } => Some(archive.as_path()), + ExtractSource::Scanned(archive, ..) => Some(archive.as_path()), ExtractSource::Edited { archive, .. } => Some(archive.as_path()), ExtractSource::Bytes(_) | ExtractSource::Sections(_) => None, ExtractSource::Written(_) => None, @@ -1054,9 +1056,10 @@ impl AppState { self.bg.extract_jobs.active = None; if let Some((doc, at)) = saves.filter(|_| !report.cancelled && report.counts.failed == 0) { // An edit made while it wrote is not in the file, so it stays unsaved. + let physics = self.gta6.physics.clone(); if let Some(doc) = self.document_mut(doc).filter(|d| d.history.at() == at) { doc.mark_saved(); - super::gta6_physics_edit::bound_reshape::saved_over(doc); + super::gta6_physics_edit::bound_reshape::saved_over(&physics, doc); } } // ⚠ Where an extraction's, an Export as…'s, a conversion's and a glTF export's writes all end, so Uses reads the install again once one landed under it. diff --git a/src/state/file_io/mod.rs b/src/state/file_io/mod.rs index 425eeeca1..b85e28883 100644 --- a/src/state/file_io/mod.rs +++ b/src/state/file_io/mod.rs @@ -1,5 +1,5 @@ use super::document_io::{ - atomic_write_with_backup, parse_payload, parse_payload_from_path, read_file_generation, + atomic_write_with_backup, parse_payload_from_path, parse_payload_with, read_file_generation, resource_image_for, serialize_archive_records, }; use super::jobs::{file_name, JobKind, Outcome, RunningJob, Then}; @@ -202,18 +202,18 @@ impl AppState { self.io_queue.load_receiver = Some((path.clone(), rx)); let provider = self.keys.provider(); + let gta6 = self.gta6.clone(); let path_clone = path.clone(); thread::spawn(move || { let _reading = gta6_script::reading(&path_clone); - let result = - parse_payload_from_path(&path_clone, kind, provider).map(|(payload, resource)| { - LoadResult::Success { - path: path_clone.clone(), - payload: validated(&path_clone, payload), - binding: None, - resource, - } - }); + let result = parse_payload_from_path(>a6, &path_clone, kind, provider).map( + |(payload, resource)| LoadResult::Success { + path: path_clone.clone(), + payload: validated(&path_clone, payload), + binding: None, + resource, + }, + ); let msg = match result { Ok(ok) => ok, @@ -328,6 +328,7 @@ impl AppState { return self.wait_for_the_loader((path, kind, data, binding)); } let provider = self.keys.provider(); + let gta6 = self.gta6.clone(); self.loading = LoadingState::Loading; let (tx, rx): (Sender, Receiver) = channel(); self.io_queue.load_receiver = Some((path.clone(), rx)); @@ -335,14 +336,15 @@ impl AppState { let path_clone = path.clone(); thread::spawn(move || { let _reading = gta6_script::reading(&path_clone); - let result = parse_payload(&path_clone, kind, &data, provider).map(|payload| { - LoadResult::Success { - path: path_clone.clone(), - payload: validated(&path_clone, payload), - binding, - resource: resource_image_for(kind, &data), - } - }); + let result = + parse_payload_with(>a6, &path_clone, kind, &data, provider).map(|payload| { + LoadResult::Success { + path: path_clone.clone(), + payload: validated(&path_clone, payload), + binding, + resource: resource_image_for(kind, &data), + } + }); let msg = match result { Ok(ok) => ok, Err(message) => LoadResult::Error { diff --git a/src/state/gta6/anim/gta6_anim_edit/mod.rs b/src/state/gta6/anim/gta6_anim_edit/mod.rs index bc3f21ee3..5423693ca 100644 --- a/src/state/gta6/anim/gta6_anim_edit/mod.rs +++ b/src/state/gta6/anim/gta6_anim_edit/mod.rs @@ -189,8 +189,9 @@ impl AppState { DocPayload::Gta6Anim(r) if wanted(r) => Some(Arc::clone(r)), _ => None, }); - let searched = (resource.external_sets.iter()) - .filter_map(|k| crate::state::gta6_set_finding::found_set(archive, *k)); + let searched = (resource.external_sets.iter()).filter_map(|k| { + crate::state::gta6_set_finding::found_set(&self.gta6.anim, archive, *k) + }); open.chain(searched).find_map(|set| { (set.sets.iter().flat_map(|s| &s.animations)) .find(|a| a.key == key)? diff --git a/src/state/gta6/anim/gta6_anim_play.rs b/src/state/gta6/anim/gta6_anim_play.rs index df46c7ac4..f60b10506 100644 --- a/src/state/gta6/anim/gta6_anim_play.rs +++ b/src/state/gta6/anim/gta6_anim_play.rs @@ -244,7 +244,9 @@ pub(crate) fn external_sets( .collect(); let searched = (resource.external_sets.iter()) .filter(|key| !sets.iter().any(|s| s.key == **key)) - .filter_map(|key| crate::state::gta6_set_finding::found_set(archive?, *key)) + .filter_map(|key| { + crate::state::gta6_set_finding::found_set(&state.gta6.anim, archive?, *key) + }) .collect::>(); sets.extend(searched); sets diff --git a/src/state/gta6/anim/gta6_bone_edit/mod.rs b/src/state/gta6/anim/gta6_bone_edit/mod.rs index 5125ac7ce..749720764 100644 --- a/src/state/gta6/anim/gta6_bone_edit/mod.rs +++ b/src/state/gta6/anim/gta6_bone_edit/mod.rs @@ -11,8 +11,10 @@ use or_io::gta6::headerless::{ bone_name_holds, rebind_under, rename_bones, write_skeleton, Resource, Skeleton, SkeletonOwner, }; +use super::AnimSession; use crate::state::bone_numbers::BoneEdit; use crate::state::document::Document; +use crate::state::gta6::session::Gta6Session; use crate::state::gta6_edit::EditSections; use crate::state::gta6_resource_save::EditedSave; use crate::state::{AppState, Change, DocPayload, DocumentId, Swap}; @@ -25,9 +27,9 @@ enum Whose { } /// `skeleton` swapped with the one held for the scanned body at `path`; `false` where none is. -fn swap_held(path: &Path, whose: Whose, skeleton: &mut Skeleton) -> bool { +fn swap_held(anim: &AnimSession, path: &Path, whose: Whose, skeleton: &mut Skeleton) -> bool { if let Whose::Entry(code) = whose { - return crate::state::gta6_entry_skeletons::swap(path, code, skeleton); + return crate::state::gta6_entry_skeletons::swap(anim, path, code, skeleton); } match crate::state::rpf9_scan::skeletons().get_mut(path) { Some(Ok(held)) => { @@ -42,6 +44,7 @@ fn swap_held(path: &Path, whose: Whose, skeleton: &mut Skeleton) -> bool { // ⚠ The skeleton is not in the payload: the scan's map of skeletons by path is what the viewport, // the Outline and the export read. struct Bones { + anim: AnimSession, path: PathBuf, whose: Whose, other: Skeleton, @@ -49,7 +52,7 @@ struct Bones { impl Swap for Bones { fn swap(&mut self, _: &mut DocPayload) -> bool { - swap_held(&self.path, self.whose, &mut self.other) + swap_held(&self.anim, &self.path, self.whose, &mut self.other) } } @@ -144,10 +147,14 @@ impl AppState { .ok_or_else(|| tr!("This document has no file, so it holds no GTA VI skeleton."))?; let mut after = match whose { Whose::Own => crate::state::rpf9_scan::scanned_skeleton(&path)?, - Whose::Entry(code) => crate::state::gta6_entry_skeletons::of(&path, code).ok_or_else(|| { - tr!("This dictionary entry held no skeleton that read when it opened, so it has no bones to edit.") - .to_string() - })?, + Whose::Entry(code) => { + crate::state::gta6_entry_skeletons::of(&self.gta6.anim, &path, code).ok_or_else( + || { + tr!("This dictionary entry held no skeleton that read when it opened, so it has no bones to edit.") + .to_string() + }, + )? + } }; apply(&mut after, bone, &edit)?; let name = after.bones[bone].name.clone(); @@ -157,7 +164,7 @@ impl AppState { BoneEdit::Scale(_) => (tr!("Scale bone {name}", name = name), "scale"), BoneEdit::Name(_) => (tr!("Rename bone {name}", name = name), "name"), }; - if !swap_held(&path, whose, &mut after) { + if !swap_held(&self.gta6.anim, &path, whose, &mut after) { return Err(tr!("The skeleton this body opened with is no longer held.").to_string()); } let key = match whose { @@ -167,6 +174,7 @@ impl AppState { let change = Change::Part { key: Some(key), parts: vec![Box::new(Bones { + anim: self.gta6.anim.clone(), path, whose, other: after, @@ -179,8 +187,11 @@ impl AppState { /// The GTA VI drawable row's `edited_sections`: the materials' and physics' edits, then the bones /// the document shows, written over the body read again; `None` where it holds no edit. -pub(in crate::state) fn edited_save(document: &Document) -> Option> { - let save = crate::state::gta6_physics_edit::edited_save(document)?; +pub(in crate::state) fn edited_save( + document: &Document, + gta6: &Gta6Session, +) -> Option> { + let save = crate::state::gta6_physics_edit::edited_save(document, gta6)?; let DocPayload::Gta6Drawable(resource) = &document.payload else { return Some(save); }; @@ -196,9 +207,10 @@ pub(in crate::state) fn edited_save(document: &Document) -> Option (crate::state::gta6_entry_skeletons::all(path).into_iter()) - .map(|(code, skeleton)| (Some(code), skeleton)) - .collect(), + Resource::Dictionary(_) => (crate::state::gta6_entry_skeletons::all(>a6.anim, path) + .into_iter()) + .map(|(code, skeleton)| (Some(code), skeleton)) + .collect(), _ => Vec::new(), }; if skeletons.is_empty() { diff --git a/src/state/gta6/anim/gta6_clip_finding.rs b/src/state/gta6/anim/gta6_clip_finding.rs index 47cac2c0d..8d2c4a23a 100644 --- a/src/state/gta6/anim/gta6_clip_finding.rs +++ b/src/state/gta6/anim/gta6_clip_finding.rs @@ -11,6 +11,7 @@ use or_io::container::rpf::{read_rpf9_body, Rpf9BodyKind, Rpf9ZlibRun}; use or_io::gta6::anim::AnimResource; use or_job::{Cancel, Progress}; +use super::AnimSession; use crate::state::gta6_set_finding::FindEnded; use crate::state::jobs::{JobKind, Outcome, RunningJob, Then}; use crate::state::rpf9_scan::{body_path, view_of, Row, View}; @@ -28,16 +29,19 @@ pub(crate) struct ClipAt { pub dictionary: String, } -/// The clips found so far, by clip key, for as long as the app runs. -// ponytail: one map for the whole app, holding only the keys a search looked for. -fn found() -> MutexGuard<'static, BTreeMap> { - static FOUND: Mutex> = Mutex::new(BTreeMap::new()); - FOUND.lock().unwrap_or_else(|p| p.into_inner()) +/// The clips found so far, by clip key, for this session. +#[derive(Clone, Default)] +pub(super) struct ClipsCache(Arc>>); + +impl ClipsCache { + fn lock(&self) -> MutexGuard<'_, BTreeMap> { + self.0.lock().unwrap_or_else(|p| p.into_inner()) + } } /// The clip of key `key` a search found, if one did. -pub(crate) fn found_clip(key: u64) -> Option { - found().get(&key).cloned() +pub(crate) fn found_clip(anim: &AnimSession, key: u64) -> Option { + anim.clips.lock().get(&key).cloned() } /// A search; a new one replaces the one running, and dropping it stops it. @@ -49,7 +53,11 @@ pub(in crate::state) struct ClipFinding { impl ClipFinding { /// Read each archive's bodies of `bodies` until every clip of `wanted` is found, on a worker. - fn start(bodies: Vec<(PathBuf, Vec)>, mut wanted: HashSet) -> Self { + fn start( + clips: ClipsCache, + bodies: Vec<(PathBuf, Vec)>, + mut wanted: HashSet, + ) -> Self { let finding = Self { cancel: Cancel::new(), progress: Progress::new(), @@ -87,7 +95,7 @@ impl ClipFinding { done += 1; for (key, clip) in clips_at(&file, archive, *offset, &wanted) { wanted.remove(&key); - found().insert(key, clip); + clips.lock().insert(key, clip); } } } @@ -186,7 +194,7 @@ impl AppState { .flatten() .collect(); let wanted: HashSet = { - let found = found(); + let found = self.gta6.anim.clips.lock(); (resource.motions.iter()) .flat_map(|m| m.clips.iter().copied()) .filter(|key| !open.contains(key) && !found.contains_key(key)) @@ -220,7 +228,11 @@ impl AppState { if bodies.is_empty() { return Err(tr!("Open the scan of an archive to look for clips in.").to_string()); } - self.gta6_finders.clip_finding = Some(ClipFinding::start(bodies, wanted)); + self.gta6_finders.clip_finding = Some(ClipFinding::start( + self.gta6.anim.clips.clone(), + bodies, + wanted, + )); Ok(()) } diff --git a/src/state/gta6/anim/gta6_entry_skeletons.rs b/src/state/gta6/anim/gta6_entry_skeletons.rs index a3f88a028..4bcad80a8 100644 --- a/src/state/gta6/anim/gta6_entry_skeletons.rs +++ b/src/state/gta6/anim/gta6_entry_skeletons.rs @@ -2,52 +2,68 @@ use std::collections::BTreeMap; use std::path::{Path, PathBuf}; -use std::sync::{Mutex, MutexGuard}; +use std::sync::{Arc, Mutex, MutexGuard}; use or_io::gta6::headerless::{read_dictionary_skeletons, Resource, Skeleton}; +use super::AnimSession; use crate::state::selection::{DictPart, SelectionKey}; use crate::state::{DocPayload, Document}; type Held = BTreeMap>; -// ponytail: one map for the whole app, which no close empties; skeletons are small. -static ENTRIES: Mutex = Mutex::new(BTreeMap::new()); +#[derive(Clone, Default)] +pub(super) struct EntrySkeletonsCache(Arc>); -fn entries() -> MutexGuard<'static, Held> { - ENTRIES - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) +impl EntrySkeletonsCache { + fn lock(&self) -> MutexGuard<'_, Held> { + self.0 + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } } /// Keep the skeletons of the drawable entries of the dictionary at the root of `virtual_section`, /// opened at `path`; one whose skeletons do not read keeps none, and its entries export with no bones. -pub(in crate::state) fn keep(path: &Path, virtual_section: &[u8]) { +pub(in crate::state) fn keep(anim: &AnimSession, path: &Path, virtual_section: &[u8]) { let skeletons = read_dictionary_skeletons(virtual_section).unwrap_or_default(); - entries().insert(path.to_path_buf(), skeletons); + anim.entry_skeletons + .lock() + .insert(path.to_path_buf(), skeletons); } /// The skeleton entry `code` of the dictionary opened at `path` holds. -pub(crate) fn of(path: &Path, code: u32) -> Option { - (entries().get(path)?.iter()) +pub(crate) fn of(anim: &AnimSession, path: &Path, code: u32) -> Option { + (anim.entry_skeletons.lock().get(path)?.iter()) .find(|(c, _)| *c == code) .map(|(_, skeleton)| skeleton.clone()) } /// Hold `skeletons` as the ones the entries of the dictionary opened at `path` hold. #[cfg(test)] -pub(crate) fn hold(path: &Path, skeletons: Vec<(u32, Skeleton)>) { - entries().insert(path.to_path_buf(), skeletons); +pub(crate) fn hold(anim: &AnimSession, path: &Path, skeletons: Vec<(u32, Skeleton)>) { + anim.entry_skeletons + .lock() + .insert(path.to_path_buf(), skeletons); } /// Every entry skeleton held for the dictionary opened at `path`, by code. -pub(in crate::state) fn all(path: &Path) -> Vec<(u32, Skeleton)> { - entries().get(path).cloned().unwrap_or_default() +pub(in crate::state) fn all(anim: &AnimSession, path: &Path) -> Vec<(u32, Skeleton)> { + anim.entry_skeletons + .lock() + .get(path) + .cloned() + .unwrap_or_default() } /// `skeleton` swapped with entry `code`'s of the dictionary at `path`; `false` where none is held. -pub(in crate::state) fn swap(path: &Path, code: u32, skeleton: &mut Skeleton) -> bool { - let mut held = entries(); +pub(in crate::state) fn swap( + anim: &AnimSession, + path: &Path, + code: u32, + skeleton: &mut Skeleton, +) -> bool { + let mut held = anim.entry_skeletons.lock(); let found = (held.get_mut(path).into_iter().flatten()).find(|(c, _)| *c == code); match found { Some((_, kept)) => { @@ -82,13 +98,17 @@ pub(crate) fn entry_bone_of(selection: SelectionKey) -> Option<(u32, usize)> { /// The skeleton `doc` shows for `selection`: its own, the selected dictionary entry's, or for an /// unselected dictionary its first entry's skeleton. -pub(crate) fn shown(doc: &Document, selection: Option) -> Option { +pub(crate) fn shown( + anim: &AnimSession, + doc: &Document, + selection: Option, +) -> Option { let path = doc.path.as_deref()?; match entry_of(doc, selection) { - Some(code) => of(path, code), + Some(code) => of(anim, path, code), None => crate::state::rpf9_scan::scanned_skeleton(path) .ok() - .or_else(|| all(path).into_iter().next().map(|(_, s)| s)), + .or_else(|| all(anim, path).into_iter().next().map(|(_, s)| s)), } } @@ -114,8 +134,10 @@ mod tests { #[test] fn a_swap_exchanges_only_the_entry_named_and_an_absent_one_is_refused() { + let anim = AnimSession::default(); let path = Path::new("entry_skeletons_test/swap.ydd"); hold( + &anim, path, vec![ (0x1111_2222, skeleton("SKEL_ROOT")), @@ -123,14 +145,15 @@ mod tests { ], ); let mut other = skeleton("SKEL_Renamed"); - assert!(swap(path, 0x3333_4444, &mut other)); + assert!(swap(&anim, path, 0x3333_4444, &mut other)); assert_eq!(other.bones[0].name, "SKEL_Pelvis"); - let names: Vec = (all(path).into_iter()) + let names: Vec = (all(&anim, path).into_iter()) .map(|(_, s)| s.bones[0].name.clone()) .collect(); assert_eq!(names, ["SKEL_ROOT", "SKEL_Renamed"]); - assert!(!swap(path, 0x5555_6666, &mut other)); + assert!(!swap(&anim, path, 0x5555_6666, &mut other)); assert!(!swap( + &anim, Path::new("entry_skeletons_test/none.ydd"), 0x1111_2222, &mut other diff --git a/src/state/gta6/anim/gta6_expression_edit.rs b/src/state/gta6/anim/gta6_expression_edit.rs index ef06d7dee..9b4450076 100644 --- a/src/state/gta6/anim/gta6_expression_edit.rs +++ b/src/state/gta6/anim/gta6_expression_edit.rs @@ -18,7 +18,10 @@ use crate::state::{AppState, Change, DocPayload, DocumentId}; /// The expression set row's `edited_sections` once an id is edited: its body read again on the /// worker and the ids written over it. -pub(crate) fn edited_save(document: &Document) -> Option> { +pub(crate) fn edited_save( + document: &Document, + _gta6: &crate::state::gta6::session::Gta6Session, +) -> Option> { if !document.history.can_undo() { return None; } @@ -207,7 +210,9 @@ mod tests { let mut state = AppState::default(); let payload = DocPayload::Gta6Expressions(Arc::new(set())); let doc = state.insert_document(archive.join("0x10.yed"), payload, None, None); - let unedited = state.document(doc).and_then(edited_save); + let unedited = state + .document(doc) + .and_then(|d| edited_save(d, &state.gta6)); assert!( unedited.is_none(), "nothing to write while nothing is edited" @@ -216,7 +221,9 @@ mod tests { assert!(state.edit_gta6_expression_id(doc, ExpressionGroup::Inputs, 1, 0xB2)); assert_eq!(ids(&state, doc), [0xA1, 0xB2]); - let saved = state.document(doc).and_then(edited_save); + let saved = state + .document(doc) + .and_then(|d| edited_save(d, &state.gta6)); let Some(Ok(EditedSave::Body { archive: from, offset, diff --git a/src/state/gta6/anim/gta6_face/mod.rs b/src/state/gta6/anim/gta6_face/mod.rs index 48b2c2a50..967021dd8 100644 --- a/src/state/gta6/anim/gta6_face/mod.rs +++ b/src/state/gta6/anim/gta6_face/mod.rs @@ -3,7 +3,7 @@ use std::collections::BTreeMap; use std::path::{Path, PathBuf}; -use std::sync::{Mutex, MutexGuard}; +use std::sync::{Arc, Mutex, MutexGuard}; use or_io::container::rpf::{Rpf9Role, Rpf9Signature}; use or_io::gta6::anim::{ @@ -14,6 +14,7 @@ use or_io::gta6::headerless::{ read_dictionary_skeletons, Drawable, Entry, Palette, Resource, Skeleton, }; +use super::AnimSession; use crate::state::{AppState, DocPayload, DocumentId}; /// The first bone of every face skeleton. @@ -21,13 +22,16 @@ const FACIAL_ROOT: u32 = name_hash32(b"FACIAL_C_FacialRoot"); /// How far a face skeleton's bind rotation may be from unit length. const UNIT_SLACK: f32 = 2e-3; -/// The face skeletons of each dictionary opened from a scan, by entry code. -// ponytail: one map for the whole app, which no close empties; a face skeleton is a few kilobytes. -static FACES: Mutex>> = Mutex::new(BTreeMap::new()); -/// Each expression set opened from a scan, by the path it opened under. -static EXPRESSIONS: Mutex> = Mutex::new(BTreeMap::new()); +type FaceSkeletons = BTreeMap>; -fn lock(map: &'static Mutex) -> MutexGuard<'static, T> { +/// Per-session face skeletons and expression sets learned from scanned bodies. +#[derive(Clone, Default)] +pub(super) struct FaceCache { + faces: Arc>, + expressions: Arc>>, +} + +fn lock(map: &Mutex) -> MutexGuard<'_, T> { map.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) } @@ -43,6 +47,7 @@ pub(in crate::state) enum Learned { /// Keep the face skeletons or the expression set of the body of `signature` opened at `path`. pub(in crate::state) fn learn( + anim: &AnimSession, path: &Path, signature: Rpf9Signature, virtual_section: &[u8], @@ -50,7 +55,7 @@ pub(in crate::state) fn learn( if signature.to_string() == EXPRESSIONS_SIGNATURE { let learned = match read_expressions(virtual_section) { Ok(set) => { - lock(&EXPRESSIONS).insert(path.to_path_buf(), set.clone()); + lock(&anim.face.expressions).insert(path.to_path_buf(), set.clone()); Learned::Expressions(Box::new(set)) } Err(e) => { @@ -72,7 +77,7 @@ pub(in crate::state) fn learn( _ => None, }; if !faces.is_empty() { - lock(&FACES).insert(path.to_path_buf(), faces); + lock(&anim.face.faces).insert(path.to_path_buf(), faces); } lone } @@ -88,10 +93,13 @@ pub(crate) fn is_face(skeleton: &Skeleton) -> bool { } /// An expression set's key and its tracks, as its body opens. -pub(crate) fn facts(set: &Expressions) -> String { +pub(crate) fn facts( + install: &crate::state::gta6::install::InstallSession, + set: &Expressions, +) -> String { let mut lines = vec![tr!( "A GTA VI expression set of key {key}.", - key = crate::state::gta6_names::said32(set.key) + key = crate::state::gta6_names::said32(install, set.key) )]; lines.push(tr_n!( "It reads {count} track: the facial controls, or bones, a clip carries.", @@ -113,12 +121,12 @@ pub(crate) fn facts(set: &Expressions) -> String { facial = set.facial_outputs.tracks.len() )); lines.push(tr!("It holds no program, so how what it reads becomes what it drives is not known. Pick it under Expression set where a clip plays in the Animation workspace to see the controls of the clip it reads.").to_string()); - lines.extend(tables(set)); + lines.extend(tables(install, set)); lines.join("\n") } /// The tracks a set reads and those it writes, each group under its name, a line a track. -fn tables(set: &Expressions) -> Vec { +fn tables(install: &crate::state::gta6::install::InstallSession, set: &Expressions) -> Vec { let mut lines = Vec::new(); for reads in [true, false] { let slots: usize = (ExpressionGroup::ALL.iter()) @@ -150,7 +158,7 @@ fn tables(set: &Expressions) -> Vec { lines.push(format!("{} ({})", group_label(group), tracks.tracks.len())); for (k, (id, word)) in tracks.tracks.iter().enumerate() { let detail = track_detail(set, group, k); - let id = crate::state::gta6_names::said32(*id); + let id = crate::state::gta6_names::said32(install, *id); lines.push(format!(" {id} {}: {detail}", track_label(*word))); } } @@ -209,13 +217,13 @@ pub(crate) fn track_detail(set: &Expressions, group: ExpressionGroup, track: usi } /// The expression set opened at `path`, if one did. -pub(crate) fn expression_set(path: &Path) -> Option { - lock(&EXPRESSIONS).get(path).cloned() +pub(crate) fn expression_set(anim: &AnimSession, path: &Path) -> Option { + lock(&anim.face.expressions).get(path).cloned() } /// Whether an expression set opened at `path`. -pub(crate) fn is_expression_set(path: &Path) -> bool { - lock(&EXPRESSIONS).contains_key(path) +pub(crate) fn is_expression_set(anim: &AnimSession, path: &Path) -> bool { + lock(&anim.face.expressions).contains_key(path) } /// The face skeleton the head named `head` is posed by, else the entry names looked for. @@ -261,7 +269,7 @@ pub(crate) fn palette_bones(drawable: &Drawable) -> Vec { /// The face skeleton of an open dictionary's entry of code `code`, read whole. fn open_face(state: &AppState, code: u32) -> Option { - let faces = lock(&FACES); + let faces = lock(&state.gta6.anim.face.faces); state.documents.iter().find_map(|d| { let DocPayload::Gta6Drawable(resource) = &d.payload else { return None; @@ -297,8 +305,9 @@ pub(crate) fn model_skeleton( // A dictionary's drawable is posed by the skeleton the entry selected holds. Resource::Dictionary(_) => { let selected = state.selection.selected(doc); - let entry = (state.document(doc)) - .and_then(|d| crate::state::gta6_entry_skeletons::shown(d, selected)); + let entry = (state.document(doc)).and_then(|d| { + crate::state::gta6_entry_skeletons::shown(&state.gta6.anim, d, selected) + }); return entry.ok_or_else(|| { tr!("Select a drawable of this dictionary that holds a skeleton, then pick the model again.") .to_string() @@ -321,7 +330,7 @@ pub(crate) fn model_skeleton( return why; } let bones: Vec = (bones.iter()) - .map(|h| crate::state::gta6_names::said32(*h)) + .map(|h| crate::state::gta6_names::said32(&state.gta6.install, *h)) .collect(); tr!( "No open dictionary holds {entries}, the face skeleton this head's name names, and the head has no skeleton of its own, so no skeleton holds the bones its palette names: {bones}. Open that dictionary from a scan of its archive, then pick the head again.", diff --git a/src/state/gta6/anim/gta6_face/tests.rs b/src/state/gta6/anim/gta6_face/tests.rs index 10afa823f..b27fc8a55 100644 --- a/src/state/gta6/anim/gta6_face/tests.rs +++ b/src/state/gta6/anim/gta6_face/tests.rs @@ -45,24 +45,25 @@ fn expression_section() -> Vec { #[test] fn an_expression_set_is_learned_as_its_set_and_a_body_the_reader_refuses_as_lines() { let _serial = crate::ui::theme::serial(); + let anim = AnimSession::default(); let mut section = expression_section(); let len = section.len() as u64; let signature = Rpf9Signature::of(§ion, len).expect("a head"); assert_eq!(signature.to_string(), EXPRESSIONS_SIGNATURE); let path = Path::new("learned/0x10.rsc"); - let Some(Learned::Expressions(set)) = learn(path, signature, §ion) else { + let Some(Learned::Expressions(set)) = learn(&anim, path, signature, §ion) else { panic!("the set is not learned as one"); }; let set = *set; assert_eq!(Some(set.clone()), read_expressions(§ion).ok()); - assert_eq!(expression_set(path), Some(set)); + assert_eq!(expression_set(&anim, path), Some(set)); // The key stated a second time differs, so the reader refuses the body and it opens as lines. section[0x14] ^= 1; let refused = Path::new("refused/0x10.rsc"); - let Some(Learned::Facts(text)) = learn(refused, signature, §ion) else { + let Some(Learned::Facts(text)) = learn(&anim, refused, signature, §ion) else { panic!("a refused set is not its lines"); }; assert!(text.contains("does not read this body"), "{text}"); - assert!(!is_expression_set(refused)); + assert!(!is_expression_set(&anim, refused)); } diff --git a/src/state/gta6/anim/gta6_set_finding/mod.rs b/src/state/gta6/anim/gta6_set_finding/mod.rs index b17e2279f..70de635cc 100644 --- a/src/state/gta6/anim/gta6_set_finding/mod.rs +++ b/src/state/gta6/anim/gta6_set_finding/mod.rs @@ -11,6 +11,7 @@ use or_io::container::rpf::{read_rpf9_body, Rpf9BodyKind, Rpf9ZlibRun}; use or_io::gta6::anim::{AnimResource, RootKind}; use or_job::{Cancel, Progress}; +use super::AnimSession; use crate::state::jobs::{JobKind, Outcome, RunningJob, Then}; use crate::state::rpf9_scan::{scanned_body, view_of, Row, View}; use crate::state::{AppState, DocPayload, DocumentId}; @@ -18,17 +19,21 @@ use crate::state::{AppState, DocPayload, DocumentId}; /// The bytes a body is read to: more than any lone set was measured to hold. const BODY_LIMIT: u64 = 256 << 20; -/// The sets found so far, by the archive searched and their root key, for as long as the app runs. +/// The sets found so far, by the archive searched and their root key, for this session. type Found = BTreeMap>>; -fn found() -> MutexGuard<'static, Found> { - static FOUND: Mutex = Mutex::new(BTreeMap::new()); - FOUND.lock().unwrap_or_else(|p| p.into_inner()) +#[derive(Clone, Default)] +pub(super) struct SetsCache(Arc>); + +impl SetsCache { + fn lock(&self) -> MutexGuard<'_, Found> { + self.0.lock().unwrap_or_else(|p| p.into_inner()) + } } /// The lone animation set of root key `key` a search of `archive` found, if one did. -pub(crate) fn found_set(archive: &Path, key: u32) -> Option> { - found().get(archive)?.get(&key).cloned() +pub(crate) fn found_set(anim: &AnimSession, archive: &Path, key: u32) -> Option> { + anim.sets.lock().get(archive)?.get(&key).cloned() } /// How a search ended. @@ -48,7 +53,12 @@ pub(in crate::state) struct SetFinding { impl SetFinding { /// Read the bodies at `offsets` of `archive` until each set of `wanted` is found, on a worker. - fn start(archive: PathBuf, offsets: Vec, mut wanted: HashSet) -> Self { + fn start( + sets: SetsCache, + archive: PathBuf, + offsets: Vec, + mut wanted: HashSet, + ) -> Self { let finding = Self { cancel: Cancel::new(), progress: Progress::new(), @@ -77,7 +87,7 @@ impl SetFinding { progress.reached(done as u64, offsets.len() as u64); if let Some(set) = set_at(&file, *offset, &wanted) { wanted.remove(&set.key); - (found().entry(archive.clone()).or_default()) + (sets.lock().entry(archive.clone()).or_default()) .insert(set.key, Arc::new(set)); } } @@ -155,7 +165,7 @@ impl AppState { .map(|(archive, _)| archive.to_path_buf()) .ok_or_else(|| tr!("This animation is no body of a scanned archive, so no scan holds the sets it names.").to_string())?; let wanted: HashSet = (resource.external_sets.iter().copied()) - .filter(|key| found_set(&archive, *key).is_none()) + .filter(|key| found_set(&self.gta6.anim, &archive, *key).is_none()) .collect(); if wanted.is_empty() { return Ok(()); @@ -182,9 +192,12 @@ impl AppState { archive = archive.display() )); } - self.gta6_finders - .set_finding - .push(SetFinding::start(archive, offsets, wanted)); + self.gta6_finders.set_finding.push(SetFinding::start( + self.gta6.anim.sets.clone(), + archive, + offsets, + wanted, + )); Ok(()) } diff --git a/src/state/gta6/anim/gta6_set_finding/tests.rs b/src/state/gta6/anim/gta6_set_finding/tests.rs index a8d6e205b..303aec86b 100644 --- a/src/state/gta6/anim/gta6_set_finding/tests.rs +++ b/src/state/gta6/anim/gta6_set_finding/tests.rs @@ -70,7 +70,7 @@ fn a_set_another_body_stores_is_found_among_the_animation_bodies_of_the_scan() { None, None, ); - assert!(found_set(&archive, wanted[0]).is_none()); + assert!(found_set(&state.gta6.anim, &archive, wanted[0]).is_none()); state.find_gta6_sets(doc).expect("a scan to look in"); assert_eq!( @@ -79,13 +79,13 @@ fn a_set_another_body_stores_is_found_among_the_animation_bodies_of_the_scan() { "the search is a job" ); finished(&mut state); - let set = found_set(&archive, wanted[0]).expect("the set the scan holds"); + let set = found_set(&state.gta6.anim, &archive, wanted[0]).expect("the set the scan holds"); assert_eq!(set.name, "sf_test-2"); assert!( - found_set(&archive, key("sf_test-1")).is_none(), + found_set(&state.gta6.anim, &archive, key("sf_test-1")).is_none(), "a set nothing names is not kept" ); - assert!(found_set(&archive, wanted[1]).is_none()); + assert!(found_set(&state.gta6.anim, &archive, wanted[1]).is_none()); let said = state .jobs .ended() @@ -98,7 +98,7 @@ fn a_set_another_body_stores_is_found_among_the_animation_bodies_of_the_scan() { std::fs::create_dir(dir.path().join("b")).expect("a sub folder"); let other = written(&dir.path().join("b"), &bytes); scanned(&mut state, other.clone()); - assert!(found_set(&other, wanted[0]).is_none()); + assert!(found_set(&state.gta6.anim, &other, wanted[0]).is_none()); let there = state.insert_document( body_path(&other, 0x10, View::Animation), DocPayload::Gta6Anim(Arc::new(naming(&wanted[..1]))), @@ -112,7 +112,7 @@ fn a_set_another_body_stores_is_found_among_the_animation_bodies_of_the_scan() { "the other archive is searched" ); finished(&mut state); - assert!(found_set(&other, wanted[0]).is_some()); + assert!(found_set(&state.gta6.anim, &other, wanted[0]).is_some()); // A dictionary that is no scanned body has no scan to look in. let elsewhere = state.insert_document( diff --git a/src/state/gta6/anim/mod.rs b/src/state/gta6/anim/mod.rs index 4e4784559..f5efd026d 100644 --- a/src/state/gta6/anim/mod.rs +++ b/src/state/gta6/anim/mod.rs @@ -10,3 +10,12 @@ pub(crate) mod gta6_face; pub(crate) mod gta6_filter_edit; pub(crate) mod gta6_filter_entries; pub(crate) mod gta6_set_finding; + +/// Per-instance animation caches owned by [`crate::state::gta6::session::Gta6Session`]. +#[derive(Clone, Default)] +pub(crate) struct AnimSession { + clips: gta6_clip_finding::ClipsCache, + entry_skeletons: gta6_entry_skeletons::EntrySkeletonsCache, + sets: gta6_set_finding::SetsCache, + face: gta6_face::FaceCache, +} diff --git a/src/state/gta6/audio/gta6_audio_links/mod.rs b/src/state/gta6/audio/gta6_audio_links/mod.rs index 7754029ab..027b84324 100644 --- a/src/state/gta6/audio/gta6_audio_links/mod.rs +++ b/src/state/gta6/audio/gta6_audio_links/mod.rs @@ -13,6 +13,7 @@ use or_io::gta6::audio_data::{AudioData, AudioDataKind}; use or_io::gta6::audio_links::{config_names, BankLink, WaveIndex}; use or_job::{Cancel, Progress}; +use super::AudioSession; use crate::state::jobs::{JobKind, RunningJob}; use crate::state::rpf9_scan::{row_at_offset, scanned_body, Row, Rpf9ScanDocument}; use crate::state::{AppState, DocPayload, DocumentId}; @@ -24,11 +25,19 @@ const POOL_TRIES: usize = 4; /// The bytes a candidate name pool is read to. const POOL_LIMIT: u64 = 16 << 20; -/// Audio configuration names a name pool gave, by key, for every audio view while the app runs. -// ponytail: one map for the whole app, which no close empties; a name is checked against its key. -pub(crate) fn pool_names() -> MutexGuard<'static, BTreeMap> { - static NAMES: Mutex> = Mutex::new(BTreeMap::new()); - NAMES.lock().unwrap_or_else(|p| p.into_inner()) +/// Audio configuration names a name pool gave, by key, for this session. +#[derive(Clone, Default)] +pub(super) struct PoolNamesCache(Arc>>); + +impl PoolNamesCache { + fn lock(&self) -> MutexGuard<'_, BTreeMap> { + self.0.lock().unwrap_or_else(|p| p.into_inner()) + } +} + +/// Audio configuration names a name pool gave, by key, for every audio view of this session. +pub(crate) fn pool_names(audio: &AudioSession) -> MutexGuard<'_, BTreeMap> { + audio.pool_names.lock() } /// What a body's links are looked for among. @@ -84,7 +93,7 @@ impl std::fmt::Debug for AudioLinking { } impl AudioLinking { - fn start(archive: PathBuf, wanted: Wanted) -> Self { + fn start(names: PoolNamesCache, archive: PathBuf, wanted: Wanted) -> Self { let linking = Self { archive, cancel: Cancel::new(), @@ -108,7 +117,7 @@ impl AudioLinking { waves(&file, &containers, &fields, &cancel, &progress) } Wanted::Pool { candidates, data } => { - pool(&file, &data, &candidates, &cancel, &progress) + pool(&names, &file, &data, &candidates, &cancel, &progress) } }, } @@ -214,6 +223,7 @@ pub(in crate::state) fn stream_words( } fn pool( + pool_cache: &PoolNamesCache, file: &File, data: &AudioData, candidates: &[u64], @@ -230,7 +240,7 @@ fn pool( }; if let Ok(names) = config_names(data, &bytes) { let count = names.len(); - pool_names().extend(names); + pool_cache.lock().extend(names); return Linked::Names { pool: *offset, count, @@ -307,7 +317,11 @@ impl AppState { }, _ => return Ok(()), }; - let linking = Arc::new(AudioLinking::start(archive, wanted)); + let linking = Arc::new(AudioLinking::start( + self.gta6.audio.pool_names.clone(), + archive, + wanted, + )); if let Some(DocPayload::Gta6AudioData(audio)) = self.document_mut(doc).map(|d| &mut d.payload) { diff --git a/src/state/gta6/audio/gta6_audio_links/tests.rs b/src/state/gta6/audio/gta6_audio_links/tests.rs index 53c476318..fce89ccfe 100644 --- a/src/state/gta6/audio/gta6_audio_links/tests.rs +++ b/src/state/gta6/audio/gta6_audio_links/tests.rs @@ -161,6 +161,12 @@ fn what_gta_vi_audio_game_data_links_to_is_found_in_its_scan_as_a_job_and_opens( "the name pool after the body" ); }); - assert_eq!(pool_names().get(&one).map(String::as_str), Some("Cfg_One")); - assert_eq!(pool_names().get(&two).map(String::as_str), Some("cfg_two")); + assert_eq!( + pool_names(&state.gta6.audio).get(&one).map(String::as_str), + Some("Cfg_One") + ); + assert_eq!( + pool_names(&state.gta6.audio).get(&two).map(String::as_str), + Some("cfg_two") + ); } diff --git a/src/state/gta6/audio/gta6_dialogue/mod.rs b/src/state/gta6/audio/gta6_dialogue/mod.rs index 29e030def..712c53692 100644 --- a/src/state/gta6/audio/gta6_dialogue/mod.rs +++ b/src/state/gta6/audio/gta6_dialogue/mod.rs @@ -7,7 +7,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::fs::File; use std::path::{Path, PathBuf}; -use std::sync::{Arc, LazyLock, Mutex, MutexGuard}; +use std::sync::{Arc, Mutex, MutexGuard}; use or_io::container::rpf::{read_rpf9_body, Rpf9BodyKind, Rpf9Content, Rpf9ScanFind, Rpf9ZlibRun}; use or_io::gta6::audio_data::{AudioData, AudioDataKind}; @@ -17,6 +17,8 @@ use or_io::gta6::text::TextTable; use or_io::gta6::text_language::{registered, LanguageArchives, Scanned}; use or_job::{Cancel, Progress}; +use super::AudioSession; +use crate::state::gta6::session::Gta6Session; use crate::state::jobs::{JobKind, RunningJob}; use crate::state::rpf9_scan::{body_path, Row, View}; use crate::state::{AppState, DocPayload}; @@ -75,11 +77,25 @@ pub(crate) struct Lines { changes: u64, } -// ponytail: one set of lines for the whole app, which no close empties, and the containers of -// one index replace those of the one before. A set for each install would lift both. -pub(crate) fn lines() -> MutexGuard<'static, Lines> { - static LINES: LazyLock> = LazyLock::new(Mutex::default); - LINES.lock().unwrap_or_else(|p| p.into_inner()) +type RadioResults = BTreeMap>>; + +/// Per-session dialogue, radio and RBF0 strict-note caches. +#[derive(Clone, Default)] +pub(super) struct DialogueCache { + lines: Arc>, + notes: Arc>>, + found: Arc>>, + radios: Arc>, + asked: Arc>>, + indexing: Arc>>, +} + +pub(crate) fn lines(audio: &AudioSession) -> MutexGuard<'_, Lines> { + audio + .dialogue + .lines + .lock() + .unwrap_or_else(|p| p.into_inner()) } /// A language archive's place among its file's, as a table with no registered name is told. @@ -226,24 +242,32 @@ impl Lines { } /// Why the strict tree of each RBF0 body opened does not read, by the body's path. -fn notes() -> MutexGuard<'static, BTreeMap> { - static NOTES: Mutex> = Mutex::new(BTreeMap::new()); - NOTES.lock().unwrap_or_else(|p| p.into_inner()) +fn notes(audio: &AudioSession) -> MutexGuard<'_, BTreeMap> { + audio + .dialogue + .notes + .lock() + .unwrap_or_else(|p| p.into_inner()) } /// What opening the metadata body `find` at `path` adds. An RBF0 body is read as its strict /// element tree, and where that fails the body still opens as the lenient reader's tree, under /// a note; a PSO body's dialogue lines are kept. -pub(in crate::state) fn opened(path: &Path, find: &Rpf9ScanFind, bytes: &[u8]) { +pub(in crate::state) fn opened( + audio: &AudioSession, + path: &Path, + find: &Rpf9ScanFind, + bytes: &[u8], +) { let Rpf9BodyKind::Zlib(run) = find.kind else { return; }; if run.content != Rpf9Content::Rbf { - return note_body(bytes); + return note_body(audio, bytes); } match or_io::gta6::ui_tree::read(bytes) { - Ok(_) => notes().remove(path), - Err(e) => notes().insert( + Ok(_) => notes(audio).remove(path), + Err(e) => notes(audio).insert( path.to_path_buf(), tr!( "The strict RBF0 reader does not read this body ({e}), so the tree shown is the lenient reader's alone", @@ -255,13 +279,13 @@ pub(in crate::state) fn opened(path: &Path, find: &Rpf9ScanFind, bytes: &[u8]) { /// Why the tree of the RBF0 body at `path` is the lenient reader's alone; `None` where the strict /// reader reads it too. -pub(crate) fn strict_note(path: &Path) -> Option { - notes().get(path).cloned() +pub(crate) fn strict_note(audio: &AudioSession, path: &Path) -> Option { + notes(audio).get(path).cloned() } /// Keeps the dialogue lines `body` states. -fn note_body(body: &[u8]) { - let mut lines = lines(); +fn note_body(audio: &AudioSession, body: &[u8]) { + let mut lines = lines(audio); if lines.dialogue.add(body) > 0 { lines.refresh(); } @@ -269,8 +293,8 @@ fn note_body(body: &[u8]) { /// Keeps the text `table` holds of each line found so far and of each key a view asked for, /// where none is kept yet. -pub(in crate::state) fn note_table(table: &TextTable) { - let mut lines = lines(); +pub(in crate::state) fn note_table(audio: &AudioSession, table: &TextTable) { + let mut lines = lines(audio); let keys = lines.keys(); let kept = lines.texts.entry(OPENED.to_string()).or_default(); for (key, text) in subtitles_in(table, &keys) { @@ -280,15 +304,15 @@ pub(in crate::state) fn note_table(table: &TextTable) { } /// The audio stream's name and the label of the line whose label hashes to `key`. -pub(crate) fn line_of(key: u32) -> Option<(String, String)> { - let lines = lines(); +pub(crate) fn line_of(audio: &AudioSession, key: u32) -> Option<(String, String)> { + let lines = lines(audio); let line = lines.by_label.get(&key)?; Some((line.wave(), line.label.clone())) } /// The comments an exported audio stream `stream` carries: none unless it speaks a line found. -pub(crate) fn comments(stream: u32) -> Vec<(String, String)> { - let lines = lines(); +pub(crate) fn comments(audio: &AudioSession, stream: u32) -> Vec<(String, String)> { + let lines = lines(audio); let Some(hash) = lines.by_stream.get(&(stream & STREAM_ID)) else { return Vec::new(); }; @@ -301,7 +325,6 @@ pub(crate) fn comments(stream: u32) -> Vec<(String, String)> { /// whole archive lists it in a language archive. // The archives are found again only when the scan's list has grown. pub(crate) fn table_language(state: &AppState, path: &Path) -> Option { - static FOUND: Mutex> = Mutex::new(BTreeMap::new()); let archive = path.parent()?; let stem = path.file_stem()?.to_str()?; let at = u64::from_str_radix(stem.strip_prefix("0x")?, 16).ok()?; @@ -310,7 +333,13 @@ pub(crate) fn table_language(state: &AppState, path: &Path) -> Option { _ => None, })?; let found = scan.found(); - let mut kept = FOUND.lock().unwrap_or_else(|p| p.into_inner()); + let mut kept = state + .gta6 + .audio + .dialogue + .found + .lock() + .unwrap_or_else(|p| p.into_inner()); let known = kept.entry(archive.to_path_buf()).or_default(); if known.0 != found.rows.len() { let bodies = found.rows.iter().filter_map(|row| match row { @@ -320,7 +349,11 @@ pub(crate) fn table_language(state: &AppState, path: &Path) -> Option { *known = (found.rows.len(), LanguageArchives::of(bodies)); } let ordinal = known.1.ordinal(at)?; - Some(language_of(&lines().registered, ordinal, known.1.len())) + Some(language_of( + &lines(&state.gta6.audio).registered, + ordinal, + known.1.len(), + )) } /// What a music body states of the radio: its stations and its tracks' texts. @@ -331,11 +364,17 @@ pub(crate) struct Radio { /// The radio of the music body `data` opened at `path`, read once; its stations' keys join the /// keys whose texts are kept, since a station's key names it. -// ponytail: kept by path for the whole app, which no close empties; a body is read-only. -pub(crate) fn radio_of(path: &Path, data: &AudioData) -> Arc> { - static RADIOS: Mutex>>> = - Mutex::new(BTreeMap::new()); - let mut radios = RADIOS.lock().unwrap_or_else(|p| p.into_inner()); +pub(crate) fn radio_of( + gta6: &Gta6Session, + path: &Path, + data: &AudioData, +) -> Arc> { + let mut radios = gta6 + .audio + .dialogue + .radios + .lock() + .unwrap_or_else(|p| p.into_inner()); if let Some(radio) = radios.get(path) { return Arc::clone(radio); } @@ -347,11 +386,11 @@ pub(crate) fn radio_of(path: &Path, data: &AudioData) -> Arc Arc MutexGuard<'static, Option<(PathBuf, u32)>> { - static ASKED: Mutex> = Mutex::new(None); - ASKED.lock().unwrap_or_else(|p| p.into_inner()) +fn asked(audio: &AudioSession) -> MutexGuard<'_, Option<(PathBuf, u32)>> { + audio + .dialogue + .asked + .lock() + .unwrap_or_else(|p| p.into_inner()) } /// The stream of the audio container opened at `path` that a view asked to hear, once: its /// place among `rows`, where a row or one of its channels has the stream's id. -pub(crate) fn play_asked(path: &Path, rows: &[crate::audio::AwcStreamRow]) -> Option { - let mut asked = asked(); +pub(crate) fn play_asked( + audio: &AudioSession, + path: &Path, + rows: &[crate::audio::AwcStreamRow], +) -> Option { + let mut asked = asked(audio); let stream = match asked.as_ref() { Some((container, stream)) if container == path => *stream, _ => return None, @@ -449,19 +495,22 @@ struct Indexing { progress: Progress, } -fn indexing() -> MutexGuard<'static, Option> { - static INDEXING: Mutex> = Mutex::new(None); - INDEXING.lock().unwrap_or_else(|p| p.into_inner()) +fn indexing(audio: &AudioSession) -> MutexGuard<'_, Option> { + audio + .dialogue + .indexing + .lock() + .unwrap_or_else(|p| p.into_inner()) } /// Whether an index is running. -pub(crate) fn running() -> bool { - indexing().is_some() +pub(crate) fn running(audio: &AudioSession) -> bool { + indexing(audio).is_some() } /// The index still running, as the job list draws it. -pub(in crate::state) fn job() -> Option { - let indexing = indexing(); +pub(in crate::state) fn job(audio: &AudioSession) -> Option { + let indexing = indexing(audio); let run = indexing.as_ref()?; Some(RunningJob { kind: JobKind::AudioLinks, @@ -474,8 +523,8 @@ pub(in crate::state) fn job() -> Option { } /// Ask the index to stop. -pub(in crate::state) fn stop() { - if let Some(run) = indexing().as_ref() { +pub(in crate::state) fn stop(audio: &AudioSession) { + if let Some(run) = indexing(audio).as_ref() { run.cancel.set(); } } @@ -505,11 +554,13 @@ impl Steps<'_> { /// the track ids the radio's streams state, the texts of `language` of the lines and of the keys /// asked for, and the stations' names. Says what it kept. fn index( + gta6: &Gta6Session, archives: &[Archive], language: Option, cancel: &Cancel, progress: &Progress, ) -> Result { + let audio = >a6.audio; let mut steps = Steps { done: 0, total: archives.iter().map(|a| a.bodies() as u64).sum(), @@ -518,7 +569,7 @@ fn index( }; let open = |a: &Archive| File::open(&a.path).map_err(|e| format!("{}: {e}", a.path.display())); - if lines().registered.is_empty() { + if lines(audio).registered.is_empty() { 'archives: for archive in archives { let file = open(archive)?; for &at in &archive.change_sets { @@ -528,7 +579,7 @@ fn index( }; let names = registered(&String::from_utf8_lossy(&bytes)); if !names.is_empty() { - lines().registered = names; + lines(audio).registered = names; break 'archives; } } @@ -541,7 +592,7 @@ fn index( for &at in &archive.conversations { steps.step()?; if let Ok((_, bytes)) = read_rpf9_body(&file, at, BODY_LIMIT) { - bodies += usize::from(lines().dialogue.add(&bytes) > 0); + bodies += usize::from(lines(audio).dialogue.add(&bytes) > 0); } } for &at in &archive.audio_data { @@ -556,7 +607,7 @@ fn index( } let read = AudioData::read(&bytes).map_err(|e| e.to_string()); match read.and_then(|d| audio_radio::streamed_sounds(&d).map_err(|e| e.to_string())) { - Ok((sounds, _)) => lines().sounds.extend(sounds), + Ok((sounds, _)) => lines(audio).sounds.extend(sounds), Err(e) => tracing::warn!(path = %archive.path.display(), at, "{e}"), } } @@ -582,7 +633,7 @@ fn index( } // A line's number is settled by the streams that exist before its stream is looked for. let sounds: BTreeSet = { - let mut lines = lines(); + let mut lines = lines(audio); lines.dialogue.settle(|id| held.contains_key(&id)); lines.refresh(); let streams = lines.sounds.values().flat_map(|s| s.streams()); @@ -605,7 +656,7 @@ fn index( } } { - let mut lines = lines(); + let mut lines = lines(audio); let keys = (track_ids.values().flatten()) .flat_map(|id| <[u32; 2]>::from(audio_radio::track_text_keys(*id))); lines.wanted.extend(keys); @@ -613,10 +664,10 @@ fn index( } let (registered, keys) = { - let lines = lines(); + let lines = lines(audio); (lines.registered.clone(), lines.keys()) }; - let language = language.unwrap_or_else(|| lines().first_language()); + let language = language.unwrap_or_else(|| lines(audio).first_language()); let (mut tables, mut kept) = (0, BTreeMap::new()); for archive in archives { let file = open(archive)?; @@ -645,7 +696,7 @@ fn index( let texts = kept.len(); let wanted: BTreeSet = { - let lines = lines(); + let lines = lines(audio); let sounds = lines.sounds.values().flat_map(|s| s.streams()); (lines.by_stream.keys().copied().chain(sounds)) .map(|id| id & STREAM_ID) @@ -656,16 +707,16 @@ fn index( .collect(); // A station is named by a name harvested or by the name its own text gives it. - let stations = lines().stations.clone(); + let stations = lines(audio).stations.clone(); let named: Vec = (stations.iter()) .filter_map(|key| kept.get(key)) .map(|text| audio_radio::name_of_text(&plain(text))) .collect(); - let vocabulary = crate::state::gta6_names::vocabulary(); + let vocabulary = crate::state::gta6_names::vocabulary(>a6.install); let known = vocabulary.names().chain(named.iter().map(String::as_str)); let station_names = audio_radio::station_names(&stations, known); - let mut lines = lines(); + let mut lines = lines(audio); lines.keep(&language, kept); lines.places = archives.iter().map(|a| a.languages).max().unwrap_or(0); lines.archives = archives.iter().map(|a| a.path.clone()).collect(); @@ -691,7 +742,7 @@ impl AppState { /// texts of `language` (the first registered where `None`), and the audio container of each /// line's and each streamed sound's stream. pub(crate) fn index_gta6_dialogue(&mut self, language: Option) -> Result<(), String> { - if running() { + if running(&self.gta6.audio) { return Ok(()); } let archives: Vec = (self.documents.iter()) @@ -706,19 +757,20 @@ impl AppState { return Err(tr!("Open the scan of a GTA VI archive first: the index reads the conversation bodies, text tables, sounds and audio containers the open scans found.").to_string()); } let (cancel, progress) = (Cancel::new(), Progress::new()); - *indexing() = Some(Indexing { + *indexing(&self.gta6.audio) = Some(Indexing { cancel: cancel.clone(), progress: progress.clone(), }); - lines().said = None; + lines(&self.gta6.audio).said = None; + let gta6 = self.gta6.clone(); std::thread::spawn(move || { // A panic still ends the job, or the views wait on it for ever. let said = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - index(&archives, language, &cancel, &progress) + index(>a6, &archives, language, &cancel, &progress) })) .unwrap_or_else(|_| Err(tr!("It stopped on an internal error").to_string())); - lines().said = Some(said); - *indexing() = None; + lines(>a6.audio).said = Some(said); + *indexing(>a6.audio) = None; }); Ok(()) } @@ -726,14 +778,14 @@ impl AppState { /// Open the audio container that holds `stream` from the scan that lists it, and play the /// stream once the container has opened. pub(crate) fn play_gta6_stream(&mut self, stream: u32) { - let held = lines() + let held = lines(&self.gta6.audio) .container(stream) .map(|(a, at)| (a.to_path_buf(), at)); let Some((archive, container)) = held else { self.show_error_toast(tr!("No audio container of the indexed scans holds this stream: index the open scans with the scan of its archive open.")); return; }; - *asked() = Some(( + *asked(&self.gta6.audio) = Some(( body_path(&archive, container, View::Audio), stream & STREAM_ID, )); diff --git a/src/state/gta6/audio/gta6_dialogue/tests.rs b/src/state/gta6/audio/gta6_dialogue/tests.rs index 6ac05d987..8cb557c80 100644 --- a/src/state/gta6/audio/gta6_dialogue/tests.rs +++ b/src/state/gta6/audio/gta6_dialogue/tests.rs @@ -49,20 +49,21 @@ fn zlib(offset: u64, content: Rpf9Content, inflated: u64) -> Rpf9ScanFind { #[test] fn a_conversation_body_s_lines_name_a_text_row_and_tag_an_exported_stream() { - note_body(&body( - "APPTESTAU_ZZ01", - &["APPTEST_ONE_QA_1", "APPTEST_TWO_2"], - )); + let audio = AudioSession::default(); + note_body( + &audio, + &body("APPTESTAU_ZZ01", &["APPTEST_ONE_QA_1", "APPTEST_TWO_2"]), + ); let line = DialogueLine { key: "APPTESTAU_ZZ01".into(), number: 1, label: "APPTEST_ONE_QA_1".into(), }; assert_eq!( - line_of(line.label_hash()), + line_of(&audio, line.label_hash()), Some(("APPTESTAU_ZZ01_01".to_string(), line.label.clone())) ); - assert_eq!(line_of(0x0BAD_0BAD), None); + assert_eq!(line_of(&audio, 0x0BAD_0BAD), None); let comment = |f: &str, v: &str| (f.to_string(), v.to_string()); let named = [ @@ -70,28 +71,29 @@ fn a_conversation_body_s_lines_name_a_text_row_and_tag_an_exported_stream() { comment("LABEL", "APPTEST_ONE_QA_1"), comment("SPEAKER", "QA"), ]; - assert_eq!(comments(line.stream_id()), named); + assert_eq!(comments(&audio, line.stream_id()), named); - note_table(&table(&[(line.label_hash(), "~z~Bonjour,~n~toi.")])); + note_table(&audio, &table(&[(line.label_hash(), "~z~Bonjour,~n~toi.")])); let mut with_subtitle = named.to_vec(); with_subtitle.push(comment("SUBTITLE", "Bonjour, toi.")); - assert_eq!(comments(line.stream_id()), with_subtitle); - assert!(comments(0x0BAD_0BAD).is_empty()); + assert_eq!(comments(&audio, line.stream_id()), with_subtitle); + assert!(comments(&audio, 0x0BAD_0BAD).is_empty()); } #[test] fn an_rbf0_body_the_strict_reader_refuses_still_opens_under_a_note() { + let audio = AudioSession::default(); // A root element of no attribute, then its close. let mut doc = b"RBF0".to_vec(); doc.extend([0, 0, 1, 0, b'A', 0, 0, 0, 0, 0, 0, 0xFF, 0xFF]); let path = Path::new("made-up.rpf/0x1000.pso"); let find = zlib(0x1000, Rpf9Content::Rbf, doc.len() as u64); - opened(path, &find, &doc); - assert_eq!(strict_note(path), None); - opened(path, &find, &doc[..doc.len() - 2]); - let note = strict_note(path).expect("a note"); + opened(&audio, path, &find, &doc); + assert_eq!(strict_note(&audio, path), None); + opened(&audio, path, &find, &doc[..doc.len() - 2]); + let note = strict_note(&audio, path).expect("a note"); assert!(note.contains("lenient"), "{note}"); // The note goes once the body reads. - opened(path, &find, &doc); - assert_eq!(strict_note(path), None); + opened(&audio, path, &find, &doc); + assert_eq!(strict_note(&audio, path), None); } diff --git a/src/state/gta6/audio/mod.rs b/src/state/gta6/audio/mod.rs index d5332a114..6c0c1ae67 100644 --- a/src/state/gta6/audio/mod.rs +++ b/src/state/gta6/audio/mod.rs @@ -1,3 +1,10 @@ pub(crate) mod gta6_audio_links; pub(crate) mod gta6_dialogue; pub(crate) mod gta6_text; + +/// Per-instance audio caches owned by [`crate::state::gta6::session::Gta6Session`]. +#[derive(Clone, Default)] +pub(crate) struct AudioSession { + dialogue: gta6_dialogue::DialogueCache, + pool_names: gta6_audio_links::PoolNamesCache, +} diff --git a/src/state/gta6/bodies/gta6_other_bodies/mod.rs b/src/state/gta6/bodies/gta6_other_bodies/mod.rs index a099f6139..9bc7610f2 100644 --- a/src/state/gta6/bodies/gta6_other_bodies/mod.rs +++ b/src/state/gta6/bodies/gta6_other_bodies/mod.rs @@ -64,6 +64,8 @@ pub(in crate::state) fn ext(body: OtherBody) -> &'static str { /// The body's payload: GTA V's height map and Scaleform views, the lines of its facts, or an `EDUP` head's lines as the refusal its bytes show under. pub(in crate::state) fn payload( + bodies: &super::BodiesSession, + install: &crate::state::gta6::install::InstallSession, path: &Path, body: OtherBody, bytes: &[u8], @@ -100,11 +102,11 @@ pub(in crate::state) fn payload( OtherBody::SpanGrid => span_lines(&SpanGrid::open(bytes).map_err(refused)?), OtherBody::MoveNetwork => { let outline = MoveOutline::open(bytes).map_err(refused)?; - let lines = move_lines(&outline); - nodes::keep(path, outline); + let lines = move_lines(install, &outline); + nodes::keep(bodies, path, outline); lines } - OtherBody::ObjectTrees => crate::state::gta6_object_trees::lines(bytes)?, + OtherBody::ObjectTrees => crate::state::gta6_object_trees::lines(install, bytes)?, }; Ok(crate::state::document_io::text_payload( path, @@ -137,7 +139,10 @@ fn span_lines(grid: &SpanGrid) -> Vec { } /// The network's head, how far its walk read, then its nodes as an outline from the root. -fn move_lines(outline: &MoveOutline) -> Vec { +fn move_lines( + install: &crate::state::gta6::install::InstallSession, + outline: &MoveOutline, +) -> Vec { let head = &outline.head; let walk = if outline.stops.is_empty() { tr!( @@ -155,7 +160,7 @@ fn move_lines(outline: &MoveOutline) -> Vec { let mut lines = vec![ tr!( "A GTA VI MoVE network at version 0x13 whose name hash is {hash}: lists of {a}, {b} and {d} entries, then a root node of type {kind}, index {index} and id {id}.", - hash = crate::state::gta6_names::said32(head.name_hash), + hash = crate::state::gta6_names::said32(install, head.name_hash), a = head.list_a.len(), b = head.list_b.len(), d = head.list_d.len(), @@ -166,11 +171,11 @@ fn move_lines(outline: &MoveOutline) -> Vec { walk, String::new(), ]; - lines.splice(1..1, list_lines(head, named)); - if let Some(name) = text_name(head.name_hash) { + lines.splice(1..1, list_lines(head, |h| named(install, h))); + if let Some(name) = text_name(install, head.name_hash) { lines.insert(1, tr!("Network name: {name}", name = name)); } - outline_lines(outline, &mut lines); + outline_lines(install, outline, &mut lines); lines } @@ -195,13 +200,17 @@ fn list_lines(head: &MoveNetworkHead, hash: impl Fn(u32) -> String) -> Vec) { +fn outline_lines( + install: &crate::state::gta6::install::InstallSession, + outline: &MoveOutline, + lines: &mut Vec, +) { let mut shown = BTreeSet::new(); let mut stack = vec![(outline.root, 0usize)]; while let Some((at, depth)) = stack.pop() { let indent = " ".repeat(depth); let inner = " ".repeat(depth + 1); - let node = node_label(outline, at); + let node = node_label(install, outline, at); let Some(read) = outline.node(at) else { let line = match outline.stop(at) { Some(stop) => tr!( @@ -236,11 +245,11 @@ fn outline_lines(outline: &MoveOutline, lines: &mut Vec) { inputs = m.inputs.len(), ); lines.push(format!("{indent}{line}")); - transition_lines(outline, &m.transitions, &inner, lines); + transition_lines(install, outline, &m.transitions, &inner, lines); for entry in &m.entries { - lines.push(format!("{inner}{}", entry_line(outline, entry))); + lines.push(format!("{inner}{}", entry_line(install, outline, entry))); for c in &entry.conditions { - lines.push(format!("{inner} {}", condition_line(c))); + lines.push(format!("{inner} {}", condition_line(install, c))); } } next.extend(&m.inputs); @@ -256,9 +265,9 @@ fn outline_lines(outline: &MoveOutline, lines: &mut Vec) { bindings = s.bindings.len(), ); lines.push(format!("{indent}{line}")); - transition_lines(outline, &s.transitions, &inner, lines); + transition_lines(install, outline, &s.transitions, &inner, lines); for binding in &s.bindings { - lines.push(format!("{inner}{}", binding_line(binding))); + lines.push(format!("{inner}{}", binding_line(install, binding))); } next.push(s.output); } @@ -278,6 +287,7 @@ fn outline_lines(outline: &MoveOutline, lines: &mut Vec) { } fn transition_lines( + install: &crate::state::gta6::install::InstallSession, outline: &MoveOutline, transitions: &[MoveTransition], indent: &str, @@ -286,13 +296,13 @@ fn transition_lines( for t in transitions { let line = tr!( "transition to {target}, {size} bytes", - target = node_label(outline, t.target), + target = node_label(install, outline, t.target), size = t.size, ); lines.push(format!("{indent}{line}")); lines.push(format!("{indent} {}", transition_words(t))); for c in &t.conditions { - lines.push(format!("{indent} {}", condition_line(c))); + lines.push(format!("{indent} {}", condition_line(install, c))); } } } @@ -307,10 +317,14 @@ fn transition_words(t: &MoveTransition) -> String { } /// A machine entry's state, size and flag. -fn entry_line(outline: &MoveOutline, entry: &MachineEntry) -> String { +fn entry_line( + install: &crate::state::gta6::install::InstallSession, + outline: &MoveOutline, + entry: &MachineEntry, +) -> String { tr!( "entry to {state}, {size} bytes, flag {flag}", - state = node_label(outline, entry.state), + state = node_label(install, outline, entry.state), size = entry.size, flag = entry.flag, ) @@ -318,8 +332,11 @@ fn entry_line(outline: &MoveOutline, entry: &MachineEntry) -> String { /// A condition as GTA V's network view writes one, its hashes as `named` names them and a flag /// half of 1 named. -fn condition_line(c: &MoveCondition) -> String { - condition_line_with(c, named) +fn condition_line( + install: &crate::state::gta6::install::InstallSession, + c: &MoveCondition, +) -> String { + condition_line_with(c, |h| named(install, h)) } fn condition_line_with(c: &MoveCondition, hash: impl Fn(u32) -> String) -> String { @@ -364,7 +381,10 @@ fn condition_line_with(c: &MoveCondition, hash: impl Fn(u32) -> String) -> Strin } /// The records a state binds to one child, inputs from groups A and B, and its operations. -fn binding_line(binding: &Binding) -> String { +fn binding_line( + install: &crate::state::gta6::install::InstallSession, + binding: &Binding, +) -> String { let inputs: Vec<[u32; 4]> = (binding.inputs_a.iter()) .chain(&binding.inputs_b) .copied() @@ -372,16 +392,19 @@ fn binding_line(binding: &Binding) -> String { tr!( "child {child} binds inputs {inputs}, outputs {outputs} and events {events}, with operations {operations}", child = binding.child, - inputs = hashes(&inputs), - outputs = hashes(&binding.outputs), - events = hashes(&binding.events), + inputs = hashes(install, &inputs), + outputs = hashes(install, &binding.outputs), + events = hashes(install, &binding.events), operations = operations_line(&binding.operations), ) } /// Each record's first word as `named` names a hash and its further words as stored, or a dash. -fn hashes(records: &[[u32; N]]) -> String { - hashes_with(records, named) +fn hashes( + install: &crate::state::gta6::install::InstallSession, + records: &[[u32; N]], +) -> String { + hashes_with(records, |h| named(install, h)) } fn hashes_with(records: &[[u32; N]], hash: impl Fn(u32) -> String) -> String { @@ -443,8 +466,12 @@ fn operator_line(o: &Operator) -> String { } /// A node's kind and id, for a node read or reached; its offset for any other. -fn node_label(outline: &MoveOutline, at: usize) -> String { - node_label_with(outline, at, named) +fn node_label( + install: &crate::state::gta6::install::InstallSession, + outline: &MoveOutline, + at: usize, +) -> String { + node_label_with(outline, at, |h| named(install, h)) } fn node_label_with(outline: &MoveOutline, at: usize, hash: impl Fn(u32) -> String) -> String { @@ -461,13 +488,13 @@ fn node_label_with(outline: &MoveOutline, at: usize, hash: impl Fn(u32) -> Strin /// A 32-bit hash by the one name the harvested text holds for it, which may be a collision and /// is marked so, else as `hash_`. -fn named(hash: u32) -> String { - text_name(hash).unwrap_or_else(|| format!("hash_{hash:08X}")) +fn named(install: &crate::state::gta6::install::InstallSession, hash: u32) -> String { + text_name(install, hash).unwrap_or_else(|| format!("hash_{hash:08X}")) } /// The name the harvested text holds for `hash`, marked as from the text. -fn text_name(hash: u32) -> Option { - crate::state::gta6_names::name32(hash).map(|name| from_the_text(&name)) +fn text_name(install: &crate::state::gta6::install::InstallSession, hash: u32) -> Option { + crate::state::gta6_names::name32(install, hash).map(|name| from_the_text(&name)) } fn from_the_text(name: &str) -> String { @@ -494,12 +521,14 @@ mod tests { #[test] fn an_edup_body_shows_its_head_over_its_refused_payload_and_the_others_open_in_a_view() { assert_eq!(view(OtherBody::Edup), Ok(View::Identified(OtherBody::Edup))); + let bodies = crate::state::gta6::bodies::BodiesSession::default(); + let install = crate::state::gta6::install::InstallSession::default(); let path = Path::new("0x10.txt"); let mut zero = b"EDUP".to_vec(); zero.extend_from_slice(&0u32.to_le_bytes()); zero.extend_from_slice(&16u32.to_le_bytes()); zero.extend_from_slice(&[0x5A; 16]); - let Err(banner) = payload(path, OtherBody::Edup, &zero) else { + let Err(banner) = payload(&bodies, &install, path, OtherBody::Edup, &zero) else { panic!("the payload is refused"); }; let lines: Vec<&str> = banner.lines().collect(); @@ -510,14 +539,14 @@ mod tests { let mut counted = b"EDUP".to_vec(); counted.extend_from_slice(&4u32.to_le_bytes()); counted.extend_from_slice(&[0; 228]); - let Err(banner) = payload(path, OtherBody::Edup, &counted) else { + let Err(banner) = payload(&bodies, &install, path, OtherBody::Edup, &counted) else { panic!("the payload is refused"); }; assert_eq!(banner.lines().count(), 2, "{banner}"); assert!(banner.contains("is 4, and 228 payload bytes"), "{banner}"); // A head its reader refuses shows the reader's reason, not the head's lines. zero.pop(); - let Err(why) = payload(path, OtherBody::Edup, &zero) else { + let Err(why) = payload(&bodies, &install, path, OtherBody::Edup, &zero) else { panic!("the head is refused"); }; assert!(why.contains("states 16 bytes where 15 follow it"), "{why}"); diff --git a/src/state/gta6/bodies/gta6_other_bodies/nodes.rs b/src/state/gta6/bodies/gta6_other_bodies/nodes.rs index d163accb8..f9022e325 100644 --- a/src/state/gta6/bodies/gta6_other_bodies/nodes.rs +++ b/src/state/gta6/bodies/gta6_other_bodies/nodes.rs @@ -7,28 +7,38 @@ use std::sync::{Arc, Mutex, MutexGuard}; use or_io::gta6::move_network::{kind_name, MoveBody, MoveCondition, MoveOutline, MoveTransition}; -// ponytail: one entry per network opened, never emptied, as the scanned lists are. -static OUTLINES: Mutex>> = Mutex::new(BTreeMap::new()); +use super::super::BodiesSession; -fn outlines() -> MutexGuard<'static, BTreeMap>> { - OUTLINES +#[derive(Clone, Default)] +pub(in crate::state::gta6::bodies) struct OutlinesCache( + Arc>>>, +); + +fn outlines(bodies: &BodiesSession) -> MutexGuard<'_, BTreeMap>> { + bodies + .outlines + .0 .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// Keep `outline` for the document at `path`. -pub(super) fn keep(path: &Path, outline: MoveOutline) { - outlines().insert(path.to_path_buf(), Arc::new(outline)); +pub(super) fn keep(bodies: &BodiesSession, path: &Path, outline: MoveOutline) { + outlines(bodies).insert(path.to_path_buf(), Arc::new(outline)); } /// The network the document at `path` opened from; `None` for any other document. -pub(crate) fn outline(path: &Path) -> Option> { - outlines().get(path).cloned() +pub(crate) fn outline(bodies: &BodiesSession, path: &Path) -> Option> { + outlines(bodies).get(path).cloned() } /// A node's kind and id, as the document's lines name it. -pub(crate) fn label(outline: &MoveOutline, at: usize) -> String { - super::node_label(outline, at) +pub(crate) fn label( + install: &crate::state::gta6::install::InstallSession, + outline: &MoveOutline, + at: usize, +) -> String { + super::node_label(install, outline, at) } /// The nodes `at` leads to: a machine's inputs and states, a state's output, a leaf's inputs. @@ -44,7 +54,11 @@ pub(crate) fn children(outline: &MoveOutline, at: usize) -> Vec { } /// The fields of the node at `at` as a label and a value each; a node not read says why. -pub(crate) fn rows(outline: &MoveOutline, at: usize) -> Vec<(String, String)> { +pub(crate) fn rows( + install: &crate::state::gta6::install::InstallSession, + outline: &MoveOutline, + at: usize, +) -> Vec<(String, String)> { let kind = |kind: u16| kind_name(kind).map_or(kind.to_string(), |n| format!("{kind} ({n})")); let mut rows = vec![(tr!("Offset").to_string(), format!("{at:#X}"))]; let Some(node) = outline.node(at) else { @@ -52,7 +66,7 @@ pub(crate) fn rows(outline: &MoveOutline, at: usize) -> Vec<(String, String)> { rows.push((tr!("Kind").to_string(), kind(stop.kind))); rows.push((tr!("Child index").to_string(), stop.index.to_string())); rows.push((tr!("Id").to_string(), format!("hash_{:08X}", stop.id))); - name_row(stop.id, &mut rows); + name_row(install, stop.id, &mut rows); rows.push(( tr!("Word at +0x08").to_string(), format!("{:#010X}", stop.word), @@ -67,26 +81,32 @@ pub(crate) fn rows(outline: &MoveOutline, at: usize) -> Vec<(String, String)> { rows.push((tr!("Kind").to_string(), kind(node.kind))); rows.push((tr!("Child index").to_string(), node.index.to_string())); rows.push((tr!("Id").to_string(), format!("hash_{:08X}", node.id))); - name_row(node.id, &mut rows); + name_row(install, node.id, &mut rows); rows.push((tr!("Bytes").to_string(), node.size.to_string())); match &node.body { MoveBody::Machine(m) => { let initial = - (m.initial).map_or_else(|| tr!("none").to_string(), |s| label(outline, s)); + (m.initial).map_or_else(|| tr!("none").to_string(), |s| label(install, outline, s)); rows.push((tr!("Initial state").to_string(), initial)); rows.push((tr!("Entries").to_string(), m.entries.len().to_string())); - transitions(outline, &m.transitions, &mut rows); + transitions(install, outline, &m.transitions, &mut rows); for e in &m.entries { - rows.push((tr!("Entry").to_string(), super::entry_line(outline, e))); - conditions(&e.conditions, &mut rows); + rows.push(( + tr!("Entry").to_string(), + super::entry_line(install, outline, e), + )); + conditions(install, &e.conditions, &mut rows); } } MoveBody::State(s) => { rows.push((tr!("Children").to_string(), s.children.to_string())); - rows.push((tr!("Output node").to_string(), label(outline, s.output))); - transitions(outline, &s.transitions, &mut rows); + rows.push(( + tr!("Output node").to_string(), + label(install, outline, s.output), + )); + transitions(install, outline, &s.transitions, &mut rows); for b in &s.bindings { - rows.push((tr!("Binding").to_string(), super::binding_line(b))); + rows.push((tr!("Binding").to_string(), super::binding_line(install, b))); } } MoveBody::Leaf { flags, inputs } => { @@ -98,6 +118,7 @@ pub(crate) fn rows(outline: &MoveOutline, at: usize) -> Vec<(String, String)> { } fn transitions( + install: &crate::state::gta6::install::InstallSession, outline: &MoveOutline, transitions: &[MoveTransition], rows: &mut Vec<(String, String)>, @@ -105,24 +126,35 @@ fn transitions( for t in transitions { let to = tr!( "transition to {target}, {size} bytes", - target = label(outline, t.target), + target = label(install, outline, t.target), size = t.size, ); rows.push((tr!("Transition").to_string(), to)); rows.push((tr!("Transition").to_string(), super::transition_words(t))); - conditions(&t.conditions, rows); + conditions(install, &t.conditions, rows); } } /// A row of the name the harvested text holds for `id`, where it holds one. -fn name_row(id: u32, rows: &mut Vec<(String, String)>) { - if let Some(name) = super::text_name(id) { +fn name_row( + install: &crate::state::gta6::install::InstallSession, + id: u32, + rows: &mut Vec<(String, String)>, +) { + if let Some(name) = super::text_name(install, id) { rows.push((tr!("Name").to_string(), name)); } } -fn conditions(conditions: &[MoveCondition], rows: &mut Vec<(String, String)>) { +fn conditions( + install: &crate::state::gta6::install::InstallSession, + conditions: &[MoveCondition], + rows: &mut Vec<(String, String)>, +) { for c in conditions { - rows.push((tr!("Condition").to_string(), super::condition_line(c))); + rows.push(( + tr!("Condition").to_string(), + super::condition_line(install, c), + )); } } diff --git a/src/state/gta6/bodies/gta6_other_bodies_save/mod.rs b/src/state/gta6/bodies/gta6_other_bodies_save/mod.rs index a38d86402..1195b5b79 100644 --- a/src/state/gta6/bodies/gta6_other_bodies_save/mod.rs +++ b/src/state/gta6/bodies/gta6_other_bodies_save/mod.rs @@ -15,7 +15,10 @@ pub type Write = dyn Fn() -> Result, String> + Send + Sync; /// The height map row's `edited_sections` where `document` is an edited height map a GTA VI scan /// found; `None` for any other. -pub(in crate::state) fn edited(document: &Document) -> Option> { +pub(in crate::state) fn edited( + document: &Document, + gta6: &crate::state::gta6::session::Gta6Session, +) -> Option> { let DocPayload::HeightMap(grid) = &document.payload else { return None; }; @@ -24,8 +27,9 @@ pub(in crate::state) fn edited(document: &Document) -> Option = Arc::new(move || { - let stored = crate::state::rpf9_scan::extracted_body(&archive, offset)?; + let stored = crate::state::rpf9_scan::extracted_body(&install, &archive, offset)?; if OtherBody::of(&stored, stored.len() as u64) == Some(OtherBody::HeightGrid) { let mut body = Gta6HeightGrid::open(&stored).map_err(|e| e.to_string())?; body.set_height_map(&grid).map_err(|e| e.to_string())?; diff --git a/src/state/gta6/bodies/gta6_resource.rs b/src/state/gta6/bodies/gta6_resource.rs index 32601079f..c08927dd0 100644 --- a/src/state/gta6/bodies/gta6_resource.rs +++ b/src/state/gta6/bodies/gta6_resource.rs @@ -4,8 +4,11 @@ use std::collections::{HashMap, HashSet}; use std::hash::{DefaultHasher, Hash, Hasher}; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Mutex, MutexGuard}; +use std::sync::atomic::Ordering; +use std::sync::MutexGuard; + +use super::{BodiesSession, EffectsCache}; +use crate::state::gta6::install::InstallSession; use or_io::container::rpf::{Rpf9Resource, Rpf9Role, Rpf9Signature}; use or_io::gta5::shaders::sgd5::{ @@ -21,30 +24,12 @@ use or_io::gta6::headerless::{ HeaderlessError, NavNode, ParameterValue, Primitive, Resource, Shader, UnknownShape, }; -/// The role's name, or that it is not known. -pub(crate) fn role_name(role: Option) -> &'static str { - match role { - Some(Rpf9Role::Bound) => tr!("bound"), - Some(Rpf9Role::Drawable) => tr!("drawable"), - Some(Rpf9Role::Dictionary) => tr!("dictionary"), - Some(Rpf9Role::DrawableWithBound) => tr!("fragment"), - Some(Rpf9Role::NavMesh) => tr!("navigation mesh"), - Some(Rpf9Role::NavOctree) => tr!("navigation octree"), - Some(Rpf9Role::AccelerationStructure) => tr!("acceleration structure"), - Some(Rpf9Role::Cloth) => tr!("cloth"), - Some(Rpf9Role::MorphTarget) => tr!("morph target"), - Some(Rpf9Role::VertexBuffers) => tr!("vertex buffers"), - Some(Rpf9Role::KeyedBlob) => tr!("keyed blob"), - Some(Rpf9Role::KeyedBlobDescriptor) => tr!("keyed-blob descriptor"), - Some(Rpf9Role::AssetIndex) => tr!("asset index"), - Some(Rpf9Role::NeighbourTable) => tr!("neighbour table"), - Some(Rpf9Role::ParticleEffects) => tr!("particle effects"), - None => tr!("not known"), - } -} +pub(crate) use super::role_name; /// What the reader reads from `bytes`, a read of `resource`: its virtual, then its physical section. pub(in crate::state) fn facts( + bodies: &BodiesSession, + install: &InstallSession, resource: &Rpf9Resource, signature: Rpf9Signature, bytes: &[u8], @@ -76,7 +61,7 @@ pub(in crate::state) fn facts( })?; match resource { Resource::Bound(b) => bound_lines(&b, false, &mut lines), - Resource::Drawable(d) => drawable_lines(&d, true, &mut lines), + Resource::Drawable(d) => drawable_lines(&d, Some(bodies), &mut lines), Resource::Dictionary(dict) => { let drawables = (dict.entries.iter()) .filter(|(_, e)| matches!(e, Ok(Entry::Drawable(_)))) @@ -88,12 +73,12 @@ pub(in crate::state) fn facts( )); for (code, entry) in &dict.entries { match entry { - Ok(Entry::Drawable(d)) => drawable_lines(d, true, &mut lines), - entry => lines.extend(entry_line(*code, entry)), + Ok(Entry::Drawable(d)) => drawable_lines(d, Some(bodies), &mut lines), + entry => lines.extend(entry_line(install, *code, entry)), } } } - Resource::DrawableWithBound(r) => fragment_lines(&r, true, &mut lines), + Resource::DrawableWithBound(r) => fragment_lines(&r, Some(bodies), &mut lines), Resource::Instances(set) => { let structures = set.instances.iter().filter_map(|i| i.structure.as_ref()); lines.push(tr!( @@ -138,7 +123,7 @@ pub(in crate::state) fn facts( key = format!("{:016X}", b.key), )), Resource::KeyedBlobDescriptor(d) => crate::state::gta6_small::descriptor_lines(&d, &mut lines), - Resource::AssetIndex(a) => crate::state::gta6_small::index_lines(&a, &mut lines), + Resource::AssetIndex(a) => crate::state::gta6_small::index_lines(install, &a, &mut lines), Resource::NeighbourTable(n) => crate::state::gta6_small::neighbour_lines(&n, &mut lines), Resource::ParticleEffects(list) => lines.extend(crate::state::gta6_particles::lines(&list)), } @@ -146,13 +131,17 @@ pub(in crate::state) fn facts( } /// What a dictionary's entry other than a drawable is; `None` for a drawable. -fn entry_line(code: u32, entry: &Result) -> Option { +fn entry_line( + install: &InstallSession, + code: u32, + entry: &Result, +) -> Option { let code = format!("{code:#010X}"); Some(match entry { Ok(Entry::Drawable(_)) => return None, Ok(Entry::Texture(t)) => texture_line(t), Ok(Entry::FrameFilter { name, tracks }) => filter_lines(name, tracks), - Ok(Entry::AnimationRecord { name, bones }) => record_lines(name, bones), + Ok(Entry::AnimationRecord { name, bones }) => record_lines(install, name, bones), Ok(Entry::Word64(word)) => tr!( "Entry {code} holds the 64-bit word {word}, whose role is not known.", code = code, @@ -184,7 +173,11 @@ fn filter_lines(name: &str, tracks: &[or_io::gta6::headerless::FilterTrack]) -> } /// An animation record's name, then a line per bone: its name hash, its kind, its flags and its floats. -fn record_lines(name: &str, bones: &[or_io::gta6::headerless::BoneRecord]) -> String { +fn record_lines( + install: &InstallSession, + name: &str, + bones: &[or_io::gta6::headerless::BoneRecord], +) -> String { let mut lines = vec![tr_n!( "An animation record named {name}, with settings for {count} skeleton bone.", "An animation record named {name}, with settings for {count} skeleton bones.", @@ -195,7 +188,7 @@ fn record_lines(name: &str, bones: &[or_io::gta6::headerless::BoneRecord]) -> St let values: Vec = b.values.iter().map(f32::to_string).collect(); tr!( "Bone {bone}: kind {kind}, flags {flags}, values {values}.", - bone = crate::state::gta6_names::said32(b.bone), + bone = crate::state::gta6_names::said32(install, b.bone), kind = b.kind, flags = format!("{:#010X}", b.flags), values = values.join(", "), @@ -204,9 +197,9 @@ fn record_lines(name: &str, bones: &[or_io::gta6::headerless::BoneRecord]) -> St lines.join("\n") } -fn fragment_lines(r: &DrawableWithBound, shaders: bool, lines: &mut Vec) { +fn fragment_lines(r: &DrawableWithBound, bodies: Option<&BodiesSession>, lines: &mut Vec) { lines.push(tr!("Its name is {name}.", name = r.name)); - drawable_lines(&r.drawable, shaders, lines); + drawable_lines(&r.drawable, bodies, lines); match &r.bound { Some(bound) => bound_lines(bound, false, lines), None => lines.push(tr!("It has no bound: its record at 0x10 is null.").to_string()), @@ -250,25 +243,26 @@ pub(crate) fn dictionary_drawables( /// What the inspector says of a scanned body the model view draws, and of the drawable `selection` /// shows, whose shaders it lists as [`material_rows`]. pub(crate) fn body_lines( + install: &InstallSession, resource: &Resource, selection: Option, ) -> Vec { let mut lines = Vec::new(); match resource { Resource::Bound(b) => bound_lines(b, true, &mut lines), - Resource::DrawableWithBound(r) => fragment_lines(r, false, &mut lines), + Resource::DrawableWithBound(r) => fragment_lines(r, None, &mut lines), Resource::Dictionary(dict) => { for (code, entry) in &dict.entries { - lines.extend(entry_line(*code, entry)); + lines.extend(entry_line(install, *code, entry)); } match drawable_of(resource, selection) { - Some(d) => drawable_lines(d, false, &mut lines), + Some(d) => drawable_lines(d, None, &mut lines), None => lines.push( tr!("No drawable is chosen: click one of the list to draw it.").to_string(), ), } } - Resource::Drawable(d) => drawable_lines(d, false, &mut lines), + Resource::Drawable(d) => drawable_lines(d, None, &mut lines), Resource::Cloth(c) => crate::state::gta6_fragment::cloth_lines(c, &mut lines), _ => {} } @@ -300,6 +294,7 @@ fn texture_line(t: &DictionaryTexture) -> String { /// A scanned navigation mesh as the model the `.ynv` view draws, the cell kept for the inspector /// under `path`; `None` where it does not read or fit. pub(in crate::state) fn as_ynv( + physics: &crate::state::gta6::physics::PhysicsSession, path: &std::path::Path, resource: &Rpf9Resource, signature: Rpf9Signature, @@ -310,7 +305,7 @@ pub(in crate::state) fn as_ynv( } let m = read_navmesh(resource.sections(bytes).0).ok()?; let mesh = cell_view(&m)?; - crate::state::gta6_navmesh::remember(path, m); + crate::state::gta6_navmesh::remember(physics, path, m); Some(mesh) } @@ -504,11 +499,6 @@ fn bound_lines(b: &Bound, drawn: bool, lines: &mut Vec) { lines.extend(refused); } -struct EffectsCache { - loaded_from: Option>, - defs: Option, -} - impl EffectsCache { /// Ensures `defs` reflects `path`, reloading whenever the config root path changes. /// Returns `true` when a load/reload happened. @@ -525,27 +515,6 @@ impl EffectsCache { } } -/// GTA VI's effects from each `SGD5` container the app has read, which name a drawable's shaders. -// ponytail: one database for the whole app, which no view empties. -static EFFECTS: Mutex = Mutex::new(EffectsCache { - loaded_from: None, - defs: None, -}); -/// How many times [`EFFECTS`] has learned a container's effects. -static EFFECTS_LEARNED: AtomicU64 = AtomicU64::new(0); - -#[derive(Default)] -struct KeptState { - started_for: Option>, - loaded_for: Option>, -} - -/// Tracks which `config_root()` path has started and finished loading kept effects, without holding [`EFFECTS`]. -static KEPT_STATE: Mutex = Mutex::new(KeptState { - started_for: None, - loaded_for: None, -}); - /// Where the effects the app has read are kept across runs. // ⚠ Named anew when a kept effect gains a field an older file lacks: `gta6_effects.json` predates // each constant's drawable place, which an absent value cannot tell from a buffer the engine fills. @@ -553,16 +522,20 @@ fn kept_effects_path() -> Option { crate::state::prefs::config_root().map(|root| root.join("gta6_effects_placed.json")) } -fn effects() -> MutexGuard<'static, EffectsCache> { +fn effects(bodies: &BodiesSession) -> MutexGuard<'_, EffectsCache> { let path = kept_effects_path(); - let mut cache = EFFECTS + let mut cache = bodies + .effects + .effects .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); + .unwrap_or_else(|p| p.into_inner()); if cache.ensure_loaded(path.clone()) { - let mut kept = KEPT_STATE + bodies + .effects + .kept_state .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - kept.loaded_for = Some(path); + .unwrap_or_else(|p| p.into_inner()) + .loaded_for = Some(path); } cache } @@ -570,18 +543,21 @@ fn effects() -> MutexGuard<'static, EffectsCache> { /// Whether the effects an earlier run kept have been read; the first call for a config folder starts reading them on a worker. /// /// ⚠ The kept file is tens of megabytes of JSON: read on the UI thread it held a frame half a second. -pub(in crate::state) fn kept_effects_ready() -> bool { +pub(in crate::state) fn kept_effects_ready(bodies: &BodiesSession) -> bool { let path = kept_effects_path(); - let mut kept = KEPT_STATE + let mut kept = bodies + .effects + .kept_state .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); + .unwrap_or_else(|p| p.into_inner()); if kept.loaded_for.as_ref() == Some(&path) { return true; } if kept.started_for.as_ref() != Some(&path) { kept.started_for = Some(path); drop(kept); - std::thread::spawn(|| drop(effects())); + let bodies = bodies.clone(); + std::thread::spawn(move || drop(effects(&bodies))); } false } @@ -604,30 +580,31 @@ fn keep_effects(path: &std::path::Path, text: serde_json::Result) -> Res } /// Whether the app knows any GTA VI effect, read this run or kept from an earlier one. -pub(in crate::state) fn effects_known() -> bool { - effects() +pub(in crate::state) fn effects_known(bodies: &BodiesSession) -> bool { + effects(bodies) .defs .as_ref() .is_some_and(|e| !e.shaders.is_empty()) } /// The effect a shader's name hash names among those the app has read, else `hash_` and the hash. -pub(crate) fn effect_name(hash: u32) -> String { - known_effect(hash).unwrap_or_else(|| format!("hash_{hash:08X}")) +pub(crate) fn effect_name(bodies: &BodiesSession, hash: u32) -> String { + known_effect(bodies, hash).unwrap_or_else(|| format!("hash_{hash:08X}")) } /// The effect a shader's name hash names among those the app has read. -pub(crate) fn known_effect(hash: u32) -> Option { - (effects().defs.as_ref()).and_then(|e| e.name_material(hash, &[]).shader) +pub(crate) fn known_effect(bodies: &BodiesSession, hash: u32) -> Option { + (effects(bodies).defs.as_ref()).and_then(|e| e.name_material(hash, &[]).shader) } /// The effect whose name hashes to `hash`, among those the app has read. -pub(crate) fn effect_def(hash: u32) -> Option { - (effects().defs.as_ref()).and_then(|e| e.shader(hash).cloned()) +pub(crate) fn effect_def(bodies: &BodiesSession, hash: u32) -> Option { + (effects(bodies).defs.as_ref()).and_then(|e| e.shader(hash).cloned()) } /// Keep the effects of `bytes`, an `SGD5` container, for the drawables' shaders; how many it holds. pub(in crate::state) fn learn_effects( + bodies: &BodiesSession, bytes: &[u8], platform: or_io::Platform, ) -> Result { @@ -635,13 +612,13 @@ pub(in crate::state) fn learn_effects( let learned = shader_definitions("gta6", "gta6", std::slice::from_ref(&file)); let count = learned.shaders.len(); let fresh: HashSet = learned.shaders.iter().map(|s| s.name_hash).collect(); - let mut effects = effects(); + let mut effects = effects(bodies); let known = effects .defs .get_or_insert_with(|| ShaderDefinitions::new("gta6", "gta6")); known.shaders.retain(|s| !fresh.contains(&s.name_hash)); known.shaders.extend(learned.shaders); - EFFECTS_LEARNED.fetch_add(1, Ordering::Relaxed); + bodies.effects.learned.fetch_add(1, Ordering::Relaxed); let text = (!known.shaders.is_empty()).then(|| known.to_json()); drop(effects); if let (Some(path), Some(text)) = (kept_effects_path(), text) { @@ -655,9 +632,15 @@ pub(in crate::state) fn learn_effects( /// A stamp of what a drawable's lines read beside it: the effects, GTA V's parameter names and the texture names learned, the packs indexed, and the documents open. pub(crate) fn drawable_lines_stamp(state: &crate::state::AppState) -> u64 { let mut hasher = DefaultHasher::new(); - EFFECTS_LEARNED.load(Ordering::Relaxed).hash(&mut hasher); + state + .gta6 + .bodies + .effects + .learned + .load(Ordering::Relaxed) + .hash(&mut hasher); shader_defs::is_installed().hash(&mut hasher); - crate::state::ttpf_document::names_known().hash(&mut hasher); + crate::state::ttpf_document::names_known(&state.gta6.ttpf).hash(&mut hasher); state.texture_packs_indexed().hash(&mut hasher); for doc in &state.documents { (doc.id, doc.payload_epoch()).hash(&mut hasher); @@ -666,8 +649,8 @@ pub(crate) fn drawable_lines_stamp(state: &crate::state::AppState) -> u64 { } /// The name a texture key is looked up and drawn by: the one the app has learned, else `hash_` and the key. -pub(crate) fn texture_name(key: u64) -> String { - crate::state::ttpf_document::known_name(key) +pub(crate) fn texture_name(gta6: &crate::state::gta6::session::Gta6Session, key: u64) -> String { + crate::state::ttpf_document::known_name(>a6.ttpf, >a6.install, key) .map_or_else(|| format!("hash_{key:016X}"), |n| n.to_ascii_lowercase()) } @@ -697,7 +680,7 @@ pub(crate) fn material_rows( d: &Drawable, ) -> Vec { let names = gta5_names(); - let effects = effects(); + let effects = effects(&state.gta6.bodies); let mut out = Vec::new(); for (i, s) in d.shaders.iter().enumerate() { let effect = (effects.defs.as_ref()).and_then(|e| e.shader(s.name_hash)); @@ -771,7 +754,7 @@ fn texture_detail( let Some(key) = key else { return (tr!("texture slot {slot} · unbound", slot = slot), false); }; - let known = texture_name(key); + let known = texture_name(&state.gta6, key); let found = crate::state::texture_resolution::probe(state, None, None, &known).found; let name = match known.starts_with("hash_") { true => known.clone(), @@ -854,8 +837,11 @@ fn constant_values(words: &[u32], effect: Option<&ShaderDef>, hash: u32) -> (Str } /// Each parameter of each of `shaders`: its name, and whether its effect declares it as floats. -pub(crate) fn parameter_rows(shaders: &[Shader]) -> Vec> { - let (names, effects) = (gta5_names(), effects()); +pub(crate) fn parameter_rows( + bodies: &BodiesSession, + shaders: &[Shader], +) -> Vec> { + let (names, effects) = (gta5_names(), effects(bodies)); let row = |s: &Shader, hash| { let effect = (effects.defs.as_ref()).and_then(|e| e.shader(s.name_hash)); let def = effect.and_then(|e| drawable_parameter(e, hash)); @@ -907,8 +893,8 @@ fn constant_lines( } } -/// A drawable's counts, its shaders' lines where `shaders`, and what is not read. -fn drawable_lines(d: &Drawable, shaders: bool, lines: &mut Vec) { +/// A drawable's counts, its shaders' lines where `bodies` is `Some`, and what is not read. +fn drawable_lines(d: &Drawable, bodies: Option<&BodiesSession>, lines: &mut Vec) { let (mut geometries, mut triangles, mut positions) = (0, 0, 0); let mut refused = Vec::new(); for (l, models) in d.levels.iter().enumerate() { @@ -952,40 +938,40 @@ fn drawable_lines(d: &Drawable, shaders: bool, lines: &mut Vec) { triangles = triangles, positions = positions, )); - let effects = effects(); - let gta5 = gta5_names(); - let listed = if shaders { d.shaders.as_slice() } else { &[] }; - for (i, s) in listed.iter().enumerate() { - let effect = (effects.defs.as_ref()).and_then(|e| e.shader(s.name_hash)); - match effect { - None => lines.push(tr!( - "Shader {index} is named only by its hash, hash_{hash}, and binds {keys} texture keys.", - index = i, - hash = format!("{:08X}", s.name_hash), - keys = s.texture_keys.iter().flatten().count(), - )), - Some(effect) => { - let named = (s.parameters.iter()) - .filter(|p| drawable_parameter(effect, p.hash).is_some()) - .count(); - let names: Vec = (s.parameters.iter()) - .map(|p| parameter_name(>a5, p.hash)) - .collect(); - lines.push(tr!( - "Shader {index} is the effect {effect}, hash_{hash}, and binds {keys} texture keys. The effect declares {named} of its {count} parameters: {names}.", + if let Some(bodies) = bodies { + let effects = effects(bodies); + let gta5 = gta5_names(); + for (i, s) in d.shaders.iter().enumerate() { + let effect = (effects.defs.as_ref()).and_then(|e| e.shader(s.name_hash)); + match effect { + None => lines.push(tr!( + "Shader {index} is named only by its hash, hash_{hash}, and binds {keys} texture keys.", index = i, - effect = effect.name, hash = format!("{:08X}", s.name_hash), keys = s.texture_keys.iter().flatten().count(), - named = named, - count = s.parameters.len(), - names = names.join(", "), - )); + )), + Some(effect) => { + let named = (s.parameters.iter()) + .filter(|p| drawable_parameter(effect, p.hash).is_some()) + .count(); + let names: Vec = (s.parameters.iter()) + .map(|p| parameter_name(>a5, p.hash)) + .collect(); + lines.push(tr!( + "Shader {index} is the effect {effect}, hash_{hash}, and binds {keys} texture keys. The effect declares {named} of its {count} parameters: {names}.", + index = i, + effect = effect.name, + hash = format!("{:08X}", s.name_hash), + keys = s.texture_keys.iter().flatten().count(), + named = named, + count = s.parameters.len(), + names = names.join(", "), + )); + } } + constant_lines(i, s, effect, >a5, lines); } - constant_lines(i, s, effect, >a5, lines); } - drop(effects); lines.extend( d.embedded .as_deref() diff --git a/src/state/gta6/bodies/gta6_resource_save/awc_in_extent.rs b/src/state/gta6/bodies/gta6_resource_save/awc_in_extent.rs index ed3f80aa7..52e1b3c50 100644 --- a/src/state/gta6/bodies/gta6_resource_save/awc_in_extent.rs +++ b/src/state/gta6/bodies/gta6_resource_save/awc_in_extent.rs @@ -14,7 +14,10 @@ use crate::state::rpf_archive_open::tree_open::{self, TableRead}; /// The audio container row's `edited_sections`: a GTA VI body's edit laid on the worker in the /// extents of the container as read, else the whole container; `None` while nothing is edited. -pub(super) fn edited(doc: &Document) -> Option> { +pub(super) fn edited( + doc: &Document, + gta6: &crate::state::gta6::session::Gta6Session, +) -> Option> { let DocPayload::Awc(awc) = &doc.payload else { return None; }; @@ -27,10 +30,11 @@ pub(super) fn edited(doc: &Document) -> Option> { return Some(awc.to_bytes().map(EditedSave::Bytes)); }; let (path, archive, awc) = (path.to_path_buf(), archive.to_path_buf(), awc.clone()); + let install = gta6.install.clone(); let write: Arc = Arc::new(move || { let mut awc = awc.clone(); let whole = awc.to_bytes()?; - let fitted = (as_read(&path, &archive, offset)) + let fitted = (as_read(&install, &path, &archive, offset)) .and_then(|source| laid(&source, awc.file(AwcKey::default())?)); Ok(fitted.unwrap_or_else(|why| { tracing::warn!( @@ -47,9 +51,14 @@ pub(super) fn edited(doc: &Document) -> Option> { /// The container the body at `offset` of `archive` opened as under `path`, read again by the door /// it opened through: its tree row's table, else a scan's read. -fn as_read(path: &Path, archive: &Path, offset: u64) -> Result, String> { +fn as_read( + install: &crate::state::gta6::install::InstallSession, + path: &Path, + archive: &Path, + offset: u64, +) -> Result, String> { match tree_open::read(path, archive, offset) { - None => crate::state::rpf9_scan::extracted_body(archive, offset), + None => crate::state::rpf9_scan::extracted_body(install, archive, offset), Some(read) => match read? { TableRead::Body(_, bytes) => Ok(bytes), TableRead::Plain(DocPayload::Hex(hex)) => Ok(hex.bytes), @@ -498,7 +507,8 @@ mod tests { continue; } let (archive, offset) = scanned_body(&path).expect("a body of the archive"); - let source = as_read(&path, archive, offset).expect("the container as read"); + let source = as_read(&state.gta6.install, &path, archive, offset) + .expect("the container as read"); let in_extent = laid(&source, state.awc_file(doc).expect("its container")); match &in_extent { Ok(_) => fits += 1, diff --git a/src/state/gta6/bodies/gta6_resource_save/mod.rs b/src/state/gta6/bodies/gta6_resource_save/mod.rs index 39ec9fe66..bca938bd3 100644 --- a/src/state/gta6/bodies/gta6_resource_save/mod.rs +++ b/src/state/gta6/bodies/gta6_resource_save/mod.rs @@ -36,8 +36,9 @@ pub enum EditedSave { /// The audio container row's `edited_sections`: the container laid in its extents, else rewritten. pub(in crate::state) fn edited_awc( doc: &crate::state::Document, + gta6: &crate::state::gta6::session::Gta6Session, ) -> Option> { - awc_in_extent::edited(doc) + awc_in_extent::edited(doc, gta6) } /// A row's `edited_sections` of the sections a payload holds edited. @@ -62,7 +63,7 @@ impl AppState { doc: DocumentId, ) -> Option> { let doc = self.document(doc)?; - (crate::state::capabilities::for_payload(&doc.payload)?.edited_sections?)(doc) + (crate::state::capabilities::for_payload(&doc.payload)?.edited_sections?)(doc, &self.gta6) } /// `name` in `dest`, the edits of `doc` written as a loose resource on a worker; `None` while @@ -76,8 +77,9 @@ impl AppState { ) -> Option { let edited = self.edited_sections(doc)?; // The neighbouring bodies whose links an edit of a scanned cell renumbered. - let beside = (self.document(doc)) - .map_or(Vec::new(), crate::state::gta6_navmesh_delete::links::beside); + let beside = (self.document(doc)).map_or(Vec::new(), |doc| { + crate::state::gta6_navmesh_delete::links::beside(&self.gta6.physics, doc) + }); Some(self.start_edited_save(edited, dest, name, reads, beside)) } @@ -156,7 +158,12 @@ impl AppState { crate::state::DocPayload::Gta6Text(text) if gxt2 => { (text.to_gxt2()).map(|bytes| ExtractItem::bytes(name.clone(), bytes)) } - _ => Ok(ExtractItem::scanned(name.clone(), archive.clone(), offset)), + _ => Ok(ExtractItem::scanned( + name.clone(), + archive.clone(), + offset, + self.gta6.install.clone(), + )), }; let item = match item { Ok(item) => item, @@ -286,12 +293,15 @@ pub(in crate::state) mod tests { } /// The sections a test holds, else the drawable's materials edited in place. - pub(in crate::state) fn held(doc: &Document) -> Option> { + pub(in crate::state) fn held( + doc: &Document, + gta6: &crate::state::gta6::session::Gta6Session, + ) -> Option> { let DocPayload::Gta6Drawable(_) = doc.payload else { return None; }; let sections = HELD.with(|held| held.borrow().clone()); - let edited = || crate::state::gta6_gltf_import::edited_save(doc); + let edited = || crate::state::gta6_gltf_import::edited_save(doc, gta6); super::held(sections.map(Ok)).or_else(edited) } diff --git a/src/state/gta6/bodies/gta6_save/mod.rs b/src/state/gta6/bodies/gta6_save/mod.rs index 8a9955349..9d3872495 100644 --- a/src/state/gta6/bodies/gta6_save/mod.rs +++ b/src/state/gta6/bodies/gta6_save/mod.rs @@ -38,12 +38,15 @@ struct Sealed { cipher: SaveCipher, } +/// Cached story-save cipher for the GTA VI executable set, scoped to a session. +#[derive(Clone, Default)] +pub(super) struct SaveCipherCache(Arc>>); + /// The story-save cipher of the GTA VI executable set, read once for each executable; `None` /// where none is set or the one set holds no cipher, as a PlayStation 5 dump's. -pub(crate) fn story_cipher() -> Option { - static HELD: Mutex> = Mutex::new(None); +pub(crate) fn story_cipher(bodies: &super::BodiesSession) -> Option { let exe = crate::state::rpf9_scan::rpf9_table::gta6_keys_flow::executable()?; - let mut held = HELD.lock().ok()?; + let mut held = bodies.save.0.lock().ok()?; if let Some((_, cipher)) = held.as_ref().filter(|(path, _)| *path == exe) { return Some(cipher.clone()); } @@ -82,12 +85,12 @@ pub(crate) fn is_save(bytes: &[u8]) -> bool { } /// The save `bytes` hold as a document; a packed copy is refused by its title and slot. -pub(crate) fn open(bytes: &[u8]) -> Result { +pub(crate) fn open(bodies: &super::BodiesSession, bytes: &[u8]) -> Result { // A console story save opens as its story where the executable set deciphers it and its tag // holds; any other record of that kind opens as the record it is. let sealed = (save::AsavHeader::read(bytes).ok()) .filter(|header| header.kind == save::AsavKind::StorySave) - .and_then(|_| story_cipher()) + .and_then(|_| story_cipher(bodies)) .and_then(|cipher| Some((StorySave::open(bytes, &cipher).ok()?, cipher))); if let Some((story, cipher)) = sealed { let doc = Gta6SaveDocument::sealed(story, cipher); @@ -598,7 +601,8 @@ mod tests { } fn document(bytes: &[u8]) -> Arc { - match open(bytes) { + let bodies = super::super::BodiesSession::default(); + match open(&bodies, bytes) { Ok(DocPayload::Gta6Save(doc)) => doc, Ok(other) => panic!("opened as {:?}", other.kind()), Err(e) => panic!("{e}"), @@ -677,7 +681,10 @@ mod tests { // A packed copy wraps a real record; opening it is refused, naming the slot it packs. let packed = save::Slayer1::write("", &record("{\"$v\":1}")).expect("a packed copy writes"); assert!(is_save(&packed)); - let refused = open(&packed).err().expect("a packed copy is refused"); + let bodies = super::super::BodiesSession::default(); + let refused = open(&bodies, &packed) + .err() + .expect("a packed copy is refused"); assert!(refused.contains("SAVE03"), "{refused}"); // A record whose payload is not JSON opens but shows no row and takes no edit. let opaque = document(&record("not json at all")); @@ -752,7 +759,7 @@ mod tests { fn an_edit_in_the_app_is_a_step_of_undo_and_marks_the_save_changed() { let bytes = story(); let mut state = AppState::new(); - let payload = open(&bytes).expect("a save"); + let payload = open(&state.gta6.bodies, &bytes).expect("a save"); let file = Some(PathBuf::from("SAVE01")); state .documents diff --git a/src/state/gta6/bodies/gta6_save/story_tests.rs b/src/state/gta6/bodies/gta6_save/story_tests.rs index 09758ad1e..96176b7df 100644 --- a/src/state/gta6/bodies/gta6_save/story_tests.rs +++ b/src/state/gta6/bodies/gta6_save/story_tests.rs @@ -86,7 +86,7 @@ fn sums(players: &Players) -> Vec { #[test] fn a_story_s_players_are_read_and_each_action_is_a_step_of_undo() { let mut state = AppState::new(); - let payload = open(&players_story()).expect("a save"); + let payload = open(&state.gta6.bodies, &players_story()).expect("a save"); let file = Some(PathBuf::from("SAVE01")); state .documents @@ -202,7 +202,7 @@ fn a_story_s_players_are_read_and_each_action_is_a_step_of_undo() { Some(DocPayload::Gta6Save(doc)) => doc.to_bytes().expect("writes"), _ => panic!("no save is open"), }; - let Ok(DocPayload::Gta6Save(again)) = open(&written) else { + let Ok(DocPayload::Gta6Save(again)) = open(&state.gta6.bodies, &written) else { panic!("the written save does not open"); }; assert_eq!(again.players, edited); @@ -283,7 +283,8 @@ fn a_console_story_save_opens_as_its_story_and_writes_back_a_file_its_cipher_ope return; }; let file0 = std::fs::read(PathBuf::from(dir).join("0")).expect("file 0"); - let Ok(payload @ DocPayload::Gta6Save(_)) = open(&file0) else { + let bodies = super::super::BodiesSession::default(); + let Ok(payload @ DocPayload::Gta6Save(_)) = open(&bodies, &file0) else { panic!("the story save does not open"); }; assert!(is_sealed(&payload)); diff --git a/src/state/gta6/bodies/mod.rs b/src/state/gta6/bodies/mod.rs index 4a0fa9c92..88819410f 100644 --- a/src/state/gta6/bodies/mod.rs +++ b/src/state/gta6/bodies/mod.rs @@ -1,6 +1,64 @@ +use std::path::PathBuf; +use std::sync::atomic::AtomicU64; +use std::sync::{Arc, Mutex}; + +use or_io::container::rpf::Rpf9Role; +use or_io::gta5::shaders::shader_defs::ShaderDefinitions; + pub(crate) mod gta6_meta_save; pub(crate) mod gta6_other_bodies; pub(crate) mod gta6_other_bodies_save; pub(crate) mod gta6_resource; pub(crate) mod gta6_resource_save; pub(crate) mod gta6_save; + +#[derive(Default)] +pub(super) struct EffectsCache { + pub(super) loaded_from: Option>, + pub(super) defs: Option, +} + +#[derive(Default)] +pub(super) struct KeptState { + pub(super) started_for: Option>, + pub(super) loaded_for: Option>, +} + +/// Per-session GTA VI effect database, learned counter and kept-file load state. +#[derive(Clone, Default)] +pub(super) struct EffectsSession { + pub(super) effects: Arc>, + pub(super) learned: Arc, + pub(super) kept_state: Arc>, +} + +/// Per-instance body, effect, save-cipher and MoVE-network caches owned by +/// [`crate::state::gta6::session::Gta6Session`]. +#[derive(Clone, Default)] +pub(crate) struct BodiesSession { + pub(super) effects: EffectsSession, + save: gta6_save::SaveCipherCache, + outlines: gta6_other_bodies::nodes::OutlinesCache, +} + +/// The role's name, or that it is not known. +pub(crate) fn role_name(role: Option) -> &'static str { + match role { + Some(Rpf9Role::Bound) => tr!("bound"), + Some(Rpf9Role::Drawable) => tr!("drawable"), + Some(Rpf9Role::Dictionary) => tr!("dictionary"), + Some(Rpf9Role::DrawableWithBound) => tr!("fragment"), + Some(Rpf9Role::NavMesh) => tr!("navigation mesh"), + Some(Rpf9Role::NavOctree) => tr!("navigation octree"), + Some(Rpf9Role::AccelerationStructure) => tr!("acceleration structure"), + Some(Rpf9Role::Cloth) => tr!("cloth"), + Some(Rpf9Role::MorphTarget) => tr!("morph target"), + Some(Rpf9Role::VertexBuffers) => tr!("vertex buffers"), + Some(Rpf9Role::KeyedBlob) => tr!("keyed blob"), + Some(Rpf9Role::KeyedBlobDescriptor) => tr!("keyed-blob descriptor"), + Some(Rpf9Role::AssetIndex) => tr!("asset index"), + Some(Rpf9Role::NeighbourTable) => tr!("neighbour table"), + Some(Rpf9Role::ParticleEffects) => tr!("particle effects"), + None => tr!("not known"), + } +} diff --git a/src/state/gta6/drawable/gta6_edit/mod.rs b/src/state/gta6/drawable/gta6_edit/mod.rs index 76c191ed9..65acc14c7 100644 --- a/src/state/gta6/drawable/gta6_edit/mod.rs +++ b/src/state/gta6/drawable/gta6_edit/mod.rs @@ -40,11 +40,11 @@ pub(crate) enum MaterialEdit { } /// The 32-bit name hash of the texture `key` names, where the app knows that name or a drawable or a typed name stated it. -pub(crate) fn named_word(key: u64) -> Option { - let known = crate::state::ttpf_document::known_name(key) +pub(crate) fn named_word(gta6: &crate::state::gta6::session::Gta6Session, key: u64) -> Option { + let known = crate::state::ttpf_document::known_name(>a6.ttpf, >a6.install, key) .filter(|name| name_hash64(name.as_bytes()) == key) .map(|name| name_hash32(name.as_bytes())); - known.or_else(|| crate::state::gta6_key_words::word(key)) + known.or_else(|| crate::state::gta6_key_words::word(>a6.install, key)) } /// The drawable `selection` shows of `resource`, by the code a save finds it under: `None` for its @@ -141,13 +141,14 @@ impl AppState { MaterialEdit::Constant { .. } => tr!("Set a material value").to_string(), MaterialEdit::TextureKey { key, .. } => tr!( "Bind {name}", - name = crate::state::gta6_resource::texture_name(*key) + name = crate::state::gta6_resource::texture_name(&self.gta6, *key) ), }; + let gta6 = self.gta6.clone(); let document = (self.document_mut(doc)).ok_or_else(|| tr!("its document is closed"))?; let stated = match (&edit, &document.payload) { (MaterialEdit::TextureKey { key, .. }, DocPayload::Gta6Drawable(resource)) => { - named_word(*key).is_some() + named_word(>a6, *key).is_some() || (shaders_of(resource).iter()) .filter(|(c, _)| *c == code) .flat_map(|(_, shaders)| shaders) @@ -182,6 +183,7 @@ pub(crate) fn is_scanned_dictionary(doc: &Document) -> bool { /// Texture `name` of the scanned GTA VI dictionary `doc` replaced from `image` in its own size, /// format and mips: the texture it held and what changed; `None` for any other document. pub(in crate::state) fn replace_scanned_texture( + ttpf: &crate::state::ttpf_document::TtpfSession, doc: &mut Document, name: &str, image: &RgbaImage, @@ -192,7 +194,7 @@ pub(in crate::state) fn replace_scanned_texture( return None; } // An array's or a cube's slice is replaced alone: the one the preview shows. - let shown = crate::state::ttpf_document::shown_scanned_slice(doc, name); + let shown = crate::state::ttpf_document::shown_scanned_slice(ttpf, doc, name); let slices = match &doc.payload { DocPayload::Resource(or_io::Asset::TextureDict(dict)) => dict.get(name), _ => None, @@ -325,7 +327,10 @@ pub(in crate::state) fn replaced( /// The GTA VI drawable and texture dictionary rows' `edited_sections` where `document` holds a GTA /// VI edit: its body read again on the worker and written over with the values it shows; `None` /// where it holds none. -pub(in crate::state) fn edited_save(document: &Document) -> Option> { +pub(in crate::state) fn edited_save( + document: &Document, + gta6: &crate::state::gta6::session::Gta6Session, +) -> Option> { if !document.history.can_undo() { return None; } @@ -335,11 +340,14 @@ pub(in crate::state) fn edited_save(document: &Document) -> Option DocumentId { } /// The texture key of `name`, which the app then knows by that name. -fn known(name: &str) -> u64 { +fn known(ttpf: &crate::state::ttpf_document::TtpfSession, name: &str) -> u64 { let key = or_io::gta6::hash::name_hash64(name.as_bytes()); - crate::state::ttpf_document::learn_named([(key, name.to_string())]); + crate::state::ttpf_document::learn_named(ttpf, [(key, name.to_string())]); key } @@ -143,7 +143,7 @@ fn a_material_edit_undoes_and_saves_as_a_loose_resource_that_reads_back_to_it() words: words.clone(), }; // A slot's key record states its key's name hash, so a bound slot takes a key the app names. - let other = known("edit_test_rebound"); + let other = known(&state.gta6.ttpf, "edit_test_rebound"); let bind = MaterialEdit::TextureKey { slot: 0, key: other, diff --git a/src/state/gta6/drawable/gta6_effects.rs b/src/state/gta6/drawable/gta6_effects.rs index 328e0bf62..239a60f8d 100644 --- a/src/state/gta6/drawable/gta6_effects.rs +++ b/src/state/gta6/drawable/gta6_effects.rs @@ -9,6 +9,7 @@ use std::sync::{Arc, Mutex}; use or_io::container::rpf::{read_rpf9_body, Rpf9ScanFind}; use or_job::{Cancel, Progress}; +use crate::state::gta6::bodies::BodiesSession; use crate::state::jobs::{file_name, JobKind, Outcome, RunningJob, Then}; use crate::state::{AppState, DocPayload}; @@ -30,7 +31,12 @@ pub struct EffectsRead { impl EffectsRead { /// Read the container `find` of `archive`, at most `limit` bytes, on a worker. - pub(in crate::state) fn start(archive: &Path, find: Rpf9ScanFind, limit: u64) -> Self { + pub(in crate::state) fn start( + bodies: BodiesSession, + archive: &Path, + find: Rpf9ScanFind, + limit: u64, + ) -> Self { let doing = tr!( "Reading the effects at {offset} of {archive}", offset = format!("{:#X}", find.offset), @@ -38,19 +44,23 @@ impl EffectsRead { ); let archive = archive.to_path_buf(); Self::run(doing, move |cancel, progress| { - effects(&archive, find, limit, cancel, progress) + effects(&bodies, &archive, find, limit, cancel, progress) }) } /// Read every `SGD5` container a scan of `archive` finds, at most `limit` bytes each, on a worker. - pub(in crate::state) fn every_container(archive: &Path, limit: u64) -> Self { + pub(in crate::state) fn every_container( + bodies: BodiesSession, + archive: &Path, + limit: u64, + ) -> Self { let doing = tr!( "Reading the effects of {archive}", archive = file_name(archive) ); let archive = archive.to_path_buf(); Self::run(doing, move |cancel, progress| { - every_container(&archive, limit, cancel, progress) + every_container(&bodies, &archive, limit, cancel, progress) }) } @@ -116,6 +126,7 @@ impl Drop for EffectsRead { /// The container's bytes read through a file that reports how far it has got and stops when asked. fn effects( + bodies: &BodiesSession, archive: &Path, find: Rpf9ScanFind, limit: u64, @@ -137,13 +148,14 @@ fn effects( } let platform = or_io::container::rpf::rpf9_platform_of(archive).unwrap_or(or_io::Platform::XboxSeries); - let count = crate::state::gta6_resource::learn_effects(&bytes, platform)?; + let count = crate::state::gta6_resource::learn_effects(bodies, &bytes, platform)?; crate::state::gta6_shaders::add_source(archive, find.offset, &bytes, platform); Ok(count) } /// The effects of each `SGD5` container a scan of `archive` finds, the scan's place its progress. fn every_container( + bodies: &BodiesSession, archive: &Path, limit: u64, cancel: &Cancel, @@ -164,7 +176,7 @@ fn every_container( if matches!(find.kind, Rpf9BodyKind::Sgd5 { .. }) { let (_, bytes) = read_rpf9_body(&file, find.offset, limit).map_err(|e| e.to_string())?; - learned += crate::state::gta6_resource::learn_effects(&bytes, platform)?; + learned += crate::state::gta6_resource::learn_effects(bodies, &bytes, platform)?; crate::state::gta6_shaders::add_source(archive, find.offset, &bytes, platform); } } @@ -229,7 +241,7 @@ impl AppState { let Some((_, root)) = crate::state::gta_vi::install(&self.prefs) else { return; }; - if !crate::state::gta6_resource::kept_effects_ready() { + if !crate::state::gta6_resource::kept_effects_ready(&self.gta6.bodies) { return; } let mut read = install_read(); @@ -237,8 +249,10 @@ impl AppState { return; } let archive = root.join("shaders.rpf"); - let start = !crate::state::gta6_resource::effects_known() && archive.is_file(); - let started = start.then(|| EffectsRead::every_container(&archive, 1 << 30)); + let start = + !crate::state::gta6_resource::effects_known(&self.gta6.bodies) && archive.is_file(); + let started = start + .then(|| EffectsRead::every_container(self.gta6.bodies.clone(), &archive, 1 << 30)); *read = Some((root.clone(), started)); } diff --git a/src/state/gta6/drawable/gta6_export.rs b/src/state/gta6/drawable/gta6_export.rs index d9b9602f2..0eb973a7b 100644 --- a/src/state/gta6/drawable/gta6_export.rs +++ b/src/state/gta6/drawable/gta6_export.rs @@ -19,6 +19,7 @@ pub(in crate::state) struct Gta6Export { skeleton: Option, /// Each texture a key of the drawable resolves to, by the name the key is known by. textures: Vec<(String, Texture<'static>)>, + gta6: crate::state::gta6::session::Gta6Session, } impl Gta6Export { @@ -37,7 +38,9 @@ impl Gta6Export { // A dictionary's entry is skinned to the skeleton it holds itself, where it holds one. Resource::Dictionary(_) => { let code = chosen.and_then(crate::state::SelectionKey::dict_hash); - code.and_then(|code| crate::state::gta6_entry_skeletons::of(path?, code)) + code.and_then(|code| { + crate::state::gta6_entry_skeletons::of(&state.gta6.anim, path?, code) + }) } _ => None, }; @@ -48,7 +51,7 @@ impl Gta6Export { .iter() .flat_map(|s| s.texture_keys.iter().flatten()) { - let name = texture_name(*key); + let name = texture_name(&state.gta6, *key); if textures.iter().any(|(n, _)| *n == name) { continue; } @@ -63,15 +66,18 @@ impl Gta6Export { chosen, skeleton, textures, + gta6: state.gta6.clone(), }) } /// The scene of the drawable chosen, named `stem`; `None` where none is chosen. pub(in crate::state) fn scene(&self, stem: &str, every_lod: bool) -> Option { let drawable = drawable_of(&self.body, self.chosen)?; + let effect = |hash| effect_name(&self.gta6.bodies, hash); + let texture = |key| texture_name(&self.gta6, key); let names = or_cli::Gta6Names { - effect: &effect_name, - texture: &texture_name, + effect: &effect, + texture: &texture, }; let mut scene = or_cli::gta6_scene(drawable, self.skeleton.as_ref(), stem, every_lod, &names); diff --git a/src/state/gta6/drawable/gta6_gltf_import/mod.rs b/src/state/gta6/drawable/gta6_gltf_import/mod.rs index f40905fad..9ccbe131b 100644 --- a/src/state/gta6/drawable/gta6_gltf_import/mod.rs +++ b/src/state/gta6/drawable/gta6_gltf_import/mod.rs @@ -306,8 +306,11 @@ impl AppState { /// The GTA VI drawable row's `edited_sections`: every other edit of the document, then each glTF /// import it holds made again over the body, oldest first. -pub(in crate::state) fn edited_save(document: &Document) -> Option> { - let save = crate::state::gta6_embedded_edit::edited_save(document)?; +pub(in crate::state) fn edited_save( + document: &Document, + gta6: &crate::state::gta6::session::Gta6Session, +) -> Option> { + let save = crate::state::gta6_embedded_edit::edited_save(document, gta6)?; let held = (document.path.as_deref()).and_then(|p| imports().get(p).cloned()); let Some(held) = held.filter(|h| !h.is_empty()) else { return Some(save); diff --git a/src/state/gta6/drawable/gta6_gltf_import/tests.rs b/src/state/gta6/drawable/gta6_gltf_import/tests.rs index 1fd4ec7cd..db680f76e 100644 --- a/src/state/gta6/drawable/gta6_gltf_import/tests.rs +++ b/src/state/gta6/drawable/gta6_gltf_import/tests.rs @@ -244,7 +244,7 @@ fn a_gltf_replaces_a_gta_vi_drawable_s_geometry_as_a_step_that_undoes_and_saves( // The body opened anew, as after a close that did not save, holds none of its imports. assert!(imports().contains_key(&path)); - crate::state::rpf9_scan::read_body(&path, &path, 0).expect("it opens again"); + crate::state::rpf9_scan::read_body(&state.gta6, &path, &path, 0).expect("it opens again"); assert!(!imports().contains_key(&path)); } diff --git a/src/state/gta6/drawable/gta6_head.rs b/src/state/gta6/drawable/gta6_head.rs index 2389d218b..150f3b0c2 100644 --- a/src/state/gta6/drawable/gta6_head.rs +++ b/src/state/gta6/drawable/gta6_head.rs @@ -91,6 +91,7 @@ pub(crate) fn head_of(path: &Path) -> Option { /// The texture `name` that the drawable `selection` shows binds by the key of a texture its own /// shader group embeds. pub(in crate::state) fn texture_named<'p>( + gta6: &crate::state::gta6::session::Gta6Session, payload: &'p DocPayload, selection: Option, name: &str, @@ -102,7 +103,7 @@ pub(in crate::state) fn texture_named<'p>( let key = (drawable.shaders.iter()) .flat_map(|s| s.texture_keys.iter().flatten()) .copied() - .find(|key| texture_name(*key).eq_ignore_ascii_case(name))?; + .find(|key| texture_name(gta6, *key).eq_ignore_ascii_case(name))?; let heads = heads(); // Only the head read with this very body: another of the same name may embed other pixels. let (path, head) = (heads.iter()) @@ -111,7 +112,7 @@ pub(in crate::state) fn texture_named<'p>( .find(|(_, head)| head.name == drawable.name)?; // What the document holds, a texture in any shape or none, is drawn in place of the body's. use crate::state::gta6_embedded_edit::Held; - let pixels = match crate::state::gta6_embedded_edit::edited(path, key) { + let pixels = match crate::state::gta6_embedded_edit::edited(>a6.textures, path, key) { Some(Held::Texture(texture)) => texture, Some(Held::Removed) => return None, None => { @@ -141,7 +142,10 @@ pub(in crate::state) fn texture_named<'p>( /// What the inspector says of a head: the object the physical section starts with, each texture /// the shader group embeds, each tint palette, and the vertex buffers no model lists. -pub(crate) fn head_lines(head: &Result) -> Vec { +pub(crate) fn head_lines( + gta6: &crate::state::gta6::session::Gta6Session, + head: &Result, +) -> Vec { let head = match head { Ok(head) => head, Err(e) => return vec![e.clone()], @@ -177,7 +181,7 @@ pub(crate) fn head_lines(head: &Result) -> Vec { let d = &t.texture; lines.push(tr!( "Its shader group embeds the texture {name} (hash_{hash} in its dictionary), {what}, of {mips} mips at p+{at}: a shader slot that binds its key draws it before any pack.", - name = texture_name(t.key), + name = texture_name(gta6, t.key), hash = format!("{:08X}", t.hash), what = format!("{}\u{00d7}{}, DXGI {}", d.width, d.height, d.format), mips = d.mip_levels, @@ -342,7 +346,8 @@ mod tests { unlisted_vertex_buffers: 0, }), ); - let found = texture_named(&opened, None, &texture_name(PAL_KEY)) + let gta6 = crate::state::gta6::session::Gta6Session::default(); + let found = texture_named(>a6, &opened, None, &texture_name(>a6, PAL_KEY)) .expect("palette key resolves to a 1D RGBA8 texture"); let Texture::Owned(grc) = found else { panic!("expected an owned GrcTexture"); diff --git a/src/state/gta6/drawable/gta6_selected.rs b/src/state/gta6/drawable/gta6_selected.rs index 1c172fe58..01e543e55 100644 --- a/src/state/gta6/drawable/gta6_selected.rs +++ b/src/state/gta6/drawable/gta6_selected.rs @@ -61,7 +61,11 @@ pub(crate) fn summary(name: &str, selection: SelectionKey) -> Option { /// What `doc`, a scanned GTA VI body, states of the part `selection` names; `None` where it names /// none, or one the body does not hold. -pub(crate) fn selected_rows(doc: &Document, selection: SelectionKey) -> Option { +pub(crate) fn selected_rows( + anim: &crate::state::gta6::anim::AnimSession, + doc: &Document, + selection: SelectionKey, +) -> Option { let DocPayload::Gta6Drawable(resource) = &doc.payload else { return None; }; @@ -70,7 +74,7 @@ pub(crate) fn selected_rows(doc: &Document, selection: SelectionKey) -> Option Option>> { /// Read and keep the parts of `read`, the body at `path` of `archive`, where its skeleton offers a /// point and the archive's names are kept; a body opened again keeps what this read finds. -pub(in crate::state) fn keep(path: &Path, archive: &Path, read: &Resource) { +pub(in crate::state) fn keep( + install: &crate::state::gta6::install::InstallSession, + path: &Path, + archive: &Path, + read: &Resource, +) { let parts = crate::state::rpf9_scan::scanned_skeleton(path) .ok() .zip(crate::state::gta6_resource::drawable_of(read, None)) .filter(|(skeleton, _)| !points(skeleton, Mat4::IDENTITY).is_empty()) .map(|(skeleton, drawable)| { - let labels = crate::state::gta6_names::labels(archive); + let labels = crate::state::gta6_names::labels(install, archive); let Ok(file) = File::open(archive) else { return Vec::new(); }; diff --git a/src/state/gta6/install/gta6_first_entry.rs b/src/state/gta6/install/gta6_first_entry.rs index c5f6e70bf..1190b4889 100644 --- a/src/state/gta6/install/gta6_first_entry.rs +++ b/src/state/gta6/install/gta6_first_entry.rs @@ -8,21 +8,28 @@ use std::collections::BTreeMap; use std::fs::{self, File}; use std::io::{ErrorKind, Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; -use std::sync::{Mutex, MutexGuard}; +use std::sync::{Arc, Mutex, MutexGuard}; use or_io::container::rpf::{rpf9_first_entry_end, Rpf9BodyKind, Rpf9ScanError, Rpf9ScanFind}; use or_job::{Cancel, Step}; +use super::InstallSession; use crate::state::document::HexDocument; use crate::state::rpf9_scan::{Ended, Found, Row}; /// Where each first entry whose end is not stated, and each nested archive, ends, by archive and /// offset, as its list gave it. -// ponytail: one map for the whole app, which no close empties; an install holds 15 such entries. -static GIVEN: Mutex> = Mutex::new(BTreeMap::new()); +#[derive(Clone, Default)] +pub(crate) struct FirstEntryState { + given: Arc>>, +} -fn given() -> MutexGuard<'static, BTreeMap<(PathBuf, u64), u64>> { - (GIVEN.lock()).unwrap_or_else(|poisoned| poisoned.into_inner()) +fn given(install: &InstallSession) -> MutexGuard<'_, BTreeMap<(PathBuf, u64), u64>> { + install + .first_entry + .given + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// Whether `find` is a first entry whose length the scan stated, so a read gives it an end. @@ -42,7 +49,12 @@ pub(in crate::state) fn banner(find: &Rpf9ScanFind) -> String { /// end is not stated ends where the list's next row starts, or at the file's end where a whole /// scan of the file lists none after it, and a nested archive where its names row ends. `false` /// where no row gives it one. -pub(in crate::state) fn note(archive: &Path, found: &Found, find: &Rpf9ScanFind) -> bool { +pub(in crate::state) fn note( + install: &InstallSession, + archive: &Path, + found: &Found, + find: &Rpf9ScanFind, +) -> bool { let rows = &found.rows; let end = match find.kind { Rpf9BodyKind::FirstEntry { .. } if !ends(find) => { @@ -70,13 +82,19 @@ pub(in crate::state) fn note(archive: &Path, found: &Found, find: &Rpf9ScanFind) let Some(end) = end else { return false; }; - given().insert((archive.to_path_buf(), find.offset), end); + given(install).insert((archive.to_path_buf(), find.offset), end); true } /// The end [`note`] gave the body at `offset` of `archive`, if it gave one. -pub(in crate::state) fn noted_end(archive: &Path, offset: u64) -> Option { - given().get(&(archive.to_path_buf(), offset)).copied() +pub(in crate::state) fn noted_end( + install: &InstallSession, + archive: &Path, + offset: u64, +) -> Option { + given(install) + .get(&(archive.to_path_buf(), offset)) + .copied() } /// The bytes copied at a time, between two looks for a stop. @@ -85,13 +103,14 @@ const SLICE: usize = 8 << 20; /// The body at `offset` of `archive` copied to `target` as `rel_path` to the end [`note`] gave /// it; `None` where it gave none, and the body is read as any other. pub(in crate::state) fn copied( + install: &InstallSession, archive: &Path, offset: u64, target: &Path, rel_path: &str, cancel: &Cancel, ) -> Option { - let end = noted_end(archive, offset)?; + let end = noted_end(install, archive, offset)?; Some(match copy_span(archive, offset, end, target, cancel) { Ok(len) => Step::Done(len), // A stop leaves no file, and the run counts it as the item it did not reach. @@ -157,13 +176,14 @@ fn copy(from: &mut impl Read, to: &Path, cancel: &Cancel) -> Result /// The bytes of the body at `offset` of `file`, the file at `archive`, that a read refused as /// `refused`, to the end [`note`] gave it, refused past `limit`; `None` where it gave none. pub(in crate::state) fn bytes( + install: &InstallSession, archive: &Path, file: &File, offset: u64, limit: u64, refused: &Rpf9ScanError, ) -> Option, String>> { - let end = match (noted_end(archive, offset), refused) { + let end = match (noted_end(install, archive, offset), refused) { (Some(end), _) => end, // No list gave it an end: the scan from the file's start gives the one its list would. (None, Rpf9ScanError::NoBodyAt { .. }) => match rpf9_first_entry_end(file, offset) { @@ -190,13 +210,14 @@ pub(in crate::state) fn bytes( /// The first entry at `offset` of `archive` read to the end [`note`] gave it: the find it is /// opened as and its bytes under why no view reads them; `None` where it gave none. pub(in crate::state) fn opened( + install: &InstallSession, archive: &Path, file: &File, offset: u64, limit: u64, refused: &Rpf9ScanError, ) -> Option> { - let bytes = match bytes(archive, file, offset, limit, refused)? { + let bytes = match bytes(install, archive, file, offset, limit, refused)? { Ok(bytes) => bytes, Err(e) => return Some(Err(e)), }; @@ -237,12 +258,13 @@ mod tests { let dir = tempfile::tempdir().expect("a scratch directory"); let archive = written(dir.path(), &bytes); let held = bytes[entry as usize..next as usize].to_vec(); + let fresh = InstallSession::default(); assert_eq!( - extracted_body(&archive, entry), + extracted_body(&fresh, &archive, entry), Ok(held.clone()), "with no list, a scan from the file's start gives it the end its list would" ); - assert!(extracted_body(&archive, entry + 16).is_err()); + assert!(extracted_body(&fresh, &archive, entry + 16).is_err()); let mut state = AppState::new(); let parent = scanned(&mut state, archive.clone()); let listed = rows(&state, parent); @@ -268,7 +290,10 @@ mod tests { "{}", hex.banner ); - assert_eq!(extracted_body(&archive, entry), Ok(held)); + assert_eq!( + extracted_body(&state.gta6.install, &archive, entry), + Ok(held) + ); let path = body_path(&archive, entry, View::Bytes); let origin = scan_origin(&path).map(|(find, _)| find.offset); assert_eq!(origin, Some(entry), "its origin is kept for the inspector"); @@ -311,7 +336,10 @@ mod tests { let nested = std::fs::read(out.join("0x1000.rpf")).expect("the nested archive"); assert_eq!(nested, bytes[NESTED as usize..names_end]); // Its end was noted, so the worker copied it as a range rather than reading it whole. - assert_eq!(noted_end(&archive, NESTED), Some(names_end as u64)); + assert_eq!( + noted_end(&state.gta6.install, &archive, NESTED), + Some(names_end as u64) + ); // The archive the list is of has no names row, so nothing is written of it. assert!(!out.join("0x0.rpf").exists()); } diff --git a/src/state/gta6/install/gta6_install_harvest.rs b/src/state/gta6/install/gta6_install_harvest.rs index d1ff1e9e2..1d23a1c21 100644 --- a/src/state/gta6/install/gta6_install_harvest.rs +++ b/src/state/gta6/install/gta6_install_harvest.rs @@ -17,6 +17,7 @@ use or_io::gta6::hash::name_hash64; use or_io::gta6::headerless::{Entry, Resource}; use or_io::gta6::texture_names::name_keys; +use super::InstallSession; use crate::state::gta6_dictionary_index::Built; use crate::state::gta6_install_scan::{lock, Hit, InstallFound}; use crate::state::gta6_texture_index::{put, stat, stated}; @@ -65,7 +66,7 @@ fn read_for_textures(hit: &Hit) -> bool { } /// The resource the body at `offset` of `file` reads to; `None` where it does not read. -fn body(file: &File, offset: u64) -> Option { +fn body(install: &InstallSession, file: &File, offset: u64) -> Option { let (find, bytes) = read_rpf9_body(file, offset, BODY_LIMIT).ok()?; let Rpf9BodyKind::Zlib(Rpf9ZlibRun { resource: Some(resource), @@ -77,7 +78,7 @@ fn body(file: &File, offset: u64) -> Option { }; let (virtual_section, physical) = resource.sections(&bytes); let read = or_io::gta6::headerless::read(signature, virtual_section, Some(physical)).ok()?; - crate::state::gta6_key_words::learn(signature, virtual_section, &read); + crate::state::gta6_key_words::learn(install, signature, virtual_section, &read); Some(read) } @@ -129,6 +130,7 @@ fn gathered( /// for these `keys`, its bodies of the hits beside it read and gathered for `keys`, and how many /// bodies read; with whether `cancel` stopped it, the archives read before the stop given. fn harvest( + install: &InstallSession, archives: Vec<(PathBuf, Vec)>, kept: &HashMap, keys: &HashSet, @@ -163,7 +165,7 @@ fn harvest( } progress.reached(done, total); done += 1; - let (Some(view), Some(resource)) = (hit.view, body(&file, hit.offset)) else { + let (Some(view), Some(resource)) = (hit.view, body(install, &file, hit.offset)) else { continue; }; read += 1; @@ -182,13 +184,17 @@ fn harvest( /// Serve through `built` the dictionaries of each archive of `kept` whose size and time stand, /// and learn the names their bodies gave; how many keys were named. -fn serve(kept: &HashMap, built: &Mutex>) -> usize { +fn serve( + ttpf: &crate::state::ttpf_document::TtpfSession, + kept: &HashMap, + built: &Mutex>, +) -> usize { let standing: Vec<&Harvested> = (kept.iter()) .filter(|(path, harvested)| stat(path) == Some(harvested.stat)) .map(|(_, harvested)| harvested) .collect(); let names = standing.iter().flat_map(|h| h.names.clone()); - let named = crate::state::ttpf_document::learn_named(names); + let named = crate::state::ttpf_document::learn_named(ttpf, names); let dictionaries = standing.iter().flat_map(|h| h.dictionaries.clone()); *built.lock().unwrap_or_else(|p| p.into_inner()) = Some(Built::of(dictionaries)); named @@ -301,9 +307,11 @@ impl AppState { return; }; let built = Arc::clone(&harvest.built); + let install = self.gta6.install.clone(); + let ttpf = self.gta6.ttpf.clone(); std::thread::spawn(move || { - crate::state::gta6_key_words::read_kept(); - serve(&read_kept(&file), &built) + crate::state::gta6_key_words::read_kept(&install); + serve(&ttpf, &read_kept(&file), &built) }); } @@ -328,6 +336,8 @@ impl AppState { }; let packs = crate::state::gta6_texture_index::pack_keys(root); let built = Arc::clone(&self.gta6_finders.texture_packs.dictionaries.harvest.built); + let install = self.gta6.install.clone(); + let ttpf = self.gta6.ttpf.clone(); let doing = tr!( "Reading the drawables and texture dictionaries of every GTA VI archive under {folder}", folder = root.display() @@ -337,16 +347,17 @@ impl AppState { return NamingEnded::Stopped; }; let mut kept = read_kept(&file); - let (harvested, read, stopped) = harvest(archives, &kept, &keys, cancel, progress); + let (harvested, read, stopped) = + harvest(&install, archives, &kept, &keys, cancel, progress); let changed = !harvested.is_empty(); kept.extend(harvested); if let Some(Err(error)) = changed.then(|| keep(&file, &kept)) { tracing::warn!(%error, "the harvest of the install's archives was not kept"); } if changed { - crate::state::gta6_key_words::keep(); + crate::state::gta6_key_words::keep(&install); } - let named = serve(&kept, &built); + let named = serve(&ttpf, &kept, &built); match stopped { true => NamingEnded::Stopped, false => NamingEnded::Harvested(read, named), diff --git a/src/state/gta6/install/gta6_install_scan.rs b/src/state/gta6/install/gta6_install_scan.rs index 3261b7eeb..ed29376a0 100644 --- a/src/state/gta6/install/gta6_install_scan.rs +++ b/src/state/gta6/install/gta6_install_scan.rs @@ -9,6 +9,7 @@ use std::time::Duration; use or_job::{Cancel, Progress}; +use super::InstallSession; use crate::state::jobs::{file_name, JobKind, Outcome, RunningJob, Then}; use crate::state::rpf9_scan::{ body_path, opens_as_bytes, Ended, Row, RowKind, Rpf9ScanDocument, View, @@ -65,11 +66,17 @@ impl Drop for InstallScan { } } -// ponytail: one scan for the whole app, of the folder it was last started for. -static INSTALL: Mutex> = Mutex::new(None); +#[derive(Clone, Default)] +pub(crate) struct InstallScanState { + install: Arc>>, +} -fn install() -> MutexGuard<'static, Option> { - INSTALL.lock().unwrap_or_else(|p| p.into_inner()) +fn install(session: &InstallSession) -> MutexGuard<'_, Option> { + session + .install_scan + .install + .lock() + .unwrap_or_else(|p| p.into_inner()) } pub(crate) fn lock(found: &Mutex) -> MutexGuard<'_, InstallFound> { @@ -77,7 +84,7 @@ pub(crate) fn lock(found: &Mutex) -> MutexGuard<'_, InstallFound> } /// Scan every archive under `root` on a worker, in place of the scan of any folder before. -pub(crate) fn start(root: &Path) { +pub(crate) fn start(session: &InstallSession, root: &Path) { let scan = InstallScan { root: root.to_path_buf(), cancel: Cancel::new(), @@ -85,42 +92,48 @@ pub(crate) fn start(root: &Path) { found: Arc::default(), said: false, }; - let (root, cancel, progress, found) = ( + let (root, cancel, progress, found, worker_session) = ( scan.root.clone(), scan.cancel.clone(), scan.progress.clone(), Arc::clone(&scan.found), + session.clone(), ); std::thread::spawn(move || { let ended = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - scan_every_archive(&root, &found, &cancel, &progress) + scan_every_archive(&worker_session, &root, &found, &cancel, &progress) })) .unwrap_or_else(|_| Ended::Failed("The install scan stopped unexpectedly".into())); lock(&found).ended = Some(ended); }); - *install() = Some(scan); + *install(session) = Some(scan); } /// What the scan of the archives under `root` has found, while it is the scan held. -pub(crate) fn found_under(root: &Path) -> Option>> { - let held = install(); +pub(crate) fn found_under( + session: &InstallSession, + root: &Path, +) -> Option>> { + let held = install(session); let scan = held.as_ref().filter(|scan| scan.root == root)?; Some(Arc::clone(&scan.found)) } -pub(crate) fn stop() { - if let Some(scan) = install().as_ref() { +pub(crate) fn stop(session: &InstallSession) { + if let Some(scan) = install(session).as_ref() { scan.cancel.set(); } } -pub(crate) fn stopping() -> bool { - install().as_ref().is_some_and(|scan| scan.cancel.is_set()) +pub(crate) fn stopping(session: &InstallSession) -> bool { + install(session) + .as_ref() + .is_some_and(|scan| scan.cancel.is_set()) } /// The scan while it runs, as the job list draws it. -pub(in crate::state) fn job() -> Option { - let held = install(); +pub(in crate::state) fn job(session: &InstallSession) -> Option { + let held = install(session); let scan = held.as_ref()?; let found = lock(&scan.found); if found.ended.is_some() { @@ -149,7 +162,7 @@ impl AppState { pub(in crate::state) fn poll_install_scan(&mut self) { self.read_kept_harvest(); let (told, harvest) = { - let mut held = install(); + let mut held = install(&self.gta6.install); let Some(scan) = held.as_mut().filter(|scan| !scan.said) else { return; }; @@ -198,6 +211,7 @@ impl AppState { /// Scan each archive under `root` as its own tab scans it, reading the scan kept of one already /// scanned and keeping a scan that reads one whole, and tally it into `found`. fn scan_every_archive( + session: &InstallSession, root: &Path, found: &Mutex, cancel: &Cancel, @@ -253,7 +267,7 @@ fn scan_every_archive( progress.reached(done + reached.min(size), total); std::thread::sleep(LOOK); } - let tally = tally_of(path, &scan, &mut held); + let tally = tally_of(session, path, &scan, &mut held); lock(found).archives.push(tally); done += size; progress.reached(done, total); @@ -266,7 +280,12 @@ fn scan_every_archive( /// How many rows of each kind `scan`, the ended scan of the archive at `path`, lists, and its /// bodies, while fewer than [`MOST_HITS`] are `held` in all. -fn tally_of(path: &Path, scan: &Rpf9ScanDocument, held: &mut usize) -> ArchiveTally { +fn tally_of( + session: &InstallSession, + path: &Path, + scan: &Rpf9ScanDocument, + held: &mut usize, +) -> ArchiveTally { let found = scan.found(); let (mut counts, mut hits) = (BTreeMap::new(), Vec::new()); for row in &found.rows { @@ -281,7 +300,7 @@ fn tally_of(path: &Path, scan: &Rpf9ScanDocument, held: &mut usize) -> ArchiveTa let view = match found.view(find) { Ok(view) => Some(view), Err(_) => (opens_as_bytes(find) - && crate::state::gta6_first_entry::note(path, &found, find)) + && crate::state::gta6_first_entry::note(session, path, &found, find)) .then_some(View::Bytes), }; hits.push(Hit { @@ -406,8 +425,9 @@ mod tests { .expect("written"); std::fs::write(dir.path().join("notes.txt"), vec![0u8; 0x400]).expect("written"); + let session = InstallSession::default(); let (found, cancel, progress) = (Mutex::default(), Cancel::new(), Progress::new()); - let ended = scan_every_archive(dir.path(), &found, &cancel, &progress); + let ended = scan_every_archive(&session, dir.path(), &found, &cancel, &progress); assert_eq!(ended, Ended::Whole); let found = lock(&found); assert_eq!(found.listed, Some(3)); @@ -440,7 +460,7 @@ mod tests { stopped.set(); let (none, progress) = (Mutex::default(), Progress::new()); assert_eq!( - scan_every_archive(dir.path(), &none, &stopped, &progress), + scan_every_archive(&session, dir.path(), &none, &stopped, &progress), Ended::Stopped ); assert!( diff --git a/src/state/gta6/install/gta6_key_words.rs b/src/state/gta6/install/gta6_key_words.rs index 48621a811..d383365b6 100644 --- a/src/state/gta6/install/gta6_key_words.rs +++ b/src/state/gta6/install/gta6_key_words.rs @@ -5,45 +5,52 @@ use std::collections::BTreeMap; use std::io; use std::path::PathBuf; -use std::sync::{Mutex, MutexGuard}; +use std::sync::{Arc, Mutex, MutexGuard}; use or_io::container::rpf::{seal_rpf9_scan, unseal_rpf9_scan, Rpf9Signature}; use or_io::gta6::hash::{name_hash32, name_hash64}; use or_io::gta6::headerless::{stated_words, Entry, Resource}; +use super::InstallSession; + /// The version of what the kept file holds: a change to it takes another. const VERSION: u64 = 1; /// The most a kept file inflates to, twelve bytes a key. const MOST_BYTES: usize = 1 << 28; -// ponytail: one map for the whole app, which no view empties. -static WORDS: Mutex> = Mutex::new(BTreeMap::new()); +#[derive(Clone, Default)] +pub(crate) struct KeyWordsState { + words: Arc>>, +} -fn words() -> MutexGuard<'static, BTreeMap> { - WORDS +fn words(install: &InstallSession) -> MutexGuard<'_, BTreeMap> { + install + .key_words + .words .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// The 32-bit name hash a drawable's key record or a typed name stated for texture `key`. -pub(crate) fn word(key: u64) -> Option { - words().get(&key).copied() +pub(crate) fn word(install: &InstallSession, key: u64) -> Option { + words(install).get(&key).copied() } /// Keep the hashes of the name `text`, where it is a name and not a `hash_` key. -pub(crate) fn typed(text: &str) { +pub(crate) fn typed(install: &InstallSession, text: &str) { let text = text.trim(); let hashed = text .get(..5) .is_some_and(|p| p.eq_ignore_ascii_case("hash_")); if !text.is_empty() && !hashed { - words().insert(name_hash64(text.as_bytes()), name_hash32(text.as_bytes())); + words(install).insert(name_hash64(text.as_bytes()), name_hash32(text.as_bytes())); } } /// Keep each word the key records of the drawables of `resource` state, read from /// `virtual_section` under `signature`. pub(in crate::state) fn learn( + install: &InstallSession, signature: Rpf9Signature, virtual_section: &[u8], resource: &Resource, @@ -62,7 +69,7 @@ pub(in crate::state) fn learn( let found: Vec<(u64, u32)> = (codes.into_iter()) .flat_map(|code| stated_words(virtual_section, role, code)) .collect(); - words().extend(found); + words(install).extend(found); } fn kept_file() -> Option { @@ -99,13 +106,13 @@ fn decode(sealed: &[u8]) -> io::Result> { } /// Keep every word learned in the configuration folder, with what was kept before. -pub(in crate::state) fn keep() { +pub(in crate::state) fn keep(install: &InstallSession) { let Some(file) = kept_file() else { return; }; // The kept words may not have been read yet this session; a key's word is one value. - read_kept(); - let plain = encode(&words()); + read_kept(install); + let plain = encode(&words(install)); let kept = seal_rpf9_scan(&plain).and_then(|sealed| { if let Some(folder) = file.parent() { std::fs::create_dir_all(folder)?; @@ -118,7 +125,7 @@ pub(in crate::state) fn keep() { } /// Learn the words kept in the configuration folder. -pub(in crate::state) fn read_kept() { +pub(in crate::state) fn read_kept(install: &InstallSession) { let Some(file) = kept_file() else { return; }; @@ -126,7 +133,7 @@ pub(in crate::state) fn read_kept() { return; }; match decode(&sealed) { - Ok(found) => words().extend(found), + Ok(found) => words(install).extend(found), Err(error) => tracing::info!("{}: {error}", file.display()), } } diff --git a/src/state/gta6/install/gta6_learned_names.rs b/src/state/gta6/install/gta6_learned_names.rs index 5306e37eb..f9a22e59f 100644 --- a/src/state/gta6/install/gta6_learned_names.rs +++ b/src/state/gta6/install/gta6_learned_names.rs @@ -9,19 +9,22 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; -use std::sync::{Mutex, OnceLock}; +use std::sync::{Arc, Mutex}; use or_io::container::rpf::{debug_name_from_virtual, Rpf9Kind}; +use super::InstallSession; + /// The learned-names store, keyed by `(archive file, body offset)`. -fn store() -> &'static Mutex> { - static STORE: OnceLock>> = OnceLock::new(); - STORE.get_or_init(Default::default) +#[derive(Clone, Default)] +pub(crate) struct LearnedNamesState { + store: Arc>>, } /// Keep the stated name of a body `virtual_section` is the virtual section of, where that kind /// carries one; `None` for a kind that does not state a name. Returns the stem that was kept. pub fn learn( + install: &InstallSession, archive: &Path, offset: u64, kind: Rpf9Kind, @@ -32,7 +35,9 @@ pub fn learn( if stem.is_empty() { return None; } - let mut store = store() + let mut store = install + .learned_names + .store .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); store @@ -42,8 +47,10 @@ pub fn learn( } /// The stem learned for the body at `offset` of `archive`, where one was kept; `None` otherwise. -pub fn lookup(archive: &Path, offset: u64) -> Option { - let store = store() +pub fn lookup(install: &InstallSession, archive: &Path, offset: u64) -> Option { + let store = install + .learned_names + .store .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); store.get(&(archive.to_path_buf(), offset)).cloned() diff --git a/src/state/gta6/install/gta6_names.rs b/src/state/gta6/install/gta6_names.rs index 635173505..5462ddce2 100644 --- a/src/state/gta6/install/gta6_names.rs +++ b/src/state/gta6/install/gta6_names.rs @@ -15,12 +15,11 @@ use or_io::gta6::names::{ use or_io::gta6::texture_names::{name_keys_by, parameter_name}; use or_job::{Cancel, Progress}; +use super::InstallSession; use crate::state::gta6_texture_naming::{NamingEnded, TextureNaming}; use crate::state::jobs::file_name; use crate::state::AppState; -static HELD: Mutex>> = Mutex::new(BTreeMap::new()); - /// The vocabulary served, and whether the kept one was asked for this session. #[derive(Default)] struct Served { @@ -28,22 +27,32 @@ struct Served { asked: bool, } -static SERVED: Mutex> = Mutex::new(None); -/// Whether a harvest runs, which the folder's bar says and one harvest at a time needs. -static HARVESTING: AtomicBool = AtomicBool::new(false); +#[derive(Clone, Default)] +pub(crate) struct NamesState { + held: Arc>>>, + served: Arc>>, + /// Whether a harvest runs, which the folder's bar says and one harvest at a time needs. + harvesting: Arc, + /// The textures the harvested archives' models name by key, once asked for. + uses: Arc>>>, +} -fn held() -> MutexGuard<'static, BTreeMap>> { - HELD.lock().unwrap_or_else(|p| p.into_inner()) +fn held(install: &InstallSession) -> MutexGuard<'_, BTreeMap>> { + install.names.held.lock().unwrap_or_else(|p| p.into_inner()) } -fn served() -> MutexGuard<'static, Option> { - SERVED.lock().unwrap_or_else(|p| p.into_inner()) +fn served(install: &InstallSession) -> MutexGuard<'_, Option> { + install + .names + .served + .lock() + .unwrap_or_else(|p| p.into_inner()) } /// The names kept of the bodies of `archive`, by offset; none where none were kept. // Read once an archive until a harvest ends, which forgets them all. -pub(crate) fn labels(archive: &Path) -> Arc { - let mut held = held(); +pub(crate) fn labels(install: &InstallSession, archive: &Path) -> Arc { + let mut held = held(install); if let Some(labels) = held.get(archive) { return labels.clone(); } @@ -55,27 +64,28 @@ pub(crate) fn labels(archive: &Path) -> Arc { } /// Add `more` to the names kept of the bodies of `archive`, by offset, for this session alone. -pub(crate) fn add_labels(archive: &Path, more: Labels) { - let mut all = (*labels(archive)).clone(); +pub(crate) fn add_labels(install: &InstallSession, archive: &Path, more: Labels) { + let mut all = (*labels(install, archive)).clone(); all.extend(more); - held().insert(archive.to_path_buf(), Arc::new(all)); + held(install).insert(archive.to_path_buf(), Arc::new(all)); } /// The vocabulary of every archive harvested: empty until the kept one is read, on a worker the /// first ask starts, since it holds every name. -pub(crate) fn vocabulary() -> Arc { - let mut slot = served(); +pub(crate) fn vocabulary(install: &InstallSession) -> Arc { + let mut slot = served(install); let served = slot.get_or_insert_with(Served::default); if !std::mem::replace(&mut served.asked, true) { let root = crate::state::prefs::config_root(); + let worker_install = install.clone(); std::thread::spawn(move || { let kept = root.map_or_else(Vocabulary::default, |root| { Vocabulary::load(&names::vocabulary_file(&root)) }); // A harvest that ended meanwhile serves more than the file read before it. let corpus = !corpus().is_empty(); - if (!kept.is_empty() || corpus) && vocabulary().is_empty() { - serve(kept); + if (!kept.is_empty() || corpus) && vocabulary(&worker_install).is_empty() { + serve(&worker_install, kept); } }); } @@ -94,39 +104,37 @@ fn corpus() -> &'static Vocabulary { } /// Serve `vocabulary` and the corpus from now on. -fn serve(mut vocabulary: Vocabulary) { +fn serve(install: &InstallSession, mut vocabulary: Vocabulary) { vocabulary.merge(corpus()); let now = Served { vocabulary: Arc::new(vocabulary), asked: true, }; - *served() = Some(now); + *served(install) = Some(now); // The textures the archives' models name are read again when next asked. - *uses_slot() = None; + *uses_slot(install) = None; } -/// The textures the harvested archives' models name by key, once asked for. -static USES: Mutex>> = Mutex::new(None); - -fn uses_slot() -> MutexGuard<'static, Option>> { - USES.lock().unwrap_or_else(|p| p.into_inner()) +fn uses_slot(install: &InstallSession) -> MutexGuard<'_, Option>> { + install.names.uses.lock().unwrap_or_else(|p| p.into_inner()) } /// The textures the models of every archive harvested name by key: none until the kept ones are /// read, on a worker the first ask starts, since a whole install's are some hundred thousand. // ponytail: a read that began before a harvest ended serves what it read after it; the harvest // after that, or a restart, serves the files as they are. -pub(crate) fn texture_uses() -> Arc { - let mut slot = uses_slot(); +pub(crate) fn texture_uses(install: &InstallSession) -> Arc { + let mut slot = uses_slot(install); if let Some(uses) = &*slot { return Arc::clone(uses); } let none = Arc::new(TextureUses::new()); *slot = Some(Arc::clone(&none)); if let Some(root) = crate::state::prefs::config_root() { + let worker_install = install.clone(); std::thread::spawn(move || { let kept = names::load_texture_uses(&root); - *uses_slot() = Some(Arc::new(kept)); + *uses_slot(&worker_install) = Some(Arc::new(kept)); }); } none @@ -134,8 +142,8 @@ pub(crate) fn texture_uses() -> Arc { /// What the texture `key` keys is used by, as [`said_use`] says it; `None` where no model of an /// archive harvested names the key. -pub(crate) fn texture_use_label(key: u64) -> Option { - texture_uses().get(&key).map(said_use) +pub(crate) fn texture_use_label(install: &InstallSession, key: u64) -> Option { + texture_uses(install).get(&key).map(said_use) } /// What a texture is used by, for one no name is known for: the first model a harvest found to @@ -171,8 +179,8 @@ pub(crate) fn used_by_model( } /// The name the 32-bit `hash` names alone in the vocabulary. -pub(crate) fn name32(hash: u32) -> Option { - vocabulary().name32(hash).map(str::to_string) +pub(crate) fn name32(install: &InstallSession, hash: u32) -> Option { + vocabulary(install).name32(hash).map(str::to_string) } /// What a 32-bit name hash of a GTA VI body is shown as: the name `vocabulary` holds for it alone, @@ -188,26 +196,26 @@ fn said32_in(vocabulary: &Vocabulary, hash: u32) -> String { } /// [`said32_in`] the vocabulary of every archive harvested. -pub(crate) fn said32(hash: u32) -> String { - said32_in(&vocabulary(), hash) +pub(crate) fn said32(install: &InstallSession, hash: u32) -> String { + said32_in(&vocabulary(install), hash) } /// The name the 64-bit `word` names in the vocabulary, else `hash_` and its digits. -pub(crate) fn said64(word: u64) -> String { - (vocabulary().name64(word)).map_or_else(|| format!("hash_{word:016X}"), str::to_string) +pub(crate) fn said64(install: &InstallSession, word: u64) -> String { + (vocabulary(install).name64(word)).map_or_else(|| format!("hash_{word:016X}"), str::to_string) } /// Whether a harvest runs now. -pub(crate) fn harvesting() -> bool { - HARVESTING.load(Ordering::Relaxed) +pub(crate) fn harvesting(install: &InstallSession) -> bool { + install.names.harvesting.load(Ordering::Relaxed) } /// Says no harvest runs once its worker ends, however it ends. -struct Harvesting; +struct Harvesting(Arc); impl Drop for Harvesting { fn drop(&mut self) { - HARVESTING.store(false, Ordering::Relaxed); + self.0.store(false, Ordering::Relaxed); } } @@ -276,6 +284,7 @@ fn harvest_into( /// rules give from each name it holds with none; how many keys were named, and whether `cancel` /// stopped it. fn name_textures( + ttpf: &crate::state::ttpf_document::TtpfSession, vocabulary: &Vocabulary, keys: &HashSet, cancel: &Cancel, @@ -283,7 +292,7 @@ fn name_textures( ) -> (usize, bool) { let spelled = (keys.iter()).filter_map(|key| Some((*key, vocabulary.name64(*key)?.to_string()))); - let mut named = crate::state::ttpf_document::learn_named(spelled); + let mut named = crate::state::ttpf_document::learn_named(ttpf, spelled); let (total, done) = (vocabulary.len() as u64, AtomicU64::new(0)); let go_on = |more: usize| { let more = more as u64; @@ -297,7 +306,7 @@ fn name_textures( true => name_keys_by(vocabulary.plain_names(), keys, plain, &go_on), }; let found = found.into_iter().map(|(key, (name, _))| (key, name)); - named += crate::state::ttpf_document::learn_named(found); + named += crate::state::ttpf_document::learn_named(ttpf, found); if cancel.is_set() { return (named, true); } @@ -315,7 +324,9 @@ impl AppState { )); return; }; - if HARVESTING.swap(true, Ordering::Relaxed) { + let install = self.gta6.install.clone(); + let ttpf = self.gta6.ttpf.clone(); + if install.names.harvesting.swap(true, Ordering::Relaxed) { return; } let packs = crate::state::gta6_texture_index::pack_keys(root); @@ -325,7 +336,7 @@ impl AppState { ); let root = root.to_path_buf(); let run = TextureNaming::run(doing, move |cancel, progress| { - let _running = Harvesting; + let _running = Harvesting(Arc::clone(&install.names.harvesting)); let archives = or_title::install::gta6_files::list(&root).archive_paths(); let file = names::vocabulary_file(&config); let mut vocabulary = Vocabulary::load(&file); @@ -347,12 +358,12 @@ impl AppState { true => None, false => packs(cancel, progress), }; - let named = keys.map(|keys| name_textures(&vocabulary, &keys, cancel, progress)); - serve(vocabulary); + let named = keys.map(|keys| name_textures(&ttpf, &vocabulary, &keys, cancel, progress)); + serve(&install, vocabulary); // The harvest wrote each archive's labels anew: they are read again when next asked. // ⚠ Not where the kept vocabulary is first read: that forgets the names a session // added, and a weapon opened after it finds no part. - self::held().clear(); + self::held(&install).clear(); match named { Some((keys, false)) => NamingEnded::Names { names: held, diff --git a/src/state/gta6/install/gta6_object_trees.rs b/src/state/gta6/install/gta6_object_trees.rs index 1aac2f3aa..f62318184 100644 --- a/src/state/gta6/install/gta6_object_trees.rs +++ b/src/state/gta6/install/gta6_object_trees.rs @@ -4,8 +4,13 @@ use std::collections::BTreeSet; use or_io::gta6::headerless::read_object_trees; +use super::InstallSession; + /// One line for the table, then one for each tree: its root's key and type, and what it points at. -pub(in crate::state) fn lines(bytes: &[u8]) -> Result, String> { +pub(in crate::state) fn lines( + install: &InstallSession, + bytes: &[u8], +) -> Result, String> { let trees = read_object_trees(bytes).map_err(|e| { tr!( "GTA VI's object-tree reader does not read this body: {e}", @@ -29,7 +34,7 @@ pub(in crate::state) fn lines(bytes: &[u8]) -> Result, String> { "{key}: a root of type {tag}, alone in its tree; it points at [{children}]", "{key}: a root of type {tag} and {count} objects in its tree; it points at [{children}]", tree.len(), - key = crate::state::gta6_names::said32(root.key), + key = crate::state::gta6_names::said32(install, root.key), tag = format!("{:#010X}", root.type_tag), children = children.join(", "), )); @@ -43,7 +48,8 @@ mod tests { #[test] fn a_body_the_reader_refuses_says_why_and_a_table_lists_one_line_a_tree() { - let why = lines(&[0; 0x40]).unwrap_err(); + let install = InstallSession::default(); + let why = lines(&install, &[0; 0x40]).unwrap_err(); assert!(why.contains("object-tree"), "{why}"); // A root keyed 0x0BADF00D of type 0xA1 over a child of type 0xB2, then a root of type 0xC3 // keyed by the hash of a name the public names hold. @@ -60,7 +66,7 @@ mod tests { let named = or_io::hash::literal_string_hash(b"CMapData"); body[0x80..0x84].copy_from_slice(&named.to_le_bytes()); body[0x88] = 0xC3; - let read = lines(&body).expect("the trees"); + let read = lines(&install, &body).expect("the trees"); assert_eq!(read.len(), 3); assert!(read[1].starts_with("hash_0BADF00D"), "{}", read[1]); assert!(read[1].contains("0x000000B2 (32 B)"), "{}", read[1]); diff --git a/src/state/gta6/install/gta6_small.rs b/src/state/gta6/install/gta6_small.rs index fecdac68f..15c298734 100644 --- a/src/state/gta6/install/gta6_small.rs +++ b/src/state/gta6/install/gta6_small.rs @@ -3,9 +3,11 @@ use or_io::gta6::headerless::{AssetIndex, KeyedBlobDescriptor, NeighbourTable}; +use super::InstallSession; + /// A 64-bit key by the name the harvested vocabulary holds for it, else `hash_` and its digits. -fn key_name(key: u64) -> String { - crate::state::gta6_names::said64(key) +fn key_name(install: &InstallSession, key: u64) -> String { + crate::state::gta6_names::said64(install, key) } /// A descriptor's key, stream length, pair and words. @@ -25,7 +27,11 @@ pub(in crate::state) fn descriptor_lines(d: &KeyedBlobDescriptor, lines: &mut Ve } /// An asset index's assets with their value records, then each key of tables 1 to 4 with its assets. -pub(in crate::state) fn index_lines(index: &AssetIndex, lines: &mut Vec) { +pub(in crate::state) fn index_lines( + install: &InstallSession, + index: &AssetIndex, + lines: &mut Vec, +) { lines.push(tr!( "An asset index of {assets} assets, each keyed by the 64-bit hash of its name. What an asset's value record holds is not known, so it is kept as it is.", assets = index.assets.len(), @@ -33,17 +39,17 @@ pub(in crate::state) fn index_lines(index: &AssetIndex, lines: &mut Vec) for (key, at) in &index.assets { lines.push(tr!( "Asset {key}: its value record at {at}.", - key = key_name(*key), + key = key_name(install, *key), at = format!("{at:#X}"), )); } for (t, group) in index.groups.iter().enumerate() { for (key, listed) in group { - let listed: Vec = listed.iter().map(|a| key_name(*a)).collect(); + let listed: Vec = listed.iter().map(|a| key_name(install, *a)).collect(); lines.push(tr!( "Table {table}, key {key}: the assets {assets}.", table = t + 1, - key = key_name(*key), + key = key_name(install, *key), assets = listed.join(", "), )); } diff --git a/src/state/gta6/install/mod.rs b/src/state/gta6/install/mod.rs index f74ca4392..44576447f 100644 --- a/src/state/gta6/install/mod.rs +++ b/src/state/gta6/install/mod.rs @@ -8,3 +8,18 @@ pub(crate) mod gta6_names; pub(crate) mod gta6_object_trees; pub(crate) mod gta6_small; pub(crate) mod gta_vi; + +#[derive(Clone, Default)] +pub(crate) struct InstallSession { + pub(crate) first_entry: gta6_first_entry::FirstEntryState, + pub(crate) install_scan: gta6_install_scan::InstallScanState, + pub(crate) key_words: gta6_key_words::KeyWordsState, + pub(crate) learned_names: gta6_learned_names::LearnedNamesState, + pub(crate) names: gta6_names::NamesState, +} + +impl std::fmt::Debug for InstallSession { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("InstallSession").finish_non_exhaustive() + } +} diff --git a/src/state/gta6/mod.rs b/src/state/gta6/mod.rs index 8da7c540f..76cd36304 100644 --- a/src/state/gta6/mod.rs +++ b/src/state/gta6/mod.rs @@ -8,5 +8,6 @@ pub(crate) mod install; pub(crate) mod modding; pub(crate) mod particles; pub(crate) mod physics; +pub(crate) mod session; pub(crate) mod textures; pub(crate) mod world; diff --git a/src/state/gta6/modding/batch_export.rs b/src/state/gta6/modding/batch_export.rs index 5f384f7a8..5567429e6 100644 --- a/src/state/gta6/modding/batch_export.rs +++ b/src/state/gta6/modding/batch_export.rs @@ -11,6 +11,7 @@ use or_io::container::rpf::gta6_kinds::Gta6Kind; use or_io::container::rpf::{RpfVersion, RPF9_MAGIC}; use or_job::{Cancel, Progress, Report, Snapshot}; +use super::ModdingSession; use crate::state::batch::Batch; use crate::state::jobs::JobKind; use crate::state::rpf_session::RpfEditSession; @@ -44,15 +45,25 @@ impl Gta6ExportChoice { /// What an export of `rows` of `session` walks: each GTA VI archive whole, each folder of one as /// its archive under the folder's path, each file of one as its row, labelled by its path in Files. -pub(crate) fn roots(session: &RpfEditSession, rows: &[RpfNodeId]) -> Vec { - rows.iter().filter_map(|&row| root(session, row)).collect() +pub(crate) fn roots( + modding: &ModdingSession, + session: &RpfEditSession, + rows: &[RpfNodeId], +) -> Vec { + rows.iter() + .filter_map(|&row| root(modding, session, row)) + .collect() } -fn root(session: &RpfEditSession, row: RpfNodeId) -> Option { +fn root( + modding: &ModdingSession, + session: &RpfEditSession, + row: RpfNodeId, +) -> Option { let node = session.node(row)?; match &node.backing { RpfNodeBacking::Archive { .. } => { - let (file, base) = mount_of(session, node)?; + let (file, base) = mount_of(modding, session, node)?; Some(Gta6BulkRoot { label: label_of(session, node, &file)?, file, @@ -63,7 +74,7 @@ fn root(session: &RpfEditSession, row: RpfNodeId) -> Option { } RpfNodeBacking::ArchiveDir { archive_id } => { let archive = holder(session, node, *archive_id)?; - let (file, base) = mount_of(session, archive)?; + let (file, base) = mount_of(modding, session, archive)?; let label = label_of(session, archive, &file)?; let (at, folder) = (session.path_of(archive.id)?, session.path_of(row)?); let inside = folder.strip_prefix(at.as_str())?.trim_start_matches('/'); @@ -129,7 +140,11 @@ fn holder<'a>( /// The file the GTA VI archive `node` is read from and where its header is in it; `None` for an /// archive of any other generation or held only in memory. -fn mount_of(session: &RpfEditSession, node: &RpfSessionNode) -> Option<(PathBuf, u64)> { +fn mount_of( + modding: &ModdingSession, + session: &RpfEditSession, + node: &RpfSessionNode, +) -> Option<(PathBuf, u64)> { let RpfNodeBacking::Archive { archive_id, source, .. } = &node.backing @@ -140,7 +155,7 @@ fn mount_of(session: &RpfEditSession, node: &RpfSessionNode) -> Option<(PathBuf, ArchiveSource::Disk(Some(path)) => { let rpf9 = match archive_id.and_then(|id| session.archive(id)) { Some(slot) => slot.archive.version == RpfVersion::Rpf9, - None => begins_rpf9(path), + None => begins_rpf9(modding, path), }; rpf9.then(|| (path.clone(), 0)) } @@ -150,7 +165,7 @@ fn mount_of(session: &RpfEditSession, node: &RpfSessionNode) -> Option<(PathBuf, .. } => { let parent = holder(session, node, *parent_archive_id)?; - let (file, base) = mount_of(session, parent)?; + let (file, base) = mount_of(modding, session, parent)?; let slot = session.archive(*parent_archive_id)?; let at = slot.archive.binary_entry(*parent_entry_index)?.file_offset; Some((file, base + at)) @@ -159,10 +174,16 @@ fn mount_of(session: &RpfEditSession, node: &RpfSessionNode) -> Option<(PathBuf, } } +#[derive(Clone, Default)] +pub(super) struct SeenRpf9Cache(std::sync::Arc>>); + /// Whether the file at `path` begins with an RPF9 header, read once per path: the menu asks every frame. -fn begins_rpf9(path: &Path) -> bool { - static SEEN: std::sync::Mutex> = std::sync::Mutex::new(BTreeMap::new()); - let mut seen = SEEN.lock().unwrap_or_else(|p| p.into_inner()); +fn begins_rpf9(modding: &ModdingSession, path: &Path) -> bool { + let mut seen = modding + .batch_export + .0 + .lock() + .unwrap_or_else(|p| p.into_inner()); *seen.entry(path.to_path_buf()).or_insert_with(|| { let mut head = [0u8; 4]; std::fs::File::open(path).is_ok_and(|mut file| file.read_exact(&mut head).is_ok()) @@ -178,7 +199,7 @@ impl AppState { fn gta6_export_roots(&self, doc: DocumentId, rows: &[RpfNodeId]) -> Vec { match self.document(doc).map(|d| &d.payload) { - Some(DocPayload::Rpf(rpf)) => roots(&rpf.session, rows), + Some(DocPayload::Rpf(rpf)) => roots(&self.gta6.modding, &rpf.session, rows), _ => Vec::new(), } } diff --git a/src/state/gta6/modding/mod.rs b/src/state/gta6/modding/mod.rs index d3c9274e0..f50873d46 100644 --- a/src/state/gta6/modding/mod.rs +++ b/src/state/gta6/modding/mod.rs @@ -12,3 +12,11 @@ pub(crate) mod references; pub(crate) mod text_search; pub(crate) mod texture_replace; pub(crate) mod typed_forms; + +/// Per-instance modding caches owned by [`crate::state::gta6::session::Gta6Session`]. +#[derive(Clone, Default)] +pub(crate) struct ModdingSession { + batch_export: batch_export::SeenRpf9Cache, + model_replace: model_replace::ModelReplaceCache, + text_search: text_search::TextSearchCache, +} diff --git a/src/state/gta6/modding/model_replace/mod.rs b/src/state/gta6/modding/model_replace/mod.rs index b1bb75d04..82a7a811f 100644 --- a/src/state/gta6/modding/model_replace/mod.rs +++ b/src/state/gta6/modding/model_replace/mod.rs @@ -14,8 +14,10 @@ use or_io::gta6::headerless::{ GeometryAt, HeaderlessError, }; +use super::ModdingSession; use crate::state::document::Document; use crate::state::edit_history::{Change, Swap}; +use crate::state::gta6::session::Gta6Session; use crate::state::gta6_edit::EditSections; use crate::state::gta6_resource_save::EditedSave; use crate::state::jobs::{JobKind, Outcome, Then}; @@ -33,14 +35,6 @@ struct Held { scene: Arc, } -/// The replaces made to each scanned body, by its document's path, oldest first. -// ponytail: one map for the whole app, as the glTF imports' is; an undo swaps a path's list. -static HELD: Mutex>> = Mutex::new(BTreeMap::new()); - -fn held() -> MutexGuard<'static, BTreeMap>> { - HELD.lock().unwrap_or_else(|p| p.into_inner()) -} - /// What a worker made: the geometry as the body reads back with it, the drawable's box, and what /// the replace says it wrote. type Made = ( @@ -59,16 +53,24 @@ struct Ended { made: Result, } -// ponytail: one list for the process; a poll takes the replaces of the documents its app holds. -static ENDED: Mutex> = Mutex::new(Vec::new()); +/// Per-session geometry replaces held per body and finished worker results. +#[derive(Clone, Default)] +pub(super) struct ModelReplaceCache { + held: Arc>>>, + ended: Arc>>, +} -fn ended() -> MutexGuard<'static, Vec> { - ENDED.lock().unwrap_or_else(|p| p.into_inner()) +fn held(modding: &ModdingSession) -> MutexGuard<'_, BTreeMap>> { + modding + .model_replace + .held + .lock() + .unwrap_or_else(|p| p.into_inner()) } /// Forget the replaces of the body at `path`, which opens anew with none. -pub(crate) fn forget(path: &Path) { - held().remove(path); +pub(crate) fn forget(modding: &ModdingSession, path: &Path) { + held(modding).remove(path); } fn how(h: &Held) -> or_cli::GeometryReplace { @@ -157,13 +159,14 @@ fn geometry_mut( /// A step's list of replaces of the body at `path`: the one the map does not hold now. struct Replaces { + modding: ModdingSession, path: PathBuf, other: Vec, } impl Swap for Replaces { fn swap(&mut self, _: &mut DocPayload) -> bool { - let mut map = held(); + let mut map = held(&self.modding); let now = map.entry(self.path.clone()).or_default(); std::mem::swap(now, &mut self.other); true @@ -172,9 +175,12 @@ impl Swap for Replaces { /// The GTA VI drawable row's `edited_sections`: every other edit of the document, its glTF imports /// included, then each geometry replace it holds made again over the body, oldest first. -pub(crate) fn edited_save(document: &Document) -> Option> { - let save = crate::state::gta6_gltf_import::edited_save(document)?; - let list = (document.path.as_deref()).and_then(|p| held().get(p).cloned()); +pub(crate) fn edited_save( + document: &Document, + gta6: &Gta6Session, +) -> Option> { + let save = crate::state::gta6_gltf_import::edited_save(document, gta6)?; + let list = (document.path.as_deref()).and_then(|p| held(>a6.modding).get(p).cloned()); let Some(list) = list.filter(|l| !l.is_empty()) else { return Some(save); }; @@ -232,7 +238,10 @@ impl AppState { let (archive, offset) = crate::state::rpf9_scan::scanned_body(&path) .map(|(archive, offset)| (archive.to_path_buf(), offset)) .ok_or_else(no_file)?; - let earlier = held().get(&path).cloned().unwrap_or_default(); + let earlier = held(&self.gta6.modding) + .get(&path) + .cloned() + .unwrap_or_default(); let name = crate::state::jobs::file_name(&mesh); self.show_toast(tr!( "Replacing geometry {geometry} of model {model}, level {level} from {mesh}", @@ -241,6 +250,7 @@ impl AppState { level = at.level, mesh = name )); + let ended_slot = Arc::clone(&self.gta6.modding.model_replace.ended); std::thread::spawn(move || { let read = std::fs::read(&mesh) .map_err(|e| tr!("{mesh} did not read: {e}", e = e, mesh = name)) @@ -264,21 +274,25 @@ impl AppState { } Err(why) => (Err(why), Arc::new(Scene::default())), }; - ended().push(Ended { - doc, - path, - mesh, - held: Held { code, at, scene }, - made: worked, - }); + ended_slot + .lock() + .unwrap_or_else(|p| p.into_inner()) + .push(Ended { + doc, + path, + mesh, + held: Held { code, at, scene }, + made: worked, + }); }); Ok(()) } /// Put each finished geometry replace into its document, or say why it was refused. pub(in crate::state) fn poll_gta6_geometry_replaces(&mut self) { + let ended_slot = Arc::clone(&self.gta6.modding.model_replace.ended); let done: Vec = { - let mut list = ended(); + let mut list = ended_slot.lock().unwrap_or_else(|p| p.into_inner()); let (mine, rest) = std::mem::take(&mut *list) .into_iter() .partition(|e| self.document(e.doc).is_some()); @@ -316,6 +330,7 @@ impl AppState { tr!("The geometry is not replaced while a task reads the body; replace it again once it ends.") }; let (code, at) = (new.code, new.at); + let modding = self.gta6.modding.clone(); let Some(document) = self.document_mut(doc) else { return; }; @@ -331,16 +346,22 @@ impl AppState { }; let min = std::mem::replace(&mut drawable.box_min, box_min); let max = std::mem::replace(&mut drawable.box_max, box_max); - let mut list = held().get(&path).cloned().unwrap_or_default(); + let mut list = held(&modding).get(&path).cloned().unwrap_or_default(); list.push(new); - let other = held().insert(path.clone(), list).unwrap_or_default(); + let other = held(&modding) + .insert(path.clone(), list) + .unwrap_or_default(); let mut change = Change::part("gta6 geometry replace", before, move |p| { geometry_mut(p, code, at) }) .and_part(min, move |p| drawable_mut(p, code).map(|d| &mut d.box_min)) .and_part(max, move |p| drawable_mut(p, code).map(|d| &mut d.box_max)); if let Change::Part { parts, .. } = &mut change { - parts.push(Box::new(Replaces { path, other })); + parts.push(Box::new(Replaces { + modding, + path, + other, + })); } self.record( doc, diff --git a/src/state/gta6/modding/model_replace/tests.rs b/src/state/gta6/modding/model_replace/tests.rs index f6f8952f7..cc6d15da6 100644 --- a/src/state/gta6/modding/model_replace/tests.rs +++ b/src/state/gta6/modding/model_replace/tests.rs @@ -201,17 +201,17 @@ fn a_geometry_replaced_in_the_app_is_a_step_that_undoes_and_a_save_makes_again() std::thread::sleep(Duration::from_millis(5)); state.poll_gta6_geometry_replaces(); } - assert_eq!(held().get(&path).map(Vec::len), Some(1)); + assert_eq!(held(&state.gta6.modding).get(&path).map(Vec::len), Some(1)); state.active_document = Some(doc); assert!(state.undo().is_some()); assert_eq!(shown(&state, doc), 3, "undone, it is as it opened"); - assert_eq!(held().get(&path).map(Vec::len), Some(0)); + assert_eq!(held(&state.gta6.modding).get(&path).map(Vec::len), Some(0)); assert!(state.redo().is_some()); assert_eq!(shown(&state, doc), 4); // The save's edit makes the replace again over the body read again. let document = state.document(doc).expect("open"); - let Some(Ok(EditedSave::Body { edit, .. })) = edited_save(document) else { + let Some(Ok(EditedSave::Body { edit, .. })) = edited_save(document, &state.gta6) else { panic!("a save of the body read again"); }; let mut sections = body(); @@ -222,6 +222,6 @@ fn a_geometry_replaced_in_the_app_is_a_step_that_undoes_and_a_save_makes_again() assert_eq!(g.vertex_count, 4); // The body opened anew holds none of its replaces. - crate::state::rpf9_scan::read_body(&path, &path, 0).expect("it opens again"); - assert!(!held().contains_key(&path)); + crate::state::rpf9_scan::read_body(&state.gta6, &path, &path, 0).expect("it opens again"); + assert!(!held(&state.gta6.modding).contains_key(&path)); } diff --git a/src/state/gta6/modding/text_search/mod.rs b/src/state/gta6/modding/text_search/mod.rs index bf35d6849..b6868063a 100644 --- a/src/state/gta6/modding/text_search/mod.rs +++ b/src/state/gta6/modding/text_search/mod.rs @@ -73,15 +73,18 @@ struct Running { progress: Progress, } -// ponytail: one search and one save at a time for the app; a new search takes the last one's place. -static RUNNING: Mutex> = Mutex::new(None); -static FOUND: Mutex> = Mutex::new(None); -/// How each archive of a save of edits ended, said once by the poll. -static SAVED: Mutex>> = Mutex::new(Vec::new()); -/// The body a line opened and the key to show in it, until its view is drawn. -static FOCUS: Mutex> = Mutex::new(None); - -fn lock(held: &'static Mutex) -> MutexGuard<'static, T> { +/// Per-session text search & text edit save state. +#[derive(Clone, Default)] +pub(super) struct TextSearchCache { + running: std::sync::Arc>>, + found: std::sync::Arc>>, + /// How each archive of a save of edits ended, said once by the poll. + saved: std::sync::Arc>>>, + /// The body a line opened and the key to show in it, until its view is drawn. + focus: std::sync::Arc>>, +} + +fn lock(held: &Mutex) -> MutexGuard<'_, T> { held.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) } @@ -91,18 +94,18 @@ fn busy() -> String { } /// What the last search found, which the view reads and edits. -pub(crate) fn found() -> MutexGuard<'static, Option> { - lock(&FOUND) +pub(crate) fn found(modding: &super::ModdingSession) -> MutexGuard<'_, Option> { + lock(&modding.text_search.found) } /// Whether a search or a save runs. -pub(crate) fn running() -> bool { - lock(&RUNNING).is_some() +pub(crate) fn running(modding: &super::ModdingSession) -> bool { + lock(&modding.text_search.running).is_some() } /// The key to show in the body opened at `path`, once: the one the line that opened it holds. -pub(crate) fn take_focus(path: &Path) -> Option { - let mut focus = lock(&FOCUS); +pub(crate) fn take_focus(modding: &super::ModdingSession, path: &Path) -> Option { + let mut focus = lock(&modding.text_search.focus); let key = focus .as_ref() .filter(|(at, _)| at == path) @@ -112,8 +115,8 @@ pub(crate) fn take_focus(path: &Path) -> Option { } /// The search or save running, as the job list draws it. -pub(in crate::state) fn job() -> Option { - let running = lock(&RUNNING); +pub(in crate::state) fn job(modding: &super::ModdingSession) -> Option { + let running = lock(&modding.text_search.running); let run = running.as_ref()?; let now = run.progress.snapshot(); Some(RunningJob { @@ -126,15 +129,15 @@ pub(in crate::state) fn job() -> Option { } /// Ask the search or save running to stop: it ends at the next table. -pub(in crate::state) fn stop() { - if let Some(run) = lock(&RUNNING).as_ref() { +pub(in crate::state) fn stop(modding: &super::ModdingSession) { + if let Some(run) = lock(&modding.text_search.running).as_ref() { run.cancel.set(); } } /// The languages a change set registers, as the dialogue index read them; none where it has not. -fn registered_languages() -> Vec { - let languages = crate::state::gta6_dialogue::lines().languages(); +fn registered_languages(audio: &crate::state::gta6::audio::AudioSession) -> Vec { + let languages = crate::state::gta6_dialogue::lines(audio).languages(); languages .into_iter() .filter(|l| !l.starts_with('#')) @@ -375,7 +378,7 @@ impl AppState { doc_id: DocumentId, query: &str, ) -> Result<(), String> { - if running() { + if running(&self.gta6.modding) { return Err(busy()); } let parsed = TextQuery::new(query); @@ -388,14 +391,15 @@ impl AppState { ); why.to_string() })?; - let registered = registered_languages(); - *lock(&FOUND) = Some(Searched { + let registered = registered_languages(&self.gta6.audio); + let cache = self.gta6.modding.text_search.clone(); + *lock(&cache.found) = Some(Searched { query: query.trim().to_string(), root: root.clone(), ..Searched::default() }); let (cancel, progress) = (Cancel::new(), Progress::new()); - *lock(&RUNNING) = Some(Running { + *lock(&cache.running) = Some(Running { doing: tr!( "Searching every GTA VI text table under {folder}", folder = root.display() @@ -422,7 +426,7 @@ impl AppState { ) })) .unwrap_or_else(|_| Err(tr!("It stopped on an internal error").to_string())); - if let Some(held) = lock(&FOUND).as_mut() { + if let Some(held) = lock(&cache.found).as_mut() { held.stopped = cancel.is_set(); match ran { Ok(searched) => { @@ -435,7 +439,7 @@ impl AppState { Err(why) => held.ended = Some(Err(why)), } } - *lock(&RUNNING) = None; + *lock(&cache.running) = None; }); Ok(()) } @@ -458,7 +462,7 @@ impl AppState { rpf9_table::keys, None, ); - *lock(&FOCUS) = Some((path.clone(), key)); + *lock(&self.gta6.modding.text_search.focus) = Some((path.clone(), key)); self.load_file(path); } @@ -466,15 +470,15 @@ impl AppState { /// a worker: each table into its own row, each archive into one copy. `Err` says why it did not /// start, except a refusal of the write gate, which says so itself. pub(crate) fn save_gta6_text_edits(&mut self, folder: PathBuf) -> Result<(), String> { - if running() { + if running(&self.gta6.modding) { return Err(busy()); } - let searched = found().as_ref().map(|s| s.root.clone()); + let searched = found(&self.gta6.modding).as_ref().map(|s| s.root.clone()); // ⚠ The folder searched is the game's even with no title's marker, which the gate cannot see. if searched.is_some_and(|root| super::mod_package::inside(&root, &folder)) { return Err(super::mod_package::in_game_folder(&folder)); } - let edits: Vec = (found() + let edits: Vec = (found(&self.gta6.modding) .as_ref() .map(|s| s.groups.as_slice()) .unwrap_or_default()) @@ -498,8 +502,9 @@ impl AppState { GateOutcome::Refused => return Ok(()), GateOutcome::Confirm(_) => return Err(super::mod_package::in_game_folder(&folder)), } + let cache = self.gta6.modding.text_search.clone(); let (cancel, progress) = (Cancel::new(), Progress::new()); - *lock(&RUNNING) = Some(Running { + *lock(&cache.running) = Some(Running { doing: tr!("Saving the edited GTA VI texts into new copies of their archives") .to_string(), cancel, @@ -517,7 +522,7 @@ impl AppState { for (archive, ended) in archives { match ended { Ok((out, saved)) => { - saved_edits(&archive, &edits); + saved_edits(&cache, &archive, &edits); said.push(Ok(saved_said(&out, &saved))); } Err(why) => said.push(Err(tr!( @@ -530,8 +535,8 @@ impl AppState { } Err(why) => said.push(Err(why)), } - lock(&SAVED).extend(said); - *lock(&RUNNING) = None; + lock(&cache.saved).extend(said); + *lock(&cache.running) = None; }); Ok(()) } @@ -539,7 +544,7 @@ impl AppState { /// Say in the job list how the last search ended, once, and each save of edits in a toast. pub(in crate::state) fn poll_gta6_text_search(&mut self) { let told = { - let mut found = found(); + let mut found = found(&self.gta6.modding); match found.as_mut() { Some(s) if !s.said && s.ended.is_some() => { s.said = true; @@ -566,7 +571,8 @@ impl AppState { }; self.jobs.record(JobKind::TextSearch, outcome, said); } - let saved: Vec> = std::mem::take(&mut *lock(&SAVED)); + let saved: Vec> = + std::mem::take(&mut *lock(&self.gta6.modding.text_search.saved)); for said in saved { match said { Ok(said) => self.show_toast(said), @@ -578,8 +584,8 @@ impl AppState { /// The lines of `archive` saved as `edits` wrote them: each takes the text written, and keeps an /// edit typed since that differs from it. -fn saved_edits(archive: &Path, edits: &[Edit]) { - let mut found = found(); +fn saved_edits(cache: &TextSearchCache, archive: &Path, edits: &[Edit]) { + let mut found = lock(&cache.found); let Some(searched) = found.as_mut() else { return; }; diff --git a/src/state/gta6/modding/text_search/tests.rs b/src/state/gta6/modding/text_search/tests.rs index 08376fc40..cbe619c18 100644 --- a/src/state/gta6/modding/text_search/tests.rs +++ b/src/state/gta6/modding/text_search/tests.rs @@ -155,7 +155,7 @@ fn a_text_search_is_a_job_the_list_shows_and_stops() { let _serial = crate::ui::theme::serial(); let mut state = AppState::new(); let (cancel, progress) = (Cancel::new(), Progress::new()); - *lock(&RUNNING) = Some(Running { + *lock(&state.gta6.modding.text_search.running) = Some(Running { doing: "searching".into(), cancel: cancel.clone(), progress, @@ -164,7 +164,7 @@ fn a_text_search_is_a_job_the_list_shows_and_stops() { assert!(listed.iter().any(|job| job.kind == JobKind::TextSearch)); state.cancel_job(JobKind::TextSearch); assert!(cancel.is_set(), "the list's stop reaches the worker"); - *lock(&RUNNING) = None; + *lock(&state.gta6.modding.text_search.running) = None; assert!(!state .running_jobs() .iter() @@ -174,5 +174,5 @@ fn a_text_search_is_a_job_the_list_shows_and_stops() { assert!(state .search_gta6_texts(crate::state::DocumentId(0), " ") .is_err()); - assert!(!running()); + assert!(!running(&state.gta6.modding)); } diff --git a/src/state/gta6/particles/gta6_particle_models.rs b/src/state/gta6/particles/gta6_particle_models.rs index 42429ddd8..c7390c790 100644 --- a/src/state/gta6/particles/gta6_particle_models.rs +++ b/src/state/gta6/particles/gta6_particle_models.rs @@ -15,6 +15,7 @@ use or_io::gta6::headerless::{read_dictionary, Drawable, Entry, ParticleEffects} use or_job::{Cancel, Progress}; use or_simulation::domain_mesh::DomainMesh; +use super::ParticlesSession; use crate::state::gta6_set_finding::FindEnded; use crate::state::jobs::{JobKind, Outcome, RunningJob, Then}; use crate::state::rpf9_scan::scanned_body; @@ -33,12 +34,15 @@ pub(crate) struct Named { pub domains: BTreeMap; 3]>, } -// ponytail: one entry per scanned list opened and per drawable or surface found, never emptied, as the list's lines are. -static KEPT: Mutex>> = Mutex::new(BTreeMap::new()); -static FOUND: Mutex>> = Mutex::new(BTreeMap::new()); -static SURFACES: Mutex>> = Mutex::new(BTreeMap::new()); +/// Per-session particle model caches: named models per list, found drawables, and built mesh surfaces. +#[derive(Clone, Default)] +pub(super) struct ParticleModelsCache { + kept: Arc>>>, + found: Arc>>>, + surfaces: Arc>>>, +} -fn lock(held: &'static Mutex) -> MutexGuard<'static, T> { +fn lock(held: &Mutex) -> MutexGuard<'_, T> { held.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) } @@ -64,28 +68,28 @@ pub(crate) fn named(list: &ParticleEffects) -> Named { } /// Keep what `list`, opened from `path`, names. -pub(in crate::state) fn keep(path: &Path, list: &ParticleEffects) { - lock(&KEPT).insert(path.to_path_buf(), Arc::new(named(list))); +pub(in crate::state) fn keep(particles: &ParticlesSession, path: &Path, list: &ParticleEffects) { + lock(&particles.models.kept).insert(path.to_path_buf(), Arc::new(named(list))); } /// What the list opened from `path` names, if a GTA VI list opened from it. -pub(crate) fn kept(path: &Path) -> Option> { - lock(&KEPT).get(path).cloned() +pub(crate) fn kept(particles: &ParticlesSession, path: &Path) -> Option> { + lock(&particles.models.kept).get(path).cloned() } /// How many drawables the searches have found, which grows as one finds more. -pub(crate) fn found_count() -> usize { - lock(&FOUND).len() +pub(crate) fn found_count(particles: &ParticlesSession) -> usize { + lock(&particles.models.found).len() } /// Whether the list opened from `path` names a drawable or a mesh domain's model. -pub(crate) fn names_drawables(path: &Path) -> bool { - kept(path).is_some_and(|named| !named.wanted.is_empty()) +pub(crate) fn names_drawables(particles: &ParticlesSession, path: &Path) -> bool { + kept(particles, path).is_some_and(|named| !named.wanted.is_empty()) } /// The drawable of name hash `hash` a search found, if one did. -pub(crate) fn found_drawable(hash: u32) -> Option> { - lock(&FOUND).get(&hash).cloned() +pub(crate) fn found_drawable(particles: &ParticlesSession, hash: u32) -> Option> { + lock(&particles.models.found).get(&hash).cloned() } /// The triangles of the first level of `drawable` that holds models, in the drawable's frame; a @@ -106,19 +110,20 @@ fn triangles(drawable: &Drawable) -> Vec<[Vec3; 3]> { } /// The surface of the model of name hash `hash`, once a search found it and it covers an area. -fn surface(hash: u32) -> Option> { - if let Some(surface) = lock(&SURFACES).get(&hash) { +fn surface(particles: &ParticlesSession, hash: u32) -> Option> { + if let Some(surface) = lock(&particles.models.surfaces).get(&hash) { return Some(Arc::clone(surface)); } - let drawable = found_drawable(hash)?; + let drawable = found_drawable(particles, hash)?; let surface = Arc::new(DomainMesh::new(triangles(&drawable))?); - lock(&SURFACES).insert(hash, Arc::clone(&surface)); + lock(&particles.models.surfaces).insert(hash, Arc::clone(&surface)); Some(surface) } /// The surface of the model `hash` names for a domain of shape `shape`, where that is a mesh. -fn mesh_of(shape: i32, hash: Option) -> Option> { - hash.filter(|_| shape == MESH).and_then(surface) +fn mesh_of(particles: &ParticlesSession, shape: i32, hash: Option) -> Option> { + hash.filter(|_| shape == MESH) + .and_then(|h| surface(particles, h)) } /// The drawables of `wanted`'s name hashes the dictionary at `offset` of `file` holds, if it is one. @@ -155,7 +160,11 @@ pub(in crate::state) struct ModelFinding { impl ModelFinding { /// Read the dictionary bodies `bodies` until every drawable of `wanted` is found, on a worker. - fn start(bodies: Vec, mut wanted: BTreeSet) -> Self { + fn start( + found: Arc>>>, + bodies: Vec, + mut wanted: BTreeSet, + ) -> Self { let finding = Self { cancel: Cancel::new(), progress: Progress::new(), @@ -192,7 +201,7 @@ impl ModelFinding { }; for (code, drawable) in drawables_at(file, offset, &wanted) { wanted.remove(&code); - lock(&FOUND).insert(code, Arc::new(drawable)); + lock(&found).insert(code, Arc::new(drawable)); } } match stopped { @@ -246,10 +255,10 @@ impl AppState { /// among the dictionaries the open archives' whole scans found. pub(crate) fn find_gta6_particle_models(&mut self, doc: DocumentId) -> Result<(), String> { let path = self.document(doc).and_then(|d| d.path.as_deref()); - let Some(named) = path.and_then(kept) else { + let Some(named) = path.and_then(|p| kept(&self.gta6.particles, p)) else { return Ok(()); }; - let missing = |hash: &u32| found_drawable(*hash).is_none(); + let missing = |hash: &u32| found_drawable(&self.gta6.particles, *hash).is_none(); let wanted: BTreeSet = named.wanted.iter().copied().filter(missing).collect(); if wanted.is_empty() { return Ok(()); @@ -260,7 +269,11 @@ impl AppState { tr!("Open the whole scan of an archive to look for the drawables in.").to_string(), ); } - self.gta6_finders.particle_model_finding = Some(ModelFinding::start(bodies, wanted)); + self.gta6_finders.particle_model_finding = Some(ModelFinding::start( + Arc::clone(&self.gta6.particles.models.found), + bodies, + wanted, + )); Ok(()) } @@ -302,8 +315,9 @@ impl AppState { /// Each emitter takes its rule's third spawner too, and every effect spawned later its own. pub(in crate::state) fn give_gta6_domain_meshes(&mut self, doc: DocumentId) { let path = self.document(doc).and_then(|d| d.path.as_deref()); - let spawners = path.and_then(crate::state::gta6_particles::spawners::of); - let named = path.and_then(kept); + let particles = &self.gta6.particles; + let spawners = path.and_then(|p| crate::state::gta6_particles::spawners::of(particles, p)); + let named = path.and_then(|p| kept(particles, p)); let manager = &mut self.sim.manager; manager.zcull_spawners = spawners.map(|s| (*s).clone()).unwrap_or_default(); let effects = (manager.effect.iter_mut()).chain(manager.spawned_effects.iter_mut()); @@ -317,13 +331,15 @@ impl AppState { for emitter in effects.flat_map(|e| e.emitters.iter_mut()) { let models = named.domains.get(&emitter.rules.rule.name); let [creation, target, attractor] = models.copied().unwrap_or_default(); - emitter.creation_domain.mesh = mesh_of(emitter.rules.creation_domain.shape, creation); - emitter.velocity_domain.mesh = mesh_of(emitter.rules.velocity_domain.shape, target); + emitter.creation_domain.mesh = + mesh_of(particles, emitter.rules.creation_domain.shape, creation); + emitter.velocity_domain.mesh = + mesh_of(particles, emitter.rules.velocity_domain.shape, target); if let Some(rule) = &emitter.rules.attractor_domain { let inst = emitter .attractor_domain .get_or_insert_with(Default::default); - inst.mesh = mesh_of(rule.shape, attractor); + inst.mesh = mesh_of(particles, rule.shape, attractor); } } } @@ -331,8 +347,8 @@ impl AppState { /// Hold `drawable` as a search would have found it under `hash`. #[cfg(test)] -pub(crate) fn found_for_tests(hash: u32, drawable: Drawable) { - lock(&FOUND).insert(hash, Arc::new(drawable)); +pub(crate) fn found_for_tests(particles: &ParticlesSession, hash: u32, drawable: Drawable) { + lock(&particles.models.found).insert(hash, Arc::new(drawable)); } /// A drawable of one triangle in its first level, in a box from the origin to `box_max`. diff --git a/src/state/gta6/particles/gta6_particles/mod.rs b/src/state/gta6/particles/gta6_particles/mod.rs index fa1b7e459..63450669c 100644 --- a/src/state/gta6/particles/gta6_particles/mod.rs +++ b/src/state/gta6/particles/gta6_particles/mod.rs @@ -17,6 +17,7 @@ use or_io::gta6::headerless::{ ParticleEffects, ParticleRule, SpawnedScalars, Spawner, DOMAIN_KFPS, EFFECT_KFPS, EMITTER_KFPS, }; +use super::ParticlesSession; use crate::state::DocPayload; pub(crate) mod sprites; @@ -36,17 +37,22 @@ const GTA5_ZCULL_MODES: i32 = 3; /// The size of the behaviour that opens most rules' lists, which no keyframed value classes. const FIRST_BEHAVIOUR: u64 = 0x10; -// ponytail: one entry per scanned list opened, never emptied, as the scanned cells are. -static SCANNED: Mutex>>> = Mutex::new(BTreeMap::new()); +#[derive(Clone, Default)] +pub(in crate::state::gta6::particles) struct ScannedParticlesCache( + Arc>>>>, +); -fn scanned() -> MutexGuard<'static, BTreeMap>>> { - SCANNED +fn scanned(particles: &ParticlesSession) -> MutexGuard<'_, BTreeMap>>> { + particles + .scanned + .0 .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// A scanned particle effects list as GTA V's, where it reads; its own lines are kept for `path`. pub(in crate::state) fn opened( + particles: &ParticlesSession, path: &Path, signature: Rpf9Signature, resource: &Rpf9Resource, @@ -59,16 +65,16 @@ pub(in crate::state) fn opened( let list = read_particle_effects(virtual_section, Some(physical)).ok()?; let mut ypt = as_ypt(&list); or_particle::list::canonical(&mut ypt); - scanned().insert(path.to_path_buf(), Arc::new(lines(&list))); - sprites::keep(path, &list); - spawners::keep(path, &list); - crate::state::gta6_particle_models::keep(path, &list); + scanned(particles).insert(path.to_path_buf(), Arc::new(lines(&list))); + sprites::keep(particles, path, &list); + spawners::keep(particles, path, &list); + crate::state::gta6_particle_models::keep(particles, path, &list); Some(DocPayload::Resource(or_io::Asset::Particles(ypt))) } /// The lines of the GTA VI list the document at `path` opened from; `None` for any other. -pub(crate) fn scanned_lines(path: &Path) -> Option>> { - scanned().get(path).cloned() +pub(crate) fn scanned_lines(particles: &ParticlesSession, path: &Path) -> Option>> { + scanned(particles).get(path).cloned() } /// Whether `doc` is a scanned GTA VI list, saved in place, so no rule is made in it from nothing. @@ -77,7 +83,7 @@ pub(crate) fn written_in_place( doc: crate::state::DocumentId, ) -> bool { let path = state.document(doc).and_then(|d| d.path.as_deref()); - path.is_some_and(|p| scanned_lines(p).is_some()) + path.is_some_and(|p| scanned_lines(&state.gta6.particles, p).is_some()) } /// The list as GTA V's, its rules in their dictionaries and named by the events and spawners. diff --git a/src/state/gta6/particles/gta6_particles/spawners.rs b/src/state/gta6/particles/gta6_particles/spawners.rs index 879707bd9..4acf5f8c7 100644 --- a/src/state/gta6/particles/gta6_particles/spawners.rs +++ b/src/state/gta6/particles/gta6_particles/spawners.rs @@ -8,11 +8,19 @@ use std::sync::{Arc, Mutex, MutexGuard}; use or_io::gta6::headerless::ParticleEffects; use or_simulation::zcull_spawner::ZCullSpawners; -// ponytail: one entry per scanned list opened, never emptied, as its lines are. -static KEPT: Mutex>> = Mutex::new(BTreeMap::new()); +use super::super::ParticlesSession; -fn kept() -> MutexGuard<'static, BTreeMap>> { - KEPT.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) +#[derive(Clone, Default)] +pub(in crate::state::gta6::particles) struct SpawnersCache( + Arc>>>, +); + +fn kept(particles: &ParticlesSession) -> MutexGuard<'_, BTreeMap>> { + particles + .spawners + .0 + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// Each rule's third spawner that starts an effect, as a GTA V spawner naming the effect. @@ -29,11 +37,11 @@ pub(crate) fn of_list(list: &ParticleEffects) -> ZCullSpawners { } /// Keep the third spawners of `list`, opened from `path`. -pub(super) fn keep(path: &Path, list: &ParticleEffects) { - kept().insert(path.to_path_buf(), Arc::new(of_list(list))); +pub(super) fn keep(particles: &ParticlesSession, path: &Path, list: &ParticleEffects) { + kept(particles).insert(path.to_path_buf(), Arc::new(of_list(list))); } /// The third spawners of the GTA VI list the document at `path` opened from; `None` for any other. -pub(crate) fn of(path: &Path) -> Option> { - kept().get(path).cloned() +pub(crate) fn of(particles: &ParticlesSession, path: &Path) -> Option> { + kept(particles).get(path).cloned() } diff --git a/src/state/gta6/particles/gta6_particles/sprites.rs b/src/state/gta6/particles/gta6_particles/sprites.rs index 405c4598c..5329afeaa 100644 --- a/src/state/gta6/particles/gta6_particles/sprites.rs +++ b/src/state/gta6/particles/gta6_particles/sprites.rs @@ -7,6 +7,8 @@ use std::sync::{Arc, Mutex, MutexGuard}; use or_io::gta6::headerless::ParticleEffects; +use super::super::ParticlesSession; + /// The slot of a single-channel sprite, which the ramp of `RAMP_SLOT` colours. pub(crate) const SHAPE_SLOT: usize = 6; /// The slot of the colour ramp a `SHAPE_SLOT` sprite is coloured through. @@ -24,11 +26,17 @@ pub(crate) struct Sprite { /// Each rule's sprite, by the rule's name. pub(crate) type Sprites = BTreeMap; -// ponytail: one entry per scanned list opened, never emptied, as its lines are. -static KEPT: Mutex>> = Mutex::new(BTreeMap::new()); +#[derive(Clone, Default)] +pub(in crate::state::gta6::particles) struct SpritesCache( + Arc>>>, +); -fn kept() -> MutexGuard<'static, BTreeMap>> { - KEPT.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) +fn kept(particles: &ParticlesSession) -> MutexGuard<'_, BTreeMap>> { + particles + .sprites + .0 + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// The sprites of `list`'s rules that draw no model and set a sprite slot. @@ -50,11 +58,11 @@ pub(crate) fn of_list(list: &ParticleEffects) -> Sprites { } /// Keep the sprites of `list`, opened from `path`. -pub(super) fn keep(path: &Path, list: &ParticleEffects) { - kept().insert(path.to_path_buf(), Arc::new(of_list(list))); +pub(super) fn keep(particles: &ParticlesSession, path: &Path, list: &ParticleEffects) { + kept(particles).insert(path.to_path_buf(), Arc::new(of_list(list))); } /// The sprites of the GTA VI list the document at `path` opened from; `None` for any other. -pub(crate) fn of(path: &Path) -> Option> { - kept().get(path).cloned() +pub(crate) fn of(particles: &ParticlesSession, path: &Path) -> Option> { + kept(particles).get(path).cloned() } diff --git a/src/state/gta6/particles/gta6_particles_save/mod.rs b/src/state/gta6/particles/gta6_particles_save/mod.rs index 994a641a9..c69f074d3 100644 --- a/src/state/gta6/particles/gta6_particles_save/mod.rs +++ b/src/state/gta6/particles/gta6_particles_save/mod.rs @@ -25,18 +25,22 @@ pub(crate) mod remove; mod copies; use crate::state::document::Document; +use crate::state::gta6::session::Gta6Session; use crate::state::gta6_edit::EditSections; use crate::state::gta6_resource_save::EditedSave; use crate::state::DocPayload; /// The Ypt row's `edited_sections` where `document` is a scanned GTA VI list holding an edit: its /// body read again on the worker and its values written over it; `None` for any other document. -pub(in crate::state) fn edited_save(document: &Document) -> Option> { +pub(in crate::state) fn edited_save( + document: &Document, + gta6: &Gta6Session, +) -> Option> { if !document.history.can_undo() { return None; } let path = document.path.as_deref()?; - crate::state::gta6_particles::scanned_lines(path)?; + crate::state::gta6_particles::scanned_lines(>a6.particles, path)?; let DocPayload::Resource(or_io::Asset::Particles(ypt)) = &document.payload else { return None; }; diff --git a/src/state/gta6/particles/mod.rs b/src/state/gta6/particles/mod.rs index 1c89ed3e9..800e8d885 100644 --- a/src/state/gta6/particles/mod.rs +++ b/src/state/gta6/particles/mod.rs @@ -1,3 +1,12 @@ pub(crate) mod gta6_particle_models; pub(crate) mod gta6_particles; pub(crate) mod gta6_particles_save; + +/// Per-instance particle caches owned by [`crate::state::gta6::session::Gta6Session`]. +#[derive(Clone, Default)] +pub struct ParticlesSession { + models: gta6_particle_models::ParticleModelsCache, + scanned: gta6_particles::ScannedParticlesCache, + spawners: gta6_particles::spawners::SpawnersCache, + sprites: gta6_particles::sprites::SpritesCache, +} diff --git a/src/state/gta6/physics/gta6_navmesh.rs b/src/state/gta6/physics/gta6_navmesh.rs index 3f95d1fdd..7edb3b853 100644 --- a/src/state/gta6/physics/gta6_navmesh.rs +++ b/src/state/gta6/physics/gta6_navmesh.rs @@ -10,40 +10,50 @@ use or_io::container::rpf::{read_rpf9_body, Rpf9BodyKind, Rpf9ScanFind, Rpf9Zlib use or_io::gta6::headerless::{joins, Border, NavMesh, SpecialLink}; use or_job::{Cancel, Progress}; +use super::PhysicsSession; use crate::state::jobs::{JobKind, Outcome, RunningJob, Then}; use crate::state::rpf9_scan::{body_path, view_of, Row}; use crate::state::{AppState, DocPayload, DocumentId}; const BORDERS: [Border; 4] = [Border::East, Border::West, Border::North, Border::South]; -// ponytail: one entry per scanned cell opened, never emptied, as the scanned skeletons are. -static CELLS: Mutex>> = Mutex::new(BTreeMap::new()); +#[derive(Clone, Default)] +pub(super) struct NavMeshCache { + cells: Arc>>>, + chosen: Arc>>, +} -fn cells() -> MutexGuard<'static, BTreeMap>> { - CELLS +fn cells(physics: &PhysicsSession) -> MutexGuard<'_, BTreeMap>> { + physics + .navmesh + .cells .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// Keep `mesh`, the cell the body at `path` opened to, with none of an earlier session's deletions. -pub(in crate::state) fn remember(path: &Path, mesh: NavMesh) { - crate::state::gta6_navmesh_delete::forget(path); +pub(in crate::state) fn remember(physics: &PhysicsSession, path: &Path, mesh: NavMesh) { + crate::state::gta6_navmesh_delete::forget(physics, path); // A body whose links an edit of another cell renumbered keeps them while that edit holds. - if crate::state::gta6_navmesh_delete::links::renumbered_by(path).is_some() { + if crate::state::gta6_navmesh_delete::links::renumbered_by(physics, path).is_some() { return; } - cells().insert(path.to_path_buf(), Arc::new(mesh)); + cells(physics).insert(path.to_path_buf(), Arc::new(mesh)); } /// The GTA VI cell the document at `path` opened from; `None` for any other document. -pub(crate) fn scanned_cell(path: &Path) -> Option> { - cells().get(path).cloned() +pub(crate) fn scanned_cell(physics: &PhysicsSession, path: &Path) -> Option> { + cells(physics).get(path).cloned() } /// Keep `mesh` as the cell the document at `path` shows now, returning the one it held; `None`, /// changing nothing, where no cell is kept there. -pub(in crate::state) fn replace(path: &Path, mesh: Arc) -> Option> { - cells() +pub(in crate::state) fn replace( + physics: &PhysicsSession, + path: &Path, + mesh: Arc, +) -> Option> { + cells(physics) .get_mut(path) .map(|held| std::mem::replace(held, mesh)) } @@ -248,24 +258,27 @@ fn body_at(path: &Path) -> Option<(&Path, u64)> { Some((path.parent()?, u64::from_str_radix(stem, 16).ok()?)) } -// ponytail: every body a search chose, never emptied, as the cells are. -static CHOSEN: Mutex> = Mutex::new(BTreeSet::new()); - -fn chosen() -> MutexGuard<'static, BTreeSet> { - CHOSEN +fn chosen(physics: &PhysicsSession) -> MutexGuard<'_, BTreeSet> { + physics + .navmesh + .chosen .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// Each border of the cell opened at `path`, the cell across it, and that cell's open body a /// search of the scan chose: only a read of every body of the archive knows which is the second. -pub(crate) fn neighbours(path: &Path, m: &NavMesh) -> Vec<(Border, u32, Option>)> { +pub(crate) fn neighbours( + physics: &PhysicsSession, + path: &Path, + m: &NavMesh, +) -> Vec<(Border, u32, Option>)> { // A body of no cell has no border, and no other body's special link ends in it. if m.cell == 0 { return Vec::new(); } let archive = body_at(path).map(|(archive, _)| archive); - let (open, chosen) = (cells(), chosen()); + let (open, chosen) = (cells(physics), chosen(physics)); BORDERS .into_iter() .filter_map(|border| { @@ -292,24 +305,32 @@ fn chosen_body( /// Each cell across `m`'s borders or at its corners, where a link of either may end in the other, /// and that cell's open body a search of the scan chose. -pub(crate) fn linked_cells(path: &Path, m: &NavMesh) -> Vec<(u32, Option>)> { +pub(crate) fn linked_cells( + physics: &PhysicsSession, + path: &Path, + m: &NavMesh, +) -> Vec<(u32, Option>)> { if m.cell == 0 { return Vec::new(); } let archive = body_at(path).map(|(archive, _)| archive); - let (open, chosen) = (cells(), chosen()); + let (open, chosen) = (cells(physics), chosen(physics)); (Border::around(m.cell).into_iter()) .map(|c| (c, chosen_body(&open, &chosen, archive, c).map(|(_, n)| n))) .collect() } /// The path and the open body of each cell of [`linked_cells`] that has one. -pub(in crate::state) fn neighbour_paths(path: &Path, m: &NavMesh) -> Vec<(PathBuf, Arc)> { +pub(in crate::state) fn neighbour_paths( + physics: &PhysicsSession, + path: &Path, + m: &NavMesh, +) -> Vec<(PathBuf, Arc)> { if m.cell == 0 { return Vec::new(); } let archive = body_at(path).map(|(archive, _)| archive); - let (open, chosen) = (cells(), chosen()); + let (open, chosen) = (cells(physics), chosen(physics)); (Border::around(m.cell).into_iter()) .filter_map(|c| chosen_body(&open, &chosen, archive, c)) .collect() @@ -419,7 +440,9 @@ impl AppState { let Some(path) = self.document(doc).and_then(|d| d.path.clone()) else { return; }; - let (Some(m), Some((archive, _))) = (scanned_cell(&path), body_at(&path)) else { + let (Some(m), Some((archive, _))) = + (scanned_cell(&self.gta6.physics, &path), body_at(&path)) + else { return; }; let finds: Vec = (self.documents.iter()) @@ -481,7 +504,7 @@ impl AppState { "{count} neighbouring cells found in the scan; they open", paths.len() ); - chosen().extend(paths.iter().cloned()); + chosen(&self.gta6.physics).extend(paths.iter().cloned()); self.load_files(paths); (Outcome::Done(Then::Nothing), said) } @@ -639,25 +662,26 @@ mod tests { #[test] fn a_body_chosen_at_a_corner_is_one_an_edit_renumbers_though_no_border_names_it() { + let physics = PhysicsSession::default(); let m = cell(); let here = PathBuf::from("a_body_chosen_at_a_corner/0x1010.rsc"); let corner = PathBuf::from("a_body_chosen_at_a_corner/0x2010.rsc"); let mut at_corner = cell(); at_corner.cell = m.cell + 512 + 1; - remember(&corner, at_corner); - chosen().insert(corner.clone()); - let linked = linked_cells(&here, &m); + remember(&physics, &corner, at_corner); + chosen(&physics).insert(corner.clone()); + let linked = linked_cells(&physics, &here, &m); assert_eq!(linked.len(), 8, "four borders and four corners"); let open: Vec = (linked.iter()) .filter(|(_, body)| body.is_some()) .map(|(c, _)| *c) .collect(); assert_eq!(open, [m.cell + 512 + 1]); - let paths: Vec = (neighbour_paths(&here, &m).into_iter()) + let paths: Vec = (neighbour_paths(&physics, &here, &m).into_iter()) .map(|(p, _)| p) .collect(); assert_eq!(paths, [corner]); - assert!(neighbours(&here, &m) + assert!(neighbours(&physics, &here, &m) .iter() .all(|(_, _, body)| body.is_none())); } diff --git a/src/state/gta6/physics/gta6_navmesh_delete/links.rs b/src/state/gta6/physics/gta6_navmesh_delete/links.rs index b14f8d6fc..dc33d00a7 100644 --- a/src/state/gta6/physics/gta6_navmesh_delete/links.rs +++ b/src/state/gta6/physics/gta6_navmesh_delete/links.rs @@ -8,6 +8,7 @@ use std::sync::{Arc, Mutex, MutexGuard}; use or_io::container::rpf::Rpf9Sections; use or_io::gta6::headerless::{relinked, with_links, write_links, NavMesh, NavRebuild}; +use super::super::PhysicsSession; use crate::state::document::{DocPayload, Document}; use crate::state::edit_history::Swap; use crate::state::extract_job::ExtractItem; @@ -17,53 +18,57 @@ use crate::state::{gta6_navmesh, rpf9_scan}; /// Per cell an edit was made in, each neighbouring body it renumbered, as it opened. type Relinks = BTreeMap>>; -// ponytail: an entry per cell whose edit renumbered a neighbour, emptied when the cell opens again. -static RELINKS: Mutex = Mutex::new(BTreeMap::new()); +#[derive(Clone, Default)] +pub(super) struct RelinksCache(Arc>); -fn relinks() -> MutexGuard<'static, Relinks> { - RELINKS +fn relinks(physics: &PhysicsSession) -> MutexGuard<'_, Relinks> { + physics + .navmesh_delete + .relinks + .0 .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// The cell whose edit holds the body at `path` with its special links renumbered; `None` where /// none does. -pub(in crate::state) fn renumbered_by(path: &Path) -> Option { - let held: Vec<(PathBuf, Arc)> = (relinks().iter()) +pub(in crate::state) fn renumbered_by(physics: &PhysicsSession, path: &Path) -> Option { + let held: Vec<(PathBuf, Arc)> = (relinks(physics).iter()) .filter_map(|(cell, bodies)| Some((cell.clone(), Arc::clone(bodies.get(path)?)))) .collect(); if held.is_empty() { return None; } - let now = gta6_navmesh::scanned_cell(path)?; + let now = gta6_navmesh::scanned_cell(physics, path)?; (held.into_iter()) .find(|(_, opened)| opened.special_links != now.special_links) .map(|(cell, _)| cell) } /// Put back each body the edits of the cell at `path` renumbered, whose own body opens again. -pub(in crate::state) fn forget(path: &Path) { - let Some(bodies) = relinks().remove(path) else { +pub(in crate::state) fn forget(physics: &PhysicsSession, path: &Path) { + let Some(bodies) = relinks(physics).remove(path) else { return; }; for (body, opened) in bodies { - gta6_navmesh::replace(&body, opened); + gta6_navmesh::replace(physics, &body, opened); } } /// Each open neighbouring body of the cell at `path` whose special links `made`, made from `cell`, /// renumbers, with them made again and tried on its stored bytes; why not, where one is refused. pub(in crate::state) fn planned( + physics: &PhysicsSession, path: &Path, cell: &NavMesh, made: &NavRebuild, ) -> Result, String> { let mut out = Vec::new(); - for (body_path, body) in gta6_navmesh::neighbour_paths(path, cell) { + for (body_path, body) in gta6_navmesh::neighbour_paths(physics, path, cell) { let Some(links) = relinked(&body, cell, made).map_err(|e| e.to_string())? else { continue; }; - if renumbered_by(&body_path).is_some_and(|by| by != path) { + if renumbered_by(physics, &body_path).is_some_and(|by| by != path) { return Err(tr!( "The special links of the neighbouring cell {cell} were renumbered by an edit of another cell, whose save writes them: save that cell or undo its edit first.", cell = body.cell @@ -85,16 +90,21 @@ pub(in crate::state) fn planned( /// The bodies `planned` gave kept as the cells the inspector reads, each as a part of the step of /// the cell at `path` that puts it back. -pub(in crate::state) fn apply(path: &Path, planned: Vec<(PathBuf, NavMesh)>) -> Vec> { +pub(in crate::state) fn apply( + physics: &PhysicsSession, + path: &Path, + planned: Vec<(PathBuf, NavMesh)>, +) -> Vec> { let mut parts: Vec> = Vec::new(); for (body, after) in planned { - let Some(held) = gta6_navmesh::replace(&body, Arc::new(after)) else { + let Some(held) = gta6_navmesh::replace(physics, &body, Arc::new(after)) else { continue; }; - (relinks().entry(path.to_path_buf()).or_default()) + (relinks(physics).entry(path.to_path_buf()).or_default()) .entry(body.clone()) .or_insert_with(|| Arc::clone(&held)); parts.push(Box::new(BodyPart { + physics: physics.clone(), path: body, cell: held, })); @@ -104,13 +114,15 @@ pub(in crate::state) fn apply(path: &Path, planned: Vec<(PathBuf, NavMesh)>) -> /// A neighbouring body's cell as the inspector reads it, which an undo puts back. struct BodyPart { + physics: PhysicsSession, path: PathBuf, cell: Arc, } impl Swap for BodyPart { fn swap(&mut self, _: &mut DocPayload) -> bool { - let Some(now) = gta6_navmesh::replace(&self.path, Arc::clone(&self.cell)) else { + let Some(now) = gta6_navmesh::replace(&self.physics, &self.path, Arc::clone(&self.cell)) + else { return false; }; self.cell = now; @@ -120,16 +132,16 @@ impl Swap for BodyPart { /// Each neighbouring body the edits of the cell `document` shows hold renumbered, read again on /// the worker with those links written over it, as `.rsc`. -pub(in crate::state) fn beside(document: &Document) -> Vec { +pub(in crate::state) fn beside(physics: &PhysicsSession, document: &Document) -> Vec { let Some(path) = document.path.as_deref() else { return Vec::new(); }; - let held: Vec<(PathBuf, Arc)> = (relinks().get(path).into_iter()) + let held: Vec<(PathBuf, Arc)> = (relinks(physics).get(path).into_iter()) .flat_map(|bodies| bodies.iter().map(|(p, m)| (p.clone(), Arc::clone(m)))) .collect(); let mut items = Vec::new(); for (body, opened) in held { - let Some(now) = gta6_navmesh::scanned_cell(&body) else { + let Some(now) = gta6_navmesh::scanned_cell(physics, &body) else { continue; }; let Some((archive, offset)) = rpf9_scan::scanned_body(&body) else { @@ -166,12 +178,13 @@ mod tests { #[test] fn a_renumbered_body_is_held_by_its_cell_until_undone_or_the_cell_opens_again() { + let physics = PhysicsSession::default(); let (edited, body) = ( PathBuf::from("a_renumbered_body/0x1010.cell"), PathBuf::from("a_renumbered_body/0x2020.cell"), ); - crate::state::gta6_navmesh::remember(&body, cell()); - assert_eq!(renumbered_by(&body), None); + crate::state::gta6_navmesh::remember(&physics, &body, cell()); + assert_eq!(renumbered_by(&physics, &body), None); let mut after = cell(); after.special_links.push(SpecialLink { from: [0; 3], @@ -183,23 +196,31 @@ mod tests { word_18: 0, heading: 0, }); - let mut parts = apply(&edited, vec![(body.clone(), after)]); + let mut parts = apply(&physics, &edited, vec![(body.clone(), after)]); assert_eq!(parts.len(), 1); - assert_eq!(renumbered_by(&body), Some(edited.clone())); + assert_eq!(renumbered_by(&physics, &body), Some(edited.clone())); // Opened again, the body keeps the links the edit holds. - crate::state::gta6_navmesh::remember(&body, cell()); - let links = - |p: &Path| crate::state::gta6_navmesh::scanned_cell(p).map(|c| c.special_links.len()); + crate::state::gta6_navmesh::remember(&physics, &body, cell()); + let links = |p: &Path| { + crate::state::gta6_navmesh::scanned_cell(&physics, p).map(|c| c.special_links.len()) + }; assert_eq!(links(&body), Some(1)); let mut payload = DocPayload::Resource(or_io::Asset::NavMesh(Default::default())); assert!(parts[0].swap(&mut payload), "undone"); - assert_eq!((links(&body), renumbered_by(&body)), (Some(0), None)); + assert_eq!( + (links(&body), renumbered_by(&physics, &body)), + (Some(0), None) + ); assert!(parts[0].swap(&mut payload), "made again"); - assert_eq!(renumbered_by(&body), Some(edited.clone())); - forget(&edited); - assert_eq!((links(&body), renumbered_by(&body)), (Some(0), None)); + assert_eq!(renumbered_by(&physics, &body), Some(edited.clone())); + forget(&physics, &edited); + assert_eq!( + (links(&body), renumbered_by(&physics, &body)), + (Some(0), None) + ); assert!(apply( + &physics, &edited, vec![(PathBuf::from("no body is kept here"), cell())] ) diff --git a/src/state/gta6/physics/gta6_navmesh_delete/look.rs b/src/state/gta6/physics/gta6_navmesh_delete/look.rs index 5dfb0b75a..b3a908dea 100644 --- a/src/state/gta6/physics/gta6_navmesh_delete/look.rs +++ b/src/state/gta6/physics/gta6_navmesh_delete/look.rs @@ -11,6 +11,8 @@ use std::sync::{Arc, Mutex, MutexGuard}; use or_io::container::rpf::{navigation_cells, Gta6Mount, GtaViKeys}; use or_io::gta6::headerless::NavMesh; +#[cfg(test)] +use super::super::PhysicsSession; use crate::state::rpf9_scan::rpf9_table; use crate::state::AppState; @@ -33,13 +35,15 @@ impl Looks { } } -// ponytail: an entry per archive a deletion looked through, never emptied, as the cells are. -static LOOKS: Mutex> = Mutex::new(BTreeMap::new()); +#[derive(Clone, Default)] +pub(super) struct LooksCache(Arc>>); -fn looks() -> MutexGuard<'static, BTreeMap> { - LOOKS - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) +impl LooksCache { + fn lock(&self) -> MutexGuard<'_, BTreeMap> { + self.0 + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } } /// The cells of `near` whose body is not open, but those `found` says the archive holds no body of. @@ -75,12 +79,12 @@ fn bodies_of( } /// Look through the table of `archive` on a worker for a navigation row of each of `wanted`. -fn look_through(archive: PathBuf, wanted: Vec) { +fn look_through(cache: LooksCache, archive: PathBuf, wanted: Vec) { std::thread::spawn(move || { let keys = rpf9_table::keys(); let keyless = keys.is_err(); let found = bodies_of(&archive, keys, &wanted); - let mut held = looks(); + let mut held = cache.lock(); let look = held.entry(archive).or_default(); look.running = false; look.keyless |= keyless; @@ -98,7 +102,8 @@ impl AppState { near: &[(u32, Option>)], ) -> Result, String> { let archive = path.parent().unwrap_or(path); - let mut held = looks(); + let cache = &self.gta6.physics.navmesh_delete.looks; + let mut held = cache.lock(); let look = held.entry(archive.to_path_buf()).or_default(); if look.keyless { look.refresh(rpf9_table::keys().is_ok()); @@ -112,7 +117,7 @@ impl AppState { } if !look.running { look.running = true; - look_through(archive.to_path_buf(), unknown.clone()); + look_through(cache.clone(), archive.to_path_buf(), unknown.clone()); } let cells: Vec = unknown.iter().map(u32::to_string).collect(); Err(cells.join(", ")) @@ -121,17 +126,23 @@ impl AppState { /// Take the table of `archive` as holding no navigation row of `cells`, as a look through it finds. #[cfg(test)] -pub(super) fn given_none_of(archive: &Path, cells: &[u32]) { - let mut held = looks(); +pub(super) fn given_none_of(physics: &PhysicsSession, archive: &Path, cells: &[u32]) { + let mut held = physics.navmesh_delete.looks.lock(); let look = held.entry(archive.to_path_buf()).or_default(); look.found.extend(cells.iter().map(|c| (*c, false))); } /// Wait for the look through the table of `archive` to end. #[cfg(test)] -pub(super) fn settled(archive: &Path) { +pub(super) fn settled(physics: &PhysicsSession, archive: &Path) { let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); - while looks().get(archive).is_some_and(|l| l.running) { + while physics + .navmesh_delete + .looks + .lock() + .get(archive) + .is_some_and(|l| l.running) + { assert!(std::time::Instant::now() < deadline, "the look never ended"); std::thread::sleep(std::time::Duration::from_millis(5)); } diff --git a/src/state/gta6/physics/gta6_navmesh_delete/mod.rs b/src/state/gta6/physics/gta6_navmesh_delete/mod.rs index bd8b60ddd..f714e0e4e 100644 --- a/src/state/gta6/physics/gta6_navmesh_delete/mod.rs +++ b/src/state/gta6/physics/gta6_navmesh_delete/mod.rs @@ -16,6 +16,7 @@ use or_io::gta6::headerless::{ NOWHERE, }; +use super::PhysicsSession; use crate::state::edit_history::{Change, Swap}; use crate::state::{AppState, DocPayload, DocumentId}; @@ -32,19 +33,25 @@ pub(in crate::state) struct Deletion { disable: bool, } -// ponytail: one entry per scanned cell a polygon was deleted from, never emptied, as the cells are. -static DELETIONS: Mutex>> = Mutex::new(BTreeMap::new()); +#[derive(Clone, Default)] +pub(super) struct NavMeshDeleteCache { + deletions: Arc>>>, + relinks: links::RelinksCache, + looks: look::LooksCache, +} -fn deletions() -> MutexGuard<'static, BTreeMap>> { - DELETIONS +fn deletions(physics: &PhysicsSession) -> MutexGuard<'_, BTreeMap>> { + physics + .navmesh_delete + .deletions .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// Drop the deletions kept for `path`, whose body opens again as it is stored. -pub(in crate::state) fn forget(path: &Path) { - deletions().remove(path); - links::forget(path); +pub(in crate::state) fn forget(physics: &PhysicsSession, path: &Path) { + deletions(physics).remove(path); + links::forget(physics, path); } fn view_of(payload: &mut DocPayload) -> Option<&mut CNavMesh> { @@ -56,6 +63,7 @@ fn view_of(payload: &mut DocPayload) -> Option<&mut CNavMesh> { /// The cell the inspector reads and the deletions a save makes, which an undo puts back. struct CellPart { + physics: PhysicsSession, path: PathBuf, cell: Arc, deletions: Vec, @@ -63,12 +71,13 @@ struct CellPart { impl Swap for CellPart { fn swap(&mut self, _: &mut DocPayload) -> bool { - let Some(now) = crate::state::gta6_navmesh::replace(&self.path, Arc::clone(&self.cell)) + let Some(now) = + crate::state::gta6_navmesh::replace(&self.physics, &self.path, Arc::clone(&self.cell)) else { return false; }; self.cell = now; - let mut made = deletions(); + let mut made = deletions(&self.physics); std::mem::swap( made.entry(self.path.clone()).or_default(), &mut self.deletions, @@ -126,7 +135,7 @@ impl AppState { polygon: usize, ) -> Option> { let path = self.document(doc)?.path.clone()?; - let cell = crate::state::gta6_navmesh::scanned_cell(&path)?; + let cell = crate::state::gta6_navmesh::scanned_cell(&self.gta6.physics, &path)?; Some(self.delete_in_cell(doc, &path, &cell, polygon)) } @@ -137,7 +146,7 @@ impl AppState { cell: &NavMesh, polygon: usize, ) -> Result { - let near = crate::state::gta6_navmesh::linked_cells(path, cell); + let near = crate::state::gta6_navmesh::linked_cells(&self.gta6.physics, path, cell); let closed = (self.unopened(path, &near)).map_err(|cells| looking(polygon, &cells))?; let open = others(&closed, cell, &near, polygon)?; let bodies: Vec<&NavMesh> = open.iter().map(|b| &**b).collect(); @@ -235,8 +244,9 @@ impl AppState { step: Deletion, ) -> Result { let closed = || tr!("its document is closed").to_string(); + let physics = self.gta6.physics.clone(); // ⚠ Each body is written by one save: this one's links are another cell's to write. - if links::renumbered_by(path).is_some() { + if links::renumbered_by(&physics, path).is_some() { return Err(tr!("This cell's special links were renumbered by an edit of a neighbouring cell, whose save writes them: save that cell or undo its edit first.").to_string()); } let before = match self.document(doc).map(|d| &d.payload) { @@ -245,24 +255,24 @@ impl AppState { None => return Err(closed()), }; let edited = view_after(&before, &made)?; - let relinks = links::planned(path, cell, &made)?; - let own = |p: &Path| deletions().get(p).is_some_and(|d| !d.is_empty()); + let relinks = links::planned(&physics, path, cell, &made)?; + let own = |p: &Path| deletions(&physics).get(p).is_some_and(|d| !d.is_empty()); if let Some((_, body)) = relinks.iter().find(|(p, _)| own(p.as_path())) { return Err(tr!( "The special links of the neighbouring cell {cell} would be renumbered, but its body holds deletions of its own, which its own save writes: undo them first.", cell = body.cell )); } - let mut planned = deletions().get(path).cloned().unwrap_or_default(); + let mut planned = deletions(&physics).get(path).cloned().unwrap_or_default(); planned.push(step); tried(path, planned)?; - let held = - crate::state::gta6_navmesh::replace(path, Arc::new(made.mesh)).ok_or_else(closed)?; + let held = crate::state::gta6_navmesh::replace(&physics, path, Arc::new(made.mesh)) + .ok_or_else(closed)?; if let Some(view) = self.document_mut(doc).and_then(|d| view_of(&mut d.payload)) { *view = edited; } let earlier = { - let mut made = deletions(); + let mut made = deletions(&physics); let list = made.entry(path.to_path_buf()).or_default(); let earlier = list.clone(); list.push(step); @@ -278,11 +288,12 @@ impl AppState { tr!("Delete polygon {polygon}", polygon = step.polygon), ), }; - let bodies = links::apply(path, relinks); + let bodies = links::apply(&physics, path, relinks); let renumbered = bodies.len(); let mut change = Change::part(kind, before, view_of); if let Change::Part { parts, .. } = &mut change { parts.push(Box::new(CellPart { + physics, path: path.to_path_buf(), cell: held, deletions: earlier, @@ -330,11 +341,12 @@ fn view_after(before: &CNavMesh, made: &NavRebuild) -> Result /// The deletions a save of the cell at `path` makes, and no neighbouring body: their links were /// made again at each step and are written beside the cell. pub(in crate::state) fn saved_with( + physics: &PhysicsSession, path: &Path, _cell: &NavMesh, ) -> (Vec, Vec>) { ( - deletions().get(path).cloned().unwrap_or_default(), + deletions(physics).get(path).cloned().unwrap_or_default(), Vec::new(), ) } @@ -505,9 +517,9 @@ mod tests { let refused = state.delete_navmesh_polygon(doc, 0).unwrap_err(); assert!(refused.contains("table is searched for them"), "{refused}"); assert!(!state.document(doc).expect("open").history.can_undo()); - look::settled(&archive_of(&state, doc)); + look::settled(&state.gta6.physics, &archive_of(&state, doc)); let around = Border::around(cell().cell); - look::given_none_of(&archive_of(&state, doc), &around); + look::given_none_of(&state.gta6.physics, &archive_of(&state, doc), &around); let said = state.delete_navmesh_polygon(doc, 0).expect("deleted"); assert!(said.contains("Polygons left: 1."), "{said}"); diff --git a/src/state/gta6/physics/gta6_navmesh_edit.rs b/src/state/gta6/physics/gta6_navmesh_edit.rs index 0792f7904..e832673ae 100644 --- a/src/state/gta6/physics/gta6_navmesh_edit.rs +++ b/src/state/gta6/physics/gta6_navmesh_edit.rs @@ -60,7 +60,7 @@ fn listed(items: &[usize]) -> String { impl AppState { fn gta6_cell(&self, doc: DocumentId) -> Option<(std::path::PathBuf, Arc)> { let path = self.document(doc)?.path.clone()?; - let cell = crate::state::gta6_navmesh::scanned_cell(&path)?; + let cell = crate::state::gta6_navmesh::scanned_cell(&self.gta6.physics, &path)?; Some((path, cell)) } @@ -83,7 +83,7 @@ impl AppState { polygon: usize, ) -> Result { let cut = polygon_cut(cell, polygon).map_err(|e| e.to_string())?; - let near = crate::state::gta6_navmesh::linked_cells(path, cell); + let near = crate::state::gta6_navmesh::linked_cells(&self.gta6.physics, path, cell); let (cuts, in_place) = match self.disable_rechained(doc, path, cell, polygon, &near) { Some(made) => (made?, false), None => (self.cut_in_view(doc, &cut, polygon)?, true), @@ -279,7 +279,7 @@ mod tests { let document = state.document(doc).expect("open"); let Some(Ok(EditedSave::Body { edit, .. })) = - crate::state::gta6_physics_edit::edited_cell(document) + crate::state::gta6_physics_edit::edited_cell(document, &state.gta6) else { panic!("the cell saves as its body read again and edited"); }; diff --git a/src/state/gta6/physics/gta6_physics_edit/bound_reshape.rs b/src/state/gta6/physics/gta6_physics_edit/bound_reshape.rs index cadf1a340..5a2bbe936 100644 --- a/src/state/gta6/physics/gta6_physics_edit/bound_reshape.rs +++ b/src/state/gta6/physics/gta6_physics_edit/bound_reshape.rs @@ -5,7 +5,7 @@ use std::collections::BTreeMap; use std::path::{Path, PathBuf}; -use std::sync::{Mutex, MutexGuard}; +use std::sync::{Arc, Mutex, MutexGuard}; use or_io::container::rpf::Rpf9Sections; use or_io::gta6::headerless::{ @@ -15,6 +15,7 @@ use or_io::gta6::headerless::{ BoundReshape, ChildBound, Primitive, Resource, UnknownShape, }; +use super::super::PhysicsSession; use super::{bound_mut, geometry_mut, shape_mut}; use crate::state::document::Document; use crate::state::edit_history::{Change, Swap}; @@ -53,18 +54,24 @@ pub(super) struct Made { type Key = (PathBuf, DocumentId); -// ponytail: one entry per document a bound was reshaped in, never emptied; an id is not reused. -static MADE: Mutex>> = Mutex::new(BTreeMap::new()); - -// The changes a save over the document's own file wrote into it, which the body read again holds. -static SAVED: Mutex>> = Mutex::new(BTreeMap::new()); +#[derive(Clone, Default)] +pub(in crate::state::gta6::physics) struct BoundReshapeCache { + made: Arc>>>, + saved: Arc>>>, +} -fn made() -> MutexGuard<'static, BTreeMap>> { - MADE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) +fn made(physics: &PhysicsSession) -> MutexGuard<'_, BTreeMap>> { + physics + .bound_reshape + .made + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) } -fn saved_made() -> MutexGuard<'static, BTreeMap>> { - SAVED +fn saved_made(physics: &PhysicsSession) -> MutexGuard<'_, BTreeMap>> { + physics + .bound_reshape + .saved .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } @@ -77,19 +84,19 @@ fn unsaved<'a>(made: &'a [Made], held: &[Made]) -> Result<&'a [Made], String> { } /// `made` less the changes the body at `key` already holds. -fn pending(key: &Key, made: &[Made]) -> Result, String> { - let held = saved_made().get(key).cloned().unwrap_or_default(); +fn pending(physics: &PhysicsSession, key: &Key, made: &[Made]) -> Result, String> { + let held = saved_made(physics).get(key).cloned().unwrap_or_default(); unsaved(made, &held).map(<[Made]>::to_vec) } /// Document `document`'s file now holds every change its collision made. -pub(crate) fn saved_over(document: &Document) { +pub(crate) fn saved_over(physics: &PhysicsSession, document: &Document) { let Some(path) = document.path.clone() else { return; }; let key = (path, document.id); - if let Some(made) = made().get(&key).cloned() { - saved_made().insert(key, made); + if let Some(made) = made(physics).get(&key).cloned() { + saved_made(physics).insert(key, made); } } @@ -123,13 +130,17 @@ fn bound_of(resource: &Resource) -> Option<&Bound> { /// The changes a save makes, which an undo puts back. struct MadePart { + physics: PhysicsSession, key: Key, made: Vec, } impl Swap for MadePart { fn swap(&mut self, _: &mut DocPayload) -> bool { - std::mem::swap(made().entry(self.key.clone()).or_default(), &mut self.made); + std::mem::swap( + made(&self.physics).entry(self.key.clone()).or_default(), + &mut self.made, + ); true } } @@ -374,6 +385,7 @@ impl AppState { || tr!("The bound is not edited while a task reads the body; try again once it ends."); let path = (self.document(doc).and_then(|d| d.path.clone())) .ok_or_else(|| tr!("This document has no file, so its collision is not reshaped."))?; + let physics = self.gta6.physics.clone(); let document = (self.document_mut(doc)).ok_or_else(|| tr!("its document is closed"))?; let payload = &mut document.payload; let holder = match &*payload { @@ -386,10 +398,10 @@ impl AppState { let (op, label, mut change) = changed(b, holder, edit)?; let last = counts(b); let key = (path.clone(), doc); - let earlier = made().get(&key).cloned().unwrap_or_default(); + let earlier = made(&physics).get(&key).cloned().unwrap_or_default(); let mut planned = earlier.clone(); planned.push(Made { op, began }); - let outcome = pending(&key, &planned).and_then(|p| tried(&path, holder, p, last)); + let outcome = pending(&physics, &key, &planned).and_then(|p| tried(&path, holder, p, last)); if let Err(why) = outcome { if let Change::Part { parts, .. } = &mut change { for part in parts.iter_mut().rev() { @@ -398,9 +410,13 @@ impl AppState { } return Err(why); } - made().insert(key.clone(), planned); + made(&physics).insert(key.clone(), planned); if let Change::Part { parts, .. } = &mut change { - parts.push(Box::new(MadePart { key, made: earlier })); + parts.push(Box::new(MadePart { + physics, + key, + made: earlier, + })); } self.record(doc, label, change); // ⚠ Never folded into the next edit: indices change under a reshape. @@ -462,13 +478,13 @@ fn write_made( } /// The changes a save of `document` makes again before its values are written in place. -pub(super) fn saved(document: &Document) -> Result, String> { +pub(super) fn saved(physics: &PhysicsSession, document: &Document) -> Result, String> { let Some(path) = document.path.clone() else { return Ok(Vec::new()); }; let key = (path, document.id); - let made = made().get(&key).cloned().unwrap_or_default(); - pending(&key, &made) + let made = made(physics).get(&key).cloned().unwrap_or_default(); + pending(physics, &key, &made) } /// `made` made again on the bound `resource` holds in `s`, then each child it gives another type diff --git a/src/state/gta6/physics/gta6_physics_edit/mod.rs b/src/state/gta6/physics/gta6_physics_edit/mod.rs index 331cb3df8..bf95ec88b 100644 --- a/src/state/gta6/physics/gta6_physics_edit/mod.rs +++ b/src/state/gta6/physics/gta6_physics_edit/mod.rs @@ -480,7 +480,7 @@ impl AppState { let path = self.document(doc).and_then(|d| d.path.clone()); if path .as_deref() - .and_then(crate::state::gta6_navmesh::scanned_cell) + .and_then(|p| crate::state::gta6_navmesh::scanned_cell(&self.gta6.physics, p)) .is_none() { return Err( @@ -502,8 +502,11 @@ impl AppState { /// The GTA VI drawable row's `edited_sections`: the materials' edit, then a bound's or a /// fragment's values written over the body read again; `None` where it holds no edit. -pub(in crate::state) fn edited_save(document: &Document) -> Option> { - let save = crate::state::gta6_edit::edited_save(document)?; +pub(in crate::state) fn edited_save( + document: &Document, + gta6: &crate::state::gta6::session::Gta6Session, +) -> Option> { + let save = crate::state::gta6_edit::edited_save(document, gta6)?; let DocPayload::Gta6Drawable(resource) = &document.payload else { return Some(save); }; @@ -515,7 +518,7 @@ pub(in crate::state) fn edited_save(document: &Document) -> Option reshaped, Err(why) => return Some(Err(why)), }; @@ -554,12 +557,15 @@ pub(in crate::state) fn edited_save(document: &Document) -> Option Option> { +pub(in crate::state) fn edited_cell( + document: &Document, + gta6: &crate::state::gta6::session::Gta6Session, +) -> Option> { if !document.history.can_undo() { return None; } let path = document.path.as_deref()?; - let cell = crate::state::gta6_navmesh::scanned_cell(path)?; + let cell = crate::state::gta6_navmesh::scanned_cell(>a6.physics, path)?; let (archive, offset) = crate::state::rpf9_scan::scanned_body(path)?; let DocPayload::Resource(or_io::Asset::NavMesh(mesh)) = &document.payload else { return None; @@ -569,7 +575,7 @@ pub(in crate::state) fn edited_cell(document: &Document) -> Option = Arc::new(move |_, sections| { crate::state::gta6_navmesh_delete::write_deletions(sections, &made, &others)?; write_polygon_flags(&mut sections.virtual_section, &flags, keep) diff --git a/src/state/gta6/physics/mod.rs b/src/state/gta6/physics/mod.rs index ccc202b7f..9a9251c42 100644 --- a/src/state/gta6/physics/mod.rs +++ b/src/state/gta6/physics/mod.rs @@ -5,3 +5,11 @@ pub(crate) mod gta6_navmesh; pub(crate) mod gta6_navmesh_delete; pub(crate) mod gta6_navmesh_edit; pub(crate) mod gta6_physics_edit; + +/// Per-instance physics and navmesh caches owned by [`crate::state::gta6::session::Gta6Session`]. +#[derive(Clone, Default)] +pub(crate) struct PhysicsSession { + navmesh: gta6_navmesh::NavMeshCache, + navmesh_delete: gta6_navmesh_delete::NavMeshDeleteCache, + bound_reshape: gta6_physics_edit::bound_reshape::BoundReshapeCache, +} diff --git a/src/state/gta6/session.rs b/src/state/gta6/session.rs new file mode 100644 index 000000000..67d32381e --- /dev/null +++ b/src/state/gta6/session.rs @@ -0,0 +1,33 @@ +//! Per-`AppState` owned session state for GTA VI subsystems. +//! +//! Each domain holds `Arc`-backed interior-mutable stores so background worker threads and +//! `&AppState` callers operate on the owning `AppState`'s isolated session rather than +//! process-global mutable statics. + +use std::ops::Deref; +use std::sync::Arc; + +#[derive(Default)] +pub(crate) struct Gta6SessionInner { + pub(crate) anim: super::anim::AnimSession, + pub(crate) audio: super::audio::AudioSession, + pub(crate) bodies: super::bodies::BodiesSession, + pub(crate) particles: super::particles::ParticlesSession, + pub(crate) physics: super::physics::PhysicsSession, + pub(crate) textures: super::textures::TexturesSession, + pub(crate) modding: super::modding::ModdingSession, + pub(crate) install: super::install::InstallSession, + pub(crate) ttpf: crate::state::ttpf_document::TtpfSession, + pub(crate) script: crate::state::document::gta6_script::ScriptSession, +} + +#[derive(Clone, Default)] +pub(crate) struct Gta6Session(Arc); + +impl Deref for Gta6Session { + type Target = Gta6SessionInner; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} diff --git a/src/state/gta6/textures/gta6_dictionary_index.rs b/src/state/gta6/textures/gta6_dictionary_index.rs index ac4472fb6..41280c88e 100644 --- a/src/state/gta6/textures/gta6_dictionary_index.rs +++ b/src/state/gta6/textures/gta6_dictionary_index.rs @@ -119,6 +119,7 @@ pub(in crate::state) fn whole_scans( /// The keys of the textures that read in each body of `bodies`, each body read and dropped in /// turn; a body that does not read holds none. `None` once `cancel` is set. pub(in crate::state) fn index( + ttpf: &crate::state::ttpf_document::TtpfSession, bodies: Vec, cancel: &or_job::Cancel, progress: &or_job::Progress, @@ -154,7 +155,7 @@ pub(in crate::state) fn index( let Ok(dict) = read_dictionary(virtual_section, Some(physical)) else { continue; }; - crate::state::ttpf_document::learn_names(&dict); + crate::state::ttpf_document::learn_names(ttpf, &dict); let at = built.bodies.len() as u32; for (_, entry) in &dict.entries { if let Ok(Entry::Texture(t)) = entry { @@ -237,9 +238,10 @@ impl AppState { return; } let built = Arc::clone(&held.built); + let ttpf = self.gta6.ttpf.clone(); let doing = tr!("Indexing the GTA VI texture dictionaries the open archives' scans found"); let run = TextureNaming::run(doing.to_string(), move |cancel, progress| { - let Some(found) = index(bodies, cancel, progress) else { + let Some(found) = index(&ttpf, bodies, cancel, progress) else { return NamingEnded::Stopped; }; let read = found.bodies.len(); @@ -253,10 +255,11 @@ impl AppState { fn read_texture_dictionary(&mut self, path: PathBuf) { let opening: Opening = Arc::default(); self.gta6_finders.texture_packs.dictionaries.opening = Some(Arc::clone(&opening)); + let gta6 = self.gta6.clone(); std::thread::spawn(move || { let read = match scanned_body(&path) { Some((archive, offset)) => { - crate::state::rpf9_scan::read_body(&path, archive, offset) + crate::state::rpf9_scan::read_body(>a6, &path, archive, offset) } None => Err(path.display().to_string()), }; diff --git a/src/state/gta6/textures/gta6_dictionary_write/mod.rs b/src/state/gta6/textures/gta6_dictionary_write/mod.rs index e2cf75316..7b027bdf3 100644 --- a/src/state/gta6/textures/gta6_dictionary_write/mod.rs +++ b/src/state/gta6/textures/gta6_dictionary_write/mod.rs @@ -52,6 +52,7 @@ pub(in crate::state) fn held(dict: &PgDictionary) -> Vec { /// The texture `name` of the scanned dictionary `doc`, where it reads and is no volume, the slices it holds one after another, and the one the preview shows. fn reshapeable<'a>( + ttpf: &crate::state::ttpf_document::TtpfSession, doc: &'a mut Document, name: &str, ) -> Result<(&'a mut GrcTexture, u32, u32), String> { @@ -60,7 +61,7 @@ fn reshapeable<'a>( _ => None, }; let slices = slices.map(|t| crate::state::ttpf_document::scanned_slices(doc, t)); - let shown = crate::state::ttpf_document::shown_scanned_slice(doc, name); + let shown = crate::state::ttpf_document::shown_scanned_slice(ttpf, doc, name); let held = match &mut doc.payload { DocPayload::Resource(or_io::Asset::TextureDict(dict)) => dict.get_mut(name), _ => None, @@ -150,6 +151,7 @@ fn reshaped( /// Texture `name` of the scanned dictionary `doc` re-encoded as `choice` with `options`' mips: the /// texture it was and what changed; `None` for any other document. pub(in crate::state) fn reencode( + ttpf: &crate::state::ttpf_document::TtpfSession, doc: &mut Document, name: &str, choice: FormatChoice, @@ -158,20 +160,24 @@ pub(in crate::state) fn reencode( if !is_scanned_dictionary(doc) { return None; } - Some(reshapeable(doc, name).and_then(|(texture, slices, shown)| { - let sources = sources_of(texture, (slices, shown), None, options)?; - let format = (sources.first()).map_or(texture.pixel_format(), |rgba| choice.resolve(rgba)); - let before = reshaped(texture, format, &sources, options)?; - let mips = u32::from(texture.mip_count); - let name = name.to_string(); - Ok((before, TextureEdit::Reencoded { name, format, mips })) - })) + Some( + reshapeable(ttpf, doc, name).and_then(|(texture, slices, shown)| { + let sources = sources_of(texture, (slices, shown), None, options)?; + let format = + (sources.first()).map_or(texture.pixel_format(), |rgba| choice.resolve(rgba)); + let before = reshaped(texture, format, &sources, options)?; + let mips = u32::from(texture.mip_count); + let name = name.to_string(); + Ok((before, TextureEdit::Reencoded { name, format, mips })) + }), + ) } /// Texture `name` of the scanned dictionary `doc` from `image`: in its own shape where the image /// has its size and `choice` and `options` keep its format and mips, else given the image's size, /// that format, or its own for an automatic one, and those mips; `None` for any other document. pub(in crate::state) fn import( + ttpf: &crate::state::ttpf_document::TtpfSession, doc: &mut Document, name: &str, image: &RgbaImage, @@ -192,23 +198,27 @@ pub(in crate::state) fn import( size && !format && !mips }); if same { - return crate::state::gta6_edit::replace_scanned_texture(doc, name, image, choice, options); + return crate::state::gta6_edit::replace_scanned_texture( + ttpf, doc, name, image, choice, options, + ); } - Some(reshapeable(doc, name).and_then(|(texture, slices, shown)| { - let format = match choice { - FormatChoice::Fixed(format) => format, - FormatChoice::Automatic => texture.pixel_format(), - }; - let sources = sources_of(texture, (slices, shown), Some(image), options)?; - let before = reshaped(texture, format, &sources, options)?; - let edit = TextureEdit::Imported { - name: name.to_string(), - format, - mips: u32::from(texture.mip_count), - replaced: true, - }; - Ok((before, edit)) - })) + Some( + reshapeable(ttpf, doc, name).and_then(|(texture, slices, shown)| { + let format = match choice { + FormatChoice::Fixed(format) => format, + FormatChoice::Automatic => texture.pixel_format(), + }; + let sources = sources_of(texture, (slices, shown), Some(image), options)?; + let before = reshaped(texture, format, &sources, options)?; + let edit = TextureEdit::Imported { + name: name.to_string(), + format, + mips: u32::from(texture.mip_count), + replaced: true, + }; + Ok((before, edit)) + }), + ) } /// Whether a scanned GTA VI dictionary takes `texture` as a new one: a name it stores in lower diff --git a/src/state/gta6/textures/gta6_embedded_edit/mod.rs b/src/state/gta6/textures/gta6_embedded_edit/mod.rs index ff95c836d..93cce89bc 100644 --- a/src/state/gta6/textures/gta6_embedded_edit/mod.rs +++ b/src/state/gta6/textures/gta6_embedded_edit/mod.rs @@ -16,8 +16,10 @@ use or_io::gta6::headerless::{ }; use or_io::gta6::Texture; +use super::TexturesSession; use crate::state::document::Document; use crate::state::edit_history::{Change, Swap}; +use crate::state::gta6::session::Gta6Session; use crate::state::gta6_edit::EditSections; use crate::state::gta6_resource::{drawable_of, texture_name}; use crate::state::gta6_resource_save::EditedSave; @@ -35,27 +37,35 @@ pub(in crate::state) enum Held { /// What each scanned body's embedded textures were edited to, by its document's path and the /// texture's key. -// ponytail: one map for the whole app, as the heads are; an undo swaps one texture's entry. -static EDITED: Mutex>> = Mutex::new(BTreeMap::new()); +#[derive(Clone, Default)] +pub(super) struct EmbeddedEditCache(Arc>>>); -fn edits() -> MutexGuard<'static, BTreeMap>> { - EDITED.lock().unwrap_or_else(|p| p.into_inner()) +fn edits(textures: &TexturesSession) -> MutexGuard<'_, BTreeMap>> { + textures + .embedded_edit + .0 + .lock() + .unwrap_or_else(|p| p.into_inner()) } /// Forget the edits of the body at `path`, which opens anew with none. -pub(in crate::state) fn forget(path: &Path) { - edits().remove(path); +pub(in crate::state) fn forget(textures: &TexturesSession, path: &Path) { + edits(textures).remove(path); } /// What the document holds for the embedded texture `key` of the body at `path`, if it edited it. -pub(in crate::state) fn edited(path: &Path, key: u64) -> Option { - edits().get(path)?.get(&key).cloned() +pub(in crate::state) fn edited(textures: &TexturesSession, path: &Path, key: u64) -> Option { + edits(textures).get(path)?.get(&key).cloned() } /// The pixels the embedded texture `key` of the body at `path` was replaced with, if it was. #[cfg(test)] -pub(in crate::state) fn replaced(path: &Path, key: u64) -> Option> { - match edited(path, key)? { +pub(in crate::state) fn replaced( + textures: &TexturesSession, + path: &Path, + key: u64, +) -> Option> { + match edited(textures, path, key)? { Held::Texture(texture) => Some(texture.pixels), Held::Removed => None, } @@ -76,15 +86,15 @@ fn bound_key(state: &AppState, doc: DocumentId, name: &str) -> Option<(PathBuf, let path = document.path.clone()?; let drawable = drawable_of(resource, None)?; let keys = || (drawable.shaders.iter()).flat_map(|s| s.texture_keys.iter().flatten()); - let key = *keys().find(|key| texture_name(**key).eq_ignore_ascii_case(name))?; + let key = *keys().find(|key| texture_name(&state.gta6, **key).eq_ignore_ascii_case(name))?; let slots = keys().filter(|k| **k == key).count(); Some((path, fragment, key, slots)) } /// The texture the document shows embedded under `key` in the body at `path`, if it reads, and /// whether it is a 2D texture of one slice; `None` where none is embedded. -fn shown(path: &Path, key: u64) -> Option<(Option, bool)> { - match edited(path, key) { +fn shown(textures: &TexturesSession, path: &Path, key: u64) -> Option<(Option, bool)> { + match edited(textures, path, key) { Some(Held::Texture(texture)) => return Some((Some(texture), true)), Some(Held::Removed) => return None, None => {} @@ -99,11 +109,11 @@ fn shown(path: &Path, key: u64) -> Option<(Option, bool)> { } /// The keys the document shows embedded in the body at `path`. -fn shown_keys(path: &Path) -> BTreeSet { +fn shown_keys(textures: &TexturesSession, path: &Path) -> BTreeSet { let head = crate::state::gta6_head::head_of(path); let read = (head.iter()).flat_map(|h| (**h).as_ref().ok().map(|h| &h.textures)); let mut keys: BTreeSet = read.flatten().flatten().map(|t| t.key).collect(); - for (key, held) in edits().get(path).into_iter().flatten() { + for (key, held) in edits(textures).get(path).into_iter().flatten() { match held { Held::Texture(_) => keys.insert(*key), Held::Removed => keys.remove(key), @@ -116,12 +126,12 @@ fn shown_keys(path: &Path) -> BTreeSet { /// of `doc` binds and shows embedded; `None` where it embeds none of that name. fn embedded_key(state: &AppState, doc: DocumentId, name: &str) -> Option<(PathBuf, bool, u64)> { let (path, fragment, key, _) = bound_key(state, doc, name)?; - is_shown(&path, key).then_some((path, fragment, key)) + is_shown(&state.gta6.textures, &path, key).then_some((path, fragment, key)) } /// Whether [`shown`] finds a texture, without copying its pixels: the preview asks every frame. -fn is_shown(path: &Path, key: u64) -> bool { - match edits().get(path).and_then(|held| held.get(&key)) { +fn is_shown(textures: &TexturesSession, path: &Path, key: u64) -> bool { + match edits(textures).get(path).and_then(|held| held.get(&key)) { Some(Held::Texture(_)) => return true, Some(Held::Removed) => return false, None => {} @@ -239,6 +249,7 @@ fn of_grc(key: u64, texture: &GrcTexture) -> Result { /// A step's entry for one embedded texture: the one the map does not hold now, `None` for none. struct Step { + textures: TexturesSession, path: PathBuf, key: u64, other: Option, @@ -246,7 +257,7 @@ struct Step { impl Swap for Step { fn swap(&mut self, _: &mut DocPayload) -> bool { - let mut held = edits(); + let mut held = edits(&self.textures); let textures = held.entry(self.path.clone()).or_default(); let now = match self.other.take() { Some(entry) => textures.insert(self.key, entry), @@ -281,7 +292,7 @@ impl AppState { image: &Path, (format, options): (FormatChoice, &TextureBuildOptions), ) -> Result { - let (read, one_slice) = shown(&path, key) + let (read, one_slice) = shown(&self.gta6.textures, &path, key) .ok_or_else(|| tr!("{name} is not in this dictionary", name = name))?; if !one_slice { return Err(tr!( @@ -318,14 +329,16 @@ impl AppState { ) -> Option> { let (path, _, key, _) = bound_key(self, doc, &texture.name)?; let name = texture.name.clone(); - let others = shown_keys(&path).into_iter().any(|k| k != key); + let others = shown_keys(&self.gta6.textures, &path) + .into_iter() + .any(|k| k != key); if others { return Some(Err(tr!( "This drawable already embeds another texture, and a dictionary of two was never measured, so {name} is not embedded.", name = name ))); } - let replaced = shown(&path, key).is_some(); + let replaced = shown(&self.gta6.textures, &path, key).is_some(); let held = match of_grc(key, texture) { Ok(held) => held, Err(why) => return Some(Err(why)), @@ -343,7 +356,7 @@ impl AppState { name: &str, ) -> Option> { let (path, _, key, slots) = bound_key(self, doc, name)?; - if shown(&path, key).is_none() { + if shown(&self.gta6.textures, &path, key).is_none() { return Some(Err(tr!( "{name} is not carried by this drawable", name = name @@ -366,10 +379,14 @@ impl AppState { held: Held, label: String, ) { - let was = edits().entry(path.clone()).or_default().insert(key, held); + let was = edits(&self.gta6.textures) + .entry(path.clone()) + .or_default() + .insert(key, held); let change = Change::Part { key: Some(format!("gta6 embedded texture {key:016X}")), parts: vec![Box::new(Step { + textures: self.gta6.textures.clone(), path, key, other: was, @@ -405,6 +422,7 @@ fn same_shape( /// `held` written over the drawable `sections` hold: each texture unembedded first, then each held /// in place where the body embeds it in that shape, else re-planned or embedded anew. fn write_held( + gta6: &Gta6Session, sections: &mut Rpf9Sections, fragment: bool, held: &[(u64, Held)], @@ -437,12 +455,12 @@ fn write_held( } None => { let model = planned(*key, texture)?; - let word = (crate::state::gta6_edit::named_word(*key)) + let word = (crate::state::gta6_edit::named_word(gta6, *key)) .or_else(|| key_word(§ions.virtual_section, *key)) .ok_or_else(|| { tr!( "No name or bound entry states the 32-bit name hash of {name}, so it is not embedded.", - name = texture_name(*key) + name = texture_name(gta6, *key) ) })?; embed_texture(sections, fragment, *key, word, &model).map_err(|e| e.to_string())?; @@ -454,15 +472,18 @@ fn write_held( /// The GTA VI drawable row's `edited_sections` before its glTF imports: its materials, physics and /// bones, then each embedded texture replaced, re-planned, embedded or unembedded. -pub(in crate::state) fn edited_save(document: &Document) -> Option> { - let save = crate::state::gta6_bone_edit::edited_save(document)?; +pub(in crate::state) fn edited_save( + document: &Document, + gta6: &Gta6Session, +) -> Option> { + let save = crate::state::gta6_bone_edit::edited_save(document, gta6)?; let DocPayload::Gta6Drawable(resource) = &document.payload else { return Some(save); }; let fragment = matches!(**resource, Resource::DrawableWithBound(_)); let held: Vec<(u64, Held)> = (document.path.as_deref()) .and_then(|p| { - let textures = edits(); + let textures = edits(>a6.textures); let held = textures.get(p)?; Some(held.iter().map(|(k, v)| (*k, v.clone())).collect()) }) @@ -470,6 +491,7 @@ pub(in crate::state) fn edited_save(document: &Document) -> Option Option { let edit: Arc = Arc::new(move |role, sections| { edit(role, sections)?; - write_held(sections, fragment, &held) + write_held(>a6, sections, fragment, &held) }); EditedSave::Body { archive, diff --git a/src/state/gta6/textures/gta6_embedded_edit/tests.rs b/src/state/gta6/textures/gta6_embedded_edit/tests.rs index cdf1ea068..fab6427e1 100644 --- a/src/state/gta6/textures/gta6_embedded_edit/tests.rs +++ b/src/state/gta6/textures/gta6_embedded_edit/tests.rs @@ -110,7 +110,7 @@ fn an_embedded_texture_is_replaced_drawn_undone_and_saved_into_its_own_tiles() { settle(&mut state); let doc = (state.active_document).unwrap_or_else(|| panic!("opened: {}", state.error_dialog.message)); - let name = texture_name(key); + let name = texture_name(&state.gta6, key); assert!(embeds(&state, doc, &name)); assert!(!embeds(&state, doc, "hash_0000000000000001")); assert_eq!(state.bound_texture_pack(doc, &name), Ok(doc)); @@ -127,7 +127,7 @@ fn an_embedded_texture_is_replaced_drawn_undone_and_saved_into_its_own_tiles() { let (auto, options) = (FormatChoice::Automatic, TextureBuildOptions::default()); let edit = state.replace_embedded_texture(doc, &name, &png, auto, &options); edit.expect("it embeds that texture").expect("replaced"); - let new = replaced(&path, key).expect("the pixels the document holds"); + let new = replaced(&state.gta6.textures, &path, key).expect("the pixels the document holds"); assert_eq!(new.len(), PIXELS); assert!(new.chunks(8).all(|block| block == &new[..8]), "one block"); assert!(new != vec![0x5A; PIXELS]); @@ -135,7 +135,7 @@ fn an_embedded_texture_is_replaced_drawn_undone_and_saved_into_its_own_tiles() { // The view draws the pixels the document holds. let drawn = |state: &AppState| { let payload = &state.document(doc).expect("open").payload; - match crate::state::gta6_head::texture_named(payload, None, &name) { + match crate::state::gta6_head::texture_named(&state.gta6, payload, None, &name) { Some(Texture::Owned(t)) => t.backing_store.clone(), _ => panic!("the embedded texture is drawn"), } @@ -144,7 +144,7 @@ fn an_embedded_texture_is_replaced_drawn_undone_and_saved_into_its_own_tiles() { state.active_document = Some(doc); assert!(state.undo().is_some()); assert_eq!( - replaced(&path, key), + replaced(&state.gta6.textures, &path, key), None, "undone, the body's pixels are drawn" ); @@ -168,7 +168,8 @@ fn an_embedded_texture_is_replaced_drawn_undone_and_saved_into_its_own_tiles() { let edit = state.replace_embedded_texture(doc, &name, &small, auto, &options); edit.expect("it embeds that texture") .expect("replaced in another size"); - let smaller = replaced(&path, key).expect("the pixels the document holds"); + let smaller = + replaced(&state.gta6.textures, &path, key).expect("the pixels the document holds"); // 16 × 16 blocks of 8 bytes, then 8 × 8: the two levels the texture held. assert_eq!(smaller.len(), (16 * 16 + 8 * 8) * 8); let saved = |state: &mut AppState| { @@ -195,7 +196,7 @@ fn an_embedded_texture_is_replaced_drawn_undone_and_saved_into_its_own_tiles() { edit.expect("a GTA VI drawable").expect("unembedded"); assert!(!embeds(&state, doc, &name)); let payload = &state.document(doc).expect("open").payload; - assert!(crate::state::gta6_head::texture_named(payload, None, &name).is_none()); + assert!(crate::state::gta6_head::texture_named(&state.gta6, payload, None, &name).is_none()); let unembedded = saved(&mut state); let head = read_drawable_head( &unembedded.virtual_section, @@ -207,9 +208,9 @@ fn an_embedded_texture_is_replaced_drawn_undone_and_saved_into_its_own_tiles() { // Undone, the document holds the smaller texture again. state.active_document = Some(doc); assert!(state.undo().is_some()); - assert_eq!(replaced(&path, key), Some(smaller)); + assert_eq!(replaced(&state.gta6.textures, &path, key), Some(smaller)); // The body opened anew, as after a close that did not save, holds none of them. - crate::state::rpf9_scan::read_body(&path, &path, 0).expect("it opens again"); - assert_eq!(replaced(&path, key), None); + crate::state::rpf9_scan::read_body(&state.gta6, &path, &path, 0).expect("it opens again"); + assert_eq!(replaced(&state.gta6.textures, &path, key), None); } diff --git a/src/state/gta6/textures/gta6_texture_index.rs b/src/state/gta6/textures/gta6_texture_index.rs index c3b348368..9ec35c40d 100644 --- a/src/state/gta6/textures/gta6_texture_index.rs +++ b/src/state/gta6/textures/gta6_texture_index.rs @@ -594,7 +594,12 @@ impl AppState { for path in wanted { let open = (self.documents.iter()).any(|d| d.path.as_deref() == Some(path.as_path())); if self.gta6_finders.texture_packs.tried.insert(path.clone()) && !open { - open_on_a_worker(&mut self.gta6_finders.texture_packs.opening, path); + open_on_a_worker( + &mut self.gta6_finders.texture_packs.opening, + path, + self.gta6.ttpf.clone(), + self.gta6.install.clone(), + ); } } } @@ -683,13 +688,19 @@ impl AppState { } /// Read the header of the pack at `path` on a worker of the bounded pool, into `opening`. -fn open_on_a_worker(opening: &mut Opening, path: PathBuf) { +fn open_on_a_worker( + opening: &mut Opening, + path: PathBuf, + ttpf_session: crate::state::ttpf_document::TtpfSession, + install: crate::state::gta6::install::InstallSession, +) { static POOL: std::sync::OnceLock = std::sync::OnceLock::new(); let pool = POOL.get_or_init(|| or_job::Pool::new(or_job::workers(), OPENING_STACK, || {})); let opened = Arc::clone(&opening.opened); opening.asked.push(path.clone()); let open = move || { - let ttpf = crate::state::ttpf_document::TtpfDocument::open(&path); + let ttpf = + crate::state::ttpf_document::TtpfDocument::open_with(&path, ttpf_session, install); (opened.lock().unwrap_or_else(|p| p.into_inner())).push((path, ttpf)); }; let task = Arc::new(Mutex::new(Some(open))); @@ -768,7 +779,7 @@ mod tests { }; assert_eq!( base(&state), - Some(texture_name(normal)), + Some(texture_name(&state.gta6, normal)), "no pack states a format" ); @@ -782,6 +793,6 @@ mod tests { state.gta6_finders.texture_packs.built = Arc::new(Mutex::new(Some(index))); assert_eq!(state.indexed_texture_format(colour), Some(72 << 3)); assert_eq!(state.indexed_texture_format(colour ^ 1), None); - assert_eq!(base(&state), Some(texture_name(colour))); + assert_eq!(base(&state), Some(texture_name(&state.gta6, colour))); } } diff --git a/src/state/gta6/textures/gta6_texture_names_file.rs b/src/state/gta6/textures/gta6_texture_names_file.rs index 0c322a6b9..91529d03b 100644 --- a/src/state/gta6/textures/gta6_texture_names_file.rs +++ b/src/state/gta6/textures/gta6_texture_names_file.rs @@ -45,6 +45,7 @@ impl AppState { } } let path = path.to_path_buf(); + let ttpf = self.gta6.ttpf.clone(); let doing = tr!("Naming GTA VI textures from {file}", file = path.display()); let run = TextureNaming::run(doing, move |cancel, progress| { let mut bytes = Vec::new(); @@ -64,7 +65,7 @@ impl AppState { return NamingEnded::Stopped; } progress.reached(done as u64, lines.len() as u64); - named += crate::state::ttpf_document::learn_rule_names(line, &keys); + named += crate::state::ttpf_document::learn_rule_names(&ttpf, line, &keys); } NamingEnded::Loaded(named) }); diff --git a/src/state/gta6/textures/gta6_texture_naming.rs b/src/state/gta6/textures/gta6_texture_naming.rs index 86034737f..313a12a9c 100644 --- a/src/state/gta6/textures/gta6_texture_naming.rs +++ b/src/state/gta6/textures/gta6_texture_naming.rs @@ -44,7 +44,11 @@ pub(in crate::state) struct TextureNaming { impl TextureNaming { /// Learn the names the rules give from `stems` for any of `keys`, on a worker. - pub(in crate::state) fn start(stems: Vec, keys: HashSet) -> Self { + pub(in crate::state) fn start( + ttpf: crate::state::ttpf_document::TtpfSession, + stems: Vec, + keys: HashSet, + ) -> Self { let doing = tr!("Naming GTA VI textures from their drawables' names").to_string(); Self::run(doing, move |cancel, progress| { let mut named = 0; @@ -53,7 +57,7 @@ impl TextureNaming { return NamingEnded::Stopped; } progress.reached(done as u64, stems.len() as u64); - named += crate::state::ttpf_document::learn_rule_names(stem, &keys); + named += crate::state::ttpf_document::learn_rule_names(&ttpf, stem, &keys); } NamingEnded::Named(named) }) diff --git a/src/state/gta6/textures/gta6_textures.rs b/src/state/gta6/textures/gta6_textures.rs index c1a6d2400..968ba5258 100644 --- a/src/state/gta6/textures/gta6_textures.rs +++ b/src/state/gta6/textures/gta6_textures.rs @@ -23,6 +23,25 @@ const PICK_A_TEXTURE: &str = "Select one of its textures, under Textures"; /// The textures the drawable's shaders bind, by the names their keys are known by; the size and /// format only of one its own dictionary holds. pub(crate) fn list(payload: &DocPayload, selection: Option) -> TextureListing { + list_with(&Default::default(), payload, selection) +} + +pub(crate) fn textures_in_with( + gta6: &crate::state::gta6::session::Gta6Session, + payload: &DocPayload, + selection: Option, +) -> TextureListing { + if matches!(payload, DocPayload::Gta6Drawable(_)) { + return list_with(gta6, payload, selection); + } + crate::state::textures::textures_in(payload, selection) +} + +pub(crate) fn list_with( + gta6: &crate::state::gta6::session::Gta6Session, + payload: &DocPayload, + selection: Option, +) -> TextureListing { use or_io::gta6::headerless::{Entry, Resource}; let DocPayload::Gta6Drawable(resource) = payload else { return TextureListing::Nothing("Active document has no texture dictionary"); @@ -43,7 +62,7 @@ pub(crate) fn list(payload: &DocPayload, selection: Option) -> Tex let entry = selection.and_then(SelectionKey::dict_hash); let mut names: Vec = Vec::new(); for key in (drawable.shaders.iter()).flat_map(|s| s.texture_keys.iter().flatten()) { - let name = texture_name(*key); + let name = texture_name(gta6, *key); if !names.contains(&name) { names.push(name); } @@ -98,7 +117,13 @@ pub fn sized_for_gta6( .iter() .for_each(|t| (&t.name, t.width).hash(&mut hasher)); let asked = hasher.finish(); - let mut kept = SIZED.lock().unwrap_or_else(|p| p.into_inner()); + let mut kept = state + .gta6 + .textures + .sized + .0 + .lock() + .unwrap_or_else(|p| p.into_inner()); if let Some((_, sizes)) = kept.as_ref().filter(|(at, _)| *at == asked) { for (t, (width, height, format)) in textures.iter_mut().zip(sizes) { (t.width, t.height, t.format) = (*width, *height, *format); @@ -130,7 +155,9 @@ pub fn sized_for_gta6( /// What [`sized_for_gta6`] last found, by what it was asked: each texture's size and format. type Sized = Option<(u64, Vec<(u32, u32, GrcTextureFormat)>)>; -static SIZED: std::sync::Mutex = std::sync::Mutex::new(None); + +#[derive(Clone, Default)] +pub(super) struct SizedCache(std::sync::Arc>); /// The directory entry an open pack holds for texture `name`, a GTA VI drawable's key by the name it is known by. pub fn open_pack_entry(state: &crate::state::AppState, name: &str) -> Option { diff --git a/src/state/gta6/textures/mod.rs b/src/state/gta6/textures/mod.rs index 73649bf77..f65ca1bd2 100644 --- a/src/state/gta6/textures/mod.rs +++ b/src/state/gta6/textures/mod.rs @@ -5,3 +5,10 @@ pub(crate) mod gta6_texture_index; pub(crate) mod gta6_texture_names_file; pub(crate) mod gta6_texture_naming; pub(crate) mod gta6_textures; + +/// Per-instance texture caches owned by [`crate::state::gta6::session::Gta6Session`]. +#[derive(Clone, Default)] +pub(crate) struct TexturesSession { + sized: gta6_textures::SizedCache, + embedded_edit: gta6_embedded_edit::EmbeddedEditCache, +} diff --git a/src/state/gta6/world/gta6_map/entity.rs b/src/state/gta6/world/gta6_map/entity.rs index cd5d1b600..3a09b44d9 100644 --- a/src/state/gta6/world/gta6_map/entity.rs +++ b/src/state/gta6/world/gta6_map/entity.rs @@ -601,12 +601,12 @@ impl AppState { Edit::Add { from, .. } => { let shown = (self.scanned_map().and_then(|s| s.data())) .and_then(|m| m.entities.get(*from.first()?)) - .map(|e| archetype_shown(e.archetype_name)) + .map(|e| archetype_shown(&self.gta6.install, e.archetype_name)) .unwrap_or_default(); tr!("Added an entity of {name}", name = shown) } Edit::New { name, .. } => { - let shown = archetype_shown(*name); + let shown = archetype_shown(&self.gta6.install, *name); tr!("Added an entity of {name}", name = shown) } Edit::Remove(index) => tr!("Removed entity {index}", index = index), @@ -653,7 +653,11 @@ impl AppState { path: &Path, before: &Rpf9Sections, ) -> Result { - let meta = MetaDocument::from_gta_vi_headerless(&before.virtual_section, &before.physical)?; + let meta = MetaDocument::from_gta_vi_headerless_with( + &before.virtual_section, + &before.physical, + self.gta6.install.clone(), + )?; super::keep(path, &before.virtual_section, &before.physical); let (active, workspace) = (self.active_document, self.active_workspace); let doc = self.insert_document(path.to_path_buf(), DocPayload::Meta(meta), None, None); @@ -698,8 +702,9 @@ impl AppState { } /// An archetype as the entity list names it: the harvested GTA VI name for its hash, else its hash. -fn archetype_shown(hash: u32) -> String { - crate::state::gta6_names::name32(hash).unwrap_or_else(|| or_maps::Name::of(hash).shown()) +fn archetype_shown(install: &crate::state::gta6::install::InstallSession, hash: u32) -> String { + crate::state::gta6_names::name32(install, hash) + .unwrap_or_else(|| or_maps::Name::of(hash).shown()) } /// How far east a duplicate stands from its source: one grid step where the grid snaps, else a metre. diff --git a/src/state/gta6/world/gta6_map/links/mod.rs b/src/state/gta6/world/gta6_map/links/mod.rs index bcf042f4a..41b160079 100644 --- a/src/state/gta6/world/gta6_map/links/mod.rs +++ b/src/state/gta6/world/gta6_map/links/mod.rs @@ -428,7 +428,8 @@ fn model_in_place(file: &File, t: &Target) -> Option> { _ => return None, }; let normals = Mat3::from_mat4(t.place).inverse().transpose(); - let meshes = crate::render::gta6_drawable::meshes_at(drawable, 0, None, None, &|_| None); + let gta6 = crate::state::gta6::session::Gta6Session::default(); + let meshes = crate::render::gta6_drawable::meshes_at(>a6, drawable, 0, None, None, &|_| None); let placed = (meshes.into_iter()) .map(|mesh| Geometry { vertices: (mesh.vertices.into_iter()) diff --git a/src/state/gta6/world/gta6_world/mod.rs b/src/state/gta6/world/gta6_world/mod.rs index 1a319a6c0..d4348da2a 100644 --- a/src/state/gta6/world/gta6_world/mod.rs +++ b/src/state/gta6/world/gta6_world/mod.rs @@ -193,8 +193,11 @@ impl Area { /// The name of the archetype `row` places where the names kept of the bodies harvested hold it, /// else its hash. -pub fn archetype_name(row: &PlacementRow) -> String { - let names = crate::state::gta6_names::vocabulary(); +pub(crate) fn archetype_name( + install: &crate::state::gta6::install::InstallSession, + row: &PlacementRow, +) -> String { + let names = crate::state::gta6_names::vocabulary(install); (names.confirmed(row.archetype_name, row.archetype_word)) .map_or_else(|| format!("{:#010X}", row.archetype_name), str::to_string) } diff --git a/src/state/gta6/world/gta6_world/worldview/model/mod.rs b/src/state/gta6/world/gta6_world/worldview/model/mod.rs index f980a51d6..23896f519 100644 --- a/src/state/gta6/world/gta6_world/worldview/model/mod.rs +++ b/src/state/gta6/world/gta6_world/worldview/model/mod.rs @@ -108,7 +108,9 @@ pub(super) fn model_of( let Some(models) = models.as_ref().filter(|models| !models.is_empty()) else { continue; }; - let read = crate::render::gta6_drawable::meshes_at(drawable, level, None, None, &|_| None); + let gta6 = crate::state::gta6::session::Gta6Session::default(); + let read = + crate::render::gta6_drawable::meshes_at(>a6, drawable, level, None, None, &|_| None); // ⚠ One mesh comes back for each geometry whose positions read, in the models' order. let geometries = (models.iter()) .flat_map(|model| model.geometries.iter().flatten()) diff --git a/src/state/jobs.rs b/src/state/jobs.rs index c69427941..95aafd3ae 100644 --- a/src/state/jobs.rs +++ b/src/state/jobs.rs @@ -245,11 +245,11 @@ impl AppState { .chain(self.set_finding_jobs()) .chain(self.map_search_jobs()) .chain(self.audio_linking_jobs()) - .chain(super::gta6_dialogue::job()) + .chain(super::gta6_dialogue::job(&self.gta6.audio)) .chain(self.awc_opus_job()) - .chain(super::gta6_install_scan::job()) - .chain(super::gta6_modding::text_search::job()) - .chain(super::ttpf_document::calibration::job()) + .chain(super::gta6_install_scan::job(&self.gta6.install)) + .chain(super::gta6_modding::text_search::job(&self.gta6.modding)) + .chain(super::ttpf_document::calibration::job(&self.gta6.ttpf)) .chain(super::rpf_archive_open::tree_verbs::plan_job::jobs()) .collect() } @@ -331,7 +331,7 @@ impl AppState { } JobKind::ArchiveScan => { // ⚠ Its end is said once its worker sees the stop, by `poll_install_scan`. - super::gta6_install_scan::stop(); + super::gta6_install_scan::stop(&self.gta6.install); let running: Vec<_> = (self.archive_scans()) .filter(|scan| scan.job().is_some()) .collect(); @@ -373,7 +373,7 @@ impl AppState { // ⚠ Its end shows in the audio game data's view once its worker sees the stop. JobKind::AudioLinks => { self.stop_audio_linking(); - super::gta6_dialogue::stop(); + super::gta6_dialogue::stop(&self.gta6.audio); false } // ⚠ Its end is said once its worker sees the stop, by `poll_awc_opus`. @@ -383,12 +383,12 @@ impl AppState { } // ⚠ Its end is said once its worker sees the stop, by `poll_texture_calibration`. JobKind::TextureCalibration => { - super::ttpf_document::calibration::stop(); + super::ttpf_document::calibration::stop(&self.gta6.ttpf); false } // ⚠ Its end is said once its worker sees the stop, by `poll_gta6_text_search`. JobKind::TextSearch => { - super::gta6_modding::text_search::stop(); + super::gta6_modding::text_search::stop(&self.gta6.modding); false } // ⚠ Its end is said once its worker sees the stop, by `poll_mod_packages`. diff --git a/src/state/media_playback.rs b/src/state/media_playback.rs index 28c3d1172..0b9100ff9 100644 --- a/src/state/media_playback.rs +++ b/src/state/media_playback.rs @@ -136,7 +136,7 @@ impl AppState { .iter() .map(|g| { // A stream that speaks a dialogue line found carries the line as comments. - let comments = super::gta6_dialogue::comments(g.id); + let comments = super::gta6_dialogue::comments(&self.gta6.audio, g.id); Ok(( format!("{:08X}.opus", g.id), ogg::ogg_opus_tagged(g, &comments).map_err(|e| e.to_string())?, diff --git a/src/state/mod.rs b/src/state/mod.rs index a65402e40..b158a2dd2 100644 --- a/src/state/mod.rs +++ b/src/state/mod.rs @@ -95,7 +95,8 @@ mod particle_textures; pub mod payload_handlers; mod pending_prompts; mod photo_documents; -pub use photo_documents::{gta6_models, gta6_models_and_kits, Gta6Model}; +pub use photo_documents::Gta6Model; +pub(crate) use photo_documents::{gta6_models, gta6_models_and_kits}; pub mod plugins; pub mod prefs; pub mod presets; @@ -146,13 +147,14 @@ pub use clip_regions::ClipRegionsLoadResult; pub use closing::{AfterClose, CloseAnswer}; pub use clothing::{Clothing, ClothingVariant}; pub use document::{ - drawable_mut, enhanced_drawable_mut, enhanced_drawables_of, gta6_script, hash_name_or_text, - hash_text_name, meta_names_from_the_text, meta_schema, meta_text_name, name_table_text, - natives_dir, ArchiveId, BaselineValue, DatTable, DocPayload, Document, DocumentId, - DocumentKind, DocumentStrings, FxcDocument, Gta6ScriptDocument, HexDocument, LoadingState, - MaterialAddress, MaterialBaseline, MetaDocument, RelDocument, ResourceImage, RpfNodeId, - ScriptDocument, Slot, TextDocument, STRING_NAMES_NEED_KEYS, + drawable_mut, enhanced_drawable_mut, enhanced_drawables_of, gta6_script, + meta_names_from_the_text, meta_schema, name_table_text, natives_dir, ArchiveId, BaselineValue, + DatTable, DocPayload, Document, DocumentId, DocumentKind, DocumentStrings, FxcDocument, + Gta6ScriptDocument, HexDocument, LoadingState, MaterialAddress, MaterialBaseline, MetaDocument, + RelDocument, ResourceImage, RpfNodeId, ScriptDocument, Slot, TextDocument, + STRING_NAMES_NEED_KEYS, }; +pub(crate) use document::{hash_name_or_text, hash_text_name, meta_text_name}; pub use document_io::{described_root, never_written}; use document_io::{empty_file_bytes_for_kind, empty_payload_for_kind, unique_child_name}; pub use edit_history::{Change, ClipFieldSnapshot, EditDirection, EditHistory, Swap}; @@ -268,6 +270,7 @@ pub struct AppState { next_doc_id: AtomicU64, pub bg: BackgroundControllers, gta6_finders: Gta6Finders, + pub(crate) gta6: gta6::session::Gta6Session, pub jobs: jobs::JobLog, pub prompts: PendingPrompts, /// Set once an exit's close has gone ahead; the editor loop exits on it. @@ -353,6 +356,7 @@ impl AppState { next_doc_id: AtomicU64::new(1), bg: BackgroundControllers::spawn(known_game_paths), gta6_finders: Gta6Finders::default(), + gta6: gta6::session::Gta6Session::default(), jobs: jobs::JobLog::default(), prompts: PendingPrompts::default(), should_exit: false, @@ -683,8 +687,11 @@ impl AppState { if let Some((names, keys)) = ttpf_document::texture_naming_work(&self.documents, &doc.payload) { - (self.gta6_finders.texture_naming) - .push(gta6_texture_naming::TextureNaming::start(names, keys)); + (self.gta6_finders.texture_naming).push(gta6_texture_naming::TextureNaming::start( + self.gta6.ttpf.clone(), + names, + keys, + )); } if matches!(kind, DocumentKind::Ypt) { self.io_queue.file_watcher.watch(path.clone()); diff --git a/src/state/photo_documents.rs b/src/state/photo_documents.rs index 8dd735b23..9af890878 100644 --- a/src/state/photo_documents.rs +++ b/src/state/photo_documents.rs @@ -41,17 +41,19 @@ fn level_of(leaf: &str, only: Option<&HashSet>) -> Option<(String, usize /// Every drawable and fragment whose path starts with `under`, in every archive below `root`, /// nested ones included: one per model, at the most detailed level it has, in name order. -pub fn gta6_models( +pub(crate) fn gta6_models( + install: &crate::state::gta6::install::InstallSession, root: &Path, under: &str, only: Option<&HashSet>, ) -> Result, String> { - Ok(gta6_models_and_kits(root, under, only, None)?.0) + Ok(gta6_models_and_kits(install, root, under, only, None)?.0) } /// [`gta6_models`], and in the same walk the ped catalogue of each kit `kits` names, by the /// kit's name: the metadata body of that name in an archive that holds paths under `under`. -pub fn gta6_models_and_kits( +pub(crate) fn gta6_models_and_kits( + install: &crate::state::gta6::install::InstallSession, root: &Path, under: &str, only: Option<&HashSet>, @@ -88,7 +90,7 @@ pub fn gta6_models_and_kits( // A weapon's parts are found by the names of the bodies beside it. let labels = std::mem::take(&mut walk.labels); if !labels.is_empty() { - super::gta6_names::add_labels(path, labels); + super::gta6_names::add_labels(install, path, labels); } } let models = found.into_values().map(|(_, model)| model).collect(); @@ -215,7 +217,8 @@ impl AppState { /// `bytes` read as the file at `path` and held as a document that is not made active. pub fn hold_bytes(&mut self, path: &Path, bytes: &[u8]) -> Result { let kind = DocumentKind::from_path(path).ok_or("not a kind of file OpenRage opens")?; - let payload = document_io::parse_payload(path, kind, bytes, self.keys.provider())?; + let payload = + document_io::parse_payload_with(&self.gta6, path, kind, bytes, self.keys.provider())?; let id = self.alloc_doc_id(); self.documents .push(Document::new(id, Some(path.to_path_buf()), payload)); @@ -232,7 +235,8 @@ impl AppState { let view = super::rpf9_scan::View::Drawable; let path = super::rpf9_scan::body_path(&model.archive, model.offset, view); let crypto = self.keys.provider(); - let (payload, _) = document_io::parse_payload_from_path(&path, DocumentKind::Hex, crypto)?; + let (payload, _) = + document_io::parse_payload_from_path(&self.gta6, &path, DocumentKind::Hex, crypto)?; if !matches!(payload, super::DocPayload::Gta6Drawable(_)) { return Err("holds no model".into()); } @@ -254,7 +258,8 @@ impl AppState { kind: DocumentKind, bytes: &[u8], ) -> Result { - match document_io::parse_payload(path, kind, bytes, self.keys.provider())? { + match document_io::parse_payload_with(&self.gta6, path, kind, bytes, self.keys.provider())? + { super::DocPayload::Resource(asset) => Ok(asset), _ => Err("not a resource file".into()), } diff --git a/src/state/reload_open_file.rs b/src/state/reload_open_file.rs index 080445d2b..180a6da5d 100644 --- a/src/state/reload_open_file.rs +++ b/src/state/reload_open_file.rs @@ -44,7 +44,8 @@ impl AppState { } continue; } - let (payload, resource) = parse_payload_from_path(path, kind, self.keys.provider())?; + let (payload, resource) = + parse_payload_from_path(&self.gta6, path, kind, self.keys.provider())?; if let Some(doc) = self.document_mut(id) { doc.reloaded(payload, resource); } diff --git a/src/state/rpf/rpf9_scan/ciphered/mod.rs b/src/state/rpf/rpf9_scan/ciphered/mod.rs index 8e3219601..0dce479cc 100644 --- a/src/state/rpf/rpf9_scan/ciphered/mod.rs +++ b/src/state/rpf/rpf9_scan/ciphered/mod.rs @@ -6,15 +6,19 @@ use super::*; /// The payload a decrypted, inflated body opens as: a PSO or RBF through the metadata reader, text /// as text, else its bytes under the reason none reads them. A headerless body (a compiled script, a /// texture) is kept as bytes, never decoded as Latin-1 text the way a `.bin` path otherwise would be. -fn decrypted_payload(path: &Path, bytes: Vec) -> DocPayload { +fn decrypted_payload( + gta6: &crate::state::gta6::session::Gta6Session, + path: &Path, + bytes: Vec, +) -> DocPayload { if bytes.starts_with(b"PSIN") || bytes.starts_with(b"RBF0") { - return DocPayload::Meta(MetaDocument::from_bytes(bytes)); + return DocPayload::Meta(MetaDocument::from_bytes_with(bytes, gta6.install.clone())); } if crate::state::document_io::is_text(&bytes) { return super::gta6_data_xml::payload(path, bytes); } // A program the decompiler reads opens as its source; the listing takes one only it reads. - if let Some(script) = crate::state::document::gta6_script::sniffed(&bytes) { + if let Some(script) = crate::state::document::gta6_script::sniffed(>a6.script, &bytes) { return script; } if let Some(listing) = gta6_script_view::script_payload(&bytes) { @@ -83,6 +87,7 @@ pub(crate) fn decipher_entry( /// body takes, so it shows in the view a clear open of it shows; everything else inflates those /// same bytes (no second decipher) and opens by their head. pub(super) fn ciphered_payload( + gta6: &crate::state::gta6::session::Gta6Session, path: &Path, archive: &Path, req: CipheredRequest, @@ -94,13 +99,13 @@ pub(super) fn ciphered_payload( let stored = mount .read_entry_deciphered_stored(&mut file, entry, &keys) .map_err(|e| e.to_string())?; - if let Some(payload) = ciphered_resource(path, archive, &stored) { + if let Some(payload) = ciphered_resource(gta6, path, archive, &stored) { return Ok(payload); } let bytes = mount .inflate_deciphered_stored(&stored, entry) .map_err(|e| e.to_string())?; - Ok(decrypted_payload(path, bytes)) + Ok(decrypted_payload(gta6, path, bytes)) } /// Load the GTA VI key snapshot and mount the archive whose header is at `base` in the file at @@ -125,7 +130,12 @@ fn mount_ciphered( /// A content-ciphered entry's deciphered STORED bytes opened as a headerless RSC8 resource of /// `archive`, through [`body_payload`], the step a clear body takes. `None` when they are none — PSO, /// RBF and text, whose reader's head is not a block map — so the caller inflates and opens them. -fn ciphered_resource(path: &Path, archive: &Path, stored: &[u8]) -> Option { +fn ciphered_resource( + gta6: &crate::state::gta6::session::Gta6Session, + path: &Path, + archive: &Path, + stored: &[u8], +) -> Option { if !starts_stored_rpf9_resource(stored, or_io::gta6::anim::RSC8_VERSION) { return None; } @@ -138,7 +148,7 @@ fn ciphered_resource(path: &Path, archive: &Path, stored: &[u8]) -> Option bool { /// The body a path [`body_path`] made names, read and given to the view its kind has, or kept as its bytes where no reader reads it. pub(in crate::state) fn read_body( + gta6: &crate::state::gta6::session::Gta6Session, path: &Path, archive: &Path, offset: u64, ) -> Result { // A body opened anew holds none of the edits a closed document of it kept, through either door. crate::state::gta6_gltf_import::forget(path); - crate::state::gta6_embedded_edit::forget(path); - crate::state::gta6_modding::model_replace::forget(path); + crate::state::gta6_embedded_edit::forget(>a6.textures, path); + crate::state::gta6_modding::model_replace::forget(>a6.modding, path); // A content-ciphered entry the archive explorer opened left a decrypt request here, keyed by // this synthetic path; the decipher runs on this worker, not the UI thread. The clear reader // below reads only bytes stored in the clear. if let Some(req) = take_ciphered(path) { - return ciphered_payload(path, archive, req); + return ciphered_payload(gta6, path, archive, req); } // A clear row the archive's tree opened is read by its table, under the kind its start names. if let Some(read) = crate::state::rpf_archive_open::tree_open::read(path, archive, offset) { @@ -476,7 +477,7 @@ pub(in crate::state) fn read_body( return match read? { TableRead::Body(find, bytes) => { origins().insert(path.to_path_buf(), (find, false)); - body_payload(path, archive, find, bytes) + body_payload(gta6, path, archive, find, bytes) } TableRead::Plain(payload) => Ok(payload), }; @@ -488,7 +489,14 @@ pub(in crate::state) fn read_body( } // A first entry whose end is not stated ends where its list's next row starts. Err(e) => { - match crate::state::gta6_first_entry::opened(archive, &file, offset, BODY_LIMIT, &e) { + match crate::state::gta6_first_entry::opened( + >a6.install, + archive, + &file, + offset, + BODY_LIMIT, + &e, + ) { Some(opened) => { let (find, hex) = opened?; origins().insert(path.to_path_buf(), (find, false)); @@ -500,7 +508,7 @@ pub(in crate::state) fn read_body( Ok(read) => read, }; origins().insert(path.to_path_buf(), (find, path == archive)); - body_payload(path, archive, find, bytes) + body_payload(gta6, path, archive, find, bytes) } /// The archive nested at `offset` of `file`, the file at `archive`, as a scan of its own. @@ -593,7 +601,12 @@ fn animation(find: &Rpf9ScanFind, bytes: &[u8]) -> Result { } /// A headerless resource through GTA VI's RBM reader, from `bytes`, a read of `resource`. -fn headerless(path: &Path, resource: &Rpf9Resource, bytes: &[u8]) -> Result { +fn headerless( + install: &crate::state::gta6::install::InstallSession, + path: &Path, + resource: &Rpf9Resource, + bytes: &[u8], +) -> Result { if bytes.get(0x10..0x14) != Some(b"0DRP") { return Err(tr!("This body starts with four zero bytes but has no 0DRP at 0x10, so what it is and which reader fits it are not known.").to_string()); } @@ -606,7 +619,7 @@ fn headerless(path: &Path, resource: &Rpf9Resource, bytes: &[u8]) -> Result Ok(DocPayload::Meta(doc)), // The map reader needs the tables alone, so the Map screen shows a map whose tree is not read. Err(e) if map => { @@ -691,7 +704,8 @@ impl crate::state::AppState { let Some(Row::Body(find)) = found.rows.get(row).cloned() else { return; }; - let ended = crate::state::gta6_first_entry::note(&scan.path, &found, &find); + let ended = + crate::state::gta6_first_entry::note(&self.gta6.install, &scan.path, &found, &find); let view = match found.view(&find) { // Its tab says why no reader fits it, so its row raises no toast. Err(_) if opens_as_bytes(&find) && ended => Ok(View::Bytes), @@ -708,7 +722,7 @@ impl crate::state::AppState { Ok(view) => { // An effect container's effects are learned as a job of its own, with a Stop. if matches!(view, View::Effects) { - scan.read_effects(*find); + scan.read_effects(self.gta6.bodies.clone(), *find); self.show_info_toast(tr!("Its effects are read in the background, and a GTA VI drawable then names its shaders and their parameters by them.")); } let path = body_path(&scan.path, find.offset, view); @@ -728,12 +742,16 @@ impl crate::state::AppState { } /// The body at `offset` of `archive` as [`extract_rpf9_body`] writes a file of it. -pub(in crate::state) fn extracted_body(archive: &Path, offset: u64) -> Result, String> { +pub(in crate::state) fn extracted_body( + install: &crate::state::gta6::install::InstallSession, + archive: &Path, + offset: u64, +) -> Result, String> { let file = File::open(archive).map_err(|e| format!("{}: {e}", archive.display()))?; extract_rpf9_body(&file, offset, BODY_LIMIT) .map(|(_, bytes)| bytes) .or_else(|e| { - crate::state::gta6_first_entry::bytes(archive, &file, offset, BODY_LIMIT, &e) + crate::state::gta6_first_entry::bytes(install, archive, &file, offset, BODY_LIMIT, &e) .unwrap_or_else(|| Err(e.to_string())) }) } @@ -770,7 +788,12 @@ impl crate::state::AppState { // A nested archive ends with its names row; the names themselves have no end. let ends = |find: &Rpf9ScanFind| { !matches!(find.kind, Rpf9BodyKind::Names { .. }) - && crate::state::gta6_first_entry::note(&scan.path, &found, find) + && crate::state::gta6_first_entry::note( + &self.gta6.install, + &scan.path, + &found, + find, + ) }; (rows.iter()) .filter_map(|row| match found.rows.get(*row) { @@ -778,6 +801,7 @@ impl crate::state::AppState { find.file_name(), scan.path.clone(), find.offset, + self.gta6.install.clone(), )), _ => None, }) @@ -848,9 +872,13 @@ impl crate::state::AppState { impl Rpf9ScanDocument { /// Read the effects of the `SGD5` container `find` on a worker, in place of any read before it. - pub(in crate::state) fn read_effects(&self, find: Rpf9ScanFind) { + pub(in crate::state) fn read_effects( + &self, + bodies: crate::state::gta6::bodies::BodiesSession, + find: Rpf9ScanFind, + ) { *self.effects() = Some(crate::state::gta6_effects::EffectsRead::start( - &self.path, find, BODY_LIMIT, + bodies, &self.path, find, BODY_LIMIT, )); } diff --git a/src/state/rpf/rpf9_scan/payload.rs b/src/state/rpf/rpf9_scan/payload.rs index 0eb2716fa..609dfda08 100644 --- a/src/state/rpf/rpf9_scan/payload.rs +++ b/src/state/rpf/rpf9_scan/payload.rs @@ -10,6 +10,7 @@ use crate::state::{ /// What `bytes`, the body `find` of `archive`, open as under `path`: its view's read, else its bytes. pub(super) fn body_payload( + gta6: &crate::state::gta6::session::Gta6Session, path: &Path, archive: &Path, find: Rpf9ScanFind, @@ -36,16 +37,21 @@ pub(super) fn body_payload( let read = match view { View::Xml | View::Text => return Ok(super::gta6_data_xml::payload(path, bytes)), View::Pso => { - gta6_dialogue::opened(path, &find, &bytes); - return Ok(DocPayload::Meta(MetaDocument::from_bytes(bytes))); + gta6_dialogue::opened(>a6.audio, path, &find, &bytes); + return Ok(DocPayload::Meta(MetaDocument::from_bytes_with( + bytes, + gta6.install.clone(), + ))); } - View::Headerless => headerless(path, &resource()?, &bytes), + View::Headerless => headerless(>a6.install, path, &resource()?, &bytes), View::TextTable => gta6_text::Gta6TextDocument::open(resource()?.sections(&bytes).0) - .inspect(|text| gta6_dialogue::note_table(&text.table)) + .inspect(|text| gta6_dialogue::note_table(>a6.audio, &text.table)) .map(|text| DocPayload::Gta6Text(Box::new(text))), View::AudioData => gta6_text::Gta6AudioDocument::open(&bytes) .map(|audio| DocPayload::Gta6AudioData(Box::new(audio))), - View::Identified(body) => gta6_other_bodies::payload(path, body, &bytes), + View::Identified(body) => { + gta6_other_bodies::payload(>a6.bodies, >a6.install, path, body, &bytes) + } View::Effects => { let platform = or_io::container::rpf::rpf9_platform_of(archive) .unwrap_or(or_io::Platform::XboxSeries); @@ -63,7 +69,7 @@ pub(super) fn body_payload( View::Facts(signature) => { let resource = resource()?; let (virtual_section, physical) = resource.sections(&bytes); - match gta6_face::learn(path, signature, virtual_section) { + match gta6_face::learn(>a6.anim, path, signature, virtual_section) { Some(gta6_face::Learned::Skeleton(skeleton)) => { skeletons().insert(path.to_path_buf(), Ok(skeleton)); } @@ -89,13 +95,14 @@ pub(super) fn body_payload( ) }; if (dict.entries.iter()).any(|(_, e)| e.as_ref().is_ok_and(edits)) { - ttpf_document::learn_names(&dict); - gta6_entry_skeletons::keep(path, virtual_section); + ttpf_document::learn_names(>a6.ttpf, &dict); + gta6_entry_skeletons::keep(>a6.anim, path, virtual_section); return Ok(DocPayload::Gta6Drawable(Arc::new(Resource::Dictionary( dict, )))); } - if let Some(textures) = ttpf_document::scanned_textures(path, dict) { + if let Some(textures) = ttpf_document::scanned_textures(>a6.ttpf, path, dict) + { return Ok(textures); } } @@ -103,13 +110,17 @@ pub(super) fn body_payload( if let Some(c) = crate::render::gta6_cloth::opened(signature, &resource, &bytes) { return Ok(c); } - if let Some(mesh) = gta6_resource::as_ynv(path, &resource, signature, &bytes) { + if let Some(mesh) = + gta6_resource::as_ynv(>a6.physics, path, &resource, signature, &bytes) + { return Ok(DocPayload::Resource(or_io::Asset::NavMesh(mesh))); } - if let Some(p) = gta6_particles::opened(path, signature, &resource, &bytes) { + if let Some(p) = + gta6_particles::opened(>a6.particles, path, signature, &resource, &bytes) + { return Ok(p); } - gta6_resource::facts(&resource, signature, &bytes) + gta6_resource::facts(>a6.bodies, >a6.install, &resource, signature, &bytes) .map(|text| document_io::text_payload(path, text.into_bytes())) } View::Drawable => { @@ -135,6 +146,7 @@ pub(super) fn body_payload( extension: Some(if fragment { "#ft" } else { "#dr" }), }; crate::state::gta6_learned_names::learn( + >a6.install, archive, find.offset, kind, @@ -146,7 +158,7 @@ pub(super) fn body_payload( let read = Arc::new(read); if let Some(fragment) = fragment { gta6_head::keep(path, &read, virtual_section, physical, fragment); - gta6_weapon_parts::keep(path, archive, &read); + gta6_weapon_parts::keep(>a6.install, path, archive, &read); } DocPayload::Gta6Drawable(read) }) diff --git a/src/state/rpf/rpf9_scan/rpf9_table/gta6_archive_save/mod.rs b/src/state/rpf/rpf9_scan/rpf9_table/gta6_archive_save/mod.rs index f30b6757e..3188565a2 100644 --- a/src/state/rpf/rpf9_scan/rpf9_table/gta6_archive_save/mod.rs +++ b/src/state/rpf/rpf9_scan/rpf9_table/gta6_archive_save/mod.rs @@ -207,7 +207,7 @@ impl AppState { archive, offset, name, - body: archive_body(doc)?, + body: archive_body(doc, &self.gta6)?, }) } @@ -346,7 +346,10 @@ impl AppState { /// What the loose save writes of `doc`'s edits, made on the save's worker; refused where it /// writes none. -fn archive_body(doc: &Document) -> Result { +fn archive_body( + doc: &Document, + gta6: &crate::state::gta6::session::Gta6Session, +) -> Result { if let DocPayload::Meta(meta) = &doc.payload { if meta.is_edited() && !meta.is_headerless() { // A metadata body's text is parsed and written on the worker, never on the UI thread; @@ -359,13 +362,16 @@ fn archive_body(doc: &Document) -> Result { })); } } - let item = archive_item(doc)?; + let item = archive_item(doc, gta6)?; Ok(Box::new(move || item.read(BodyForm::Decoded))) } /// The item the loose save writes of `doc`'s edits other than a metadata body's, refused where it /// writes none. -fn archive_item(doc: &Document) -> Result { +fn archive_item( + doc: &Document, + gta6: &crate::state::gta6::session::Gta6Session, +) -> Result { let name = String::new(); match &doc.payload { // An edited text body is written in the encoding and line endings it was read with. @@ -379,7 +385,7 @@ fn archive_item(doc: &Document) -> Result { } let edited = crate::state::capabilities::for_payload(&doc.payload) .and_then(|row| row.edited_sections) - .and_then(|edited| edited(doc)); + .and_then(|edited| edited(doc, gta6)); match edited { Some(Ok(EditedSave::Sections(sections))) => Ok(ExtractItem::sections(name, sections)), Some(Ok(EditedSave::Body { diff --git a/src/state/rpf/rpf_archive_open/tree_open/bind/mod.rs b/src/state/rpf/rpf_archive_open/tree_open/bind/mod.rs index 1fcc8aaad..a71330a70 100644 --- a/src/state/rpf/rpf_archive_open/tree_open/bind/mod.rs +++ b/src/state/rpf/rpf_archive_open/tree_open/bind/mod.rs @@ -37,7 +37,10 @@ fn ended() -> MutexGuard<'static, Vec> { /// What `doc`'s edits store in its row: a headerless resource's loose form, as the tree holds such a /// row, any other row's body, made on the worker; refused where the view writes none. -fn row_body(doc: &Document) -> Result { +fn row_body( + doc: &Document, + gta6: &crate::state::gta6::session::Gta6Session, +) -> Result { if let DocPayload::Meta(meta) = &doc.payload { if meta.is_edited() && !meta.is_headerless() { // A metadata body's text is parsed and written on the worker, never on the UI thread; @@ -50,11 +53,14 @@ fn row_body(doc: &Document) -> Result { })); } } - let item = row_item(doc)?; + let item = row_item(doc, gta6)?; Ok(Box::new(move || item.read(BodyForm::Decoded))) } -fn row_item(doc: &Document) -> Result { +fn row_item( + doc: &Document, + gta6: &crate::state::gta6::session::Gta6Session, +) -> Result { let name = String::new(); match &doc.payload { // An edited text body is stored in the encoding and line endings it was read with. @@ -68,7 +74,7 @@ fn row_item(doc: &Document) -> Result { } let edited = crate::state::capabilities::for_payload(&doc.payload) .and_then(|row| row.edited_sections) - .and_then(|edited| edited(doc)); + .and_then(|edited| edited(doc, gta6)); match edited { Some(Ok(EditedSave::Sections(sections))) => Ok(ExtractItem::sections(name, sections)), Some(Ok(EditedSave::Body { @@ -99,7 +105,7 @@ impl AppState { super::super::tree_verbs::refused_tree(&rpf.session)?; let doc = self.document(doc_id)?; let at = doc.history.at(); - match row_body(doc) { + match row_body(doc, &self.gta6) { Ok(body) => { self.say_the_checksum_is_kept(doc_id); std::thread::spawn(move || { diff --git a/src/state/rpf/rpf_archive_open/tree_open/mod.rs b/src/state/rpf/rpf_archive_open/tree_open/mod.rs index 4caf64144..f81c21719 100644 --- a/src/state/rpf/rpf_archive_open/tree_open/mod.rs +++ b/src/state/rpf/rpf_archive_open/tree_open/mod.rs @@ -393,7 +393,8 @@ mod tests { 1 => { leave(&path, &place, start, rpf9_table::keys, None); assert!(read(&path, &disk, offset).is_none()); - if read_body(&path, &disk, offset).is_err() { + let gta6 = crate::state::gta6::session::Gta6Session::default(); + if read_body(>a6, &path, &disk, offset).is_err() { continue; } let stated = nested.map_or(0, |n| n.stored_size()); @@ -416,7 +417,8 @@ mod tests { } // The read works, so the open does. leave(&path, &place, start, rpf9_table::keys, None); - if let Err(e) = read_body(&path, &disk, offset) { + let gta6 = crate::state::gta6::session::Gta6Session::default(); + if let Err(e) = read_body(>a6, &path, &disk, offset) { panic!("{}: row {} opens: {e}", disk.display(), entry.index); } left[shape] = false; diff --git a/src/state/rpf/rpf_archive_open/tree_verbs/headerless_tests/saves_per_kind/mod.rs b/src/state/rpf/rpf_archive_open/tree_verbs/headerless_tests/saves_per_kind/mod.rs index d7b022eb8..c663059d2 100644 --- a/src/state/rpf/rpf_archive_open/tree_verbs/headerless_tests/saves_per_kind/mod.rs +++ b/src/state/rpf/rpf_archive_open/tree_verbs/headerless_tests/saves_per_kind/mod.rs @@ -257,7 +257,11 @@ fn label_done(label: &str, settled: &HashSet) -> bool { } /// The kind the document `doc`, opened from a row labelled `label`, is; `None` for any other. -fn kind_of(doc: &Document, label: &str) -> Option { +fn kind_of( + doc: &Document, + label: &str, + gta6: &crate::state::gta6::session::Gta6Session, +) -> Option { let path = doc.path.as_deref()?; Some(match &doc.payload { DocPayload::Gta6Text(_) => "text table", @@ -285,12 +289,12 @@ fn kind_of(doc: &Document, label: &str) -> Option { "texture dictionary" } DocPayload::Resource(or_io::Asset::NavMesh(_)) - if crate::state::gta6_navmesh::scanned_cell(path).is_some() => + if crate::state::gta6_navmesh::scanned_cell(>a6.physics, path).is_some() => { "navigation mesh" } DocPayload::Resource(or_io::Asset::Particles(_)) - if crate::state::gta6_particles::scanned_lines(path).is_some() => + if crate::state::gta6_particles::scanned_lines(>a6.particles, path).is_some() => { "particles" } @@ -629,7 +633,7 @@ fn attempt( .map(|r| r.entry_id) == Some(c.node) })?; - let (doc, kind) = (doc.id, kind_of(doc, &c.label)?); + let (doc, kind) = (doc.id, kind_of(doc, &c.label, &state.gta6)?); let (line, edit) = line_for(kind, settled)?; let failed = |why: String| Some((line, Ended::Failed(why))); state.toasts.clear(); diff --git a/src/state/source_textures.rs b/src/state/source_textures.rs index a2b5af9b6..abc1e33b9 100644 --- a/src/state/source_textures.rs +++ b/src/state/source_textures.rs @@ -6,6 +6,7 @@ use super::textures::{texture_named, Texture}; /// The texture `name` a preview mesh source's own document embeds: in its `entry` of a drawable dictionary, else in any of them. pub fn texture_embedded_in<'p>( + gta6: &super::gta6::session::Gta6Session, payload: &'p DocPayload, entry: Option, name: &str, @@ -14,9 +15,11 @@ pub fn texture_embedded_in<'p>( DocPayload::Resource(or_io::Asset::DrawableDict(dict)) => &dict.codes, DocPayload::Resource(or_io::Asset::DrawableDictGen9(dict)) => &dict.codes, // A drawable or a fragment names no selection. - _ => return texture_named(payload, None, name), + _ => return texture_named(gta6, payload, None, name), }; (codes.iter().enumerate()) .filter(|(index, _)| entry.is_none_or(|chosen| chosen == *index)) - .find_map(|(_, code)| texture_named(payload, Some(SelectionKey::dict_entry(*code)), name)) + .find_map(|(_, code)| { + texture_named(gta6, payload, Some(SelectionKey::dict_entry(*code)), name) + }) } diff --git a/src/state/tests/opening_a_gta_vi_body.rs b/src/state/tests/opening_a_gta_vi_body.rs index 302bc1468..9597e9288 100644 --- a/src/state/tests/opening_a_gta_vi_body.rs +++ b/src/state/tests/opening_a_gta_vi_body.rs @@ -102,9 +102,10 @@ fn the_cells_across_a_gta_vi_cell_s_borders_are_found_in_its_scan_as_a_job_and_o .document(opened) .and_then(|d| d.path.clone()) .expect("a path"); + let physics = state.gta6.physics.clone(); let joins = || { - let m = crate::state::gta6_navmesh::scanned_cell(&path).expect("the cell"); - let near = crate::state::gta6_navmesh::neighbours(&path, &m); + let m = crate::state::gta6_navmesh::scanned_cell(&physics, &path).expect("the cell"); + let near = crate::state::gta6_navmesh::neighbours(&physics, &path, &m); crate::state::gta6_navmesh::join_lines(&m, &near).join("\n") }; let east_unjoined = format!("Cell {}, across the east border, has no body", here + 1); diff --git a/src/state/texture_edit.rs b/src/state/texture_edit.rs index ca059861f..8d2bfce58 100644 --- a/src/state/texture_edit.rs +++ b/src/state/texture_edit.rs @@ -341,8 +341,9 @@ impl AppState { self.after_texture_edit(doc, step); return Ok(edit); } + let ttpf = self.gta6.ttpf.clone(); let scanned = (self.document_mut(doc)) - .and_then(|d| super::gta6_dictionary_write::reencode(d, name, format, options)); + .and_then(|d| super::gta6_dictionary_write::reencode(&ttpf, d, name, format, options)); if let Some(outcome) = scanned { let (before, edit) = outcome?; self.after_texture_edit(doc, replaced(source, name, before)); @@ -388,8 +389,10 @@ impl AppState { self.after_texture_edit(doc, step); return Ok(edit); } - let scanned = (self.document_mut(doc)) - .and_then(|d| super::gta6_dictionary_write::import(d, name, image, format, options)); + let ttpf = self.gta6.ttpf.clone(); + let scanned = (self.document_mut(doc)).and_then(|d| { + super::gta6_dictionary_write::import(&ttpf, d, name, image, format, options) + }); if let Some(outcome) = scanned { let (before, edit) = outcome?; self.after_texture_edit(doc, replaced(source, name, before)); diff --git a/src/state/texture_resolution.rs b/src/state/texture_resolution.rs index 816516014..0bc27154f 100644 --- a/src/state/texture_resolution.rs +++ b/src/state/texture_resolution.rs @@ -218,8 +218,8 @@ fn embedded<'a>( ) -> Option<(&'a Document, textures::Texture<'a>)> { let doc = subject(state, from)?; let texture = match from { - Some(source) => texture_embedded_in(&doc.payload, source.entry, name)?, - None => textures::texture_named(&doc.payload, selection, name)?, + Some(source) => texture_embedded_in(&state.gta6, &doc.payload, source.entry, name)?, + None => textures::texture_named(&state.gta6, &doc.payload, selection, name)?, }; Some((doc, texture)) } @@ -420,7 +420,7 @@ fn rank_candidates(state: &AppState, from: Option, name: &str) -> Ve .documents .iter() .enumerate() - .filter(|(_, doc)| holds(active, doc, name)) + .filter(|(_, doc)| holds(&state.gta6.ttpf, active, doc, name)) .filter_map(|(index, doc)| { let pin_index = pins.iter().position(|id| *id == doc.id); let attach_index = state @@ -470,10 +470,16 @@ fn rank_candidates(state: &AppState, from: Option, name: &str) -> Ve out } -fn holds(asker: Option<&Document>, doc: &Document, name: &str) -> bool { +fn holds( + ttpf: &super::ttpf_document::TtpfSession, + asker: Option<&Document>, + doc: &Document, + name: &str, +) -> bool { // ⚠ A scanned GTA VI dictionary reads as a Legacy one, and serves only a GTA VI asker. let gta6 = super::ttpf_document::is_gta_vi; - if gta6(Some(doc)) && (!gta6(asker) || super::ttpf_document::refused(doc, name).is_some()) { + if gta6(Some(doc)) && (!gta6(asker) || super::ttpf_document::refused(ttpf, doc, name).is_some()) + { return false; } match &doc.payload { diff --git a/src/state/textures.rs b/src/state/textures.rs index c60b54b08..5a3d47c4c 100644 --- a/src/state/textures.rs +++ b/src/state/textures.rs @@ -165,6 +165,8 @@ pub fn textures_in(payload: &DocPayload, selection: Option) -> Tex } } +pub(crate) use super::gta6_textures::textures_in_with; + pub fn texture_for_selection(payload: &DocPayload, selection: SelectionKey) -> TextureResolution { match capabilities::for_payload(payload).and_then(|row| row.texture_for_selection) { Some(resolve) => resolve(payload, selection), @@ -181,11 +183,12 @@ pub fn texture_at<'p>( } pub fn texture_named<'p>( + gta6: &super::gta6::session::Gta6Session, payload: &'p DocPayload, selection: Option, name: &str, ) -> Option> { - (capabilities::for_payload(payload)?.texture_named?)(payload, selection, name) + (capabilities::for_payload(payload)?.texture_named?)(gta6, payload, selection, name) } pub use super::gta6_textures::{open_pack_entry, resolved_for_gta6, sized_for_gta6}; @@ -888,13 +891,12 @@ pub(crate) mod rows { .find(|t| T::texture_name(t) == name); found.filter(|t| T::decodes(t)).map(|t| T::wrap(t)) } - if source - != (TextureSource::Entry { - hash: FRAGMENT_ENTRY_HASH, - }) - { + let TextureSource::Entry { + hash: FRAGMENT_ENTRY_HASH, + } = source + else { return None; - } + }; match payload { DocPayload::Resource(or_io::Asset::Fragment(frag)) => in_fragment(frag, name), DocPayload::Resource(or_io::Asset::FragmentGen9(frag)) => in_fragment(frag, name), @@ -924,11 +926,8 @@ pub(crate) mod rows { let (DocPayload::Ttpf(ttpf), TextureSource::Document) = (payload, source) else { return None; }; - let index = ttpf.index_of(name)?; - let texture = ttpf.texture(index).ok()?; - Some(Texture::Owned(Cow::Owned(gen8::GrcTexture::clone( - &texture, - )))) + let texture = ttpf.texture(ttpf.index_of(name)?).ok()?; + Some(Texture::Owned(Cow::Owned((*texture).clone()))) } } @@ -944,6 +943,7 @@ pub(crate) mod rows { } pub(crate) fn ydr<'p>( + _gta6: &crate::state::gta6::session::Gta6Session, payload: &'p DocPayload, _selection: Option, name: &str, @@ -956,6 +956,7 @@ pub(crate) mod rows { } pub(crate) fn ydd<'p>( + _gta6: &crate::state::gta6::session::Gta6Session, payload: &'p DocPayload, selection: Option, name: &str, @@ -973,6 +974,7 @@ pub(crate) mod rows { } pub(crate) fn yft<'p>( + _gta6: &crate::state::gta6::session::Gta6Session, payload: &'p DocPayload, _selection: Option, name: &str, @@ -989,6 +991,7 @@ pub(crate) mod rows { } pub(crate) fn ypt<'p>( + _gta6: &crate::state::gta6::session::Gta6Session, payload: &'p DocPayload, selection: Option, name: &str, diff --git a/src/state/ttpf_document/calibration.rs b/src/state/ttpf_document/calibration.rs index 4d3ef5de8..41569f583 100644 --- a/src/state/ttpf_document/calibration.rs +++ b/src/state/ttpf_document/calibration.rs @@ -39,11 +39,18 @@ struct Calibration { ended: Arc>>, } -// ponytail: one calibration at a time for the whole app, as one game's packs are fitted together. -static RUN: Mutex> = Mutex::new(None); +use super::TtpfSession; -fn run() -> MutexGuard<'static, Option> { - RUN.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) +#[derive(Clone, Default)] +pub(crate) struct CalibrationState { + run: Arc>>, +} + +fn run(ttpf: &TtpfSession) -> MutexGuard<'_, Option> { + ttpf.calibration + .run + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) } fn ended(calibration: &Calibration) -> Option { @@ -98,8 +105,8 @@ pub(crate) fn decline(pack: &TexturePack) { } /// Whether a calibration is running. -pub(crate) fn running() -> bool { - job().is_some() +pub(crate) fn running(ttpf: &TtpfSession) -> bool { + job(ttpf).is_some() } fn work(folder: &Path, cancel: &Cancel, progress: &Progress) -> Ended { @@ -145,8 +152,8 @@ fn work(folder: &Path, cancel: &Cancel, progress: &Progress) -> Ended { } /// The calibration running, as the job list draws it. -pub(in crate::state) fn job() -> Option { - let held = run(); +pub(in crate::state) fn job(ttpf: &TtpfSession) -> Option { + let held = run(ttpf); let calibration = held.as_ref().filter(|running| ended(running).is_none())?; Some(RunningJob { kind: JobKind::TextureCalibration, @@ -161,8 +168,8 @@ pub(in crate::state) fn job() -> Option { } /// Ask the calibration to stop; it says it stopped once its worker sees the stop. -pub(in crate::state) fn stop() { - if let Some(calibration) = run().as_ref() { +pub(in crate::state) fn stop(ttpf: &TtpfSession) { + if let Some(calibration) = run(ttpf).as_ref() { calibration.cancel.set(); } } @@ -170,7 +177,7 @@ pub(in crate::state) fn stop() { impl AppState { /// Fit the BCPack coder's tables from every texture pack under `folder`, on a worker. pub fn calibrate_texture_decoding(&mut self, folder: &Path) { - let mut held = run(); + let mut held = run(&self.gta6.ttpf); if (held.as_ref()).is_some_and(|running| ended(running).is_none()) { drop(held); self.show_info_toast(tr!( @@ -204,7 +211,7 @@ impl AppState { /// what it kept. pub(in crate::state) fn poll_texture_calibration(&mut self) { let how = { - let mut held = run(); + let mut held = run(&self.gta6.ttpf); let Some(how) = held.as_ref().and_then(ended) else { return; }; @@ -217,7 +224,7 @@ impl AppState { bodies, unknown, } => { - crate::state::ttpf_document::forget_decodes(); + crate::state::ttpf_document::forget_decodes(&self.gta6.ttpf); for doc in &mut self.documents { crate::state::ttpf_document::recalibrate(&mut doc.payload); } @@ -256,7 +263,7 @@ mod tests { /// Waits out the calibration, then polls the jobs once, which says how it ended. fn worked(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(120); - while job().is_some() { + while job(&state.gta6.ttpf).is_some() { assert!(Instant::now() < deadline, "the calibration never ended"); std::thread::sleep(Duration::from_millis(5)); } @@ -272,8 +279,6 @@ mod tests { cancel.set(); assert_eq!(work(dir.path(), &cancel, &progress), Ended::NoPack); - // ⚠ The calibration is one for the whole app, so a test that polls another state's jobs - // at the same time may be the one that logs its end. let mut state = AppState::new(); state.calibrate_texture_decoding(dir.path()); state.cancel_job(JobKind::TextureCalibration); @@ -283,6 +288,6 @@ mod tests { if let Some(logged) = logged { assert_eq!(logged.outcome, Outcome::Failed, "{}", logged.said); } - assert!(job().is_none()); + assert!(job(&state.gta6.ttpf).is_none()); } } diff --git a/src/state/ttpf_document/mod.rs b/src/state/ttpf_document/mod.rs index cb1d9660d..af5a87aa7 100644 --- a/src/state/ttpf_document/mod.rs +++ b/src/state/ttpf_document/mod.rs @@ -23,22 +23,32 @@ use super::edit_history::Change; use super::texture_edit::TextureEdit; use super::textures::{self, Texture, TextureSource}; -/// Names whose 64-bit hash may key a pack's texture: each texture dictionary's the app has read, -/// each one the user typed that a pack's key matched, and each the naming rules gave for a key. -// ponytail: one list for the whole app, which no view empties. -static NAMES: Mutex> = Mutex::new(BTreeMap::new()); +type RefusedTextures = BTreeMap>; -fn names() -> std::sync::MutexGuard<'static, BTreeMap> { - NAMES +#[derive(Clone, Default)] +pub(crate) struct TtpfSession { + names: Arc>>, + decodes: Arc>>, + refused: Arc>, + shown: Arc>>, + pub(crate) calibration: calibration::CalibrationState, +} + +fn names(ttpf: &TtpfSession) -> std::sync::MutexGuard<'_, BTreeMap> { + ttpf.names .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// The name the app has learned for a texture key, else the one the kept vocabulary holds for it. // ⚠ What a harvest learns lasts a session, and the vocabulary it keeps is what names a key after it. -pub(crate) fn known_name(key: u64) -> Option { - let learned = names().get(&key).cloned(); - named_by(learned, &super::gta6_names::vocabulary(), key) +pub(crate) fn known_name( + ttpf: &TtpfSession, + install: &crate::state::gta6::install::InstallSession, + key: u64, +) -> Option { + let learned = names(ttpf).get(&key).cloned(); + named_by(learned, &super::gta6_names::vocabulary(install), key) } pub(super) fn named_by( @@ -50,24 +60,19 @@ pub(super) fn named_by( } /// How many texture names the app has learned. -pub(crate) fn names_known() -> usize { - names().len() +pub(crate) fn names_known(ttpf: &TtpfSession) -> usize { + names(ttpf).len() } -/// How each texture read was rebuilt from its bodies through the BCPack coder, by its pack's -/// file and its index: a worker's copy of a document reads for the one that is shown. -// ponytail: one map for the whole app, which a calibration that ends empties. -static DECODES: Mutex> = Mutex::new(BTreeMap::new()); - -fn decodes() -> std::sync::MutexGuard<'static, BTreeMap<(PathBuf, usize), Decode>> { - DECODES +fn decodes(ttpf: &TtpfSession) -> std::sync::MutexGuard<'_, BTreeMap<(PathBuf, usize), Decode>> { + ttpf.decodes .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// Forget how every texture was rebuilt, as a calibration that ended changes it. -pub(super) fn forget_decodes() { - decodes().clear(); +pub(super) fn forget_decodes(ttpf: &TtpfSession) { + decodes(ttpf).clear(); } /// Where the BCPack coder's tables fitted on this machine are kept. @@ -93,6 +98,8 @@ pub struct TtpfDocument { /// The texture each key on disk keys. keys: HashMap, read: Mutex, + ttpf: TtpfSession, + install: crate::state::gta6::install::InstallSession, } /// What reading has found, so a frame that asks again reads nothing from disk. @@ -107,7 +114,16 @@ struct Read { impl TtpfDocument { /// Reads the pack's header, table and directory, and no body. + #[cfg(test)] pub fn open(path: &std::path::Path) -> Result { + Self::open_with(path, Default::default(), Default::default()) + } + + pub(crate) fn open_with( + path: &std::path::Path, + ttpf: TtpfSession, + install: crate::state::gta6::install::InstallSession, + ) -> Result { let mut pack = TexturePack::open(path).map_err(|e| e.to_string())?; // A body that does not decode exactly is drawn through a calibration that read the pack. calibrate(&mut pack); @@ -119,6 +135,8 @@ impl TtpfDocument { pack, keys, read: Mutex::default(), + ttpf, + install, }) } @@ -127,17 +145,18 @@ impl TtpfDocument { let Some(entry) = (self.pack.entries.get(index)).filter(|e| e.on_disk && e.key != 0) else { return format!("#{index}"); }; - known_name(entry.key).unwrap_or_else(|| format!("hash_{:016X}", entry.key)) + known_name(&self.ttpf, &self.install, entry.key) + .unwrap_or_else(|| format!("hash_{:016X}", entry.key)) } /// What texture `index` is used by, where no name is known for it and a model of an archive /// harvested names its key: what its tile and its row say beside the hash. pub fn use_label(&self, index: usize) -> Option { let entry = (self.pack.entries.get(index)).filter(|e| e.on_disk && e.key != 0)?; - if known_name(entry.key).is_some() { + if known_name(&self.ttpf, &self.install, entry.key).is_some() { return None; } - super::gta6_names::texture_use_label(entry.key) + super::gta6_names::texture_use_label(&self.install, entry.key) } /// The texture [`Self::name`] names, or whose key a name of the user's hashes to. @@ -156,7 +175,7 @@ impl TtpfDocument { pub fn learn(&self, name: &str) -> Option { let key = name_hash64(name.as_bytes()); let index = self.keys.get(&key).copied()?; - names().insert(key, name.to_string()); + names(&self.ttpf).insert(key, name.to_string()); Some(index) } @@ -194,7 +213,7 @@ impl TtpfDocument { return Err(why.clone()); } let noted = self.pack.texture_noted(index).map(|(texture, how)| { - decodes().insert((self.pack.path().to_path_buf(), index), how); + decodes(&self.ttpf).insert((self.pack.path().to_path_buf(), index), how); self.keep_against(&how); texture }); @@ -221,7 +240,7 @@ impl TtpfDocument { let path = self.pack.path().to_path_buf(); let of_the_pack = (path.clone(), 0)..=(path, usize::MAX); let mut all = Decode::default(); - for (_, how) in decodes().range(of_the_pack) { + for (_, how) in decodes(&self.ttpf).range(of_the_pack) { all.add(*how); } all @@ -248,7 +267,7 @@ impl TtpfDocument { /// How texture `index` was rebuilt and what its read may be called, once it has been read. fn reading(&self, index: usize) -> Option<(Decode, Reading)> { - let read = decodes() + let read = decodes(&self.ttpf) .get(&(self.pack.path().to_path_buf(), index)) .copied(); read.map(|how| (how, how.reading(self.standing()))) @@ -446,6 +465,8 @@ impl Clone for TtpfDocument { pack: self.pack.clone(), keys: self.keys.clone(), read: Mutex::default(), + ttpf: self.ttpf.clone(), + install: self.install.clone(), } } } @@ -637,14 +658,17 @@ pub(super) fn texture_naming_work( } /// Keep the name the texture naming rules give a key of `keys` from a drawable's `name`; how many it named. -pub(super) fn learn_rule_names(name: &str, keys: &HashSet) -> usize { +pub(super) fn learn_rule_names(ttpf: &TtpfSession, name: &str, keys: &HashSet) -> usize { let found = name_keys([name], keys); - learn_named(found.into_iter().map(|(key, (name, _))| (key, name))) + learn_named(ttpf, found.into_iter().map(|(key, (name, _))| (key, name))) } /// Keep each name of `found` for its key where no name is known for it; how many it named. -pub(super) fn learn_named(found: impl IntoIterator) -> usize { - let mut known = names(); +pub(super) fn learn_named( + ttpf: &TtpfSession, + found: impl IntoIterator, +) -> usize { + let mut known = names(ttpf); let mut named = 0; for (key, name) in found { if let std::collections::btree_map::Entry::Vacant(at) = known.entry(key) { @@ -656,8 +680,8 @@ pub(super) fn learn_named(found: impl IntoIterator) -> usi } /// Keep the name of each texture of `dict`, which a pack's or a drawable's 64-bit key may hash. -pub(super) fn learn_names(dict: &Dictionary) { - let mut known = names(); +pub(super) fn learn_names(ttpf: &TtpfSession, dict: &Dictionary) { + let mut known = names(ttpf); for (_, entry) in &dict.entries { if let Ok(Entry::Texture(t)) = entry { known.insert(name_hash64(t.name.as_bytes()), t.name.clone()); @@ -665,19 +689,17 @@ pub(super) fn learn_names(dict: &Dictionary) { } } -/// Why each texture of a scanned dictionary does not read, by the dictionary's path. -// ponytail: one list for the whole app, which no close empties. -static REFUSED: Mutex>> = Mutex::new(BTreeMap::new()); - -fn refused_lists() -> std::sync::MutexGuard<'static, BTreeMap>> { - REFUSED +fn refused_lists( + ttpf: &TtpfSession, +) -> std::sync::MutexGuard<'_, BTreeMap>> { + ttpf.refused .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// Why the texture `name` of the scanned dictionary `doc` is does not read; `None` for one that reads, or another document. -pub(crate) fn refused(doc: &Document, name: &str) -> Option { - let lists = refused_lists(); +pub(crate) fn refused(ttpf: &TtpfSession, doc: &Document, name: &str) -> Option { + let lists = refused_lists(ttpf); let list = lists.get(doc.path.as_deref()?)?; (list.iter()) .find(|(refused, _)| refused.eq_ignore_ascii_case(name)) @@ -691,9 +713,13 @@ pub(super) const VOLUME_IMAGE: u8 = 3; /// texture that reads, and each that does not as its name with no pixels, its reason kept for /// [`refused`]. `None` where an entry is no texture or none reads, which opens as the facts its /// reader reads. -pub(super) fn scanned_textures(path: &Path, dict: Dictionary) -> Option { - learn_names(&dict); - refused_lists().remove(path); +pub(super) fn scanned_textures( + ttpf: &TtpfSession, + path: &Path, + dict: Dictionary, +) -> Option { + learn_names(ttpf, &dict); + refused_lists(ttpf).remove(path); let mut dictionary = PgDictionary::::default(); let mut refused = Vec::new(); for (code, entry) in dict.entries { @@ -747,7 +773,7 @@ pub(super) fn scanned_textures(path: &Path, dict: Dictionary) -> Option u32 { } } -/// The slice of each scanned dictionary's texture the preview shows, by the dictionary's path and the texture's name. -// ponytail: one map for the whole app, which no close empties; an entry is a path and a name. -static SHOWN: Mutex> = Mutex::new(BTreeMap::new()); - -fn shown() -> std::sync::MutexGuard<'static, BTreeMap<(PathBuf, String), u32>> { - SHOWN +fn shown(ttpf: &TtpfSession) -> std::sync::MutexGuard<'_, BTreeMap<(PathBuf, String), u32>> { + ttpf.shown .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// Have slice `slice` of the texture `name` of the scanned dictionary `doc` be the one a replacement takes. -pub(crate) fn show_scanned_slice(doc: &Document, name: &str, slice: u32) { +pub(crate) fn show_scanned_slice(ttpf: &TtpfSession, doc: &Document, name: &str, slice: u32) { if let Some(path) = doc.path.clone() { - shown().insert((path, name.to_ascii_lowercase()), slice); + shown(ttpf).insert((path, name.to_ascii_lowercase()), slice); } } /// The slice of that texture the preview shows: 0 until it shows another. -pub(crate) fn shown_scanned_slice(doc: &Document, name: &str) -> u32 { +pub(crate) fn shown_scanned_slice(ttpf: &TtpfSession, doc: &Document, name: &str) -> u32 { let Some(path) = doc.path.clone() else { return 0; }; let key = (path, name.to_ascii_lowercase()); - shown().get(&key).copied().unwrap_or(0) + shown(ttpf).get(&key).copied().unwrap_or(0) } /// Slice `slice` of `slices` of such a texture, as a texture of one slice. diff --git a/src/state/world_session/gta6.rs b/src/state/world_session/gta6.rs index 6344a5241..2743765fb 100644 --- a/src/state/world_session/gta6.rs +++ b/src/state/world_session/gta6.rs @@ -55,11 +55,15 @@ pub struct Gta6Session { bases: HashMap, /// The laid maps of the world the documents were last laid over: a world started in its place, after its thread died or its index was built again, holds none of them. laid_on: Option, + install: crate::state::gta6::install::InstallSession, } impl Gta6Session { - pub fn new(key: WorldKey) -> Self { - Self::over(key, viewer) + pub(crate) fn new(key: WorldKey, install: crate::state::gta6::install::InstallSession) -> Self { + Self { + install, + ..Self::over(key, viewer) + } } /// The session of `key` as a shell over the viewer `viewer` gives. @@ -79,6 +83,7 @@ impl Gta6Session { laid: Vec::new(), bases: HashMap::new(), laid_on: None, + install: Default::default(), } } @@ -242,7 +247,7 @@ impl WorldSession for Gta6Session { }; self.open = true; let (asked, answer) = (self.asked, Arc::clone(&self.answer)); - let names = crate::state::gta6_names::vocabulary(); + let names = crate::state::gta6_names::vocabulary(&self.install); std::thread::spawn(move || { let named = |word: u64| names.name64(word).map(str::to_string); let met = || standing.pick(&ray, &named); diff --git a/src/state/world_session/mod.rs b/src/state/world_session/mod.rs index 66e423234..5510eedee 100644 --- a/src/state/world_session/mod.rs +++ b/src/state/world_session/mod.rs @@ -413,7 +413,7 @@ impl AppState { self.world.drop_session(); if let Some(key) = wanted { let session: Box = match key.game.is_gta_vi() { - true => Box::new(gta6::Gta6Session::new(key)), + true => Box::new(gta6::Gta6Session::new(key, self.gta6.install.clone())), false => Box::new(driven::DrivenSession::of_install(key, &self.prefs)), }; self.world.hold(session); diff --git a/src/ui/commands/tools_and_help.rs b/src/ui/commands/tools_and_help.rs index 78ea84d51..34a4600fd 100644 --- a/src/ui/commands/tools_and_help.rs +++ b/src/ui/commands/tools_and_help.rs @@ -49,8 +49,8 @@ pub(super) const HARVEST_GTA6_NAMES: Spec = Spec { in the background. They are kept, and hashes, texture keys and scanned drawables are \ shown by name from then on." ), - enabled: |_| { - let harvesting = crate::state::gta6_names::harvesting(); + enabled: |state| { + let harvesting = crate::state::gta6_names::harvesting(&state.gta6.install); none_if(harvesting, tr!("A harvest is under way")) }, run: |state, _| state.harvest_names_of_the_open_gta6_folder(), diff --git a/src/ui/panels/gallery.rs b/src/ui/panels/gallery.rs index 0e0b00d50..0b0cc568c 100644 --- a/src/ui/panels/gallery.rs +++ b/src/ui/panels/gallery.rs @@ -104,7 +104,7 @@ pub fn draw(ui: &mut egui::Ui, state: &mut AppState, mut bridge: Option<&mut Ren return; }; let selection = state.selection.selected(doc_id); - let textures = textures::textures_in(&doc.payload, selection); + let textures = textures::textures_in_with(&state.gta6, &doc.payload, selection); let textures = textures::sized_for_gta6(state, doc_id, textures); let models = models::models_in(&doc.payload); // A GTA VI drawable's textures lie in other documents, where a tile's menu acts. diff --git a/src/ui/panels/gxt2_table.rs b/src/ui/panels/gxt2_table.rs index 641f4df99..fca6f470f 100644 --- a/src/ui/panels/gxt2_table.rs +++ b/src/ui/panels/gxt2_table.rs @@ -173,7 +173,10 @@ pub fn draw(ui: &mut egui::Ui, state: &mut AppState) { }, Some(DocPayload::Gta6Text(t)) => match t.row(entry_idx) { Some((hash, form, text)) => { - let line = crate::state::gta6_dialogue::line_of(hash); + let line = crate::state::gta6_dialogue::line_of( + &state.gta6.audio, + hash, + ); let name = match state.install.name_index.name_of(hash) { Some(name) => name.to_string(), None if hash == typed => query.trim().to_string(), diff --git a/src/ui/panels/hierarchy/drawable.rs b/src/ui/panels/hierarchy/drawable.rs index b16d7033e..70a5c8f90 100644 --- a/src/ui/panels/hierarchy/drawable.rs +++ b/src/ui/panels/hierarchy/drawable.rs @@ -357,7 +357,7 @@ pub(super) fn section_shaders( for (i, effect_hash) in effects.iter().enumerate() { let sel = SelectionKey::Shader(i as u32); let selected = state.selection.is_selected(doc_id, sel); - let resolved = crate::ui::panels::effect_name(*effect_hash); + let resolved = crate::ui::panels::effect_name(&state.gta6.bodies, *effect_hash); let display_name = if resolved.is_empty() { format!("Shader {}", i) } else { @@ -840,7 +840,7 @@ pub(super) fn ypt_model_section_shaders( for (i, effect_hash) in shaders.iter().enumerate() { let sel = SelectionKey::dict_part(model_hash, DictPart::Shader(i as u32)); let selected = state.selection.is_selected(doc_id, sel); - let resolved = crate::ui::panels::effect_name(*effect_hash); + let resolved = crate::ui::panels::effect_name(&state.gta6.bodies, *effect_hash); let display_name = if resolved.is_empty() { format!("Shader {}", i) } else { diff --git a/src/ui/panels/hierarchy/files/folder_view.rs b/src/ui/panels/hierarchy/files/folder_view.rs index b87cfc9ca..2aca2017e 100644 --- a/src/ui/panels/hierarchy/files/folder_view.rs +++ b/src/ui/panels/hierarchy/files/folder_view.rs @@ -235,7 +235,7 @@ fn row_of(state: &AppState, doc: DocumentId, id: RpfNodeId) -> Option { // A drawable/fragment body's stated model name stands in for a hash-only name. let learned = kind .filter(|_| node.name.starts_with("hash_")) - .and_then(|_| learned_name_for(&rpf.session, &node)); + .and_then(|_| learned_name_for(&state.gta6.install, &rpf.session, &node)); let row_name = learned.unwrap_or_else(|| node.name.clone()); let letter = platform_letter_for(state, &rpf.session, &node); let icon_node = icon_name(&row_name, kind).map_or_else( diff --git a/src/ui/panels/hierarchy/gta6/drawable.rs b/src/ui/panels/hierarchy/gta6/drawable.rs index 1b45c4dc9..13546eefb 100644 --- a/src/ui/panels/hierarchy/gta6/drawable.rs +++ b/src/ui/panels/hierarchy/gta6/drawable.rs @@ -61,6 +61,7 @@ fn bone_names(ui: &egui::Ui, doc: &Document) -> Option>> { /// while its payload is the same. fn entry_bone_names( ui: &egui::Ui, + anim: &crate::state::gta6::anim::AnimSession, doc: &Document, resource: &Resource, ) -> Arc>> { @@ -75,7 +76,7 @@ fn entry_bone_names( let path = doc.path.as_deref(); let names: BTreeMap> = dictionary_drawables(resource) .filter_map(|(code, _)| { - let skeleton = crate::state::gta6_entry_skeletons::of(path?, code)?; + let skeleton = crate::state::gta6_entry_skeletons::of(anim, path?, code)?; Some((code, skeleton.bones.into_iter().map(|b| b.name).collect())) }) .collect(); @@ -90,7 +91,8 @@ fn texture_rows(state: &AppState, doc_id: DocumentId) -> Vec { let Some(doc) = state.document(doc_id) else { return Vec::new(); }; - let listed = textures::textures_in(&doc.payload, state.selection.selected(doc_id)); + let listed = + textures::textures_in_with(&state.gta6, &doc.payload, state.selection.selected(doc_id)); let TextureListing::Textures { textures, .. } = textures::sized_for_gta6(state, doc_id, listed) else { return Vec::new(); @@ -120,7 +122,7 @@ pub(crate) fn draw_gta6_drawable(ui: &mut egui::Ui, state: &mut AppState, doc_id Resource::DrawableWithBound(r) => &r.drawable, Resource::Dictionary(_) => { // Each entry lists the bones of the skeleton it holds, as a `.ydd`'s entries do. - let names = entry_bone_names(ui, doc, &resource); + let names = entry_bone_names(ui, &state.gta6.anim, doc, &resource); let bones_of = |code: u32| { (names.get(&code)).map(|n| n.iter().map(String::as_str).collect::>()) }; diff --git a/src/ui/panels/hierarchy/gta6/expressions.rs b/src/ui/panels/hierarchy/gta6/expressions.rs index e2c705f43..15a0b8662 100644 --- a/src/ui/panels/hierarchy/gta6/expressions.rs +++ b/src/ui/panels/hierarchy/gta6/expressions.rs @@ -33,7 +33,11 @@ fn row_of(sel: SelectionKey) -> Option<(ExpressionGroup, Option)> { } /// What the row `sel` picks states: a group's count of tracks, or a track's id, word and detail. -fn picked(set: &Expressions, sel: SelectionKey) -> Option { +fn picked( + install: &crate::state::gta6::install::InstallSession, + set: &Expressions, + sel: SelectionKey, +) -> Option { let (group, track) = row_of(sel)?; let tracks = &group.of(set)?.tracks; let label = group_label(group); @@ -48,7 +52,7 @@ fn picked(set: &Expressions, sel: SelectionKey) -> Option { Some(tr!( "{group}: {id} {word} ({at} of {total}), {detail}", group = label, - id = crate::state::gta6_names::said32(id), + id = crate::state::gta6_names::said32(install, id), word = track_label(word), at = k + 1, total = tracks.len(), @@ -57,7 +61,7 @@ fn picked(set: &Expressions, sel: SelectionKey) -> Option { } /// The set's key, and how many tracks it reads and writes. -fn whole(set: &Expressions) -> String { +fn whole(install: &crate::state::gta6::install::InstallSession, set: &Expressions) -> String { let count = |reads: bool| -> usize { (ExpressionGroup::ALL.iter()) .filter(|g| g.reads() == reads) @@ -67,18 +71,26 @@ fn whole(set: &Expressions) -> String { }; tr!( "Expression set {key}, tracks read: {reads}, tracks written: {writes}", - key = crate::state::gta6_names::said32(set.key), + key = crate::state::gta6_names::said32(install, set.key), reads = count(true), writes = count(false) ) } +pub(crate) fn summary_with( + install: &crate::state::gta6::install::InstallSession, + set: &Expressions, + sel: SelectionKey, +) -> String { + picked(install, set, sel).unwrap_or_else(|| whole(install, set)) +} + /// The status line of the row picked, else the set's key and counts. fn summary(payload: &DocPayload, sel: SelectionKey) -> String { let DocPayload::Gta6Expressions(set) = payload else { return String::new(); }; - picked(set, sel).unwrap_or_else(|| whole(set)) + summary_with(&Default::default(), set, sel) } /// Whether the set holds a track, which is a row. @@ -142,7 +154,9 @@ fn draw_facts( return; }; let set = std::sync::Arc::clone(set); - if let Some((sel, said)) = selection.and_then(|sel| Some((sel, picked(&set, sel)?))) { + if let Some((sel, said)) = + selection.and_then(|sel| Some((sel, picked(&state.gta6.install, &set, sel)?))) + { ui.strong(said); if let Some((group, Some(track))) = row_of(sel) { draw_id(ui, state, (doc_id, sel), &set, group, track); @@ -153,7 +167,7 @@ fn draw_facts( } ui.separator(); } - for line in facts(&set).lines() { + for line in facts(&state.gta6.install, &set).lines() { ui.label(line); } } diff --git a/src/ui/panels/hierarchy/gta6/install.rs b/src/ui/panels/hierarchy/gta6/install.rs index 6d652c666..a03985713 100644 --- a/src/ui/panels/hierarchy/gta6/install.rs +++ b/src/ui/panels/hierarchy/gta6/install.rs @@ -38,7 +38,7 @@ fn fallback(ui: &mut egui::Ui, state: &mut AppState, root: &Path, keys: &Gta6Key } Gta6Keys::Held { .. } => return, }; - let found = install::found_under(root); + let found = install::found_under(&state.gta6.install, root); let mut open = None; egui::Panel::top(ui.id().with("gta6_install_bar")) .frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(8, 4))) @@ -51,7 +51,7 @@ fn fallback(ui: &mut egui::Ui, state: &mut AppState, root: &Path, keys: &Gta6Key ), ); names_row(ui, state, root); - open = bar(ui, root, found.as_deref()); + open = bar(ui, &state.gta6.install, root, found.as_deref()); }); if let Some((archive, hit, preview)) = open { state.open_install_hit(&archive, hit, preview); @@ -64,7 +64,7 @@ fn names_row(ui: &mut egui::Ui, state: &mut AppState, root: &Path) { use crate::state::gta6_names; ui.horizontal_wrapped(|ui| { ui.strong(tr!("Names")); - if gta6_names::harvesting() { + if gta6_names::harvesting(&state.gta6.install) { ui.spinner(); if ui.button(tr!("Stop")).clicked() { state.cancel_job(crate::state::jobs::JobKind::TextureNames); @@ -81,7 +81,7 @@ fn names_row(ui: &mut egui::Ui, state: &mut AppState, root: &Path) { if button.clicked() { state.harvest_gta6_names(root); } - let held = gta6_names::vocabulary().len(); + let held = gta6_names::vocabulary(&state.gta6.install).len(); let said = match held { 0 => tr!("No name is held yet").to_string(), _ => tr_n!("{count} name held", "{count} names held", held), @@ -106,6 +106,7 @@ fn is_gta_vi(ui: &egui::Ui, root: &Path) -> bool { /// click opens, and whether in the preview tab. fn bar( ui: &mut egui::Ui, + session: &crate::state::gta6::install::InstallSession, root: &Path, found: Option<&Mutex>, ) -> Option<(PathBuf, Hit, bool)> { @@ -114,9 +115,9 @@ fn bar( ui.strong(tr!("Every archive of this folder")); if running { ui.spinner(); - let stop = ui.add_enabled(!install::stopping(), egui::Button::new(tr!("Stop"))); + let stop = ui.add_enabled(!install::stopping(session), egui::Button::new(tr!("Stop"))); if stop.clicked() { - install::stop(); + install::stop(session); } ui.ctx() .request_repaint_after(std::time::Duration::from_millis(200)); @@ -128,7 +129,7 @@ fn bar( }; let button = ui.button(label).on_hover_text(tr!("Scans each GTA VI archive under this folder in turn, as a job of the job list: an archive scanned before is read from its kept scan. Its bodies are then tallied by kind, archive by archive, and the bodies of a kind are listed across them.")); if button.clicked() { - install::start(root); + install::start(session, root); } }); let found = found?; diff --git a/src/ui/panels/hierarchy/gta6/mission/mod.rs b/src/ui/panels/hierarchy/gta6/mission/mod.rs index 3b48a14a2..50ee630ce 100644 --- a/src/ui/panels/hierarchy/gta6/mission/mod.rs +++ b/src/ui/panels/hierarchy/gta6/mission/mod.rs @@ -55,6 +55,7 @@ pub(crate) fn has_tables(payload: &DocPayload) -> bool { /// A body's tables while they are drawn. struct Tables<'a> { + install: &'a crate::state::gta6::install::InstallSession, bytes: &'a [u8], body: &'a Body, tables: &'a [StateTable], @@ -85,7 +86,7 @@ impl Tables<'_> { let name = { // GTA VI's name snapshot names a key before the text does. let _names = or_io::meta::binary::hash_index::title_names(); - crate::state::hash_name_or_text(record.key) + crate::state::hash_name_or_text(self.install, record.key) }; let detail = match record.run { Some((block, offset)) => tr_n!( @@ -117,13 +118,16 @@ impl Tables<'_> { let [x, y, z] = element.position; let [a, b, c] = element.rotation; leaf_row(ui, |ui| { - ui.label(crate::state::gta6_names::said32(element.archetype)); + ui.label(crate::state::gta6_names::said32( + self.install, + element.archetype, + )); ui.add(detail_label(tr!( "at {at}: position {position}, rotation {rotation}, link {link}", at = format!("{at:#X}"), position = format!("{x:.3} {y:.3} {z:.3}"), rotation = format!("{a:.3} {b:.3} {c:.3}"), - link = crate::state::gta6_names::said32(element.link) + link = crate::state::gta6_names::said32(self.install, element.link) ))); }); } @@ -135,7 +139,7 @@ impl Tables<'_> { usize::from(record.count), size = element ))); - other::rows(ui, id, self.bytes, self.body, record); + other::rows(ui, id, self.install, self.bytes, self.body, record); } _ => {} }, @@ -175,6 +179,7 @@ pub(crate) fn draw(ui: &mut egui::Ui, state: &mut AppState, doc_id: DocumentId) } }; let drawn = Tables { + install: &state.gta6.install, bytes, body: &body, tables: &tables, diff --git a/src/ui/panels/hierarchy/gta6/mission/other.rs b/src/ui/panels/hierarchy/gta6/mission/other.rs index c4c82f79f..24dface5d 100644 --- a/src/ui/panels/hierarchy/gta6/mission/other.rs +++ b/src/ui/panels/hierarchy/gta6/mission/other.rs @@ -46,8 +46,13 @@ fn key_label(vocabulary: &Vocabulary, wide: bool, key: u64) -> String { /// `record`'s run decoded, from the cache where the form, the record and the vocabulary are the /// ones last decoded with. -fn decoded(bytes: &[u8], body: &Body, record: &StateRecord) -> Decoded { - let vocabulary = gta6_names::vocabulary(); +fn decoded( + install: &crate::state::gta6::install::InstallSession, + bytes: &[u8], + body: &Body, + record: &StateRecord, +) -> Decoded { + let vocabulary = gta6_names::vocabulary(install); let key = ( bytes.as_ptr() as usize, bytes.len(), @@ -81,11 +86,12 @@ fn decoded(bytes: &[u8], body: &Body, record: &StateRecord) -> Decoded { pub(super) fn rows( ui: &mut egui::Ui, id: egui::Id, + install: &crate::state::gta6::install::InstallSession, bytes: &[u8], body: &Body, record: &StateRecord, ) { - let decoded = decoded(bytes, body, record); + let decoded = decoded(install, bytes, body, record); let rows = match decoded.as_ref() { Ok(rows) => rows, Err(e) => { @@ -110,7 +116,7 @@ pub(super) fn rows( }, |ui| { for (n, (name, value)) in element.value.fields.iter().enumerate() { - value_row(ui, id.with(n), name, value); + value_row(ui, id.with(n), install, name, value); } }, ); @@ -118,7 +124,13 @@ pub(super) fn rows( } /// A member's row: a leaf with its value, or a row that opens into what the value holds. -fn value_row(ui: &mut egui::Ui, id: egui::Id, name: &str, value: &Value) { +fn value_row( + ui: &mut egui::Ui, + id: egui::Id, + install: &crate::state::gta6::install::InstallSession, + name: &str, + value: &Value, +) { let below: Vec<(String, &Value)> = match value { Value::Struct(inner) | Value::Pointer(Some(inner)) => { (inner.fields.iter()).map(|(n, v)| (n.clone(), v)).collect() @@ -126,12 +138,14 @@ fn value_row(ui: &mut egui::Ui, id: egui::Id, name: &str, value: &Value) { Value::Array(items) => (items.iter().enumerate()) .map(|(i, v)| (format!("[{i}]"), v)) .collect(), - Value::Map(pairs) => (pairs.iter()).map(|(key, v)| (text(key), v)).collect(), + Value::Map(pairs) => (pairs.iter()) + .map(|(key, v)| (text(install, key), v)) + .collect(), _ => Vec::new(), }; let header = |ui: &mut egui::Ui| { ui.label(name); - ui.add(detail_label(text(value))); + ui.add(detail_label(text(install, value))); }; if below.is_empty() { leaf_row(ui, header); @@ -144,7 +158,7 @@ fn value_row(ui: &mut egui::Ui, id: egui::Id, name: &str, value: &Value) { |ui, _| header(ui), |ui| { for (k, (name, value)) in below.iter().enumerate() { - value_row(ui, id.with(k), name, value); + value_row(ui, id.with(k), install, name, value); } }, ); @@ -159,7 +173,7 @@ fn floats(lanes: &[f32]) -> String { } /// A value as one line: a structure by its type, an array or a map by its count. -fn text(value: &Value) -> String { +fn text(install: &crate::state::gta6::install::InstallSession, value: &Value) -> String { match value { Value::Null | Value::Pointer(None) => "null".into(), Value::Bool(b) => b.to_string(), @@ -167,7 +181,7 @@ fn text(value: &Value) -> String { Value::UInt(n) => n.to_string(), Value::Float(f) => format!("{f:.3}"), Value::String(s) | Value::Raw(s) => s.clone(), - Value::Hash(h) if h.raw.is_empty() => gta6_names::said32(h.hash), + Value::Hash(h) if h.raw.is_empty() => gta6_names::said32(install, h.hash), Value::Hash(h) => h.raw.clone(), Value::Vec2(v) => floats(v), Value::Vec3(v) => floats(v), diff --git a/src/ui/panels/hierarchy/gta6/save.rs b/src/ui/panels/hierarchy/gta6/save.rs index a1f9e01fd..3cfbdcab1 100644 --- a/src/ui/panels/hierarchy/gta6/save.rs +++ b/src/ui/panels/hierarchy/gta6/save.rs @@ -257,7 +257,7 @@ fn draw_rows(ui: &mut egui::Ui, state: &mut AppState, doc_id: DocumentId) { "Keeps the rows whose key, or the known name it hashes, holds this text" )); }); - let vocabulary = crate::state::gta6_names::vocabulary(); + let vocabulary = crate::state::gta6_names::vocabulary(&state.gta6.install); let mut tree = Tree { doc: &doc, vocabulary: &vocabulary, diff --git a/src/ui/panels/hierarchy/gta6/script.rs b/src/ui/panels/hierarchy/gta6/script.rs index 8f94e40f2..2011e39d4 100644 --- a/src/ui/panels/hierarchy/gta6/script.rs +++ b/src/ui/panels/hierarchy/gta6/script.rs @@ -449,7 +449,7 @@ fn draw_labels( } let dim = |text: String| egui::RichText::new(text).color(theme::TEXT_SECONDARY); let idle = state.gta6_script_job(doc_id).is_none(); - let mut on = labels_on(); + let mut on = labels_on(&state.gta6.script); let choice = egui::Checkbox::new( &mut on, tr!("Label natives from the labels files (guesses)"), @@ -475,7 +475,7 @@ fn draw_labels( }; ui.label(dim(line)); if toggled { - set_labels(on); + set_labels(&state.gta6.script, on); state.redo_gta6_script(doc_id, doc.ask(), None); } } diff --git a/src/ui/panels/hierarchy/rpf_tree.rs b/src/ui/panels/hierarchy/rpf_tree.rs index 57cdb5c8a..e155b8f99 100644 --- a/src/ui/panels/hierarchy/rpf_tree.rs +++ b/src/ui/panels/hierarchy/rpf_tree.rs @@ -158,7 +158,11 @@ fn canonical_game_for_container(family: or_title::ContainerFamily) -> or_title:: /// The stem a GTA VI drawable or fragment body stated for `node` on open, where `(archive, offset)` /// gave [`crate::state::gta6_learned_names::lookup`] one; `None` for a row of any other archive /// or a row whose body never opened. -pub(super) fn learned_name_for(session: &RpfEditSession, node: &RpfSessionNode) -> Option { +pub(super) fn learned_name_for( + install: &crate::state::gta6::install::InstallSession, + session: &RpfEditSession, + node: &RpfSessionNode, +) -> Option { let (archive_id, entry_index) = match &node.backing { RpfNodeBacking::ArchiveFile { archive_id, @@ -169,7 +173,7 @@ pub(super) fn learned_name_for(session: &RpfEditSession, node: &RpfSessionNode) }; let archive = &session.archive(archive_id)?.archive; let place = archive.rpf9_place(entry_index)?; - crate::state::gta6_learned_names::lookup(&place.file, place.offset) + crate::state::gta6_learned_names::lookup(install, &place.file, place.offset) } /// The dimmed words after a file row's name: its kind where its archive's table names one, then its size. @@ -443,7 +447,7 @@ pub(super) fn draw_row( // where its row's name was never resolved; `None` for any other row. let learned = kind .filter(|_| node.name.starts_with("hash_")) - .and_then(|_| learned_name_for(&rpf.session, &node)); + .and_then(|_| learned_name_for(&state.gta6.install, &rpf.session, &node)); // The platform letter rows of this archive read under, so a Windows-form name // the vocabulary ships (`n01.ybn`) renders as `.zbn` on an Xbox Series archive. let letter = platform_letter_for(state, &rpf.session, &node); diff --git a/src/ui/panels/hierarchy/ttpf.rs b/src/ui/panels/hierarchy/ttpf.rs index c93928746..18188057e 100644 --- a/src/ui/panels/hierarchy/ttpf.rs +++ b/src/ui/panels/hierarchy/ttpf.rs @@ -39,7 +39,7 @@ pub(super) fn draw_ttpf(ui: &mut egui::Ui, state: &mut AppState, doc_id: Documen .on_hover_text(tr!( "Show only the textures used by a model whose name holds this text. A harvest of the game's names finds, for each texture, the first model whose material binds it" )); - let shown = rows_used_by(ui, doc_id, &ttpf, &model); + let shown = rows_used_by(ui, &state.gta6.install, doc_id, &ttpf, &model); ui.data_mut(|d| d.insert_temp(id, model)); let load = ui.button(tr!("Load names…")).on_hover_text(tr!( "Name the textures of the open packs from a text file: each line a texture's name, or a drawable's name the naming rules expand" @@ -61,7 +61,7 @@ pub(super) fn draw_ttpf(ui: &mut egui::Ui, state: &mut AppState, doc_id: Documen let offered = ui .data_mut(|d| *d.get_temp_mut_or_insert_with(id, || calibration::offered(&ttpf.pack))) && !ttpf.pack.is_calibrated() - && !calibration::running(); + && !calibration::running(&state.gta6.ttpf); if offered { ui.label(tr!( "Some textures of this game are stored through the console's coder and do not read yet. A calibration fits what they need from the game's own packs, once: about a quarter of an hour, which can be stopped and taken up again. They then read as estimates, marked calibrated" @@ -163,6 +163,7 @@ type UsedByStamp = (String, usize, usize); // Kept until the text, the uses served or the pack changes: a pack lists a hundred thousand keys. fn rows_used_by( ui: &egui::Ui, + install: &crate::state::gta6::install::InstallSession, doc_id: DocumentId, ttpf: &crate::state::ttpf_document::TtpfDocument, typed: &str, @@ -172,7 +173,7 @@ fn rows_used_by( if needle.is_empty() { return None; } - let uses = crate::state::gta6_names::texture_uses(); + let uses = crate::state::gta6_names::texture_uses(install); let entries = &ttpf.pack.entries; let stamp: UsedByStamp = (needle, Arc::as_ptr(&uses) as usize, entries.len()); let id = egui::Id::new(("ttpf_used_by_rows", doc_id)); diff --git a/src/ui/panels/hierarchy/ynv.rs b/src/ui/panels/hierarchy/ynv.rs index 14bd5047f..da1fec461 100644 --- a/src/ui/panels/hierarchy/ynv.rs +++ b/src/ui/panels/hierarchy/ynv.rs @@ -36,7 +36,7 @@ pub(super) fn draw_ynv(ui: &mut egui::Ui, state: &mut AppState, doc_id: Document .map(|p| p.iter().collect()) .unwrap_or_default(); let cell = (state.document(doc_id).and_then(|d| d.path.as_deref())) - .and_then(crate::state::gta6_navmesh::scanned_cell); + .and_then(|p| crate::state::gta6_navmesh::scanned_cell(&state.gta6.physics, p)); // A pick in the viewport opens the section its row is in if revealing(state, doc_id) .and_then(SelectionKey::nav_polygon) diff --git a/src/ui/panels/inspector/awc.rs b/src/ui/panels/inspector/awc.rs index 84f8b82ba..e7db5b62b 100644 --- a/src/ui/panels/inspector/awc.rs +++ b/src/ui/panels/inspector/awc.rs @@ -48,7 +48,7 @@ pub(super) fn draw_awc(ui: &mut egui::Ui, state: &mut AppState, doc_id: Document .collect(); // A stream a radio or a dialogue view asked to hear plays once its container has opened. let asked = (state.document(doc_id).and_then(|d| d.path.as_deref())) - .and_then(|path| crate::state::gta6_dialogue::play_asked(path, &rows)); + .and_then(|path| crate::state::gta6_dialogue::play_asked(&state.gta6.audio, path, &rows)); let mut action = asked.map(Action::Play); egui::ScrollArea::both() .id_salt(("awc_streams", doc_id)) diff --git a/src/ui/panels/inspector/gta6/anim/face.rs b/src/ui/panels/inspector/gta6/anim/face.rs index b22d96ba2..a5a0b0dd5 100644 --- a/src/ui/panels/inspector/gta6/anim/face.rs +++ b/src/ui/panels/inspector/gta6/anim/face.rs @@ -58,7 +58,7 @@ fn draw( let sets: Vec<(DocumentId, String, PathBuf)> = (state.documents.iter()) .filter_map(|d| { let path = d.path.clone()?; - is_expression_set(&path).then(|| (d.id, d.file_name(), path)) + is_expression_set(&state.gta6.anim, &path).then(|| (d.id, d.file_name(), path)) }) .collect(); if sets.is_empty() { @@ -69,7 +69,7 @@ fn draw( for (doc, name, path) in sets { let now = face.set.as_ref().is_some_and(|(d, _, _)| *d == doc); if ui.selectable_label(now, &name).clicked() { - face.set = expression_set(&path).map(|set| (doc, name, set)); + face.set = expression_set(&state.gta6.anim, &path).map(|set| (doc, name, set)); face.read.clear(); } } diff --git a/src/ui/panels/inspector/gta6/anim/mod.rs b/src/ui/panels/inspector/gta6/anim/mod.rs index 30ecf36dd..3b5e5b2fb 100644 --- a/src/ui/panels/inspector/gta6/anim/mod.rs +++ b/src/ui/panels/inspector/gta6/anim/mod.rs @@ -140,7 +140,9 @@ pub(crate) fn draw_gta6_anim(ui: &mut egui::Ui, state: &mut AppState, doc_id: Do for (m, motion) in resource.motions.iter().enumerate() { let shown = egui::CollapsingHeader::new(&motion.name) .id_salt(("gta6_anim_motion", doc_id, m)) - .show(ui, |ui| draw_motion(ui, (doc_id, m), motion, &clip_named)); + .show(ui, |ui| { + draw_motion(ui, &state.gta6.anim, (doc_id, m), motion, &clip_named) + }); let (opened, toggled) = shown.body_returned.unwrap_or_default(); open = open.or(opened); looped = looped.or(toggled.map(|l| (m, l))); @@ -426,6 +428,7 @@ fn describe(record: &Record) -> String { /// loop the Looped box was set to. fn draw_motion( ui: &mut egui::Ui, + anim: &crate::state::gta6::anim::AnimSession, id: (DocumentId, usize), motion: &Motion, clip_named: &dyn Fn(u64) -> Option, @@ -452,7 +455,7 @@ fn draw_motion( let key = format!("{:#010X}:{:#010X}", clip >> 32, clip & 0xFFFF_FFFF); if let Some(named) = clip_named(clip) { ui.monospace(format!("{key} {named}")); - } else if let Some(at) = found_clip(clip) { + } else if let Some(at) = found_clip(anim, clip) { ui.horizontal(|ui| { ui.monospace(format!("{key} {} ({})", at.clip, at.dictionary)); if ui.small_button(tr!("Open")).clicked() { diff --git a/src/ui/panels/inspector/gta6/anim/play.rs b/src/ui/panels/inspector/gta6/anim/play.rs index 5f714ce38..63a15be96 100644 --- a/src/ui/panels/inspector/gta6/anim/play.rs +++ b/src/ui/panels/inspector/gta6/anim/play.rs @@ -109,7 +109,13 @@ fn unjoined_lines(state: &AppState, model: &mut Model) -> Vec { state.preview_scene.lod, ); if model.unjoined.as_ref().is_none_or(|(k, _)| *k != key) { - let found = crate::render::gta6_drawable::unjoined(doc, selection, key.3, skeleton); + let found = crate::render::gta6_drawable::unjoined( + &state.gta6.anim, + doc, + selection, + key.3, + skeleton, + ); let lines = found .iter() .map(|(m, g, why)| { diff --git a/src/ui/panels/inspector/gta6/dialogue.rs b/src/ui/panels/inspector/gta6/dialogue.rs index dd3fc4d6e..0b8c7bfed 100644 --- a/src/ui/panels/inspector/gta6/dialogue.rs +++ b/src/ui/panels/inspector/gta6/dialogue.rs @@ -15,7 +15,7 @@ const LIST_ROWS: f32 = 16.0; /// How the index of the open scans stands, and the button that starts it. fn draw_index(ui: &mut egui::Ui, state: &mut AppState) { - if store::running() { + if store::running(&state.gta6.audio) { // Drawn again until the index ends, so what it kept shows without a click. ui.ctx() .request_repaint_after(std::time::Duration::from_millis(250)); @@ -26,7 +26,7 @@ fn draw_index(ui: &mut egui::Ui, state: &mut AppState) { return; } let (said, language) = { - let lines = lines(); + let lines = lines(&state.gta6.audio); (lines.said.clone(), lines.filter.language.clone()) }; match said { @@ -50,8 +50,8 @@ fn draw_index(ui: &mut egui::Ui, state: &mut AppState) { } /// The language of the texts shown, picked among those registered or found. -fn draw_language(ui: &mut egui::Ui) { - let mut guard = lines(); +fn draw_language(ui: &mut egui::Ui, audio: &crate::state::gta6::audio::AudioSession) { + let mut guard = lines(audio); let lines: &mut Lines = &mut guard; let offered = lines.languages(); if offered.is_empty() { @@ -223,7 +223,7 @@ pub(super) fn draw_radio(ui: &mut egui::Ui, state: &mut AppState, doc_id: Docume if audio.data.kind != AudioDataKind::Music { return; } - let read = store::radio_of(path, &audio.data); + let read = store::radio_of(&state.gta6, path, &audio.data); let radio = match &*read { Ok(radio) if radio.stations.is_empty() => return, Ok(radio) => radio, @@ -243,14 +243,14 @@ pub(super) fn draw_radio(ui: &mut egui::Ui, state: &mut AppState, doc_id: Docume .color(theme::TEXT_SECONDARY), ); draw_index(ui, state); - draw_language(ui); + draw_language(ui, &state.gta6.audio); // A station's band orders the stations a text names. let mut order: Vec<&Station> = radio.stations.iter().collect(); order.sort_by_key(|station| station.band); let mut play = None; { - let lines = lines(); + let lines = lines(&state.gta6.audio); let language = match lines.filter.language.is_empty() { true => lines.first_language(), false => lines.filter.language.clone(), @@ -296,16 +296,16 @@ pub(crate) fn draw_dialogue(ui: &mut egui::Ui, state: &mut AppState) { .color(theme::TEXT_SECONDARY), ); draw_index(ui, state); - draw_language(ui); - if let Some(stream) = draw_lines(ui) { + draw_language(ui, &state.gta6.audio); + if let Some(stream) = draw_lines(ui, &state.gta6.audio) { state.play_gta6_stream(stream); } }); } /// The filter and the lines it keeps; returns the stream of the line whose button was clicked. -fn draw_lines(ui: &mut egui::Ui) -> Option { - let mut guard = lines(); +fn draw_lines(ui: &mut egui::Ui, audio: &crate::state::gta6::audio::AudioSession) -> Option { + let mut guard = lines(audio); let lines: &mut Lines = &mut guard; if lines.count() == 0 { return None; diff --git a/src/ui/panels/inspector/gta6/drawable/bone_edit.rs b/src/ui/panels/inspector/gta6/drawable/bone_edit.rs index 94468bb0c..9fceb0adc 100644 --- a/src/ui/panels/inspector/gta6/drawable/bone_edit.rs +++ b/src/ui/panels/inspector/gta6/drawable/bone_edit.rs @@ -39,7 +39,7 @@ pub(super) fn draw( let shown = match ui.data(|d| d.get_temp::(id)) { Some((s, shown)) if s == stamp => shown, _ => { - let skeleton = shown_skeleton(doc, selection); + let skeleton = shown_skeleton(&state.gta6.anim, doc, selection); let shown = skeleton.and_then(|s| { let b = s.bones.get(bone)?; let [x, y, z, w] = b.rotation; diff --git a/src/ui/panels/inspector/gta6/drawable/head.rs b/src/ui/panels/inspector/gta6/drawable/head.rs index a7a6906a2..46b387f01 100644 --- a/src/ui/panels/inspector/gta6/drawable/head.rs +++ b/src/ui/panels/inspector/gta6/drawable/head.rs @@ -24,7 +24,7 @@ pub(super) fn draw(ui: &mut egui::Ui, state: &AppState, doc_id: DocumentId) { let lines = match ui.data(|d| d.get_temp::(id)) { Some((s, lines)) if s == stamp => lines, _ => { - let lines = Arc::new(head_lines(&head)); + let lines = Arc::new(head_lines(&state.gta6, &head)); ui.data_mut(|d| d.insert_temp(id, (stamp, lines.clone()))); lines } diff --git a/src/ui/panels/inspector/gta6/drawable/material_edit.rs b/src/ui/panels/inspector/gta6/drawable/material_edit.rs index 08c68cef1..1dd5cd32f 100644 --- a/src/ui/panels/inspector/gta6/drawable/material_edit.rs +++ b/src/ui/panels/inspector/gta6/drawable/material_edit.rs @@ -19,10 +19,14 @@ type Rows = Arc>>; type Row = (String, bool, Option>); /// `rows` of `shaders`, each given the default its effect sets, as a Reset sets it. -fn with_defaults(shaders: &[Shader], rows: Vec>) -> Vec> { +fn with_defaults( + bodies: &crate::state::gta6::bodies::BodiesSession, + shaders: &[Shader], + rows: Vec>, +) -> Vec> { (shaders.iter().zip(rows)) .map(|(s, rows)| { - let effect = effect_def(s.name_hash); + let effect = effect_def(bodies, s.name_hash); (s.parameters.iter().zip(rows)) .map(|(p, (name, floats))| { let default = match (&p.value, &effect) { @@ -66,8 +70,8 @@ pub(super) fn draw( let rows = match cached.filter(|(s, _)| *s == stamp) { Some((_, rows)) => rows, None => { - let named = parameter_rows(&drawable.shaders); - let rows: Rows = Arc::new(with_defaults(&drawable.shaders, named)); + let named = parameter_rows(&state.gta6.bodies, &drawable.shaders); + let rows: Rows = Arc::new(with_defaults(&state.gta6.bodies, &drawable.shaders, named)); ui.data_mut(|d| d.insert_temp(id, (stamp, rows.clone()))); rows } @@ -91,7 +95,9 @@ pub(super) fn draw( ParameterValue::Texture { slot } => { let slot = usize::from(*slot); let held = s.texture_keys.get(slot).copied().flatten(); - if let Some(key) = key_field(ui, (doc_id, i, slot), held) { + if let Some(key) = + key_field(ui, &state.gta6, (doc_id, i, slot), held) + { edits.push((i, MaterialEdit::TextureKey { slot, key })); } } @@ -143,11 +149,16 @@ fn word_field(ui: &mut egui::Ui, word: u32, floats: bool) -> Option { /// A texture slot's key as the name it is known by, empty for a slot that binds none, typed until /// the field lets go; the key typed. -fn key_field(ui: &mut egui::Ui, at: (DocumentId, usize, usize), key: Option) -> Option { +fn key_field( + ui: &mut egui::Ui, + gta6: &crate::state::gta6::session::Gta6Session, + at: (DocumentId, usize, usize), + key: Option, +) -> Option { let id = egui::Id::new(("gta6_texture_key", at)); let mut text = ui .data(|d| d.get_temp::(id)) - .unwrap_or_else(|| key.map(texture_name).unwrap_or_default()); + .unwrap_or_else(|| key.map(|k| texture_name(gta6, k)).unwrap_or_default()); let field = egui::TextEdit::singleline(&mut text) .desired_width(220.0) .hint_text(tr!("unbound")); @@ -159,6 +170,6 @@ fn key_field(ui: &mut egui::Ui, at: (DocumentId, usize, usize), key: Option return None; } ui.data_mut(|d| d.remove::(id)); - crate::state::gta6_key_words::typed(&text); + crate::state::gta6_key_words::typed(>a6.install, &text); texture_key(&text).filter(|typed| Some(*typed) != key) } diff --git a/src/ui/panels/inspector/gta6/drawable/material_layout.rs b/src/ui/panels/inspector/gta6/drawable/material_layout.rs index d156d424f..e39e21d1f 100644 --- a/src/ui/panels/inspector/gta6/drawable/material_layout.rs +++ b/src/ui/panels/inspector/gta6/drawable/material_layout.rs @@ -70,16 +70,20 @@ pub(super) fn draw( ui.add_space(crate::ui::theme::SPACING_TIGHT); ui.horizontal(|ui| { ui.strong(tr!("Shader {index}", index = i)); - let text = typed(ui, ("gta6_effect", doc_id, i), effect_name(s.name_hash)); + let text = typed( + ui, + ("gta6_effect", doc_id, i), + effect_name(&state.gta6.bodies, s.name_hash), + ); if let Some(hash) = text.and_then(|t| hash_of(&t)) { if hash != s.name_hash { - let (edit, why) = effect_change(s, hash); + let (edit, why) = effect_change(&state.gta6.bodies, s, hash); edits.push((i, edit)); failed.extend(why); } } }); - if let Some(effect) = effect_def(s.name_hash) { + if let Some(effect) = effect_def(&state.gta6.bodies, s.name_hash) { let picked = declared_pick(ui, (doc_id, i), s, &effect); match picked { Some(Ok(edit)) => edits.push((i, edit)), @@ -157,8 +161,12 @@ pub(super) fn draw( /// The change of `s`'s effect to `hash`: an effect the app has read gives the shader the /// parameters it declares; any other, or one whose parameters are not placed, changes the effect /// alone, with why its parameters were not taken. -fn effect_change(s: &Shader, hash: u32) -> (LayoutEdit, Option) { - let Some(effect) = effect_def(hash) else { +fn effect_change( + bodies: &crate::state::gta6::bodies::BodiesSession, + s: &Shader, + hash: u32, +) -> (LayoutEdit, Option) { + let Some(effect) = effect_def(bodies, hash) else { return (LayoutEdit::Effect(hash), None); }; match declared_shader(s, &effect) { diff --git a/src/ui/panels/inspector/gta6/drawable/mod.rs b/src/ui/panels/inspector/gta6/drawable/mod.rs index 719ec1c51..8e8bfdc04 100644 --- a/src/ui/panels/inspector/gta6/drawable/mod.rs +++ b/src/ui/panels/inspector/gta6/drawable/mod.rs @@ -32,7 +32,7 @@ pub(crate) fn draw_gta6_cell( let Some(path) = state.document(doc_id).and_then(|d| d.path.clone()) else { return false; }; - let Some(cell) = scanned_cell(&path) else { + let Some(cell) = scanned_cell(&state.gta6.physics, &path) else { return false; }; ui.heading(tr!("GTA VI Navigation Cell")); @@ -48,7 +48,7 @@ pub(crate) fn draw_gta6_cell( } physics_edit::draw_cell(ui, state, doc_id, polygon); // Built again only when a neighbouring cell opens or closes. - let near = neighbours(&path, &cell); + let near = neighbours(&state.gta6.physics, &path, &cell); let key: Vec = (near.iter()) .map(|(_, _, n)| n.as_ref().map_or(0, |n| std::sync::Arc::as_ptr(n) as usize)) .collect(); @@ -66,7 +66,9 @@ pub(crate) fn draw_gta6_cell( ui.add(egui::Label::new(line.as_str()).extend()); } // A deletion also asks for the cells at the corners, which no join line names. - if linked_cells(&path, &cell).iter().any(|(_, n)| n.is_none()) + if linked_cells(&state.gta6.physics, &path, &cell) + .iter() + .any(|(_, n)| n.is_none()) && ui .button(tr!("Find the neighbouring cells in the scan")) .clicked() @@ -208,7 +210,10 @@ pub(crate) fn draw_gta6_drawable( let materials = drawable_of(&resource, selection) .map(|d| material_rows(state, doc_id, d)) .unwrap_or_default(); - let shown = std::sync::Arc::new((body_lines(&resource, selection), materials)); + let shown = std::sync::Arc::new(( + body_lines(&state.gta6.install, &resource, selection), + materials, + )); ui.data_mut(|d| d.insert_temp(id, (stamp.0, stamp.1, stamp.2, shown.clone()))); shown } diff --git a/src/ui/panels/inspector/gta6/drawable/selected.rs b/src/ui/panels/inspector/gta6/drawable/selected.rs index a026081a9..3cfc8754d 100644 --- a/src/ui/panels/inspector/gta6/drawable/selected.rs +++ b/src/ui/panels/inspector/gta6/drawable/selected.rs @@ -22,7 +22,7 @@ pub(super) fn draw( let shown = match ui.data(|d| d.get_temp::(id)) { Some((s, shown)) if s == stamp => shown, _ => { - let shown = selected_rows(doc, sel).map(Arc::new); + let shown = selected_rows(&state.gta6.anim, doc, sel).map(Arc::new); ui.data_mut(|d| d.insert_temp(id, (stamp, shown.clone()))); shown } diff --git a/src/ui/panels/inspector/gta6/move_network.rs b/src/ui/panels/inspector/gta6/move_network.rs index cbf203fc7..5da108874 100644 --- a/src/ui/panels/inspector/gta6/move_network.rs +++ b/src/ui/panels/inspector/gta6/move_network.rs @@ -12,20 +12,30 @@ const DEPTH: usize = 64; /// The nodes of the GTA VI network the document at `path` opened from; `false`, drawing /// nothing, for any other document. -pub(crate) fn draw_scanned(ui: &mut egui::Ui, path: Option<&std::path::Path>) -> bool { - let Some(outline) = path.and_then(nodes::outline) else { +pub(crate) fn draw_scanned( + ui: &mut egui::Ui, + gta6: &crate::state::gta6::session::Gta6Session, + path: Option<&std::path::Path>, +) -> bool { + let Some(outline) = path.and_then(|p| nodes::outline(>a6.bodies, p)) else { return false; }; ui.heading(tr!("GTA VI MoVE network")); ui.separator(); ui.label(tr!("Each node opens to its fields and to the nodes it leads to, from the root. A kind's name is GTA V's at the same place in GTA V's list, which is not confirmed.")); ui.add_space(crate::ui::theme::SPACING_TIGHT); - draw_node(ui, &outline, outline.root, 0); + draw_node(ui, >a6.install, &outline, outline.root, 0); true } -fn draw_node(ui: &mut egui::Ui, outline: &MoveOutline, at: usize, depth: usize) { - let label = nodes::label(outline, at); +fn draw_node( + ui: &mut egui::Ui, + install: &crate::state::gta6::install::InstallSession, + outline: &MoveOutline, + at: usize, + depth: usize, +) { + let label = nodes::label(install, outline, at); if depth >= DEPTH { ui.label(label); return; @@ -34,12 +44,12 @@ fn draw_node(ui: &mut egui::Ui, outline: &MoveOutline, at: usize, depth: usize) .id_salt(("gta6_move_node", at)) .show(ui, |ui| { grid(ui, &format!("gta6_move_fields_{at:X}_{depth}"), |ui| { - for (name, value) in nodes::rows(outline, at) { + for (name, value) in nodes::rows(install, outline, at) { row(ui, &name, &value); } }); for child in nodes::children(outline, at) { - draw_node(ui, outline, child, depth + 1); + draw_node(ui, install, outline, child, depth + 1); } }); } diff --git a/src/ui/panels/inspector/gta6/particles.rs b/src/ui/panels/inspector/gta6/particles.rs index 50894873c..4ff9fae7f 100644 --- a/src/ui/panels/inspector/gta6/particles.rs +++ b/src/ui/panels/inspector/gta6/particles.rs @@ -8,10 +8,12 @@ pub(crate) fn draw_scanned(ui: &mut egui::Ui, state: &mut AppState, doc_id: Docu let Some(path) = state.document(doc_id).and_then(|d| d.path.as_deref()) else { return; }; - let Some(lines) = crate::state::gta6_particles::scanned_lines(path) else { + let Some(lines) = crate::state::gta6_particles::scanned_lines(&state.gta6.particles, path) + else { return; }; - let names_drawables = crate::state::gta6_particle_models::names_drawables(path); + let names_drawables = + crate::state::gta6_particle_models::names_drawables(&state.gta6.particles, path); ui.separator(); egui::CollapsingHeader::new(tr!("What the GTA VI list holds beyond this GTA V form")) .id_salt(("gta6_particles", doc_id)) diff --git a/src/ui/panels/inspector/gta6/text.rs b/src/ui/panels/inspector/gta6/text.rs index a5504aa01..dffc4ed1c 100644 --- a/src/ui/panels/inspector/gta6/text.rs +++ b/src/ui/panels/inspector/gta6/text.rs @@ -218,12 +218,15 @@ fn draw_audio_items(ui: &mut egui::Ui, state: &AppState, doc_id: DocumentId) -> if linkable && draw_links(ui, linked, doc.linking.is_some() && linked.is_none()) { asked = Some(Asked::Link); } - let pool = pool_names(); + let pool = pool_names(&state.gta6.audio); let name = |key: u32| { let pooled = pool.get(&key).map(String::as_str); match pooled.or_else(|| state.install.name_index.name_of(key)) { Some(known) => hash_text(key, Some(known)), - None => hash_text(key, crate::state::hash_text_name(key).as_deref()), + None => hash_text( + key, + crate::state::hash_text_name(&state.gta6.install, key).as_deref(), + ), } }; let row_height = ui.spacing().interact_size.y; diff --git a/src/ui/panels/inspector/gta6/text_entries.rs b/src/ui/panels/inspector/gta6/text_entries.rs index d6e61b8c4..6b6be0634 100644 --- a/src/ui/panels/inspector/gta6/text_entries.rs +++ b/src/ui/panels/inspector/gta6/text_entries.rs @@ -31,7 +31,7 @@ fn show_focused_key(ui: &egui::Ui, state: &AppState, doc_id: DocumentId) { let Some(path) = state.document(doc_id).and_then(|d| d.path.as_deref()) else { return; }; - if let Some(key) = text_search::take_focus(path) { + if let Some(key) = text_search::take_focus(&state.gta6.modding, path) { let filter = egui::Id::new(("gxt2_search", doc_id)); ui.ctx() .data_mut(|d| d.insert_temp(filter, format!("{key:08x}"))); @@ -123,7 +123,7 @@ fn search(ui: &mut egui::Ui, state: &mut AppState, doc_id: DocumentId) { ui.strong(tr!("Search every language of the install")); let query_id = egui::Id::new("gta6_text_search_every_language"); let mut query: String = ui.data_mut(|d| d.get_temp(query_id)).unwrap_or_default(); - let running = text_search::running(); + let running = text_search::running(&state.gta6.modding); let mut start = false; ui.horizontal_wrapped(|ui| { let typed = ui.add( @@ -173,7 +173,7 @@ fn search(ui: &mut egui::Ui, state: &mut AppState, doc_id: DocumentId) { /// The keys the last search found, a line per language, each line's text edited in place. fn results(ui: &mut egui::Ui, state: &AppState, running: bool) -> Option { - let mut found = text_search::found(); + let mut found = text_search::found(&state.gta6.modding); let searched = found.as_mut()?; match &searched.ended { None => { diff --git a/src/ui/panels/inspector/rpf9.rs b/src/ui/panels/inspector/rpf9.rs index 90acf9f9f..3ad0245e2 100644 --- a/src/ui/panels/inspector/rpf9.rs +++ b/src/ui/panels/inspector/rpf9.rs @@ -175,7 +175,7 @@ pub(super) fn draw_scan_rows(ui: &mut egui::Ui, state: &mut AppState, doc_id: Do list.seek(&found.rows); let filtering = list.filtering(found.rows.len()); let (jumped, scroll) = (list.jumped, std::mem::take(&mut list.scroll)); - let names = crate::state::gta6_names::labels(&scan.path); + let names = crate::state::gta6_names::labels(&state.gta6.install, &scan.path); let name_of = |row: &Row| match row { Row::Body(find) => names.get(&find.offset).map(String::as_str), Row::Missing { .. } => None, @@ -516,7 +516,7 @@ pub(super) fn draw_scan_origin(ui: &mut egui::Ui, state: &AppState, doc_id: Docu if let Some(DocPayload::Hex(hex)) = state.document(doc_id).map(|d| &d.payload) { row(ui, tr!("Shown as bytes"), &hex.banner); } - if let Some(note) = crate::state::gta6_dialogue::strict_note(path) { + if let Some(note) = crate::state::gta6_dialogue::strict_note(&state.gta6.audio, path) { row(ui, tr!("Strict tree"), ¬e); } }); diff --git a/src/ui/panels/inspector/text.rs b/src/ui/panels/inspector/text.rs index deafb0a5e..65855c2b1 100644 --- a/src/ui/panels/inspector/text.rs +++ b/src/ui/panels/inspector/text.rs @@ -31,7 +31,7 @@ pub(super) fn draw_text(ui: &mut egui::Ui, state: &AppState, doc_id: crate::stat let DocPayload::Text(text) = &doc.payload else { return; }; - if super::gta6::move_network::draw_scanned(ui, doc.path.as_deref()) { + if super::gta6::move_network::draw_scanned(ui, &state.gta6, doc.path.as_deref()) { return; } if (doc.path.as_deref()).is_some_and(crate::state::rpf9_scan::opened_as_facts) { diff --git a/src/ui/panels/inspector/ttpf.rs b/src/ui/panels/inspector/ttpf.rs index f82f26885..456b3a2ae 100644 --- a/src/ui/panels/inspector/ttpf.rs +++ b/src/ui/panels/inspector/ttpf.rs @@ -75,7 +75,9 @@ pub(super) fn draw_ttpf( row(ui, tr!("Shape"), &shape(&entry)); row(ui, tr!("Key"), &format!("{:016X}", entry.key)); // The model a names harvest found to bind the key, which says what a texture with no name is. - if let Some(used) = crate::state::gta6_names::texture_use_label(entry.key) { + if let Some(used) = + crate::state::gta6_names::texture_use_label(&state.gta6.install, entry.key) + { row(ui, tr!("Use"), &used); } let mips = match entry.mip_count { diff --git a/src/ui/panels/maps/scanned.rs b/src/ui/panels/maps/scanned.rs index 9f7f8b88f..628cf9dfc 100644 --- a/src/ui/panels/maps/scanned.rs +++ b/src/ui/panels/maps/scanned.rs @@ -22,13 +22,13 @@ const ROW: f32 = 20.0; /// A name for people: the one the names harvested from GTA VI's archives hold for its hash, else /// as every map shows it. pub(super) fn shown(state: &AppState, name: &Name) -> String { - let harvested = crate::state::gta6_names::name32(name.hash); + let harvested = crate::state::gta6_names::name32(&state.gta6.install, name.hash); harvested.unwrap_or_else(|| super::shown(state, name)) } /// A map's name hash, with the name the names harvested hold for it. -fn map_hash(hash: u32) -> String { - match crate::state::gta6_names::name32(hash) { +fn map_hash(install: &crate::state::gta6::install::InstallSession, hash: u32) -> String { + match crate::state::gta6_names::name32(install, hash) { Some(name) => format!("{hash:#010X} ({name})"), None => format!("{hash:#010X}"), } @@ -69,8 +69,8 @@ pub fn draw_list(ui: &mut egui::Ui, state: &mut AppState) { let dictionaries = links::unresolved_dictionaries(scanned); let shown_links = std::sync::Arc::clone(&scanned.links); ui.label(egui::RichText::new(file(scanned)).strong()); - row(ui, "name", map_hash(m.name)); - row(ui, "parent", map_hash(m.parent)); + row(ui, "name", map_hash(&state.gta6.install, m.name)); + row(ui, "parent", map_hash(&state.gta6.install, m.parent)); row( ui, "flags", @@ -327,8 +327,8 @@ pub(super) fn draw_on_plan( } /// What a level-of-detail parent names, for people. -fn parent_text(p: &Parent) -> String { - let map = map_hash(p.map); +fn parent_text(install: &crate::state::gta6::install::InstallSession, p: &Parent) -> String { + let map = map_hash(install, p.map); let Some((path, target)) = &p.found else { return tr!( "map {map}, index {index}: open that map body to follow it", @@ -365,13 +365,18 @@ fn parent_text(p: &Parent) -> String { } /// The parent of element `index` (the entities, then the prop lists), where the map's links read. -fn parent_row(ui: &mut egui::Ui, scanned: &ScannedMap, index: usize) { +fn parent_row( + ui: &mut egui::Ui, + install: &crate::state::gta6::install::InstallSession, + scanned: &ScannedMap, + index: usize, +) { let Some(parent) = scanned.links.parents.get(index) else { return; }; let text = match parent { None => tr!("None").to_string(), - Some(p) => parent_text(p), + Some(p) => parent_text(install, p), }; row(ui, tr!("Level-of-detail parent"), text); } @@ -457,7 +462,7 @@ pub fn draw_selection(ui: &mut egui::Ui, state: &mut AppState) { row(ui, "childLodDist", format!("{:.1}", e.child_lod_dist)); row(ui, "numChildren", e.num_children.to_string()); row(ui, "parentIndex", e.parent_index.to_string()); - parent_row(ui, scanned, index); + parent_row(ui, &state.gta6.install, scanned, index); note(ui, tr!("parentIndex indexes the chosen parent map's entities, then its prop lists, then its grass lists")); row(ui, "hash_E74C3C23", e.hash_e74c3c23.to_string()); row(ui, "flags", format!("{:#010X}", e.flags)); @@ -498,7 +503,7 @@ pub fn draw_selection(ui: &mut egui::Ui, state: &mut AppState) { row(ui, "InstanceList", tr_n!("{count} instance", "{count} instances", list.instances)); row(ui, "BatchAABB", format!("{} .. {}", point(list.batch_aabb.min), point(list.batch_aabb.max))); if k < m.prop_lists.len() { - parent_row(ui, scanned, index); + parent_row(ui, &state.gta6.install, scanned, index); } note(ui, tr!("The plan draws its instances as points")); } diff --git a/src/ui/panels/maps/world.rs b/src/ui/panels/maps/world.rs index 49bdb16be..2ae1edcfb 100644 --- a/src/ui/panels/maps/world.rs +++ b/src/ui/panels/maps/world.rs @@ -180,7 +180,7 @@ pub(super) fn tools(ui: &mut egui::Ui, state: &mut AppState, shown: &mut Shown) }); if let Some((area, row, map)) = picked { ui.horizontal_wrapped(|ui| { - ui.monospace(gta6_world::archetype_name(row)); + ui.monospace(gta6_world::archetype_name(&state.gta6.install, row)); ui.weak(tr!( "{level}, in the map at {offset}", level = LOD_LEVELS[usize::from(row.lod_level)], diff --git a/src/ui/panels/meta_editor/ctx.rs b/src/ui/panels/meta_editor/ctx.rs index d226920d3..4455b6aff 100644 --- a/src/ui/panels/meta_editor/ctx.rs +++ b/src/ui/panels/meta_editor/ctx.rs @@ -25,6 +25,7 @@ pub struct EditorCtx { pub text_names: bool, /// The names the document's own string sections give its hash values. pub strings: Arc, + pub(crate) install: crate::state::gta6::install::InstallSession, } impl EditorCtx { @@ -73,6 +74,7 @@ impl EditorCtx { edits: Rc::default(), text_names: false, strings: Default::default(), + install: Default::default(), } } } diff --git a/src/ui/panels/meta_editor/mod.rs b/src/ui/panels/meta_editor/mod.rs index a8da211c7..6baf996b3 100644 --- a/src/ui/panels/meta_editor/mod.rs +++ b/src/ui/panels/meta_editor/mod.rs @@ -129,6 +129,7 @@ fn draw_visual_view(ui: &mut egui::Ui, state: &mut AppState, doc_id: crate::stat edits: Default::default(), text_names, strings, + install: state.gta6.install.clone(), }; let Some(doc) = state.document_mut(doc_id) else { diff --git a/src/ui/panels/meta_editor/text_names.rs b/src/ui/panels/meta_editor/text_names.rs index 94a190863..4a082aa38 100644 --- a/src/ui/panels/meta_editor/text_names.rs +++ b/src/ui/panels/meta_editor/text_names.rs @@ -22,13 +22,13 @@ fn shown_name(ctx: &EditorCtx, value: &Value) -> Option { .flatten(); own.or_else(|| { (ctx.text_names) - .then(|| crate::state::meta_text_name(hash)) + .then(|| crate::state::meta_text_name(&ctx.install, hash)) .flatten() }) } Value::UInt(wide) => (ctx.strings.name64(*wide).map(str::to_owned)).or_else(|| { (ctx.text_names) - .then(|| wide_text_name(&crate::state::gta6_names::vocabulary(), *wide)) + .then(|| wide_text_name(&crate::state::gta6_names::vocabulary(&ctx.install), *wide)) .flatten() }), _ => None, diff --git a/src/ui/panels/mod.rs b/src/ui/panels/mod.rs index 27eb9b3d8..921be71ac 100644 --- a/src/ui/panels/mod.rs +++ b/src/ui/panels/mod.rs @@ -154,10 +154,10 @@ pub fn question_waits(ctx: &egui::Context) -> bool { /// A shader's effect name from its hash, GTA V's or a GTA VI effect the app has read, or the hash /// as `shader_XXXXXXXX` when no name is known. -pub fn effect_name(hash: u32) -> String { +pub(crate) fn effect_name(bodies: &crate::state::gta6::bodies::BodiesSession, hash: u32) -> String { match or_io::gta5::shaders::shader_names::lookup(hash) { Some(name) => name.to_string(), - None => crate::state::gta6_resource::known_effect(hash) + None => crate::state::gta6_resource::known_effect(bodies, hash) .unwrap_or_else(|| format!("shader_{hash:08X}")), } } diff --git a/src/ui/panels/status_bar.rs b/src/ui/panels/status_bar.rs index 51414c7c6..4ed7c45a9 100644 --- a/src/ui/panels/status_bar.rs +++ b/src/ui/panels/status_bar.rs @@ -478,6 +478,9 @@ fn selection_summary(state: &AppState) -> String { let Some(sel) = state.selection.selected(doc.id) else { return String::new(); }; + if let crate::state::DocPayload::Gta6Expressions(set) = &doc.payload { + return super::hierarchy::gta6_expressions::summary_with(&state.gta6.install, set, sel); + } capabilities::for_payload(&doc.payload) .and_then(|row| row.selection_summary) .map(|summary| summary(&doc.payload, sel)) diff --git a/src/ui/panels/texture_preview/mod.rs b/src/ui/panels/texture_preview/mod.rs index 3b6b702e6..e03470072 100644 --- a/src/ui/panels/texture_preview/mod.rs +++ b/src/ui/panels/texture_preview/mod.rs @@ -183,7 +183,7 @@ pub fn draw(ui: &mut egui::Ui, state: &mut AppState) { empty(ui, "No document"); return; }; - let refused = crate::state::ttpf_document::refused(doc, &texture_name); + let refused = crate::state::ttpf_document::refused(&state.gta6.ttpf, doc, &texture_name); let texture = textures::texture_at(&doc.payload, source, &texture_name) .map(textures::Texture::into_owned) .filter(|_| refused.is_none()); @@ -194,7 +194,12 @@ pub fn draw(ui: &mut egui::Ui, state: &mut AppState) { { slices = crate::state::ttpf_document::scanned_slices(doc, &t); slice = slice.min(slices - 1); - crate::state::ttpf_document::show_scanned_slice(doc, &texture_name, slice); + crate::state::ttpf_document::show_scanned_slice( + &state.gta6.ttpf, + doc, + &texture_name, + slice, + ); cube = t.image_type == 1; let t = crate::state::ttpf_document::scanned_slice(t.into_owned(), slice, slices); Some(textures::Texture::Owned(std::borrow::Cow::Owned(t))) diff --git a/src/ui/panels/world_viewer/map.rs b/src/ui/panels/world_viewer/map.rs index 8db760ff2..366032db3 100644 --- a/src/ui/panels/world_viewer/map.rs +++ b/src/ui/panels/world_viewer/map.rs @@ -449,10 +449,14 @@ pub fn draw(ui: &mut egui::Ui, overview: &mut Overview, viewer: &mut Viewer) { } /// Where the camera stands, in words: the map under it where the vocabulary names one, how high over the ground and which way it looks. -pub fn place_words(overview: &mut Overview, viewer: &Viewer) -> String { +pub(crate) fn place_words( + install: &crate::state::gta6::install::InstallSession, + overview: &mut Overview, + viewer: &Viewer, +) -> String { let camera = &viewer.camera; let point = camera.position.truncate(); - let vocabulary = crate::state::gta6_names::vocabulary(); + let vocabulary = crate::state::gta6_names::vocabulary(install); let named_with = Arc::as_ptr(&vocabulary) as usize; // ⚠ The name is a pass over every map at rest: it is looked for again only once the camera moved or the vocabulary changed. let fresh = diff --git a/src/ui/panels/world_viewer/places.rs b/src/ui/panels/world_viewer/places.rs index c9bd9fc19..2e2951ff2 100644 --- a/src/ui/panels/world_viewer/places.rs +++ b/src/ui/panels/world_viewer/places.rs @@ -126,18 +126,21 @@ pub fn places( } /// The places of `index`, by the maps that stream at rest and the names the vocabulary gives them. -pub fn of_index(index: &WorldIndex) -> Vec { +pub(crate) fn of_index( + install: &crate::state::gta6::install::InstallSession, + index: &WorldIndex, +) -> Vec { let at_rest = Enabled::default(); let maps = (index.maps.iter()).filter(|m| at_rest.allows(m)).map(|m| { let (low, high) = m.boxes().entities; Counted { - head: crate::state::gta6_names::name32(m.name).and_then(|name| head_of(&name)), + head: crate::state::gta6_names::name32(install, m.name).and_then(|name| head_of(&name)), middle: (low + high) / 2.0, top: high.z, side: (high.x - low.x).max(high.y - low.y), } }); - let vocabulary = crate::state::gta6_names::vocabulary(); + let vocabulary = crate::state::gta6_names::vocabulary(install); places(maps, MOST, &|at| { super::map::place_at(index, &vocabulary, at) }) diff --git a/src/ui/panels/world_viewer/side.rs b/src/ui/panels/world_viewer/side.rs index fbc918181..bb52cad8d 100644 --- a/src/ui/panels/world_viewer/side.rs +++ b/src/ui/panels/world_viewer/side.rs @@ -65,8 +65,8 @@ impl crate::ui::panel_state::PanelState for GroupFilter { } /// The name the vocabulary gives `hash`, else the hash itself. -fn name_of(hash: u32) -> String { - crate::state::gta6_names::name32(hash).unwrap_or_else(|| format!("{hash:08X}")) +fn name_of(install: &crate::state::gta6::install::InstallSession, hash: u32) -> String { + crate::state::gta6_names::name32(install, hash).unwrap_or_else(|| format!("{hash:08X}")) } /// The name the vocabulary gives `group`, by its word or its hash, else its hash. @@ -82,11 +82,14 @@ fn group_name( } /// Which interior and room the camera stands in, where it stands in one. -fn where_inside(inside: gta6_worldview::Inside) -> String { +fn where_inside( + install: &crate::state::gta6::install::InstallSession, + inside: gta6_worldview::Inside, +) -> String { tr!( "In the interior {interior}, room {room}", - interior = name_of(inside.interior), - room = name_of(inside.room), + interior = name_of(install, inside.interior), + room = name_of(install, inside.room), ) } @@ -333,16 +336,17 @@ fn go_to(ui: &mut egui::Ui, state: &mut AppState, viewer: &mut Viewer) { let Some(index) = viewer.index.clone() else { return; }; + let install = state.gta6.install.clone(); let held = state.panels.get_or_default_mut::(); // ⚠ The vocabulary is read on a worker after the first ask: the places are named again once it is served. - let vocabulary = crate::state::gta6_names::vocabulary(); + let vocabulary = crate::state::gta6_names::vocabulary(&install); let of = ( std::sync::Arc::as_ptr(&index) as usize, std::sync::Arc::as_ptr(&vocabulary) as usize, ); if held.of != of { // A pass over every map at rest, once an index and a vocabulary. - (held.of, held.found) = (of, places::of_index(&index)); + (held.of, held.found) = (of, places::of_index(&install, &index)); } if held.found.is_empty() { return; @@ -377,13 +381,14 @@ fn go_to(ui: &mut egui::Ui, state: &mut AppState, viewer: &mut Viewer) { fn camera(ui: &mut egui::Ui, state: &mut AppState, viewer: &mut Viewer) { ui.strong(tr!("Camera")); go_to(ui, state, viewer); + let install = state.gta6.install.clone(); let overview = state.panels.get_or_default_mut::(); map::draw(ui, overview, viewer); // Inside, the interior and its room say where the camera is; outside, the map under it and the ground. match viewer.inside() { - Some(inside) => said(ui, &where_inside(inside)), + Some(inside) => said(ui, &where_inside(&install, inside)), None if viewer.index.is_some() => { - let words = map::place_words(overview, viewer); + let words = map::place_words(&install, overview, viewer); if let Some(place) = overview.place.clone() { said(ui, &tr!("In {place}", place = place)); } @@ -494,13 +499,14 @@ fn streams(ui: &mut egui::Ui, state: &mut AppState, viewer: &mut Viewer) { viewer.groups_chosen = false; } } + let install = state.gta6.install.clone(); let filter = &mut state.panels.get_or_default_mut::().0; let field = egui::TextEdit::singleline(filter) .hint_text(tr!("Filter groups by name")) .desired_width(f32::INFINITY); named(ui.add(field), tr!("Filter groups by name")); let needle = filter.to_lowercase(); - let vocabulary = crate::state::gta6_names::vocabulary(); + let vocabulary = crate::state::gta6_names::vocabulary(&install); let mut rows: Vec<(&or_world_gta6::index::Group, String)> = (groups.iter()) .map(|group| (group, group_name(&vocabulary, group))) .filter(|(_, name)| needle.is_empty() || name.to_lowercase().contains(&needle))