diff --git a/src/app/editor_window.rs b/src/app/editor_window.rs index fa7306d8..76029429 100644 --- a/src/app/editor_window.rs +++ b/src/app/editor_window.rs @@ -190,11 +190,12 @@ impl App { if self.device_retry.is_some_and(|at| now < at) { return Ok(()); } - let Some(editor) = self.editor.as_ref() else { + let Some(editor) = self.editor.as_mut() else { return Ok(()); }; - if self.device_retry.is_none() { - self.app_state.graphics_device_lost(editor.bridge.mode()); + if self.device_retry.is_none() && self.app_state.graphics_device_lost(editor.bridge.mode()) + { + editor.bridge.gta6_device_lost(); } self.device_retry = Some(now + std::time::Duration::from_secs(2)); let window = editor.surface.window.clone(); @@ -218,6 +219,7 @@ impl App { .warm_thumbnails(); bridge.set_game_pack_path(self.app_state.install.game_pack.root()); bridge.set_mode(or_renderer::ShadingMode::Material); + bridge.carry_gta6_lost_effects(editor.bridge.take_gta6_lost_effects()); editor.bridge = bridge; self.device_retry = None; Ok(()) diff --git a/src/photo/gta6.rs b/src/photo/gta6.rs index 26a90150..89b645b1 100644 --- a/src/photo/gta6.rs +++ b/src/photo/gta6.rs @@ -275,6 +275,7 @@ pub(super) fn photograph( let fitted = (ctx.wheels.as_ref().zip(ctx.wheel_models.as_ref())) .and_then(|(table, models)| Some((table.get(&model.name)?, models))) .filter(|_| ctx.shaded); + let mut bridge = bridge.scoped_gta6_overrides(); // Each model's surfaces in its own colours: the vehicle's, and each wheel model's one tone. let mut painted = std::collections::HashMap::new(); if let Some(ids) = ctx @@ -287,13 +288,15 @@ pub(super) fn photograph( for (wheel, .., tone) in fitted.iter().flat_map(|(wheels, _)| wheels.iter()) { painted.insert(wheel.to_ascii_lowercase(), vec![*tone; 256]); } - crate::render::gta6_paint::paint_with(painted); + bridge.gta6_overrides_mut().set_paint(painted); let finished = (ctx .finishes .as_ref() .and_then(|table| table.get(&model.name))) .map(|ids| (model.name.to_ascii_lowercase(), ids.clone())); - crate::render::gta6_paint::finish_with(finished.into_iter().collect()); + bridge + .gta6_overrides_mut() + .set_finish(finished.into_iter().collect()); let held = match prefetched.remove(&idx) { Some(held) => held, None => super::timing::time("10 gta6: hold_model", || { @@ -312,16 +315,16 @@ pub(super) fn photograph( }; crate::render::gta6_drawable::wheel_parts(doc, wheels, &read) }); - crate::render::gta6_meshlets::show_beside(beside); + bridge.gta6_overrides_mut().set_beside(beside); if ctx.shaded { let captured = capture_shaded( state, - bridge, + &mut bridge, options.size, settle, ctx.look, ctx.shadow, - |state| { + |state, bridge| { // Kick off pack opening and worker texture decoding for upcoming // models so they overlap with this model's GPU render + readback. next_prefetch = next_prefetch.max(idx + 1); @@ -339,7 +342,7 @@ pub(super) fn photograph( if let Ok(next_id) = held_next { state.active_document = Some(next_id); let _ = state.try_open_texture_pack(); - crate::render::gta6_meshlets::start_decoding(state); + bridge.start_decoding_gta6_alone(state); state.active_document = Some(id); } prefetched.insert(upcoming_idx, held_next); @@ -362,7 +365,8 @@ pub(super) fn photograph( Err(err) => tally.record(&model.name, Err(err)), } } else { - let drawn = draw_gta6(state, bridge, ctx, id, options.size, settle, ctx.look); + let drawn = + draw_gta6(state, &mut bridge, ctx, id, options.size, settle, ctx.look); settle = LATER_SETTLE; state.let_go(&[id]); tally.record(&model.name, drawn.and_then(|image| save(&image, &target))); @@ -599,7 +603,6 @@ fn photograph_kits( println!("the build's ped asset lists are read"); let poses = crate::render::gta6_ped_pose::load_human_poses(root); let hair_lib = crate::render::gta6_hair::HairLibrary::load(root); - crate::render::gta6_meshlets::frame_beside(true); let mut settle = FIRST_SETTLE; for (name, kit) in kits { let target = options @@ -704,31 +707,31 @@ fn photograph_kits( skin_preset = format!("0x{skin_preset:08X}"), "selected ped skin tone preset" ); - crate::render::gta6_ped::set_active_skin_preset(skin_preset); - crate::render::gta6_hair::set_active(hair_verts); - crate::render::gta6_ped_pose::set_active(pose); + let mut bridge = bridge.scoped_gta6_overrides(); + { + let overrides = bridge.gta6_overrides_mut(); + overrides.framed_whole = true; + overrides.skin_preset = skin_preset; + overrides.hair = hair_verts; + overrides.ped_pose = pose; + overrides.set_beside(Some(beside)); + } index::dress(Some( (parts.iter()) .map(|(model, textures)| (drawable_word(&model.name), textures.clone())) .collect(), )); - crate::render::gta6_meshlets::show_beside(Some(beside)); let look = Some(kit_look(dressing.kind)); let made = state.hold_gta6_model(parts[0].0, root).and_then(|id| { state.active_document = Some(id); - let drawn = draw_gta6(state, bridge, ctx, id, options.size, settle, look); + let drawn = draw_gta6(state, &mut bridge, ctx, id, options.size, settle, look); settle = LATER_SETTLE; state.let_go(&[id]); drawn.and_then(|image| save(&image, &target)) }); + index::dress(None); tally.record(name, made); } - crate::render::gta6_ped::set_active_skin_preset(0); - crate::render::gta6_hair::set_active(None); - crate::render::gta6_ped_pose::set_active(None); - crate::render::gta6_meshlets::show_beside(None); - crate::render::gta6_meshlets::frame_beside(false); - index::dress(None); Ok(()) } @@ -805,9 +808,12 @@ fn draw_gta6( } let until = Instant::now() + limit; let mut quiet = 0; - while quiet < 2 && state.wants_texture_packs() && Instant::now() < until { + while quiet < 2 + && state.wants_texture_packs(bridge.gta6_overrides().beside()) + && Instant::now() < until + { state.poll_jobs(); - state.try_open_texture_pack(); + state.try_open_texture_pack_with(bridge.gta6_overrides().beside()); if state.texture_packs_indexed() > 0 && !state.texture_packs_opening() { quiet += 1; } else { diff --git a/src/photo/gta6_shaded.rs b/src/photo/gta6_shaded.rs index ff5a9107..cbb00737 100644 --- a/src/photo/gta6_shaded.rs +++ b/src/photo/gta6_shaded.rs @@ -38,7 +38,10 @@ fn settle_shaded( ) { // Frame the active model's camera on CPU right away so `--look` takes effect before any GPU // pass runs. - let _ = state.step_viewport_camera(crate::render::viewport::CameraInputs::default()); + let _ = state.step_viewport_camera_with( + crate::render::viewport::CameraInputs::default(), + bridge.gta6_overrides().framed_beside(), + ); if let (Some(look), false) = (look, *aimed) { let [yaw, pitch, lens] = look.map(|degrees| (degrees as f32).to_radians()); state.look_active_camera(yaw, pitch, lens); @@ -51,10 +54,11 @@ fn settle_shaded( let mut settled = false; while Instant::now() < until { state.poll_jobs(); - let opened = state.try_open_texture_pack(); + let beside = bridge.gta6_overrides().beside(); + let opened = state.try_open_texture_pack_with(beside); let packs = !opened && !state.texture_packs_opening() - && (state.texture_packs_indexed() > 0 || !state.wants_texture_packs()); + && (state.texture_packs_indexed() > 0 || !state.wants_texture_packs(beside)); if !packs { std::thread::sleep(Duration::from_millis(1)); continue; @@ -62,7 +66,7 @@ fn settle_shaded( // Kick off worker decoding of every texture key before preparing `MeshletScene`, so the // scene binds real textures on its first prepare without a redundant rebind. if !decoding_started { - crate::render::gta6_meshlets::start_decoding(state); + bridge.start_decoding_gta6(state); decoding_started = true; } if crate::render::gta6_maps::pending() > 0 { @@ -70,14 +74,14 @@ fn settle_shaded( continue; } let drawn = bridge.prepare_gta6(state, px); - let opened_after = state.try_open_texture_pack(); + let opened_after = state.try_open_texture_pack_with(bridge.gta6_overrides().beside()); if opened_after { decoding_started = false; continue; } let maps = crate::render::gta6_maps::pending() == 0; - let programs_ready = !crate::render::gta6_meshlets::awaits_programs(); - let light_ready = !crate::render::gta6_frame_light::awaits(); + let programs_ready = !bridge.awaits_gta6_programs(); + let light_ready = !bridge.awaits_gta6_light(); if drawn && maps && programs_ready && light_ready { // If any surface fell back to Material, ensure its fallback textures finish decoding // via `material_maps` before capture. @@ -110,8 +114,8 @@ fn settle_shaded( tracing::warn!( packs_opening = state.texture_packs_opening(), maps_pending = crate::render::gta6_maps::pending(), - awaits_programs = crate::render::gta6_meshlets::awaits_programs(), - awaits_light = crate::render::gta6_frame_light::awaits(), + awaits_programs = bridge.awaits_gta6_programs(), + awaits_light = bridge.awaits_gta6_light(), "Shaded photo did not settle before the time limit" ); } @@ -126,7 +130,7 @@ pub(super) fn capture_shaded( limit: Duration, look: Option<[i32; 3]>, shadow: bool, - mut before_gpu_capture: impl FnMut(&mut AppState), + mut before_gpu_capture: impl FnMut(&mut AppState, &mut RenderBridge), ) -> Result<(image::RgbaImage, image::RgbaImage), String> { let px = size * SUPERSAMPLE; // The model alone on a clear frame: no sky is drawn behind it. @@ -134,12 +138,12 @@ pub(super) fn capture_shaded( state.drivers.world_background.sky = false; // A ground is laid only for the shadow the model casts on it, and is no part of the picture. state.drivers.world_background.ground = shadow; - crate::render::viewport::light_as_a_studio(); + let mut bridge = bridge.scoped_gta6_studio(); let mut aimed = false; super::timing::time("11 gta6: settle", || { - settle_shaded(state, bridge, px, limit, look, &mut aimed); + settle_shaded(state, &mut bridge, px, limit, look, &mut aimed); }); - before_gpu_capture(state); + before_gpu_capture(state, &mut bridge); let capture = |state: &mut AppState, bridge: &mut RenderBridge| -> Result<(image::RgbaImage, image::RgbaImage), String> { @@ -147,7 +151,7 @@ pub(super) fn capture_shaded( bridge.capture_gta6_frame(state, px, shadow) }) }; - let (mut large, mut whole) = capture(state, bridge)?; + let (mut large, mut whole) = capture(state, &mut bridge)?; let (empty, brightness) = super::timing::time("13 gta6: brightness", || { let b = mean_brightness(&large); let e = large.as_raw().as_chunks::<4>().0.iter().all(|p| p[3] == 0); @@ -162,8 +166,8 @@ pub(super) fn capture_shaded( "Shaded picture mean brightness is near zero; retrying once" ); bridge.recheck_gta6_lighting(); - settle_shaded(state, bridge, px, LATER_SETTLE, look, &mut aimed); - (large, whole) = capture(state, bridge)?; + settle_shaded(state, &mut bridge, px, LATER_SETTLE, look, &mut aimed); + (large, whole) = capture(state, &mut bridge)?; let retry = mean_brightness(&large); if retry < NEAR_BLACK { tracing::warn!( @@ -199,6 +203,6 @@ pub(super) fn draw_shaded( look: Option<[i32; 3]>, shadow: bool, ) -> Result { - let (large, whole) = capture_shaded(state, bridge, size, limit, look, shadow, |_| {})?; + let (large, whole) = capture_shaded(state, bridge, size, limit, look, shadow, |_, _| {})?; Ok(finalize_shaded(large, whole, size, shadow)) } diff --git a/src/photo/mod.rs b/src/photo/mod.rs index f739968f..92747b56 100644 --- a/src/photo/mod.rs +++ b/src/photo/mod.rs @@ -9,7 +9,7 @@ use std::time::{Duration, Instant}; use std::sync::Arc; use crate::render::dressed::{Diffuse, DressedScene, Geometry, ScenePart}; -use crate::render::thumbnails::{camera_for, geometry_for, TILE_YAW}; +use crate::render::thumbnails::{camera_for, geometry_for_with, TILE_YAW}; use crate::render::RenderBridge; use crate::state::front_door::{NewProject, Template}; use crate::state::models::{models_in, ModelListing}; @@ -419,7 +419,12 @@ fn draw( return Err("holds no model".into()); }; let first = listed.first().ok_or("holds no model")?; - let mut uploads = geometry_for(state, doc, first.selection_id); + let mut uploads = geometry_for_with( + state, + doc, + first.selection_id, + bridge.gta6_overrides().beside(), + ); let turn = if let Some(ctx) = gta6_ctx { gta6::dress(state, doc, ctx, &mut uploads); ctx.turn_radians() diff --git a/src/render/gta6_drawable/mod.rs b/src/render/gta6_drawable/mod.rs index 8d329d12..0253595e 100644 --- a/src/render/gta6_drawable/mod.rs +++ b/src/render/gta6_drawable/mod.rs @@ -59,8 +59,7 @@ pub(crate) fn meshes(req: &GeometryRequest<'_>) -> Vec { .collect(), None => { let mut own = meshes_at(drawable, lod, posing, channel, &srgb); - let beside = super::gta6_meshlets::beside(); - let beside = beside.iter().flat_map(|parts| parts.iter()); + let beside = req.beside.into_iter().flatten(); own.extend(beside.flat_map(|part| part_meshes(part, lod, channel, &srgb))); own } @@ -955,8 +954,7 @@ pub(crate) fn bounds(req: &GeometryRequest<'_>) -> Option<(Vec3, f32)> { }; let (mut min, mut max) = (Vec3::from(min), Vec3::from(max)); // The parts a run draws beside the document's drawable as one figure are framed with it. - let beside = super::gta6_meshlets::framed_beside(); - for part in beside.iter().flat_map(|parts| parts.iter()) { + for part in req.beside.into_iter().flatten() { let Some(d) = drawable_of(&part.resource, None) else { continue; }; diff --git a/src/render/gta6_fallback_tests.rs b/src/render/gta6_fallback_tests.rs index a13e3299..87996547 100644 --- a/src/render/gta6_fallback_tests.rs +++ b/src/render/gta6_fallback_tests.rs @@ -75,18 +75,19 @@ fn opened() -> AppState { #[test] fn a_geometry_the_pack_draws_nothing_of_is_left_out_before_its_material_is_made() { let state = opened(); + let session = crate::render::gta6_meshlets::MeshletSession::default(); let made = std::cell::Cell::new(0); let refused = |_: &str| { made.set(made.get() + 1); Err("draws nothing".to_string()) }; - let left = shaded_surfaces(&state, &refused).expect("a drawable is open"); + 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); assert_eq!(left.left_out, [(effect, "draws nothing".to_string())]); assert_eq!(made.get(), 1, "asked once a shader"); - let drawn = shaded_surfaces(&state, &|_| Ok(())).expect("a drawable is open"); + let drawn = shaded_surfaces(&state, &session, &|_| Ok(())).expect("a drawable is open"); assert!(drawn.left_out.is_empty()); let [(_, material)] = drawn.surfaces.as_slice() else { panic!("one surface"); @@ -94,9 +95,7 @@ fn a_geometry_the_pack_draws_nothing_of_is_left_out_before_its_material_is_made( assert_eq!(material.vectors.len(), 1, "its constant"); // No pack the app has read holds the map: nothing decodes it, and nothing waits for it. assert!(material.textures.is_empty() && drawn.decoding.is_empty()); - assert!(crate::render::gta6_meshlets::all_in(&[ - 0x5EED_0000_0000_0001 - ])); + assert!(session.all_in(&[0x5EED_0000_0000_0001])); } #[test] diff --git a/src/render/gta6_frame_light.rs b/src/render/gta6_frame_light.rs index 4481c168..f99294e4 100644 --- a/src/render/gta6_frame_light.rs +++ b/src/render/gta6_frame_light.rs @@ -6,7 +6,6 @@ use std::collections::BTreeMap; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use or_cli::{Gta6Feed as Filled, Gta6Lights, Gta6Stage as Stage, Gta6Table}; @@ -80,9 +79,10 @@ const METER: [&str; 2] = [ "ComputeAverageLuminanceFromHistogramCS", ]; -/// Where the passes stand, across frames. +/// Where the GTA VI deferred lighting and tone-mapping passes stand across frames, owned by +/// [`super::RenderBridge`]. #[derive(Default)] -struct Glue { +pub(crate) struct FrameLightState { programs: Option>, tables: Option>, tone: Option>, @@ -97,6 +97,8 @@ struct Glue { hardware: Option, /// Where the last frame's scene stood, which the Shaded line says. stood: Option, + /// Whether the last frame left nothing to wait for: no scene, or one the passes light. + settled: bool, } /// Where a scene stands with the lighting passes. @@ -107,10 +109,6 @@ enum Stood { Refused, } -static GLUE: Mutex> = Mutex::new(None); -/// Whether the last frame left nothing to wait for: no scene, or one the passes light. -static SETTLED: AtomicBool = AtomicBool::new(false); - /// `work` run on the trace's worker, off the frame, one task after another. fn start( work: impl FnOnce() -> Result + Send + 'static, @@ -309,173 +307,170 @@ fn table_stages(programs: &Programs, hardware: bool) -> Result bool { - !SETTLED.load(Ordering::Relaxed) -} - -/// `said`, warned once, as why no scene is handed a pass from here on. -fn give_up(glue: &mut Glue, said: String) { - tracing::warn!(why = %said, "GTA VI's lighting passes did not prepare: the model is drawn as Material"); - glue.given_up = Some(said); -} +impl FrameLightState { + /// Whether the scene last drawn is not lit by the passes, still built or refused: a picture + /// taken then shows it as Material. + pub(crate) fn awaits(&self) -> bool { + !self.settled + } -/// `said` with where the scene last drawn stands with the lighting passes. -pub(crate) fn said(said: String) -> String { - let held = GLUE.lock().unwrap_or_else(PoisonError::into_inner); - let Some(glue) = held.as_ref() else { - return said; - }; - let line = match (glue.stood, &glue.given_up) { - (Some(Stood::Lit), _) => tr!("Lit by GTA VI's own lighting programs, translated: one each for the standard, clear coat, emissive, translucent and skin kinds, and the standard one for every other kind").to_owned(), - (Some(Stood::Refused), Some(why)) => tr!( - "GTA VI's lighting programs did not prepare, so the model is drawn as Material: {why}", - why = why.as_str(), - ), - (Some(_), _) => tr!("GTA VI's lighting programs are being prepared: the model is drawn as Material until they are").to_owned(), - (None, _) => return said, - }; - format!("{said}\n{line}") -} + /// `said`, warned once, as why no scene is handed a pass from here on. + fn give_up(&mut self, said: String) { + tracing::warn!(why = %said, "GTA VI's lighting passes did not prepare: the model is drawn as Material"); + self.given_up = Some(said); + } -/// Advance the passes for this frame of `scene`: whether where it stands with them moved, which -/// the Shaded line says. `hardware` says whether the drawing adapter is hardware rather than -/// software. -pub(crate) fn refresh( - devices: (&wgpu::Device, &wgpu::Queue), - scene: Option<&MeshletScene>, - archive: impl FnOnce() -> Option, - hardware: bool, -) -> bool { - let mut held = GLUE.lock().unwrap_or_else(PoisonError::into_inner); - let glue = held.get_or_insert_with(Glue::default); - // What was built for a device that went is of no use to this one; the programs read are. - if glue.device.as_ref() != Some(devices.0) || glue.hardware != Some(hardware) { - *glue = Glue { - programs: glue.programs.take(), - device: Some(devices.0.clone()), - hardware: Some(hardware), - ..Glue::default() + /// `said` with where the scene last drawn stands with the lighting passes. + pub(crate) fn said(&self, said: String) -> String { + let line = match (self.stood, &self.given_up) { + (Some(Stood::Lit), _) => tr!("Lit by GTA VI's own lighting programs, translated: one each for the standard, clear coat, emissive, translucent and skin kinds, and the standard one for every other kind").to_owned(), + (Some(Stood::Refused), Some(why)) => tr!( + "GTA VI's lighting programs did not prepare, so the model is drawn as Material: {why}", + why = why.as_str(), + ), + (Some(_), _) => tr!("GTA VI's lighting programs are being prepared: the model is drawn as Material until they are").to_owned(), + (None, _) => return said, }; + format!("{said}\n{line}") } - advance(glue, devices, scene, archive, hardware); - let lit = scene.is_none_or(MeshletScene::lit_by_game); - SETTLED.store(lit, Ordering::Relaxed); - let stood = scene.map(|_| match (lit, &glue.given_up) { - (true, _) => Stood::Lit, - (false, Some(_)) => Stood::Refused, - (false, None) => Stood::Preparing, - }); - std::mem::replace(&mut glue.stood, stood) != stood -} -/// Read the programs from the install's `archive` the first time, and hand a `scene` the -/// passes do not light yet the pass of each kind its targets hold, once a worker has built them. -fn advance( - glue: &mut Glue, - (device, queue): (&wgpu::Device, &wgpu::Queue), - scene: Option<&MeshletScene>, - archive: impl FnOnce() -> Option, - hardware: bool, -) { - let read = Arc::clone(glue.programs.get_or_insert_with(|| { - let archive = archive(); - start(move || { - let archive = archive.ok_or("no GTA VI install holds the effect container")?; - programs(&archive) - }) - })); - let tables = Arc::clone(glue.tables.get_or_insert_with(|| { - let (read, device, queue) = (Arc::clone(&read), device.clone(), queue.clone()); - start(move || { - let stages = table_stages(&*made_before(&read)?, hardware)?; - FrameLightTables::bake(&device, &queue, &stages).map_err(|e| e.to_string()) - }) - })); - let tone = Arc::clone(glue.tone.get_or_insert_with(|| { - let (read, device) = (Arc::clone(&read), device.clone()); - start(move || { - FrameTone::build(&device, &tone_stages(&*made_before(&read)?, hardware)?) - .map_err(|e| e.to_string()) - }) - })); - let Some(scene) = scene.filter(|s| !s.lit_by_game() && glue.given_up.is_none()) else { - return; - }; - // The standard program always: it lights every kind that has no program of its own. - // When binding every kind (`lit=all`), skip `kinds_held`; otherwise reduce kinds on the GPU. - let every = meshlets::lit_every_kind_aid(); - let kinds = if every { - None - } else { - match glue.held { - Some((number, kinds)) if number == scene.number() => Some(kinds), - _ => { - let Some(kinds) = scene.kinds_held(device, queue) else { - return; - }; - let said: Vec = (kinds.iter().enumerate()) - .filter(|(_, pixels)| **pixels > 0) - .map(|(kind, pixels)| format!("{kind}: {pixels}")) - .collect(); - tracing::info!(kinds = %said.join(", "), "the pixels of each kind of material a GTA VI frame holds, the background among kind 0's"); - glue.held = Some((scene.number(), kinds)); - Some(kinds) - } + /// Advance the passes for this frame of `scene`: whether where it stands with them moved, which + /// the Shaded line says. `hardware` says whether the drawing adapter is hardware rather than + /// software. + pub(crate) fn refresh( + &mut self, + devices: (&wgpu::Device, &wgpu::Queue), + scene: Option<&MeshletScene>, + archive: impl FnOnce() -> Option, + hardware: bool, + ) -> bool { + // What was built for a device that went is of no use to this one; the programs read are. + if self.device.as_ref() != Some(devices.0) || self.hardware != Some(hardware) { + *self = Self { + programs: self.programs.take(), + device: Some(devices.0.clone()), + hardware: Some(hardware), + ..Self::default() + }; } - }; - let wanted = (LIT_KINDS.iter().copied()) - .filter(|kind| every || *kind == 0 || kinds.is_some_and(|k| k[*kind as usize] > 0)); - let mut built = Vec::new(); - let mut waiting = peek(&tables).is_none() || peek(&tone).is_none(); - // A kind whose pass is not built has nothing to light its pixels: no pass is then handed. - let mut refused = None; - for kind in wanted { - let slot = glue.passes.entry(kind).or_insert_with(|| { + self.advance(devices, scene, archive, hardware); + let lit = scene.is_none_or(MeshletScene::lit_by_game); + self.settled = lit; + let stood = scene.map(|_| match (lit, &self.given_up) { + (true, _) => Stood::Lit, + (false, Some(_)) => Stood::Refused, + (false, None) => Stood::Preparing, + }); + std::mem::replace(&mut self.stood, stood) != stood + } + + /// Read the programs from the install's `archive` the first time, and hand a `scene` the + /// passes do not light yet the pass of each kind its targets hold, once a worker has built them. + fn advance( + &mut self, + (device, queue): (&wgpu::Device, &wgpu::Queue), + scene: Option<&MeshletScene>, + archive: impl FnOnce() -> Option, + hardware: bool, + ) { + let read = Arc::clone(self.programs.get_or_insert_with(|| { + let archive = archive(); + start(move || { + let archive = archive.ok_or("no GTA VI install holds the effect container")?; + programs(&archive) + }) + })); + let tables = Arc::clone(self.tables.get_or_insert_with(|| { + let (read, device, queue) = (Arc::clone(&read), device.clone(), queue.clone()); + start(move || { + let stages = table_stages(&*made_before(&read)?, hardware)?; + FrameLightTables::bake(&device, &queue, &stages).map_err(|e| e.to_string()) + }) + })); + let tone = Arc::clone(self.tone.get_or_insert_with(|| { let (read, device) = (Arc::clone(&read), device.clone()); start(move || { - let stages = stages_of(&*made_before(&read)?, kind, hardware)?; - FrameLightPass::build(&device, &stages).map_err(|e| e.to_string()) + FrameTone::build(&device, &tone_stages(&*made_before(&read)?, hardware)?) + .map_err(|e| e.to_string()) }) - }); - match peek(slot) { - Some(Ok(pass)) => built.push(pass), - Some(Err(why)) => refused = Some(format!("the pass of kind {kind}: {why}")), - None => waiting = true, + })); + let Some(scene) = scene.filter(|s| !s.lit_by_game() && self.given_up.is_none()) else { + return; + }; + // The standard program always: it lights every kind that has no program of its own. + // When binding every kind (`lit=all`), skip `kinds_held`; otherwise reduce kinds on the GPU. + let every = meshlets::lit_every_kind_aid(); + let kinds = if every { + None + } else { + match self.held { + Some((number, kinds)) if number == scene.number() => Some(kinds), + _ => { + let Some(kinds) = scene.kinds_held(device, queue) else { + return; + }; + let said: Vec = (kinds.iter().enumerate()) + .filter(|(_, pixels)| **pixels > 0) + .map(|(kind, pixels)| format!("{kind}: {pixels}")) + .collect(); + tracing::info!(kinds = %said.join(", "), "the pixels of each kind of material a GTA VI frame holds, the background among kind 0's"); + self.held = Some((scene.number(), kinds)); + Some(kinds) + } + } + }; + let wanted = (LIT_KINDS.iter().copied()) + .filter(|kind| every || *kind == 0 || kinds.is_some_and(|k| k[*kind as usize] > 0)); + let mut built = Vec::new(); + let mut waiting = peek(&tables).is_none() || peek(&tone).is_none(); + // A kind whose pass is not built has nothing to light its pixels: no pass is then handed. + let mut refused = None; + for kind in wanted { + let slot = self.passes.entry(kind).or_insert_with(|| { + let (read, device) = (Arc::clone(&read), device.clone()); + start(move || { + let stages = stages_of(&*made_before(&read)?, kind, hardware)?; + FrameLightPass::build(&device, &stages).map_err(|e| e.to_string()) + }) + }); + match peek(slot) { + Some(Ok(pass)) => built.push(pass), + Some(Err(why)) => refused = Some(format!("the pass of kind {kind}: {why}")), + None => waiting = true, + } } - } - if waiting { - return; - } - if let Some(why) = refused { - return give_up(glue, why); - } - let tables = match peek(&tables) { - Some(Ok(tables)) => tables, - Some(Err(why)) => return give_up(glue, why), - None => return, - }; - let tone = match peek(&tone) { - Some(Ok(tone)) => tone, - Some(Err(why)) => return give_up(glue, format!("the steps that tone the frame: {why}")), - None => return, - }; - // What the device refuses of the groups is the passes' refusal, and no panic. - let validation = device.push_error_scope(wgpu::ErrorFilter::Validation); - let bound = scene - .light_with(device, queue, &built, &tables, &tone) - .map_err(|e| e.to_string()); - let refused = pollster::block_on(validation.pop()).map(|error| error.to_string()); - match bound.and(refused.map_or(Ok(()), Err)) { - Ok(()) => { - let lit: Vec = built.iter().map(|pass| pass.kind().to_string()).collect(); - tracing::info!(kinds = %lit.join(", "), "a GTA VI frame is lit by the game's own lighting program of each of these kinds"); + if waiting { + return; + } + if let Some(why) = refused { + return self.give_up(why); } - // ponytail: one scene's refusal ends the passes for the device; no scene is asked again. - Err(why) => { - let _ = scene.light_with(device, queue, &[], &tables, &tone); - give_up(glue, why); + let tables = match peek(&tables) { + Some(Ok(tables)) => tables, + Some(Err(why)) => return self.give_up(why), + None => return, + }; + let tone = match peek(&tone) { + Some(Ok(tone)) => tone, + Some(Err(why)) => return self.give_up(format!("the steps that tone the frame: {why}")), + None => return, + }; + // What the device refuses of the groups is the passes' refusal, and no panic. + let validation = device.push_error_scope(wgpu::ErrorFilter::Validation); + let bound = scene + .light_with(device, queue, &built, &tables, &tone) + .map_err(|e| e.to_string()); + let refused = pollster::block_on(validation.pop()).map(|error| error.to_string()); + match bound.and(refused.map_or(Ok(()), Err)) { + Ok(()) => { + let lit: Vec = built.iter().map(|pass| pass.kind().to_string()).collect(); + tracing::info!(kinds = %lit.join(", "), "a GTA VI frame is lit by the game's own lighting program of each of these kinds"); + } + // ponytail: one scene's refusal ends the passes for the device; no scene is asked again. + Err(why) => { + let _ = scene.light_with(device, queue, &[], &tables, &tone); + self.give_up(why); + } } } } diff --git a/src/render/gta6_hair.rs b/src/render/gta6_hair.rs index c696c317..038ec6df 100644 --- a/src/render/gta6_hair.rs +++ b/src/render/gta6_hair.rs @@ -10,7 +10,6 @@ use std::collections::HashMap; use std::fs::File; use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex}; use glam::Vec3; use or_io::container::rpf::{read_rpf9_body, Gta6Mount, GtaViKeys, Rpf9Sections, RPF9_SLOT}; @@ -47,18 +46,6 @@ const DEFAULT_GRADIENT: [[f32; 3]; 4] = [ /// Maximum interpolated child strands generated across all hair parts of one ped. const MAX_CHILD_STRANDS: usize = 36_000; -static ACTIVE: Mutex>>> = Mutex::new(None); - -/// Set the active strand hair ribbon vertices for the ped currently being rendered. -pub(crate) fn set_active(vertices: Option>>) { - *ACTIVE.lock().unwrap_or_else(|p| p.into_inner()) = vertices; -} - -/// The active ped's strand hair ribbon vertices, if any. -pub(crate) fn active() -> Option>> { - ACTIVE.lock().unwrap_or_else(|p| p.into_inner()).clone() -} - /// Indexed secondary-motion hair asset map, cloth body offsets, and colour database from `packs.rpf`. pub(crate) struct HairLibrary { packs_path: PathBuf, diff --git a/src/render/gta6_meshlets/mod.rs b/src/render/gta6_meshlets/mod.rs index dfeea608..6755cb10 100644 --- a/src/render/gta6_meshlets/mod.rs +++ b/src/render/gta6_meshlets/mod.rs @@ -26,31 +26,99 @@ use crate::state::{gta6_shaders, AppState, DocPayload}; /// dwords of 32 bits read as unsigned numbers. const DWORDS: u32 = (4 << 8) | 32; -/// Whether a geometry of the drawable last made into surfaces still awaited its programs. -static AWAITED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +/// The effect of the geometry a windscreen's wipers clear. +const WIPER_MASK: &str = "windshield_wipermask"; -/// Whether the drawable [`meshlets`] last read still awaits the translation of a program: a -/// picture taken then lacks what that program draws. -pub(crate) fn awaits_programs() -> bool { - AWAITED.load(std::sync::atomic::Ordering::Relaxed) +/// Per-bridge GTA VI meshlet session state: whether the last build awaited shader translation, +/// which effects were drawing or suffered a device loss, and the session's decoded texture cache. +#[derive(Default)] +pub(crate) struct MeshletSession { + /// Whether a geometry of the drawable last made into surfaces still awaited its programs. + awaited: bool, + /// Effects whose own passes were last handed to the device. + drawing: Vec, + /// Effects a device was lost under: such an effect draws as Material until restart. + lost: BTreeSet, + /// First-level decoded texture cache keyed by texture hash. + decoded: Mutex>, } -/// The effect of the geometry a windscreen's wipers clear. -const WIPER_MASK: &str = "windshield_wipermask"; +impl MeshletSession { + /// Whether the drawable [`meshlets`] last read still awaits the translation of a program: a + /// picture taken then lacks what that program draws. + pub(crate) fn awaits_programs(&self) -> bool { + self.awaited + } -/// The effects whose own passes were last handed to the device, and those a device was lost -/// under: such an effect draws as Material until the program is started again. -type Under = (Vec, BTreeSet); -static UNDER: Mutex = Mutex::new((Vec::new(), BTreeSet::new())); + /// Keep the effects last handed to the device from one made after it: the device was lost + /// while it drew them. + pub(crate) fn device_lost(&mut self) { + self.lost.extend(self.drawing.drain(..)); + } -fn lose((drawing, lost): &mut Under) { - lost.extend(drawing.drain(..)); -} + /// Take the effects that suffered a device loss so a recovered bridge continues refusing them. + pub(crate) fn take_lost_effects(&mut self) -> BTreeSet { + std::mem::take(&mut self.lost) + } -/// Keep the effects last handed to the device from one made after it: the device was lost -/// while it drew them. -pub(crate) fn device_lost() { - lose(&mut UNDER.lock().unwrap_or_else(|p| p.into_inner())); + /// Seed this session with effects that suffered a device loss on an earlier bridge. + pub(crate) fn carry_lost_effects(&mut self, lost: BTreeSet) { + self.lost.extend(lost); + } + + /// The first level of the texture of `key`, decoded once a session, on a worker: a frame never + /// waits for a map, and a model opened again, or another that wears the same maps, decodes + /// nothing. `Err` while the worker decodes it; `stored` gives the level as its pack stores it. + // ponytail: past the cap every map is let go at once; let go the least lately used when a + // session that opens many models shows the decode again. + pub(super) fn decoded( + &self, + key: u64, + stored: impl FnOnce() -> Option, + ) -> Result>, ()> { + let mut kept = self.decoded.lock().unwrap_or_else(|p| p.into_inner()); + if let Some(slot) = kept.get(&key) { + return slot + .lock() + .unwrap_or_else(|p| p.into_inner()) + .clone() + .ok_or(()); + } + // A map no pack read so far holds is asked for again: its pack may be read by then. + let Some(stored) = stored() else { + return Ok(None); + }; + let bytes = |slot: &Decoding| match &*slot.lock().unwrap_or_else(|p| p.into_inner()) { + Some(Some(image)) => image.rgba.len(), + _ => 0, + }; + if kept.values().map(bytes).sum::() > DECODED_BYTES { + kept.clear(); + } + let slot = Decoding::default(); + kept.insert(key, Arc::clone(&slot)); + drop(kept); + super::gta6_maps::decode(move || { + struct Settle(Decoding); + impl Drop for Settle { + fn drop(&mut self) { + let mut guard = self.0.lock().unwrap_or_else(|p| p.into_inner()); + if guard.is_none() { + *guard = Some(None); + } + } + } + let guard = Settle(slot); + let image = stored.decode().map(Arc::new); + *guard.0.lock().unwrap_or_else(|p| p.into_inner()) = Some(image); + }); + Err(()) + } + + /// Whether no worker still decodes the map of any of `keys`; none is started. + pub(crate) fn all_in(&self, keys: &[u64]) -> bool { + keys.iter().all(|key| self.decoded(*key, || None).is_ok()) + } } /// The active GTA VI drawable drawn by its own programs. @@ -135,62 +203,6 @@ const DECODED_BYTES: usize = 1 << 30; /// A map as far as it is decoded: nothing while a worker decodes it. type Decoding = Arc>>>>; -/// The first level of the texture of `key`, decoded once a session, on a worker: a frame never -/// waits for a map, and a model opened again, or another that wears the same maps, decodes -/// nothing. `Err` while the worker decodes it; `stored` gives the level as its pack stores it. -// ponytail: past the cap every map is let go at once; let go the least lately used when a -// session that opens many models shows the decode again. -pub(super) fn decoded( - key: u64, - stored: impl FnOnce() -> Option, -) -> Result>, ()> { - use std::collections::HashMap; - static DECODED: std::sync::Mutex>> = std::sync::Mutex::new(None); - let mut guard = DECODED.lock().unwrap_or_else(|p| p.into_inner()); - let kept = guard.get_or_insert_with(HashMap::new); - if let Some(slot) = kept.get(&key) { - return slot - .lock() - .unwrap_or_else(|p| p.into_inner()) - .clone() - .ok_or(()); - } - // A map no pack read so far holds is asked for again: its pack may be read by then. - let Some(stored) = stored() else { - return Ok(None); - }; - let bytes = |slot: &Decoding| match &*slot.lock().unwrap_or_else(|p| p.into_inner()) { - Some(Some(image)) => image.rgba.len(), - _ => 0, - }; - if kept.values().map(bytes).sum::() > DECODED_BYTES { - kept.clear(); - } - let slot = Decoding::default(); - kept.insert(key, Arc::clone(&slot)); - drop(guard); - super::gta6_maps::decode(move || { - struct Settle(Decoding); - impl Drop for Settle { - fn drop(&mut self) { - let mut guard = self.0.lock().unwrap_or_else(|p| p.into_inner()); - if guard.is_none() { - *guard = Some(None); - } - } - } - let guard = Settle(slot); - let image = stored.decode().map(Arc::new); - *guard.0.lock().unwrap_or_else(|p| p.into_inner()) = Some(image); - }); - Err(()) -} - -/// Whether no worker still decodes the map of any of `keys`; none is started. -pub(crate) fn all_in(keys: &[u64]) -> bool { - keys.iter().all(|key| decoded(*key, || None).is_ok()) -} - /// The texel a map no pack holds is read as, where a white one is not neutral: a normal map /// bends no normal (a program takes the square root of what its two channels leave of one), and /// a specular map states no metal (a program keeps one less its red of the diffuse colour). @@ -577,7 +589,7 @@ fn surface( /// Have workers start on every map the active GTA VI drawable's shaders name, before its /// programs are translated: the two take about as long, and neither waits for the other. -pub(crate) fn start_decoding(state: &AppState) { +pub(crate) fn start_decoding(state: &AppState, session: &MeshletSession, beside: Option<&[Part]>) { let Some(doc) = state.active_document() else { return; }; @@ -588,10 +600,10 @@ pub(crate) fn start_decoding(state: &AppState) { if drawable_of(resource, selection).is_none() { return; } - each_shown(state, &mut |drawable, _, _| { + each_shown(state, beside, &mut |drawable, _, _| { let shaders = drawable.shaders.iter(); for key in shaders.flat_map(|shader| shader.texture_keys.iter().flatten()) { - let _ = decoded(*key, || super::gta6_maps::stored(state, selection, *key)); + let _ = session.decoded(*key, || super::gta6_maps::stored(state, selection, *key)); } }); } @@ -622,42 +634,14 @@ pub(crate) fn drawn(models: &[Model]) -> impl Iterator { /// What the active GTA VI drawable's geometries wear: each one's effect with the streams it /// holds, which its shading pass is picked by. Empty where the document shows no such drawable. -pub(crate) fn worn(state: &AppState) -> Vec { +pub(crate) fn worn(state: &AppState, beside: Option<&[Part]>) -> Vec { let mut worn = Vec::new(); - each_shown(state, &mut |drawable, models, _| { + each_shown(state, beside, &mut |drawable, models, _| { worn.extend(worn_by(drawable, models)) }); worn } -/// The parts drawn beside the active document's own drawable, where a run fitted some: a -/// vehicle's wheels, each on its bone. -static BESIDE: Mutex>>> = Mutex::new(None); - -/// Have `parts` drawn beside the own drawable of the document shown from now on, or none. -pub(crate) fn show_beside(parts: Option>) { - *BESIDE.lock().unwrap_or_else(|p| p.into_inner()) = parts.map(Arc::new); -} - -/// Whether the view frames the parts beside the document's drawable with it: a ped's parts, -/// which make the figure, and not a vehicle's wheels. -static FRAMED_WHOLE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - -/// Have the parts [`show_beside`] keeps framed with the document's drawable, or not. -pub(crate) fn frame_beside(whole: bool) { - FRAMED_WHOLE.store(whole, std::sync::atomic::Ordering::Relaxed); -} - -/// The parts [`show_beside`] kept, where the view frames them with the document's drawable. -pub(crate) fn framed_beside() -> Option>> { - beside().filter(|_| FRAMED_WHOLE.load(std::sync::atomic::Ordering::Relaxed)) -} - -/// The parts [`show_beside`] kept. -pub(crate) fn beside() -> Option>> { - BESIDE.lock().unwrap_or_else(|p| p.into_inner()).clone() -} - /// The models of the level of `drawable` the view draws at `lod`: that level's, else the first's. fn level_of(drawable: &Drawable, lod: usize) -> Option<&[Model]> { let held = |level: usize| { @@ -673,32 +657,35 @@ pub(crate) type Shown<'a> = dyn FnMut(&Drawable, &[Model], [f32; 12]) + 'a; /// Each drawable the view draws of the active GTA VI document, with the models of its level and /// where it is placed, a row-major 3x4 matrix: the parts drawn in place of a weapon's own mesh, -/// each on its point, else the document's own drawable where it stands. -pub(crate) fn each_shown(state: &AppState, each: &mut Shown<'_>) { +/// each on its point, else the document's own drawable where it stands followed by any `beside` +/// parts. +pub(crate) fn each_shown(state: &AppState, beside: Option<&[Part]>, each: &mut Shown<'_>) { let parts = (state.active_document()).and_then(|doc| super::gta6_drawable::parts_drawn(state, doc)); - let parts = match parts { - Some(parts) => parts, + let emit = |parts: &[Part], each: &mut Shown<'_>| { + for part in parts { + let shown = drawable_of(&part.resource, None).and_then(|drawable| { + Some((drawable, level_of(drawable, state.preview_scene.lod)?)) + }); + if let Some((drawable, models)) = shown { + let rows = part.place.transpose().to_cols_array(); + let mut placement = [0.0; 12]; + placement.copy_from_slice(&rows[..12]); + each(drawable, models, placement); + } + } + }; + match parts { + Some(parts) => emit(&parts, each), None => { let Some((drawable, models)) = drawn_level(state) else { return; }; each(drawable, models, super::gta6_instances::IN_PLACE[0]); - match beside() { - Some(parts) => parts, - None => return, + if let Some(parts) = beside { + emit(parts, each); } } - }; - for part in parts.iter() { - let shown = drawable_of(&part.resource, None) - .and_then(|drawable| Some((drawable, level_of(drawable, state.preview_scene.lod)?))); - if let Some((drawable, models)) = shown { - let rows = part.place.transpose().to_cols_array(); - let mut placement = [0.0; 12]; - placement.copy_from_slice(&rows[..12]); - each(drawable, models, placement); - } } } @@ -715,50 +702,71 @@ pub(crate) fn worn_by(drawable: &Drawable, models: &[Model]) -> Vec Option> { +pub(crate) fn meshlets( + state: &AppState, + session: &mut MeshletSession, + overrides: &super::gta6_overrides::Gta6DrawOverrides, + terrain: &mut super::gta6_terrain::TerrainCache, +) -> Option> { drawn_level(state)?; let selection = state.selection.selected(state.active_document()?.id); let stored = |key: u64| super::gta6_maps::stored(state, selection, key); - let lost = UNDER.lock().unwrap_or_else(|p| p.into_inner()).1.clone(); - AWAITED.store(false, std::sync::atomic::Ordering::Relaxed); + session.awaited = false; + let mut awaited = false; // Every drawable shown, its meshes numbered after those of the ones before it. let mut merged: Option)>> = None; let mut before = 0; - each_shown(state, &mut |drawable, models, placement| { - let name = drawable.name.as_str(); - let sources = Sources { - shading: >a6_shaders::shading, - map: &|key| decoded(key, || stored(key)), - layered: &|| gta6_layer_index::worn_as(state, name, true), - lost: &lost, - ped: &|| crate::state::gta6_shaders::ped_assets::worn(state, name), - tile: &|| crate::state::gta6_shaders::terrain_tile::worn(state), - game_texture: &|name| crate::state::gta6_shaders::global_textures::worn(state, name), - skin_tones: &|| crate::state::gta6_shaders::ped_assets::skin_tones::worn(state), - }; - let made = meshlets_of(drawable, models, &sources, placement).map(|(mut made, effects)| { - made.of.iter_mut().for_each(|(mesh, _)| *mesh += before); - made.rest.iter_mut().for_each(|mesh| *mesh += before); - (made, effects) - }); - before += drawn(models).count(); - merged = Some(match (merged.take(), made) { - (None, made) => made, - (Some(Some((mut all, mut effects))), Some((made, more))) => { - all.surfaces.extend(made.surfaces); - all.of.extend(made.of); - all.rest.extend(made.rest); - all.zeroed += made.zeroed; - all.why = all.why.or(made.why); - all.decoding |= made.decoding; - effects.extend(more); - Some((all, effects)) - } - _ => None, - }); - }); + each_shown( + state, + overrides.beside(), + &mut |drawable, models, placement| { + let name = drawable.name.as_str(); + let sources = Sources { + shading: >a6_shaders::shading, + map: &|key| session.decoded(key, || stored(key)), + layered: &|| gta6_layer_index::worn_as(state, name, true), + lost: &session.lost, + ped: &|| crate::state::gta6_shaders::ped_assets::worn(state, name), + tile: &|| crate::state::gta6_shaders::terrain_tile::worn(state), + game_texture: &|name| { + crate::state::gta6_shaders::global_textures::worn(state, name) + }, + skin_tones: &|| crate::state::gta6_shaders::ped_assets::skin_tones::worn(state), + }; + let made = meshlets_of( + drawable, + models, + &sources, + placement, + overrides, + terrain, + &mut awaited, + ) + .map(|(mut made, effects)| { + made.of.iter_mut().for_each(|(mesh, _)| *mesh += before); + made.rest.iter_mut().for_each(|mesh| *mesh += before); + (made, effects) + }); + before += drawn(models).count(); + merged = Some(match (merged.take(), made) { + (None, made) => made, + (Some(Some((mut all, mut effects))), Some((made, more))) => { + all.surfaces.extend(made.surfaces); + all.of.extend(made.of); + all.rest.extend(made.rest); + all.zeroed += made.zeroed; + all.why = all.why.or(made.why); + all.decoding |= made.decoding; + effects.extend(more); + Some((all, effects)) + } + _ => None, + }); + }, + ); + session.awaited = awaited; let (mut out, effects) = merged??; - UNDER.lock().unwrap_or_else(|p| p.into_inner()).0 = effects; + session.drawing = effects; match (out.surfaces.is_empty(), out.why.take()) { (true, Some(why)) => Some(Err(why)), (true, None) => None, @@ -828,6 +836,9 @@ pub(crate) fn meshlets_of( models: &[Model], from: &Sources<'_>, placement: [f32; 12], + overrides: &super::gta6_overrides::Gta6DrawOverrides, + terrain: &mut super::gta6_terrain::TerrainCache, + awaited: &mut bool, ) -> Option<(Meshlets, Vec)> { let mut out = Meshlets { surfaces: Vec::new(), @@ -851,7 +862,7 @@ pub(crate) fn meshlets_of( }; let mut tile = map; let mut effects = Vec::new(); - let active_pose = super::gta6_ped_pose::active(); + let active_pose = overrides.ped_pose.as_deref(); let geometries = or_io::gta6::headerless::main_view_models(models) .flat_map(|model| { model @@ -877,7 +888,7 @@ pub(crate) fn meshlets_of( Some(Ok(pass)) => Ok(pass), Some(Err(why)) => Err(format!("{effect}: {why}")), None => { - AWAITED.store(true, std::sync::atomic::Ordering::Relaxed); + *awaited = true; Err(tr!( "{effect}: its programs are not translated yet", effect = effect, @@ -906,7 +917,7 @@ pub(crate) fn meshlets_of( let mut drawn = surface(pass, geometry, shader, &mut texture, worn, &mut tile); if let Some((surface, _)) = drawn.as_mut() { game_textures(pass, from.game_texture, &decoding, &mut surface.feeds); - super::gta6_paint::fill(pass, &drawable.name, &mut surface.feeds); + super::gta6_paint::fill(pass, &drawable.name, overrides, &mut surface.feeds); let stages = || pass.mesh.feeds.iter().chain(&pass.pixel.feeds); if stages().any(|fed| fed.feed == Filled::SkinTones) { let tones = skin_tones.get_or_insert_with(|| { @@ -915,7 +926,12 @@ pub(crate) fn meshlets_of( None }) }); - super::gta6_ped::fill_skin(pass, tones.as_deref(), &mut surface.feeds); + super::gta6_ped::fill_skin( + pass, + tones.as_deref(), + overrides.skin_preset, + &mut surface.feeds, + ); } let joined = super::gta6_ped::joined_for(pass, &mut ped, from.ped, &decoding); let mut ped_map = map; @@ -939,7 +955,8 @@ pub(crate) fn meshlets_of( let tile = terrain_tile.get_or_insert_with(|| (from.tile)()).clone(); let mut tile_map = map; let feeds = &mut surface.feeds; - let fed = super::gta6_terrain::fill(pass, tile.as_deref(), &mut tile_map, feeds); + let fed = + super::gta6_terrain::fill(terrain, pass, tile.as_deref(), &mut tile_map, feeds); if let Err(why) = fed { out.rest.push(mesh); out.why.get_or_insert(format!("{effect}: {why}")); @@ -950,7 +967,7 @@ pub(crate) fn meshlets_of( if let Some((surface, zeroed)) = drawn { let mut surface = surface; stand(pass, &mut surface, placement); - if let Some(pose) = active_pose.as_deref() { + if let Some(pose) = active_pose { pose_surface(pass, &mut surface, drawable, model, pose); } for mut surface in super::gta6_instances::placed(pass, surface, &[placement]) { @@ -967,7 +984,7 @@ pub(crate) fn meshlets_of( if let Some((mut surface, _)) = surface(&next, geometry, shader, &mut texture, None, &mut tile) { - if let Some(pose) = active_pose.as_deref() { + if let Some(pose) = active_pose { pose_surface(&next, &mut surface, drawable, model, pose); } merge_feeds(&next.merged, &mut surface.feeds); diff --git a/src/render/gta6_overrides.rs b/src/render/gta6_overrides.rs new file mode 100644 index 00000000..f70de65c --- /dev/null +++ b/src/render/gta6_overrides.rs @@ -0,0 +1,174 @@ +//! Per-draw GTA VI rendering overrides owned by [`super::RenderBridge`]. +//! +//! Headless photography (`src/photo/gta6.rs`, `src/photo/gta6_shaded.rs`) configures per-model +//! vehicle paint/finishes, beside parts (wheels or ped kit garments), ped pose, strand hair, +//! skin-tone preset, and studio lighting through this struct instead of mutating process-global +//! statics. + +use std::collections::HashMap; +use std::ops::{Deref, DerefMut}; +use std::sync::Arc; + +use or_renderer::game_shaders::meshlets::HairVertex; + +use super::gta6_paint::{Finish, Finished, Painted}; +use super::gta6_ped_pose::PedPose; +use super::RenderBridge; +use crate::state::gta6_weapon_parts::Part; + +/// Explicit per-draw overrides for GTA VI Shaded and Material rendering, owned by [`RenderBridge`]. +#[derive(Default)] +pub(crate) struct Gta6DrawOverrides { + /// Skin tone preset hash worn by the active ped kit (`0` for the engine fallback preset). + pub skin_preset: u32, + /// Active ped's strand hair ribbon vertices, if any. + pub hair: Option>>, + /// Active ped pose applied to skinned GTA VI meshlet surfaces, or `None` for bind pose. + pub ped_pose: Option>, + /// Per-model surface-id linear paint colours (`model_name -> colours`), where a run gave them. + pub paint: Option, + /// Per-model surface-id paint finishes (`model_name -> finishes`), where a run gave them. + pub finish: Option, + /// Parts drawn beside the active document's own drawable (vehicle wheels or ped kit parts). + pub beside: Option>>, + /// Whether camera framing includes [`Self::beside`] with the document's drawable (ped kits). + pub framed_whole: bool, + /// Whether GTA VI models are lit as in a studio (headless Shaded photography). + pub studio: bool, +} + +impl Gta6DrawOverrides { + /// Parts drawn beside the active document's own drawable, if any. + pub(crate) fn beside(&self) -> Option<&[Part]> { + self.beside.as_deref().map(Vec::as_slice) + } + + /// Parts drawn beside the active document's own drawable when framed together with it. + pub(crate) fn framed_beside(&self) -> Option<&[Part]> { + self.beside().filter(|_| self.framed_whole) + } + + /// Set the per-model surface-id paint colours. + pub(crate) fn set_paint(&mut self, colours: HashMap>) { + let colours = colours.into_iter().map(|(name, ids)| (name, Arc::new(ids))); + self.paint = Some(colours.collect()); + } + + /// Set the per-model surface-id paint finishes. + pub(crate) fn set_finish(&mut self, finishes: HashMap>>) { + let finishes = finishes + .into_iter() + .map(|(name, ids)| (name, Arc::new(ids))); + self.finish = Some(finishes.collect()); + } + + /// Set the parts drawn beside the active document's drawable, or clear them. + pub(crate) fn set_beside(&mut self, parts: Option>) { + self.beside = parts.map(Arc::new); + } + + /// Clear every override back to its default rest state. + pub(crate) fn clear(&mut self) { + *self = Self::default(); + } +} + +/// Scoped guard giving mutable access to a [`RenderBridge`] and resetting its [`Gta6DrawOverrides`] +/// on drop (including across loop `continue`, early returns, and panics). +pub(crate) struct Gta6OverridesGuard<'a> { + bridge: &'a mut RenderBridge, +} + +impl<'a> Gta6OverridesGuard<'a> { + pub(crate) fn new(bridge: &'a mut RenderBridge) -> Self { + Self { bridge } + } +} + +impl Deref for Gta6OverridesGuard<'_> { + type Target = RenderBridge; + + fn deref(&self) -> &Self::Target { + self.bridge + } +} + +impl DerefMut for Gta6OverridesGuard<'_> { + fn deref_mut(&mut self) -> &mut Self::Target { + self.bridge + } +} + +impl Drop for Gta6OverridesGuard<'_> { + fn drop(&mut self) { + self.bridge.reset_gta6_overrides(); + } +} + +/// Scoped guard that enables studio lighting on a [`RenderBridge`] and restores its prior value on +/// drop. +pub(crate) struct Gta6StudioGuard<'a> { + bridge: &'a mut RenderBridge, + previous: bool, +} + +impl<'a> Gta6StudioGuard<'a> { + pub(crate) fn new(bridge: &'a mut RenderBridge) -> Self { + let previous = std::mem::replace(&mut bridge.gta6_overrides_mut().studio, true); + Self { bridge, previous } + } +} + +impl Deref for Gta6StudioGuard<'_> { + type Target = RenderBridge; + + fn deref(&self) -> &Self::Target { + self.bridge + } +} + +impl DerefMut for Gta6StudioGuard<'_> { + fn deref_mut(&mut self) -> &mut Self::Target { + self.bridge + } +} + +impl Drop for Gta6StudioGuard<'_> { + fn drop(&mut self) { + self.bridge.gta6_overrides_mut().studio = self.previous; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn overrides_clear_resets_every_field_and_framed_beside_respects_flag() { + let mut overrides = Gta6DrawOverrides::default(); + assert_eq!(overrides.skin_preset, 0); + assert!(overrides.beside().is_none()); + assert!(overrides.framed_beside().is_none()); + + overrides.skin_preset = 0x31D7_BC23; + overrides.studio = true; + overrides.set_paint(HashMap::from([("car".to_string(), vec![[1, 2, 3]])])); + overrides.set_finish(HashMap::from([("car".to_string(), vec![Some([9; 9])])])); + overrides.set_beside(Some(Vec::new())); + assert!(overrides.beside().is_some()); + assert!(overrides.framed_beside().is_none()); + + overrides.framed_whole = true; + assert!(overrides.framed_beside().is_some()); + + overrides.clear(); + assert_eq!(overrides.skin_preset, 0); + assert!(!overrides.studio); + assert!(!overrides.framed_whole); + assert!(overrides.paint.is_none()); + assert!(overrides.finish.is_none()); + assert!(overrides.beside().is_none()); + assert!(overrides.hair.is_none()); + assert!(overrides.ped_pose.is_none()); + } +} diff --git a/src/render/gta6_paint.rs b/src/render/gta6_paint.rs index ebdf1f2d..ab4baf5c 100644 --- a/src/render/gta6_paint.rs +++ b/src/render/gta6_paint.rs @@ -2,7 +2,7 @@ //! surface id into a record's number, a record a surface, and three paint records a surface. use std::collections::{BTreeMap, HashMap}; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use or_cli::{Gta6Feed as Filled, Gta6ShadingPass}; use or_renderer::game_shaders::meshlets::Feed; @@ -55,8 +55,7 @@ const ROUGH: u8 = 0x8C; const CHROME: ([u8; 3], u8) = ([190, 190, 195], 0x18); /// The colour of each surface id of each model drawn, by the model's name, where a run gave them. -type Painted = HashMap>>; -static PAINTED: Mutex> = Mutex::new(None); +pub(crate) type Painted = HashMap>>; /// The finish of a surface as its paint record holds it: its metal at the two ends a map of /// the drawable mixes, then its roughness at the two, then its clear coat's strength and @@ -64,23 +63,7 @@ static PAINTED: Mutex> = Mutex::new(None); pub(crate) type Finish = [u8; 9]; /// The finish of each surface id of each model drawn, where the build's tables state one. -type Finished = HashMap>>>; -static FINISHED: Mutex> = Mutex::new(None); - -/// Have the models drawn from now on finished as `finishes` state, a surface id each, by the -/// model's name; an id with none keeps the finish the editor gives its kind of model. -pub(crate) fn finish_with(finishes: HashMap>>) { - let finishes = finishes - .into_iter() - .map(|(name, ids)| (name, Arc::new(ids))); - *FINISHED.lock().unwrap_or_else(|p| p.into_inner()) = Some(finishes.collect()); -} - -/// Have the models drawn from now on painted with `colours`: one a surface id, by the model's name. -pub(crate) fn paint_with(colours: HashMap>) { - let colours = colours.into_iter().map(|(name, ids)| (name, Arc::new(ids))); - *PAINTED.lock().unwrap_or_else(|p| p.into_inner()) = Some(colours.collect()); -} +pub(crate) type Finished = HashMap>>>; /// The table of surface ids: each id names the record of its own number, from a base of nought. fn ids() -> Vec { @@ -157,24 +140,28 @@ fn paints(colours: &[[u8; 3]], finishes: &[Option], plain: (u8, u8)) -> bytes } -/// Fill what `pass` reads of a vehicle's paint from the colours [`paint_with`] kept for the model +/// Fill what `pass` reads of a vehicle's paint from the colours `overrides` holds for the model /// named `name`; nothing where none is kept, which leaves each buffer as the editor leaves what /// only the game fills. -pub(crate) fn fill(pass: &Gta6ShadingPass, name: &str, feeds: &mut BTreeMap<(u32, u32), Feed>) { +pub(crate) fn fill( + pass: &Gta6ShadingPass, + name: &str, + overrides: &super::gta6_overrides::Gta6DrawOverrides, + feeds: &mut BTreeMap<(u32, u32), Feed>, +) { let model = super::gta6_drawable::model_name(name).to_ascii_lowercase(); - let painted = PAINTED.lock().unwrap_or_else(|p| p.into_inner()); - let Some(colours) = painted.as_ref().and_then(|all| all.get(&model)).cloned() else { + let Some(colours) = overrides.paint.as_ref().and_then(|all| all.get(&model)) else { return; }; - drop(painted); - let finished = FINISHED.lock().unwrap_or_else(|p| p.into_inner()); - let finishes = finished.as_ref().and_then(|all| all.get(&model)).cloned(); - drop(finished); - let finishes = finishes.as_deref().map_or(&[][..], Vec::as_slice); + let finishes = overrides + .finish + .as_ref() + .and_then(|all| all.get(&model)) + .map_or(&[][..], |v| v.as_slice()); for fed in pass.mesh.feeds.iter().chain(&pass.pixel.feeds) { let bytes = match fed.feed { Filled::Zero(Some(IDS)) => ids(), - Filled::Zero(Some(PAINTS)) => paints(&colours, finishes, finish_of(&model)), + Filled::Zero(Some(PAINTS)) => paints(colours, finishes, finish_of(&model)), Filled::Zero(Some(SECONDS)) => seconds(), Filled::Zero(Some(TYRES)) => tyres(), Filled::Zero(Some(VEHICLE)) => vehicle(), diff --git a/src/render/gta6_ped.rs b/src/render/gta6_ped.rs index 93645c23..0c94eb4a 100644 --- a/src/render/gta6_ped.rs +++ b/src/render/gta6_ped.rs @@ -2,7 +2,6 @@ //! whether the pixel program samples the textures it picks, and those textures, by the join. use std::collections::BTreeMap; -use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::Arc; use or_cli::gta6_ped_layers::{ @@ -160,19 +159,13 @@ pub(crate) fn fill( } } -static ACTIVE_SKIN_PRESET: AtomicU32 = AtomicU32::new(0); - -/// Set the skin tone preset hash worn by the active ped kit (0 to use the engine fallback preset). -pub(crate) fn set_active_skin_preset(preset: u32) { - ACTIVE_SKIN_PRESET.store(preset, Ordering::Relaxed); -} - /// Feed the skin tone table and the object record of a pass that reads the table with `tones` -/// as the game builds them for the active ped's preset, or the fallback preset when none is set. +/// as the game builds them for `preset`, or the fallback preset when `preset` is 0. /// `None` where no skin tones are loaded leaves the records at rest. pub(crate) fn fill_skin( pass: &Gta6ShadingPass, tones: Option<&SkinTones>, + preset: u32, feeds: &mut BTreeMap<(u32, u32), Feed>, ) { let stages = || pass.mesh.feeds.iter().chain(&pass.pixel.feeds); @@ -204,7 +197,6 @@ pub(crate) fn fill_skin( tones: &loaded_tones, presets: &presets, }; - let preset = ACTIVE_SKIN_PRESET.load(Ordering::Relaxed); let slot = loaded.slot(preset); let record = ObjectData { skin_tone: slot, @@ -396,10 +388,8 @@ mod tests { ], }; let pass = pass(vec![fed(0, Filled::SkinTones), fed(1, Filled::ObjectData)]); - set_active_skin_preset(0x31D7_BC23); let mut feeds = BTreeMap::new(); - fill_skin(&pass, Some(&tones), &mut feeds); - set_active_skin_preset(0); + fill_skin(&pass, Some(&tones), 0x31D7_BC23, &mut feeds); let Some(Feed::Bytes(bytes)) = feeds.get(&(1, 1)) else { panic!("object data was not fed"); }; diff --git a/src/render/gta6_ped_pose.rs b/src/render/gta6_ped_pose.rs index c02543a2..f34e50f5 100644 --- a/src/render/gta6_ped_pose.rs +++ b/src/render/gta6_ped_pose.rs @@ -5,7 +5,7 @@ use std::collections::HashMap; use std::fs::File; use std::path::Path; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use glam::{Mat4, Vec3}; use or_io::container::rpf::{read_rpf9_body, Gta6Mount, GtaViKeys, Rpf9Sections, RPF9_SLOT}; @@ -125,18 +125,6 @@ pub(crate) struct HumanPoses { pub female: Option>, } -static ACTIVE: Mutex>> = Mutex::new(None); - -/// Set the active ped pose applied to skinned GTA VI meshlet surfaces, or `None` for bind pose. -pub(crate) fn set_active(pose: Option>) { - *ACTIVE.lock().unwrap_or_else(|p| p.into_inner()) = pose; -} - -/// The active ped pose, where a kit photo run posed one. -pub(crate) fn active() -> Option> { - ACTIVE.lock().unwrap_or_else(|p| p.into_inner()).clone() -} - /// Load the canonical male and female standing neutral idle poses from `root`. pub(crate) fn load_human_poses(root: &Path) -> HumanPoses { let Ok(keys) = crate::state::rpf9_scan::rpf9_table::keys() else { diff --git a/src/render/gta6_shaded.rs b/src/render/gta6_shaded.rs index b9ddb163..66ad5864 100644 --- a/src/render/gta6_shaded.rs +++ b/src/render/gta6_shaded.rs @@ -36,6 +36,7 @@ pub(crate) struct Fallback { // of: a building's maps decoded here held its first own frame for tens of seconds. pub(crate) fn shaded_surfaces( state: &AppState, + session: &super::gta6_meshlets::MeshletSession, draws: &dyn Fn(&str) -> Result<(), String>, ) -> Option { let doc = state.active_document()?; @@ -48,8 +49,16 @@ pub(crate) fn shaded_surfaces( let materials: Vec<(String, Result)> = (drawable.shaders.iter()) .map(|shader| { let effect = effect_name(shader.name_hash); - let made = draws(&effect) - .map(|()| material(state, selection, shader, effect.clone(), &mut decoding)); + let made = draws(&effect).map(|()| { + material( + state, + session, + selection, + shader, + effect.clone(), + &mut decoding, + ) + }); (effect, made) }) .collect(); @@ -91,21 +100,45 @@ pub(crate) fn pack_draws( } } -/// The box the geometries of the active GTA VI drawable's drawn level fill, from its least -/// corner to its greatest; `None` where the document shows none, or none of them reads. -pub(crate) fn bounds(state: &AppState) -> Option<(glam::Vec3, glam::Vec3)> { - let doc = state.active_document()?; - let DocPayload::Gta6Drawable(resource) = &doc.payload else { - return None; - }; - let selection = state.selection.selected(doc.id); - let drawable = drawable_of(resource, selection)?; - let lod = state.preview_scene.lod; - kept_box((doc.id, doc.payload_epoch(), selection, lod), || { - let geometries = drawn_level(drawable, lod).flat_map(|model| model.geometries.iter()); - let read = (geometries.flatten()).filter_map(|geometry| geometry.positions.as_ref().ok()); - bounds_of(read.flatten()) - }) +/// Cached bounding box of the last measured GTA VI drawable, owned by [`super::RenderBridge`]. +#[derive(Default)] +pub(crate) struct ShadedCache { + kept: Option<(Measured, Option<(glam::Vec3, glam::Vec3)>)>, +} + +impl ShadedCache { + /// The box the geometries of the active GTA VI drawable's drawn level fill, from its least + /// corner to its greatest; `None` where the document shows none, or none of them reads. + pub(crate) fn bounds(&mut self, state: &AppState) -> Option<(glam::Vec3, glam::Vec3)> { + let doc = state.active_document()?; + let DocPayload::Gta6Drawable(resource) = &doc.payload else { + return None; + }; + let selection = state.selection.selected(doc.id); + let drawable = drawable_of(resource, selection)?; + let lod = state.preview_scene.lod; + self.kept_box((doc.id, doc.payload_epoch(), selection, lod), || { + let geometries = drawn_level(drawable, lod).flat_map(|model| model.geometries.iter()); + let read = + (geometries.flatten()).filter_map(|geometry| geometry.positions.as_ref().ok()); + bounds_of(read.flatten()) + }) + } + + /// The box kept for `of`, else the one `measure` gives, kept in its place: a frame asks again + /// with the same. + fn kept_box( + &mut self, + of: Measured, + measure: impl FnOnce() -> Option<(glam::Vec3, glam::Vec3)>, + ) -> Option<(glam::Vec3, glam::Vec3)> { + if let Some((_, held)) = self.kept.as_ref().filter(|(held, _)| *held == of) { + return *held; + } + let measured = measure(); + self.kept = Some((of, measured)); + measured + } } /// What a box was measured of: the document, what it held when it was read, the drawable picked @@ -118,23 +151,6 @@ type Measured = ( usize, ); -/// The box kept for `of`, else the one `measure` gives, kept in its place: a frame asks again -/// with the same. -fn kept_box( - of: Measured, - measure: impl FnOnce() -> Option<(glam::Vec3, glam::Vec3)>, -) -> Option<(glam::Vec3, glam::Vec3)> { - type Kept = (Measured, Option<(glam::Vec3, glam::Vec3)>); - static KEPT: std::sync::Mutex> = std::sync::Mutex::new(None); - let mut kept = KEPT.lock().unwrap_or_else(|p| p.into_inner()); - if let Some((_, held)) = kept.as_ref().filter(|(held, _)| *held == of) { - return *held; - } - let measured = measure(); - *kept = Some((of, measured)); - measured -} - /// The box `positions` fill; `None` where there is none. pub(super) fn bounds_of<'a>( positions: impl Iterator, @@ -201,6 +217,7 @@ fn surface(geometry: &Geometry) -> Option { /// parameter's +0x14 hash; the key of one a worker still decodes is added to `decoding`. fn material( state: &AppState, + session: &super::gta6_meshlets::MeshletSession, selection: Option, shader: &Shader, effect: String, @@ -236,7 +253,7 @@ fn material( continue; }; let stored = || super::gta6_maps::stored(state, selection, key); - match super::gta6_meshlets::decoded(key, stored) { + match session.decoded(key, stored) { Ok(Some(image)) => { material.textures.insert(name, Image::clone(&image)); } @@ -419,29 +436,29 @@ mod tests { #[test] fn a_box_measured_of_one_document_is_not_handed_to_the_next() { + let mut cache = ShadedCache::default(); let (first, second) = ( Some((glam::Vec3::ZERO, glam::Vec3::ONE)), Some((glam::Vec3::NEG_ONE, glam::Vec3::splat(4.0))), ); - // Documents no other test opens: the box is kept for the whole process. let (one, next) = ( crate::state::DocumentId(u64::MAX - 7), crate::state::DocumentId(u64::MAX - 6), ); - assert_eq!(kept_box((one, 0, None, 0), || first), first); + assert_eq!(cache.kept_box((one, 0, None, 0), || first), first); // Another document, though it may lie where the first did, is measured itself. - assert_eq!(kept_box((next, 0, None, 0), || second), second); + assert_eq!(cache.kept_box((next, 0, None, 0), || second), second); // And so is the same document read again, another drawable of it, and another level. - assert_eq!(kept_box((next, 1, None, 0), || first), first); + assert_eq!(cache.kept_box((next, 1, None, 0), || first), first); assert_eq!( - kept_box( + cache.kept_box( (next, 1, Some(crate::state::SelectionKey::Row(3)), 0), || second ), second ); assert_eq!( - kept_box( + cache.kept_box( (next, 1, Some(crate::state::SelectionKey::Row(3)), 2), || { None } ), diff --git a/src/render/gta6_terrain.rs b/src/render/gta6_terrain.rs index 5f4e6118..d39044a5 100644 --- a/src/render/gta6_terrain.rs +++ b/src/render/gta6_terrain.rs @@ -97,16 +97,19 @@ fn cell_layers(indices: Option<&Image>, weights: Option<&Image>, cell: u32) -> O Some(used.into_iter().map(|(layer, _)| layer).collect()) } +/// Cached 512×512 terrain layer slices keyed by the source image's address, owned by +/// [`super::RenderBridge`]. +#[derive(Default)] +pub(crate) struct TerrainCache { + kept: std::collections::HashMap, Arc)>, +} + /// `image` at [`LAYER_SIDE`] texels a side: its level of that size where it has one, else its -/// texels taken nearest. Kept by the image's place in memory, so a surface prepared again binds -/// the same. -fn layer_slice(image: &Arc) -> Arc { - type Kept = std::collections::HashMap, Arc)>; - static KEPT: std::sync::Mutex> = std::sync::Mutex::new(None); +/// texels taken nearest. Kept in `cache` by the image's place in memory, so a surface prepared +/// again binds the same. +fn layer_slice(cache: &mut TerrainCache, image: &Arc) -> Arc { let place = Arc::as_ptr(image) as usize; - let mut kept = KEPT.lock().unwrap_or_else(|p| p.into_inner()); - let kept = kept.get_or_insert_with(Default::default); - if let Some((_, slice)) = kept.get(&place) { + if let Some((_, slice)) = cache.kept.get(&place) { return Arc::clone(slice); } let side = LAYER_SIDE; @@ -139,7 +142,9 @@ fn layer_slice(image: &Arc) -> Arc { srgb: image.srgb, }); // The source is kept with its slice: no other image comes to lie where it does meanwhile. - kept.insert(place, (Arc::clone(image), Arc::clone(&slice))); + cache + .kept + .insert(place, (Arc::clone(image), Arc::clone(&slice))); slice } @@ -149,6 +154,7 @@ type Slices = Vec>>; /// The drawn cell's layers' textures, an array a kind, and each layer's three numbers: a slice's /// where its texture is held, else the default's, as the game numbers a layer not streamed in. fn layer_arrays( + cache: &mut TerrainCache, tile: &Tile, used: &[usize], found: &mut dyn FnMut(u64) -> Option>, @@ -166,7 +172,7 @@ fn layer_arrays( let Some(image) = found(textures.keys[kind]).filter(|_| !full) else { continue; }; - let slice = layer_slice(&image); + let slice = layer_slice(cache, &image); // An array has one colour space, the first slice's: another stays at the default. if let Some(Some(first)) = array.first() { if first.srgb != slice.srgb { @@ -199,6 +205,7 @@ pub(super) fn reads_a_tile(pass: &Gta6ShadingPass) -> bool { // slices their records number; every other layer keeps the defaults, as the game numbers a layer // that has not streamed in. pub(super) fn fill( + cache: &mut TerrainCache, pass: &Gta6ShadingPass, tile: Option<&Tile>, map: &mut dyn FnMut(u64) -> Option>, @@ -244,7 +251,7 @@ pub(super) fn fill( // The layers the cell's pixels select; the masks' where the maps are not in yet. let used = cell_layers(slots[4].as_deref(), slots[3].as_deref(), tile.cell) .unwrap_or_else(|| tile.masked_layers()); - let (arrays, numbers) = layer_arrays(tile, &used, &mut found); + let (arrays, numbers) = layer_arrays(cache, tile, &used, &mut found); let layers: Vec = (tile.material.layers.iter().zip(&numbers)) .flat_map(|(params, numbers)| terrain::tile_layer(*params, *numbers).words()) .collect(); @@ -358,15 +365,16 @@ mod tests { #[test] fn a_stage_that_reads_the_cells_of_a_model_with_no_tile_is_refused_and_another_keeps_the_defaults( ) { + let mut cache = TerrainCache::default(); let mut map = |_: u64| -> Option> { None }; let mut out = BTreeMap::new(); let cells = pass(vec![fed(2, Terrain::Cells, Some(4))]); assert_eq!( - fill(&cells, None, &mut map, &mut out), + fill(&mut cache, &cells, None, &mut map, &mut out), Err(terrain::no_tile()) ); let record = pass(vec![fed(0, Terrain::Record, Some(372))]); - assert_eq!(fill(&record, None, &mut map, &mut out), Ok(())); + assert_eq!(fill(&mut cache, &record, None, &mut map, &mut out), Ok(())); assert!( out.is_empty(), "the defaults are what the binder's feeds give" diff --git a/src/render/gta6_trace.rs b/src/render/gta6_trace.rs index 0c7d6ce6..0b534782 100644 --- a/src/render/gta6_trace.rs +++ b/src/render/gta6_trace.rs @@ -17,9 +17,9 @@ type Slot = Arc, String>>>>; /// and the level drawn. type Of = (DocumentId, u64, Option, usize); -/// What the traced writer is made of so far, across frames. +/// What the traced writer is made of so far, across frames, owned by [`super::RenderBridge`]. #[derive(Default)] -struct Glue { +pub(crate) struct TraceState { /// The walk file the aid names, empty for those `OPENRAGE_RDNA_WALKS` lists, whether its test /// of a node asks the device's query, and its walk. asked: Option<(String, bool)>, @@ -34,8 +34,6 @@ struct Glue { line: Option, } -static GLUE: Mutex> = Mutex::new(None); - /// `work` run on the trace's worker, off the frame. fn start( work: impl FnOnce() -> Result + Send + 'static, @@ -145,7 +143,7 @@ fn body(queried: bool) -> String { } } -impl Glue { +impl TraceState { /// Where the traced writer stands this frame, with what it lacks started on the worker. fn advance( &mut self, @@ -256,35 +254,32 @@ impl Glue { | or_renderer::game_shaders::meshlets::TracedState::Building => building(), } } -} - -/// Advance the traced writer of the sun's mask for this frame of `scene`, where the aid asks for -/// it: whether what the Shaded line says of it changed. -pub(crate) fn refresh( - (device, queue): (&wgpu::Device, &wgpu::Queue), - scene: Option<&MeshletScene>, - state: &AppState, -) -> bool { - let mut held = GLUE.lock().unwrap_or_else(PoisonError::into_inner); - let Some(asked) = trace::traced_aid() else { - return false; - }; - let glue = held.get_or_insert_with(Glue::default); - let line = glue.advance((device, queue), scene, state, asked); - if glue.line.as_ref() == Some(&line) { - return false; + /// Advance the traced writer of the sun's mask for this frame of `scene`, where the aid asks for + /// it: whether what the Shaded line says of it changed. + pub(crate) fn refresh( + &mut self, + (device, queue): (&wgpu::Device, &wgpu::Queue), + scene: Option<&MeshletScene>, + state: &AppState, + ) -> bool { + let Some(asked) = trace::traced_aid() else { + return false; + }; + let line = self.advance((device, queue), scene, state, asked); + if self.line.as_ref() == Some(&line) { + return false; + } + tracing::info!(said = %line, "the sun's mask of a GTA VI model"); + self.line = Some(line); + true } - tracing::info!(said = %line, "the sun's mask of a GTA VI model"); - glue.line = Some(line); - true -} -/// `said` with what the traced writer says of the sun's mask, where the aid asks for one. -pub(crate) fn said(said: String) -> String { - let held = GLUE.lock().unwrap_or_else(PoisonError::into_inner); - match held.as_ref().and_then(|glue| glue.line.as_ref()) { - Some(line) => format!("{said}\n{line}"), - None => said, + /// `said` with what the traced writer says of the sun's mask, where the aid asks for one. + pub(crate) fn said(&self, said: String) -> String { + match self.line.as_ref() { + Some(line) => format!("{said}\n{line}"), + None => said, + } } } diff --git a/src/render/lines.rs b/src/render/lines.rs index 579bf0db..dfb3e645 100644 --- a/src/render/lines.rs +++ b/src/render/lines.rs @@ -138,6 +138,7 @@ pub fn build_lines_for_active_document(state: &AppState) -> Vec { doc, selection: state.selection.selected(doc.id), entry: None, + beside: None, }; capabilities::for_payload(&doc.payload) .and_then(|row| row.lines) diff --git a/src/render/meshes.rs b/src/render/meshes.rs index 61b867e8..311dc717 100644 --- a/src/render/meshes.rs +++ b/src/render/meshes.rs @@ -93,7 +93,15 @@ impl MeshUpload { } } +#[cfg(test)] pub fn build_meshes_for_active_document(state: &AppState) -> Vec { + build_meshes_for_active_document_with(state, None) +} + +pub(crate) fn build_meshes_for_active_document_with( + state: &AppState, + beside: Option<&[crate::state::gta6_weapon_parts::Part]>, +) -> Vec { if state.active_workspace == crate::state::Workspace::Animation { // A GTA VI animation draws the drawable picked for it, posed where it binds. if state.active_document().map(|d| d.kind()) == Some(crate::state::DocumentKind::Gta6Anim) { @@ -106,6 +114,7 @@ pub fn build_meshes_for_active_document(state: &AppState) -> Vec { doc, selection: state.selection.selected(doc.id), entry: None, + beside, }; return crate::render::gta6_drawable::meshes(&request); } @@ -119,6 +128,7 @@ pub fn build_meshes_for_active_document(state: &AppState) -> Vec { doc, selection: state.selection.selected(doc.id), entry: None, + beside, }; capabilities::for_payload(&doc.payload) .and_then(|row| row.meshes) @@ -451,6 +461,7 @@ fn extend_from_mesh_source( doc, selection: None, entry, + beside: None, }; if let Some(build) = capabilities::for_payload(&doc.payload).and_then(|row| row.scene_meshes) { let source = Some(MeshSource { diff --git a/src/render/mod.rs b/src/render/mod.rs index 2afc989a..59069f23 100644 --- a/src/render/mod.rs +++ b/src/render/mod.rs @@ -12,6 +12,7 @@ pub(crate) mod gta6_instances; pub(crate) mod gta6_layers; pub(crate) mod gta6_maps; pub(crate) mod gta6_meshlets; +pub(crate) mod gta6_overrides; pub(crate) mod gta6_paint; pub(crate) mod gta6_ped; pub(crate) mod gta6_ped_pose; diff --git a/src/render/thumbnails.rs b/src/render/thumbnails.rs index d393ff16..27654fe1 100644 --- a/src/render/thumbnails.rs +++ b/src/render/thumbnails.rs @@ -342,6 +342,15 @@ pub fn geometry_for( state: &crate::state::AppState, doc: &crate::state::Document, selection: crate::state::SelectionKey, +) -> Vec { + geometry_for_with(state, doc, selection, None) +} + +pub(crate) fn geometry_for_with( + state: &crate::state::AppState, + doc: &crate::state::Document, + selection: crate::state::SelectionKey, + beside: Option<&[crate::state::gta6_weapon_parts::Part]>, ) -> Vec { use crate::state::capabilities::{self, GeometryRequest}; @@ -350,6 +359,7 @@ pub fn geometry_for( doc, selection: Some(selection), entry: None, + beside, }; capabilities::for_payload(&doc.payload) .and_then(|row| row.meshes) diff --git a/src/render/viewport/day.rs b/src/render/viewport/day.rs index b124864a..28726d99 100644 --- a/src/render/viewport/day.rs +++ b/src/render/viewport/day.rs @@ -113,14 +113,6 @@ fn gta6_sky( sky } -/// Whether a model is lit as in a studio from now on: a run that photographs models alone. -static STUDIO: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - -/// Light every GTA VI model drawn from now on as in a studio, [`studio`]. -pub(crate) fn light_as_a_studio() { - STUDIO.store(true, std::sync::atomic::Ordering::Relaxed); -} - /// The share of the open sky's light a studio leaves all around a model. const STUDIO_AROUND: f32 = 0.4; /// The least and the most stops a studio's frame is exposed by. The game's meter counts the lit @@ -161,29 +153,31 @@ fn exposure_times(exposure: f32) -> f32 { /// The sky an install's cycles gave last, and the tables, the hour and the weather it was /// worked out for: a frame asks again with the same, and the air is not marched through again. -type Kept = ( - usize, - u32, - WeatherState, - Option, -); -static KEPT: std::sync::Mutex> = std::sync::Mutex::new(None); +#[derive(Default)] +pub(super) struct Gta6SkyCache { + kept: Option<( + usize, + u32, + WeatherState, + Option, + )>, +} /// The sky the install's cycles state at `hour` in `weather`, exposed as the drivers say. fn sky_by_cycles( + cache: &mut Gta6SkyCache, tables: &Arc, hour: f32, weather: WeatherState, exposure: f32, ) -> Option { let key = (Arc::as_ptr(tables) as usize, hour.to_bits(), weather); - let mut kept = KEPT.lock().unwrap_or_else(|p| p.into_inner()); - let held = (kept.as_ref()) + let held = (cache.kept.as_ref()) .filter(|(of, at, in_weather, _)| (*of, *at, *in_weather) == key) .map(|(.., sky)| *sky); let sky = held.unwrap_or_else(|| { let sky = super::gta6_day::sky(tables, hour, weather); - *kept = Some((key.0, key.1, key.2, sky)); + cache.kept = Some((key.0, key.1, key.2, sky)); sky }); sky.map(|sky| or_renderer::game_shaders::meshlets::Sky { @@ -254,13 +248,20 @@ impl RenderBridge { let days = state.drivers.time_of_day.days; let exposure = state.drivers.exposure.value; let tables = crate::state::gta6_shaders::timecycle::timecycle(state); - let by_cycles = - (tables.as_ref()).and_then(|tables| sky_by_cycles(tables, hour, weather, exposure)); + let by_cycles = (tables.as_ref()).and_then(|tables| { + sky_by_cycles( + &mut self.game_scene.gta6_sky_cache, + tables, + hour, + weather, + exposure, + ) + }); let mut sky = by_cycles.unwrap_or_else(|| gta6_sky(hour, weather, exposure)); - sky.scene.bounds = crate::render::gta6_shaded::bounds(state); + sky.scene.bounds = self.gta6.shaded_cache.bounds(state); sky.scene.laid = (state.drivers.world_background.ground) .then_some(glam::Vec3::splat(super::gta6_day::GROUND)); - if STUDIO.load(std::sync::atomic::Ordering::Relaxed) { + if self.gta6.overrides.studio { studio(&mut sky); } self.renderer.set_gta6_sky(sky); diff --git a/src/render/viewport/framing.rs b/src/render/viewport/framing.rs index 8b2e5d63..49bb9a25 100644 --- a/src/render/viewport/framing.rs +++ b/src/render/viewport/framing.rs @@ -6,21 +6,33 @@ use crate::state::selection_lookup::{ }; use crate::state::{AppState, DictPart, DocPayload, SelectionKey}; +#[cfg(test)] pub fn compute_active_doc_bounds(state: &AppState) -> Option<(Vec3, f32)> { + compute_active_doc_bounds_with(state, None) +} + +pub(crate) fn compute_active_doc_bounds_with( + state: &AppState, + beside: Option<&[crate::state::gta6_weapon_parts::Part]>, +) -> Option<(Vec3, f32)> { let doc = state.active_document()?; let request = crate::state::capabilities::GeometryRequest { state, doc, selection: state.selection.selected(doc.id), entry: None, + beside, }; let row = crate::state::capabilities::for_payload(&doc.payload)?; (row.bounds?)(&request) } /// What Frame selection frames: the selected model or geometry, else what Frame all frames. -pub fn compute_selection_bounds(state: &AppState) -> Option<(Vec3, f32)> { - selected_part_sphere(state).or_else(|| compute_active_doc_bounds(state)) +pub(crate) fn compute_selection_bounds_with( + state: &AppState, + beside: Option<&[crate::state::gta6_weapon_parts::Part]>, +) -> Option<(Vec3, f32)> { + selected_part_sphere(state).or_else(|| compute_active_doc_bounds_with(state, beside)) } /// The model or geometry the active selection names, by the box its model ships for it. diff --git a/src/render/viewport/game_shaders.rs b/src/render/viewport/game_shaders.rs index 8c1bbbf1..3e94d71e 100644 --- a/src/render/viewport/game_shaders.rs +++ b/src/render/viewport/game_shaders.rs @@ -6,7 +6,9 @@ use or_renderer::game_shaders::mesh::{Material, MeshScene, Surface}; use or_renderer::game_shaders::pack::GamePack; use or_renderer::ShadingMode; +use super::state::Gta6MeshletState; use super::{MeshCacheKey, RenderBridge}; +use crate::render::gta6_overrides::{Gta6DrawOverrides, Gta6OverridesGuard, Gta6StudioGuard}; use crate::state::AppState; /// What the surfaces of the open drawable came to when prepared for the game's own passes. @@ -84,6 +86,73 @@ impl RenderBridge { } } + /// Explicit per-draw GTA VI rendering overrides (paint, finishes, beside parts, pose, hair, + /// skin preset, studio lighting). + pub(crate) fn gta6_overrides(&self) -> &Gta6DrawOverrides { + &self.gta6.overrides + } + + /// Mutable access to per-draw GTA VI rendering overrides. + pub(crate) fn gta6_overrides_mut(&mut self) -> &mut Gta6DrawOverrides { + &mut self.gta6.overrides + } + + /// Reset all per-draw GTA VI rendering overrides back to their defaults. + pub(crate) fn reset_gta6_overrides(&mut self) { + self.gta6.overrides.clear(); + } + + /// Acquire a scoped guard that resets all per-draw GTA VI overrides on drop. + pub(crate) fn scoped_gta6_overrides(&mut self) -> Gta6OverridesGuard<'_> { + Gta6OverridesGuard::new(self) + } + + /// Acquire a scoped guard that enables studio lighting and restores its prior value on drop. + pub(crate) fn scoped_gta6_studio(&mut self) -> Gta6StudioGuard<'_> { + Gta6StudioGuard::new(self) + } + + /// Whether the active GTA VI drawable still awaits translation of any shader program. + pub(crate) fn awaits_gta6_programs(&self) -> bool { + self.gta6.session.awaits_programs() + } + + /// Whether the active GTA VI scene still awaits deferred lighting/tone-mapping passes. + pub(crate) fn awaits_gta6_light(&self) -> bool { + self.gta6.frame_light.awaits() + } + + /// Start background texture decoding for the active GTA VI drawable and its current `beside` + /// override parts. + pub(crate) fn start_decoding_gta6(&self, state: &AppState) { + crate::render::gta6_meshlets::start_decoding( + state, + &self.gta6.session, + self.gta6.overrides.beside(), + ); + } + + /// Start background texture decoding for the active GTA VI drawable alone (without any current + /// `beside` override parts), used when prefetching upcoming documents. + pub(crate) fn start_decoding_gta6_alone(&self, state: &AppState) { + crate::render::gta6_meshlets::start_decoding(state, &self.gta6.session, None); + } + + /// Record that the graphics device was lost while GTA VI's own passes were drawing. + pub(crate) fn gta6_device_lost(&mut self) { + self.gta6.session.device_lost(); + } + + /// Take the set of GTA VI effects that suffered a device loss on this bridge. + pub(crate) fn take_gta6_lost_effects(&mut self) -> std::collections::BTreeSet { + self.gta6.session.take_lost_effects() + } + + /// Seed this bridge with GTA VI effects that suffered a device loss on an earlier bridge. + pub(crate) fn carry_gta6_lost_effects(&mut self, lost: std::collections::BTreeSet) { + self.gta6.session.carry_lost_effects(lost); + } + /// What the last frame of the active GTA VI drawable's own passes asked of the device; none where they draw nothing. pub fn model_cost(&self) -> Option { let scene = self.renderer.gta6_scene().filter(|s| s.drawn() > 0)?; @@ -379,7 +448,7 @@ impl RenderBridge { }) }; gta6_shaders::request( - &crate::render::gta6_meshlets::worn(state), + &crate::render::gta6_meshlets::worn(state, self.gta6.overrides.beside()), install, self.gta6.hardware_adapter, ); @@ -387,7 +456,7 @@ impl RenderBridge { tracing::info!(%doc, "Shaded was asked for a GTA VI drawable"); self.gta6.since = Some((doc, std::time::Instant::now(), false, false)); self.gta6.maps = Default::default(); - crate::render::gta6_meshlets::start_decoding(state); + self.start_decoding_gta6(state); } let running = gta6_shaders::running(); let pack = gta6_shaders::pack(); @@ -395,9 +464,8 @@ impl RenderBridge { // A map learnt or decoded since the scene was bound is bound where it is read self.take_on_gta6_maps(state, key); // The pack's passes drew without maps a worker decoded: prepared again once all are in - let fallen = &mut self.gta6.fallback; - if !fallen.is_empty() && crate::render::gta6_meshlets::all_in(fallen) { - fallen.clear(); + if !self.gta6.fallback.is_empty() && self.gta6.session.all_in(&self.gta6.fallback) { + self.gta6.fallback.clear(); self.game_scene.key = None; } let fresh = self.game_scene.key != Some(key); @@ -405,8 +473,11 @@ impl RenderBridge { let was = report.and_then(|r| r.gta6.as_ref()).map(|(was, _)| *was); let building = self.gta6.building.is_some(); let devices = (&*self.device, &*self.queue); - let traced = crate::render::gta6_trace::refresh(devices, self.renderer.gta6_scene(), state); - let lighting = crate::render::gta6_frame_light::refresh( + let traced = self + .gta6 + .trace + .refresh(devices, self.renderer.gta6_scene(), state); + let lighting = self.gta6.frame_light.refresh( devices, self.renderer.gta6_scene(), install, @@ -420,9 +491,17 @@ impl RenderBridge { .map(|r| (r.drawn, r.left_out.clone())); let (drawn, left_out) = match kept { // A worker was building a pass of its own programs: once it has, they draw it - Some(kept) if building => { - self.ask_again(|| crate::render::gta6_meshlets::meshlets(state), kept) - } + Some(kept) if building => self.ask_again( + |gta6| { + crate::render::gta6_meshlets::meshlets( + state, + &mut gta6.session, + >a6.overrides, + &mut gta6.terrain_cache, + ) + }, + kept, + ), Some(kept) => kept, None => { self.gta6.building = None; @@ -439,7 +518,11 @@ impl RenderBridge { (_, Some((_, pack))) => { let draws = |effect: &str| crate::render::gta6_shaded::pack_draws(pack, effect); - crate::render::gta6_shaded::shaded_surfaces(state, &draws) + crate::render::gta6_shaded::shaded_surfaces( + state, + &self.gta6.session, + &draws, + ) } }; match (&pack, fallback) { @@ -470,7 +553,7 @@ impl RenderBridge { // When a brand-new scene was just prepared and `light_every_kind` is on, bind the cached // lighting passes immediately on the same tick without waiting for another frame. if self.renderer.gta6_scene().is_some_and(|s| !s.lit_by_game()) { - let _ = crate::render::gta6_frame_light::refresh( + let _ = self.gta6.frame_light.refresh( (&*self.device, &*self.queue), self.renderer.gta6_scene(), install, @@ -485,8 +568,8 @@ impl RenderBridge { let by_cycles = crate::state::gta6_shaders::timecycle::timecycle(state) .is_some_and(|tables| super::gta6_day::lights(&tables, state.drivers.weather.state)); let said = crate::render::gta6_shaded::said_of_own(said, self.gta6.own.as_ref(), by_cycles); - let said = crate::render::gta6_trace::said(said); - let said = crate::render::gta6_frame_light::said(said); + let said = self.gta6.trace.said(said); + let said = self.gta6.frame_light.said(said); self.game_scene.report = Some(GameSceneReport { drawn, left_out, @@ -498,7 +581,9 @@ impl RenderBridge { /// builds for one any more: what the pack's passes draw of it, `kept` where its own draw none. fn ask_again( &mut self, - read: impl FnOnce() -> Option>, + read: impl FnOnce( + &mut Gta6MeshletState, + ) -> Option>, kept: (usize, Vec<(String, String)>), ) -> (usize, Vec<(String, String)>) { let drew = matches!(self.gta6.own, Some(Ok(_))); @@ -525,13 +610,22 @@ impl RenderBridge { &mut self, state: &AppState, ) -> Option> { - self.prepare_gta6_meshlets_of(|| crate::render::gta6_meshlets::meshlets(state)) + self.prepare_gta6_meshlets_of(|gta6| { + crate::render::gta6_meshlets::meshlets( + state, + &mut gta6.session, + >a6.overrides, + &mut gta6.terrain_cache, + ) + }) } /// [`Self::prepare_gta6_meshlets`] of the drawable `read` gives where no worker builds for one. pub(super) fn prepare_gta6_meshlets_of( &mut self, - read: impl FnOnce() -> Option>, + read: impl FnOnce( + &mut Gta6MeshletState, + ) -> Option>, ) -> Option> { use or_renderer::game_shaders::meshlets::MeshletScene; // The drawable a worker builds for is the one asked about again, as it was read then @@ -541,7 +635,7 @@ impl RenderBridge { self.renderer.set_gta6_scene(None); // A map decoded from here on is bound by a later frame self.gta6.maps.seen = crate::render::gta6_maps::arrived(); - match read()? { + match read(&mut self.gta6)? { Ok(meshlets) => meshlets, Err(why) => return Some(Err(why)), } @@ -608,8 +702,8 @@ impl RenderBridge { return Some(Err(building.to_string())); } (Ok(Some(mut scene)), None) => { - if let Some(hair) = crate::render::gta6_hair::active() { - scene.set_hair(&self.device, &hair); + if let Some(hair) = self.gta6.overrides.hair.as_deref() { + scene.set_hair(&self.device, hair); } // A surface the device has no pass for, or none yet, is drawn as Material beside // the others diff --git a/src/render/viewport/gta6_ahead_tests.rs b/src/render/viewport/gta6_ahead_tests.rs index 61cd01df..69676d7e 100644 --- a/src/render/viewport/gta6_ahead_tests.rs +++ b/src/render/viewport/gta6_ahead_tests.rs @@ -146,7 +146,7 @@ fn a_drawable_some_passes_drew_and_none_can_once_all_are_built_ends_as_one_they_ bridge .renderer .set_meshes(vec![mesh(&device, held), mesh(&device, ahead)]); - let read = || { + let read = |_: &mut Gta6MeshletState| { Some(Ok(Meshlets { surfaces: surfaces.to_vec(), of: vec![(0, "held".to_string()), (1, "ahead".to_string())], diff --git a/src/render/viewport/gta6_late_maps.rs b/src/render/viewport/gta6_late_maps.rs index 58f55342..1b6d7d8a 100644 --- a/src/render/viewport/gta6_late_maps.rs +++ b/src/render/viewport/gta6_late_maps.rs @@ -45,7 +45,12 @@ impl RenderBridge { }; // A map decoded from here on is taken on by a later frame. self.gta6.maps.seen = now; - let read = crate::render::gta6_meshlets::meshlets(state); + let read = crate::render::gta6_meshlets::meshlets( + state, + &mut self.gta6.session, + &self.gta6.overrides, + &mut self.gta6.terrain_cache, + ); let validation = self.device.push_error_scope(wgpu::ErrorFilter::Validation); let rebound = match &read { Some(Ok(meshlets)) => scene.rebind(&self.device, &self.queue, &meshlets.surfaces), diff --git a/src/render/viewport/gta6_late_maps_tests.rs b/src/render/viewport/gta6_late_maps_tests.rs index e9b680a7..ecddc8c9 100644 --- a/src/render/viewport/gta6_late_maps_tests.rs +++ b/src/render/viewport/gta6_late_maps_tests.rs @@ -69,7 +69,7 @@ fn a_surface_whose_pass_is_built_draws_by_it_while_its_map_is_still_decoded() { two_sided: false, forward: None, }; - let read = || { + let read = |_: &mut super::super::state::Gta6MeshletState| { Some(Ok(Meshlets { surfaces: vec![surface.clone()], of: vec![(0, "decoding".to_string())], diff --git a/src/render/viewport/material_maps.rs b/src/render/viewport/material_maps.rs index ff2dc49b..bfd0d595 100644 --- a/src/render/viewport/material_maps.rs +++ b/src/render/viewport/material_maps.rs @@ -77,76 +77,83 @@ pub(super) fn in_pack( }) } -/// The map of `map`, read `bump` (linear) or as colour: `Err` while a worker reads it, which is -/// started the first time it is asked for; `Ok(None)` where it will not read or decode. -pub(super) fn prepared(map: PackMap, bump: bool) -> Result>, ()> { - prepared_with( - (map.stamp, bump), - move || { - let texture = map.pack.texture(map.index).ok()?; - let texture = - crate::state::textures::Texture::Owned(std::borrow::Cow::Borrowed(&*texture)); - super::texture_upload::prepare(&texture, bump) - }, - run, - ) +/// Decoded Material-view texture-pack maps cached for a [`super::RenderBridge`]. +#[derive(Default)] +pub(super) struct MaterialMapsCache { + kept: HashMap<(u64, bool), Slot>, } -/// The maps asked for this session, by what each is read from and whether it is read as a normal map. -static KEPT: Mutex>> = Mutex::new(None); - -/// [`prepared`] of the map kept as `key`, made by `make` on a worker `spawn` runs it on. -fn prepared_with( - key: (u64, bool), - make: impl FnOnce() -> Option + Send + 'static, - spawn: impl FnOnce(Box), -) -> Result>, ()> { - let mut guard = KEPT.lock().unwrap_or_else(|p| p.into_inner()); - let kept = guard.get_or_insert_with(HashMap::new); - if let Some(slot) = kept.get(&key) { - return slot - .lock() - .unwrap_or_else(|p| p.into_inner()) - .clone() - .ok_or(()); +impl MaterialMapsCache { + /// The map of `map`, read `bump` (linear) or as colour: `Err` while a worker reads it, which is + /// started the first time it is asked for; `Ok(None)` where it will not read or decode. + pub(super) fn prepared( + &mut self, + map: PackMap, + bump: bool, + ) -> Result>, ()> { + self.prepared_with( + (map.stamp, bump), + move || { + let texture = map.pack.texture(map.index).ok()?; + let texture = + crate::state::textures::Texture::Owned(std::borrow::Cow::Borrowed(&*texture)); + super::texture_upload::prepare(&texture, bump) + }, + run, + ) } - let bytes = |slot: &Slot| match &*slot.lock().unwrap_or_else(|p| p.into_inner()) { - Some(Some(map)) => map.rgba.len(), - _ => 0, - }; - // ponytail: past the cap every map is let go at once; the least lately used when a session - // that opens many models shows the read again. - if kept.values().map(bytes).sum::() > KEPT_BYTES { - kept.clear(); - } - let slot = Slot::default(); - kept.insert(key, Arc::clone(&slot)); - drop(guard); - spawn(Box::new(move || { - struct Settle(Slot); - impl Drop for Settle { - fn drop(&mut self) { - let mut guard = self.0.lock().unwrap_or_else(|p| p.into_inner()); - if guard.is_none() { - *guard = Some(None); + + /// [`Self::prepared`] of the map kept as `key`, made by `make` on a worker `spawn` runs it on. + fn prepared_with( + &mut self, + key: (u64, bool), + make: impl FnOnce() -> Option + Send + 'static, + spawn: impl FnOnce(Box), + ) -> Result>, ()> { + if let Some(slot) = self.kept.get(&key) { + return slot + .lock() + .unwrap_or_else(|p| p.into_inner()) + .clone() + .ok_or(()); + } + let bytes = |slot: &Slot| match &*slot.lock().unwrap_or_else(|p| p.into_inner()) { + Some(Some(map)) => map.rgba.len(), + _ => 0, + }; + // ponytail: past the cap every map is let go at once; the least lately used when a session + // that opens many models shows the read again. + if self.kept.values().map(bytes).sum::() > KEPT_BYTES { + self.kept.clear(); + } + let slot = Slot::default(); + self.kept.insert(key, Arc::clone(&slot)); + spawn(Box::new(move || { + struct Settle(Slot); + impl Drop for Settle { + fn drop(&mut self) { + let mut guard = self.0.lock().unwrap_or_else(|p| p.into_inner()); + if guard.is_none() { + *guard = Some(None); + } } } - } - let guard = Settle(slot); - let map = make().map(Arc::new); - *guard.0.lock().unwrap_or_else(|p| p.into_inner()) = Some(map); - })); - Err(()) -} + let guard = Settle(slot); + let map = make().map(Arc::new); + *guard.0.lock().unwrap_or_else(|p| p.into_inner()) = Some(map); + })); + Err(()) + } -/// Whether no worker still reads the map kept as any of `reads`; none is started. -pub(super) fn all_in(reads: &[(u64, bool)]) -> bool { - let kept = KEPT.lock().unwrap_or_else(|p| p.into_inner()); - // A map let go past the cap is in: a build asks for it again. - let read = |read| kept.as_ref()?.get(read).cloned(); - (reads.iter()).all(|r| { - read(r).is_none_or(|slot| slot.lock().unwrap_or_else(|p| p.into_inner()).is_some()) - }) + /// Whether no worker still reads the map kept as any of `reads`; none is started. + pub(super) fn all_in(&self, reads: &[(u64, bool)]) -> bool { + // A map let go past the cap is in: a build asks for it again. + reads.iter().all(|r| { + self.kept + .get(r) + .is_none_or(|slot| slot.lock().unwrap_or_else(|p| p.into_inner()).is_some()) + }) + } } /// Have a worker of the bounded pool run `task`; with none to take it, it runs here. @@ -182,27 +189,30 @@ mod tests { #[test] fn a_map_is_made_once_off_the_asking_thread_and_waited_for_until_it_is_in() { + let mut cache = MaterialMapsCache::default(); let key = (0x5EED_0001, false); let mut held = None; - let asked = prepared_with(key, map, |task| held = Some(task)); + let asked = cache.prepared_with(key, map, |task| held = Some(task)); assert!(asked.is_err(), "nothing is made on the asking thread"); let spawned = |_: Box| panic!("a map asked for again is not made again"); assert!( - prepared_with(key, map, spawned).is_err(), + cache.prepared_with(key, map, spawned).is_err(), "still being made" ); held.expect("the map was handed to a worker")(); - let made = prepared_with(key, map, spawned).expect("the map is in"); + let made = cache + .prepared_with(key, map, spawned) + .expect("the map is in"); assert_eq!(made.expect("it decoded").rgba, [1, 2, 3, 4]); // Read as a normal map, the same texture is another upload. let mut other = false; - let _ = prepared_with((key.0, true), map, |_| other = true); + let _ = cache.prepared_with((key.0, true), map, |_| other = true); assert!(other); assert!( - !all_in(&[key, (key.0, true)]), + !cache.all_in(&[key, (key.0, true)]), "the normal map is still being made" ); - assert!(all_in(&[key])); + assert!(cache.all_in(&[key])); } } diff --git a/src/render/viewport/mod.rs b/src/render/viewport/mod.rs index fc79bdb9..ccc420a1 100644 --- a/src/render/viewport/mod.rs +++ b/src/render/viewport/mod.rs @@ -5,7 +5,7 @@ use or_renderer::{MeshDraw, OrbitCamera, ShadingMode, ViewportRenderer}; use wgpu::util::DeviceExt; use crate::render::lines::{build_axes, build_grid, document_lines}; -use crate::render::meshes::{build_meshes_for_active_document, MeshUpload}; +use crate::render::meshes::{build_meshes_for_active_document_with, MeshUpload}; use crate::state::{AppState, DocPayload, DocumentId, MeshSource}; pub(crate) mod bones; @@ -36,9 +36,11 @@ use state::{ ParticleGpuCache, PhotoCaptureState, }; -pub(crate) use day::light_as_a_studio; -pub(crate) use framing::bound_rows; -pub use framing::{compute_active_doc_bounds, compute_selection_bounds}; +#[cfg(test)] +pub use framing::compute_active_doc_bounds; +pub(crate) use framing::{ + bound_rows, compute_active_doc_bounds_with, compute_selection_bounds_with, +}; pub use game_shaders::GameSceneReport; pub(crate) use photo::lay_shadow; pub(crate) use posing::pose_uploads; @@ -541,13 +543,17 @@ impl RenderBridge { let key = MeshCacheKey::of(state, doc_id, 0); let maps_in = with_textures && !self.doc_cache.maps_waiting.is_empty() - && material_maps::all_in(&self.doc_cache.maps_waiting); + && self + .doc_cache + .material_maps + .all_in(&self.doc_cache.maps_waiting); if with_textures && self.doc_cache.mesh_key == Some(key) && !maps_in { return; } self.dressed.key = None; - let mut uploads = build_meshes_for_active_document(state); + let mut uploads = + build_meshes_for_active_document_with(state, self.gta6.overrides.beside()); // ⚠ **Here and nowhere else.** A palette is an index into the // skeleton it was authored against, and the cache key hashes the // skeleton source — so this runs once per pairing, before any pose is @@ -634,7 +640,9 @@ impl RenderBridge { } pub fn end_frame(&mut self, encoder: &mut wgpu::CommandEncoder, state: &mut AppState) -> bool { - self.frame.camera = state.step_viewport_camera(self.frame.inputs).clone(); + self.frame.camera = state + .step_viewport_camera_with(self.frame.inputs, self.gta6.overrides.framed_beside()) + .clone(); self.doc_cache .gpu_textures .set_budget(state.prefs.gpu_texture_budget()); @@ -813,7 +821,7 @@ impl RenderBridge { let read = map.read(bump); // Past the build's share of uploads a map waits for the next build, a frame later. let spent = self.doc_cache.maps_uploaded > material_maps::UPLOAD_BYTES; - let prepared = match material_maps::prepared(map, bump) { + let prepared = match self.doc_cache.material_maps.prepared(map, bump) { Ok(prepared) if !spent => prepared?, _ => { self.doc_cache.maps_waiting.push(read); @@ -910,6 +918,7 @@ pub(crate) fn selected_dictionary_entry(state: &AppState, doc_id: DocumentId) -> mod tests { use super::*; use crate::render::lines::build_lines_for_active_document; + use crate::render::meshes::build_meshes_for_active_document; use crate::state::{Document, SelectionKey}; #[test] diff --git a/src/render/viewport/photo.rs b/src/render/viewport/photo.rs index 50131226..355cb455 100644 --- a/src/render/viewport/photo.rs +++ b/src/render/viewport/photo.rs @@ -285,7 +285,9 @@ impl RenderBridge { self.begin_frame(); self.set_desired_size(px, px); self.frame.mode = ShadingMode::Shaded; - self.frame.camera = state.step_viewport_camera(self.frame.inputs).clone(); + self.frame.camera = state + .step_viewport_camera_with(self.frame.inputs, self.gta6.overrides.framed_beside()) + .clone(); self.renderer.resize(&self.device, px, px); self.refresh_day(state); self.refresh_key_light(state); diff --git a/src/render/viewport/state.rs b/src/render/viewport/state.rs index bd0eae9a..64a1456a 100644 --- a/src/render/viewport/state.rs +++ b/src/render/viewport/state.rs @@ -46,6 +46,8 @@ pub(super) struct DocumentMeshCache { /// The `skin_revision` of the pose `mesh_uploads` hold. pub skinned_revision: Option, pub gpu_textures: crate::render::gpu_budget::GpuTextures>, + /// Decoded Material-view texture-pack maps cached for this bridge. + pub material_maps: super::material_maps::MaterialMapsCache, /// The maps of open packs a worker still read when the meshes were last built without them. pub maps_waiting: Vec<(u64, bool)>, /// The bytes of those maps the build of the meshes uploaded so far. @@ -73,6 +75,7 @@ impl DocumentMeshCache { gpu_textures: crate::render::gpu_budget::GpuTextures::new( crate::state::DEFAULT_GPU_TEXTURE_MIB as usize * 1024 * 1024, ), + material_maps: super::material_maps::MaterialMapsCache::default(), maps_waiting: Vec::new(), maps_uploaded: 0, cache_doc: None, @@ -103,9 +106,11 @@ pub(super) struct GameSceneCache { pub day_key: Option<(usize, u32, u32, crate::state::drivers::WeatherState)>, /// What the day of a world drawn by the game's own programs was worked out for: the install's timecycle, the session's hour and its weather. pub world_day_key: Option<(usize, u32, u64)>, + /// Last GTA VI sky computed from the install's timecycle tables. + pub gta6_sky_cache: super::day::Gta6SkyCache, } -/// GTA VI meshlet async pipeline build, late-map binding, and fallback decode state. +/// GTA VI meshlet async pipeline build, late-map binding, session caches, and per-draw overrides. pub(crate) struct Gta6MeshletState { /// How the active GTA VI drawable's own mesh and pixel programs came out: the surfaces they /// draw and the bindings left at nought, or why it draws without them; `None` where they @@ -130,6 +135,18 @@ pub(crate) struct Gta6MeshletState { pub(super) maps: super::gta6_late_maps::LateMaps, /// Whether the graphics device sits on a hardware adapter rather than a software fallback. pub(crate) hardware_adapter: bool, + /// Explicit per-draw overrides (paint, finish, beside parts, ped pose, hair, skin preset, studio). + pub(crate) overrides: crate::render::gta6_overrides::Gta6DrawOverrides, + /// Per-bridge meshlet session state (awaited programs, device-lost effects, decoded textures). + pub(crate) session: crate::render::gta6_meshlets::MeshletSession, + /// Per-bridge GTA VI deferred lighting and tone-mapping pass state. + pub(crate) frame_light: crate::render::gta6_frame_light::FrameLightState, + /// Per-bridge GTA VI traced sun-mask state. + pub(crate) trace: crate::render::gta6_trace::TraceState, + /// Cached bounding box of the last measured GTA VI drawable. + pub(super) shaded_cache: crate::render::gta6_shaded::ShadedCache, + /// Cached 512×512 terrain layer slices keyed by source image address. + pub(super) terrain_cache: crate::render::gta6_terrain::TerrainCache, } impl Gta6MeshletState { @@ -143,6 +160,12 @@ impl Gta6MeshletState { since: None, maps: Default::default(), hardware_adapter: false, + overrides: Default::default(), + session: Default::default(), + frame_light: Default::default(), + trace: Default::default(), + shaded_cache: Default::default(), + terrain_cache: Default::default(), } } diff --git a/src/self_check/shots/lost_device.rs b/src/self_check/shots/lost_device.rs index c5c74cca..4fcd297b 100644 --- a/src/self_check/shots/lost_device.rs +++ b/src/self_check/shots/lost_device.rs @@ -46,7 +46,9 @@ impl Shell { if !self.bridge.device_lost() { return Ok(()); } - state.graphics_device_lost(self.bridge.mode()); + if state.graphics_device_lost(self.bridge.mode()) { + self.bridge.gta6_device_lost(); + } self.bridge.set_mode(ShadingMode::Material); Err(DEVICE_LOST.to_owned()) } diff --git a/src/state/capabilities.rs b/src/state/capabilities.rs index fee23480..a124c568 100644 --- a/src/state/capabilities.rs +++ b/src/state/capabilities.rs @@ -18,6 +18,8 @@ pub struct GeometryRequest<'a> { pub selection: Option, pub entry: Option, + + pub beside: Option<&'a [crate::state::gta6_weapon_parts::Part]>, } pub type InspectorFn = fn(&mut egui::Ui, &mut AppState, DocumentId, Option); @@ -1620,6 +1622,7 @@ mod tests { doc: &doc, selection: None, entry: None, + beside: None, }; let row = builtins().get(DocumentKind::Ybn).expect("a row"); @@ -1650,6 +1653,7 @@ mod tests { doc: &doc, selection: None, entry: None, + beside: None, }; let row = builtins().get(DocumentKind::Gxt2).expect("a row"); diff --git a/src/state/gta6/drawable/gta6_shaders/layer_index.rs b/src/state/gta6/drawable/gta6_shaders/layer_index.rs index 3d61e464..db587559 100644 --- a/src/state/gta6/drawable/gta6_shaders/layer_index.rs +++ b/src/state/gta6/drawable/gta6_shaders/layer_index.rs @@ -398,10 +398,13 @@ pub(crate) fn worn_as( /// The keys of the textures the layers of the active GTA VI drawable's material name, once the /// index that serves it is read; none for a drawable that wears no layered material. -pub(in crate::state) fn tile_keys(state: &crate::state::AppState) -> Vec { +pub(in crate::state) fn tile_keys( + state: &crate::state::AppState, + beside: Option<&[crate::state::gta6_weapon_parts::Part]>, +) -> Vec { // Each drawable the view draws wears its own: a weapon's parts in place of the weapon. let mut keys = Vec::new(); - crate::render::gta6_meshlets::each_shown(state, &mut |drawable, _, _| { + crate::render::gta6_meshlets::each_shown(state, beside, &mut |drawable, _, _| { let Some((index, material)) = worn_as(state, &drawable.name, false) else { return; }; diff --git a/src/state/gta6/drawable/gta6_shaders/mod.rs b/src/state/gta6/drawable/gta6_shaders/mod.rs index ecb8938e..966a7f4c 100644 --- a/src/state/gta6/drawable/gta6_shaders/mod.rs +++ b/src/state/gta6/drawable/gta6_shaders/mod.rs @@ -1041,20 +1041,18 @@ pub(in crate::state) fn stop() { impl crate::state::AppState { /// What the editor does once its graphics device is lost while the view draws in `mode`: the - /// view goes back to Material, what a GTA VI drawable's own passes were drawing is kept from - /// the next device, and a person is told. - pub(crate) fn graphics_device_lost(&mut self, mode: or_renderer::ShadingMode) { + /// view goes back to Material, a person is told, and the return value reports whether a GTA VI + /// drawable's own Shaded passes were drawing (so the caller marks those effects on the bridge). + pub(crate) fn graphics_device_lost(&mut self, mode: or_renderer::ShadingMode) -> bool { use or_renderer::ShadingMode; let own = self.active_document().map(|doc| &doc.payload); - if mode == ShadingMode::Shaded - && matches!(own, Some(crate::state::DocPayload::Gta6Drawable(_))) - { - crate::render::gta6_meshlets::device_lost(); - } + let gta6_shaded = mode == ShadingMode::Shaded + && matches!(own, Some(crate::state::DocPayload::Gta6Drawable(_))); self.remember_shading_mode(ShadingMode::Material); self.show_warning_toast(tr!( "The graphics device was lost. The view is back to Material, and what the Shaded view was drawing when it was lost draws as Material until OpenRage is started again" )); + gta6_shaded } } diff --git a/src/state/gta6/drawable/gta6_shaders/tests.rs b/src/state/gta6/drawable/gta6_shaders/tests.rs index d3d51f29..8b98e591 100644 --- a/src/state/gta6/drawable/gta6_shaders/tests.rs +++ b/src/state/gta6/drawable/gta6_shaders/tests.rs @@ -500,13 +500,20 @@ fn two_geometries_that_wear_one_effect_with_other_streams_are_each_drawn_by_the_ skin_tones: &|| Ok(None), game_texture: &|_| Ok(None), }; + let overrides = crate::render::gta6_overrides::Gta6DrawOverrides::default(); + let mut terrain = crate::render::gta6_terrain::TerrainCache::default(); + let mut awaited = false; let (meshlets, effects) = meshlets_of( &drawable, models, &sources, crate::render::gta6_instances::IN_PLACE[0], + &overrides, + &mut terrain, + &mut awaited, ) .expect("its shader"); + assert!(!awaited); assert_eq!((meshlets.rest.as_slice(), &meshlets.why), (&[][..], &None)); assert_eq!(effects, [hash, hash]); // The stand-in names the one type of a mesh stage by the streams its pass reads. diff --git a/src/state/gta6/textures/gta6_texture_index.rs b/src/state/gta6/textures/gta6_texture_index.rs index 9abc476b..c3b34836 100644 --- a/src/state/gta6/textures/gta6_texture_index.rs +++ b/src/state/gta6/textures/gta6_texture_index.rs @@ -433,7 +433,11 @@ fn dictionary_textures( /// Every key a shader of `doc`'s GTA VI drawable binds that no open document holds: a material's /// maps beyond its base colour, which Shaded samples and the model view's report never asks for. -fn unheld_material_keys(state: &AppState, doc: &Document) -> Vec { +fn unheld_material_keys( + state: &AppState, + doc: &Document, + beside: Option<&[crate::state::gta6_weapon_parts::Part]>, +) -> Vec { let DocPayload::Gta6Drawable(resource) = &doc.payload else { return Vec::new(); }; @@ -447,8 +451,7 @@ fn unheld_material_keys(state: &AppState, doc: &Document) -> Vec { }; // The parts a run draws beside the drawable bind maps too, and so do the states a ped's // parts are worn in. - let beside = crate::render::gta6_meshlets::beside(); - let beside = beside.iter().flat_map(|parts| parts.iter()); + let beside = beside.into_iter().flatten(); let beside = beside.filter_map(|part| crate::state::gta6_resource::drawable_of(&part.resource, None)); let shaders = drawables @@ -463,8 +466,17 @@ impl AppState { /// Open every pack that holds a key the active GTA VI drawable binds and nothing open holds, /// indexing the packs of its install or folder first, as a job; whether one opened. pub fn try_open_texture_pack(&mut self) -> bool { + self.try_open_texture_pack_with(None) + } + + /// [`Self::try_open_texture_pack`] also checking any `beside` parts drawn alongside the active + /// drawable. + pub(crate) fn try_open_texture_pack_with( + &mut self, + beside: Option<&[crate::state::gta6_weapon_parts::Part]>, + ) -> bool { let opened = self.take_opened_texture_packs(); - self.ask_for_texture_packs(); + self.ask_for_texture_packs(beside); opened } @@ -475,9 +487,14 @@ impl AppState { self.gta6_finders.texture_packs.kept_across_documents = true; } - /// Whether the active GTA VI drawable binds a key nothing open holds. - pub(crate) fn wants_texture_packs(&self) -> bool { - (self.active_document()).is_some_and(|doc| !unheld_material_keys(self, doc).is_empty()) + /// Whether the active GTA VI drawable (or any `beside` parts drawn alongside it) binds a key + /// nothing open holds. + pub(crate) fn wants_texture_packs( + &self, + beside: Option<&[crate::state::gta6_weapon_parts::Part]>, + ) -> bool { + (self.active_document()) + .is_some_and(|doc| !unheld_material_keys(self, doc, beside).is_empty()) } /// Whether a worker still opens a pack [`Self::try_open_texture_pack`] asked for. @@ -521,7 +538,7 @@ impl AppState { } /// Have workers open the packs the active drawable's missing maps are in, each once. - fn ask_for_texture_packs(&mut self) { + fn ask_for_texture_packs(&mut self, beside: Option<&[crate::state::gta6_weapon_parts::Part]>) { // A drawable that asked and closed reopens under another id, so its folder is walked again. let (documents, asked) = (&self.documents, self.gta6_finders.texture_packs.asked.len()); (self.gta6_finders.texture_packs.asked) @@ -542,9 +559,11 @@ impl AppState { .collect(), false => Vec::new(), }; - missing.extend(crate::state::gta6_shaders::layer_index::tile_keys(self)); + missing.extend(crate::state::gta6_shaders::layer_index::tile_keys( + self, beside, + )); missing.extend(crate::state::gta6_shaders::terrain_tile::texture_keys(self)); - missing.extend(unheld_material_keys(self, doc)); + missing.extend(unheld_material_keys(self, doc, beside)); if missing.is_empty() || !matches!(doc.payload, DocPayload::Gta6Drawable(_)) { return; } diff --git a/src/state/tests/opening_a_ttpf.rs b/src/state/tests/opening_a_ttpf.rs index e1dbc9a8..95c9ce55 100644 --- a/src/state/tests/opening_a_ttpf.rs +++ b/src/state/tests/opening_a_ttpf.rs @@ -299,6 +299,7 @@ pub(in crate::state) fn drawn( doc: state.document(doc).expect("open"), selection: None, entry: None, + beside: None, }; (doc, crate::render::gta6_drawable::meshes(&request)) } diff --git a/src/state/viewport_camera.rs b/src/state/viewport_camera.rs index a79623bd..2f63a04a 100644 --- a/src/state/viewport_camera.rs +++ b/src/state/viewport_camera.rs @@ -7,7 +7,8 @@ use or_renderer::OrbitCamera; use super::{AppState, DocumentId}; use crate::render::viewport::{ - compute_active_doc_bounds, compute_selection_bounds, selected_dictionary_entry, CameraInputs, + compute_active_doc_bounds_with, compute_selection_bounds_with, selected_dictionary_entry, + CameraInputs, }; // ⚠ Keyed by document and never by workspace. A workspace is a layout preset @@ -39,7 +40,16 @@ impl AppState { /// A document seen for the first time is framed on its own bounds; after /// that its camera moves only by input, by a frame key, or by choosing /// another dictionary entry inside it. + #[cfg(test)] pub fn step_viewport_camera(&mut self, inputs: CameraInputs) -> &OrbitCamera { + self.step_viewport_camera_with(inputs, None) + } + + pub(crate) fn step_viewport_camera_with( + &mut self, + inputs: CameraInputs, + framed_beside: Option<&[crate::state::gta6_weapon_parts::Part]>, + ) -> &OrbitCamera { // The Wardrobe dresses a ped that is no document, with a camera of its own. if self.active_workspace == crate::state::Workspace::Wardrobe { return self.step_dressed_camera(inputs); @@ -81,9 +91,9 @@ impl AppState { .get(&active) .is_none_or(|view| view.framed_entry != entry); let bounds = if inputs.frame_selection { - compute_selection_bounds(self) + compute_selection_bounds_with(self, framed_beside) } else if reframe { - compute_active_doc_bounds(self) + compute_active_doc_bounds_with(self, framed_beside) } else { None };