Auto: Integrate mesh replacement from latest main

This commit is contained in:
chasse20 committed 2026-11-15 19:44:18 +00:00
commit ce96c243a1
10 files changed
+275 -5

No files matched your search

+110
View File
@@ -37,6 +37,15 @@ pub fn specs() -> Vec<CommandSpec> {
always,
reimport
),
cmd!(
"file.changeMesh",
"Change mesh",
[],
None,
"{path: the new mesh file, preserveStrokes?: bool (painted pixels follow the surface where the UVs differ; default true)} → {preserved?: texels re-projected}. Keeps layers, texture sets and settings; texture sets map to the new mesh by material index",
always,
change_mesh
),
cmd!(
"file.exportTextures",
"Export textures",
@@ -438,6 +447,16 @@ fn reimport(s: &mut Session, p: &Value) -> Result<Value> {
Ok(reply)
}
#[cfg(not(target_arch = "wasm32"))]
fn change_mesh(s: &mut Session, p: &Value) -> Result<Value> {
let path = native::path_param(p, "path", "file.changeMesh")?;
let file = native::read_mesh("file.changeMesh", path)?;
let reply = s.reimport_mesh(Some(file), crate::commands::boolp(p, "preserveStrokes").unwrap_or(true))?;
// Only after the swap succeeded: Reimport mesh and Save keep following the new file.
s.doc.project.mesh_path = native::absolute(path);
Ok(reply)
}
#[cfg(not(target_arch = "wasm32"))]
impl Session {
/// The file the mesh was imported from, when it is still there: what Reimport mesh reads again.
@@ -471,6 +490,19 @@ impl Session {
let mut next = Session::new(doc, mesh, source)?;
next.log.extend(warnings);
next.path = self.path.clone();
next.sync_images();
// The high polys and the skew map stay. The cage is sampled by triangle index and
// barycentrics, so it stays only for an identical mesh; the low poly's base colours are
// read again from the new mesh.
next.bake_meshes = self.bake_meshes.clone();
next.bake_meshes.low_base_color = Default::default();
if next.bake_meshes.cage.is_some() && *next.mesh != *self.mesh {
next.bake_meshes.cage = None;
next.log.push("the cage mesh was dropped: the low-poly mesh changed".into());
}
if self.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_core::BakePaintTarget::Skew) && self.source.uvs != next.source.uvs {
next.log.push("the skew map is laid over the old UV layout; check it in Bake mode".into());
}
next.modified = true;
next.project_id = self.project_id;
let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next));
@@ -621,6 +653,8 @@ use unsupported as save_copy;
#[cfg(target_arch = "wasm32")]
use unsupported as reimport;
#[cfg(target_arch = "wasm32")]
use unsupported as change_mesh;
#[cfg(target_arch = "wasm32")]
use unsupported as export_textures;
#[cfg(target_arch = "wasm32")]
use unsupported as export_mesh;
@@ -764,6 +798,82 @@ f 1/1 2/2 3/3
let _ = std::fs::remove_dir_all(&dir);
}
/// A project built on one mesh moves to another mesh file with its layers intact, even when
/// it carries its own copy of the mesh (a plain reimport would only re-read that copy).
#[test]
fn change_mesh_swaps_the_mesh_and_keeps_the_layers() {
let dir = std::env::temp_dir().join(format!("tc_change_mesh_{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let quad = dir.join("quad.obj");
std::fs::write(&quad, "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n").unwrap();
let tri = dir.join("tri.obj");
std::fs::write(&tri, "v 0 0 0\nv 1 0 0\nv 0 1 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("quad.obj", &std::fs::read(&quad).unwrap(), 128, "quad").unwrap();
crate::execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap();
let layers = s.doc.project.layers.len();
assert!(crate::execute(&mut s, "file.changeMesh", &json!({})).is_err(), "a path is required");
crate::execute(&mut s, "file.changeMesh", &json!({"path": tri.display().to_string()})).unwrap();
assert_eq!(s.mesh.triangle_count(), 1, "the new mesh is in use");
assert_eq!(s.doc.project.mesh_file, "tri.obj");
assert_eq!(s.doc.project.layers.len(), layers, "the layers stay");
std::fs::remove_dir_all(&dir).ok();
}
/// Open A, change to B, edit B on disk: Reimport mesh (also after save and reopen) must read B,
/// not A. A failed change leaves the remembered path alone.
#[test]
fn change_mesh_remembers_the_new_file_for_reimport() {
let dir = std::env::temp_dir().join(format!("tc_change_mesh_path_{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let obj = |x: f32| format!("v 0 0 0\nv {x} 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n");
let (a, b) = (dir.join("a.obj"), dir.join("b.obj"));
std::fs::write(&a, obj(1.0)).unwrap();
std::fs::write(&b, obj(2.0)).unwrap();
let width = |s: &Session| s.mesh.positions.iter().map(|p| p.x).fold(0.0_f32, f32::max);
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
crate::execute(&mut s, "file.new", &json!({"mesh": a.display().to_string(), "resolution": 128})).unwrap();
let a_abs = s.remembered_mesh_path().map(str::to_string).unwrap();
// A failed change (unreadable file) keeps A.
let missing = dir.join("missing.obj");
assert!(crate::execute(&mut s, "file.changeMesh", &json!({"path": missing.display().to_string()})).is_err());
assert_eq!(s.remembered_mesh_path(), Some(a_abs.as_str()));
crate::execute(&mut s, "file.changeMesh", &json!({"path": b.display().to_string()})).unwrap();
assert_eq!(width(&s), 2.0);
let b_abs = s.remembered_mesh_path().map(str::to_string).expect("B is remembered");
assert_ne!(a_abs, b_abs);
// The remembered path survives save and reopen.
let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
assert_eq!(reopened.remembered_mesh_path(), Some(b_abs.as_str()));
// Edit B, then Reimport from the remembered path: B's edits arrive, not A.
std::fs::write(&b, obj(3.0)).unwrap();
let remembered = reopened.remembered_mesh_path().map(str::to_string).unwrap();
crate::execute(&mut reopened, "file.reimportMesh", &json!({"path": remembered})).unwrap();
assert_eq!(width(&reopened), 3.0);
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn change_mesh_resets_base_colours_and_drops_a_cage_of_another_mesh() {
let dir = std::env::temp_dir().join(format!("tc_change_mesh_cage_{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let a = dir.join("a.obj");
std::fs::write(&a, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap();
// Same triangle count, other vertices.
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(), bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() };
s.bake_meshes.cage = Some(cage);
let _ = s.bake_meshes.low_base_color.set(Err("old".into()));
// The same mesh again keeps the cage but not the cached colours.
crate::execute(&mut s, "file.changeMesh", &json!({"path": a.display().to_string()})).unwrap();
assert!(s.bake_meshes.cage.is_some());
assert!(s.bake_meshes.low_base_color.get().is_none(), "the colours are read again");
crate::execute(&mut s, "file.changeMesh", &json!({"path": b.display().to_string()})).unwrap();
assert!(s.bake_meshes.cage.is_none(), "the cage was made for another mesh");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn unnamed_parts_keep_their_names_and_masks_through_save_and_reopen() {
// A GLB quad whose mesh and node have no name: its one part is named after the file.
+65 -2
View File
@@ -16,8 +16,14 @@ use crate::Session;
const REACH: f32 = 0.05;
/// Re-project the painted pixels of `next` (a session on the reimported mesh holding `old`'s
/// document) from `old`'s UV layout. Returns how many texels found the old surface.
/// document) from `old`'s UV layout. Returns how many texels found the old surface;
/// a texture set where none does keeps its pixels as they are. Nothing is re-projected when the
/// UV layout and topology are unchanged (same triangles, materials and UVs): the pixels already
/// sit where they belong, however far the mesh moved.
pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize {
if same_layout(&old.mesh, &next.mesh) {
return 0;
}
let reach = REACH * 2.0 * old.mesh.radius().max(next.mesh.radius());
let mut found = 0;
for ts in 0..next.set_count() {
@@ -52,7 +58,12 @@ pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize {
((tx, ty), src)
})
.collect();
found += table.values().flatten().filter(|p| p[0].is_finite()).count();
let matched = table.values().flatten().filter(|p| p[0].is_finite()).count();
found += matched;
// No old surface within reach anywhere (a moved or unrelated mesh): the paint stays where it is.
if matched == 0 {
continue;
}
let map = |x: f32, y: f32| {
let (xi, yi) = (x as u32, y as u32);
table.get(&(xi / TILE, yi / TILE)).and_then(|t| t.get(((yi % TILE) * TILE + xi % TILE) as usize)).filter(|p| p[0].is_finite()).map(|p| (p[0], p[1]))
@@ -63,6 +74,12 @@ pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize {
found
}
/// Same index buffer, same UVs per vertex and the same material ranges.
fn same_layout(a: &texturecraft_geom::Mesh, b: &texturecraft_geom::Mesh) -> bool {
let ranges = |m: &texturecraft_geom::Mesh| m.submeshes.iter().map(|s| (s.material, s.start, s.count)).collect::<Vec<_>>();
a.indices == b.indices && a.uvs == b.uvs && ranges(a) == ranges(b)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -104,4 +121,50 @@ mod tests {
}
assert!(right > 10_000 && wrong == 0, "{right} right, {wrong} wrong");
}
#[test]
fn a_mesh_with_no_surface_in_reach_keeps_the_paint_where_it_is() {
let mut s = Session::new_project("p", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap();
let id = s.doc.project.texture_sets[0].stack[0];
let img = s.doc.pixels.layer_mut(id, Channel::BaseColor, (128, 128));
for x in 0..64 {
img.set(x, 40, &[65535, 0, 0, 65535]);
}
// The same plane far away and with mirrored UVs (so the layout differs and the unchanged-layout
// shortcut is not taken): nothing of the old surface is within reach.
let mut mesh = (*s.mesh).clone();
for p in &mut mesh.positions {
p.x += 100.0;
}
for uv in &mut mesh.uvs {
*uv = Vec2::new(1.0 - uv.x, uv.y);
}
let mut next = Session::new(s.doc.clone(), mesh, None).unwrap();
assert_eq!(preserve_strokes(&s, &mut next), 0);
let img = next.doc.pixels.layer(id, Channel::BaseColor).unwrap();
assert_eq!(img.get(10, 40)[3], 65535, "the painted texel is still there");
}
#[test]
fn a_translated_mesh_with_the_same_uvs_keeps_every_pixel() {
let mut s = Session::new_project("p", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap();
let id = s.doc.project.texture_sets[0].stack[0];
let img = s.doc.pixels.layer_mut(id, Channel::BaseColor, (128, 128));
for x in 0..128 {
img.set(x, 40, &[65535, 0, 0, 65535]);
}
// Slid along its own surface by a fraction of the plane: half of it still overlaps the old one.
let mut mesh = (*s.mesh).clone();
let shift = mesh.radius() * 0.5;
for p in &mut mesh.positions {
p.x += shift;
}
let mut next = Session::new(s.doc.clone(), mesh, None).unwrap();
assert_eq!(preserve_strokes(&s, &mut next), 0);
let img = next.doc.pixels.layer(id, Channel::BaseColor).unwrap();
for x in 0..128 {
assert_eq!(img.get(x, 40)[3], 65535, "texel {x} of the painted row moved");
assert_eq!(img.get(x, 41)[3], 0, "texel {x} of the next row got paint");
}
}
}
+39
View File
@@ -612,3 +612,42 @@ fn a_failed_multi_set_bake_restores_settings_pixels_and_history() {
assert_eq!(session.doc.baked, original.baked);
assert_eq!(session.history_labels(), history);
}
/// `file.changeMesh` swaps the mesh under a baked project: the high poly and the skew map stay,
/// the project counts as changed, and image resources are decoded in the new session.
#[test]
fn changing_the_mesh_keeps_the_bake_setup_and_marks_the_project_changed() {
let mut s = plane_session();
let plane = s.mesh.as_ref().clone();
let high = temp_file("change_high.obj", &obj(&plane, 0.002, f32::MAX, [1.0; 3]));
execute(&mut s, "bake.highPoly.add", &json!({ "path": high })).unwrap();
execute(&mut s, "bake.skew.set", &json!({ "value": 1.0 })).unwrap();
// 1x1 PNG as an image resource.
let png = [
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08,
0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xf8, 0xcf, 0xc0, 0xf0, 0x1f, 0x00,
0x05, 0x00, 0x01, 0xff, 0x89, 0x99, 0x3d, 0x1d, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
];
s.import_resource_bytes("dot.png", png.to_vec()).unwrap();
s.modified = false;
let mesh_id = s.mesh_id;
let mut low = String::new();
for p in &plane.positions {
low += &format!("v {} {} {}\n", p.x, p.y, p.z);
}
for uv in &plane.uvs {
low += &format!("vt {} {}\n", uv.x, 1.0 - uv.y);
}
for t in plane.indices.as_chunks::<3>().0 {
low += &format!("f {a}/{a} {b}/{b} {c}/{c}\n", a = t[0] + 1, b = t[1] + 1, c = t[2] + 1);
}
let low = temp_file("change_low.obj", &low);
execute(&mut s, "file.changeMesh", &json!({ "path": low })).unwrap();
assert_ne!(s.mesh_id, mesh_id, "the session is on a new mesh");
assert_eq!(s.bake_meshes.high.len(), 1, "the high poly stays");
assert!(s.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_engine::core::BakePaintTarget::Skew), "the skew map stays");
assert!(s.modified, "the project differs from the saved one");
assert_eq!(s.images.len(), 1, "image resources are decoded in the new session");
}
+2
View File
@@ -5,4 +5,6 @@ pub struct BakeJob {
pub queue: Vec<usize>,
pub current: Option<RunningBake>,
pub total: usize,
/// The mesh the job was started on: a result for another mesh (changed or reimported meanwhile) is not applied.
pub mesh_id: u64,
}
+10 -1
View File
@@ -328,7 +328,7 @@ impl TextureCraftApp {
}
let total = sets.len();
self.bake = Some(BakeJob { queue: sets, current: None, total });
self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id });
}
/// Re-cook MaterialCraft material layer `layer` in the background. While one cook of the layer
@@ -394,6 +394,15 @@ impl TextureCraftApp {
return;
};
if job.mesh_id != self.session.mesh_id {
// The mesh was swapped under the job: stop it and drop its result.
if let Some(running) = &job.current {
running.progress.cancel.store(true, Ordering::Relaxed);
}
self.bake = None;
return;
}
ctx.request_repaint_after(std::time::Duration::from_millis(50));
if let Some(running) = &job.current {
let set_index = running.set_index;
+1 -1
View File
@@ -263,7 +263,7 @@ mod tests {
assert!(!safe_to_close(h.state()), "unsaved changes");
h.state_mut().session.modified = false;
h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0 });
h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0, mesh_id: 0 });
assert!(!safe_to_close(h.state()), "a bake");
h.state_mut().bake = None;
+2
View File
@@ -125,9 +125,11 @@ fn a_ready_result_waits_for_the_map_stream_to_close() {
result_sender.send(Ok(output)).unwrap();
let app = harness.state_mut();
app.start_bake(vec![0]);
let mesh_id = app.session.mesh_id;
app.bake = Some(BakeJob {
queue: Vec::new(),
total: 1,
mesh_id,
current: Some(RunningBake {
set_index: 0,
progress: Arc::new(Progress::new()),
+43
View File
@@ -0,0 +1,43 @@
//! A bake job belongs to the mesh it started on: when `file.changeMesh` (or a reimport) swaps
//! the mesh meanwhile, the job is cancelled and its result is dropped.
use std::sync::Arc;
use std::sync::atomic::Ordering;
use egui_kittest::Harness;
use texturecraft_engine::bake::Progress;
use texturecraft_ui_egui::{BakeJob, RunningBake, TextureCraftApp};
/// An app with a running bake job (its worker never answers) started on mesh `mesh_id`.
fn harness_with_job(mesh_id: impl FnOnce(u64) -> u64) -> (Harness<'static, TextureCraftApp>, Arc<Progress>) {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
let progress = Arc::new(Progress::new());
let (tx, receiver) = std::sync::mpsc::channel();
let (maps_tx, maps) = std::sync::mpsc::channel();
let id = mesh_id(h.state().session.mesh_id);
// Leak the sender so the channel stays empty instead of closed.
std::mem::forget(tx);
std::mem::forget(maps_tx);
let running =
RunningBake { set_index: 0, progress: progress.clone(), receiver, maps, maps_done: Arc::new(std::sync::atomic::AtomicUsize::new(0)), maps_total: 1 };
h.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: id });
(h, progress)
}
#[test]
fn a_job_on_a_swapped_mesh_is_cancelled_and_dropped() {
let (mut h, progress) = harness_with_job(|current| current + 1);
h.step();
assert!(h.state().bake.is_none(), "the job is dropped");
assert!(progress.cancel.load(Ordering::Relaxed), "and its worker is told to stop");
}
#[test]
fn a_job_on_the_current_mesh_keeps_running() {
let (mut h, progress) = harness_with_job(|current| current);
h.step();
assert!(h.state().bake.is_some(), "the job stays");
assert!(!progress.cancel.load(Ordering::Relaxed));
}
+1
View File
@@ -1,6 +1,7 @@
//! One integration-test executable avoids linking the same dependencies for every feature.
//! Keep feature tests in their own modules; the standalone ui_snapshots.rs target remains available.
mod bake_job_mesh;
mod bake_mode;
mod brush_drag;
mod brush_section_reset;
+2 -1
View File
@@ -80,7 +80,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
- **Open** glTF/GLB, FBX (binary and ASCII), COLLADA, **USD** (usda, usdc, usdz), **Alembic**,
OBJ, PLY and STL, or a built-in mesh; UVs are generated when a mesh has none. A `.gltf`'s buffers
and images and a loose USD layer's textures are read from its folder and kept in the project.
Reimport a changed mesh and your painted strokes stay on the surface.
Reimport a changed mesh and your painted strokes stay on the surface. The
`file.changeMesh` command (trusted local command API and the control channel) moves the project onto a different mesh file and keeps its layers.
- **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile (blurs,
other filters and height-to-normal slopes keep their size in UV space at any tile resolution)
and one texture per tile on export (`$udim`).