diff --git a/crates/core/src/bake.rs b/crates/core/src/bake.rs index a40f5ab0..8289ef42 100644 --- a/crates/core/src/bake.rs +++ b/crates/core/src/bake.rs @@ -4,9 +4,11 @@ mod ambient_occlusion_attenuation; mod ambient_occlusion_settings; mod backface_mode; mod bake_antialiasing; +mod bake_change; mod bake_paint_target; mod bake_resolution; mod bake_settings; +mod bake_source; mod bake_sync; mod bake_sync_group; mod mesh_match_mode; @@ -45,8 +47,10 @@ pub use ambient_occlusion_attenuation::AmbientOcclusionAttenuation; pub use ambient_occlusion_settings::AmbientOcclusionSettings; pub use backface_mode::BackfaceMode; pub use bake_antialiasing::BakeAntialiasing; +pub use bake_change::BakeChange; pub use bake_resolution::BakeResolution; pub use bake_settings::BakeSettings; +pub use bake_source::{BakeSource, fingerprint, fingerprint_words}; pub use bake_sync::BakeSync; pub use bake_sync_group::BakeSyncGroup; pub use baked_map::BakedMap; diff --git a/crates/core/src/bake/bake_change.rs b/crates/core/src/bake/bake_change.rs new file mode 100644 index 00000000..bb73b1f2 --- /dev/null +++ b/crates/core/src/bake/bake_change.rs @@ -0,0 +1,25 @@ +use serde::{Deserialize, Serialize}; + +/// What changed since a mesh map was baked, which makes it out of date +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum BakeChange { + LowPoly, + HighPoly, + Cage, + Settings, + MapSettings, +} + +impl BakeChange { + /// Identifier in automation replies + pub fn id(self) -> &'static str { + match self { + BakeChange::LowPoly => "lowPoly", + BakeChange::HighPoly => "highPoly", + BakeChange::Cage => "cage", + BakeChange::Settings => "settings", + BakeChange::MapSettings => "mapSettings", + } + } +} diff --git a/crates/core/src/bake/bake_source.rs b/crates/core/src/bake/bake_source.rs new file mode 100644 index 00000000..9cc59c44 --- /dev/null +++ b/crates/core/src/bake/bake_source.rs @@ -0,0 +1,69 @@ +use super::BakeChange; +use serde::{Deserialize, Serialize}; + +/// Fingerprints of what one mesh map was baked from: a later change to any of them shows the map out of date +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BakeSource { + /// The low poly's geometry + pub low_poly: u64, + /// The high poly files, in list order (0: none, the set bakes from the low poly) + pub high_poly: u64, + /// The cage file (0: none) + pub cage: u64, + /// The settings every map of the set shares (size, high poly, cage, skew) and its UV tiles + pub settings: u64, + /// The map's own settings + pub map_settings: u64, +} + +impl BakeSource { + /// What differs in `current` from this record, in [`BakeChange`] order (empty: up to date) + pub fn changes(&self, current: &BakeSource) -> Vec { + [ + (self.low_poly != current.low_poly, BakeChange::LowPoly), + (self.high_poly != current.high_poly, BakeChange::HighPoly), + (self.cage != current.cage, BakeChange::Cage), + (self.settings != current.settings, BakeChange::Settings), + (self.map_settings != current.map_settings, BakeChange::MapSettings), + ] + .into_iter() + .filter_map(|(changed, change)| changed.then_some(change)) + .collect() + } +} + +/// A fingerprint of `bytes` that stays the same across runs, platforms and Rust versions (unlike `std::hash`) +pub fn fingerprint(bytes: &[u8]) -> u64 { + let words = bytes.chunks(8).map(|chunk| { + let mut word_bytes = [0; 8]; + word_bytes[..chunk.len()].copy_from_slice(chunk); + u64::from_le_bytes(word_bytes) + }); + fingerprint_words(words.chain([bytes.len() as u64])) +} + +/// [`fingerprint`] of a sequence of words: FNV-1a taking a 64-bit word per step +pub fn fingerprint_words(words: impl IntoIterator) -> u64 { + // FNV-1a 64-bit offset basis and prime + const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; + const PRIME: u64 = 0x0000_0100_0000_01b3; + + words.into_iter().fold(OFFSET_BASIS, |hash, word| (hash ^ word).wrapping_mul(PRIME)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_fingerprint_changes_with_any_byte_and_with_the_length() { + let bytes: Vec = (0..=20).collect(); + let mut changed = bytes.clone(); + changed[17] ^= 1; + + assert_ne!(fingerprint(&bytes), fingerprint(&changed)); + assert_ne!(fingerprint(&bytes), fingerprint(&bytes[..20])); + assert_ne!(fingerprint(&[]), fingerprint(&[0])); + } +} diff --git a/crates/core/src/bake/mesh_map_settings.rs b/crates/core/src/bake/mesh_map_settings.rs index 281d5c98..579141e7 100644 --- a/crates/core/src/bake/mesh_map_settings.rs +++ b/crates/core/src/bake/mesh_map_settings.rs @@ -84,6 +84,22 @@ impl MeshMapSettings { } } + /// `map`'s typed parameters as JSON + pub fn parameters_json(&self, map: BakedMap) -> serde_json::Value { + let parameters = match map { + // These maps have no parameters of their own + BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => return serde_json::Value::Null, + BakedMap::Id => serde_json::to_value(self.id.parameters), + BakedMap::AmbientOcclusion => serde_json::to_value(self.ao.parameters), + BakedMap::Curvature => serde_json::to_value(self.curvature.parameters), + BakedMap::Position => serde_json::to_value(self.position.parameters), + BakedMap::Thickness => serde_json::to_value(self.thickness.parameters), + BakedMap::Height => serde_json::to_value(self.height.parameters), + BakedMap::BentNormal => serde_json::to_value(self.bent_normal.parameters), + }; + parameters.unwrap_or_default() + } + pub fn enabled(&self) -> impl Iterator { BakedMap::ALL.into_iter().filter(|map| self.is_enabled(*map)) } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index eedf93ec..772653e4 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -80,11 +80,12 @@ pub const FULL_TURN_DEGREES: f32 = 360.0; pub use anisotropic_kuwahara::AnisotropicKuwahara; pub use backface::Backface; pub use bake::{ - AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakeSync, - BakeSyncGroup, BakedMap, BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings, GroundPlaneSettings, - HeightNormalization, HeightSettings, HighPolySettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings, MeshCurvatureSettings, MeshMapSettings, - MeshMatchMode, NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, RayDistribution, RaySettings, - SelfOcclusion, SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings, + AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakeChange, BakePaintTarget, BakeResolution, BakeSettings, + BakeSource, BakeSync, BakeSyncGroup, BakedMap, BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings, + GroundPlaneSettings, HeightNormalization, HeightSettings, HighPolySettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings, + MeshCurvatureSettings, MeshMapSettings, MeshMatchMode, NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale, + PositionSettings, RayDistribution, RaySettings, SelfOcclusion, SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings, fingerprint, + fingerprint_words, }; pub use bevel::Bevel; pub use bevel_blur::BevelBlur; diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 0a4bf868..69437007 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; -use crate::{BakeSettings, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result}; +use crate::{BakeSettings, BakeSource, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result}; pub use crate::env_alignment::EnvAlignment; pub use crate::shadow_mode::ShadowMode; @@ -69,6 +69,9 @@ pub struct TextureSet { /// Mesh maps that have been baked (pixels live with the engine / project file). #[serde(default)] pub baked: BTreeSet, + /// What each baked map was baked from; a map without a record (imported, or older project) is never out of date + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub bake_sources: BTreeMap, #[serde(default = "yes")] pub visible: bool, /// UDIM numbers of the UV tiles this set paints, ascending (UV tiles mode); @@ -171,6 +174,7 @@ impl TextureSet { height_strength: 1.0, bake: BakeSettings::default(), baked: BTreeSet::new(), + bake_sources: BTreeMap::new(), visible: true, uv_tiles: Vec::new(), bake_excluded_tiles: BTreeSet::new(), @@ -187,6 +191,19 @@ impl TextureSet { self.uv_tiles.is_empty() || self.uv_tiles.iter().any(|tile| !self.bake_excluded_tiles.contains(tile)) } + /// Fingerprint of the shared bake settings (not the set's check) and baked UV tiles (not their working resolutions) + pub fn bake_settings_fingerprint(&self) -> u64 { + let mut common = self.bake.common; + common.is_enabled = true; + let shared = (common, &self.bake.high_poly, &self.bake.cage, &self.bake.skew, &self.uv_tiles, &self.bake_excluded_tiles); + crate::fingerprint(serde_json::to_string(&shared).unwrap_or_default().as_bytes()) + } + + /// Fingerprint of `map`'s own bake settings (not whether it is checked) + pub fn map_settings_fingerprint(&self, map: BakedMap) -> u64 { + crate::fingerprint(self.bake.maps.parameters_json(map).to_string().as_bytes()) + } + /// Height strength for slopes measured over the whole texture width (the viewport shader, /// the path tracer): a UV tile atlas is one tile per column wide. pub fn atlas_height_strength(&self) -> f32 { diff --git a/crates/engine/src/bake/bake_mesh.rs b/crates/engine/src/bake/bake_mesh.rs index bcdb2bcc..d4dbfeeb 100644 --- a/crates/engine/src/bake/bake_mesh.rs +++ b/crates/engine/src/bake/bake_mesh.rs @@ -11,4 +11,6 @@ pub struct BakeMesh { pub bytes: Arc>, pub mesh: Arc, pub base_color: Vec>>, + /// [`texturecraft_core::fingerprint`] of `bytes`: what bakes from this file record + pub fingerprint: u64, } diff --git a/crates/engine/src/bake/bake_sources.rs b/crates/engine/src/bake/bake_sources.rs new file mode 100644 index 00000000..70f7665c --- /dev/null +++ b/crates/engine/src/bake/bake_sources.rs @@ -0,0 +1,65 @@ +//! What each baked map was baked from, and which maps are out of date since + +use std::collections::BTreeMap; + +use texturecraft_core::{BakeChange, BakeSource, BakedMap, CageType, fingerprint_words}; + +use crate::{Result, Session}; + +impl Session { + /// What a bake of `map` on texture set `texture_set` would read now + pub fn bake_source(&self, texture_set: usize, map: BakedMap) -> Result { + let set = self.doc.project.texture_set(texture_set)?; + let from_high = !set.bake.high_poly.use_low_as_high && !self.doc.bake_meshes.high.is_empty(); + let high_poly = match from_high { + true => fingerprint_words(self.doc.bake_meshes.high.iter().map(|high| high.fingerprint)), + false => 0, + }; + let reads_cage = from_high && set.bake.cage.kind == CageType::CustomFile; + let cage = self.doc.bake_meshes.cage.as_ref().filter(|_| reads_cage).map_or(0, |cage| cage.fingerprint); + + Ok(BakeSource { + low_poly: self.low_poly_fingerprint(), + high_poly, + cage, + settings: set.bake_settings_fingerprint(), + map_settings: set.map_settings_fingerprint(map), + }) + } + + /// What changed since `map` of texture set `texture_set` was baked; empty when up to date, not baked or without a record + pub fn bake_changes(&self, texture_set: usize, map: BakedMap) -> Vec { + let Ok(set) = self.doc.project.texture_set(texture_set) else { return Vec::new() }; + let Some(record) = set.bake_sources.get(&map).filter(|_| set.baked.contains(&map)) else { return Vec::new() }; + + self.bake_source(texture_set, map).map(|current| record.changes(¤t)).unwrap_or_default() + } + + /// The out-of-date maps of texture set `texture_set`, each with what changed + pub fn out_of_date_maps(&self, texture_set: usize) -> BTreeMap> { + BakedMap::ALL.into_iter().map(|map| (map, self.bake_changes(texture_set, map))).filter(|(_, changes)| !changes.is_empty()).collect() + } + + /// Fingerprint of the low poly's own geometry (computed once per loaded mesh) + fn low_poly_fingerprint(&self) -> u64 { + *self.low_poly_fingerprint.get_or_init(|| { + let source = &self.source; + let floats = source.positions.iter().chain(&source.normals).flat_map(|vector| vector.to_array()).chain(source.uvs.iter().flat_map(|uv| uv.to_array())); + let words = floats.map(|float| u64::from(float.to_bits())).chain(source.indices.iter().map(|index| u64::from(*index))); + fingerprint_words(words) + }) + } + + /// Keep `sources` as what maps of `texture_set` were baked from; without them the `stored` maps lose their record + pub(super) fn record_bake_sources(&mut self, texture_set: usize, sources: Option<&BTreeMap>, stored: &[BakedMap]) -> Result<()> { + let set = self.doc.project.texture_set_mut(texture_set)?; + match sources { + Some(sources) => set.bake_sources.extend(sources), + None => set.bake_sources.retain(|map, _| !stored.contains(map)), + } + + let baked = &set.baked; + set.bake_sources.retain(|map, _| baked.contains(map)); + Ok(()) + } +} diff --git a/crates/engine/src/bake/bake_task.rs b/crates/engine/src/bake/bake_task.rs index a617d97b..3c0cb59e 100644 --- a/crates/engine/src/bake/bake_task.rs +++ b/crates/engine/src/bake/bake_task.rs @@ -26,6 +26,8 @@ pub struct BakeTask { pub previous_maps: BakedMaps, /// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`). pub tracer: Option>, + /// What each map this task makes is baked from, taken when the task was made + pub sources: std::collections::BTreeMap, } impl BakeTask { @@ -66,7 +68,13 @@ impl BakeTask { // A resized partial bake also returns unchecked maps that must survive application let mut retained: std::collections::BTreeMap<_, _> = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(); retained.insert(map, data); - combined = Some(StreamedBake { resolution: output.resolution, height: output.height, maps: retained, tracer: output.tracer }); + combined = Some(StreamedBake { + resolution: output.resolution, + height: output.height, + maps: retained, + tracer: output.tracer, + sources: self.sources.clone(), + }); } } } @@ -80,6 +88,7 @@ impl BakeTask { height: output.height, maps: output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(), tracer: output.tracer, + sources: self.sources.clone(), }) } } diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index fef806b1..49ec4ec0 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -15,8 +15,8 @@ use serde_json::{Value, json}; use texturecraft_bake::tracing::Tracer; use texturecraft_bake::{BakeOutput, BakePaintMap, MAX_RAYS, Progress}; use texturecraft_core::{ - BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakeSyncGroup, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, - SelfOcclusion, + BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakeSource, BakeSyncGroup, BakedMap, CurvatureMethod, PositionMode, RayDistribution, + RaySettings, SelfOcclusion, }; use texturecraft_geom::Mesh; @@ -121,7 +121,8 @@ pub(super) fn parse_mesh(file_name: &str, bytes: Vec) -> Result { let imported = texturecraft_formats::import_high_poly_bytes(file_name, &bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?; let base_color = imported.base_color.into_iter().map(|c| c.map(Arc::new)).collect(); let folder = std::path::Path::new(file_name).parent().map(|folder| folder.display().to_string()).filter(|folder| !folder.is_empty()); - Ok(BakeMesh { name: file_name.to_string(), folder, bytes: Arc::new(bytes), mesh: Arc::new(imported.mesh), base_color }) + let fingerprint = texturecraft_core::fingerprint(&bytes); + Ok(BakeMesh { name: file_name.to_string(), folder, bytes: Arc::new(bytes), mesh: Arc::new(imported.mesh), base_color, fingerprint }) } impl Session { @@ -183,6 +184,7 @@ impl Session { let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&texture_set).cloned().unwrap_or_default() }; let tracer = chosen_tracer(GPU_TRACER.get(), GPU_RAYTRACING.load(Ordering::Relaxed)); + let sources = set.bake.maps.enabled().map(|map| Ok((map, self.bake_source(texture_set, map)?))).collect::>()?; Ok(BakeTask { low_base_color, ts: texture_set, @@ -198,6 +200,7 @@ impl Session { excluded_tiles, previous_maps, tracer, + sources, }) } @@ -260,7 +263,7 @@ impl Session { /// Store a finished bake as one undo step pub fn apply_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> { let tracer = output.tracer.clone(); - self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output))?; + self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output, None))?; self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})")); Ok(()) } @@ -269,17 +272,26 @@ impl Session { /// preview that showed them holds the same ones) pub fn apply_streamed_bake(&mut self, texture_set: usize, output: StreamedBake) -> Result<()> { let tracer = output.tracer.clone(); - self.edit("Bake mesh maps", |session| session.store_bake_maps(texture_set, output.resolution, output.height, output.maps))?; + self.edit("Bake mesh maps", |session| session.store_bake_maps(texture_set, output.resolution, output.height, output.maps, Some(&output.sources)))?; self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})")); Ok(()) } - fn store_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> { + /// Store `output`, recording what its maps were baked from when `sources` are known + fn store_bake(&mut self, texture_set: usize, output: BakeOutput, sources: Option<&BTreeMap>) -> Result<()> { let maps = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(); - self.store_bake_maps(texture_set, output.resolution, output.height, maps) + self.store_bake_maps(texture_set, output.resolution, output.height, maps, sources) } - fn store_bake_maps(&mut self, texture_set: usize, resolution: u32, height: u32, maps: std::collections::BTreeMap>>) -> Result<()> { + fn store_bake_maps( + &mut self, + texture_set: usize, + resolution: u32, + height: u32, + maps: BTreeMap>>, + sources: Option<&BTreeMap>, + ) -> Result<()> { + let stored: Vec = maps.keys().copied().collect(); let entry = self.doc.baked.entry(texture_set).or_default(); if entry.resolution != resolution || entry.maps.keys().any(|map| entry.height(*map) != height) { entry.maps.clear(); @@ -288,7 +300,7 @@ impl Session { entry.resolution = resolution; entry.maps.extend(maps); self.doc.project.texture_set_mut(texture_set)?.baked = entry.maps.keys().copied().collect(); - Ok(()) + self.record_bake_sources(texture_set, sources, &stored) } /// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran. @@ -299,7 +311,8 @@ impl Session { } let out = task.run(&Progress::new())?; let tracer = out.tracer.clone(); - self.apply_bake(ts, out)?; + self.edit("Bake mesh maps", |session| session.store_bake(ts, out, Some(&task.sources)))?; + self.log.info("Baker", format!("Baked texture set {ts} ({tracer})")); Ok(tracer) } @@ -879,7 +892,7 @@ fn bake_one_set(session: &mut Session, index: usize, cpu: bool) -> Result>>, pub tracer: String, + /// What the baked maps were baked from (the task's [`crate::BakeTask::sources`]) + pub sources: BTreeMap, } diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 9c447c3c..5cfc235b 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -1655,7 +1655,14 @@ f 1/1 2/2 3/3 let b = dir.join("b.obj"); std::fs::write(&b, "v 0 0 0\nv 2 0 0\nv 0 2 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); let mut s = Session::from_mesh_bytes("a.obj", &std::fs::read(&a).unwrap(), 128, "a").unwrap(); - let cage = crate::bake::BakeMesh { name: "cage".into(), folder: None, bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() }; + let cage = crate::bake::BakeMesh { + name: "cage".into(), + folder: None, + bytes: Default::default(), + mesh: s.mesh.clone(), + base_color: Vec::new(), + fingerprint: 0, + }; s.doc.bake_meshes.cage = Some(cage); let _ = s.doc.bake_meshes.low_base_color.set(Err("old".into())); diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index a4258463..e9c3b2e5 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -276,6 +276,7 @@ pub fn texture_set(session: &Session, index: usize) -> Value { "layers": session.doc.project.walk(index).len(), "parts": crate::set_cmds::parts(session, index), "baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)), + "outOfDate": session.out_of_date_maps(index).into_iter().map(|(map, changes)| (map.id(), changes.iter().map(|change| change.id()).collect::>())).collect::>(), "visible": texture_set.visible, "active": index == session.ts(), }) diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index f08d34c4..5736c5ca 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -53,19 +53,19 @@ fn set(s: &mut Session, p: &Value) -> Result { pub(crate) const FIRST_TILE: u32 = *UDIM_RANGE.start(); /// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `ts` in the caller's edit; returns its width -pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result { - let texture_set = s.doc.project.texture_set(ts)?; +pub(crate) fn use_images(session: &mut Session, command: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result { + let texture_set = session.doc.project.texture_set(ts)?; let grid = texture_set.tile_grid(); if let Some(tile) = texture_set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) { - return Err(bad(cmd, format!("no image for UV tile {tile}"))); + return Err(bad(command, format!("no image for UV tile {tile}"))); } - let (width, height) = image_map_size(s, cmd, ts)?; + let (width, height) = image_map_size(session, command, ts)?; // Bent normals are tangent-space maps like the normal map, so both follow the project's normal format - let flip_green = matches!(map, BakedMap::Normal | BakedMap::BentNormal) && s.doc.project.normal_format == NormalFormat::DirectX; + let flip_green = matches!(map, BakedMap::Normal | BakedMap::BentNormal) && session.doc.project.normal_format == NormalFormat::DirectX; let data = match (grid, images.values().next()) { - (_, None) => return Err(bad(cmd, "no image to use")), + (_, None) => return Err(bad(command, "no image to use")), (None, Some(image)) => resample(map.components(), (width, height), flip_green, |u, v| image.sample(u, v)), // An atlas texel reads the image of the tile its mesh UV falls in (Some(grid), Some(_)) => resample(map.components(), (width, height), flip_green, |u, v| { @@ -74,10 +74,13 @@ pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, i }), }; - let entry = s.doc.baked.entry(ts).or_default(); + let entry = session.doc.baked.entry(ts).or_default(); entry.resolution = width; entry.maps.insert(map, Arc::new(data)); - s.doc.project.texture_set_mut(ts)?.baked.insert(map); + // An imported map is never out of date: nothing records what it was made from + let set = session.doc.project.texture_set_mut(ts)?; + set.baked.insert(map); + set.bake_sources.remove(&map); Ok(width) } @@ -153,18 +156,20 @@ fn resample(comps: usize, (w, h): (u32, u32), flip_green: bool, sample: impl Fn( out } -fn clear(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "textureSet.meshMap.clear"; - let ts = ts_param(s, p, CMD)?; - let map = map_param(p, CMD)?; - if !s.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)) { - return Err(bad(CMD, format!("texture set {ts} has no {} map", map.id()))); +fn clear(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "textureSet.meshMap.clear"; + let ts = ts_param(session, params, COMMAND)?; + let map = map_param(params, COMMAND)?; + if !session.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map)) { + return Err(bad(COMMAND, format!("texture set {ts} has no {} map", map.id()))); } - s.edit("Clear mesh map", |s| { - if let Some(b) = s.doc.baked.get_mut(&ts) { - b.maps.remove(&map); + session.edit("Clear mesh map", |session| { + if let Some(baked) = session.doc.baked.get_mut(&ts) { + baked.maps.remove(&map); } - s.doc.project.texture_set_mut(ts)?.baked.remove(&map); + let set = session.doc.project.texture_set_mut(ts)?; + set.baked.remove(&map); + set.bake_sources.remove(&map); Ok(()) })?; Ok(Value::Null) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index f0a8df58..05a0c779 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -425,6 +425,8 @@ pub struct Session { pub project_id: u64, /// The mesh with its own UVs (`mesh` maps UV-tiled sets into their atlas). pub(crate) source: Arc, + /// Fingerprint of `source`'s geometry, once a bake or an out-of-date check needs it + pub(crate) low_poly_fingerprint: std::sync::OnceLock, pub bvh: Arc, /// Original mesh file (saved inside the project); None for built-in meshes. pub mesh_source: Option<(String, Arc>)>, @@ -527,6 +529,7 @@ impl Session { mesh_id: next_mesh_id(), project_id: next_mesh_id(), source, + low_poly_fingerprint: Default::default(), mesh, bvh: Arc::new(bvh), mesh_source: mesh_source.map(|(extension, bytes)| (extension, Arc::new(bytes))), diff --git a/crates/engine/tests/it/bake_out_of_date.rs b/crates/engine/tests/it/bake_out_of_date.rs new file mode 100644 index 00000000..9a5c1dcd --- /dev/null +++ b/crates/engine/tests/it/bake_out_of_date.rs @@ -0,0 +1,136 @@ +//! Out-of-date mesh maps: what each map was baked from, compared with what a bake would read now + +use std::sync::atomic::{AtomicBool, Ordering}; + +use serde_json::json; +use texturecraft_engine::bake::Progress; +use texturecraft_engine::core::{BakeChange, BakedMap, CageType}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// A plane with its position map baked by `bake.run` +fn baked_plane() -> Session { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["position"], "dilation": 0 })).unwrap(); + session +} + +fn changes(session: &Session) -> Vec { + session.bake_changes(0, BakedMap::Position) +} + +#[test] +fn a_map_goes_out_of_date_when_its_settings_or_the_shared_ones_change_and_a_bake_brings_it_back() { + let mut session = baked_plane(); + assert!(changes(&session).is_empty(), "fresh bake: {:?}", changes(&session)); + + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + assert_eq!(changes(&session), [BakeChange::MapSettings]); + execute(&mut session, "bake.settings", &json!({ "dilation": 4 })).unwrap(); + assert_eq!(changes(&session), [BakeChange::Settings, BakeChange::MapSettings]); + let inspect = execute(&mut session, "project.inspect", &json!({})).unwrap(); + assert_eq!(inspect["textureSets"][0]["outOfDate"], json!({ "position": ["settings", "mapSettings"] })); + + execute(&mut session, "bake.run", &json!({})).unwrap(); + assert!(changes(&session).is_empty(), "rebaked: {:?}", changes(&session)); +} + +#[test] +fn the_record_is_saved_with_the_project() { + let mut session = baked_plane(); + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + + assert_eq!(changes(&reopened), [BakeChange::MapSettings]); +} + +#[test] +fn maps_saved_before_records_existed_and_imported_maps_never_go_out_of_date() { + let mut old = baked_plane(); + old.doc.project.texture_sets[0].bake_sources.clear(); + let mut old = Session::from_project_bytes(&old.to_project_bytes().unwrap()).unwrap(); + execute(&mut old, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + assert!(changes(&old).is_empty(), "{:?}", changes(&old)); + + let mut imported = baked_plane(); + let mut png = Vec::new(); + image::RgbImage::from_pixel(4, 4, image::Rgb([128, 64, 32])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + imported.import_resource_bytes("position.png", png).unwrap(); + execute(&mut imported, "textureSet.meshMap.set", &json!({ "map": "position", "image": "position.png" })).unwrap(); + execute(&mut imported, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + assert!(changes(&imported).is_empty(), "{:?}", changes(&imported)); +} + +#[test] +fn adding_a_high_poly_puts_the_maps_out_of_date() { + let mut session = baked_plane(); + + session.add_high_poly_bytes("detail_high.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + + assert_eq!(changes(&session), [BakeChange::HighPoly]); +} + +#[test] +fn a_cage_file_counts_only_for_sets_that_bake_with_it() { + let mut session = baked_plane(); + session.add_high_poly_bytes("detail_high.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + execute(&mut session, "bake.run", &json!({})).unwrap(); + + let cage: String = (0..session.mesh.triangle_count()).map(|_| "v 0 0 0\nv 1 0 0\nv 0 1 0\nf -3 -2 -1\n").collect(); + session.set_cage_bytes("cage.obj", cage.into_bytes()).unwrap(); + assert!(changes(&session).is_empty(), "the cage type is not Custom File: {:?}", changes(&session)); + + session.doc.project.texture_sets[0].bake.cage.kind = CageType::CustomFile; + assert!(changes(&session).contains(&BakeChange::Cage), "{:?}", changes(&session)); +} + +#[test] +fn a_setting_changed_while_the_bake_runs_leaves_the_new_map_out_of_date() { + let mut session = baked_plane(); + let task = session.bake_task(0).unwrap(); + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + + let streamed_once = AtomicBool::new(false); + let output = task.run_streaming(&Progress::new(), &mut |_| streamed_once.store(true, Ordering::Relaxed)).unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + + assert!(streamed_once.load(Ordering::Relaxed)); + assert_eq!(changes(&session), [BakeChange::MapSettings]); +} + +/// Two quads side by side, one texture set each, lifted by `lift` where a high poly or cage stands off the low poly +fn two_parts(lift: f32) -> String { + let mut obj = String::new(); + for left in [0.0, 2.0] { + let right = left + 1.0; + obj += &format!("v {left} 0 {lift}\nv {right} 0 {lift}\nv {right} 1 {lift}\nv {left} 1 {lift}\n"); + } + obj += "vt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\n"; + obj += "usemtl Left\nf 1/1 2/2 3/3\nf 1/1 3/3 4/4\nusemtl Right\nf 5/1 6/2 7/3\nf 5/1 7/3 8/4\n"; + obj +} + +#[test] +fn a_reopened_project_keeps_every_sets_maps_up_to_date() { + let mut session = Session::from_mesh_bytes_with_uvs("parts.obj", two_parts(0.0).as_bytes(), 128, "parts", None, false).unwrap(); + session.add_high_poly_bytes("parts_high.obj", two_parts(0.05).into_bytes()).unwrap(); + session.set_cage_bytes("parts_cage.obj", two_parts(0.2).into_bytes()).unwrap(); + for texture_set in &mut session.doc.project.texture_sets { + texture_set.bake.cage.kind = CageType::CustomFile; + } + execute(&mut session, "bake.run", &json!({ "ts": "all", "resolution": 32, "maps": ["position", "normal"], "dilation": 0 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "ts": 1, "map": "normal" })).unwrap(); + let records = |session: &Session| session.doc.project.texture_sets.iter().map(|set| set.bake_sources.clone()).collect::>(); + assert_eq!(session.set_count(), 2); + assert!(records(&session).iter().all(|sources| sources.len() == 2), "both maps of both sets are recorded"); + + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + + assert_eq!(records(&reopened), records(&session), "the records are saved as they were"); + for texture_set in 0..reopened.set_count() { + assert!(reopened.out_of_date_maps(texture_set).is_empty(), "set {texture_set}: {:?}", reopened.out_of_date_maps(texture_set)); + } + assert!(reopened.auto_rebake_due().is_empty(), "opening the project starts no rebake"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 11b199c9..f43035f4 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -5,6 +5,7 @@ mod add_mask_items; mod bake; mod bake_checks; mod bake_log; +mod bake_out_of_date; mod bake_resolution; mod bake_settings; mod bake_tiles; diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 1f7253ac..720d4c49 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -595,7 +595,7 @@ fn a_loaded_cage_can_be_removed_while_the_cage_does_not_apply() { session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); let mesh = session.mesh.clone(); session.doc.bake_meshes.cage = - Some(texturecraft_engine::BakeMesh { name: "Cage.obj".into(), folder: None, bytes: Default::default(), mesh, base_color: Vec::new() }); + Some(texturecraft_engine::BakeMesh { name: "Cage.obj".into(), folder: None, bytes: Default::default(), mesh, base_color: Vec::new(), fingerprint: 0 }); let settings = &mut session.doc.project.texture_sets[0].bake; (settings.cage.kind, settings.high_poly.use_low_as_high) = (CageType::CustomFile, true); harness.run_steps(3); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index a682a901..91fad894 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -320,6 +320,12 @@ with no partner. It is `null` when no set of the bake matches by mesh name: "pairs": [{"low": "Arm_low", "high": "Arm_high"}, {"low": "Strap_low", "high": null}]}} ``` +Each texture set in `project.inspect` / `session.inspect` lists its out-of-date mesh maps as +`outOfDate`: map id → what changed since that map was baked, any of `lowPoly`, `highPoly`, `cage`, +`settings` (the bake settings every map shares, or the UV tiles baked) and `mapSettings` (the map's +own). Imported maps, and maps saved before this record existed, never show: +`"outOfDate": {"ambientOcclusion": ["mapSettings"]}`. + `{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with `ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) until `baking` is `null`.