diff --git a/Cargo.lock b/Cargo.lock
index 65420d3c..19c65129 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -578,7 +578,7 @@ dependencies = [
"maybe-owned",
"rustix 1.1.5",
"rustix-linux-procfs",
- "windows-sys 0.60.2",
+ "windows-sys 0.61.2",
"winx",
]
@@ -1319,7 +1319,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
- "windows-sys 0.60.2",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -2542,7 +2542,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"png",
"thiserror 2.0.21",
- "windows-sys 0.60.2",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -2640,6 +2640,15 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "ntapi"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae"
+dependencies = [
+ "winapi",
+]
+
[[package]]
name = "num-complex"
version = "0.4.6"
@@ -2858,6 +2867,16 @@ dependencies = [
"objc2-core-foundation",
]
+[[package]]
+name = "objc2-io-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15"
+dependencies = [
+ "libc",
+ "objc2-core-foundation",
+]
+
[[package]]
name = "objc2-io-surface"
version = "0.3.2"
@@ -3047,7 +3066,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
- "windows-sys 0.60.2",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -3691,7 +3710,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
- "windows-sys 0.60.2",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -3758,7 +3777,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
- "windows-sys 0.60.2",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -4111,7 +4130,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
dependencies = [
"libc",
- "windows-sys 0.60.2",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -4192,6 +4211,20 @@ dependencies = [
"web-sys",
]
+[[package]]
+name = "sysinfo"
+version = "0.40.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e8a3edbe0394ce115f3917a00349dd242be09eb5a091ed509eaf67b55cfb8a8"
+dependencies = [
+ "libc",
+ "memchr",
+ "ntapi",
+ "objc2-core-foundation",
+ "objc2-io-kit",
+ "windows",
+]
+
[[package]]
name = "tar"
version = "0.4.46"
@@ -4212,7 +4245,7 @@ dependencies = [
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.5",
- "windows-sys 0.60.2",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -4226,7 +4259,7 @@ dependencies = [
[[package]]
name = "texturecraft"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"craft-menu",
"craft-update",
@@ -4247,7 +4280,7 @@ dependencies = [
[[package]]
name = "texturecraft-automation"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"base64 0.22.1",
"cap-std",
@@ -4268,7 +4301,7 @@ dependencies = [
[[package]]
name = "texturecraft-bake"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"bytemuck",
"rayon",
@@ -4280,7 +4313,7 @@ dependencies = [
[[package]]
name = "texturecraft-cli"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"image",
"serde_json",
@@ -4292,7 +4325,7 @@ dependencies = [
[[package]]
name = "texturecraft-compose"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"half",
"rayon",
@@ -4303,7 +4336,7 @@ dependencies = [
[[package]]
name = "texturecraft-core"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"serde",
"serde_json",
@@ -4312,7 +4345,7 @@ dependencies = [
[[package]]
name = "texturecraft-engine"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"epaint_default_fonts",
"image",
@@ -4332,7 +4365,7 @@ dependencies = [
[[package]]
name = "texturecraft-formats"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"base64 0.22.1",
"exr",
@@ -4345,6 +4378,7 @@ dependencies = [
"rayon",
"serde",
"serde_json",
+ "sysinfo",
"texturecraft-compose",
"texturecraft-core",
"texturecraft-geom",
@@ -4356,7 +4390,7 @@ dependencies = [
[[package]]
name = "texturecraft-geom"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"glam 0.30.10",
"mikktspace",
@@ -4367,7 +4401,7 @@ dependencies = [
[[package]]
name = "texturecraft-paint"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"epaint_default_fonts",
"harfrust",
@@ -4382,7 +4416,7 @@ dependencies = [
[[package]]
name = "texturecraft-render"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"bytemuck",
"half",
@@ -4401,11 +4435,11 @@ dependencies = [
[[package]]
name = "texturecraft-texel"
-version = "0.5.0"
+version = "0.6.0"
[[package]]
name = "texturecraft-ui-egui"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"base64 0.22.1",
"craft-dialogs",
@@ -4421,6 +4455,7 @@ dependencies = [
"image",
"js-sys",
"log",
+ "pollster 0.4.0",
"rayon",
"rfd",
"serde",
@@ -4438,7 +4473,7 @@ dependencies = [
[[package]]
name = "texturecraft-web"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"eframe",
"js-sys",
@@ -4730,7 +4765,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
dependencies = [
"memoffset",
"tempfile",
- "windows-sys 0.60.2",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -5303,15 +5338,37 @@ dependencies = [
"web-sys",
]
+[[package]]
+name = "winapi"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
+dependencies = [
+ "winapi-i686-pc-windows-gnu",
+ "winapi-x86_64-pc-windows-gnu",
+]
+
+[[package]]
+name = "winapi-i686-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
+
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
- "windows-sys 0.60.2",
+ "windows-sys 0.61.2",
]
+[[package]]
+name = "winapi-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+
[[package]]
name = "windows"
version = "0.62.2"
@@ -5808,7 +5865,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "xtask"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"serde_json",
]
diff --git a/Cargo.toml b/Cargo.toml
index c2846157..b67d119b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -5,7 +5,7 @@ exclude = ["vendor"]
default-members = ["crates/core", "crates/texel", "crates/geom", "crates/compose", "crates/bake", "crates/formats", "crates/paint", "crates/engine", "crates/render", "crates/automation", "crates/ui-egui", "apps/texturecraft", "apps/texturecraft-cli", "xtask"]
[workspace.package]
-version = "0.5.0"
+version = "0.6.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -32,6 +32,8 @@ serde_json = "1"
glam = { version = "0.30", features = ["serde", "bytemuck"] }
bytemuck = { version = "1", features = ["derive"] }
rayon = "1"
+# Free RAM, to size how much a project save holds in flight.
+sysinfo = { version = "0.40", default-features = false, features = ["system"] }
# Text alphas: shaping and glyph outlines, the versions egui's text layout already builds.
harfrust = "0.12"
skrifa = { version = "0.44", default-features = false, features = ["std"] }
diff --git a/README.md b/README.md
index 80f807b6..69cd720c 100644
--- a/README.md
+++ b/README.md
@@ -32,6 +32,7 @@
+
diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs
index 4965c438..2deac956 100644
--- a/apps/texturecraft/src/main.rs
+++ b/apps/texturecraft/src/main.rs
@@ -121,16 +121,16 @@ fn set_taskbar_icon(w: &winit::window::Window) {
}
}
-/// Settings › Interface › System title bar, read before the window opens from `ui.json`, else as earlier builds saved it; missing or unreadable: off
-fn saved_system_title_bar(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> bool {
+/// Preferences needed before opening the initial project or window, with legacy storage fallback.
+fn saved_prefs(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> texturecraft_ui_egui::state::Prefs {
if let Some(ui) = ui_file.and_then(ui_state_store::read) {
- return ui.prefs.system_title_bar;
+ return ui.prefs;
}
let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("app.ron")));
let saved = file.and_then(|file| std::fs::read_to_string(file).ok());
let entries = saved.and_then(|text| ron::from_str::>(&text).ok());
- entries.and_then(|entries| ron::from_str::(entries.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar)
+ entries.and_then(|entries| ron::from_str::(entries.get("ui")?).ok()).map(|ui| ui.prefs).unwrap_or_default()
}
/// The app with the window chrome that needs the native window: the Windows borderless guard, and
@@ -197,7 +197,6 @@ fn main() {
fatal(&format!("internal error: {info}"), std::thread::current().name() == Some("main"));
prev(info);
}));
- let session = initial_session(&args);
// Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS to keep the user's saved settings untouched: state goes to throwaway files
let persistence_path =
std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id())));
@@ -206,7 +205,10 @@ fn main() {
if let Some(file) = &ui_file {
let _ = ui_state_store::FILE.set(file.clone());
}
- let title_bar = TitleBar::decide(saved_system_title_bar(ui_file.as_deref(), persistence_path.as_deref()));
+ let prefs = saved_prefs(ui_file.as_deref(), persistence_path.as_deref());
+ prefs.apply_resource_limits();
+ let session = initial_session(&args);
+ let title_bar = TitleBar::decide(prefs.system_title_bar);
let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size(DEFAULT_SIZE).with_min_inner_size(MIN_SIZE);
if let Some(i) = icon() {
viewport = viewport.with_icon(i);
@@ -331,27 +333,36 @@ mod tests {
}
#[test]
- fn the_system_title_bar_setting_is_read_from_ui_json_else_as_earlier_builds_saved_it() {
+ fn startup_preferences_use_ui_json_then_legacy_storage_then_defaults() {
let ron_path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id()));
let json_path = ron_path.with_extension("json");
for on in [false, true] {
let mut ui = UiState::default();
ui.prefs.system_title_bar = on;
+ ui.prefs.project_open_limit_gib = 16;
+
// Written as eframe writes it: a pretty RON map of RON strings
let kv = std::collections::HashMap::from([("ui".to_string(), ron::to_string(&ui).unwrap())]);
std::fs::write(&ron_path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap();
- assert_eq!(saved_system_title_bar(None, Some(&ron_path)), on);
+
+ let legacy = saved_prefs(None, Some(&ron_path));
+ assert_eq!(legacy.system_title_bar, on);
+ assert_eq!(legacy.project_open_limit_gib, 16);
ui.prefs.system_title_bar = !on;
+ ui.prefs.project_open_limit_gib = 32;
std::fs::write(&json_path, serde_json::to_vec(&ui).unwrap()).unwrap();
- assert_eq!(saved_system_title_bar(Some(&json_path), Some(&ron_path)), !on, "ui.json comes first");
+
+ let current = saved_prefs(Some(&json_path), Some(&ron_path));
+ assert_eq!(current.system_title_bar, !on, "ui.json comes first");
+ assert_eq!(current.project_open_limit_gib, 32);
}
std::fs::write(&json_path, "not json").unwrap();
std::fs::write(&ron_path, "not ron").unwrap();
- assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path)));
+ assert_eq!(saved_prefs(Some(&json_path), Some(&ron_path)), texturecraft_ui_egui::state::Prefs::default());
std::fs::remove_file(&json_path).unwrap();
std::fs::remove_file(&ron_path).unwrap();
- assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path)));
+ assert_eq!(saved_prefs(Some(&json_path), Some(&ron_path)), texturecraft_ui_egui::state::Prefs::default());
}
}
diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs
index c61fce50..e390c239 100644
--- a/crates/automation/src/render.rs
+++ b/crates/automation/src/render.rs
@@ -85,7 +85,15 @@ impl Gpu {
/// Render `s` with `kind` at `size` through `camera`; RGBA8 (sRGB) pixels.
pub fn render(&mut self, s: &mut Session, kind: ViewKind, size: [u32; 2], camera: texturecraft_engine::geom::OrbitCamera) -> Option<(u32, u32, Vec)> {
self.sync(s);
- let frame = Frame { view_id: 1, size, kind, camera, shade: shade(s), visible: s.doc.project.texture_sets.iter().map(|t| t.visible).collect() };
+ let frame = Frame {
+ view_id: 1,
+ size,
+ kind,
+ camera,
+ shade: shade(s),
+ visible: s.doc.project.texture_sets.iter().map(|t| t.visible).collect(),
+ overlay: Vec::new(),
+ };
self.h.render(&frame)
}
diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs
index 0f5e6ab5..63c12b0e 100644
--- a/crates/automation/src/security.rs
+++ b/crates/automation/src/security.rs
@@ -178,8 +178,11 @@ pub struct ConnectionLimiter(Arc);
pub struct Permit(Arc);
impl ConnectionLimiter {
- pub fn try_acquire(&self, max: usize) -> Option {
- self.0.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| (n < max).then_some(n + 1)).ok().map(|_| Permit(self.0.clone()))
+ pub fn try_acquire(&self, max_connections: usize) -> Option {
+ self.0
+ .try_update(Ordering::AcqRel, Ordering::Acquire, |connections| (connections < max_connections).then_some(connections + 1))
+ .ok()
+ .map(|_| Permit(self.0.clone()))
}
}
@@ -328,10 +331,12 @@ mod tests {
#[test]
fn limiter_releases() {
- let l = ConnectionLimiter::default();
- let p = l.try_acquire(1).unwrap();
- assert!(l.try_acquire(1).is_none());
- drop(p);
- assert!(l.try_acquire(1).is_some());
+ let limiter = ConnectionLimiter::default();
+
+ let permit = limiter.try_acquire(1).unwrap();
+ assert!(limiter.try_acquire(1).is_none());
+
+ drop(permit);
+ assert!(limiter.try_acquire(1).is_some());
}
}
diff --git a/crates/bake/src/cage/high_poly_reach.rs b/crates/bake/src/cage/high_poly_reach.rs
index f957ce49..2f461343 100644
--- a/crates/bake/src/cage/high_poly_reach.rs
+++ b/crates/bake/src/cage/high_poly_reach.rs
@@ -77,20 +77,21 @@ impl HighPolyReach {
/// Each vertex's mesh-name key, from the first triangle that uses it
fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec {
let mut keys = vec![ANY; mesh.positions.len()];
- for (corners, &triangle_key) in mesh.indices.chunks_exact(3).zip(triangle_keys) {
+ for (corners, &triangle_key) in mesh.indices.as_chunks::<3>().0.iter().zip(triangle_keys) {
for &corner in corners {
if let Some(key) = keys.get_mut(corner as usize).filter(|key| **key == ANY) {
*key = triangle_key;
}
}
}
+
keys
}
/// Each vertex's sum of its triangles' winding normals, weighted by area: the side the bake's backface test sees as the front
fn winding_normals(mesh: &Mesh) -> Vec {
let mut normals = vec![Vec3::ZERO; mesh.positions.len()];
- for corners in mesh.indices.chunks_exact(3) {
+ for corners in mesh.indices.as_chunks::<3>().0 {
let position = |corner: u32| mesh.positions.get(corner as usize).copied().unwrap_or(Vec3::ZERO);
let winding_normal = (position(corners[1]) - position(corners[0])).cross(position(corners[2]) - position(corners[0]));
for &corner in corners {
@@ -99,5 +100,6 @@ fn winding_normals(mesh: &Mesh) -> Vec {
}
}
}
+
normals
}
diff --git a/crates/bake/src/test/high_poly_reach.rs b/crates/bake/src/test/high_poly_reach.rs
index e6d66d07..8a4f83c4 100644
--- a/crates/bake/src/test/high_poly_reach.rs
+++ b/crates/bake/src/test/high_poly_reach.rs
@@ -23,7 +23,7 @@ fn bumpy_high_poly() -> (Mesh, Vec) {
let mut flipped = vec![false; mesh.positions.len()];
let mut unflipped = vec![false; mesh.positions.len()];
- for corners in mesh.indices.chunks_exact_mut(3) {
+ for corners in mesh.indices.as_chunks_mut::<3>().0 {
let center_x = corners.iter().map(|&corner| mesh.positions[corner as usize].x).sum::() / 3.0;
if center_x > FLIPPED_FROM_X {
corners.swap(1, 2);
@@ -32,6 +32,7 @@ fn bumpy_high_poly() -> (Mesh, Vec) {
if center_x > FLIPPED_FROM_X { flipped[corner as usize] = true } else { unflipped[corner as usize] = true }
}
}
+
// Vertices on the border face both ways: neither answer is right for them
let mixed = flipped.iter().zip(&unflipped).map(|(flipped, unflipped)| *flipped && *unflipped).collect();
(mesh, mixed)
diff --git a/crates/bake/src/test/setting.rs b/crates/bake/src/test/setting.rs
index b490655d..668338a7 100644
--- a/crates/bake/src/test/setting.rs
+++ b/crates/bake/src/test/setting.rs
@@ -41,13 +41,18 @@ fn matching_skips_a_closer_unrelated_high_mesh_and_backfaces() {
parameters.cage.relative_to_bounding_box = false;
parameters.maps.height.parameters.normalization = HeightNormalization::Manual;
let height = |parameters: &BakeSettings, high: &Mesh| transfer(&low, high, None, parameters).unwrap().maps[&BakedMap::Height][128];
+
assert!((height(¶meters, &high) - 0.54).abs() < 1e-5);
+
parameters.high_poly.match_mode = MeshMatchMode::ByMeshName;
assert!((height(¶meters, &high) - 0.52).abs() < 1e-5);
- for triangle in high.indices.chunks_exact_mut(3) {
+
+ for triangle in high.indices.as_chunks_mut::<3>().0 {
triangle.swap(1, 2);
}
+
assert_eq!(height(¶meters, &high), 0.5);
+
parameters.high_poly.ignore_backface = false;
assert!((height(¶meters, &high) - 0.52).abs() < 1e-5);
}
@@ -159,12 +164,14 @@ fn position_axis_and_material_bounds_change_only_the_requested_space() {
mesh.append(&distant);
let mut parameters = settings(16, &[BakedMap::Position]);
parameters.maps.position.parameters.axis = PositionAxis::X;
+
let global = run(&mesh, ¶meters).unwrap();
parameters.maps.position.parameters.scale = PositionNormalizationScale::PerMaterial;
let local = run(&mesh, ¶meters).unwrap();
+
assert!(global.maps[&BakedMap::Position].iter().all(|value| *value < 0.2));
assert!(local.maps[&BakedMap::Position].iter().any(|value| *value > 0.9));
- assert!(local.maps[&BakedMap::Position].chunks_exact(3).all(|pixel| pixel[0] == pixel[1] && pixel[1] == pixel[2]));
+ assert!(local.maps[&BakedMap::Position].as_chunks::<3>().0.iter().all(|pixel| pixel[0] == pixel[1] && pixel[1] == pixel[2]));
}
#[test]
diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs
index abfccaac..0c313462 100644
--- a/crates/bake/src/tests.rs
+++ b/crates/bake/src/tests.rs
@@ -100,18 +100,20 @@ fn open_quad_is_unoccluded() {
#[test]
fn inside_of_a_closed_box_is_occluded() {
- let mut m = primitives::cube(2.0);
- for t in m.indices.chunks_exact_mut(3) {
- t.swap(1, 2);
+ let mut mesh = primitives::cube(2.0);
+ for triangle in mesh.indices.as_chunks_mut::<3>().0 {
+ triangle.swap(1, 2);
}
- for n in &mut m.normals {
- *n = -*n;
+ for normal in &mut mesh.normals {
+ *normal = -*normal;
}
- m.compute_tangents();
- let s = with_rays(settings(64, &[BakedMap::AmbientOcclusion]), 64, 4.0);
- let out = run(&m, &s).unwrap();
- let ao = mean(covered_values(&m, &out, BakedMap::AmbientOcclusion).into_iter().map(|v| v.1));
- assert!(ao < 0.3, "{ao}");
+ mesh.compute_tangents();
+ let parameters = with_rays(settings(64, &[BakedMap::AmbientOcclusion]), 64, 4.0);
+
+ let output = run(&mesh, ¶meters).unwrap();
+
+ let mean_occlusion = mean(covered_values(&mesh, &output, BakedMap::AmbientOcclusion).into_iter().map(|v| v.1));
+ assert!(mean_occlusion < 0.3, "{mean_occlusion}");
}
#[test]
diff --git a/crates/compose/src/display.rs b/crates/compose/src/display.rs
index ba4b675e..5ebb667b 100644
--- a/crates/compose/src/display.rs
+++ b/crates/compose/src/display.rs
@@ -93,20 +93,21 @@ fn u8_of(v: u16) -> u8 {
(v >> 8) as u8
}
-/// Tile bytes (`TILE × TILE`, row-major) for `kind` from the composite, or None when the tile is
-/// absent in every source (the GPU texture keeps its cleared default).
-pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u32, ty: u32) -> Vec {
- let bpt = kind.bytes_per_texel();
- let mut out = vec![0u8; TILE_AREA * bpt];
- let lut = srgb_lut();
- let get = |c: Channel| comp.channels.get(&c).and_then(|img| img.tile(tx, ty));
- let res = comp.resolution;
+/// Tile bytes (`TILE × TILE`, row-major) for `kind`, using channel defaults for absent source tiles.
+pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u32, ty: u32) -> Vec {
+ let bytes_per_texel = kind.bytes_per_texel();
+ let mut out = vec![0u8; TILE_AREA * bytes_per_texel];
+ let srgb = srgb_lut();
+ let get = |c: Channel| composite.channels.get(&c).and_then(|img| img.tile(tx, ty));
+ let resolution = composite.resolution;
let default16 = |c: Channel| texturecraft_texel::to_u16(c.default_value()[0]);
- // A scalar channel's texel `i` as 8 bits (its default where the set lacks it).
+
+ // A scalar channel's texel `i` as 8 bits (its default where the set lacks it)
let scalar8 = |c: Channel| {
let (t, d) = (get(c), default16(c));
move |i: usize| u8_of(t.and_then(|t| t.get(i).copied()).unwrap_or(d))
};
+
match kind {
DisplayKind::BaseColor | DisplayKind::Emissive | DisplayKind::Sheen => {
let (c, alpha) = match kind {
@@ -117,81 +118,87 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3
let (src, alpha) = (get(c), scalar8(alpha));
let d = c.default_value().map(|v| (texturecraft_texel::linear_to_srgb(v) * 255.0 + 0.5) as u8);
for i in 0..TILE_AREA {
- let px = &mut out[i * 4..i * 4 + 4];
+ let pixel = &mut out[i * 4..i * 4 + 4];
match src {
Some(s) => {
for k in 0..3 {
- px[k] = lut[(s.get(i * 3 + k).copied().unwrap_or(0) >> 4) as usize];
+ pixel[k] = srgb[(s.get(i * 3 + k).copied().unwrap_or(0) >> 4) as usize];
}
}
- None => px[..3].copy_from_slice(&d),
+ None => pixel[..3].copy_from_slice(&d),
}
- px[3] = alpha(i);
+ pixel[3] = alpha(i);
}
}
DisplayKind::Lobes => {
let lanes = [Channel::CoatWeight, Channel::CoatRoughness, Channel::AnisotropyLevel, Channel::AnisotropyAngle].map(scalar8);
- for (i, px) in out.chunks_exact_mut(4).enumerate() {
- for (d, lane) in px.iter_mut().zip(&lanes) {
+ for (i, pixel) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() {
+ for (d, lane) in pixel.iter_mut().zip(&lanes) {
*d = lane(i);
}
}
}
DisplayKind::Extra => {
let (n, transmission) = (get(Channel::CoatNormal), scalar8(Channel::Transmission));
- // Signed 8-bit around 128 so the flat normal packs exactly.
- let snorm = |v: u16| (128.0 + 127.0 * (v as f32 / 65535.0 * 2.0 - 1.0)).round().clamp(0.0, 255.0) as u8;
- // A TILE never straddles two atlas blocks.
- let scale = (-32.0 * comp.block_scales.at(tx * TILE, ty * TILE).log2()).round().clamp(0.0, 255.0) as u8;
- for (i, px) in out.chunks_exact_mut(4).enumerate() {
- for (k, d) in px.iter_mut().take(2).enumerate() {
- *d = n.and_then(|t| t.get(i * 3 + k)).map_or(128, |v| snorm(*v));
+
+ // Signed 8-bit around 128 so the flat normal packs exactly
+ let pack_signed_normal = |v: u16| (128.0 + 127.0 * (v as f32 / 65535.0 * 2.0 - 1.0)).round().clamp(0.0, 255.0) as u8;
+
+ // A TILE never straddles two atlas blocks
+ let scale = (-32.0 * composite.block_scales.at(tx * TILE, ty * TILE).log2()).round().clamp(0.0, 255.0) as u8;
+ for (i, pixel) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() {
+ for (k, d) in pixel.iter_mut().take(2).enumerate() {
+ *d = n.and_then(|t| t.get(i * 3 + k)).map_or(128, |v| pack_signed_normal(*v));
}
- px[2] = transmission(i);
- px[3] = scale;
+ pixel[2] = transmission(i);
+ pixel[3] = scale;
}
}
DisplayKind::Orm => {
let (ao, m, s) = (get(Channel::AmbientOcclusion), get(Channel::Metallic), get(Channel::SpecularLevel));
- // Specular/glossiness sets: the viewport shades roughness = 1 − glossiness.
- let gloss = comp.channels.contains_key(&Channel::Glossiness);
+
+ // Specular/glossiness sets: the viewport shades roughness = 1 − glossiness
+ let gloss = composite.channels.contains_key(&Channel::Glossiness);
let (r, r_default) =
if gloss { (get(Channel::Glossiness), default16(Channel::Glossiness)) } else { (get(Channel::Roughness), default16(Channel::Roughness)) };
for i in 0..TILE_AREA {
let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE));
- let baked_ao = baked.sample_working(BakedMap::AmbientOcclusion, x, y, (res, comp.height), &comp.block_scales).map_or(1.0, |value| value[0]);
+ let baked_ao = baked
+ .sample_working(BakedMap::AmbientOcclusion, x, y, (resolution, composite.height), &composite.block_scales)
+ .map_or(1.0, |value| value[0]);
let ch_ao = ao.and_then(|a| a.get(i)).map(|v| *v as f32 / 65535.0).unwrap_or(1.0);
- let px = &mut out[i * 4..i * 4 + 4];
- px[0] = ((baked_ao * ch_ao).clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
+ let pixel = &mut out[i * 4..i * 4 + 4];
+ pixel[0] = ((baked_ao * ch_ao).clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
let v = r.and_then(|t| t.get(i).copied()).unwrap_or(r_default);
- px[1] = u8_of(if gloss { 65535 - v } else { v });
- px[2] = u8_of(m.and_then(|t| t.get(i).copied()).unwrap_or(0));
- px[3] = u8_of(s.and_then(|t| t.get(i).copied()).unwrap_or(default16(Channel::SpecularLevel)));
+ pixel[1] = u8_of(if gloss { 65535 - v } else { v });
+ pixel[2] = u8_of(m.and_then(|t| t.get(i).copied()).unwrap_or(0));
+ pixel[3] = u8_of(s.and_then(|t| t.get(i).copied()).unwrap_or(default16(Channel::SpecularLevel)));
}
}
DisplayKind::Normal => {
- let (n, sheen_rough) = (get(Channel::Normal), scalar8(Channel::SheenRoughness));
+ let (n, sheen_roughness) = (get(Channel::Normal), scalar8(Channel::SheenRoughness));
for i in 0..TILE_AREA {
- let px = &mut out[i * 4..i * 4 + 4];
- // The baked normal is the base the painted normal details sit on (as in export).
+ let pixel = &mut out[i * 4..i * 4 + 4];
+
+ // The baked normal is the base the painted normal details sit on (as in export)
let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE));
- let base = baked.sample_working(BakedMap::Normal, x, y, (res, comp.height), &comp.block_scales);
+ let base = baked.sample_working(BakedMap::Normal, x, y, (resolution, composite.height), &composite.block_scales);
match (n, base) {
(Some(t), None) => {
- for (k, d) in px.iter_mut().take(3).enumerate() {
+ for (k, d) in pixel.iter_mut().take(3).enumerate() {
*d = u8_of(t.get(i * 3 + k).copied().unwrap_or(0));
}
}
(detail, Some(base)) => {
let detail = detail.map_or([0.5, 0.5, 1.0], |t| [0, 1, 2].map(|k| t.get(i * 3 + k).map_or(0.0, |v| *v as f32 / 65535.0)));
let v = texturecraft_core::blend::rnm(base, detail);
- for (d, v) in px.iter_mut().zip(v) {
+ for (d, v) in pixel.iter_mut().zip(v) {
*d = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
}
}
- (None, None) => px[..3].copy_from_slice(&[128, 128, 255]),
+ (None, None) => pixel[..3].copy_from_slice(&[128, 128, 255]),
}
- px[3] = sheen_rough(i);
+ pixel[3] = sheen_roughness(i);
}
}
DisplayKind::Height => {
@@ -206,6 +213,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3
}
}
}
+
out
}
diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs
index b43796e8..d3ae712e 100644
--- a/crates/compose/src/eval.rs
+++ b/crates/compose/src/eval.rs
@@ -2,6 +2,8 @@
//! tile by tile in parallel. This is the reference implementation (the oracle) for the viewport
//! and for export.
+pub(crate) mod thumbnail;
+
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
@@ -1173,39 +1175,43 @@ impl<'a, 'b> Texel<'a, 'b> {
w * image.map_or(1.0, |img| img.sample(c.uv.x, c.uv.y)[3].clamp(0.0, 1.0))
}
- fn source(&mut self, s: &Source, proj: &Projection, kind: ChannelKind) -> [f32; 3] {
- match s {
- Source::Uniform(v) => *v,
+ /// The value `source` gives this texel through `projection`, read as a channel of `kind`
+ fn source(&mut self, source: &Source, projection: &Projection, kind: ChannelKind) -> [f32; 3] {
+ match source {
+ Source::Uniform(value) => *value,
Source::Procedural { pattern, low, high } => {
- let (c, proj, _) = self.projected(proj);
- let t = procedural(pattern, proj, &c);
- mix3(*low, *high, t)
+ let (coords, projection, _) = self.projected(projection);
+ let amount = procedural(pattern, projection, &coords);
+ mix3(*low, *high, amount)
}
Source::Image { name, normal_format } => {
- let Some(img) = self.inp.images.get(name) else { return [0.5; 3] };
- let (c, proj, _) = self.projected(proj);
- let mut acc = [0.0f32; 4];
- for (uv, w) in image_samples(proj, &c).into_iter().filter(|(_, w)| *w > 0.0) {
- let s = img.sample(uv.x, uv.y);
- for k in 0..4 {
- acc[k] += s[k] * w;
+ let Some(image) = self.inp.images.get(name) else { return [0.5; 3] };
+
+ let (coords, projection, _) = self.projected(projection);
+ let mut sum = [0.0f32; 4];
+ for (uv, weight) in image_samples(projection, &coords).into_iter().filter(|(_, weight)| *weight > 0.0) {
+ for (total, value) in sum.iter_mut().zip(image.sample(uv.x, uv.y)) {
+ *total += value * weight;
}
}
+
+ let rgb = [sum[0], sum[1], sum[2]];
match kind {
- ChannelKind::Color if img.srgb => [acc[0], acc[1], acc[2]].map(texturecraft_texel::srgb_to_linear),
- // Normal channels are OpenGL (+Y up the image): a DirectX image's green flips.
- ChannelKind::NormalMap if *normal_format == NormalFormat::DirectX => [acc[0], 1.0 - acc[1], acc[2]],
- ChannelKind::Color | ChannelKind::NormalMap => [acc[0], acc[1], acc[2]],
- ChannelKind::Scalar => [acc[0]; 3],
- ChannelKind::Signed => [acc[0] * 2.0 - 1.0; 3],
+ ChannelKind::Color if image.srgb => rgb.map(texturecraft_texel::srgb_to_linear),
+ // Normal channels are OpenGL (+Y up the image): a DirectX image's green flips
+ ChannelKind::NormalMap if *normal_format == NormalFormat::DirectX => [rgb[0], 1.0 - rgb[1], rgb[2]],
+ ChannelKind::Color | ChannelKind::NormalMap => rgb,
+ // A one-value channel or mask reads the image's gray, so a color image works as a mask
+ ChannelKind::Scalar => [lum(rgb); 3],
+ ChannelKind::Signed => [lum(rgb) * 2.0 - 1.0; 3],
}
}
Source::Anchor { anchor, channel } => {
- // An anchor not evaluated yet (above this layer, hidden) reads the channel default.
- let v = self.anchors.iter().rev().find(|(id, _)| id == anchor).and_then(|(_, acc)| acc.get(channel.index()).copied());
- let v = v.unwrap_or_else(|| channel.default_value());
+ // An anchor not evaluated yet (above this layer, hidden) reads the channel default
+ let anchored = self.anchors.iter().rev().find(|(id, _)| id == anchor).and_then(|(_, values)| values.get(channel.index()).copied());
+ let value = anchored.unwrap_or_else(|| channel.default_value());
let gray = matches!(channel.kind(), ChannelKind::Color | ChannelKind::NormalMap) && matches!(kind, ChannelKind::Scalar | ChannelKind::Signed);
- if gray { [lum(v); 3] } else { v }
+ if gray { [lum(value); 3] } else { value }
}
}
}
@@ -2203,60 +2209,67 @@ pub type FlatTile = (Channel, (u32, u32), Vec);
/// Flatten one paint or fill layer: its content (with content effects) times its mask, as
/// premultiplied (value, coverage) tiles per enabled channel, ready to become a plain paint
/// layer. Groups are not supported (None).
-pub fn flatten_layer(inp: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option> {
- let set = inp.project.texture_set(inp.ts).ok()?;
- if inp.project.content_layer(id)?.is_group() {
+pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option> {
+ let set = inputs.project.texture_set(inputs.ts).ok()?;
+ if inputs.project.content_layer(id)?.is_group() {
return None;
}
+
let channels: Vec = set.channel_list();
- // Plan the layer forced visible so hidden layers flatten too.
- let mut solo = inp.project.clone();
+
+ // Plan the layer forced visible so hidden layers flatten too
+ let mut solo = inputs.project.clone();
if let Some(l) = solo.layers.get_mut(&id) {
l.visible = true;
}
- let solo_inp = Inputs { project: &solo, preview: None, block_scales: inp.block_scales.clone(), ..*inp };
- let fields = neighbourhood_fields(&solo_inp, &channels, tiles);
+ let visible_inputs = Inputs { project: &solo, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs };
+ let fields = neighbourhood_fields(&visible_inputs, &channels, tiles);
+
let out: Vec> = tiles
.par_iter()
.map(|&(tx, ty)| {
- let nodes = plan(&solo_inp, &[id], &channels, tx, ty, 0, Some(&fields));
+ let nodes = plan(&visible_inputs, &[id], &channels, tx, ty, 0, Some(&fields));
let Some(n) = nodes.first() else { return Vec::new() };
- let full = anchor_plan(&solo_inp, id, &channels, tx, ty, Some(&fields));
- let mut bufs: Vec<(Channel, Vec, bool)> =
+ let full = anchor_plan(&visible_inputs, id, &channels, tx, ty, Some(&fields));
+ let mut buffers: Vec<(Channel, Vec, bool)> =
n.chans.iter().filter_map(|c| Channel::ALL.get(c.ch).map(|ch| (*ch, vec![0u16; TILE_AREA * (c.comps + 1)], false))).collect();
- for (ch, buf, _) in &mut bufs {
+ for (ch, buffer, _) in &mut buffers {
if ch.kind() == ChannelKind::Signed {
- for px in buf.chunks_exact_mut(2) {
- px[0] = to_u16_signed(0.0);
+ for pixel in buffer.as_chunks_mut::<2>().0 {
+ pixel[0] = to_u16_signed(0.0);
}
}
}
- for (x, y, o) in tile_texels(inp.gbuf, tx, ty) {
- let mut tex = Texel::new(&solo_inp, x, y, o, 0.0);
+
+ for (x, y, o) in tile_texels(inputs.gbuf, tx, ty) {
+ let mut tex = Texel::new(&visible_inputs, x, y, o, 0.0);
if !full.is_empty() {
tex.anchors_below(&full, id);
}
let m = tex.node_mask(n);
- for (c, (ch, buf, any)) in n.chans.iter().zip(bufs.iter_mut()) {
+ for (c, (ch, buffer, any)) in n.chans.iter().zip(buffers.iter_mut()) {
let Some((v, cov)) = tex.content(&n.content, c) else { continue };
let a = (cov * m).clamp(0.0, 1.0);
if a <= 0.0 {
continue;
}
+
*any = true;
let comps = c.comps;
- let Some(px) = buf.get_mut(o * (comps + 1)..(o + 1) * (comps + 1)) else { continue };
- for (slot, pv) in px.iter_mut().zip(v.iter().take(comps)) {
+ let Some(pixel) = buffer.get_mut(o * (comps + 1)..(o + 1) * (comps + 1)) else { continue };
+ for (slot, pv) in pixel.iter_mut().zip(v.iter().take(comps)) {
*slot = if ch.kind() == ChannelKind::Signed { to_u16_signed(pv * a) } else { to_u16(pv * a) };
}
- if let Some(slot) = px.get_mut(comps) {
+ if let Some(slot) = pixel.get_mut(comps) {
*slot = to_u16(a);
}
}
}
- bufs.into_iter().filter(|(_, _, any)| *any).map(|(ch, buf, _)| (ch, (tx, ty), buf)).collect()
+
+ buffers.into_iter().filter(|(_, _, any)| *any).map(|(ch, buffer, _)| (ch, (tx, ty), buffer)).collect()
})
.collect();
+
Some(out.into_iter().flatten().collect())
}
diff --git a/crates/compose/src/eval/thumbnail.rs b/crates/compose/src/eval/thumbnail.rs
new file mode 100644
index 00000000..92290afe
--- /dev/null
+++ b/crates/compose/src/eval/thumbnail.rs
@@ -0,0 +1,30 @@
+//! Isolated folder evaluation with the original stack available for anchor inputs.
+
+use super::{Channel, ChannelKind, Composite, Inputs, LayerId, Texel, all_tiles, neighbourhood_fields, plan, tile_texels, to_u16, to_u16_signed};
+
+/// Composite one layer over channel defaults, keeping anchors from the stack below it.
+pub(crate) fn composite_layer(inputs: &Inputs, layer: LayerId, channel: Channel) -> Option {
+ let set = inputs.project.texture_set(inputs.ts).ok()?;
+ let channels = set.channel_list();
+ let (width, height) = (inputs.gbuf.width, inputs.gbuf.height);
+ let tiles = all_tiles(width, height);
+ let fields = neighbourhood_fields(inputs, &channels, &tiles);
+ let mut composite = Composite::with_size(&[channel], width, height);
+ let output = composite.channels.get_mut(&channel)?;
+
+ for (tile_x, tile_y) in tiles {
+ let nodes = plan(inputs, &[layer], &channels, tile_x, tile_y, 0, Some(&fields));
+ let full_stack = if set.stack.as_slice() == [layer] { Vec::new() } else { plan(inputs, &set.stack, &channels, tile_x, tile_y, 0, Some(&fields)) };
+ for (x, y, offset) in tile_texels(inputs.gbuf, tile_x, tile_y) {
+ let mut texel = Texel::new(inputs, x, y, offset, 0.0);
+ texel.anchors_below(&full_stack, layer);
+ let mut values = Channel::ALL.map(Channel::default_value);
+ texel.eval(&nodes, &mut values);
+ let value = values.get(channel.index()).copied().unwrap_or_else(|| channel.default_value());
+ let encoded = value.map(|component| if channel.kind() == ChannelKind::Signed { to_u16_signed(component) } else { to_u16(component) });
+ output.set(x, y, &encoded[..channel.components()]);
+ }
+ }
+
+ Some(composite)
+}
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index fe57e611..46c3c6b5 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -15,6 +15,7 @@ pub mod display;
pub mod eval;
pub mod pattern;
pub mod store;
+pub mod thumb;
pub use below::{BelowCache, StackKey};
pub use display::{DisplayKind, tile_bytes};
@@ -23,3 +24,4 @@ pub use eval::{
mask_at, mask_image, pad_tiles,
};
pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore};
+pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget};
diff --git a/crates/compose/src/thumb.rs b/crates/compose/src/thumb.rs
new file mode 100644
index 00000000..b4c59a15
--- /dev/null
+++ b/crates/compose/src/thumb.rs
@@ -0,0 +1,206 @@
+//! Small previews of one layer's content, one mask, or one effect stage, computed without
+//! touching the main composite.
+//!
+//! Every thumbnail is the ordinary compositor run on a *cut* copy of the project: only the
+//! requested layer is drawn, forced visible at Normal / 100 %, and
+//! the layer's effect list is truncated after the effect being previewed. The evaluator is the
+//! same code the viewport uses (just on a small G-buffer), so a thumbnail always agrees with
+//! what the stack really computes. Nothing here mutates the caller's project.
+
+use texturecraft_core::{BlendMode, Channel, ChannelBlend, ChannelKind, LayerId, Project};
+use texturecraft_texel::{TILE, from_u16, from_u16_signed, linear_to_srgb};
+
+use crate::eval::{Composite, FlatTile, Inputs, all_tiles, flatten_layer, mask_image};
+
+/// Edge length (texels) the thumbnails are computed at.
+pub const THUMB_TEXELS: u32 = 64;
+
+/// What a thumbnail shows.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub enum ThumbTarget {
+ /// The content of a layer (content effects included, mask ignored) in `channel`.
+ Content { layer: LayerId, channel: Channel },
+ /// The mask of a layer (an instance without its own mask shows its source's).
+ Mask { layer: LayerId },
+ /// The result up to and including `effect`, in the layer's content (`channel`) or in its
+ /// mask (the channel is ignored). An effect that is hidden shows the bypassed result.
+ Stage { effect: LayerId, channel: Channel },
+}
+
+/// An 8-bit RGBA thumbnail (straight alpha). Alpha is 0 where the mesh does not cover the
+/// texture and, for a paint or fill layer's content, where the layer has nothing; the view
+/// paints its own background there.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct ThumbImage {
+ pub width: u32,
+ pub height: u32,
+ pub rgba: Vec,
+}
+
+/// The thumbnail of `target`, computed at `inp.gbuf`'s size, which must be square (use a
+/// [`THUMB_TEXELS`] G-buffer; None otherwise). None for an unknown layer or effect, a layer without that channel, or a
+/// mask that does not exist.
+pub fn render(inp: &Inputs, target: ThumbTarget) -> Option {
+ if inp.gbuf.width != inp.gbuf.height {
+ return None;
+ }
+ match target {
+ ThumbTarget::Content { layer, channel } => content(inp, layer, channel, None),
+ ThumbTarget::Mask { layer } => mask(inp, layer, None),
+ ThumbTarget::Stage { effect, channel } => {
+ let (owner, _) = inp.project.effect(effect)?;
+ let in_mask = inp.project.layers.get(&owner)?.mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| e.id == effect));
+ if in_mask { mask(inp, owner, Some(effect)) } else { content(inp, owner, channel, Some(effect)) }
+ }
+ }
+}
+
+/// Force the requested layer visible, retaining the stack needed by anchor readers.
+fn solo(project: &Project, texture_set: usize, id: LayerId, channel: Option) -> Option {
+ let mut cut = project.clone();
+
+ // Ordinary previews need no neighbouring layers or their filter allocations
+ if !project.render_tree(&[id]).iter().any(|layer| crate::eval::reads_anchor(project, *layer)) {
+ cut.texture_sets.get_mut(texture_set)?.stack = vec![id];
+ }
+
+ cut.layers.get_mut(&id)?.visible = true;
+ if let Some(channel) = channel {
+ // Instances inherit channels from their source
+ let owner = cut.content_layer(id)?.id;
+ *cut.layers.get_mut(&owner)?.channels.get_mut(&channel)? = ChannelBlend { mode: BlendMode::Normal, opacity: 1.0 };
+ }
+
+ Some(cut)
+}
+
+/// Keep the effects of `list` up to and including `last`.
+fn truncate_after(list: &mut Vec, last: LayerId) -> bool {
+ match list.iter().position(|e| e.id == last) {
+ Some(k) => {
+ list.truncate(k + 1);
+ true
+ }
+ None => false,
+ }
+}
+
+fn content(inputs: &Inputs, layer: LayerId, channel: Channel, through_effect: Option) -> Option {
+ let set = inputs.project.texture_set(inputs.ts).ok()?;
+ if !set.channel_list().contains(&channel) {
+ return None;
+ }
+
+ // An instance draws its source's effects
+ let mut cut = solo(inputs.project, inputs.ts, layer, Some(channel))?;
+ let owner = cut.content_layer(layer)?.id;
+ for id in [layer, owner] {
+ let content = cut.layers.get_mut(&id)?;
+ content.mask = None;
+ content.visible = true;
+ }
+
+ if let Some(effect) = through_effect
+ && !truncate_after(&mut cut.layers.get_mut(&owner)?.content_effects, effect)
+ {
+ return None;
+ }
+
+ let cut_inputs = Inputs { project: &cut, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs };
+ let (width, height) = (inputs.gbuf.width, inputs.gbuf.height);
+
+ // Paint and fill previews retain coverage; folders composite over channel defaults
+ if !cut.layers.get(&owner)?.is_group() {
+ let flat = flatten_layer(&cut_inputs, layer, &all_tiles(width, height))?;
+ return Some(encode_flat(&flat, channel, width, height));
+ }
+
+ let comp = crate::eval::thumbnail::composite_layer(&cut_inputs, layer, channel)?;
+ Some(encode_channel(&comp, channel, inputs))
+}
+
+/// Encode the flattened (premultiplied value, coverage) tiles of `channel`: alpha is coverage.
+fn encode_flat(flat: &[FlatTile], channel: Channel, w: u32, h: u32) -> ThumbImage {
+ let mut rgba = vec![0u8; (w * h) as usize * 4];
+ let comps = channel.components();
+ let signed = channel.kind() == ChannelKind::Signed;
+ for (c, (tx, ty), buf) in flat {
+ if *c != channel {
+ continue;
+ }
+ for (o, px) in buf.chunks_exact(comps + 1).enumerate() {
+ let (x, y) = (tx * TILE + o as u32 % TILE, ty * TILE + o as u32 / TILE);
+ let a = px.get(comps).map_or(0.0, |v| from_u16(*v));
+ if x >= w || y >= h || a <= 0.0 {
+ continue;
+ }
+ let mut v = [0.0f32; 3];
+ for (k, slot) in v.iter_mut().enumerate() {
+ let raw = px.get(k.min(comps - 1)).copied().unwrap_or(0);
+ *slot = if signed { from_u16_signed(raw) } else { from_u16(raw) } / a;
+ }
+ let p = display(channel, v);
+ let i = ((y * w + x) * 4) as usize;
+ if let Some(d) = rgba.get_mut(i..i + 4) {
+ d.copy_from_slice(&[p[0], p[1], p[2], to_byte(a)]);
+ }
+ }
+ }
+ ThumbImage { width: w, height: h, rgba }
+}
+
+/// A channel value as display bytes: colors linear → sRGB, signed values with 0 at mid gray,
+/// normal maps and scalars as stored.
+fn display(channel: Channel, v: [f32; 3]) -> [u8; 3] {
+ match channel.kind() {
+ ChannelKind::Color => v.map(|c| to_byte(linear_to_srgb(c.clamp(0.0, 1.0)))),
+ ChannelKind::Signed => v.map(|c| to_byte(c * 0.5 + 0.5)),
+ ChannelKind::Scalar | ChannelKind::NormalMap => v.map(to_byte),
+ }
+}
+
+fn mask(inputs: &Inputs, layer: LayerId, through_effect: Option) -> Option {
+ let mut cut = solo(inputs.project, inputs.ts, layer, None)?;
+ let owner = cut.mask_owner(layer);
+ let mask = cut.layers.get_mut(&owner)?.mask.as_mut()?;
+ mask.enabled = true;
+ if let Some(effect) = through_effect
+ && !truncate_after(&mut mask.effects, effect)
+ {
+ return None;
+ }
+
+ let cut_inputs = Inputs { project: &cut, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs };
+ let (width, height) = (inputs.gbuf.width, inputs.gbuf.height);
+ let gray = mask_image(&cut_inputs, layer, width)?;
+ let mut rgba = Vec::with_capacity((width * height) as usize * 4);
+ for y in 0..height {
+ for x in 0..width {
+ let offset = (y * width + x) as usize;
+ let value = gray.get(offset).copied().unwrap_or(0);
+ rgba.extend_from_slice(&[value, value, value, if inputs.gbuf.covered(offset) { 255 } else { 0 }]);
+ }
+ }
+
+ Some(ThumbImage { width, height, rgba })
+}
+
+/// Encode the composited `channel` for display: colors linear → sRGB, signed values 0 → mid
+/// gray, normal maps and scalars as stored (data channels raw).
+fn encode_channel(comp: &Composite, channel: Channel, inp: &Inputs) -> ThumbImage {
+ let (w, h) = (comp.resolution, comp.height);
+ let mut rgba = Vec::with_capacity((w * h) as usize * 4);
+ for y in 0..h {
+ for x in 0..w {
+ let v = comp.value(channel, x, y);
+ let px = display(channel, v);
+ let covered = inp.gbuf.covered((y * w + x) as usize);
+ rgba.extend_from_slice(&[px[0], px[1], px[2], if covered { 255 } else { 0 }]);
+ }
+ }
+ ThumbImage { width: w, height: h, rgba }
+}
+
+fn to_byte(v: f32) -> u8 {
+ if v.is_finite() { (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8 } else { 0 }
+}
diff --git a/crates/engine/src/bake/bake_task.rs b/crates/engine/src/bake/bake_task.rs
index 8c942176..24629b56 100644
--- a/crates/engine/src/bake/bake_task.rs
+++ b/crates/engine/src/bake/bake_task.rs
@@ -1,9 +1,9 @@
-use super::MergedHigh;
+use super::{MergedHigh, StreamedBake, StreamedMap};
use crate::{EngineError, Result};
use std::sync::Arc;
use texturecraft_bake::{BakeOutput, BakePaintMap, BakeRequest, HighPoly, Progress, bake_tiles, tracing::Tracer};
use texturecraft_compose::BakedMaps;
-use texturecraft_core::BakeSettings;
+use texturecraft_core::{BakeSettings, BakedMap};
use texturecraft_geom::{Bvh, Mesh};
/// A self-contained bake task that can run on another thread.
@@ -29,7 +29,69 @@ pub struct BakeTask {
}
impl BakeTask {
+ /// The maps this task makes, in the order [`BakeTask::run_streaming`] finishes them
+ pub fn maps(&self) -> Vec {
+ self.settings.maps.enabled().collect()
+ }
+
+ /// Bake the maps one after another, handing each one to `on_map` as soon as it is padded,
+ /// and return all of them together. Each map is a bake of its own, so with a high poly
+ /// the transfer rays are cast once per map: slower than [`BakeTask::run`] with several
+ /// maps, in exchange for showing them as they land. The pixels are the same as `run`'s.
+ /// The handed-over buffers are the returned ones too (no copy is made), so a preview that
+ /// keeps them costs no second set of maps. A cancel or an error leaves the maps already
+ /// handed over whole.
+ pub fn run_streaming(&self, progress: &Progress, on_map: &mut dyn FnMut(StreamedMap)) -> Result {
+ let maps = self.maps();
+ let total = maps.len();
+ let mut combined: Option = None;
+
+ for (index, map) in maps.iter().copied().enumerate() {
+ let mut settings = self.settings.clone();
+ settings.maps.select([map]);
+ let mut output = self.run_with(&settings, progress)?;
+ let Some(data) = output.maps.remove(&map) else { continue };
+ if combined.is_none() {
+ // Retain unchecked maps once, using the full selection rather than this one-map pass.
+ super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &maps)?;
+ }
+
+ let data = Arc::new(data);
+ on_map(StreamedMap { map, index, total, resolution: output.resolution, height: output.height, data: data.clone() });
+ match &mut combined {
+ Some(combined) => {
+ combined.maps.insert(map, data);
+ }
+ None => {
+ // 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 });
+ }
+ }
+ }
+
+ match combined {
+ Some(output) => Ok(output),
+ None => {
+ let output = self.run(progress)?;
+ Ok(StreamedBake {
+ resolution: output.resolution,
+ height: output.height,
+ maps: output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(),
+ tracer: output.tracer,
+ })
+ }
+ }
+ }
+
pub fn run(&self, progress: &Progress) -> Result {
+ let mut output = self.run_with(&self.settings, progress)?;
+ super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &[])?;
+ Ok(output)
+ }
+
+ fn run_with(&self, settings: &BakeSettings, progress: &Progress) -> Result {
let high =
self.high.as_ref().map(|source| HighPoly { file_ids: &source.file_ids, mesh: &source.mesh, bvh: &source.bvh, base_color: &source.base_color });
let request = BakeRequest {
@@ -37,16 +99,118 @@ impl BakeTask {
mesh: &self.mesh,
bvh: &self.bvh,
material: self.material,
- settings: &self.settings,
+ settings,
high,
cage: self.cage.as_deref(),
skew: self.skew.as_deref(),
cage_paint: self.cage_paint.as_deref(),
tiles: self.tiles,
};
+
let mut output = bake_tiles(&request, progress, &self.excluded_tiles, self.tracer.as_deref())
.map_err(|error| EngineError::Other(format!("bake failed: {error}")))?;
super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?;
Ok(output)
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{Session, execute};
+ use serde_json::json;
+ use texturecraft_geom::primitives;
+
+ const PREVIOUS_MAPS: [BakedMap; 3] = [BakedMap::Normal, BakedMap::AmbientOcclusion, BakedMap::Height];
+ const SELECTED_MAPS: [BakedMap; 2] = [BakedMap::AmbientOcclusion, BakedMap::Height];
+
+ fn partial_task(selected: &[BakedMap], resized: bool, excluded: bool) -> BakeTask {
+ let mut session = Session::new_project("Partial bake", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap();
+ execute(&mut session, "bake.settings", &json!({"resolution": 64, "rays": 2})).unwrap();
+ if excluded {
+ execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap();
+ }
+ let mut task = session.bake_task(0).unwrap();
+ task.tracer = None;
+ task.settings.maps.select(selected.iter().copied());
+ let (width, height) = if resized { (64, 32) } else { (128, 64) };
+ task.previous_maps = BakedMaps {
+ resolution: width,
+ maps: PREVIOUS_MAPS.into_iter().map(|map| (map, Arc::new(vec![0.25; width as usize * height * map.components()]))).collect(),
+ };
+ task
+ }
+
+ #[test]
+ fn streaming_allocates_only_truly_unchecked_resized_maps_once() {
+ for (selected, resized, excluded) in [
+ (SELECTED_MAPS.as_slice(), true, true),
+ (PREVIOUS_MAPS.as_slice(), true, true),
+ (SELECTED_MAPS.as_slice(), false, true),
+ (SELECTED_MAPS.as_slice(), true, false),
+ ] {
+ let task = partial_task(selected, resized, excluded);
+ let whole = task.run(&Progress::new()).unwrap();
+ super::super::preserve_tiles::take_retained_allocations();
+ let mut allocations = Vec::new();
+ let mut handed_over = Vec::new();
+ let output = task
+ .run_streaming(&Progress::new(), &mut |map| {
+ allocations.extend(super::super::preserve_tiles::take_retained_allocations());
+ assert!(allocations.iter().all(|map| !selected.contains(map)), "maps scheduled to bake must never allocate retained buffers");
+ handed_over.push(map);
+ })
+ .unwrap();
+ allocations.extend(super::super::preserve_tiles::take_retained_allocations());
+ let expected: Vec<_> = PREVIOUS_MAPS.into_iter().filter(|map| resized && excluded && !selected.contains(map)).collect();
+ assert_eq!(allocations, expected, "each truly unchecked resized map must allocate exactly once");
+ assert_eq!(output.maps.keys().collect::>(), whole.maps.keys().collect::>());
+ for (map, pixels) in &whole.maps {
+ assert_eq!(*output.maps[map], *pixels, "{map:?} must preserve the ordinary bake's pixels");
+ }
+ for map in handed_over {
+ assert!(Arc::ptr_eq(&map.data, &output.maps[&map.map]), "streaming must keep sharing the baked buffer");
+ }
+ }
+ }
+
+ #[test]
+ fn cancelling_a_partial_stream_does_not_resample_future_maps() {
+ let task = partial_task(&SELECTED_MAPS, true, true);
+ let whole = task.run(&Progress::new()).unwrap();
+ super::super::preserve_tiles::take_retained_allocations();
+ let progress = Progress::new();
+ let mut handed_over = Vec::new();
+ let result = task.run_streaming(&progress, &mut |map| {
+ handed_over.push(map);
+ progress.cancel();
+ });
+ assert!(result.is_err());
+ assert_eq!(handed_over.len(), 1);
+ for map in handed_over {
+ assert_eq!(*map.data, whole.maps[&map.map], "cancellation leaves the handed-over map whole");
+ }
+ assert_eq!(super::super::preserve_tiles::take_retained_allocations(), [BakedMap::Normal]);
+ }
+
+ #[test]
+ fn an_empty_streaming_selection_keeps_the_ordinary_bake_behavior() {
+ let task = partial_task(&[], true, true);
+ super::super::preserve_tiles::take_retained_allocations();
+ let whole = task.run(&Progress::new());
+ let expected_allocations = super::super::preserve_tiles::take_retained_allocations();
+ let output = task.run_streaming(&Progress::new(), &mut |_| panic!("an empty selection must not stream a map"));
+ assert_eq!(super::super::preserve_tiles::take_retained_allocations(), expected_allocations);
+ match (whole, output) {
+ (Ok(whole), Ok(output)) => {
+ assert_eq!((output.resolution, output.height), (whole.resolution, whole.height));
+ assert_eq!(output.maps.keys().collect::>(), whole.maps.keys().collect::>());
+ for (map, pixels) in whole.maps {
+ assert_eq!(*output.maps[&map], pixels);
+ }
+ }
+ (Err(whole), Err(output)) => assert_eq!(whole.to_string(), output.to_string()),
+ _ => panic!("empty streaming and ordinary bakes must agree"),
+ }
+ }
+}
diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs
index b65d6ac8..14248cc3 100644
--- a/crates/engine/src/bake/mesh_map_command.rs
+++ b/crates/engine/src/bake/mesh_map_command.rs
@@ -9,7 +9,7 @@ use std::sync::{Arc, OnceLock};
use texturecraft_core::BakePaintTarget;
use super::{BakeCageInputs, MergedHigh};
-use crate::{BakeMesh, BakeTask};
+use crate::{BakeMesh, BakeTask, StreamedBake};
use serde_json::{Value, json};
use texturecraft_bake::tracing::Tracer;
use texturecraft_bake::{BakeOutput, BakePaintMap, MAX_RAYS, Progress};
@@ -207,15 +207,28 @@ impl Session {
Ok(())
}
+ /// Apply a streamed bake like [`Session::apply_bake`], keeping the maps' shared buffers (the
+ /// 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.log.push(format!("Baked texture set {texture_set} ({tracer})"));
+ Ok(())
+ }
+
fn store_bake(&mut self, texture_set: usize, output: BakeOutput) -> 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)
+ }
+
+ fn store_bake_maps(&mut self, texture_set: usize, resolution: u32, height: u32, maps: std::collections::BTreeMap>>) -> Result<()> {
let entry = self.doc.baked.entry(texture_set).or_default();
- if entry.resolution != output.resolution || entry.maps.keys().any(|map| entry.height(*map) != output.height) {
+ if entry.resolution != resolution || entry.maps.keys().any(|map| entry.height(*map) != height) {
entry.maps.clear();
}
- entry.resolution = output.resolution;
- for (map, pixels) in output.maps {
- entry.maps.insert(map, Arc::new(pixels));
- }
+
+ entry.resolution = resolution;
+ entry.maps.extend(maps);
self.doc.project.texture_set_mut(texture_set)?.baked = entry.maps.keys().copied().collect();
Ok(())
}
diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs
index fa3403df..f06ab265 100644
--- a/crates/engine/src/bake/mod.rs
+++ b/crates/engine/src/bake/mod.rs
@@ -11,6 +11,8 @@ mod mesh_map_command;
mod model_patch;
mod paint_command;
mod preserve_tiles;
+mod streamed_bake;
+mod streamed_map;
mod tile_command;
pub use bake_cage_inputs::BakeCageInputs;
@@ -21,6 +23,8 @@ pub use high_poly_missed::high_poly_missed;
pub use merged_high::MergedHigh;
pub use mesh_map_command::{install_gpu_tracer, meshes_json, settings_params};
pub use model_patch::settings_patch;
+pub use streamed_bake::StreamedBake;
+pub use streamed_map::StreamedMap;
pub use texturecraft_bake::*;
use crate::CommandSpec;
diff --git a/crates/engine/src/bake/preserve_tiles.rs b/crates/engine/src/bake/preserve_tiles.rs
index 27c74ae8..f44a09a4 100644
--- a/crates/engine/src/bake/preserve_tiles.rs
+++ b/crates/engine/src/bake/preserve_tiles.rs
@@ -1,5 +1,6 @@
use texturecraft_bake::BakeOutput;
use texturecraft_compose::BakedMaps;
+use texturecraft_core::BakedMap;
use crate::{EngineError, Result};
@@ -29,9 +30,18 @@ pub(super) fn restore(output: &mut BakeOutput, previous: &BakedMaps, excluded_ti
}
}
- // Keep unchecked map outputs too when a partial bake changes the atlas dimensions
+ Ok(())
+}
+
+/// Retain only maps outside the full task selection, once per completed atlas.
+/// A one-map streaming pass must not resample maps that are still scheduled to bake.
+pub(super) fn restore_unchecked(output: &mut BakeOutput, previous: &BakedMaps, excluded_tiles: &[(u32, u32)], selected: &[BakedMap]) -> Result<()> {
+ if excluded_tiles.is_empty() {
+ return Ok(());
+ }
+ let size = (output.resolution, output.height);
for map in previous.maps.keys() {
- if output.maps.contains_key(map) || (previous.resolution == size.0 && previous.height(*map) == size.1) {
+ if selected.contains(map) || output.maps.contains_key(map) || (previous.resolution == size.0 && previous.height(*map) == size.1) {
continue;
}
@@ -42,6 +52,8 @@ pub(super) fn restore(output: &mut BakeOutput, previous: &BakedMaps, excluded_ti
.ok_or_else(|| EngineError::Other("resized bake map exceeds the addressable size".into()))?;
let mut pixels = Vec::new();
pixels.try_reserve_exact(count).map_err(|error| EngineError::Other(format!("cannot retain mesh map {}: {error}", map.id())))?;
+ #[cfg(test)]
+ RETAINED_ALLOCATIONS.with(|allocations| allocations.borrow_mut().push(*map));
for y in 0..size.1 {
for x in 0..size.0 {
let value = previous.sample(*map, x, y, size).unwrap_or_else(|| map.neutral());
@@ -52,3 +64,15 @@ pub(super) fn restore(output: &mut BakeOutput, previous: &BakedMaps, excluded_ti
}
Ok(())
}
+
+// Restoration is sequential on the calling thread. Record successful retained-buffer allocations
+// only in unit tests, without a global allocator or interference from parallel test threads.
+#[cfg(test)]
+std::thread_local! {
+ static RETAINED_ALLOCATIONS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) };
+}
+
+#[cfg(test)]
+pub(super) fn take_retained_allocations() -> Vec {
+ RETAINED_ALLOCATIONS.with(|allocations| std::mem::take(&mut *allocations.borrow_mut()))
+}
diff --git a/crates/engine/src/bake/streamed_bake.rs b/crates/engine/src/bake/streamed_bake.rs
new file mode 100644
index 00000000..55aecbca
--- /dev/null
+++ b/crates/engine/src/bake/streamed_bake.rs
@@ -0,0 +1,14 @@
+use std::collections::BTreeMap;
+use std::sync::Arc;
+
+use texturecraft_core::BakedMap;
+
+/// The result of a streamed bake: the finished maps stay shared (`Arc`) with whoever was shown them,
+/// so the preview and the document hold one buffer per map, never two
+#[derive(Clone, Debug)]
+pub struct StreamedBake {
+ pub resolution: u32,
+ pub height: u32,
+ pub maps: BTreeMap>>,
+ pub tracer: String,
+}
diff --git a/crates/engine/src/bake/streamed_map.rs b/crates/engine/src/bake/streamed_map.rs
new file mode 100644
index 00000000..33781099
--- /dev/null
+++ b/crates/engine/src/bake/streamed_map.rs
@@ -0,0 +1,17 @@
+use std::sync::Arc;
+
+use texturecraft_core::BakedMap;
+
+/// One finished map of a streamed bake (see [`crate::BakeTask::run_streaming`]).
+#[derive(Clone, Debug)]
+pub struct StreamedMap {
+ pub map: BakedMap,
+ /// Position among the maps this bake makes, from 0, and how many there are.
+ pub index: usize,
+ pub total: usize,
+ /// Width and height in texels.
+ pub resolution: u32,
+ pub height: u32,
+ /// Row-major, `map.components()` floats per texel, padded.
+ pub data: Arc>,
+}
diff --git a/crates/engine/src/bake_preview.rs b/crates/engine/src/bake_preview.rs
new file mode 100644
index 00000000..878fb276
--- /dev/null
+++ b/crates/engine/src/bake_preview.rs
@@ -0,0 +1,236 @@
+//! Live bake preview: while the app bakes, the 3D view shows each mesh map on the model as soon
+//! as it is finished ([`crate::BakeTask::run_streaming`]). The streamed maps live here, not in
+//! the document: nothing enters the undo history until a texture set's bake is applied
+//! ([`Session::apply_streamed_bake`]). Cancellation leaves the current set unchanged; sets already
+//! applied keep their results and undo steps. The preview shows one map at a time, raw on the
+//! model; maps and texture sets not baked yet show their neutral value.
+
+mod preview_set;
+mod preview_show;
+mod stage;
+
+pub use preview_set::PreviewSet;
+pub use preview_show::PreviewShow;
+pub use stage::Stage;
+
+use std::collections::BTreeMap;
+
+use serde_json::{Value, json};
+use texturecraft_compose::BakedMaps;
+use texturecraft_core::BakedMap;
+
+use crate::bake::StreamedMap;
+use crate::commands::{CommandSpec, always, bad, strp};
+use crate::session::ViewMode;
+use crate::{Result, Session, cmd};
+
+/// What painting says while a bake preview shows (the app translates it).
+pub const PAINTING_PAUSED: &str = "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.";
+
+pub fn specs() -> Vec {
+ vec![cmd!(
+ "bake.preview",
+ "Bake preview",
+ [],
+ None,
+ "{show?: \"follow\" (the newest finished map) | \"material\" | \"map:\" (pin a map)} → {active, show, shown, newest, stage, sets}. While the app bakes, the 3D view shows the maps as they finish; `show` picks what it shows. With no bake running {active: false} (setting `show` is then an error)",
+ always,
+ preview
+ )]
+}
+
+#[derive(Clone, Debug)]
+pub struct BakePreview {
+ /// The view mode to put back when the preview ends.
+ pub restore: ViewMode,
+ pub show: PreviewShow,
+ pub sets: BTreeMap,
+ /// The texture set being baked.
+ pub current: Option,
+ /// The last map that finished.
+ pub newest: Option,
+}
+
+impl BakePreview {
+ /// The map the view shows, None for the material.
+ pub fn shown(&self) -> Option {
+ match self.show {
+ PreviewShow::Material => None,
+ PreviewShow::Pin(map) => Some(map),
+ PreviewShow::Follow => self
+ .newest
+ .or_else(|| self.current_set().and_then(|set| set.order.first().copied()))
+ .or_else(|| self.sets.values().find_map(|set| set.order.first().copied())),
+ }
+ }
+
+ pub fn current_set(&self) -> Option<&PreviewSet> {
+ self.sets.get(&self.current?)
+ }
+
+ /// The map being baked now (None between sets and once the set's maps are all in).
+ pub fn stage(&self) -> Option {
+ let texture_set = self.current?;
+ let set = self.sets.get(&texture_set)?;
+ let done = set.baked.maps.len();
+ Some(Stage { texture_set, map: *set.order.get(done)?, position: done + 1, total: set.order.len() })
+ }
+}
+
+impl Session {
+ /// Start a preview from each selected texture set's enabled maps, in the same order as
+ /// [`crate::BakeTask::maps`]. Invalid indices return the project's texture-set error before
+ /// changing the preview or view mode. This reads settings without preparing bake geometry.
+ pub fn bake_preview_begin_for(&mut self, sets: &[usize]) -> Result<()> {
+ let orders = sets
+ .iter()
+ .map(|&texture_set| {
+ let set = self.doc.project.texture_set(texture_set)?;
+ Ok((texture_set, set.bake.maps.enabled().collect()))
+ })
+ .collect::>>()?;
+
+ self.bake_preview_begin(orders);
+ Ok(())
+ }
+
+ /// Start showing a bake of `sets` (each with the maps it makes, in order): the 3D view
+ /// follows the newest map and every set shows neutral values until its maps arrive. The
+ /// view mode in use comes back with [`Session::bake_preview_end`]. An active stroke is
+ /// discarded so a later pointer release cannot commit paint during the preview.
+ pub fn bake_preview_begin(&mut self, sets: Vec<(usize, Vec)>) {
+ self.cancel_stroke();
+
+ let restore = self.bake_preview.as_ref().map_or(self.view, |preview| preview.restore);
+ let sets = sets.into_iter().map(|(texture_set, order)| (texture_set, PreviewSet { baked: BakedMaps::default(), order })).collect();
+
+ self.bake_preview = Some(BakePreview { restore, show: PreviewShow::Follow, sets, current: None, newest: None });
+ self.bake_preview_refresh();
+ }
+
+ /// The texture set whose maps stream in now.
+ pub fn bake_preview_set_current(&mut self, texture_set: usize) {
+ if let Some(preview) = &mut self.bake_preview {
+ preview.current = Some(texture_set);
+ }
+
+ self.bake_preview_refresh();
+ }
+
+ /// Install one finished map of set `texture_set`. Returns false when no preview shows.
+ pub fn bake_preview_map(&mut self, texture_set: usize, streamed: StreamedMap) -> bool {
+ let Some(preview) = &mut self.bake_preview else { return false };
+
+ let set = preview.sets.entry(texture_set).or_default();
+
+ // A new bake of the set starts from nothing (the baker never repeats a map)
+ if streamed.index == 0 {
+ set.baked = BakedMaps::default();
+ }
+
+ set.baked.resolution = streamed.resolution;
+ set.baked.maps.insert(streamed.map, streamed.data);
+ preview.newest = Some(streamed.map);
+ self.bake_preview_refresh();
+ true
+ }
+
+ /// Choose what the view shows (Follow, a pinned map or the material).
+ pub fn bake_preview_show(&mut self, show: PreviewShow) -> Result<()> {
+ let Some(preview) = &mut self.bake_preview else { return Err(bad("bake.preview", "no bake is running")) };
+
+ preview.show = show;
+ self.bake_preview_refresh();
+ Ok(())
+ }
+
+ /// The user picked a view mode during a bake: a mesh map pins it, any other mode shows
+ /// the material and is what comes back when the bake ends.
+ pub(crate) fn bake_preview_user_view(&mut self, view: ViewMode) {
+ let Some(preview) = &mut self.bake_preview else { return };
+
+ match view {
+ ViewMode::MeshMap(map) => preview.show = PreviewShow::Pin(map),
+ other => {
+ preview.show = PreviewShow::Material;
+ preview.restore = other;
+ }
+ }
+
+ self.bake_preview_refresh();
+ if !matches!(view, ViewMode::MeshMap(_)) {
+ self.view = view;
+ }
+ }
+
+ /// Drop the displayed maps and restore the previous view mode. This does not stop a
+ /// worker or undo any applied results; the UI also uses it when leaving Bake mode.
+ pub fn bake_preview_end(&mut self) {
+ if let Some(preview) = self.bake_preview.take() {
+ self.view = preview.restore;
+ self.revision = self.revision.wrapping_add(1);
+ }
+ }
+
+ pub fn bake_preview_active(&self) -> bool {
+ self.bake_preview.is_some()
+ }
+
+ /// The streamed maps of set `texture_set` while a preview shows (empty for a set not baked
+ /// yet: neutral values), None when the document's baked maps are what shows.
+ pub fn bake_preview_baked(&self, texture_set: usize) -> Option<&BakedMaps> {
+ self.bake_preview.as_ref()?.sets.get(&texture_set).map(|set| &set.baked)
+ }
+
+ /// Why painting is not possible now, when a bake preview shows.
+ pub fn painting_blocked(&self) -> Option<&'static str> {
+ self.bake_preview.as_ref().map(|_| PAINTING_PAUSED)
+ }
+
+ fn bake_preview_refresh(&mut self) {
+ let Some(preview) = &self.bake_preview else { return };
+
+ self.view = match preview.shown() {
+ Some(map) => ViewMode::MeshMap(map),
+ None => ViewMode::Material,
+ };
+ self.revision = self.revision.wrapping_add(1);
+ }
+}
+
+/// The preview as JSON, for `bake.preview`, `session.inspect` and `ui.inspect`.
+pub fn preview_json(session: &Session) -> Value {
+ let Some(preview) = &session.bake_preview else { return json!({ "active": false }) };
+
+ let stage = preview.stage().map(|stage| json!({ "set": stage.texture_set, "map": stage.map.id(), "n": stage.position, "total": stage.total }));
+ let sets: Vec = preview
+ .sets
+ .iter()
+ .map(|(texture_set, set)| {
+ json!({
+ "set": texture_set,
+ "order": set.order.iter().map(|map| map.id()).collect::>(),
+ "done": set.baked.maps.keys().map(|map| map.id()).collect::>(),
+ })
+ })
+ .collect();
+
+ json!({
+ "active": true,
+ "show": preview.show.id(),
+ "shown": preview.shown().map(|map| map.id()),
+ "newest": preview.newest.map(|map| map.id()),
+ "restore": preview.restore.label(),
+ "stage": stage,
+ "sets": sets,
+ })
+}
+
+fn preview(session: &mut Session, params: &Value) -> Result {
+ if let Some(show) = strp(params, "show") {
+ let show = PreviewShow::parse(show).ok_or_else(|| bad("bake.preview", format!("unknown `show` {show:?}: follow, material or map:")))?;
+ session.bake_preview_show(show)?;
+ }
+
+ Ok(preview_json(session))
+}
diff --git a/crates/engine/src/bake_preview/preview_set.rs b/crates/engine/src/bake_preview/preview_set.rs
new file mode 100644
index 00000000..e1eabef8
--- /dev/null
+++ b/crates/engine/src/bake_preview/preview_set.rs
@@ -0,0 +1,10 @@
+use texturecraft_compose::BakedMaps;
+use texturecraft_core::BakedMap;
+
+/// The maps of one texture set streamed so far.
+#[derive(Clone, Debug, Default)]
+pub struct PreviewSet {
+ pub baked: BakedMaps,
+ /// The maps this set's bake makes, in the order they arrive.
+ pub order: Vec,
+}
diff --git a/crates/engine/src/bake_preview/preview_show.rs b/crates/engine/src/bake_preview/preview_show.rs
new file mode 100644
index 00000000..28a13614
--- /dev/null
+++ b/crates/engine/src/bake_preview/preview_show.rs
@@ -0,0 +1,30 @@
+use texturecraft_core::BakedMap;
+
+/// What the 3D view shows while a bake runs.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum PreviewShow {
+ /// The newest finished map (the first one, still neutral, before any is done).
+ Follow,
+ /// One map, pinned: neutral until it is baked.
+ Pin(BakedMap),
+ /// The lit material.
+ Material,
+}
+
+impl PreviewShow {
+ pub fn id(self) -> String {
+ match self {
+ PreviewShow::Follow => "follow".into(),
+ PreviewShow::Pin(map) => format!("map:{}", map.id()),
+ PreviewShow::Material => "material".into(),
+ }
+ }
+
+ pub fn parse(text: &str) -> Option {
+ match text {
+ "follow" => Some(PreviewShow::Follow),
+ "material" => Some(PreviewShow::Material),
+ _ => text.strip_prefix("map:").and_then(BakedMap::parse).map(PreviewShow::Pin),
+ }
+ }
+}
diff --git a/crates/engine/src/bake_preview/stage.rs b/crates/engine/src/bake_preview/stage.rs
new file mode 100644
index 00000000..d1513ae2
--- /dev/null
+++ b/crates/engine/src/bake_preview/stage.rs
@@ -0,0 +1,11 @@
+use texturecraft_core::BakedMap;
+
+/// The map a bake is working on.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Stage {
+ pub texture_set: usize,
+ pub map: BakedMap,
+ /// 1-based position among the set's maps, and how many there are.
+ pub position: usize,
+ pub total: usize,
+}
diff --git a/crates/engine/src/brush_preset_cmds.rs b/crates/engine/src/brush_preset_cmds.rs
index 0ebfa070..2a83b3e1 100644
--- a/crates/engine/src/brush_preset_cmds.rs
+++ b/crates/engine/src/brush_preset_cmds.rs
@@ -3,7 +3,9 @@
use serde_json::{Value, json};
use texturecraft_paint::BrushSettings;
-use texturecraft_paint::presets::{PRESETS, find_preset, with_stroke_of};
+#[cfg(not(target_arch = "wasm32"))]
+use texturecraft_paint::presets::with_stroke_of;
+use texturecraft_paint::presets::{PRESETS, find_preset};
use crate::commands::{CommandSpec, always, bad, strp};
use crate::tool_cmds::brush_json;
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index d9a31b39..d754fc70 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -4,6 +4,7 @@
use serde_json::{Value, json};
use texturecraft_core::{BlendMode, Channel, NormalFormat};
+use texturecraft_geom::glam::Vec3;
use crate::{EngineError, Result, Session};
@@ -71,6 +72,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(crate::template_cmds::specs());
v.extend(crate::project_cmds::specs());
v.extend(crate::bake::specs());
+ v.extend(crate::bake_preview::specs());
v.extend(crate::materialx_cmds::specs());
v.extend(crate::file_cmds::specs());
v.extend(crate::preset_cmds::specs());
@@ -134,6 +136,14 @@ pub(crate) fn u64p(p: &Value, key: &str) -> Option {
p.get(key).and_then(|v| v.as_u64().or_else(|| v.as_f64().filter(|f| f.is_finite() && *f >= 0.0).map(|f| f.round() as u64)))
}
+/// A `[x, y, z]` param of finite numbers
+pub(crate) fn vec3(params: &Value, key: &str) -> Option {
+ let [x, y, z] = params.get(key)?.as_array()?.as_slice() else { return None };
+ let vector = Vec3::new(x.as_f64()? as f32, y.as_f64()? as f32, z.as_f64()? as f32);
+
+ vector.is_finite().then_some(vector)
+}
+
pub(crate) fn boolp(p: &Value, key: &str) -> Option {
p.get(key).and_then(Value::as_bool)
}
diff --git a/crates/engine/src/decal_cmds.rs b/crates/engine/src/decal_cmds.rs
index e937b6f5..f1cecf11 100644
--- a/crates/engine/src/decal_cmds.rs
+++ b/crates/engine/src/decal_cmds.rs
@@ -2,12 +2,12 @@
//! (a decal fill with a planar projection), as a fill layer with a decal projection.
use serde_json::{Value, json};
-use texturecraft_core::{Channel, Decal, Fill, Layer, LayerId, LayerKind, Projection, Source};
+use texturecraft_core::{Channel, Decal, Effect, EffectKind, Fill, Layer, LayerId, LayerKind, Mask, MaskBackground, Projection, Source};
use texturecraft_geom::glam::{Vec2, Vec3};
-use crate::commands::{CommandSpec, always, bad, f32p, has_layer, layer_param, strp};
+use crate::commands::{CommandSpec, always, bad, channel_param, f32p, has_layer, layer_param, strp, u64p, vec3};
use crate::tool_cmds::viewport_of;
-use crate::{Result, Session, cmd};
+use crate::{Result, Session, StackTarget, cmd};
pub fn specs() -> Vec {
vec![
@@ -16,7 +16,7 @@ pub fn specs() -> Vec {
"Add decal",
[],
None,
- "{image: resource name, x?, y?: viewport pixels (default: the view center), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z], up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round",
+ "{image: resource name, channel?: a channel id (default baseColor) | \"mask\" (a new fill layer masked by the image's gray), x?, y?: viewport pixels (default: the view center; a point on another texture set selects it), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z] (on the selected texture set), up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} → {layer, decal, maskEffect: the mask fill effect holding the image with channel \"mask\", else null} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round",
always,
add
),
@@ -25,60 +25,58 @@ pub fn specs() -> Vec {
"Edit decal",
[],
None,
- "{layer?, x?, y?, viewport? | position?, normal? (re-place it), up?: [x,y,z], size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?, merge?: true continues the previous Edit decal undo step (drags)}",
+ "{layer? | effect?: a mask fill effect id (a decal placed as a mask; with `layer`, it must be in that layer), x?, y?, viewport? | position?, normal? (re-place it on its own texture set), up?: [x,y,z], size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?: replaces the image in the channel or mask it was placed in, merge?: true continues the previous Edit decal undo step (drags)}",
has_layer,
set
),
]
}
-/// A `[x, y, z]` param of finite numbers.
-fn vec3(p: &Value, key: &str) -> Option {
- let a = p.get(key)?.as_array()?;
- let v: Vec = a.iter().filter_map(Value::as_f64).map(|x| x as f32).filter(|x| x.is_finite()).collect();
- match v.as_slice() {
- [x, y, z] => Some(Vec3::new(*x, *y, *z)),
- _ => None,
+/// Resolve a viewport hit or explicit world position, using `texture_set` for explicit positions.
+/// Returns None when placement is optional and no position or viewport point is given.
+fn placement(session: &Session, command: &str, params: &Value, texture_set: usize, optional: bool) -> Result