Repository navigation
Assets: baked mesh maps appear as project texture resources #986
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,227 @@ | ||
| //! Live image resources derived from baked mesh maps in [`crate::Document::baked`] | ||
|
|
||
| use std::collections::{BTreeMap, BTreeSet, HashSet}; | ||
| use std::sync::{Arc, Weak}; | ||
|
|
||
| use texturecraft_compose::ImageRes; | ||
| use texturecraft_core::{BakedMap, Project}; | ||
|
|
||
| use crate::Session; | ||
| use crate::session::Document; | ||
|
|
||
| /// A baked mesh map currently exposed in [`Session::images`] under its resource name | ||
| #[derive(Clone, Debug)] | ||
| pub(crate) struct BakedImageEntry { | ||
| pub texture_set: usize, | ||
| pub map: BakedMap, | ||
| pub width: u32, | ||
| pub height: u32, | ||
| pub bytes: usize, | ||
| /// Weak pointer to the baked buffer so unchanged maps keep their [`ImageRes`] | ||
| pub source: Weak<Vec<f32>>, | ||
| } | ||
|
|
||
| /// Whether `(texture_set, map)` already comes from an imported image resource file | ||
| fn is_imported_mesh_map(project: &Project, texture_set: usize, map: BakedMap) -> bool { | ||
| project.resource_sources.values().any(|source| source.mesh_map.is_some_and(|slot| slot.texture_set == texture_set && slot.map == map)) | ||
| } | ||
|
|
||
| /// Disambiguate a baked map name without slicing inside multi-byte UTF-8 characters | ||
| fn unique_baked_name(base: String, taken: impl Fn(&str) -> bool) -> String { | ||
| if !taken(&base) { | ||
| return base; | ||
| } | ||
|
|
||
| let mut index = 2; | ||
| loop { | ||
| let candidate = format!("{index}_{base}"); | ||
| if !taken(&candidate) { | ||
| return candidate; | ||
| } | ||
|
|
||
| index += 1; | ||
| } | ||
| } | ||
|
|
||
| /// The resource names assigned to every baked mesh map in `doc` that is not backed by an imported file | ||
| pub(crate) fn baked_map_names(doc: &Document) -> Vec<(String, usize, BakedMap)> { | ||
| let mut names = Vec::new(); | ||
| let mut used = HashSet::new(); | ||
|
|
||
| for (texture_set, set) in doc.project.texture_sets.iter().enumerate() { | ||
| let Some(baked) = doc.baked.get(&texture_set) else { continue }; | ||
| if baked.resolution == 0 { | ||
| continue; | ||
| } | ||
|
|
||
| for (&map, data) in &baked.maps { | ||
| if baked.height(map) == 0 || data.is_empty() || is_imported_mesh_map(&doc.project, texture_set, map) { | ||
| continue; | ||
| } | ||
|
|
||
| let base = format!("{}_{}", set.name, map.id()); | ||
| let name = unique_baked_name(base, |candidate| { | ||
| doc.resources.contains_key(candidate) || used.contains(candidate) || crate::fill_alpha::library_alpha_of(candidate).is_some() | ||
| }); | ||
| used.insert(name.clone()); | ||
| names.push((name, texture_set, map)); | ||
| } | ||
| } | ||
|
|
||
| names | ||
| } | ||
|
|
||
| /// The resource name `(texture_set, map)` gets in `doc`, if any | ||
| pub(crate) fn baked_map_name_in(doc: &Document, texture_set: usize, map: BakedMap) -> Option<String> { | ||
| baked_map_names(doc).into_iter().find_map(|(name, set, baked_map)| (set == texture_set && baked_map == map).then_some(name)) | ||
| } | ||
|
|
||
| /// Expand a baked 1- or 3-component float map into a decoded [`ImageRes`] | ||
| fn baked_map_to_image(width: u32, height: u32, components: usize, data: &[f32]) -> Option<Arc<ImageRes>> { | ||
| let texel_count = usize::try_from(width).ok()?.checked_mul(usize::try_from(height).ok()?)?; | ||
| if texel_count == 0 || data.len() < texel_count.checked_mul(components)? { | ||
| return None; | ||
| } | ||
|
|
||
| let mut rgba = Vec::new(); | ||
| rgba.try_reserve_exact(texel_count).ok()?; | ||
| if components == 3 { | ||
| for texel in data[..texel_count * 3].as_chunks::<3>().0 { | ||
| rgba.push([texel[0], texel[1], texel[2], 1.0]); | ||
| } | ||
| } else { | ||
| for &value in &data[..texel_count] { | ||
| rgba.push([value, value, value, 1.0]); | ||
| } | ||
| } | ||
|
|
||
| // Stored data maps display as-is in previews, 2D/3D image views and BaseColor fills, and stay out of HDR environments | ||
| Some(Arc::new(ImageRes::new(width, height, rgba, true))) | ||
| } | ||
|
|
||
| fn same_baked_buffer(previous: &BakedImageEntry, width: u32, height: u32, data: &Arc<Vec<f32>>) -> bool { | ||
| previous.width == width && previous.height == height && previous.source.upgrade().is_some_and(|existing| Arc::ptr_eq(&existing, data)) | ||
| } | ||
|
|
||
| impl Session { | ||
| /// Decoded project image resource names in display order (imported images and baked mesh maps) | ||
| pub fn image_resource_names(&self) -> Vec<String> { | ||
| let names: BTreeSet<&str> = | ||
| self.doc.resources.keys().chain(self.baked_images.keys()).filter(|name| self.images.contains_key(name.as_str())).map(String::as_str).collect(); | ||
| names.into_iter().map(str::to_owned).collect() | ||
| } | ||
|
|
||
| /// Whether `name` is a live resource derived from a baked mesh map | ||
| pub fn is_baked_map_resource(&self, name: &str) -> bool { | ||
| self.baked_images.contains_key(name) | ||
| } | ||
|
|
||
| /// The live resource name of texture set `texture_set`'s baked `map`, if exposed as a resource | ||
| pub fn baked_map_resource_name(&self, texture_set: usize, map: BakedMap) -> Option<&str> { | ||
| self.baked_images.iter().find_map(|(name, entry)| (entry.texture_set == texture_set && entry.map == map).then_some(name.as_str())) | ||
| } | ||
|
|
||
| /// Keep [`Session::images`] and [`Session::baked_images`] synchronized with [`Document::baked`]. | ||
| /// Returns `(removed_or_replaced, added_names, changed_names)` for cache invalidation. | ||
| pub(crate) fn sync_baked_images(&mut self) -> (bool, Vec<String>, HashSet<String>) { | ||
| let desired = baked_map_names(&self.doc); | ||
| let mut next_entries = BTreeMap::new(); | ||
| let mut next_images = Vec::new(); | ||
| let mut removed_or_replaced = false; | ||
| let mut added = Vec::new(); | ||
| let mut changed = HashSet::new(); | ||
|
|
||
| for (name, texture_set, map) in desired { | ||
| let Some(baked) = self.doc.baked.get(&texture_set) else { continue }; | ||
| let Some(data) = baked.maps.get(&map) else { continue }; | ||
| let height = baked.height(map); | ||
|
|
||
| if let Some(previous) = self.baked_images.get(&name) | ||
| && same_baked_buffer(previous, baked.resolution, height, data) | ||
| && self.images.contains_key(&name) | ||
| { | ||
| next_entries.insert(name, previous.clone()); | ||
| continue; | ||
| } | ||
|
|
||
| // Reuse the decoded buffer when a texture set rename moved the same baked map under a new name | ||
| let moved_image = self.baked_images.iter().find_map(|(old_name, previous)| { | ||
| same_baked_buffer(previous, baked.resolution, height, data).then(|| self.images.get(old_name).cloned()).flatten() | ||
| }); | ||
| let image = match moved_image { | ||
| Some(existing) => Some(existing), | ||
| None => baked_map_to_image(baked.resolution, height, map.components(), data), | ||
| }; | ||
| let Some(image) = image else { | ||
| self.log.warn(crate::log::LIBRARY_SOURCE, format!("baked map resource {name}: out of memory")); | ||
| continue; | ||
| }; | ||
|
|
||
| if self.baked_images.contains_key(&name) { | ||
| removed_or_replaced = true; | ||
| } else { | ||
| added.push(name.clone()); | ||
| } | ||
| changed.insert(name.clone()); | ||
|
|
||
| next_entries.insert( | ||
| name.clone(), | ||
| BakedImageEntry { | ||
| texture_set, | ||
| map, | ||
| width: baked.resolution, | ||
| height, | ||
| bytes: data.len().saturating_mul(std::mem::size_of::<f32>()), | ||
| source: Arc::downgrade(data), | ||
| }, | ||
| ); | ||
| next_images.push((name, image)); | ||
| } | ||
|
|
||
| // Drop stale baked entries without removing user resources stored in `doc.resources` | ||
| for old_name in self.baked_images.keys() { | ||
| if !next_entries.contains_key(old_name) { | ||
| removed_or_replaced = true; | ||
| changed.insert(old_name.clone()); | ||
| if !self.doc.resources.contains_key(old_name) { | ||
| self.images.remove(old_name); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| for (name, image) in next_images { | ||
| self.images.insert(name, image); | ||
| } | ||
|
|
||
| self.baked_images = next_entries; | ||
| (removed_or_replaced, added, changed) | ||
| } | ||
|
|
||
| /// Point tool image selections at the renamed baked map resource after a texture set rename or its undo/redo | ||
| pub(crate) fn follow_renamed_baked_resources(&mut self, other: &Document) { | ||
| let names: Vec<String> = self.tool_images_mut().map(|name| name.clone()).collect(); | ||
| let missing: Vec<String> = names.into_iter().filter(|name| !self.doc.resources.contains_key(name) && !self.baked_images.contains_key(name)).collect(); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Follow map identity when an old name remains occupied. Start with sets This filter excludes the selection because Resolve each captured selection through its previous
|
||
| if missing.is_empty() { | ||
| return; | ||
| } | ||
|
|
||
| let previous_names = baked_map_names(other); | ||
| let mut renames = Vec::new(); | ||
| for name in missing { | ||
| let Some((_, texture_set, map)) = previous_names.iter().find(|(old_name, _, _)| *old_name == name) else { continue }; | ||
| let Some(previous_data) = other.baked.get(texture_set).and_then(|baked| baked.maps.get(map)) else { continue }; | ||
| let Some(current_data) = self.doc.baked.get(texture_set).and_then(|baked| baked.maps.get(map)) else { continue }; | ||
| if Arc::ptr_eq(previous_data, current_data) | ||
| && let Some(new_name) = self.baked_map_resource_name(*texture_set, *map) | ||
| { | ||
| renames.push((name, new_name.to_owned())); | ||
| } | ||
| } | ||
|
|
||
| for (old_name, new_name) in renames { | ||
| for tool_image in self.tool_images_mut().filter(|tool_image| **tool_image == old_name) { | ||
| tool_image.clone_from(&new_name); | ||
| } | ||
| } | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Preserve baked-map references when collision names change.
If imported
Set_idexists before baking, the baked map gets2_Set_id. A fill can then select2_Set_id.If
resource.removeremoves importedSet_id, this synchronization renames the baked map toSet_idand removes2_Set_id. The fill still names2_Set_id, so it loses access to the existing bake.Reconcile project references whenever generated names change. The reference update in
textureSet.renamedoes not cover resource removal.