Merge main into release for TextureCraft v0.6.0

This commit is contained in:
FredApps committed 2026-11-11 16:52:46 +01:00
commit d1ca3fdfba
170 files changed
+15374 -1931

No files matched your search

Generated
+82 -25
View File
@@ -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",
]
+3 -1
View File
@@ -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"] }
+1
View File
@@ -32,6 +32,7 @@
<img alt="MCP server for agents" src="https://img.shields.io/badge/agents-MCP%20server-555555?style=flat-square">
<img alt="License: MIT OR Apache-2.0" src="https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-555555?style=flat-square">
<br>
<a href="https://sonarcloud.io/project/overview?id=storytold_texturecraft"><img alt="Scanned by SonarCloud" src="https://img.shields.io/badge/Scanned_by-SonarCloud-4b9fd5?style=flat-square&logo=sonarqubecloud&logoColor=white"></a>
<a href="https://coderabbit.ai"><img alt="Reviewed by CodeRabbit" src="https://img.shields.io/coderabbit/prs/github/storytold/texturecraft?style=flat-square&label=Reviewed%20by%20CodeRabbit&logo=coderabbit"></a>
</p>
+22 -11
View File
@@ -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::<std::collections::HashMap<String, String>>(&text).ok());
entries.and_then(|entries| ron::from_str::<UiState>(entries.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar)
entries.and_then(|entries| ron::from_str::<UiState>(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());
}
}
+9 -1
View File
@@ -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<u8>)> {
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)
}
+12 -7
View File
@@ -178,8 +178,11 @@ pub struct ConnectionLimiter(Arc<AtomicUsize>);
pub struct Permit(Arc<AtomicUsize>);
impl ConnectionLimiter {
pub fn try_acquire(&self, max: usize) -> Option<Permit> {
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<Permit> {
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());
}
}
+4 -2
View File
@@ -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<u32> {
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<Vec3> {
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<Vec3> {
}
}
}
normals
}
+2 -1
View File
@@ -23,7 +23,7 @@ fn bumpy_high_poly() -> (Mesh, Vec<bool>) {
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::<f32>() / 3.0;
if center_x > FLIPPED_FROM_X {
corners.swap(1, 2);
@@ -32,6 +32,7 @@ fn bumpy_high_poly() -> (Mesh, Vec<bool>) {
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)
+9 -2
View File
@@ -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(&parameters, &high) - 0.54).abs() < 1e-5);
parameters.high_poly.match_mode = MeshMatchMode::ByMeshName;
assert!((height(&parameters, &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(&parameters, &high), 0.5);
parameters.high_poly.ignore_backface = false;
assert!((height(&parameters, &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, &parameters).unwrap();
parameters.maps.position.parameters.scale = PositionNormalizationScale::PerMaterial;
let local = run(&mesh, &parameters).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]
+12 -10
View File
@@ -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, &parameters).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]
+48 -40
View File
@@ -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<u8> {
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<u8> {
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
}
+56 -43
View File
@@ -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<u16>);
/// 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<Vec<FlatTile>> {
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<Vec<FlatTile>> {
let set = inputs.project.texture_set(inputs.ts).ok()?;
if inputs.project.content_layer(id)?.is_group() {
return None;
}
let channels: Vec<Channel> = 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<Vec<FlatTile>> = 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<u16>, bool)> =
let full = anchor_plan(&visible_inputs, id, &channels, tx, ty, Some(&fields));
let mut buffers: Vec<(Channel, Vec<u16>, 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())
}
+30
View File
@@ -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<Composite> {
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)
}
+2
View File
@@ -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};
+206
View File
@@ -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<u8>,
}
/// 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<ThumbImage> {
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<Channel>) -> Option<Project> {
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<texturecraft_core::Effect>, 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<LayerId>) -> Option<ThumbImage> {
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<LayerId>) -> Option<ThumbImage> {
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 }
}
+167 -3
View File
@@ -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<BakedMap> {
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<StreamedBake> {
let maps = self.maps();
let total = maps.len();
let mut combined: Option<StreamedBake> = 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<BakeOutput> {
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<BakeOutput> {
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::<Vec<_>>(), whole.maps.keys().collect::<Vec<_>>());
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::<Vec<_>>(), whole.maps.keys().collect::<Vec<_>>());
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"),
}
}
}
+19 -6
View File
@@ -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<BakedMap, Arc<Vec<f32>>>) -> 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(())
}
+4
View File
@@ -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;
+26 -2
View File
@@ -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<Vec<texturecraft_core::BakedMap>> = const { std::cell::RefCell::new(Vec::new()) };
}
#[cfg(test)]
pub(super) fn take_retained_allocations() -> Vec<texturecraft_core::BakedMap> {
RETAINED_ALLOCATIONS.with(|allocations| std::mem::take(&mut *allocations.borrow_mut()))
}
+14
View File
@@ -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<BakedMap, Arc<Vec<f32>>>,
pub tracer: String,
}
+17
View File
@@ -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<Vec<f32>>,
}
+236
View File
@@ -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<CommandSpec> {
vec![cmd!(
"bake.preview",
"Bake preview",
[],
None,
"{show?: \"follow\" (the newest finished map) | \"material\" | \"map:<id>\" (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<usize, PreviewSet>,
/// The texture set being baked.
pub current: Option<usize>,
/// The last map that finished.
pub newest: Option<BakedMap>,
}
impl BakePreview {
/// The map the view shows, None for the material.
pub fn shown(&self) -> Option<BakedMap> {
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<Stage> {
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::<Result<Vec<_>>>()?;
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<BakedMap>)>) {
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<Value> = preview
.sets
.iter()
.map(|(texture_set, set)| {
json!({
"set": texture_set,
"order": set.order.iter().map(|map| map.id()).collect::<Vec<_>>(),
"done": set.baked.maps.keys().map(|map| map.id()).collect::<Vec<_>>(),
})
})
.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<Value> {
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:<id>")))?;
session.bake_preview_show(show)?;
}
Ok(preview_json(session))
}
@@ -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<BakedMap>,
}
@@ -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<PreviewShow> {
match text {
"follow" => Some(PreviewShow::Follow),
"material" => Some(PreviewShow::Material),
_ => text.strip_prefix("map:").and_then(BakedMap::parse).map(PreviewShow::Pin),
}
}
}
+11
View File
@@ -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,
}
+3 -1
View File
@@ -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;
+10
View File
@@ -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<u64> {
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<Vec3> {
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<bool> {
p.get(key).and_then(Value::as_bool)
}
+170 -87
View File
@@ -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<CommandSpec> {
vec![
@@ -16,7 +16,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<CommandSpec> {
"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<Vec3> {
let a = p.get(key)?.as_array()?;
let v: Vec<f32> = 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<Option<(Vec3, Vec3, usize)>> {
if let Some(position) = vec3(params, "position") {
let normal = vec3(params, "normal").and_then(Vec3::try_normalize).ok_or_else(|| bad(command, "`position` needs a non-zero `normal`"))?;
return Ok(Some((position, normal, texture_set)));
}
}
/// Where a decal goes: a surface point and its normal, from `x`/`y` (viewport pixels, the view
/// center by default) or `position` + `normal`. None when `optional` and neither is given.
fn placement(s: &Session, cmd: &str, p: &Value, optional: bool) -> Result<Option<(Vec3, Vec3)>> {
if let Some(pos) = vec3(p, "position") {
let n = vec3(p, "normal").and_then(Vec3::try_normalize).ok_or_else(|| bad(cmd, "`position` needs a non-zero `normal`"))?;
return Ok(Some((pos, n)));
}
let vp = viewport_of(s, p);
let at = match (f32p(p, "x"), f32p(p, "y")) {
let viewport = viewport_of(session, params);
let point = match (f32p(params, "x"), f32p(params, "y")) {
(Some(x), Some(y)) => Vec2::new(x, y),
_ if optional => return Ok(None),
_ => vp * 0.5,
_ => viewport * 0.5,
};
let hit = s.pick(at, vp).ok_or_else(|| bad(cmd, "nothing under that point: place the decal on the mesh"))?;
if s.doc.project.texture_set(s.ts()).ok().map(|t| t.material) != Some(hit.material) {
return Err(bad(cmd, "that surface belongs to another texture set"));
}
Ok(Some((hit.pos, hit.nrm)))
let hit = session.pick(point, viewport).ok_or_else(|| bad(command, "nothing under that point: place the decal on the mesh"))?;
let hit_set = session.texture_set_of_material(hit.material).ok_or_else(|| bad(command, "that surface has no texture set"))?;
Ok(Some((hit.pos, hit.nrm, hit_set)))
}
/// A new decal's height, relative to the mesh diagonal
const DEFAULT_HEIGHT: f32 = 0.25;
/// The smallest decal side or depth, relative to the mesh diagonal
const MIN_SIZE: f32 = 1e-4;
/// The largest decal side or depth, relative to the mesh diagonal
const MAX_SIZE: f32 = 10.0;
/// The mesh's diagonal (decal sizes are relative to it).
fn mesh_size(s: &Session) -> f32 {
let (lo, hi) = s.mesh.bounds();
(hi - lo).length().max(1e-3)
}
/// Width and height from a `size` param (a height keeping `aspect`, or `[w, h]`).
fn size_param(p: &Value, aspect: f32, diag: f32) -> Option<[f32; 2]> {
let v = p.get("size")?;
let size = match v.as_array() {
Some(a) => [a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32],
/// Width and height from a `size` param (a height keeping `aspect`, or `[w, h]`), within the decal size limits
fn size_param(p: &Value, aspect: f32, mesh_diagonal: f32) -> Option<[f32; 2]> {
let value = p.get("size")?;
let size = match value.as_array() {
Some(pair) => [pair.first()?.as_f64()? as f32, pair.get(1)?.as_f64()? as f32],
None => {
let h = v.as_f64()? as f32;
[h * aspect, h]
let height = value.as_f64()? as f32;
[height * aspect, height]
}
};
size.iter().all(|x| x.is_finite()).then(|| size.map(|x| x.clamp(diag * 1e-4, diag * 10.0)))
size.iter().all(|side| side.is_finite()).then(|| size.map(|side| side.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE)))
}
/// The decal's up direction: `up` when given, else the camera's (decals are placed upright on
@@ -96,11 +94,25 @@ fn decal_up(s: &Session, cmd: &str, p: &Value, normal: Vec3) -> Result<Vec3> {
fn add(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "layer.add.decal";
let image = strp(p, "image").ok_or_else(|| bad(cmd, "`image` is required"))?.to_string();
let img = s.images.get(&image).ok_or_else(|| bad(cmd, format!("no image resource `{image}` (import it first)")))?;
let aspect = img.width as f32 / img.height.max(1) as f32;
let (center, normal) = placement(s, cmd, p, false)?.ok_or_else(|| bad(cmd, "no placement"))?;
let diag = mesh_size(s);
let size = size_param(p, aspect, diag).unwrap_or([diag * 0.25 * aspect, diag * 0.25]);
let resource = s.images.get(&image).ok_or_else(|| bad(cmd, format!("no image resource `{image}` (import it first)")))?;
let aspect = resource.width as f32 / resource.height.max(1) as f32;
let (center, normal, ts) = placement(s, cmd, p, s.ts(), false)?.ok_or_else(|| bad(cmd, "no placement"))?;
// None: the image masks a new fill layer
let target = match strp(p, "channel") {
Some("mask") => None,
_ => Some(channel_param(cmd, p, "channel")?.unwrap_or(Channel::BaseColor)),
};
let set_channels = s.doc.project.texture_set(ts)?.channel_list();
if let Some(channel) = target
&& !set_channels.contains(&channel)
{
return Err(bad(cmd, format!("the texture set has no {} channel", channel.label())));
}
let mesh_diagonal = mesh_size(s);
let default_height = mesh_diagonal * DEFAULT_HEIGHT;
let size = size_param(p, aspect, mesh_diagonal).unwrap_or([default_height * aspect, default_height]);
let decal = Decal {
center: center.to_array(),
normal: normal.to_array(),
@@ -108,68 +120,139 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
size,
rotation: f32p(p, "rotation").unwrap_or(0.0).rem_euclid(360.0),
offset: [0.0; 2],
depth: f32p(p, "depth").map_or(size[0].max(size[1]) * 0.5, |d| d.clamp(diag * 1e-4, diag * 10.0)),
// By default it reaches half its larger side into the surface
depth: f32p(p, "depth").map_or(size[0].max(size[1]) * 0.5, |depth| depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE)),
};
let ts = s.ts();
let base =
strp(p, "name").map(str::to_string).unwrap_or_else(|| std::path::Path::new(&image).file_stem().and_then(|n| n.to_str()).unwrap_or("Decal").to_string());
// A decal dropped on another texture set goes there and selects it, as a dropped material does
if ts != s.ts() {
crate::set_cmds::select_set(s, ts)?;
}
let base = strp(p, "name")
.map(str::to_string)
.unwrap_or_else(|| std::path::Path::new(&image).file_stem().and_then(|stem| stem.to_str()).unwrap_or("Decal").to_string());
let name = s.doc.project.next_layer_name(ts, &base);
let id = s.edit("Add decal", |s| {
let (id, mask_effect) = s.edit("Add decal", |s| {
let id = s.doc.project.alloc_id();
let Some(channel) = target else {
let effect_id = s.doc.project.alloc_id();
let mut layer = Layer::new(id, name, LayerKind::Fill(Fill::default()), &set_channels);
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(Effect::new(effect_id, EffectKind::Fill { source: Source::image(image.clone()), projection: Projection::Decal(decal) }));
layer.mask = Some(mask);
crate::layer_cmds::insert_selected(s, layer)?;
s.target = StackTarget::Effect(effect_id);
return Ok((id, Some(effect_id)));
};
let mut fill = Fill { projection: Projection::Decal(decal), ..Fill::default() };
fill.sources.insert(Channel::BaseColor, Source::image(image.clone()));
crate::layer_cmds::insert_selected(s, Layer::new(id, name, LayerKind::Fill(fill), &[Channel::BaseColor]))
fill.sources.insert(channel, Source::image(image.clone()));
crate::layer_cmds::insert_selected(s, Layer::new(id, name, LayerKind::Fill(fill), &[channel]))?;
Ok((id, None))
})?;
Ok(json!({ "layer": id.0, "decal": decal }))
Ok(json!({ "layer": id.0, "decal": decal, "maskEffect": mask_effect.map(|effect| effect.0) }))
}
/// The decal of fill layer `id`.
fn decal_of(s: &Session, cmd: &str, id: LayerId) -> Result<Decal> {
/// The decal of fill layer `id`, or of mask fill effect `effect` when given
fn decal_of(s: &Session, cmd: &str, id: LayerId, effect: Option<LayerId>) -> Result<Decal> {
if let Some(effect) = effect {
return match s.doc.project.effect(effect).map(|(_, effect)| &effect.kind) {
Some(EffectKind::Fill { projection: Projection::Decal(decal), .. }) => Ok(*decal),
_ => Err(bad(cmd, "the effect is not a decal (layer.add.decal with channel mask)")),
};
}
match &s.doc.project.layer(id)?.kind {
LayerKind::Fill(Fill { projection: Projection::Decal(d), .. }) => Ok(*d),
LayerKind::Fill(Fill { projection: Projection::Decal(decal), .. }) => Ok(*decal),
_ => Err(bad(cmd, "the layer is not a decal (layer.add.decal)")),
}
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "layer.decal.set";
let id = s.doc.project.content_layer(layer_param(s, cmd, p)?).map(|l| l.id).ok_or_else(|| bad(cmd, "no layer"))?;
let mut d = decal_of(s, cmd, id)?;
let diag = mesh_size(s);
if let Some((center, normal)) = placement(s, cmd, p, true)? {
(d.center, d.normal, d.offset) = (center.to_array(), normal.to_array(), [0.0; 2]);
}
if p.get("up").is_some() {
d.up = decal_up(s, cmd, p, Vec3::from(d.normal))?.to_array();
}
if let Some(size) = size_param(p, d.size[0] / d.size[1].max(1e-6), diag) {
d.size = size;
}
if let Some(r) = f32p(p, "rotation") {
d.rotation = r.rem_euclid(360.0);
}
if let Some(o) = p.get("offset").and_then(Value::as_array) {
let v: Vec<f32> = o.iter().filter_map(Value::as_f64).map(|x| x as f32).filter(|x| x.is_finite()).collect();
let [x, y] = v.as_slice() else { return Err(bad(cmd, "`offset` must be [right, up]")) };
d.offset = [x.clamp(-diag, diag), y.clamp(-diag, diag)];
}
if let Some(v) = f32p(p, "depth") {
d.depth = v.clamp(diag * 1e-4, diag * 10.0);
}
let image = strp(p, "image").map(str::to_string);
if let Some(name) = &image
&& !s.doc.resources.contains_key(name)
fn set(session: &mut Session, params: &Value) -> Result<Value> {
let command = "layer.decal.set";
let effect = u64p(params, "effect").map(LayerId);
let layer_id = match effect {
Some(effect) => session.doc.project.effect(effect).map(|(owner, _)| owner).ok_or_else(|| bad(command, format!("no effect {}", effect.0)))?,
None => session.doc.project.content_layer(layer_param(session, command, params)?).map(|layer| layer.id).ok_or_else(|| bad(command, "no layer"))?,
};
if let (Some(effect), Some(layer)) = (effect, u64p(params, "layer"))
&& layer != layer_id.0
{
return Err(bad(cmd, format!("no image resource `{name}`")));
return Err(bad(command, format!("effect {} is not in layer {layer}", effect.0)));
}
s.edit("Edit decal", |s| {
if let LayerKind::Fill(f) = &mut s.doc.project.layer_mut(id)?.kind {
f.projection = Projection::Decal(d);
if let Some(name) = image {
f.sources.insert(Channel::BaseColor, Source::image(name));
let mut decal = decal_of(session, command, layer_id, effect)?;
let texture_set =
session.doc.project.locate(layer_id).map(|(texture_set, _, _)| texture_set).ok_or_else(|| bad(command, "the decal has no texture set"))?;
let mesh_diagonal = mesh_size(session);
if let Some((center, normal, hit_set)) = placement(session, command, params, texture_set, true)? {
// Selecting another set must not let this decal leave its layer's stack
if hit_set != texture_set {
return Err(bad(command, "that surface belongs to another texture set"));
}
(decal.center, decal.normal, decal.offset) = (center.to_array(), normal.to_array(), [0.0; 2]);
}
if params.get("up").is_some() {
decal.up = decal_up(session, command, params, Vec3::from(decal.normal))?.to_array();
}
if let Some(size) = size_param(params, decal.size[0] / decal.size[1].max(1e-6), mesh_diagonal) {
decal.size = size;
}
if let Some(rotation) = f32p(params, "rotation") {
decal.rotation = rotation.rem_euclid(360.0);
}
if let Some(offset) = params.get("offset").and_then(Value::as_array) {
let values: Vec<f32> = offset.iter().filter_map(Value::as_f64).map(|value| value as f32).filter(|value| value.is_finite()).collect();
let [right, up] = values.as_slice() else { return Err(bad(command, "`offset` must be [right, up]")) };
decal.offset = [right.clamp(-mesh_diagonal, mesh_diagonal), up.clamp(-mesh_diagonal, mesh_diagonal)];
}
if let Some(depth) = f32p(params, "depth") {
decal.depth = depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE);
}
let image = strp(params, "image").map(str::to_string);
if let Some(name) = &image
&& !session.doc.resources.contains_key(name)
{
return Err(bad(command, format!("no image resource `{name}`")));
}
session.edit("Edit decal", |session| {
if let Some(effect) = effect {
if let Some(EffectKind::Fill { source, projection }) = session.doc.project.effect_mut(effect).map(|effect| &mut effect.kind) {
*projection = Projection::Decal(decal);
if let Some(image) = image {
*source = Source::image(image);
}
}
} else if let LayerKind::Fill(fill) = &mut session.doc.project.layer_mut(layer_id)?.kind {
fill.projection = Projection::Decal(decal);
// The new image goes where the decal's image is (the channel it was placed in)
let placed = fill.sources.values().find_map(|source| match source {
Source::Image { name, .. } => Some(name.clone()),
_ => None,
});
match (image, placed) {
(Some(image), Some(placed)) => {
for source in fill.sources.values_mut() {
if let Source::Image { name, .. } = source
&& *name == placed
{
name.clone_from(&image);
}
}
}
(Some(image), None) => {
fill.sources.insert(Channel::BaseColor, Source::image(image));
}
(None, _) => {}
}
}
Ok(())
})?;
Ok(json!({ "layer": id.0, "decal": d }))
Ok(json!({ "layer": layer_id.0, "decal": decal }))
}
+2 -2
View File
@@ -3,8 +3,8 @@
use serde_json::{Value, json};
#[cfg(not(target_arch = "wasm32"))]
use texturecraft_core::PROJECT_EXT;
use texturecraft_core::{NormalFormat, Project, TextureSet};
use texturecraft_core::{NormalFormat, PROJECT_EXT};
use texturecraft_core::{Project, TextureSet};
use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, Padding, ProjectFile};
use texturecraft_geom::{Mesh, primitives};
+1
View File
@@ -187,6 +187,7 @@ pub fn session(s: &Session) -> Value {
"layers": stack(s, ts),
"tool": { "tool": s.tool.tool.id(), "brush": crate::tool_cmds::brush_json(s) },
"view": s.view.label(),
"bakePreview": crate::bake_preview::preview_json(s),
"camera": crate::view_cmds::camera_json(s),
"display": s.doc.project.display,
"history": { "undo": s.undo_label(), "redo": s.redo_label(), "depth": s.history_labels().len() },
+7
View File
@@ -168,6 +168,12 @@ fn group(s: &mut Session, p: &Value) -> Result<Value> {
fn select(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.select", p)?;
let (ts, _, _) = s.doc.project.locate(id).ok_or_else(|| bad("layer.select", "layer not in a stack"))?;
// Paths paint into the active set
if ts != s.ts() {
s.finish_path()?;
}
s.active_set = ts;
s.selected.insert(ts, id);
s.target = match p.get("target") {
@@ -184,6 +190,7 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
},
None => StackTarget::Content,
};
s.revision = s.revision.wrapping_add(1);
Ok(json!({ "layer": id.0, "textureSet": ts }))
}
+5 -1
View File
@@ -9,6 +9,7 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod bake;
pub mod bake_preview;
pub mod brush_preset_cmds;
pub mod camera_cmds;
pub mod color_selection_cmds;
@@ -36,6 +37,7 @@ pub mod meshmap_import_cmds;
mod orb_camera;
pub mod orb_preview;
pub mod painting;
mod path_draft;
pub mod path_tool;
mod polygon_fill;
mod polygon_fill_drag;
@@ -52,13 +54,15 @@ pub mod set_cmds;
pub mod smart_masks;
pub mod template_cmds;
pub mod text_cmds;
pub mod thumbs;
pub mod tool_cmds;
mod triangle_partition;
mod uv_stroke_state;
pub mod uv_tile_cmds;
pub mod view_cmds;
pub use bake::{BakeMesh, BakeMeshes, BakeTask};
pub use bake::{BakeMesh, BakeMeshes, BakeTask, StreamedBake, StreamedMap};
pub use bake_preview::{BakePreview, PreviewShow};
pub use commands::{CommandSpec, command_specs, execute, find};
pub use fill_hit_test::FillHitTest;
pub use fill_mode::FillMode;
+3 -1
View File
@@ -8,7 +8,9 @@ use std::sync::Arc;
use serde_json::{Map, Value, json};
use texturecraft_core::{BakedMap, Channel, Fill, Layer, LayerId, LayerKind, LinkParam, MaterialLink, Source};
use texturecraft_formats::mcmat::{MCMAT_EXT, MCRAFT_EXT, PortableMaterial, is_mcraft, read_mcmat};
#[cfg(not(target_arch = "wasm32"))]
use texturecraft_formats::mcmat::MCMAT_EXT;
use texturecraft_formats::mcmat::{MCRAFT_EXT, PortableMaterial, is_mcraft, read_mcmat};
use crate::commands::{CommandSpec, bad, boolp, has_layer, layer_param, strp};
use crate::materials::Place;
+3 -1
View File
@@ -14,7 +14,9 @@ use serde_json::{Value, json};
use texturecraft_core::{Channel, Fill, Layer, LayerKind, Projection, Source};
use texturecraft_formats::materialx_read::{Material, Value as Mtlx};
use crate::commands::{CommandSpec, always, bad, strp};
use crate::commands::{CommandSpec, always};
#[cfg(not(target_arch = "wasm32"))]
use crate::commands::{bad, strp};
use crate::{EngineError, Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
+11
View File
@@ -155,6 +155,7 @@ impl Session {
/// Common setup of 3D and 2D strokes. `first_uv` is where the stroke starts on the mesh
/// (the Clone tool's destination anchor).
fn start_stroke(&mut self, viewport: Vec2, uv_mode: bool, first_uv: Option<Vec2>) -> Result<()> {
self.refuse_while_baking()?;
let tool = self.tool.tool;
let erase = tool == Tool::Eraser;
let quick_mask = self.quick_mask.editing;
@@ -296,9 +297,18 @@ impl Session {
Some(texturecraft_compose::Stencil { image, view_proj: self.camera.view_proj(aspect), center, half, rotation, tile: st.tile })
}
/// Painting is paused while a bake preview shows the baked maps instead of the material.
pub(crate) fn refuse_while_baking(&self) -> Result<()> {
match self.painting_blocked() {
Some(why) => Err(EngineError::Other(why.into())),
None => Ok(()),
}
}
/// Start a stroke at `screen` (viewport pixels). Returns false when the cursor misses the
/// mesh (the stroke starts anyway and resumes when the cursor enters the mesh).
pub fn begin_stroke(&mut self, screen: Vec2, viewport: Vec2, pressure: f32) -> Result<bool> {
self.refuse_while_baking()?;
self.cancel_stroke();
match self.tool.tool {
Tool::PolygonFill => return self.polygon_fill(screen, viewport).map(|_| true),
@@ -313,6 +323,7 @@ impl Session {
/// Start a stroke in the 2D view at texture coordinate `uv` (polygon fill fills there).
pub fn begin_stroke_uv(&mut self, uv: Vec2, pressure: f32) -> Result<()> {
self.refuse_while_baking()?;
self.cancel_stroke();
match self.tool.tool {
Tool::PolygonFill => return self.polygon_fill_uv(uv).map(|_| ()),
+13
View File
@@ -0,0 +1,13 @@
//! A new Path tool path previewed in the document before it is applied
use serde_json::Value;
use crate::Document;
/// A new path previewed in the document before it is applied
pub(crate) struct PathDraft {
/// The document before the preview
pub(crate) base: Document,
/// What painting the preview last reported (the commit's report when nothing changed since)
pub(crate) painted: Value,
}
+655 -95
View File
@@ -7,56 +7,108 @@
//! (`path.edit`, live while the points, brush or material change) or removed (`path.remove`).
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use texturecraft_compose::{PaintTarget, PixelStore};
use texturecraft_core::{Channel, Effect, EffectKind, LayerId, Mask, MaskBackground, PathShape};
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_geom::glam::{Mat3, Vec2, Vec3};
use texturecraft_geom::{OrbitCamera, surface_at};
use texturecraft_paint::{BrushSettings, Lasso, fill_coverage, spline};
use texturecraft_paint::{BrushSettings, Lasso, PickCtx, fill_coverage, pick, spline, spline_segments};
use texturecraft_texel::TileImage;
use crate::commands::{CommandSpec, always, bad, boolp, has_layer, u64p};
use crate::path_draft::PathDraft;
use crate::session::{StackTarget, Tool};
use crate::tool_cmds::{points_param, set_tool, viewport_of};
use crate::{EngineError, Result, Session, cmd};
use crate::{Document, EngineError, Result, Session, cmd};
/// Control points kept at most.
pub const MAX_PATH_POINTS: usize = 4096;
/// The undo step that adds a new path
pub(crate) const NEW_PATH_LABEL: &str = "Path";
/// Curve sampling step in viewport pixels (3D view) and texture units (2D view).
const STEP_PX: f32 = 2.0;
const STEP_UV: f32 = 0.001;
/// A stored path's viewport is clamped to this range (pixels per side) before painting from it
const MIN_PAINT_VIEWPORT_PX: f32 = 16.0;
const MAX_PAINT_VIEWPORT_PX: f32 = 16384.0;
/// Sampling step of a 3D path's curve on the mesh for the views, in its paint viewport pixels
const SURFACE_STEP_PX: f32 = 4.0;
const MIN_PROJECTIVE_W: f32 = 1e-6;
// Match the minimum world-space scale used by brush stamps
const MIN_BRUSH_SCALE: f32 = 1e-4;
// Allow ray hits to differ slightly from transformed texel positions
const RAY_HIT_RELATIVE_TOLERANCE: f32 = 0.001;
/// The curve being edited with the Path tool.
/// The curve being edited with the Path tool
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct PathState {
/// Control points: surface positions (3D view) or texture coordinates with z = 0 (2D view).
/// Control points: surface positions (3D view) or texture coordinates with z = 0 (2D view)
pub points: Vec<Vec3>,
/// The points are texture coordinates (placed in the 2D view).
/// The points are texture coordinates (placed in the 2D view)
pub uv: bool,
/// The curve loops back to its first point.
/// The curve loops back to its first point
pub closed: bool,
/// A closed path fills its interior instead of stroking the curve.
/// A closed path fills its interior instead of stroking the curve
pub fill: bool,
/// The stored path being edited: (path sublayer, index). Changes repaint it live.
/// The stored path being edited: (path sublayer, index). Changes repaint it live
#[serde(default)]
pub editing: Option<(LayerId, usize)>,
/// This edit has already repainted: later changes join its undo step, not an earlier edit's.
/// This edit has already repainted: later changes join its undo step, not an earlier edit's
#[serde(default)]
pub edited: bool,
/// The selected control point (drawn in the accent color; Backspace or Remove point removes it)
#[serde(default)]
pub selected: Option<usize>,
}
impl PathState {
/// Append a control point; a point placed in the other view starts a new path.
pub fn push(&mut self, p: Vec3, uv: bool) {
pub fn push(&mut self, point: Vec3, uv: bool) {
if uv != self.uv {
self.points.clear();
self.uv = uv;
}
if self.points.len() < MAX_PATH_POINTS {
self.points.push(p);
self.points.push(point);
}
}
/// Insert a control point before point `at` (on the segment ending there) and select it; None when it can't
pub fn insert(&mut self, at: usize, point: Vec3) -> Option<usize> {
if at > self.points.len() || self.points.len() >= MAX_PATH_POINTS {
return None;
}
self.points.insert(at, point);
self.selected = Some(at);
self.selected
}
/// The same curve (points, open or closed, filled, view) as `other`
fn same_curve(&self, other: &PathState) -> bool {
(&self.points, self.closed, self.fill, self.uv) == (&other.points, other.closed, other.fill, other.uv)
}
/// Empty the tool for the next path: no points, open, nothing selected or edited
pub fn clear(&mut self) {
self.points.clear();
self.closed = false;
self.selected = None;
self.editing = None;
self.edited = false;
}
/// Remove the selected control point, or the last one when none is selected
pub fn remove_selected(&mut self) {
let at = self.selected.take().filter(|i| *i < self.points.len()).or(self.points.len().checked_sub(1));
if let Some(i) = at {
self.points.remove(i);
}
if self.closed && self.points.len() < 3 {
self.closed = false;
}
}
}
@@ -116,31 +168,35 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
/// Set the curve from command parameters, then preview or commit it in the supplied viewport
fn path(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "tool.path";
if s.tool.tool != Tool::Path {
set_tool(s, Tool::Path)?;
}
let vp = viewport_of(s, p);
let viewport = viewport_of(s, p);
if boolp(p, "clear") == Some(true) {
s.tool.path.points.clear();
s.tool.path.editing = None;
s.cancel_path();
}
let placed = match (points_param(CMD, p, "points")?, points_param(CMD, p, "uvPoints")?) {
(Some(pts), _) => Some((
pts.iter()
(Some(pixels), _) => Some((
pixels
.iter()
.enumerate()
.map(|(i, q)| s.pick(*q, vp).map(|h| h.pos).ok_or_else(|| bad(CMD, format!("point {i} misses the mesh"))))
.map(|(i, pixel)| s.pick(*pixel, viewport).map(|hit| hit.pos).ok_or_else(|| bad(CMD, format!("point {i} misses the mesh"))))
.collect::<Result<Vec<_>>>()?,
false,
)),
(None, Some(pts)) => Some((pts.iter().map(|q| q.clamp(Vec2::ZERO, Vec2::ONE).extend(0.0)).collect(), true)),
(None, Some(uvs)) => Some((uvs.iter().map(|uv| uv.clamp(Vec2::ZERO, Vec2::ONE).extend(0.0)).collect(), true)),
(None, None) => None,
};
if let Some((points, uv)) = placed {
if points.len() > MAX_PATH_POINTS {
return Err(bad(CMD, format!("at most {MAX_PATH_POINTS} control points")));
}
s.tool.path.points = points;
s.tool.path.uv = uv;
}
@@ -151,19 +207,21 @@ fn path(s: &mut Session, p: &Value) -> Result<Value> {
s.tool.path.fill = v;
}
s.revision = s.revision.wrapping_add(1);
let committed = if boolp(p, "commit") == Some(true) {
let r = s.commit_path(vp)?;
let report = s.commit_path(viewport)?;
s.update();
r
report
} else {
if s.path_live()? {
if s.path_live_in_view(viewport)? {
s.update();
}
Value::Null
};
let st = &s.tool.path;
let editing = st.editing.map(|(e, i)| json!({ "effect": e.0, "index": i }));
Ok(json!({ "points": st.points.len(), "uv": st.uv, "closed": st.closed, "fill": st.fill, "editing": editing, "committed": committed }))
let path = &s.tool.path;
let editing = path.editing.map(|(e, i)| json!({ "effect": e.0, "index": i }));
Ok(json!({ "points": path.points.len(), "uv": path.uv, "closed": path.closed, "fill": path.fill, "editing": editing, "committed": committed }))
}
/// The `effect` and `index` params naming a stored path, with the path.
@@ -177,20 +235,25 @@ fn path_ref(s: &Session, cmd: &str, p: &Value) -> Result<(LayerId, usize, PathSh
Ok((eid, i, shape))
}
/// Finish any draft and load a stored path's geometry and paint settings for live editing
fn edit_path(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "path.edit";
let (eid, index, shape) = path_ref(s, CMD, p)?;
let paint = read_paint(&shape)?;
s.finish_path()?;
set_tool(s, Tool::Path)?;
s.tool.brush = paint.brush;
s.tool.values = paint.values;
s.tool.enabled = paint.enabled;
s.tool.mask_value = paint.mask_value;
s.tool.path = PathState { editing: Some((eid, index)), ..state_of(&shape) };
s.path_steps = Default::default();
s.target = StackTarget::Effect(eid);
Ok(json!({ "effect": eid.0, "index": index, "points": s.tool.path.points.len() }))
}
/// Remove one stored curve and repaint its sublayer as an atomic document edit
fn remove_path(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "path.remove";
let (eid, index, _) = path_ref(s, CMD, p)?;
@@ -216,10 +279,46 @@ fn read_paint(shape: &PathShape) -> Result<PathPaint> {
Ok(paint)
}
/// The Path tool state showing a stored path (finite points only, at most [`MAX_PATH_POINTS`]).
/// The Path tool state showing a stored path (finite points only, at most [`MAX_PATH_POINTS`])
fn state_of(shape: &PathShape) -> PathState {
let points = shape.points.iter().filter(|p| p.iter().all(|v| v.is_finite())).take(MAX_PATH_POINTS).map(|p| Vec3::from_array(*p)).collect();
PathState { points, uv: shape.uv, closed: shape.closed, fill: shape.fill, editing: None, edited: false }
PathState { points, uv: shape.uv, closed: shape.closed, fill: shape.fill, ..PathState::default() }
}
/// Tiles (x, y) where sublayer `eid`'s pixels differ between `before` and `after` (copy-on-write: an unchanged tile is the same allocation)
fn changed_tiles(before: &PixelStore, after: &PixelStore, eid: LayerId) -> BTreeSet<(u32, u32)> {
let (before_images, after_images) = (sublayer_images(before, eid), sublayer_images(after, eid));
let channels: BTreeSet<Option<Channel>> = before_images.keys().chain(after_images.keys()).copied().collect();
let mut tiles = BTreeSet::new();
for channel in channels {
let (before_image, after_image) = (before_images.get(&channel), after_images.get(&channel));
let Some(image) = before_image.or(after_image) else { continue };
for ty in 0..image.tiles_y() {
for tx in 0..image.tiles_x() {
let same = match (before_image.and_then(|i| i.tile_handle(tx, ty)), after_image.and_then(|i| i.tile_handle(tx, ty))) {
(None, None) => true,
(Some(before_tile), Some(after_tile)) => Arc::ptr_eq(before_tile, after_tile),
_ => false,
};
if !same {
tiles.insert((tx, ty));
}
}
}
}
tiles
}
/// Sublayer `eid`'s images by channel (None: its mask image)
fn sublayer_images(pixels: &PixelStore, eid: LayerId) -> BTreeMap<Option<Channel>, &TileImage> {
let layers = pixels.layers.iter().filter(|((id, _), _)| *id == eid).map(|((_, channel), image)| (Some(*channel), image));
layers.chain(pixels.masks.get(&eid).map(|mask| (None, mask))).collect()
}
/// The camera and viewport a stored path paints through (the views draw its curve the same way)
fn paint_view(shape: &PathShape, paint: &PathPaint) -> (OrbitCamera, Vec2) {
(paint.camera, Vec2::from_array(shape.viewport).max(Vec2::splat(MIN_PAINT_VIEWPORT_PX)).min(Vec2::splat(MAX_PAINT_VIEWPORT_PX)))
}
/// NDC (y up) to viewport pixels (origin top-left).
@@ -235,10 +334,16 @@ impl Session {
if path.uv {
return path.points.iter().map(|p| Some(p.truncate())).collect();
}
let aspect = viewport.x.max(1.0) / viewport.y.max(1.0);
path.points.iter().map(|p| self.camera.project(*p, aspect).map(|n| to_pixels(n.truncate(), viewport))).collect()
}
/// The stored paths of path sublayer `eid` as Path tool states, for the views to draw
pub fn stored_path_states(&self, eid: LayerId) -> Vec<PathState> {
self.paths(eid).unwrap_or_default().iter().map(state_of).collect()
}
/// The stored paths of path sublayer `eid` (None if it isn't one).
pub fn paths(&self, eid: LayerId) -> Option<&[PathShape]> {
match self.doc.project.effect(eid) {
@@ -261,12 +366,36 @@ impl Session {
}
}
/// Store the Path tool's curve (a new path in the selected path sublayer, or in a new one;
/// or the path being edited) and repaint the sublayer, as one undo step. Clears the tool.
/// Store the Path tool's curve (new, or the path being edited) and repaint its sublayer as one undo step, then clear the tool
pub fn commit_path(&mut self, viewport: Vec2) -> Result<Value> {
if let Some((effect, index)) = self.tool.path.editing
&& self.paths(effect).and_then(|paths| paths.get(index)).is_some_and(|stored| self.same_as_stored(stored))
{
// Camera navigation alone must not replace the pixels the user just previewed
let mut report = match self.path_draft.take() {
Some(draft) => {
self.push_step(NEW_PATH_LABEL, draft.base, false);
draft.painted
}
None => json!({}),
};
report["effect"] = json!(effect.0);
report["index"] = json!(index);
self.target = StackTarget::Effect(effect);
self.cancel_path();
return Ok(report);
}
if let Some(draft) = self.path_draft.take() {
// Changed settings paint again from the document before the preview
let preview = std::mem::replace(&mut self.doc, draft.base);
self.changed_without_history(&preview);
self.tool.path.editing = None;
}
let shape = self.path_shape(self.camera, viewport);
let editing = self.tool.path.editing;
let label = editing.map_or("Path".to_string(), |(_, i)| format!("Edit path {}", i + 1));
let label = editing.map_or(NEW_PATH_LABEL.to_string(), |(_, i)| format!("Edit path {}", i + 1));
let out = self.edit_merging(&label, editing.is_some() && self.tool.path.edited, |s| {
let (eid, index) = match editing {
Some(at) => at,
@@ -274,49 +403,309 @@ impl Session {
};
s.put_path(eid, index, shape)
})?;
if let Some(eid) = out.get("effect").and_then(Value::as_u64) {
self.target = StackTarget::Effect(LayerId(eid));
}
self.tool.path.points.clear();
self.tool.path.editing = None;
self.tool.path.clear();
Ok(out)
}
/// While a stored path is edited, repaint its sublayer when the tool's points, brush or
/// material changed (orbiting or resizing the view alone doesn't), merged into one undo
/// step. Cheap when nothing changed; the UI calls it every frame. Returns whether it
/// repainted.
/// Repaint the edited path (one merged undo step) or a new path's preview (no step) when its points, brush or material changed; called every frame
pub fn path_live(&mut self) -> Result<bool> {
let Some((eid, index)) = self.tool.path.editing else { return Ok(false) };
let Some(stored) = self.paths(eid).and_then(|v| v.get(index)).cloned() else {
self.stop_path_edit();
return Ok(false);
self.path_live_in_view(self.viewport)
}
/// Compare curve and typed paint settings through the stored camera and viewport
fn same_as_stored(&self, stored: &PathShape) -> bool {
// JSON round trips can change float representation without changing the paint settings
read_paint(stored).is_ok_and(|paint| {
let current = self.path_shape(paint.camera, Vec2::from_array(stored.viewport));
(&current.points, current.uv, current.closed, current.fill) == (&stored.points, stored.uv, stored.closed, stored.fill)
&& read_paint(&current).is_ok_and(|current_paint| current_paint == paint)
})
}
/// Preview a command's points in its supplied viewport, or the UI's current viewport
fn path_live_in_view(&mut self, viewport: Vec2) -> Result<bool> {
let stored = match self.tool.path.editing {
Some((eid, index)) => match self.paths(eid).and_then(|v| v.get(index)).cloned() {
Some(shape) => Some((eid, index, shape)),
None => {
self.stop_path_edit();
return Ok(false);
}
},
None => None,
};
if self.tool.tool != Tool::Path || self.stroke.is_some() {
return Ok(false);
}
if self.tool.path.points.is_empty() {
if let Some((effect, index, _)) = stored {
if self.path_draft.is_some() {
self.cancel_path();
} else {
self.edit_merging(&format!("Edit path {}", index + 1), self.tool.path.edited, |session| {
if let Some(Effect { kind: EffectKind::Path(paths), .. }) = session.doc.project.effect_mut(effect) {
paths.remove(index);
}
session.render_paths(effect, index)
})?;
self.cancel_path();
}
return Ok(true);
}
return Ok(false);
}
let path = &self.tool.path;
if self.tool.tool != Tool::Path || self.stroke.is_some() || path.points.is_empty() || (path.closed && path.fill && path.points.len() < 3) {
if path.closed && path.fill && path.points.len() < 3 {
return Ok(false);
}
// Typed comparison: the stored settings went through JSON (f64), maybe a save and load.
let unchanged = read_paint(&stored).is_ok_and(|p| {
let now = self.path_shape(p.camera, Vec2::from_array(stored.viewport));
(&now.points, now.uv, now.closed, now.fill) == (&stored.points, stored.uv, stored.closed, stored.fill) && read_paint(&now).is_ok_and(|n| n == p)
});
if unchanged {
let Some((eid, index, stored)) = stored else { return self.start_path_draft(viewport) };
if self.same_as_stored(&stored) {
return Ok(false);
}
let shape = self.path_shape(self.camera, self.viewport);
self.edit_merging(&format!("Edit path {}", index + 1), self.tool.path.edited, |s| s.put_path(eid, index, shape))?;
self.tool.path.edited = true;
let shape = self.path_shape(self.camera, viewport);
let (painted, before) = self.repaint_path(eid, index, shape)?;
match &mut self.path_draft {
Some(draft) => draft.painted = painted,
None => {
// The path's own repaint keeps its point changes undoable, unlike other steps
let steps = std::mem::take(&mut self.path_steps);
self.push_step(&format!("Edit path {}", index + 1), before, self.tool.path.edited);
self.path_steps = steps;
self.tool.path.edited = true;
}
}
Ok(true)
}
/// Stop editing a stored path (its changes are already applied) and clear the tool.
pub fn stop_path_edit(&mut self) {
if self.tool.path.editing.take().is_some() {
self.tool.path.points.clear();
/// Paint a new path's first preview where [`Session::commit_path`] would add it, keeping the document before it for apply and cancel
fn start_path_draft(&mut self, viewport: Vec2) -> Result<bool> {
let base = self.doc.clone();
let shape = self.path_shape(self.camera, viewport);
let placed = self.path_effect().and_then(|eid| {
let index = self.paths(eid).map_or(0, <[_]>::len);
self.put_path(eid, index, shape).map(|painted| ((eid, index), painted))
});
match placed {
Ok((at, painted)) => {
// Placing a path is a new action: what was undone before can't be redone over it
self.redo.clear();
self.tool.path.editing = Some(at);
self.changed_without_history(&base);
self.path_draft = Some(PathDraft { base, painted });
Ok(true)
}
Err(e) => {
self.doc = base;
Err(e)
}
}
}
/// Remember the curve before a point change from a view, so undo steps back through those changes while the path is edited
pub fn path_checkpoint(&mut self) {
if !self.path_steps.0.last().is_some_and(|s| s.same_curve(&self.tool.path)) {
self.path_steps.0.push(self.tool.path.clone());
// Each snapshot can contain thousands of points; bound point history like document history
let excess = self.path_steps.0.len().saturating_sub(crate::session::MAX_HISTORY);
self.path_steps.0.drain(..excess);
self.path_steps.1.clear();
}
}
/// Select a point without changing its geometry or clearing redo
pub fn select_path_point(&mut self, index: usize) {
self.tool.path.selected = (index < self.tool.path.points.len()).then_some(index);
}
/// Append and select a point, checkpointing the curve before it changes
pub fn append_path_point(&mut self, point: Vec3, uv: bool) -> Option<usize> {
if !point.is_finite() || (self.tool.path.uv == uv && self.tool.path.points.len() >= MAX_PATH_POINTS) {
return None;
}
// A click in the other view must not replace a committed path's coordinate space
if self.tool.path.editing.is_some() && self.path_draft.is_none() && self.tool.path.uv != uv {
return None;
}
self.path_checkpoint();
self.tool.path.push(point, uv);
self.tool.path.selected = self.tool.path.points.len().checked_sub(1);
self.tool.path.selected
}
/// Insert and select a point as one undoable point edit
pub fn insert_path_point(&mut self, index: usize, point: Vec3) -> Option<usize> {
if !point.is_finite() || index > self.tool.path.points.len() || self.tool.path.points.len() >= MAX_PATH_POINTS {
return None;
}
self.path_checkpoint();
self.tool.path.insert(index, point)
}
/// Move a point, checkpointing only the first actual movement in a drag
pub fn move_path_point(&mut self, index: usize, point: Vec3, begin_drag: bool) -> bool {
if !point.is_finite() || self.tool.path.points.get(index).is_none_or(|current| *current == point) {
return false;
}
if begin_drag {
self.path_checkpoint();
}
if let Some(current) = self.tool.path.points.get_mut(index) {
*current = point;
}
true
}
/// Remove the selected point, or the last one, as one undoable point edit
pub fn remove_selected_path_point(&mut self) {
if self.tool.path.points.is_empty() {
return;
}
self.path_checkpoint();
self.tool.path.remove_selected();
}
/// Change whether the path loops back to its first point, with point undo
pub fn set_path_closed(&mut self, closed: bool) {
if self.tool.path.closed != closed {
self.path_checkpoint();
self.tool.path.closed = closed;
}
}
/// Change whether a closed path fills its interior, with point undo
pub fn set_path_fill(&mut self, fill: bool) {
if self.tool.path.fill != fill {
self.path_checkpoint();
self.tool.path.fill = fill;
}
}
/// Whether [`Session::step_path`] would undo (`back`) or redo a point change
pub(crate) fn path_step_pending(&self, back: bool) -> bool {
let steps = if back { &self.path_steps.0 } else { &self.path_steps.1 };
self.tool.tool == Tool::Path && steps.iter().any(|s| !s.same_curve(&self.tool.path))
}
/// Undo calls needed to move back through document history, including pending path operations.
/// With zero document steps, only an uncommitted draft is canceled; stored edits stay applied.
pub fn history_undo_steps(&self, document_steps: usize) -> usize {
if document_steps == 0 && self.path_draft.is_none() {
return 0;
}
let (point_steps, clears_path) = self.path_steps_before_document(true);
let cancel_draft = self.path_draft.is_some() && !clears_path;
document_steps.saturating_add(point_steps).saturating_add(usize::from(cancel_draft))
}
/// Redo calls needed to move forward through document history, including pending point edits.
/// Unlike undo, document redo cancels any remaining draft in the same call.
pub fn history_redo_steps(&self, document_steps: usize) -> usize {
if document_steps == 0 {
return 0;
}
document_steps.saturating_add(self.path_steps_before_document(false).0)
}
/// Count pending point steps and whether their last step clears the path
fn path_steps_before_document(&self, back: bool) -> (usize, bool) {
if self.tool.tool != Tool::Path {
return (0, false);
}
let states = if back { &self.path_steps.0 } else { &self.path_steps.1 };
let mut steps = 0usize;
let mut current = &self.tool.path;
for state in states.iter().rev() {
if state.same_curve(current) {
continue;
}
steps = steps.saturating_add(1);
// Restoring an empty curve cancels the draft and clears point history in the same step
if state.points.is_empty() {
return (steps, true);
}
current = state;
}
(steps, false)
}
/// Undo (`back`) or redo a point change and repaint before returning; failure preserves the curve and history
pub(crate) fn step_path(&mut self, back: bool) -> Result<bool> {
if self.tool.tool != Tool::Path {
return Ok(false);
}
// Skip no-change checkpoints without consuming history until the repaint succeeds
let from = if back { &self.path_steps.0 } else { &self.path_steps.1 };
let Some((index, state)) = from.iter().enumerate().rfind(|(_, state)| !state.same_curve(&self.tool.path)) else { return Ok(false) };
let path = &mut self.tool.path;
let previous = std::mem::replace(path, PathState { editing: path.editing, edited: path.edited, ..state.clone() });
if let Err(error) = self.path_live() {
self.tool.path = previous;
return Err(error);
}
if self.tool.path.points.is_empty() {
self.stop_path_edit();
} else {
let (from, to) = if back { (&mut self.path_steps.0, &mut self.path_steps.1) } else { (&mut self.path_steps.1, &mut self.path_steps.0) };
from.truncate(index);
to.push(previous);
}
Ok(true)
}
/// Apply a new path being placed (as Enter would) and end the edit of a stored one, e.g. before the active texture set changes
pub fn finish_path(&mut self) -> Result<()> {
if self.path_draft.is_some() {
let viewport = self.viewport;
self.commit_path(viewport)?;
}
self.stop_path_edit();
Ok(())
}
/// Cancel the Path tool's path: a new one's preview is removed, a stored one keeps its applied changes
pub fn cancel_path(&mut self) {
self.stop_path_edit();
self.tool.path.clear();
}
/// Stop editing a stored path (its changes are already applied) and clear the tool; a new path's preview is removed
pub fn stop_path_edit(&mut self) {
if let Some(draft) = self.path_draft.take() {
let preview = std::mem::replace(&mut self.doc, draft.base);
self.changed_without_history(&preview);
}
if self.tool.path.editing.is_some() {
self.tool.path.clear();
}
self.path_steps = Default::default();
}
/// The selected path sublayer, or a new one on the selected layer's content or mask
/// (whichever is selected).
fn path_effect(&mut self) -> Result<LayerId> {
@@ -346,6 +735,32 @@ impl Session {
Ok(eid)
}
/// [`Session::put_path`] recompositing only the tiles it changed, with no undo step: returns the paint report and the document before
fn repaint_path(&mut self, eid: LayerId, index: usize, shape: PathShape) -> Result<(Value, Document)> {
let before = self.doc.clone();
let painted = match self.put_path(eid, index, shape) {
Ok(v) => v,
Err(e) => {
self.doc = before;
return Err(e);
}
};
// Paths paint into the active set; a sublayer in another set recomposites in full
let project = &self.doc.project;
let set = project.effect(eid).and_then(|(owner, _)| project.locate(owner)).map(|(ts, _, _)| ts);
if set == Some(self.ts()) {
// Content or mask, the sublayer's owner decides which sets redraw
let tiles = changed_tiles(&before.pixels, &self.doc.pixels, eid);
self.mark_painted(self.ts(), Some(PaintTarget::Layer(eid)), tiles);
} else {
self.invalidate_changed(&before);
}
self.revision = self.revision.wrapping_add(1);
self.modified = true;
Ok((painted, before))
}
/// Replace path `index` of sublayer `eid` (append when out of range) and repaint the
/// sublayer. Returns what painting that path reported, with the sublayer and index.
fn put_path(&mut self, eid: LayerId, index: usize, shape: PathShape) -> Result<Value> {
@@ -421,13 +836,41 @@ impl Session {
fn paint_shape(&mut self, shape: &PathShape) -> Result<Value> {
let paint = read_paint(shape)?;
let (camera, viewport) = paint_view(shape, &paint);
self.tool.brush = paint.brush;
self.tool.values = paint.values;
self.tool.enabled = paint.enabled;
self.tool.mask_value = paint.mask_value;
self.camera = paint.camera;
self.camera = camera;
self.tool.path = state_of(shape);
self.paint_path(Vec2::from_array(shape.viewport).max(Vec2::splat(16.0)).min(Vec2::splat(16384.0)))
self.paint_path(viewport)
}
/// Where a 3D path's curve lands on the mesh painted through `camera`, per segment as [`spline_segments`] (None off the mesh)
pub fn path_surface(&self, points: &[Vec3], closed: bool, camera: OrbitCamera, viewport: Vec2) -> Vec<Vec<Option<Vec3>>> {
let aspect = viewport.x.max(1.0) / viewport.y.max(1.0);
let Some(screen) = points.iter().map(|p| camera.project(*p, aspect).map(|n| to_pixels(n.truncate(), viewport))).collect::<Option<Vec<_>>>() else {
return Vec::new();
};
let ctx = PickCtx { mesh: &self.mesh, bvh: &self.bvh, camera: &camera, viewport };
spline_segments(&screen, closed, SURFACE_STEP_PX)
.into_iter()
.zip(&screen)
.map(|(samples, first)| std::iter::once(*first).chain(samples).map(|q| pick(&ctx, q).map(|hit| hit.pos)).collect())
.collect()
}
/// [`Session::path_surface`] of a stored 3D path through the camera and viewport it paints with
pub fn stored_path_surface(&self, eid: LayerId, index: usize) -> Option<Vec<Vec<Option<Vec3>>>> {
let shape = self.paths(eid)?.get(index)?;
if shape.uv {
return None;
}
let (camera, viewport) = paint_view(shape, &read_paint(shape).ok()?);
let path = state_of(shape);
Some(self.path_surface(&path.points, path.closed, camera, viewport))
}
/// Paint the Path tool's curve with the current brush (or fill it when closed and filled)
@@ -452,74 +895,101 @@ impl Session {
})
}
/// Fill the inside of `poly`: viewport pixels over the visible surface, or texture
/// coordinates. Returns the touched tiles.
fn lasso_fill(&mut self, poly: Vec<Vec2>, uv: bool, viewport: Vec2) -> Result<usize> {
let ts = self.ts();
let (gbuf, mut canvas) = self.fill_canvas(ts)?;
let w = gbuf.width.max(1);
/// Fill the inside of `polygon` (viewport pixels over the visible surface, or texture coordinates); returns the touched tiles
fn lasso_fill(&mut self, polygon: Vec<Vec2>, uv: bool, viewport: Vec2) -> Result<usize> {
let texture_set = self.ts();
let (uv_buffer, mut canvas) = self.fill_canvas(texture_set)?;
let width = uv_buffer.width.max(1);
if uv {
let lasso = Lasso::new(poly.iter().map(|p| *p * Vec2::new(w as f32, gbuf.height as f32)).collect());
fill_coverage(&mut canvas, &gbuf, |i, _| lasso.coverage(Vec2::new((i as u32 % w) as f32 + 0.5, (i as u32 / w) as f32 + 0.5)));
let lasso = Lasso::new(polygon.iter().map(|point| *point * Vec2::new(width as f32, uv_buffer.height as f32)).collect());
fill_coverage(&mut canvas, &uv_buffer, |texel, _| {
lasso.coverage(Vec2::new((texel as u32 % width) as f32 + 0.5, (texel as u32 / width) as f32 + 0.5))
});
} else {
let lasso = Lasso::new(poly);
let view_proj = self.camera.view_proj(viewport.x.max(1.0) / viewport.y.max(1.0));
let inv = view_proj.inverse();
let (cull, mesh, bvh) = (self.tool.brush.backface_culling, &self.mesh, &self.bvh);
let lasso = Lasso::new(polygon);
let view_projection = self.camera.view_proj(viewport.x.max(1.0) / viewport.y.max(1.0));
let inverse_view_projection = view_projection.inverse();
let (mesh, bvh) = (&self.mesh, &self.bvh);
let brush = self.tool.brush.sanitized();
// A visible source inside the lasso can paint each symmetry copy
let (lo, hi) = mesh.bounds();
let center = (lo + hi) * 0.5;
let inverses: Vec<_> = self.tool.brush.sanitized().symmetry.transforms().iter().map(|m| m.inverse()).collect();
let (bounds_min, bounds_max) = mesh.bounds();
let symmetry = brush.symmetry;
let symmetry_origin = symmetry.origin((bounds_min + bounds_max) * 0.5);
let inverses: Vec<_> = symmetry.transforms().iter().map(|transform| transform.inverse()).collect();
fill_coverage(&mut canvas, &gbuf, |i, _| {
let Some(s) = gbuf.surface(mesh, i) else { return 0.0 };
// Copies can leave the source surface, within the same depth allowed for brush stamps
let copy_depth = brush.size * (bounds_max - bounds_min).length().max(MIN_BRUSH_SCALE) * brush.depth;
let eye = self.camera.eye();
let camera_distance = self.camera.distance.max(MIN_BRUSH_SCALE);
// Bound the search using the farthest bounding-box corner; acceptance still uses the actual hit
let max_copy_depth =
if brush.screen_space { copy_depth * (bounds_min - eye).abs().max((bounds_max - eye).abs()).length() / camera_distance } else { copy_depth };
fill_coverage(&mut canvas, &uv_buffer, |texel, _| {
let Some(surface) = uv_buffer.surface(mesh, texel) else { return 0.0 };
let mut best = 0.0f32;
for m in &inverses {
let pos = center + *m * (s.pos - center);
let c = view_proj * pos.extend(1.0);
if c.w <= MIN_PROJECTIVE_W {
for inverse in &inverses {
let position = symmetry_origin + *inverse * (surface.pos - symmetry_origin);
let clip = view_projection * position.extend(1.0);
if clip.w <= MIN_PROJECTIVE_W {
continue;
}
let ndc = Vec2::new(c.x, c.y) / c.w;
let a = lasso.coverage(to_pixels(ndc, viewport));
if a <= best {
let normalized_screen = Vec2::new(clip.x, clip.y) / clip.w;
let coverage = lasso.coverage(to_pixels(normalized_screen, viewport));
if coverage <= best {
continue;
}
// Use the source surface normal; a copy may face away from the camera
let o = inv * ndc.extend(0.0).extend(1.0);
let origin = o.truncate() / o.w;
let to = pos - origin;
let d = to.length();
let Some(dir) = to.try_normalize() else { continue };
let Some(hit) =
bvh.closest(origin, dir, d * (1.0 + RAY_HIT_RELATIVE_TOLERANCE)).filter(|hit| hit.t >= d * (1.0 - RAY_HIT_RELATIVE_TOLERANCE))
else {
continue;
let near_clip = inverse_view_projection * normalized_screen.extend(0.0).extend(1.0);
let origin = near_clip.truncate() / near_clip.w;
let to_surface = position - origin;
let distance = to_surface.length();
let Some(direction) = to_surface.try_normalize() else { continue };
let is_copy = *inverse != Mat3::IDENTITY;
let max_distance = distance * (1.0 + RAY_HIT_RELATIVE_TOLERANCE);
let search_depth = if is_copy { max_copy_depth } else { 0.0 };
let Some(hit) = bvh.closest(origin, direction, max_distance + search_depth) else { continue };
// Keep identity copies exact and reject occluders beyond the bounded displacement
let off_surface = if !is_copy {
0.0
} else if brush.screen_space {
copy_depth * (origin + direction * hit.t).distance(eye) / camera_distance
} else {
copy_depth
};
let Some(source) = surface_at(mesh, hit.tri, hit.u, hit.v) else { continue };
if cull && source.nrm.dot(dir) >= 0.0 {
if hit.t < distance * (1.0 - RAY_HIT_RELATIVE_TOLERANCE) - off_surface || hit.t > max_distance + off_surface {
continue;
}
best = a;
let Some(source) = surface_at(mesh, hit.tri, hit.u, hit.v) else { continue };
if brush.backface_culling && source.nrm.dot(direction) >= 0.0 {
continue;
}
best = coverage;
}
best
});
}
let tiles = canvas.dirty.len();
self.commit_fill("Path fill", ts, &canvas)?;
self.commit_fill("Path fill", texture_set, &canvas)?;
Ok(tiles)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use crate::{Session, execute};
@@ -556,4 +1026,94 @@ mod tests {
assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path");
assert!(!cached.is_empty());
}
#[test]
fn point_insertion_and_removal_respect_boundaries() {
let mut path = PathState { points: vec![Vec3::ZERO, Vec3::X], ..Default::default() };
assert_eq!(path.insert(2, Vec3::Y), Some(2));
assert_eq!(path.points, vec![Vec3::ZERO, Vec3::X, Vec3::Y]);
assert_eq!(path.insert(4, Vec3::Z), None);
path.closed = true;
path.selected = Some(usize::MAX);
path.remove_selected();
assert_eq!(path.points, vec![Vec3::ZERO, Vec3::X]);
assert!(!path.closed);
path.remove_selected();
path.remove_selected();
path.remove_selected();
assert!(path.points.is_empty());
assert_eq!(path.selected, None);
path.points = vec![Vec3::ZERO; MAX_PATH_POINTS];
assert_eq!(path.insert(MAX_PATH_POINTS, Vec3::X), None);
assert_eq!(path.points.len(), MAX_PATH_POINTS);
}
#[test]
fn changed_tiles_include_mask_and_channel_creation_and_deletion() {
let effect = LayerId(7);
let mut before = PixelStore::default();
let mut image = TileImage::new(192, 128, 1);
image.tile_mut(0, 0, &[1]).unwrap();
before.masks.insert(effect, image.clone());
before.layers.insert((effect, Channel::Roughness), image.clone());
let mut after = before.clone();
after.masks.get_mut(&effect).unwrap().set_tile(0, 0, None);
after.masks.get_mut(&effect).unwrap().tile_mut(2, 1, &[1]).unwrap();
after.layers.remove(&(effect, Channel::Roughness));
image.set_tile(0, 0, None);
image.tile_mut(1, 0, &[1]).unwrap();
after.layers.insert((effect, Channel::Metallic), image);
assert_eq!(changed_tiles(&before, &before.clone(), effect), BTreeSet::new());
assert_eq!(changed_tiles(&before, &after, effect), BTreeSet::from([(0, 0), (1, 0), (2, 1)]));
assert_eq!(changed_tiles(&before, &after, LayerId(8)), BTreeSet::new());
}
#[test]
fn point_checkpoints_skip_noops_and_bound_retained_points() {
let mut session = Session::new_project("t", texturecraft_geom::primitives::plane(1.0, 1), "builtin:test", None, 128).unwrap();
session.tool.tool = Tool::Path;
session.tool.path.points = vec![Vec3::ZERO; MAX_PATH_POINTS];
session.path_checkpoint();
assert!(!session.path_step_pending(true));
assert!(!session.step_path(true).unwrap());
for index in 0..crate::session::MAX_HISTORY + 10 {
session.path_checkpoint();
session.tool.path.points[0].x = index as f32 + 1.0;
}
assert_eq!(session.path_steps.0.len(), crate::session::MAX_HISTORY);
assert_eq!(session.path_steps.0.iter().map(|state| state.points.len()).sum::<usize>(), crate::session::MAX_HISTORY * MAX_PATH_POINTS);
session.path_checkpoint();
assert!(session.step_path(true).unwrap(), "a no-change checkpoint does not consume an undo");
assert_eq!(session.tool.path.points[0].x, (crate::session::MAX_HISTORY + 9) as f32);
}
#[test]
fn stored_surface_uses_bounded_viewports_and_skips_uv_paths() {
let mut session = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap();
execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap();
let StackTarget::Effect(effect) = session.target else { panic!("path sublayer") };
assert!(session.stored_path_surface(effect, 0).is_none());
let shape = session.paths(effect).unwrap()[0].clone();
let paint = read_paint(&shape).unwrap();
let mut shape = shape;
shape.viewport = [-1.0, f32::MAX];
assert_eq!(paint_view(&shape, &paint).1, Vec2::new(MIN_PAINT_VIEWPORT_PX, MAX_PAINT_VIEWPORT_PX));
let points = [Vec3::new(-0.2, 0.0, 1.0), Vec3::new(0.0, 0.2, 1.0), Vec3::new(0.2, 0.0, 1.0)];
session.camera.yaw = 0.0;
session.camera.pitch = 0.0;
let surface = session.path_surface(&points, true, session.camera, Vec2::splat(400.0));
assert_eq!(surface.len(), 3);
let first = surface.first().unwrap().first().unwrap().unwrap();
let last = surface.last().unwrap().last().unwrap().unwrap();
assert!(first.distance(last) < 1e-5, "the closed curve returns to its starting surface point");
let off_mesh = session.path_surface(&[Vec3::new(10.0, 0.0, 0.0), Vec3::new(11.0, 0.0, 0.0)], false, session.camera, Vec2::splat(400.0));
assert!(!off_mesh.is_empty());
assert!(off_mesh.iter().flatten().all(Option::is_none));
}
}
+7
View File
@@ -19,6 +19,7 @@ const CORNER_GRID_STEPS: f32 = 1e5;
impl Session {
/// Fill the triangle / polygon / UV island / connected mesh under viewport pixel `screen`
pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result<usize> {
self.refuse_while_baking()?;
let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?;
if hit.material != self.fill_material()? {
return Err(EngineError::Other("that surface belongs to another texture set".into()));
@@ -29,6 +30,7 @@ impl Session {
/// Fill like [`Session::polygon_fill`] at texture coordinate `uv` (the 2D view): the triangle covering that texel's center, so slivers thinner than a texel can't be clicked
pub fn polygon_fill_uv(&mut self, uv: Vec2) -> Result<usize> {
self.refuse_while_baking()?;
let gbuf = self.caches.get(self.ts()).map(|cache| cache.gbuf.clone()).ok_or_else(|| EngineError::Other("texture set not ready".into()))?;
let size = Vec2::new(gbuf.width as f32, gbuf.height as f32);
let texel = (uv * size).floor();
@@ -43,6 +45,8 @@ impl Session {
/// Fill what the box between viewport pixels `corner` and `opposite` selects (one undo step)
pub fn polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result<usize> {
self.refuse_while_baking()?;
// A scripted box stands alone: it finishes any drag under way, and ends even when it fails
self.end_polygon_fill_box();
let shown = self.drag_polygon_fill_box(corner, opposite, viewport);
@@ -52,6 +56,8 @@ impl Session {
/// Fill what the box between texture coordinates `corner` and `opposite` selects (the 2D view, one undo step)
pub fn polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result<usize> {
self.refuse_while_baking()?;
self.end_polygon_fill_box();
let shown = self.drag_polygon_fill_box_uv(corner, opposite);
let filled = self.end_polygon_fill_box();
@@ -83,6 +89,7 @@ impl Session {
/// Show the fill of a box from `corner` to `opposite` in the 3D view of size `viewport`, or in the 2D view when None
fn drag_polygon_fill(&mut self, corner: Vec2, opposite: Vec2, viewport: Option<Vec2>) -> Result<usize> {
self.refuse_while_baking()?;
if !corner.is_finite() || !opposite.is_finite() {
return Err(EngineError::Other("the box corners must be finite".into()));
}
+17 -14
View File
@@ -105,34 +105,37 @@ impl Session {
/// Includes the stroke in progress.
pub fn quick_mask_rgba(&self, ts: usize, size: u32) -> Option<Vec<u8>> {
let cache = self.caches.get(ts)?;
let (w, h) = cache.size;
let size = size.clamp(1, w.max(h));
let (width, height) = cache.size;
let size = size.clamp(1, width.max(height));
let mask = self.quick_mask_image(ts, cache.size);
let live = self.stroke.as_ref().filter(|s| s.ts == ts && s.target.is_none()).map(|s| (&s.canvas.alpha, s.stroke.settings.opacity, s.erase));
let base = cache.composite.channels.get(&Channel::BaseColor);
let lut = srgb_lut();
let srgb = srgb_lut();
let inverted = self.quick_mask.inverted;
let mut out = vec![255u8; size as usize * size as usize * 4];
out.par_chunks_mut(size as usize * 4).enumerate().for_each(|(y, row)| {
let ty = (y as u64 * u64::from(h) / u64::from(size)) as u32;
for (x, px) in row.chunks_exact_mut(4).enumerate() {
let tx = (x as u64 * u64::from(w) / u64::from(size)) as u32;
let mut m = from_u16(mask.get(tx, ty)[0]);
let ty = (y as u64 * u64::from(height) / u64::from(size)) as u32;
for (x, pixel) in row.as_chunks_mut::<4>().0.iter_mut().enumerate() {
let tx = (x as u64 * u64::from(width) / u64::from(size)) as u32;
let mut coverage = from_u16(mask.get(tx, ty)[0]);
if let Some((alpha, opacity, erase)) = live {
let a = from_u16(alpha.get(tx, ty)[0]) * opacity;
m = if erase { m * (1.0 - a) } else { a + m * (1.0 - a) };
let stroke_coverage = from_u16(alpha.get(tx, ty)[0]) * opacity;
coverage = if erase { coverage * (1.0 - stroke_coverage) } else { stroke_coverage + coverage * (1.0 - stroke_coverage) };
}
let blocked = if inverted { m } else { 1.0 - m };
let blocked = if inverted { coverage } else { 1.0 - coverage };
let raw = base.map(|b| b.get(tx, ty)).unwrap_or([32768; 4]);
let t = 0.55 * blocked;
let tint_amount = 0.55 * blocked;
for (k, tint) in [0.9, 0.1, 0.15].into_iter().enumerate() {
let c = f32::from(lut.get(usize::from(raw[k] >> 4)).copied().unwrap_or(0)) / 255.0;
if let Some(slot) = px.get_mut(k) {
*slot = ((c + (tint - c) * t).clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
let color = f32::from(srgb.get(usize::from(raw[k] >> 4)).copied().unwrap_or(0)) / 255.0;
if let Some(slot) = pixel.get_mut(k) {
*slot = ((color + (tint - color) * tint_amount).clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
}
}
}
});
Some(out)
}
}
+73 -10
View File
@@ -341,6 +341,8 @@ pub struct Session {
pub target: StackTarget,
pub camera: OrbitCamera,
pub view: ViewMode,
/// The live bake preview while the app bakes (see [`crate::bake_preview`]).
pub bake_preview: Option<crate::bake_preview::BakePreview>,
/// Viewport size (pixels) used by scripted strokes.
pub viewport: Vec2,
pub(crate) stroke: Option<ActiveStroke>,
@@ -354,6 +356,10 @@ pub struct Session {
pub(crate) painting_paths: bool,
/// Pixels of the paths below the one being edited, so live edits skip repainting them.
pub(crate) path_cache: Option<crate::path_tool::PathCache>,
/// A new path's live preview: the path becomes an undo step only when it is applied
pub(crate) path_draft: Option<crate::path_draft::PathDraft>,
/// Point changes of the path being edited: (earlier states for undo, undone states for redo)
pub(crate) path_steps: (Vec<crate::path_tool::PathState>, Vec<crate::path_tool::PathState>),
pub path: Option<String>,
pub modified: bool,
/// Bumps on every document change.
@@ -372,8 +378,7 @@ pub struct Session {
}
impl Session {
/// A session for `project` on `mesh` (texture sets must reference mesh materials). The
/// UVs of UV-tiled sets are mapped into their tile atlas (see [`Session::source_mesh`]).
/// A session for `project` on `mesh` (its sets must reference mesh materials), with UV-tiled sets' UVs mapped into their atlas ([`Session::source_mesh`])
pub fn new(doc: Document, mesh: Mesh, mesh_source: Option<(String, Vec<u8>)>) -> Result<Session> {
mesh.validate().map_err(|e| EngineError::Other(e.to_string()))?;
let source = Arc::new(mesh);
@@ -403,6 +408,7 @@ impl Session {
target: StackTarget::Content,
camera,
view: ViewMode::Material,
bake_preview: None,
viewport: Vec2::new(1280.0, 800.0),
stroke: None,
clipboard: None,
@@ -410,6 +416,8 @@ impl Session {
quick_mask: Default::default(),
painting_paths: false,
path_cache: None,
path_draft: None,
path_steps: Default::default(),
path: None,
modified: false,
revision: 1,
@@ -526,21 +534,43 @@ impl Session {
self.record(label, before, false);
}
/// A change from `before` to the current document: a new undo step `label`, or with
/// `merge` part of the previous one when it has the same label.
/// A change from `before`: a new undo step `label`, or with `merge` part of the previous one when it has the same label
fn record(&mut self, label: &str, before: Document, merge: bool) {
self.invalidate_changed(&before);
self.push_step(label, before, merge);
}
/// [`Session::record`] for a change whose tiles the caller already marked for recompositing
pub(crate) fn push_step(&mut self, label: &str, before: Document, merge: bool) {
// Another change during a new path's preview makes the path its own step first
if !self.painting_paths
&& let Some(draft) = self.path_draft.take()
{
self.undo.push((crate::path_tool::NEW_PATH_LABEL.to_string(), draft.base));
}
// Point changes of an edited path undo only until another step lands
if !self.painting_paths {
self.path_steps = Default::default();
}
self.modified = true;
self.revision = self.revision.wrapping_add(1);
self.invalidate_changed(&before);
if !(merge && self.undo.last().is_some_and(|(l, _)| l == label)) {
self.undo.push((label.to_string(), before));
if self.undo.len() > MAX_HISTORY {
self.undo.remove(0);
}
}
let over = self.undo.len().saturating_sub(MAX_HISTORY);
self.undo.drain(..over);
self.redo.clear();
}
/// A change from `other` to the current document that is not an undo step (a path preview)
pub(crate) fn changed_without_history(&mut self, other: &Document) {
self.modified = true;
self.revision = self.revision.wrapping_add(1);
self.invalidate_changed(other);
}
/// Mark dirty every texture set whose composite differs between `other` and the current
/// document (after an edit, undo or redo).
pub(crate) fn invalidate_changed(&mut self, other: &Document) {
@@ -617,18 +647,32 @@ impl Session {
}
}
/// Whether a point edit, an uncommitted path preview, or a document edit can be undone
pub fn can_undo(&self) -> bool {
!self.undo.is_empty()
!self.undo.is_empty() || self.path_draft.is_some() || self.path_step_pending(true)
}
/// Whether a point edit or document edit can be restored
pub fn can_redo(&self) -> bool {
!self.redo.is_empty()
!self.redo.is_empty() || self.path_step_pending(false)
}
/// Label of the next undo action, giving an active path's point edits and preview priority
pub fn undo_label(&self) -> Option<&str> {
if self.path_draft.is_some() || self.path_step_pending(true) {
return Some(crate::path_tool::NEW_PATH_LABEL);
}
self.undo.last().map(|(l, _)| l.as_str())
}
/// Label of the next redo action, giving an active path's point history priority
pub fn redo_label(&self) -> Option<&str> {
if self.path_step_pending(false) {
return Some(crate::path_tool::NEW_PATH_LABEL);
}
self.redo.last().map(|(l, _)| l.as_str())
}
/// The undone steps, the next one to redo first.
pub fn redo_labels(&self) -> Vec<String> {
self.redo.iter().rev().map(|(l, _)| l.clone()).collect()
@@ -637,10 +681,23 @@ impl Session {
self.undo.iter().map(|(l, _)| l.clone()).collect()
}
/// Undo a point edit, cancel an uncommitted path, or restore a document snapshot, in that order
pub fn undo(&mut self) -> Result<String> {
// A stroke, a box fill or an edited path under way would otherwise write over the restored document
self.cancel_stroke();
self.end_polygon_fill_box();
// While a path is edited, undo steps back through its point changes first
if self.step_path(true)? {
return Ok(crate::path_tool::NEW_PATH_LABEL.to_string());
}
// A path being placed isn't a step yet: undo removes it
if self.path_draft.is_some() {
self.stop_path_edit();
return Ok(crate::path_tool::NEW_PATH_LABEL.to_string());
}
self.stop_path_edit();
let (label, restored) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?;
@@ -651,10 +708,16 @@ impl Session {
Ok(label)
}
/// Restore a point edit and its pixels before considering document redo
pub fn redo(&mut self) -> Result<String> {
// A stroke, a box fill or an edited path under way would otherwise write over the restored document
self.cancel_stroke();
self.end_polygon_fill_box();
if self.step_path(false)? {
return Ok(crate::path_tool::NEW_PATH_LABEL.to_string());
}
self.stop_path_edit();
let (label, restored) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?;
+17 -2
View File
@@ -75,12 +75,27 @@ pub(crate) fn ts_param(s: &Session, p: &Value, cmd: &str) -> Result<usize> {
}
fn select(s: &mut Session, p: &Value) -> Result<Value> {
let ts = u64p(p, "ts").map(|t| t as usize).filter(|t| *t < s.set_count()).ok_or_else(|| bad("textureSet.select", "valid `ts` index required"))?;
let ts = u64p(p, "ts")
.map(|index| index as usize)
.filter(|index| *index < s.set_count())
.ok_or_else(|| bad("textureSet.select", "valid `ts` index required"))?;
select_set(s, ts)?;
Ok(json!({ "ts": ts }))
}
/// Make texture set `ts` the active one, on its content stack
pub(crate) fn select_set(s: &mut Session, ts: usize) -> Result<()> {
s.cancel_stroke();
// Paths paint into the active set
if ts != s.ts() {
s.finish_path()?;
}
s.active_set = ts;
s.target = StackTarget::Content;
s.revision = s.revision.wrapping_add(1);
Ok(json!({ "ts": ts }))
Ok(())
}
fn resolution(s: &mut Session, p: &Value) -> Result<Value> {
+1
View File
@@ -25,6 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
/// Fonts bundled with the app (egui's), used when nothing is installed or in the browser.
const BUILT_IN: [(&str, &[u8]); 2] = [("Ubuntu Light", epaint_default_fonts::UBUNTU_LIGHT), ("Hack", epaint_default_fonts::HACK_REGULAR)];
/// Families tried, in order, when no font is asked for.
#[cfg(not(target_arch = "wasm32"))]
const DEFAULT_FAMILIES: [&str; 6] = ["Arial", "Segoe UI", "Helvetica", "Liberation Sans", "DejaVu Sans", "Noto Sans"];
/// Largest font file read.
#[cfg(not(target_arch = "wasm32"))]
+570
View File
@@ -0,0 +1,570 @@
//! Asynchronous layer-panel thumbnails.
//!
//! The panel asks for small previews of layer contents, masks and effect stages
//! ([`ThumbTarget`]). The work never runs on the UI thread and never touches the main composite:
//!
//! * A **snapshot** ([`ThumbSnapshot`]) is an immutable copy of what the compositor reads (the
//! project, copy-on-write pixel tiles, baked maps, images and the mesh) plus a 64 px G-buffer.
//! It is rebuilt only when the document really changed, at most every [`DEBOUNCE`] seconds
//! (a slider drag renders at that pace, not once per frame).
//! * A **worker thread** evaluates one target at a time from a snapshot with
//! [`texturecraft_compose::thumb::render`]. On wasm32 (no threads) one job runs per
//! [`ThumbService::poll`] instead.
//! * Results are kept in a small LRU **cache** ([`CACHE_ENTRIES`]). A result computed from an
//! older snapshot than the current one is dropped, so a slow job can never overwrite a newer
//! thumbnail. An entry that is out of date keeps showing until its replacement arrives.
//! * Only targets requested during the current frame are rendered: a row that scrolled away
//! before its turn is dropped from the queue.
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::Arc;
use texturecraft_compose::{BakedMaps, ImageStore, Inputs, PixelStore, THUMB_TEXELS, ThumbImage, ThumbTarget, thumb};
use texturecraft_core::Project;
use texturecraft_geom::glam::Vec3;
use texturecraft_geom::{Mesh, UvGBuffer};
use crate::Session;
/// Thumbnails kept.
pub const CACHE_ENTRIES: usize = 96;
/// Seconds between checks for a changed document while it keeps changing.
pub const DEBOUNCE: f64 = 0.12;
/// Jobs handed to the worker at once (the rest wait here, where they can still be dropped).
const IN_FLIGHT: usize = 2;
/// An immutable copy of everything the thumbnails of one texture set read.
pub struct ThumbSnapshot {
ts: usize,
mesh_id: u64,
project: Project,
pixels: PixelStore,
baked: BakedMaps,
images: ImageStore,
mesh: Arc<Mesh>,
gbuf: Arc<UvGBuffer>,
bounds: (Vec3, Vec3),
}
impl ThumbSnapshot {
/// Snapshot texture set `ts` of `s`, with the G-buffer from `gbufs` (built on a miss).
pub fn new(s: &Session, ts: usize, gbufs: &mut GbufCache) -> Option<ThumbSnapshot> {
let material = s.doc.project.texture_set(ts).ok()?.material;
let gbuf = gbufs.get(&s.mesh, s.mesh_id, material);
Some(ThumbSnapshot {
ts,
mesh_id: s.mesh_id,
project: s.doc.project.clone(),
pixels: s.doc.pixels.clone(),
baked: s.doc.baked.get(&ts).cloned().unwrap_or_default(),
images: s.images.clone(),
mesh: s.mesh.clone(),
gbuf,
bounds: s.mesh.bounds(),
})
}
/// Whether `session` would give the same thumbnails as this snapshot.
fn matches(&self, session: &Session, texture_set: usize) -> bool {
let same_pixels = self.pixels.layers.len() == session.doc.pixels.layers.len()
&& self.pixels.masks.len() == session.doc.pixels.masks.len()
&& self.pixels.layers.iter().all(|(key, pixels)| session.doc.pixels.layers.get(key) == Some(pixels))
&& self.pixels.masks.iter().all(|(key, pixels)| session.doc.pixels.masks.get(key) == Some(pixels));
let empty = BakedMaps::default();
let baked = session.doc.baked.get(&texture_set).unwrap_or(&empty);
// Copy-on-write maps change handles on edits; float equality would scan entire bakes
let same_baked = self.baked.resolution == baked.resolution
&& self.baked.maps.len() == baked.maps.len()
&& self.baked.maps.iter().all(|(map, pixels)| baked.maps.get(map).is_some_and(|current| Arc::ptr_eq(pixels, current)));
self.ts == texture_set
&& self.mesh_id == session.mesh_id
&& self.project == session.doc.project
&& same_pixels
&& same_baked
&& self.images.len() == session.images.len()
&& self.images.iter().all(|(key, image)| session.images.get(key).is_some_and(|current| Arc::ptr_eq(current, image)))
}
/// Render `target`: the work of one job.
pub fn render(&self, target: ThumbTarget) -> Option<ThumbImage> {
let inp = Inputs {
project: &self.project,
ts: self.ts,
mesh: &self.mesh,
gbuf: &self.gbuf,
pixels: &self.pixels,
baked: &self.baked,
block_scales: self.project.texture_set(self.ts).map(|set| set.block_scales()).unwrap_or_default(),
preview: None,
images: &self.images,
bounds: self.bounds,
};
thumb::render(&inp, target)
}
/// Whether the layer or effect `target` shows still exists in the snapshot's project.
fn has(&self, target: ThumbTarget) -> bool {
has_target(&self.project, target)
}
}
fn has_target(p: &Project, target: ThumbTarget) -> bool {
match target {
ThumbTarget::Content { layer, .. } | ThumbTarget::Mask { layer } => p.layers.contains_key(&layer),
ThumbTarget::Stage { effect, .. } => p.effect(effect).is_some(),
}
}
/// The 64 px G-buffers built so far, per mesh and material (rasterizing is the one part of a
/// snapshot that is not just copying handles).
#[derive(Default)]
pub struct GbufCache {
map: HashMap<(u64, usize), Arc<UvGBuffer>>,
}
impl GbufCache {
fn get(&mut self, mesh: &Mesh, mesh_id: u64, material: usize) -> Arc<UvGBuffer> {
if self.map.len() > 16 {
self.map.clear();
}
self.map.entry((mesh_id, material)).or_insert_with(|| Arc::new(UvGBuffer::new(mesh, material, THUMB_TEXELS, THUMB_TEXELS))).clone()
}
}
struct Entry {
/// None: the target has nothing to show (a layer without that channel).
image: Option<Arc<ThumbImage>>,
/// Snapshot generation it was rendered from.
generation: u64,
/// Changes whenever `image` does (views key their GPU textures on it).
version: u64,
used: u64,
}
/// What the panel draws for one target.
#[derive(Clone)]
pub struct ThumbView {
pub image: Option<Arc<ThumbImage>>,
/// Identifies `image`; changes when a new picture arrives.
pub version: u64,
/// A newer picture is on its way.
pub pending: bool,
}
struct Job {
snapshot: Arc<ThumbSnapshot>,
generation: u64,
target: ThumbTarget,
}
struct Done {
generation: u64,
target: ThumbTarget,
image: Option<ThumbImage>,
}
#[cfg(not(target_arch = "wasm32"))]
struct Worker {
tx: std::sync::mpsc::Sender<Job>,
rx: std::sync::mpsc::Receiver<Done>,
}
#[cfg(not(target_arch = "wasm32"))]
fn spawn_worker() -> Option<Worker> {
let (tx, jobs) = std::sync::mpsc::channel::<Job>();
let (done_tx, rx) = std::sync::mpsc::channel::<Done>();
std::thread::Builder::new()
.name("layer-thumbs".into())
.spawn(move || {
while let Ok(job) = jobs.recv() {
let image = job.snapshot.render(job.target);
if done_tx.send(Done { generation: job.generation, target: job.target, image }).is_err() {
break;
}
}
})
.ok()?;
Some(Worker { tx, rx })
}
/// The thumbnail cache and its worker. One lives in the UI; see the module documentation.
pub struct ThumbService {
snapshot: Option<Arc<ThumbSnapshot>>,
/// Bumps whenever the snapshot's content changes; entries and jobs carry it.
generation: u64,
/// The session revision the snapshot was last compared with.
seen: Option<u64>,
last_check: f64,
cache: HashMap<ThumbTarget, Entry>,
tick: u64,
versions: u64,
queue: VecDeque<ThumbTarget>,
in_flight: HashSet<(u64, ThumbTarget)>,
wanted: HashSet<ThumbTarget>,
gbufs: GbufCache,
#[cfg(not(target_arch = "wasm32"))]
worker: Option<Worker>,
#[cfg(not(target_arch = "wasm32"))]
spawned: bool,
/// Jobs run inline (wasm32, or no worker thread could start).
inline: VecDeque<Job>,
/// Pictures computed (tests, benchmarks).
pub rendered: u64,
}
impl Default for ThumbService {
fn default() -> Self {
ThumbService {
snapshot: None,
generation: 0,
seen: None,
last_check: f64::NEG_INFINITY,
cache: HashMap::new(),
tick: 0,
versions: 0,
queue: VecDeque::new(),
in_flight: HashSet::new(),
wanted: HashSet::new(),
gbufs: GbufCache::default(),
#[cfg(not(target_arch = "wasm32"))]
worker: None,
#[cfg(not(target_arch = "wasm32"))]
spawned: false,
inline: VecDeque::new(),
rendered: 0,
}
}
}
impl ThumbService {
pub fn new() -> ThumbService {
ThumbService::default()
}
/// Start of a frame: forget what the last frame asked for and notice document changes.
pub fn begin_frame(&mut self, session: &Session, now: f64) {
self.wanted.clear();
let texture_set = session.ts();
if self.seen == Some(session.revision)
&& self.snapshot.as_ref().is_some_and(|snapshot| snapshot.ts == texture_set && snapshot.mesh_id == session.mesh_id)
{
return;
}
// Compare at the debounce pace while the document keeps changing
if self.snapshot.is_some() && now - self.last_check < DEBOUNCE {
return;
}
self.last_check = now;
if self.snapshot.as_ref().is_some_and(|snapshot| snapshot.matches(session, texture_set)) {
self.seen = Some(session.revision);
return;
}
self.snapshot = ThumbSnapshot::new(session, texture_set, &mut self.gbufs).map(Arc::new);
self.seen = Some(session.revision);
self.generation = self.generation.wrapping_add(1);
// Keep dispatched jobs counted until they finish, even when their snapshot is stale
self.queue.clear();
for job in self.inline.drain(..) {
self.in_flight.remove(&(job.generation, job.target));
}
if let Some(snapshot) = &self.snapshot {
self.cache.retain(|target, _| snapshot.has(*target));
} else {
self.cache.clear();
}
}
/// Whether the displayed pictures wait for a document comparison that is still debounced.
fn checked(&self, session: &Session) -> bool {
self.seen == Some(session.revision)
}
/// The picture for `target` (call for the rows on screen only). Queues work when the
/// picture is missing or out of date.
pub fn get(&mut self, session: &Session, target: ThumbTarget) -> ThumbView {
self.wanted.insert(target);
self.tick = self.tick.wrapping_add(1);
let fresh = self.cache.get(&target).is_some_and(|entry| entry.generation == self.generation);
let checked = self.checked(session);
if !fresh && checked && self.snapshot.is_some() && !self.in_flight.contains(&(self.generation, target)) && !self.queue.contains(&target) {
self.queue.push_back(target);
}
match self.cache.get_mut(&target) {
Some(entry) => {
entry.used = self.tick;
ThumbView { image: entry.image.clone(), version: entry.version, pending: !(fresh && checked) }
}
None => ThumbView { image: None, version: 0, pending: true },
}
}
/// End of a frame: collect results, discard unrequested rows, and dispatch new work.
/// Returns whether another frame is needed, including to display newly collected pictures.
pub fn poll(&mut self, session: &Session) -> bool {
let changed = self.collect();
self.queue.retain(|target| self.wanted.contains(target));
self.dispatch();
self.trim();
changed || !self.queue.is_empty() || !self.in_flight.is_empty() || !self.checked(session)
}
fn dispatch(&mut self) {
let Some(snapshot) = self.snapshot.clone() else { return };
while self.in_flight.len() < IN_FLIGHT {
let Some(target) = self.queue.pop_front() else { break };
let job = Job { snapshot: snapshot.clone(), generation: self.generation, target };
self.in_flight.insert((job.generation, target));
self.send(job);
}
}
#[cfg(not(target_arch = "wasm32"))]
fn send(&mut self, job: Job) {
if !self.spawned {
self.spawned = true;
self.worker = spawn_worker();
}
match &self.worker {
Some(worker) => {
if let Err(error) = worker.tx.send(job) {
// A stopped worker cannot complete any of its outstanding jobs
self.worker = None;
self.in_flight.clear();
self.in_flight.insert((error.0.generation, error.0.target));
self.inline.push_back(error.0);
}
}
None => self.inline.push_back(job),
}
}
#[cfg(target_arch = "wasm32")]
fn send(&mut self, job: Job) {
self.inline.push_back(job);
}
fn collect(&mut self) -> bool {
let mut completed = Vec::new();
let mut changed = false;
#[cfg(not(target_arch = "wasm32"))]
if let Some(worker) = &self.worker {
loop {
match worker.rx.try_recv() {
Ok(result) => completed.push(result),
Err(std::sync::mpsc::TryRecvError::Empty) => break,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
// Request another frame so wanted targets retry on the inline fallback
self.worker = None;
self.in_flight.clear();
changed = true;
break;
}
}
}
}
// Without a thread, bound each poll to one render
if let Some(job) = self.inline.pop_front() {
let image = job.snapshot.render(job.target);
completed.push(Done { generation: job.generation, target: job.target, image });
}
for result in completed {
self.rendered = self.rendered.wrapping_add(1);
self.in_flight.remove(&(result.generation, result.target));
// A picture of an older snapshot never replaces a newer one
if result.generation != self.generation {
continue;
}
if !self.snapshot.as_ref().is_some_and(|snapshot| snapshot.has(result.target)) {
continue;
}
self.versions = self.versions.wrapping_add(1);
let entry = Entry { image: result.image.map(Arc::new), generation: result.generation, version: self.versions, used: self.tick };
self.cache.insert(result.target, entry);
changed = true;
}
changed
}
fn trim(&mut self) {
while self.cache.len() > CACHE_ENTRIES {
let Some(oldest) = self.cache.iter().filter(|(t, _)| !self.wanted.contains(t)).min_by_key(|(_, e)| e.used).map(|(t, _)| *t) else { break };
self.cache.remove(&oldest);
}
}
/// Entries held (tests).
pub fn cached(&self) -> usize {
self.cache.len()
}
/// Whether `target` has a picture of the current snapshot (tests).
pub fn is_fresh(&self, target: ThumbTarget) -> bool {
self.cache.get(&target).is_some_and(|e| e.generation == self.generation)
}
/// Whether any work is queued or running (tests).
pub fn busy(&self) -> bool {
!self.queue.is_empty() || !self.in_flight.is_empty() || !self.inline.is_empty()
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
use texturecraft_core::Channel;
use texturecraft_geom::primitives;
fn test_session() -> crate::Result<Session> {
Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128)
}
fn held_worker() -> (ThumbService, std::sync::mpsc::Receiver<Job>, std::sync::mpsc::Sender<Done>) {
let (sender, jobs) = std::sync::mpsc::channel();
let (results, receiver) = std::sync::mpsc::channel();
let service = ThumbService { worker: Some(Worker { tx: sender, rx: receiver }), spawned: true, ..Default::default() };
(service, jobs, results)
}
#[test]
fn unchanged_baked_handles_match_even_with_non_finite_samples() {
let mut session = test_session().unwrap();
let baked = session.doc.baked.entry(0).or_default();
baked.resolution = 1;
baked.maps.insert(texturecraft_core::BakedMap::Height, Arc::new(vec![f32::NAN]));
let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap();
assert!(snapshot.matches(&session, 0), "unchanged shared data must not invalidate every frame");
let map = session.doc.baked.get_mut(&0).unwrap().maps.get_mut(&texturecraft_core::BakedMap::Height).unwrap();
Arc::make_mut(map)[0] = 0.5;
assert!(!snapshot.matches(&session, 0), "a copy-on-write edit must invalidate the snapshot");
}
#[test]
#[ignore]
fn benchmark_unchanged_4k_baked_snapshot() {
let mut session = test_session().unwrap();
let baked = session.doc.baked.entry(0).or_default();
baked.resolution = 4096;
baked.maps.insert(texturecraft_core::BakedMap::Normal, Arc::new(vec![0.5; 4096 * 4096 * 3]));
baked.maps.insert(texturecraft_core::BakedMap::AmbientOcclusion, Arc::new(vec![0.5; 4096 * 4096]));
let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap();
let start = std::time::Instant::now();
for _ in 0..20 {
assert!(std::hint::black_box(&snapshot).matches(std::hint::black_box(&session), 0));
}
eprintln!("20 unchanged snapshot comparisons, 4K normal + AO (256 MiB): {:?}", start.elapsed());
}
#[test]
fn collecting_the_last_result_requests_a_frame_to_display_it() {
let session = test_session().unwrap();
let target = ThumbTarget::Content { layer: session.selected_layer().unwrap(), channel: Channel::BaseColor };
let (mut service, jobs, results) = held_worker();
service.begin_frame(&session, 0.0);
service.get(&session, target);
assert!(service.poll(&session));
let job = jobs.try_recv().unwrap();
results.send(Done { generation: job.generation, target, image: job.snapshot.render(target) }).unwrap();
service.begin_frame(&session, 0.1);
assert!(service.get(&session, target).image.is_none());
let repaint = service.poll(&session);
assert!(service.is_fresh(target));
assert!(repaint, "the frame drew before collecting the final thumbnail");
service.begin_frame(&session, 0.2);
assert!(service.get(&session, target).image.is_some());
assert!(!service.poll(&session), "an idle cache must stop repainting");
}
#[test]
fn a_stopped_worker_retries_visible_targets_inline() {
let session = test_session().unwrap();
let target = ThumbTarget::Content { layer: session.selected_layer().unwrap(), channel: Channel::BaseColor };
let (mut service, jobs, results) = held_worker();
service.begin_frame(&session, 0.0);
service.get(&session, target);
service.poll(&session);
// Simulate a worker that stops with a dispatched request still outstanding
drop(jobs);
drop(results);
for frame in 1..=4 {
service.begin_frame(&session, f64::from(frame));
service.get(&session, target);
service.poll(&session);
}
assert!(service.get(&session, target).image.is_some());
assert!(!service.busy());
}
#[test]
fn edits_keep_worker_jobs_and_retained_snapshots_bounded() {
let mut session = test_session().unwrap();
let layer = session.selected_layer().unwrap();
let target = ThumbTarget::Content { layer, channel: Channel::BaseColor };
let (mut service, jobs, results) = held_worker();
let mut snapshots = Vec::new();
// Hold the worker's receiver still while repeated edits each produce a new snapshot
for revision in 0..2_000 {
session.doc.pixels.layer_mut(layer, Channel::BaseColor, (128, 128)).set(0, 0, &[revision, 0, 0, u16::MAX]);
session.revision += 1;
service.begin_frame(&session, f64::from(revision));
snapshots.push(Arc::downgrade(service.snapshot.as_ref().unwrap()));
service.get(&session, target);
service.poll(&session);
}
let queued: Vec<_> = jobs.try_iter().collect();
let retained = snapshots.iter().filter(|snapshot| snapshot.strong_count() > 0).count();
let retained_pixel_bytes: usize = snapshots.iter().filter_map(std::sync::Weak::upgrade).map(|snapshot| snapshot.pixels.bytes()).sum();
eprintln!("2,000 edits: {} queued jobs, {retained} live snapshots, {retained_pixel_bytes} retained pixel bytes", queued.len());
assert!(queued.len() <= IN_FLIGHT, "{} queued jobs bypassed the worker limit", queued.len());
assert!(retained <= IN_FLIGHT + 1, "{retained} document snapshots retained across edits");
assert!(retained_pixel_bytes <= (IN_FLIGHT + 1) * texturecraft_texel::TILE_AREA * 4 * std::mem::size_of::<u16>());
// Finishing stale work frees a slot for the newest document, without caching old results
for job in queued {
results.send(Done { generation: job.generation, target: job.target, image: None }).unwrap();
}
assert_eq!(snapshots.iter().filter(|snapshot| snapshot.strong_count() > 0).count(), 1, "completed jobs release stale snapshots");
assert!(service.poll(&session));
assert!(!service.is_fresh(target));
let latest = jobs.try_recv().unwrap();
assert_eq!(latest.generation, service.generation);
results.send(Done { generation: latest.generation, target, image: latest.snapshot.render(target) }).unwrap();
drop(latest);
assert!(service.poll(&session));
assert!(service.is_fresh(target));
let image = Arc::downgrade(service.cache.get(&target).unwrap().image.as_ref().unwrap());
drop(service);
assert!(snapshots.iter().all(|snapshot| snapshot.upgrade().is_none()), "dropping the cache releases its last snapshot");
assert!(image.upgrade().is_none(), "dropping the cache releases the rendered image");
assert!(jobs.try_recv().is_err());
}
}
+148 -82
View File
@@ -4,12 +4,12 @@
use serde_json::{Value, json};
use texturecraft_core::Channel;
use texturecraft_geom::glam::Vec2;
use texturecraft_paint::{Alignment, BrushAlpha, alphas};
use texturecraft_paint::{Alignment, BrushAlpha, MAX_RADIAL_COPIES, alphas};
use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp};
use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp, vec3};
use crate::fill_hit_test::FillHitTest;
use crate::fill_mode::FillMode;
use crate::session::{CloneFrom, CloneSource, Tool};
use crate::session::{CloneFrom, CloneSource, StackTarget, Tool};
use crate::{Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Brush settings",
[],
None,
"{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, backfaceCulling?, symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), minSize?, smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}",
"{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, backfaceCulling?, symmetryOn? (the toolbar toggle; off keeps the settings), symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), symmetryOffset?: [x, y, z] (world units from the mesh center, where the mirror planes and radial axis cross), symmetryAngleSpan?: 0..360 degrees the radial copies spread over, minSize?, smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}",
always,
brush
),
@@ -53,6 +53,15 @@ pub fn specs() -> Vec<CommandSpec> {
always,
material
),
cmd!(
"tool.swapMaskValue",
"Invert mask value",
["Tools"],
Some("X"),
"{} — mask value becomes 1 − value: switch the brush between adding to and removing from the mask",
paints_mask,
swap_mask_value
),
cmd!(
"tool.stencil",
"Projection stencil",
@@ -119,126 +128,159 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
set_tool(s, t)
}
/// Brush values use the UI's 0–100 scales, so agents and the sliders speak the same numbers.
fn brush(s: &mut Session, p: &Value) -> Result<Value> {
let b = &mut s.tool.brush;
let pct = |k: &str| f32p(p, k).map(|v| v / 100.0);
if let Some(v) = pct("size") {
b.size = v * 0.25;
/// Brush values use the UI's 0–100 scales, so agents and the sliders speak the same numbers
fn brush(session: &mut Session, params: &Value) -> Result<Value> {
let mut settings = session.tool.brush.clone();
let percent = |key: &str| f32p(params, key).map(|value| value / 100.0);
if let Some(value) = percent("size") {
settings.size = value * 0.25;
}
if let Some(v) = pct("minSize") {
b.min_size = v;
if let Some(value) = percent("minSize") {
settings.min_size = value;
}
if let Some(v) = pct("flow") {
b.flow = v;
if let Some(value) = percent("flow") {
settings.flow = value;
}
if let Some(v) = pct("opacity") {
b.opacity = v;
if let Some(value) = percent("opacity") {
settings.opacity = value;
}
if let Some(v) = pct("spacing") {
b.spacing = v;
if let Some(value) = percent("spacing") {
settings.spacing = value;
}
if let Some(v) = pct("hardness") {
b.hardness = v;
if let Some(value) = percent("hardness") {
settings.hardness = value;
}
if let Some(v) = f32p(p, "angle") {
b.angle = v;
if let Some(value) = f32p(params, "angle") {
settings.angle = value;
}
if let Some(v) = boolp(p, "followPath") {
b.follow_path = v;
if let Some(value) = boolp(params, "followPath") {
settings.follow_path = value;
}
if let Some(a) = strp(p, "alignment") {
b.alignment = match a {
if let Some(alignment) = strp(params, "alignment") {
settings.alignment = match alignment {
"camera" => Alignment::Camera,
"tangent" | "uv" => Alignment::Tangent,
other => return Err(bad("tool.brush", format!("unknown alignment `{other}`"))),
};
}
if let Some(v) = f32p(p, "lazy") {
b.lazy = v;
if let Some(value) = f32p(params, "lazy") {
settings.lazy = value;
}
for (k, slot) in [("jitterSize", &mut b.jitter_size), ("jitterAngle", &mut b.jitter_angle), ("jitterFlow", &mut b.jitter_flow)] {
if let Some(v) = f32p(p, k) {
*slot = v / 100.0;
for (key, slot) in [("jitterSize", &mut settings.jitter_size), ("jitterAngle", &mut settings.jitter_angle), ("jitterFlow", &mut settings.jitter_flow)] {
if let Some(value) = f32p(params, key) {
*slot = value / 100.0;
}
}
if let Some(v) = f32p(p, "jitterPosition") {
b.jitter_position = v / 100.0;
if let Some(value) = f32p(params, "jitterPosition") {
settings.jitter_position = value / 100.0;
}
let alpha = p.get("alpha");
if let Some(a) = strp(p, "alpha") {
b.alpha = BrushAlpha::parse(a).ok_or_else(|| bad("tool.brush", format!("unknown alpha `{a}`")))?;
(b.alpha_image, b.alpha_library) = (None, None);
} else if let Some(name) = alpha.and_then(|a| a.get("image")).and_then(Value::as_str) {
if !s.images.contains_key(name) {
let alpha = params.get("alpha");
if let Some(alpha_name) = strp(params, "alpha") {
settings.alpha = BrushAlpha::parse(alpha_name).ok_or_else(|| bad("tool.brush", format!("unknown alpha `{alpha_name}`")))?;
(settings.alpha_image, settings.alpha_library) = (None, None);
} else if let Some(name) = alpha.and_then(|alpha| alpha.get("image")).and_then(Value::as_str) {
if !session.images.contains_key(name) {
return Err(bad("tool.brush", format!("no image resource `{name}` (import it first)")));
}
(b.alpha_image, b.alpha_library) = (Some(name.to_string()), None);
} else if let Some(id) = alpha.and_then(|a| a.get("library")).and_then(Value::as_str) {
let a = alphas::find(id).ok_or_else(|| bad("tool.brush", format!("unknown library alpha `{id}` (see alpha.list)")))?;
// Render it now rather than on the first stamp.
a.image();
(b.alpha_image, b.alpha_library) = (None, Some(a.id.clone()));
(settings.alpha_image, settings.alpha_library) = (Some(name.to_string()), None);
} else if let Some(id) = alpha.and_then(|alpha| alpha.get("library")).and_then(Value::as_str) {
let alpha = alphas::find(id).ok_or_else(|| bad("tool.brush", format!("unknown library alpha `{id}` (see alpha.list)")))?;
// Render it now rather than on the first stamp
alpha.image();
(settings.alpha_image, settings.alpha_library) = (None, Some(alpha.id.clone()));
}
if let Some(v) = boolp(p, "backfaceCulling") {
b.backface_culling = v;
if let Some(value) = boolp(params, "backfaceCulling") {
settings.backface_culling = value;
}
for (k, slot) in [("symmetryX", &mut b.symmetry.x), ("symmetryY", &mut b.symmetry.y), ("symmetryZ", &mut b.symmetry.z)] {
if let Some(v) = boolp(p, k) {
*slot = v;
if let Some(value) = boolp(params, "symmetryOn") {
settings.symmetry.enabled = value;
}
for (key, slot) in [("symmetryX", &mut settings.symmetry.x), ("symmetryY", &mut settings.symmetry.y), ("symmetryZ", &mut settings.symmetry.z)] {
if let Some(value) = boolp(params, key) {
*slot = value;
}
}
if let Some(v) = f32p(p, "symmetryRadial") {
b.symmetry.radial = v.clamp(0.0, 32.0) as u8;
if let Some(value) = f32p(params, "symmetryRadial") {
settings.symmetry.radial = value.clamp(0.0, f32::from(MAX_RADIAL_COPIES)) as u8;
}
if let Some(a) = strp(p, "symmetryAxis") {
b.symmetry.axis = match a.to_ascii_lowercase().as_str() {
if let Some(axis) = strp(params, "symmetryAxis") {
settings.symmetry.axis = match axis.to_ascii_lowercase().as_str() {
"x" => 0,
"y" => 1,
"z" => 2,
_ => return Err(bad("tool.brush", format!("unknown symmetry axis `{a}` (x, y or z)"))),
_ => return Err(bad("tool.brush", format!("unknown symmetry axis `{axis}` (x, y or z)"))),
};
}
if let Some(v) = boolp(p, "screenSpace") {
b.screen_space = v;
if let Some(value) = f32p(params, "symmetryAngleSpan") {
settings.symmetry.angle_span = value;
}
if let Some(q) = p.get("particles") {
let pt = &mut b.particles;
pt.enabled = boolp(q, "enabled").unwrap_or(pt.enabled);
pt.count = f32p(q, "count").map_or(pt.count, |v| v as u32);
pt.lifetime = f32p(q, "lifetime").map_or(pt.lifetime, |v| v as u32);
pt.gravity = f32p(q, "gravity").unwrap_or(pt.gravity);
if params.get("symmetryOffset").is_some() {
settings.symmetry.offset = vec3(params, "symmetryOffset").ok_or_else(|| bad("tool.brush", "`symmetryOffset` must be [x, y, z]"))?.to_array();
}
*b = b.sanitized();
if let Some(v) = f32p(p, "smudgeStrength") {
s.tool.smudge_strength = (v / 100.0).clamp(0.0, 1.0);
if let Some(value) = boolp(params, "screenSpace") {
settings.screen_space = value;
}
if let Some(v) = strp(p, "cloneSource") {
s.tool.clone_from = match v {
if let Some(particle_params) = params.get("particles") {
let particles = &mut settings.particles;
particles.enabled = boolp(particle_params, "enabled").unwrap_or(particles.enabled);
particles.count = f32p(particle_params, "count").map_or(particles.count, |value| value as u32);
particles.lifetime = f32p(particle_params, "lifetime").map_or(particles.lifetime, |value| value as u32);
particles.gravity = f32p(particle_params, "gravity").unwrap_or(particles.gravity);
}
let clone_from = if let Some(value) = strp(params, "cloneSource") {
match value {
"composite" => CloneFrom::Composite,
"layer" => CloneFrom::Layer,
other => return Err(bad("tool.brush", format!("unknown clone source `{other}`: use composite or layer"))),
};
}
} else {
session.tool.clone_from
};
session.tool.brush = settings.sanitized();
session.tool.clone_from = clone_from;
if let Some(value) = f32p(params, "smudgeStrength") {
session.tool.smudge_strength = (value / 100.0).clamp(0.0, 1.0);
}
s.revision = s.revision.wrapping_add(1);
Ok(brush_json(s))
session.revision = session.revision.wrapping_add(1);
Ok(brush_json(session))
}
pub(crate) fn brush_json(s: &Session) -> Value {
let b = &s.tool.brush;
pub(crate) fn brush_json(session: &Session) -> Value {
let settings = &session.tool.brush;
json!({
"size": b.size / 0.25 * 100.0, "minSize": b.min_size * 100.0, "flow": b.flow * 100.0, "opacity": b.opacity * 100.0,
"spacing": b.spacing * 100.0, "hardness": b.hardness * 100.0, "angle": b.angle, "followPath": b.follow_path,
"alignment": format!("{:?}", b.alignment).to_lowercase(), "lazy": b.lazy,
"alpha": match (&b.alpha_image, &b.alpha_library) {
"size": settings.size / 0.25 * 100.0, "minSize": settings.min_size * 100.0, "flow": settings.flow * 100.0, "opacity": settings.opacity * 100.0,
"spacing": settings.spacing * 100.0, "hardness": settings.hardness * 100.0, "angle": settings.angle, "followPath": settings.follow_path,
"alignment": format!("{:?}", settings.alignment).to_lowercase(), "lazy": settings.lazy,
"alpha": match (&settings.alpha_image, &settings.alpha_library) {
(Some(name), _) => json!({ "image": name }),
(None, Some(id)) => json!({ "library": id }),
(None, None) => json!(b.alpha.label()),
(None, None) => json!(settings.alpha.label()),
},
"backfaceCulling": b.backface_culling, "symmetry": [b.symmetry.x, b.symmetry.y, b.symmetry.z],
"radialSymmetry": { "copies": b.symmetry.radial, "axis": (["x", "y", "z"].get(b.symmetry.axis as usize)) },
"smudgeStrength": s.tool.smudge_strength * 100.0, "particles": b.particles,
"cloneSource": if s.tool.clone_from == CloneFrom::Layer { "layer" } else { "composite" },
"backfaceCulling": settings.backface_culling, "symmetry": [settings.symmetry.x, settings.symmetry.y, settings.symmetry.z],
"radialSymmetry": { "copies": settings.symmetry.radial, "axis": (["x", "y", "z"].get(settings.symmetry.axis as usize)) },
"symmetryOffset": settings.symmetry.offset, "symmetryOn": settings.symmetry.enabled, "symmetryAngleSpan": settings.symmetry.angle_span,
"smudgeStrength": session.tool.smudge_strength * 100.0, "particles": settings.particles,
"cloneSource": if session.tool.clone_from == CloneFrom::Layer { "layer" } else { "composite" },
})
}
@@ -273,6 +315,30 @@ fn material(s: &mut Session, p: &Value) -> Result<Value> {
}))
}
/// Whether strokes paint the selected layer's mask: the mask itself or one of its effects
fn paints_mask(session: &Session) -> std::result::Result<(), String> {
session.selected_layer().ok_or("no layer selected")?;
let project = &session.doc.project;
let targets_mask = match session.target {
StackTarget::Content => false,
StackTarget::Mask => true,
StackTarget::Effect(effect_id) => project
.effect(effect_id)
.and_then(|(owner, _)| project.layers.get(&owner))
.is_some_and(|owner_layer| !owner_layer.content_effects.iter().any(|effect| effect.id == effect_id)),
};
if targets_mask { Ok(()) } else { Err("select a mask to paint on".into()) }
}
fn swap_mask_value(session: &mut Session, _: &Value) -> Result<Value> {
session.tool.mask_value = 1.0 - session.tool.mask_value;
session.revision = session.revision.wrapping_add(1);
Ok(json!({ "maskValue": session.tool.mask_value }))
}
fn stencil(s: &mut Session, p: &Value) -> Result<Value> {
if boolp(p, "clear") == Some(true) {
s.tool.stencil = None;
+7 -1
View File
@@ -88,7 +88,13 @@ fn frame(s: &mut Session, _: &Value) -> Result<Value> {
}
fn set_view(s: &mut Session, v: ViewMode) -> Result<Value> {
s.view = v;
if s.bake_preview.is_some() {
// During a bake the view follows the preview: a mesh map pins it, another mode comes back afterwards
s.bake_preview_user_view(v);
} else {
s.view = v;
}
let v = s.view;
s.revision = s.revision.wrapping_add(1);
Ok(json!({ "view": v.label() }))
}
+428
View File
@@ -0,0 +1,428 @@
//! Live bake preview: maps stream into the view while a bake runs, the view mode comes back,
//! painting is paused, a cancelled bake leaves the set it was baking alone (sets finished before it
//! stay applied), the streamed pixels are the ones a single bake makes, and the preview and the
//! document share each map's buffer instead of holding two copies.
use serde_json::{Value, json};
use texturecraft_engine::bake::Progress;
use texturecraft_engine::core::{BakeResolution, BakedMap, Channel};
use texturecraft_engine::geom::glam::Vec2;
use texturecraft_engine::{BakeTask, PreviewShow, Session, ViewMode, execute};
const MAPS: [BakedMap; 4] = [BakedMap::Id, BakedMap::AmbientOcclusion, BakedMap::Curvature, BakedMap::Height];
fn session() -> Session {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
for texture_set in &mut session.doc.project.texture_sets {
texture_set.bake = Default::default();
texture_set.bake.common.resolution = BakeResolution::R64;
texture_set.bake.maps.ao.parameters.rays.rays = 8;
texture_set.bake.maps.select(MAPS);
}
session
}
fn task(session: &Session) -> BakeTask {
let mut task = session.bake_task(0).unwrap();
task.tracer = None;
task
}
fn order(session: &Session) -> Vec<BakedMap> {
task(session).maps()
}
#[test]
fn streamed_maps_are_the_pixels_of_one_bake() {
let session = session();
let task = task(&session);
let whole = task.run(&Progress::new()).unwrap();
let mut streamed = Vec::new();
let combined = task.run_streaming(&Progress::new(), &mut |map| streamed.push(map)).unwrap();
assert_eq!(streamed.iter().map(|map| map.map).collect::<Vec<_>>(), order(&session));
assert_eq!(streamed.iter().map(|map| (map.index, map.total)).collect::<Vec<_>>(), (0..MAPS.len()).map(|index| (index, MAPS.len())).collect::<Vec<_>>());
assert_eq!((combined.resolution, combined.height), (whole.resolution, whole.height));
assert_eq!(combined.maps.keys().collect::<Vec<_>>(), whole.maps.keys().collect::<Vec<_>>());
for (map, pixels) in &whole.maps {
assert!(*combined.maps[map] == *pixels, "{map:?} differs between a streamed and a single bake");
}
for map in &streamed {
assert!(*map.data == whole.maps[&map.map], "{:?} handed over differs from the bake", map.map);
}
}
#[test]
fn the_view_follows_each_map_and_the_previous_mode_comes_back() {
let mut session = session();
session.view = ViewMode::Channel(Channel::Roughness);
let before = session.view;
let baked_before = session.doc.baked.get(&0).cloned();
let maps = order(&session);
session.bake_preview_begin(vec![(0, maps.clone())]);
session.bake_preview_set_current(0);
// Nothing is baked yet: the first map shows, neutral
assert_eq!(session.view, ViewMode::MeshMap(maps[0]));
assert!(session.bake_preview_baked(0).is_some_and(|baked| baked.maps.is_empty()));
let task = task(&session);
let mut shown = Vec::new();
let mut stages = Vec::new();
let output = task
.run_streaming(&Progress::new(), &mut |map| {
session.bake_preview_map(0, map);
shown.push(session.view);
stages.push(session.bake_preview.as_ref().and_then(|preview| preview.stage()).map(|stage| (stage.position, stage.total)));
})
.unwrap();
assert_eq!(shown, maps.iter().map(|map| ViewMode::MeshMap(*map)).collect::<Vec<_>>(), "the view follows the newest map");
assert_eq!(stages, [Some((2, 4)), Some((3, 4)), Some((4, 4)), None], "the stage names the next map");
assert_eq!(session.doc.baked.get(&0).cloned(), baked_before, "the document is untouched until the bake is applied");
let undo_before = session.undo_label().map(str::to_owned);
session.apply_streamed_bake(0, output).unwrap();
assert_ne!(session.undo_label().map(str::to_owned), undo_before, "applying the bake is one undo step");
session.bake_preview_end();
assert_eq!(session.view, before, "the previous view mode is restored");
assert!(!session.bake_preview_active());
assert!(maps.iter().all(|map| session.doc.baked[&0].maps.contains_key(map)));
}
#[test]
fn pinning_material_and_follow() {
let mut session = session();
let maps = order(&session);
session.bake_preview_begin(vec![(0, maps.clone())]);
session.bake_preview_set_current(0);
let task = task(&session);
let mut count = 0;
task.run_streaming(&Progress::new(), &mut |map| {
session.bake_preview_map(0, map);
count += 1;
match count {
// Pin the finished map: later maps do not take the view
1 => session.bake_preview_show(PreviewShow::Pin(maps[0])).unwrap(),
2 => {
assert_eq!(session.view, ViewMode::MeshMap(maps[0]));
session.bake_preview_show(PreviewShow::Material).unwrap();
}
3 => {
assert_eq!(session.view, ViewMode::Material);
session.bake_preview_show(PreviewShow::Follow).unwrap();
assert_eq!(session.view, ViewMode::MeshMap(maps[2]));
}
_ => {}
}
})
.unwrap();
// A mesh map picked in the viewport pins it; another mode is what comes back at the end
execute(&mut session, "viewport.view", &json!({ "mode": "map:height" })).unwrap();
assert_eq!(session.bake_preview.as_ref().map(|preview| preview.show), Some(PreviewShow::Pin(BakedMap::Height)));
execute(&mut session, "viewport.view", &json!({ "mode": "uvChecker" })).unwrap();
assert_eq!(session.view, ViewMode::UvChecker);
session.bake_preview_end();
assert_eq!(session.view, ViewMode::UvChecker);
}
#[test]
fn unbaked_sets_show_neutral_and_the_control_command_reports() {
let mut session = session();
assert_eq!(execute(&mut session, "bake.preview", &Value::Null).unwrap()["active"], false);
assert!(execute(&mut session, "bake.preview", &json!({ "show": "material" })).is_err(), "nothing to show when no bake runs");
session.bake_preview_begin(vec![(0, order(&session)), (1, order(&session))]);
session.bake_preview_set_current(0);
assert!(session.bake_preview_baked(1).is_some_and(|baked| baked.maps.is_empty()), "a queued set has nothing yet");
assert!(session.bake_preview_baked(7).is_none(), "a set outside the bake shows its document maps");
let reply = execute(&mut session, "bake.preview", &json!({ "show": "map:ambientOcclusion" })).unwrap();
assert_eq!(
(reply["active"].clone(), reply["show"].clone(), reply["shown"].clone()),
(json!(true), json!("map:ambientOcclusion"), json!("ambientOcclusion"))
);
assert!(execute(&mut session, "bake.preview", &json!({ "show": "nonsense" })).is_err());
assert_eq!(texturecraft_engine::inspect::session(&session)["bakePreview"]["active"], true);
}
#[test]
fn painting_is_refused_while_a_bake_shows() {
let mut session = session();
session.bake_preview_begin(vec![(0, order(&session))]);
let error = session.begin_stroke(Vec2::new(10.0, 10.0), Vec2::new(100.0, 100.0), 1.0).unwrap_err().to_string();
assert_eq!(error, texturecraft_engine::bake_preview::PAINTING_PAUSED);
assert!(session.begin_stroke_uv(Vec2::new(0.5, 0.5), 1.0).is_err());
assert!(session.polygon_fill(Vec2::new(10.0, 10.0), Vec2::new(100.0, 100.0)).is_err());
assert!(!session.stroke_active());
session.bake_preview_end();
assert!(session.painting_blocked().is_none());
}
#[test]
fn cancelling_mid_bake_leaves_the_document_and_the_shown_maps_whole() {
let mut session = session();
let before = session.doc.baked.get(&0).cloned();
let maps = order(&session);
let full = task(&session).run(&Progress::new()).unwrap();
session.bake_preview_begin(vec![(0, maps.clone())]);
session.bake_preview_set_current(0);
let progress = Progress::new();
let task = task(&session);
let result = task.run_streaming(&progress, &mut |map| {
if map.index == 1 {
progress.cancel();
}
session.bake_preview_map(0, map);
});
assert!(result.is_err(), "a cancelled bake fails");
// The two maps that landed are whole and equal to a full bake's; the others are still neutral
let shown = session.bake_preview_baked(0).unwrap();
assert_eq!(shown.maps.len(), 2);
for (map, data) in &shown.maps {
assert!(**data == full.maps[map], "{map:?}");
}
// What the app does on cancel: end the preview; the document keeps what it had
session.bake_preview_end();
assert_eq!(session.doc.baked.get(&0).cloned(), before);
assert!(session.bake_preview_baked(0).is_none());
}
#[test]
fn the_preview_and_the_applied_document_share_each_map_buffer() {
let mut session = session();
let maps = order(&session);
session.bake_preview_begin(vec![(0, maps)]);
session.bake_preview_set_current(0);
let mut handed_over = Vec::new();
let output = task(&session)
.run_streaming(&Progress::new(), &mut |map| {
handed_over.push((map.map, map.data.clone()));
session.bake_preview_map(0, map);
})
.unwrap();
// Sharing the streamed buffers keeps preview memory independent of document ownership
for (map, data) in &handed_over {
assert!(std::sync::Arc::ptr_eq(data, &output.maps[map]), "{map:?} was copied on the way out of the bake");
let shown = &session.bake_preview_baked(0).unwrap().maps[map];
assert!(std::sync::Arc::ptr_eq(data, shown), "{map:?} is held twice by the preview");
}
// Applying the result must preserve sharing with the preview
session.apply_streamed_bake(0, output).unwrap();
for (map, data) in &handed_over {
assert!(std::sync::Arc::ptr_eq(data, &session.doc.baked[&0].maps[map]), "{map:?} was copied into the document");
}
session.bake_preview_end();
}
#[test]
fn cancelling_keeps_a_set_that_was_already_applied_as_one_undo_step() {
let mut session = session();
let before = session.doc.baked.get(&0).cloned();
let maps = order(&session);
// A multi-set bake applies each set when it finishes; a later cancel does not undo it
session.bake_preview_begin(vec![(0, maps)]);
session.bake_preview_set_current(0);
let output = task(&session)
.run_streaming(&Progress::new(), &mut |map| {
session.bake_preview_map(0, map);
})
.unwrap();
session.apply_streamed_bake(0, output).unwrap();
session.bake_preview_end();
assert!(MAPS.iter().all(|map| session.doc.baked[&0].maps.contains_key(map)), "the finished set stays baked after the cancel");
session.undo().unwrap();
assert_eq!(session.doc.baked.get(&0).cloned(), before, "applying the set was one undo step");
}
#[test]
fn a_resized_partial_streamed_bake_keeps_unchecked_maps() {
use std::sync::Arc;
use texturecraft_engine::compose::BakedMaps;
use texturecraft_engine::geom::primitives;
let mut session = Session::new_project("Partial bake", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap();
session.doc.baked.insert(
0,
BakedMaps {
resolution: 64,
maps: [
(BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 64 * 32])),
(BakedMap::Normal, Arc::new(vec![0.4; 64 * 32 * 3])),
(BakedMap::Height, Arc::new(vec![0.75; 64 * 32])),
]
.into(),
},
);
execute(&mut session, "bake.settings", &json!({"resolution": 64, "maps": ["ambientOcclusion", "height"], "rays": 2})).unwrap();
execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap();
let before = session.doc.baked.clone();
let task = task(&session);
let whole = task.run(&Progress::new()).unwrap();
let mut streamed = Vec::new();
let output = task.run_streaming(&Progress::new(), &mut |map| streamed.push(map)).unwrap();
assert_eq!((output.resolution, output.height), (128, 64));
assert_eq!(output.maps.keys().collect::<Vec<_>>(), whole.maps.keys().collect::<Vec<_>>());
for (map, pixels) in &whole.maps {
assert_eq!(*output.maps[map], *pixels, "{map:?} must match a whole bake, including retained pixels");
}
assert_eq!(streamed.iter().map(|map| map.map).collect::<Vec<_>>(), [BakedMap::AmbientOcclusion, BakedMap::Height]);
for map in &streamed {
assert!(Arc::ptr_eq(&map.data, &output.maps[&map.map]));
}
session.apply_streamed_bake(0, output).unwrap();
for (map, pixels) in &whole.maps {
assert_eq!(*session.doc.baked[&0].maps[map], *pixels);
}
session.undo().unwrap();
assert_eq!(session.doc.baked, before);
}
#[test]
fn box_fills_are_refused_while_a_bake_shows() {
let mut session = session();
execute(&mut session, "layer.add.paint", &Value::Null).unwrap();
execute(&mut session, "tool.polygonFill", &Value::Null).unwrap();
session.bake_preview_begin(vec![(0, order(&session))]);
let before = texturecraft_engine::inspect::session(&session);
let viewport = Vec2::new(100.0, 100.0);
for result in [
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE),
session.drag_polygon_fill_box(Vec2::ZERO, viewport, viewport),
session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE),
session.polygon_fill_box(Vec2::ZERO, viewport, viewport),
execute(&mut session, "tool.click", &json!({"uv0": [0, 0], "uv1": [1, 1]})).map(|_| 0),
execute(&mut session, "tool.click", &json!({"x0": 0, "y0": 0, "x1": 100, "y1": 100})).map(|_| 0),
] {
assert_eq!(result.unwrap_err().to_string(), texturecraft_engine::bake_preview::PAINTING_PAUSED);
}
assert_eq!(session.end_polygon_fill_box(), 0);
assert_eq!(texturecraft_engine::inspect::session(&session), before);
session.bake_preview_end();
assert!(session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap() > 0);
}
#[test]
fn preview_order_matches_each_sets_bake_task() {
let mut session = session();
session.doc.project.texture_sets[1].bake.maps.select([BakedMap::WorldNormal, BakedMap::Height]);
let expected: Vec<_> = [0, 1].into_iter().map(|texture_set| session.bake_task(texture_set).unwrap().maps()).collect();
session.bake_preview_begin_for(&[0, 1]).unwrap();
let preview = session.bake_preview.as_ref().unwrap();
for (texture_set, maps) in expected.iter().enumerate() {
assert_eq!(&preview.sets[&texture_set].order, maps);
assert!(preview.sets[&texture_set].baked.maps.is_empty());
}
assert_eq!(session.view, ViewMode::MeshMap(expected[0][0]));
}
#[test]
fn invalid_preview_sets_preserve_the_existing_preview_and_view() {
let mut session = session();
session.bake_preview_begin_for(&[0]).unwrap();
session.bake_preview_set_current(0);
session.bake_preview_show(PreviewShow::Material).unwrap();
let before = texturecraft_engine::bake_preview::preview_json(&session);
let view = session.view;
let revision = session.revision;
let invalid_set = session.set_count();
let expected_error = session.doc.project.texture_set(invalid_set).unwrap_err().to_string();
let error = session.bake_preview_begin_for(&[1, invalid_set]).unwrap_err();
assert!(error.to_string().contains(&expected_error));
assert_eq!(texturecraft_engine::bake_preview::preview_json(&session), before);
assert_eq!(session.view, view);
assert_eq!(session.revision, revision);
}
#[test]
fn starting_a_bake_preview_discards_an_active_stroke() {
for (from_settings, paint_mask) in [(false, false), (true, false), (false, true), (true, true)] {
let mut session = session();
execute(&mut session, "layer.add.paint", &Value::Null).unwrap();
if paint_mask {
session.target = texturecraft_engine::StackTarget::Mask;
}
let before = session.doc.clone();
let history = session.history_labels();
let view = session.view;
session.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap();
assert!(session.stroke_tiles() > 0, "the stroke must contain paint before the preview starts");
if from_settings {
session.bake_preview_begin_for(&[0]).unwrap();
} else {
session.bake_preview_begin(vec![(0, order(&session))]);
}
let stroke_survived = session.stroke_active();
session.continue_stroke_uv(Vec2::splat(0.6), 1.0);
session.end_stroke().unwrap();
assert_eq!(session.history_labels(), history, "releasing the pointer during a preview must not commit paint");
assert!(!stroke_survived, "activation must cancel the stroke immediately");
assert_eq!(session.doc.project, before.project);
assert_eq!(session.doc.pixels.layers, before.pixels.layers);
assert_eq!(session.doc.pixels.masks, before.pixels.masks);
assert!(session.bake_preview_active());
session.bake_preview_end();
assert_eq!(session.view, view);
session.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap();
session.end_stroke().unwrap();
assert_eq!(session.history_labels().len(), history.len() + 1, "painting resumes after the preview ends");
}
}
#[test]
fn a_rejected_bake_preview_preserves_the_active_stroke() {
let mut session = session();
execute(&mut session, "layer.add.paint", &Value::Null).unwrap();
let history_steps = session.history_labels().len();
let view = session.view;
session.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap();
let painted_tiles = session.stroke_tiles();
assert!(painted_tiles > 0);
let result = session.bake_preview_begin_for(&[0, session.set_count()]);
assert!(result.is_err());
assert!(!session.bake_preview_active());
assert!(session.stroke_active());
assert_eq!(session.stroke_tiles(), painted_tiles);
assert_eq!(session.view, view);
session.end_stroke().unwrap();
assert_eq!(session.history_labels().len(), history_steps + 1, "a rejected preview must not discard painting");
}
+10 -9
View File
@@ -10,17 +10,18 @@ fn plane_session() -> Session {
Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap()
}
/// `mesh` as OBJ text, lifted by `dy`, keeping only vertices with x ≤ `max_x` (triangles that
/// lose a vertex are dropped), every vertex colored `rgb`.
fn obj(mesh: &Mesh, dy: f32, max_x: f32, rgb: [f32; 3]) -> String {
let mut s = String::from("o Part_high\n");
for p in &mesh.positions {
s += &format!("v {} {} {} {} {} {}\n", p.x.min(max_x), p.y + dy, p.z, rgb[0], rgb[1], rgb[2]);
/// `mesh` as OBJ text, shifted by `offset_y`, with x clamped to `max_x` and every vertex colored `rgb`.
fn obj(mesh: &Mesh, offset_y: f32, max_x: f32, rgb: [f32; 3]) -> String {
let mut text = String::from("o Part_high\n");
for position in &mesh.positions {
text += &format!("v {} {} {} {} {} {}\n", position.x.min(max_x), position.y + offset_y, position.z, rgb[0], rgb[1], rgb[2]);
}
for t in mesh.indices.chunks_exact(3) {
s += &format!("f {} {} {}\n", t[0] + 1, t[1] + 1, t[2] + 1);
for triangle in mesh.indices.as_chunks::<3>().0 {
text += &format!("f {} {} {}\n", triangle[0] + 1, triangle[1] + 1, triangle[2] + 1);
}
s
text
}
fn temp_file(name: &str, text: &str) -> String {
+7 -2
View File
@@ -53,14 +53,16 @@ fn partial_bake_preserves_unchecked_tiles_and_uses_the_workers_selection() {
execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": true})).unwrap();
execute(&mut session, "bake.tile.set", &json!({"tile": 1001, "enabled": false})).unwrap();
let before = session.doc.baked.clone();
let output = task.run(&Progress::new()).unwrap();
session.apply_bake(0, output).unwrap();
let pixels = &session.doc.baked[&0].maps[&BakedMap::AmbientOcclusion];
for row in pixels.chunks_exact(64) {
for row in pixels.as_chunks::<64>().0 {
assert!(row[..32].iter().all(|value| *value > 0.99));
assert!(row[32..].iter().all(|value| *value == 0.25));
}
session.undo().unwrap();
assert_eq!(session.doc.baked, before);
}
@@ -76,17 +78,20 @@ fn partial_bake_resizes_retained_tiles_and_unchecked_map_outputs() {
},
);
execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap();
let result = execute(&mut session, "bake.run", &json!({"resolution": 64, "cpu": true})).unwrap();
assert_eq!(result["baked"], json!([0]));
let baked = &session.doc.baked[&0];
assert_eq!((baked.resolution, baked.height(BakedMap::AmbientOcclusion)), (128, 64));
for row in baked.maps[&BakedMap::AmbientOcclusion].chunks_exact(128) {
for row in baked.maps[&BakedMap::AmbientOcclusion].as_chunks::<128>().0 {
assert!(row[..64].iter().all(|value| *value > 0.99));
assert!(row[64..].iter().all(|value| *value == 0.25));
}
assert_eq!(baked.maps[&BakedMap::Normal].len(), 128 * 64 * 3);
assert!(baked.maps[&BakedMap::Normal].iter().all(|value| *value == 0.4));
let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
assert_eq!(reopened.doc.baked, session.doc.baked);
}
+4
View File
@@ -17,11 +17,15 @@ mod materialx;
mod materialx_import;
mod meshmap_import;
mod painter_gaps;
mod path_perf;
mod path_tool;
mod perf;
mod polygon_fill;
mod project_recovery;
mod sample;
mod thumbs;
mod tools;
mod udim;
mod uv_strokes;
mod symmetry;
+126
View File
@@ -34,6 +34,9 @@ fn red(v: [f32; 3]) -> bool {
v[0] > 0.85 && v[1] < 0.15
}
/// Distance between the view points searched for a texture set
const SEARCH_STEP: f32 = 10.0;
fn png(w: u32, h: u32, f: impl Fn(u32, u32) -> [u8; 4]) -> Vec<u8> {
let mut out = Vec::new();
image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
@@ -345,6 +348,129 @@ fn decal_drags_merge_into_one_undo_step() {
assert_eq!(execute(&mut s, "project.inspect", &Value::Null).unwrap()["layers"], start);
}
/// A decal dropped on another texture set lands there and selects it, in one undo step
#[test]
fn a_decal_on_another_texture_set_selects_that_set() {
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap();
s.viewport = Vec2::new(400.0, 400.0);
s.update();
let name = s.import_resource_bytes("logo.png", png(8, 8, |_, _| [255, 0, 0, 255])).unwrap();
let selected = s.ts();
let (columns, rows) = ((s.viewport.x / SEARCH_STEP) as u32, (s.viewport.y / SEARCH_STEP) as u32);
let other_set_pixel = (0..rows)
.flat_map(|row| (0..columns).map(move |column| Vec2::new(column as f32, row as f32) * SEARCH_STEP))
.find(|&pixel| s.texture_set_at(pixel, s.viewport).is_some_and(|ts| ts != selected))
.expect("the material ball shows both of its texture sets");
let other = s.texture_set_at(other_set_pixel, s.viewport).unwrap();
let steps = s.history_labels().len();
let drop = json!({"image": name, "x": other_set_pixel.x, "y": other_set_pixel.y, "viewport": [s.viewport.x, s.viewport.y]});
let layer = id(execute(&mut s, "layer.add.decal", &drop).unwrap(), "layer");
assert_eq!(s.ts(), other, "the set under the point is selected");
assert_eq!(s.doc.project.locate(layer).map(|(ts, _, _)| ts), Some(other), "the decal is in that set");
assert_eq!(s.selected_layer(), Some(layer));
assert_eq!(s.history_labels().len(), steps + 1, "one undo step");
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert!(s.doc.project.locate(layer).is_none(), "one undo takes the decal away");
let background = json!({"image": name, "x": 2, "y": 2, "viewport": [s.viewport.x, s.viewport.y]});
assert!(s.texture_set_at(Vec2::new(2.0, 2.0), s.viewport).is_none());
assert!(execute(&mut s, "layer.add.decal", &background).is_err(), "the background still takes nothing");
}
/// A decal's image goes in the channel asked for, or masks a new fill layer
#[test]
fn a_decal_image_fills_a_chosen_channel_or_a_mask() {
let mut s = session();
let name = s.import_resource_bytes("logo.png", png(8, 8, |_, _| [255, 255, 255, 255])).unwrap();
let place = |channel: &str| json!({"image": name, "channel": channel, "x": 200, "y": 200, "size": 0.5});
let rough = id(execute(&mut s, "layer.add.decal", &place("roughness")).unwrap(), "layer");
assert_eq!(s.doc.project.layer(rough).unwrap().channels.keys().copied().collect::<Vec<_>>(), [Channel::Roughness]);
assert!(at(&mut s, Channel::Roughness, 200.0, 200.0)[0] > 0.95, "the white image is full roughness under the decal");
assert!(execute(&mut s, "layer.add.decal", &place("sparkle")).is_err(), "unknown channel");
let missing = Channel::ALL.into_iter().find(|channel| !s.doc.project.texture_sets[0].has_channel(*channel)).unwrap();
assert!(execute(&mut s, "layer.add.decal", &place(missing.id())).is_err(), "a channel the set lacks");
let added = execute(&mut s, "layer.add.decal", &place("mask")).unwrap();
let masked = id(added.clone(), "layer");
let mask = s.doc.project.layer(masked).unwrap().mask.as_ref().unwrap();
assert!(matches!(mask.effects.as_slice(), [effect] if matches!(effect.kind, EffectKind::Fill { projection: Projection::Decal(_), .. })));
assert_eq!(added["maskEffect"], json!(mask.effects[0].id.0));
execute(&mut s, "layer.fill.set", &json!({"layer": masked.0, "channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap();
assert!(red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "the mask shows the layer under the decal");
assert!(!red(at(&mut s, Channel::BaseColor, 120.0, 200.0)), "and hides it elsewhere");
let effect = &added["maskEffect"];
execute(&mut s, "layer.decal.set", &json!({"effect": effect, "x": 150, "y": 200})).unwrap();
assert!(red(at(&mut s, Channel::BaseColor, 150.0, 200.0)), "a mask decal moves like a decal layer");
assert!(!red(at(&mut s, Channel::BaseColor, 230.0, 200.0)));
assert!(execute(&mut s, "layer.decal.set", &json!({"effect": rough.0, "x": 150, "y": 200})).is_err(), "a layer id is not an effect");
execute(&mut s, "layer.decal.set", &json!({"effect": effect, "layer": masked.0, "size": 0.4})).expect("an effect with its own layer");
let mismatched = json!({"effect": effect, "layer": rough.0, "size": 0.4});
assert!(execute(&mut s, "layer.decal.set", &mismatched).is_err(), "an effect with another layer is refused");
}
#[test]
fn editing_a_decal_checks_its_own_texture_set_after_selection_changes() {
for channel in ["baseColor", "mask"] {
let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap();
session.viewport = Vec2::new(400.0, 400.0);
session.update();
let image = session.import_resource_bytes("logo.png", png(8, 8, |_, _| [255; 4])).unwrap();
let (columns, rows) = ((session.viewport.x / SEARCH_STEP) as u32, (session.viewport.y / SEARCH_STEP) as u32);
let point_on = |texture_set| {
(0..rows)
.flat_map(|row| (0..columns).map(move |column| Vec2::new(column as f32, row as f32) * SEARCH_STEP))
.find(|&point| session.texture_set_at(point, session.viewport) == Some(texture_set))
.expect("both material-ball sets are visible")
};
let original_point = point_on(0);
let other_point = point_on(1);
let added =
execute(&mut session, "layer.add.decal", &json!({"image": image, "channel": channel, "x": original_point.x, "y": original_point.y})).unwrap();
let layer = added["layer"].clone();
let effect = added["maskEffect"].clone();
execute(&mut session, "textureSet.select", &json!({"ts": 1})).unwrap();
execute(&mut session, "layer.add.paint", &Value::Null).unwrap();
let before = serde_json::to_value(&session.doc.project).unwrap();
let history = session.history_labels();
let rejected = execute(&mut session, "layer.decal.set", &json!({"layer": layer, "effect": effect, "x": other_point.x, "y": other_point.y}));
assert!(rejected.is_err(), "{channel}: selecting another set must not allow moving the decal onto that set");
assert_eq!(serde_json::to_value(&session.doc.project).unwrap(), before);
assert_eq!(session.history_labels(), history);
let replaced = execute(&mut session, "layer.decal.set", &json!({"layer": layer, "effect": effect, "x": original_point.x, "y": original_point.y}));
assert!(replaced.is_ok(), "{channel}: the decal's own set remains a valid placement: {replaced:?}");
let decal = replaced.unwrap()["decal"].clone();
execute(&mut session, "layer.decal.set", &json!({"layer": layer, "effect": effect, "position": decal["center"], "normal": decal["normal"]})).unwrap();
assert_eq!(session.ts(), 1, "editing an explicit decal does not change selection");
}
}
/// A decal's new image stays in the channel the decal was placed in, read as gray there
#[test]
fn a_channel_decal_reads_its_image_as_gray_and_keeps_its_channel() {
let mut s = session();
let white = s.import_resource_bytes("white.png", png(8, 8, |_, _| [255, 255, 255, 255])).unwrap();
let green = s.import_resource_bytes("green.png", png(8, 8, |_, _| [0, 255, 0, 255])).unwrap();
let place = json!({"image": white, "channel": "roughness", "x": 200, "y": 200, "size": 0.5});
let layer = id(execute(&mut s, "layer.add.decal", &place).unwrap(), "layer");
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "image": green})).unwrap();
assert_eq!(s.doc.project.layer(layer).unwrap().channels.keys().copied().collect::<Vec<_>>(), [Channel::Roughness]);
let roughness = at(&mut s, Channel::Roughness, 200.0, 200.0)[0];
assert!((roughness - texturecraft_engine::core::lum([0.0, 1.0, 0.0])).abs() < 0.02, "green reads as its gray, not its red: {roughness}");
}
/// The Geometry mask tool: a click toggles the selected layer on the part under it.
#[test]
fn geometry_mask_tool_toggles_the_clicked_part() {
+115
View File
@@ -0,0 +1,115 @@
//! Path preview timings and a repeatable memory soak (release, --ignored --nocapture).
use std::time::{Duration, Instant};
use serde_json::json;
use texturecraft_engine::execute;
use texturecraft_engine::geom::glam::Vec2;
/// Sort a nonempty timing sample in place and report its middle value in milliseconds
fn median_ms(samples: &mut [Duration]) -> f64 {
samples.sort_unstable();
samples[samples.len() / 2].as_secs_f64() * 1_000.0
}
/// Separate repaint cost from dirty-tile and full-set compositing across representative brush sizes
#[test]
#[ignore = "release benchmark: two texture resolutions and brush sizes"]
fn path_preview_timings() {
for resolution in [2048, 4096] {
let mut session = texturecraft_engine::sample_session(resolution, 64).unwrap();
session.viewport = Vec2::splat(400.0);
session.camera.yaw = 0.0;
session.camera.pitch = 0.0;
session.update();
for size in [4, 20] {
execute(&mut session, "tool.brush", &json!({"size": size})).unwrap();
execute(&mut session, "tool.path", &json!({"points": [[150, 210], [175, 180], [200, 210], [225, 180], [250, 210]]})).unwrap();
session.update();
let original = session.tool.path.points[2];
let (mut paint, mut composite, mut full) = (Vec::new(), Vec::new(), Vec::new());
let mut dirty_tiles = Vec::new();
for step in 0..20 {
let point = original + texturecraft_engine::geom::glam::Vec3::Y * (step as f32 + 1.0) * 0.001;
assert!(session.move_path_point(2, point, step == 0));
let started = Instant::now();
assert!(session.path_live().unwrap());
paint.push(started.elapsed());
dirty_tiles.push(session.pending_tiles());
let started = Instant::now();
session.update();
composite.push(started.elapsed());
// The same document with full invalidation isolates the compositor saving
if step < 3 {
for cache in &mut session.caches {
cache.invalidate_all();
}
let started = Instant::now();
session.update();
full.push(started.elapsed());
}
}
println!(
"path {resolution}px brush={size}: paint {:.2} ms, dirty composite {:.2} ms, full composite {:.2} ms; dirty tiles {:?}",
median_ms(&mut paint),
median_ms(&mut composite),
median_ms(&mut full),
dirty_tiles
);
session.cancel_path();
session.update();
}
}
}
/// Observe resident memory without treating allocator-retained pages as a leak
#[cfg(target_os = "linux")]
fn resident_kib() -> usize {
let status = std::fs::read_to_string("/proc/self/status").unwrap();
status.lines().find_map(|line| line.strip_prefix("VmRSS:").and_then(|rest| rest.split_whitespace().next()).and_then(|n| n.parse().ok())).unwrap()
}
/// Check that repeated canceled previews release tile buffers and leave no document history
#[cfg(target_os = "linux")]
#[test]
#[ignore = "release memory soak: 1,000 edits across 100 canceled previews"]
fn path_preview_memory_soak() {
use texturecraft_engine::Session;
use texturecraft_engine::geom::primitives;
let mut session = Session::new_project("Path soak", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 512).unwrap();
session.viewport = Vec2::splat(400.0);
session.update();
let history = session.history_labels().len();
let mut resident = Vec::new();
for cycle in 0..100 {
execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.35, 0.45], [0.5, 0.5], [0.65, 0.45], [0.8, 0.5]]})).unwrap();
for step in 0..10 {
let point = texturecraft_engine::geom::glam::Vec3::new(0.5, 0.5 + (step as f32 + 1.0) * 0.002, 0.0);
session.move_path_point(2, point, true);
assert!(session.path_live().unwrap());
session.update();
}
let preview_tiles: Vec<_> = session
.doc
.pixels
.layers
.values()
.flat_map(|image| image.allocated().map(|(x, y)| std::sync::Arc::downgrade(image.tile_handle(x, y).unwrap())))
.collect();
assert!(!preview_tiles.is_empty());
session.cancel_path();
session.update();
assert!(preview_tiles.iter().all(|tile| tile.upgrade().is_none()), "canceled previews release their painted tile buffers");
assert_eq!(session.history_labels().len(), history, "canceled previews retain no document history");
if (cycle + 1) % 10 == 0 {
resident.push(resident_kib());
}
}
println!("path soak VmRSS KiB after each 100 edits: {resident:?}");
// RSS is an observation, not a portable leak assertion: allocators can retain freed pages
}
+434 -3
View File
@@ -37,7 +37,7 @@ fn path_stroke_paints_along_the_curve() {
let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap();
assert_eq!(r["points"], 3);
assert_eq!(s.tool.tool, texturecraft_engine::Tool::Path);
assert!(!red_at(&s, 200.0, 180.0), "nothing painted before commit");
assert!(red_at(&s, 200.0, 180.0), "the path is previewed before it is applied");
let r = execute(&mut s, "tool.path", &json!({"commit": true})).unwrap();
assert!(r["committed"]["stamps"].as_u64().unwrap() > 10, "{r}");
assert_eq!(r["points"], 0, "commit clears the path");
@@ -46,11 +46,11 @@ fn path_stroke_paints_along_the_curve() {
}
assert!(!red_at(&s, 200.0, 240.0), "below the curve");
assert!(!red_at(&s, 200.0, 130.0), "above the curve");
// One undo step.
// One undo step
execute(&mut s, "edit.undo", &Value::Null).unwrap();
s.update();
assert!(!red_at(&s, 200.0, 180.0));
// Errors: no points, points off the mesh.
// Errors: no points, points off the mesh
assert!(execute(&mut s, "tool.path", &json!({"commit": true})).is_err());
assert!(execute(&mut s, "tool.path", &json!({"points": [[2, 2]]})).is_err());
}
@@ -278,3 +278,434 @@ fn each_path_and_each_edit_of_one_is_its_own_undo_step() {
s.update();
assert!(red_at(&s, 200.0, 230.0), "undo brings back the first edit");
}
/// The pixels of every path sublayer of the selected layer, comparable
fn path_pixels(s: &Session) -> Vec<String> {
let ids: Vec<u64> = path_sublayers(s).into_iter().map(|(id, _)| id).collect();
let mut v: Vec<String> = s.doc.pixels.layers.iter().filter(|((id, _), _)| ids.contains(&id.0)).map(|(k, img)| format!("{k:?}{img:?}")).collect();
v.sort();
v
}
#[test]
fn placing_points_previews_the_path_with_no_undo_step_until_it_is_applied() {
let points = json!([[140, 210], [200, 180], [260, 210]]);
let mut direct = session(primitives::sphere(1.0, 48, 24));
execute(&mut direct, "tool.path", &json!({"points": points, "commit": true})).unwrap();
let mut s = session(primitives::sphere(1.0, 48, 24));
let start = s.history_labels();
execute(&mut s, "tool.path", &json!({"points": [[140, 280], [260, 280]]})).unwrap();
assert!(red_at(&s, 200.0, 280.0));
execute(&mut s, "tool.path", &json!({"points": points})).unwrap();
assert!(red_at(&s, 200.0, 180.0) && !red_at(&s, 200.0, 280.0), "the preview follows the points");
assert_eq!(s.history_labels(), start, "no undo step while placing");
execute(&mut s, "tool.path", &json!({"commit": true})).unwrap();
assert_eq!(s.history_labels().len(), start.len() + 1, "applying is one undo step");
assert_eq!(s.undo_label(), Some("Path"));
assert_eq!(path_pixels(&s), path_pixels(&direct), "the same pixels as applying without a preview");
// Cancelling removes the preview
execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap();
assert!(red_at(&s, 200.0, 250.0));
execute(&mut s, "tool.path", &json!({"clear": true})).unwrap();
s.update();
assert!(!red_at(&s, 200.0, 250.0) && red_at(&s, 200.0, 180.0));
assert_eq!(s.history_labels().len(), start.len() + 1);
}
#[test]
fn undo_while_placing_removes_the_preview_only() {
let mut s = session(primitives::sphere(1.0, 48, 24));
execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap();
let steps = s.history_labels().len();
execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap();
execute(&mut s, "edit.undo", &Value::Null).unwrap();
s.update();
assert!(!red_at(&s, 200.0, 250.0), "the preview is gone");
assert!(red_at(&s, 200.0, 180.0), "the applied path stays");
assert_eq!(s.history_labels().len(), steps);
assert!(s.tool.path.points.is_empty() && s.tool.path.editing.is_none());
}
#[test]
fn another_change_while_placing_makes_the_path_its_own_step_first() {
let mut s = session(primitives::sphere(1.0, 48, 24));
let steps = s.history_labels().len();
execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap();
execute(&mut s, "layer.add.paint", &Value::Null).unwrap();
let labels = s.history_labels();
assert_eq!(labels.len(), steps + 2);
assert_eq!(labels.get(steps).map(String::as_str), Some("Path"));
// Undoing the other change keeps the path; undoing again removes it
execute(&mut s, "edit.undo", &Value::Null).unwrap();
s.update();
assert!(red_at(&s, 200.0, 180.0));
execute(&mut s, "edit.undo", &Value::Null).unwrap();
s.update();
assert!(!red_at(&s, 200.0, 180.0));
}
#[test]
fn editing_another_path_while_placing_applies_the_new_one() {
let mut s = session(primitives::sphere(1.0, 48, 24));
let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap();
let eid = r["committed"]["effect"].as_u64().unwrap();
execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap();
execute(&mut s, "path.edit", &json!({"effect": eid, "index": 0})).unwrap();
assert_eq!(path_sublayers(&s), vec![(eid, 2)], "the new path was applied");
assert_eq!(s.undo_label(), Some("Path"));
assert_eq!(s.tool.path.editing, Some((texturecraft_engine::core::LayerId(eid), 0)));
}
#[test]
fn the_next_path_starts_open_after_a_closed_one() {
let mut s = session(primitives::sphere(1.0, 48, 24));
execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "closed": true, "commit": true})).unwrap();
assert!(!s.tool.path.closed, "applying a closed path leaves the tool open for the next one");
execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]], "closed": true})).unwrap();
execute(&mut s, "tool.path", &json!({"clear": true})).unwrap();
assert!(!s.tool.path.closed, "cancelling does too");
}
/// A short path's repaint marks under 1/N of a 1024-texel set's 256 tiles
const SHORT_PATH_TILE_SHARE_DIVISOR: usize = 4;
/// Move the middle point of the Path tool's curve down to viewport row `y` and repaint, returning the (dirty, all) tile counts
fn move_middle_point(s: &mut Session, y: f32) -> (usize, usize) {
s.tool.path.points[1] = s.pick(Vec2::new(200.0, y), s.viewport).unwrap().pos;
assert!(s.path_live().unwrap());
(s.caches[0].dirty.len(), s.caches[0].covered_tiles.len())
}
#[test]
fn moving_a_point_recomposites_only_the_paths_tiles() {
// 1024 texels: 256 tiles, so a short path covers few of them
let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:test", None, 1024).unwrap();
s.viewport = Vec2::new(400.0, 400.0);
(s.camera.yaw, s.camera.pitch) = (0.0, 0.0);
execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap();
execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap();
s.update();
let (dirty, all) = move_middle_point(&mut s, 190.0);
assert!(dirty > 0 && dirty * SHORT_PATH_TILE_SHARE_DIVISOR < all, "a new path: {dirty} of {all} tiles to recomposite");
s.update();
let r = execute(&mut s, "tool.path", &json!({"commit": true})).unwrap();
execute(&mut s, "path.edit", &json!({"effect": r["committed"]["effect"], "index": 0})).unwrap();
s.update();
// Another row than the applied one, so the edit changes the path
let (dirty, all) = move_middle_point(&mut s, 200.0);
assert!(dirty > 0 && dirty * SHORT_PATH_TILE_SHARE_DIVISOR < all, "an applied path being edited: {dirty} of {all} tiles to recomposite");
}
#[test]
fn another_change_ends_the_point_undo_of_an_edited_path() {
let mut s = session(primitives::sphere(1.0, 48, 24));
let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap();
let eid = texturecraft_engine::core::LayerId(r["committed"]["effect"].as_u64().unwrap());
execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 0})).unwrap();
s.path_checkpoint();
s.tool.path.points[1] = s.pick(Vec2::new(200.0, 230.0), s.viewport).unwrap().pos;
assert!(s.path_live().unwrap());
let moved: Vec<[f32; 3]> = s.tool.path.points.iter().map(|p| p.to_array()).collect();
let layers = s.doc.project.layers.len();
execute(&mut s, "layer.add.paint", &Value::Null).unwrap();
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(s.doc.project.layers.len(), layers, "undo removes the new layer");
assert_eq!(s.paths(eid).unwrap()[0].points, moved, "the path keeps its moved point");
}
#[test]
fn placing_a_path_ends_redo() {
let mut s = session(primitives::sphere(1.0, 48, 24));
execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap();
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert!(s.can_redo());
execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap();
assert!(!s.can_redo(), "redo would throw the path being placed away");
}
#[test]
fn switching_texture_sets_applies_the_path_being_placed() {
let mut s = texturecraft_engine::sample_session(256, 64).unwrap();
execute(&mut s, "layer.add.paint", &Value::Null).unwrap();
let steps = s.history_labels().len();
execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.5, 0.45], [0.8, 0.5]]})).unwrap();
execute(&mut s, "textureSet.select", &json!({"ts": 1})).unwrap();
assert_eq!(s.history_labels().len(), steps + 1);
assert_eq!(s.undo_label(), Some("Path"));
assert!(s.tool.path.points.is_empty() && s.tool.path.editing.is_none(), "the path no longer paints into the other set");
}
#[test]
fn applying_after_orbit_preserves_preview_pixels_and_storage() {
let mut session = session(primitives::sphere(1.0, 48, 24));
execute(&mut session, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap();
let preview = session.doc.clone();
let steps = session.history_labels().len();
session.camera.yaw += 0.6;
session.viewport = Vec2::new(600.0, 400.0);
assert!(!session.path_live().unwrap());
execute(&mut session, "tool.path", &json!({"commit": true})).unwrap();
assert_eq!(session.doc.project, preview.project, "apply must keep the preview's camera and viewport");
assert_eq!(session.doc.pixels.layers, preview.pixels.layers, "apply must keep the preview pixels");
for (key, image) in &preview.pixels.layers {
for (x, y) in image.allocated() {
assert!(std::sync::Arc::ptr_eq(image.tile_handle(x, y).unwrap(), session.doc.pixels.layers[key].tile_handle(x, y).unwrap()));
}
}
assert_eq!(session.history_labels().len(), steps + 1);
}
#[test]
fn applying_an_unchanged_stored_path_after_orbit_adds_no_history() {
let mut session = session(primitives::sphere(1.0, 48, 24));
let report = execute(&mut session, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap();
execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap();
let before = session.doc.clone();
let history = session.history_labels();
session.camera.yaw += 0.6;
assert!(!session.path_live().unwrap());
execute(&mut session, "tool.path", &json!({"commit": true})).unwrap();
assert_eq!(session.history_labels(), history, "accepting an unchanged path is not an edit");
assert_eq!(session.doc.project, before.project);
assert_eq!(session.doc.pixels.layers, before.pixels.layers);
assert!(session.tool.path.editing.is_none());
}
#[test]
fn removing_the_final_preview_point_removes_its_pixels() {
let mut session = session(wall());
let before = session.doc.clone();
let history = session.history_labels();
execute(&mut session, "tool.path", &json!({"uvPoints": [[0.5, 0.5]]})).unwrap();
assert!(!path_sublayers(&session).is_empty());
session.path_checkpoint();
session.tool.path.remove_selected();
assert!(session.path_live().unwrap());
session.update();
assert_eq!(session.doc.project, before.project);
assert_eq!(session.doc.pixels.layers, before.pixels.layers);
assert_eq!(session.history_labels(), history);
assert!(session.tool.path.editing.is_none());
}
#[test]
fn preview_uses_the_commands_explicit_viewport() {
let mut session = session(primitives::sphere(1.0, 48, 24));
let params = json!({"points": [[170, 210], [200, 180], [230, 210]], "viewport": [400, 600]});
execute(&mut session, "tool.path", &params).unwrap();
let preview = path_pixels(&session);
let (effect, index) = session.tool.path.editing.unwrap();
let mut direct = self::session(primitives::sphere(1.0, 48, 24));
let mut params = params;
params["commit"] = json!(true);
execute(&mut direct, "tool.path", &params).unwrap();
assert_eq!(session.paths(effect).unwrap()[index].viewport, [400.0, 600.0]);
assert_eq!(preview, path_pixels(&direct));
}
/// An opposite-view placement must preserve the stored curve, painted pixels and point redo
#[test]
fn stored_paths_ignore_point_placement_from_the_other_view() {
for uv in [false, true] {
let mut session = session(wall());
let params =
if uv { json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true}) } else { json!({"points": [[140, 210], [260, 210]], "commit": true}) };
let report = execute(&mut session, "tool.path", &params).unwrap();
execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap();
let (effect, index) = session.tool.path.editing.unwrap();
let uv_point = Vec3::new(0.5, 0.6, 0.0);
let world_point = session.pick(Vec2::new(200.0, 240.0), session.viewport).unwrap().pos;
assert_eq!(session.append_path_point(if uv { uv_point } else { world_point }, uv), Some(2));
session.path_live().unwrap();
let extended = session.tool.path.points.clone();
session.undo().unwrap();
let before = session.doc.clone();
let path = session.tool.path.clone();
let history = session.history_labels();
let placed = session.append_path_point(if uv { world_point } else { uv_point }, !uv);
session.path_live().unwrap();
assert_eq!(session.paths(effect).unwrap()[index].uv, uv, "the stored path must keep its coordinate space");
assert_eq!(placed, None);
assert_eq!(session.tool.path, path);
assert_eq!(session.doc.project, before.project);
assert_eq!(session.doc.pixels.layers, before.pixels.layers);
assert_eq!(session.doc.pixels.masks, before.pixels.masks);
assert_eq!(session.history_labels(), history);
assert!(session.can_redo(), "ignored placement must preserve point redo");
session.redo().unwrap();
assert_eq!(session.tool.path.points, extended);
}
}
/// A new, uncommitted curve can still switch views and cancel without changing the document
#[test]
fn draft_paths_can_switch_to_the_other_view() {
for uv in [false, true] {
let mut session = session(wall());
let before = session.doc.clone();
let history = session.history_labels();
let params = if uv { json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]}) } else { json!({"points": [[140, 210], [260, 210]]}) };
execute(&mut session, "tool.path", &params).unwrap();
let point = if uv { session.pick(Vec2::new(200.0, 240.0), session.viewport).unwrap().pos } else { Vec3::new(0.5, 0.6, 0.0) };
assert_eq!(session.append_path_point(point, !uv), Some(0));
session.path_live().unwrap();
assert_eq!(session.tool.path.points, vec![point]);
assert_eq!(session.tool.path.uv, !uv);
assert_eq!(session.history_labels(), history);
session.cancel_path();
assert_eq!(session.doc.project, before.project);
assert_eq!(session.doc.pixels.layers, before.pixels.layers);
}
}
/// Headless history commands must restore geometry and pixels before any frame or subsequent edit
#[test]
fn stored_point_edits_undo_and_redo_in_order_without_selection_steps() {
let mut session = session(wall());
let report = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap();
let effect = texturecraft_engine::core::LayerId(report["committed"]["effect"].as_u64().unwrap());
execute(&mut session, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap();
let original = session.tool.path.points.clone();
let original_pixels = session.doc.pixels.clone();
let history = session.history_labels().len();
session.insert_path_point(1, Vec3::new(0.5, 0.5, 0.0));
session.path_live().unwrap();
let inserted = session.tool.path.points.clone();
let inserted_pixels = session.doc.pixels.clone();
session.move_path_point(1, Vec3::new(0.5, 0.6, 0.0), true);
session.move_path_point(1, Vec3::new(0.5, 0.7, 0.0), false);
session.path_live().unwrap();
let moved = session.tool.path.points.clone();
let moved_pixels = session.doc.pixels.clone();
session.remove_selected_path_point();
session.path_live().unwrap();
let removed = session.tool.path.points.clone();
let removed_pixels = session.doc.pixels.clone();
for (expected, pixels) in [(&moved, &moved_pixels), (&inserted, &inserted_pixels), (&original, &original_pixels)] {
execute(&mut session, "edit.undo", &Value::Null).unwrap();
assert_eq!(&session.tool.path.points, expected);
assert_eq!(session.paths(effect).unwrap()[0].points, expected.iter().map(|point| point.to_array()).collect::<Vec<_>>());
assert_eq!(session.doc.pixels.layers, pixels.layers);
assert_eq!(session.doc.pixels.masks, pixels.masks);
}
session.select_path_point(0);
assert!(session.can_redo(), "selection must preserve point redo");
for (expected, pixels) in [(&inserted, &inserted_pixels), (&moved, &moved_pixels), (&removed, &removed_pixels)] {
execute(&mut session, "edit.redo", &Value::Null).unwrap();
assert_eq!(&session.tool.path.points, expected);
assert_eq!(session.paths(effect).unwrap()[0].points, expected.iter().map(|point| point.to_array()).collect::<Vec<_>>());
assert_eq!(session.doc.pixels.layers, pixels.layers);
assert_eq!(session.doc.pixels.masks, pixels.masks);
}
assert_eq!(session.history_labels().len(), history + 1, "all point edits share one document step");
execute(&mut session, "edit.undo", &Value::Null).unwrap();
execute(&mut session, "layer.add.paint", &Value::Null).unwrap();
execute(&mut session, "edit.undo", &Value::Null).unwrap();
assert_eq!(session.paths(effect).unwrap()[0].points, moved.iter().map(|point| point.to_array()).collect::<Vec<_>>());
assert_eq!(session.doc.pixels.layers, moved_pixels.layers, "a subsequent command keeps the undone path pixels");
}
/// A bad path above the edited one must not consume undo or redo when repainting fails
#[test]
fn point_history_repaint_errors_preserve_the_edit_and_can_be_retried() {
use texturecraft_engine::core::{EffectKind, LayerId};
let mut session = session(wall());
let report = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap();
let effect = LayerId(report["committed"]["effect"].as_u64().unwrap());
execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.8], [0.8, 0.8]], "commit": true})).unwrap();
let paint = session.paths(effect).unwrap()[1].paint.clone();
execute(&mut session, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap();
let original = session.tool.path.points.clone();
session.move_path_point(0, Vec3::new(0.2, 0.3, 0.0), true);
session.path_live().unwrap();
let moved = session.tool.path.points.clone();
for (command, expected) in [("edit.undo", &original), ("edit.redo", &moved)] {
let EffectKind::Path(paths) = &mut session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path sublayer") };
paths[1].paint = Value::Null;
let before = session.doc.clone();
let path = session.tool.path.clone();
let history = (session.history_labels(), session.redo_labels());
let error = execute(&mut session, command, &Value::Null).unwrap_err();
assert!(error.to_string().contains("unreadable path settings"), "{error}");
assert_eq!(session.tool.path, path);
assert_eq!(session.doc.project, before.project);
assert_eq!(session.doc.pixels.layers, before.pixels.layers);
assert_eq!((session.history_labels(), session.redo_labels()), history);
let EffectKind::Path(paths) = &mut session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path sublayer") };
paths[1].paint = paint.clone();
execute(&mut session, command, &Value::Null).unwrap();
assert_eq!(&session.tool.path.points, expected, "the failed step remains available");
assert_eq!(session.paths(effect).unwrap()[0].points, expected.iter().map(|point| point.to_array()).collect::<Vec<_>>());
}
}
/// Point history repaints an uncommitted preview without creating document undo steps
#[test]
fn draft_point_history_repaints_immediately_and_undoing_all_points_cancels() {
let mut session = session(wall());
execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap();
let before = session.doc.clone();
let history = session.history_labels();
session.append_path_point(Vec3::new(0.2, 0.5, 0.0), true);
session.path_live().unwrap();
let one_point = session.doc.clone();
session.append_path_point(Vec3::new(0.8, 0.5, 0.0), true);
session.path_live().unwrap();
let two_points = session.doc.clone();
for (command, expected) in [("edit.undo", &one_point), ("edit.redo", &two_points), ("edit.undo", &one_point), ("edit.undo", &before)] {
execute(&mut session, command, &Value::Null).unwrap();
assert_eq!(session.doc.project, expected.project);
assert_eq!(session.doc.pixels.layers, expected.pixels.layers);
assert_eq!(session.history_labels(), history);
}
assert!(session.tool.path.points.is_empty());
assert!(session.tool.path.editing.is_none());
}
#[test]
fn removing_the_final_stored_point_removes_the_path_and_undo_restores_it() {
let mut session = session(wall());
let report = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.5, 0.5]], "commit": true})).unwrap();
let effect = texturecraft_engine::core::LayerId(report["committed"]["effect"].as_u64().unwrap());
execute(&mut session, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap();
let before = session.doc.clone();
session.remove_selected_path_point();
assert!(session.path_live().unwrap());
assert!(session.paths(effect).unwrap().is_empty());
assert!(session.doc.pixels.layers.keys().all(|(id, _)| *id != effect));
assert!(session.tool.path.editing.is_none());
session.undo().unwrap();
assert_eq!(session.doc.project, before.project);
assert_eq!(session.doc.pixels.layers, before.pixels.layers);
}
+47
View File
@@ -350,3 +350,50 @@ fn bench_8k_resize() {
println!("[resize] dilation {:.2?}", t.elapsed());
drop(d);
}
/// Layer-panel thumbnails on the 4K stack: the snapshot, each kind of picture, and a whole panel.
#[test]
#[ignore]
fn bench_layer_thumbs_4k() {
use texturecraft_engine::compose::ThumbTarget;
use texturecraft_engine::core::Channel;
use texturecraft_engine::thumbs::{GbufCache, ThumbSnapshot};
let s = stack(4096);
let ts = s.ts();
let mut gbufs = GbufCache::default();
let t = Instant::now();
let snap = ThumbSnapshot::new(&s, ts, &mut gbufs).unwrap();
let first = t.elapsed();
let t = Instant::now();
let _again = ThumbSnapshot::new(&s, ts, &mut gbufs).unwrap();
let cached = t.elapsed();
let p = &s.doc.project;
let mut targets = Vec::new();
for l in p.layers.values() {
targets.push(("content", ThumbTarget::Content { layer: l.id, channel: Channel::BaseColor }));
if l.mask.is_some() {
targets.push(("mask", ThumbTarget::Mask { layer: l.id }));
}
for e in l.mask.iter().flat_map(|m| m.effects.iter()).chain(l.content_effects.iter()) {
targets.push(("stage", ThumbTarget::Stage { effect: e.id, channel: Channel::BaseColor }));
}
}
let mut per: std::collections::BTreeMap<&str, (Duration, usize, Duration)> = Default::default();
let all = Instant::now();
for (kind, target) in &targets {
let t = Instant::now();
let _ = snap.render(*target);
let d = t.elapsed();
let e = per.entry(kind).or_default();
e.0 += d;
e.1 += 1;
e.2 = e.2.max(d);
}
let total = all.elapsed();
eprintln!("layer thumbnails, 4096 set, {} layers, 64 px:", p.layers.len());
eprintln!(" snapshot: {:.2} ms first (with the 64 px G-buffer), {:.2} ms after", first.as_secs_f64() * 1e3, cached.as_secs_f64() * 1e3);
for (kind, (sum, n, max)) in per {
eprintln!(" {kind:8} {n:3} × avg {:.2} ms, max {:.2} ms", sum.as_secs_f64() * 1e3 / n as f64, max.as_secs_f64() * 1e3);
}
eprintln!(" every target once: {:.1} ms ({} pictures)", total.as_secs_f64() * 1e3, targets.len());
}
+283
View File
@@ -0,0 +1,283 @@
//! Symmetry around a moved plane or axis, driven through engine commands the way agents paint
use serde_json::json;
use texturecraft_engine::core::Channel;
use texturecraft_engine::geom::glam::{Vec2, Vec3, Vec4};
use texturecraft_engine::geom::{Mesh, primitives};
use texturecraft_engine::{Session, execute};
const TEXTURE_SIZE: f32 = 256.0;
const VIEWPORT: f32 = 400.0;
fn session(mesh: Mesh) -> Session {
let mut session = Session::new_project("t", mesh, "builtin:test", None, TEXTURE_SIZE as u32).unwrap();
session.viewport = Vec2::splat(VIEWPORT);
session.camera.yaw = 0.0;
session.camera.pitch = 0.0;
session.update();
execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap();
execute(&mut session, "tool.brush", &json!({"size": 6, "hardness": 90})).unwrap();
session
}
/// A 2×2 wall in the XY plane facing the camera (+Z)
fn wall() -> Mesh {
let mut mesh = primitives::plane(2.0, 8);
for point in &mut mesh.positions {
*point = Vec3::new(point.x, -point.z, 0.0);
}
mesh.normals.iter_mut().for_each(|normal| *normal = Vec3::Z);
mesh.tangents.iter_mut().for_each(|tangent| *tangent = Vec4::new(1.0, 0.0, 0.0, 1.0));
mesh
}
/// Viewport pixel of world `point`
fn screen(session: &Session, point: Vec3) -> Vec2 {
let ndc = session.camera.project(point, 1.0).unwrap();
Vec2::new((ndc.x * 0.5 + 0.5) * VIEWPORT, (0.5 - ndc.y * 0.5) * VIEWPORT)
}
/// Is the surface at world `point` painted red?
fn red_at(session: &Session, point: Vec3) -> bool {
let hit = session.pick(screen(session, point), session.viewport).unwrap();
let color = session.caches[0].composite.value(Channel::BaseColor, (hit.uv.x * TEXTURE_SIZE) as u32, (hit.uv.y * TEXTURE_SIZE) as u32);
color[0] > 0.85 && color[1] < 0.15
}
/// Where a viewport pixel lands on the mesh
fn surface(session: &Session, x: f32, y: f32) -> Vec3 {
session.pick(Vec2::new(x, y), session.viewport).unwrap().pos
}
#[test]
fn a_moved_mirror_plane_paints_the_copy_at_the_mirrored_point() {
let mut session = session(wall());
let reply = execute(&mut session, "tool.brush", &json!({"symmetryX": true, "symmetryOffset": [0.25, 0.0, 0.0]})).unwrap();
// Right of the view's center, on the wall
let stroke = surface(&session, 300.0, 200.0);
execute(&mut session, "tool.stroke", &json!({"points": [[300, 200]]})).unwrap();
session.update();
let mirrored = Vec3::new(0.5 - stroke.x, stroke.y, stroke.z);
assert!(red_at(&session, stroke), "the stroke");
assert!(red_at(&session, mirrored), "its copy across x = 0.25");
assert!(!red_at(&session, Vec3::new(-stroke.x, stroke.y, stroke.z)), "nothing across the mesh center");
assert_eq!(reply["symmetryOffset"], json!([0.25, 0.0, 0.0]), "agents read the offset back");
}
#[test]
fn radial_copies_turn_around_the_moved_axis() {
let mut session = session(wall());
let axis = Vec3::new(0.2, -0.1, 0.0);
execute(&mut session, "tool.brush", &json!({"symmetryRadial": 2, "symmetryAxis": "z", "symmetryOffset": axis.to_array()})).unwrap();
// Up and right of the view's center, on the wall
let stroke = surface(&session, 290.0, 160.0);
execute(&mut session, "tool.stroke", &json!({"points": [[290, 160]]})).unwrap();
session.update();
// Half a turn around Z through the moved axis
assert!(red_at(&session, stroke), "the stroke");
assert!(red_at(&session, axis * 2.0 - stroke), "its copy half a turn around the moved axis");
assert!(!red_at(&session, Vec3::new(-stroke.x, -stroke.y, 0.0)), "nothing around the mesh center");
}
#[test]
fn a_closed_path_fill_mirrors_around_the_moved_plane() {
let mut session = session(wall());
execute(&mut session, "tool.brush", &json!({"symmetryX": true, "symmetryOffset": [-0.2, 0.0, 0.0]})).unwrap();
// A small square right of the view's center, on the wall
let square = json!([[250, 180], [280, 180], [280, 220], [250, 220]]);
execute(&mut session, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap();
let inside = surface(&session, 265.0, 200.0);
assert!(red_at(&session, inside), "the filled lasso");
assert!(red_at(&session, Vec3::new(-0.4 - inside.x, inside.y, 0.0)), "its copy across x = -0.2");
assert!(!red_at(&session, Vec3::new(-inside.x, inside.y, 0.0)), "nothing across the mesh center");
}
#[test]
fn a_closed_path_fill_reaches_a_curved_copy_across_a_moved_plane() {
let mut session = session(primitives::sphere(1.0, 48, 24));
// Occlusion must still protect the rear surface when normal-based culling is disabled
execute(&mut session, "tool.brush", &json!({"symmetryX": true, "symmetryOffset": [0.1, 0.0, 0.0], "backfaceCulling": false})).unwrap();
let inside = surface(&session, 185.0, 200.0);
let mirrored_x = 0.2 - inside.x;
let copy = Vec3::new(mirrored_x, inside.y, (1.0 - mirrored_x * mirrored_x - inside.y * inside.y).sqrt());
let square = json!([[175, 190], [195, 190], [195, 210], [175, 210]]);
execute(&mut session, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap();
assert!(red_at(&session, inside), "the filled lasso");
assert!(red_at(&session, copy), "its copy where the sphere curves away across x = 0.1");
session.camera.yaw = std::f32::consts::PI;
assert!(!red_at(&session, Vec3::new(copy.x, copy.y, -copy.z)), "the hidden back of the copy stays clean");
assert!(!red_at(&session, Vec3::new(inside.x, inside.y, -inside.z)), "the hidden back of the source stays clean");
}
#[test]
fn a_closed_path_fill_reaches_a_copy_in_front_of_the_source_surface() {
for ortho in [false, true] {
for screen_space in [false, true] {
let mut session = session(primitives::sphere(1.0, 48, 24));
session.camera.ortho = ortho;
execute(&mut session, "tool.brush", &json!({"size": 10, "screenSpace": screen_space, "symmetryX": true, "symmetryOffset": [0.1, 0.0, 0.0]}))
.unwrap();
let inside = surface(&session, 235.0, 200.0);
let mirrored_x = 0.2 - inside.x;
let copy = Vec3::new(mirrored_x, inside.y, (1.0 - mirrored_x * mirrored_x - inside.y * inside.y).sqrt());
assert!(copy.z > inside.z + 0.01, "the copy must be nearer the camera than its source");
let square = json!([[225, 190], [245, 190], [245, 210], [225, 210]]);
execute(&mut session, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap();
assert!(red_at(&session, inside), "the filled lasso");
assert!(red_at(&session, copy), "the ray must reach the source: ortho={ortho}, screen_space={screen_space}");
}
}
}
#[test]
fn screen_space_fill_copy_depth_is_limited_at_the_source_hit() {
// The source hit allows about 0.071 world units; the search bound allows about 0.122
for (displacement, painted) in [(-0.074, false), (0.068, true), (0.1, false)] {
let mut session = session(wall());
session.camera.ortho = true;
session.camera.distance = 1.0;
execute(
&mut session,
"tool.brush",
&json!({"size": 10, "screenSpace": true, "symmetryRadial": 2, "symmetryAxis": "y", "symmetryOffset": [0.0, 0.0, displacement * 0.5]}),
)
.unwrap();
let inside = surface(&session, 265.0, 200.0);
let square = json!([[250, 180], [280, 180], [280, 220], [250, 220]]);
execute(&mut session, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap();
assert!(red_at(&session, inside), "the filled lasso");
assert_eq!(red_at(&session, Vec3::new(-inside.x, inside.y, 0.0)), painted, "source displacement {displacement}");
}
}
/// How much redder than green a texel must be to count as painted (faded edges included)
const PAINTED_TINT: f32 = 0.05;
/// Texels tinted red in the top and bottom half of the texture
fn painted_halves(session: &Session) -> (usize, usize) {
let painted = |x: u32, y: u32| {
let color = session.caches[0].composite.value(Channel::BaseColor, x, y);
color[0] - color[1] > PAINTED_TINT
};
let half = TEXTURE_SIZE as u32 / 2;
let count = |rows: std::ops::Range<u32>| rows.flat_map(|y| (0..TEXTURE_SIZE as u32).map(move |x| (x, y))).filter(|&(x, y)| painted(x, y)).count();
(count(0..half), count(half..TEXTURE_SIZE as u32))
}
#[test]
fn a_mirror_copy_paints_exactly_where_its_stroke_does() {
let mut session = session(primitives::sphere(1.0, 48, 24));
execute(&mut session, "tool.brush", &json!({"size": 4, "symmetryY": true})).unwrap();
// From the middle of the view to past the ball's right edge, above center, where it fades out; the copy below must fade the same way
let points: Vec<serde_json::Value> = (0..40).map(|step| json!([200.0 + step as f32 * 6.0, 165.0])).collect();
execute(&mut session, "tool.stroke", &json!({"points": points})).unwrap();
session.update();
let (stroke, copy) = painted_halves(&session);
assert!(stroke > 0);
// Within 4%: the ball's texture layout is not exactly symmetric texel for texel
assert!(stroke.abs_diff(copy) * 25 <= stroke, "stroke {stroke} texels, copy {copy}");
}
#[test]
fn a_copy_paints_on_a_curved_mesh_across_a_moved_plane() {
let mut session = session(primitives::sphere(1.0, 48, 24));
execute(&mut session, "tool.brush", &json!({"symmetryX": true, "symmetryOffset": [0.1, 0.0, 0.0]})).unwrap();
// Left of the view's center; across x = 0.1 its copy lands where the ball curves away a little more
let stroke = surface(&session, 185.0, 200.0);
execute(&mut session, "tool.stroke", &json!({"points": [[185, 200]]})).unwrap();
session.update();
let mirrored_x = 0.2 - stroke.x;
let on_ball = Vec3::new(mirrored_x, stroke.y, (1.0 - mirrored_x * mirrored_x - stroke.y * stroke.y).sqrt());
assert!(red_at(&session, stroke), "the stroke");
assert!(red_at(&session, on_ball), "its copy on the ball across x = 0.1");
}
#[test]
fn symmetry_offsets_require_exactly_three_finite_numbers() {
let mut session = session(wall());
let invalid = [json!([1, 2, 3, null]), json!([null, 1, 2, 3]), json!([1, "bad", 2, 3]), json!([1, 2, 3, 1e100]), json!([1, 2]), json!([1, 2, 1e100])];
for offset in invalid {
let result = execute(&mut session, "tool.brush", &json!({"symmetryOffset": offset}));
assert!(result.is_err(), "accepted malformed offset: {offset}");
}
}
#[test]
fn invalid_brush_settings_leave_the_tool_unchanged() {
let mut session = session(wall());
let before = session.tool.clone();
let revision = session.revision;
for invalid in [
json!({"size": 20, "symmetryOn": false, "symmetryOffset": [1, 2]}),
json!({"size": 20, "symmetryAxis": "bad"}),
json!({"symmetryOffset": [0.2, 0, 0], "smudgeStrength": 70, "cloneSource": "bad"}),
] {
let result = execute(&mut session, "tool.brush", &invalid);
assert!(result.is_err());
assert_eq!(session.tool, before, "a rejected partial update must not change the tool");
assert_eq!(session.revision, revision);
}
}
#[test]
fn symmetry_commands_report_effective_limits_and_keep_updates_out_of_history() {
let mut session = session(wall());
let history = session.history_labels();
for (span, expected) in [(-20.0, 0.0), (120.0, 120.0), (500.0, 360.0)] {
let reply = execute(&mut session, "tool.brush", &json!({"symmetryAngleSpan": span, "symmetryOffset": [1e30, -1e30, 0.25]})).unwrap();
assert_eq!(reply["symmetryAngleSpan"], json!(expected));
assert_eq!(reply["symmetryOffset"], json!([1e6, -1e6, 0.25]));
assert_eq!(session.tool.brush, session.tool.brush.sanitized());
}
assert_eq!(session.history_labels(), history);
}
#[test]
fn disabling_symmetry_paints_only_the_source_and_keeps_the_settings() {
for radial in [false, true] {
let mut session = session(wall());
execute(&mut session, "tool.brush", &json!({"symmetryX": !radial, "symmetryRadial": if radial { 2 } else { 0 }, "symmetryAxis": "z"})).unwrap();
let settings = session.tool.brush.symmetry;
let stroke = surface(&session, 290.0, 160.0);
let copy = if radial { -stroke } else { Vec3::new(-stroke.x, stroke.y, stroke.z) };
execute(&mut session, "tool.brush", &json!({"symmetryOn": false})).unwrap();
execute(&mut session, "tool.stroke", &json!({"points": [[290, 160]]})).unwrap();
session.update();
assert!(red_at(&session, stroke));
assert!(!red_at(&session, copy), "disabled symmetry must not paint its copy");
assert_eq!(session.tool.brush.symmetry, texturecraft_engine::paint::Symmetry { enabled: false, ..settings });
execute(&mut session, "tool.brush", &json!({"symmetryOn": true})).unwrap();
execute(&mut session, "tool.stroke", &json!({"points": [[290, 160]]})).unwrap();
session.update();
assert!(red_at(&session, copy), "enabling symmetry restores its copies");
assert_eq!(session.tool.brush.symmetry, settings);
}
}
+439
View File
@@ -0,0 +1,439 @@
//! Layer-panel thumbnails: they equal a plain CPU evaluation of the same sub-stack at 64 px,
//! follow edits, drop stale and vanished work, and only render what was asked for.
use std::time::{Duration, Instant};
use serde_json::{Value, json};
use texturecraft_engine::compose::{Inputs, ThumbImage, ThumbTarget, all_tiles, flatten_layer, mask_image};
use texturecraft_engine::core::{Channel, ChannelKind, LayerId};
use texturecraft_engine::geom::UvGBuffer;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::texel::{from_u16, from_u16_signed, linear_to_srgb};
use texturecraft_engine::thumbs::{CACHE_ENTRIES, ThumbService};
use texturecraft_engine::{Session, execute};
const N: u32 = 64;
fn session() -> Session {
Session::new_project("t", primitives::sphere(1.0, 32, 16), "builtin:sphere", None, 256).unwrap()
}
fn id(v: Value, key: &str) -> LayerId {
LayerId(v[key].as_u64().unwrap())
}
/// A fill layer with two content effects (invert, then posterize) and a masked generator.
struct Stack {
layer: LayerId,
invert: LayerId,
posterize: LayerId,
gen_: LayerId,
}
fn stack(s: &mut Session) -> Stack {
let layer = id(execute(s, "layer.add.fill", &json!({"color": "#336699", "roughness": 0.2})).unwrap(), "layer");
let invert = id(execute(s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect");
let posterize = id(execute(s, "effect.add.filter", &json!({"target": "content", "filter": "posterize"})).unwrap(), "effect");
execute(s, "mask.add.black", &Value::Null).unwrap();
let gen_ = id(execute(s, "effect.add.generator", &json!({"generator": "position", "level": 0.5})).unwrap(), "effect");
Stack { layer, invert, posterize, gen_ }
}
fn inputs<'a>(s: &'a Session, project: &'a texturecraft_engine::core::Project, gbuf: &'a UvGBuffer) -> Inputs<'a> {
static EMPTY_BAKED: std::sync::LazyLock<texturecraft_engine::compose::BakedMaps> = std::sync::LazyLock::new(Default::default);
let baked = s.doc.baked.get(&0).unwrap_or(&EMPTY_BAKED);
Inputs {
project,
ts: 0,
mesh: &s.mesh,
gbuf,
pixels: &s.doc.pixels,
baked,
block_scales: Default::default(),
preview: None,
images: &s.images,
bounds: s.mesh.bounds(),
}
}
/// The reference: the same sub-stack cut by hand and evaluated at 64 px with the ordinary CPU
/// evaluator (the mask with `mask_image`, the content with `flatten_layer`), then encoded.
fn oracle(s: &Session, target: ThumbTarget) -> ThumbImage {
let gbuf = UvGBuffer::new(&s.mesh, 0, N, N);
let mut p = s.doc.project.clone();
let (layer, upto, channel) = match target {
ThumbTarget::Content { layer, channel } => (layer, None, channel),
ThumbTarget::Mask { layer } => (layer, None, Channel::BaseColor),
ThumbTarget::Stage { effect, channel } => (p.effect(effect).unwrap().0, Some(effect), channel),
};
let l = p.layers.get_mut(&layer).unwrap();
l.visible = true;
let in_mask = upto.is_some_and(|e| l.mask.as_ref().is_some_and(|m| m.effects.iter().any(|x| x.id == e))) || matches!(target, ThumbTarget::Mask { .. });
if in_mask {
let m = l.mask.as_mut().unwrap();
m.enabled = true;
if let Some(e) = upto {
let k = m.effects.iter().position(|x| x.id == e).unwrap();
m.effects.truncate(k + 1);
}
let gray = mask_image(&inputs(s, &p, &gbuf), layer, N).unwrap();
let rgba = gray.iter().enumerate().flat_map(|(i, g)| [*g, *g, *g, if gbuf.covered(i) { 255 } else { 0 }]).collect();
return ThumbImage { width: N, height: N, rgba };
}
l.mask = None;
l.channels.insert(channel, texturecraft_engine::core::ChannelBlend::default());
if let Some(e) = upto {
let k = l.content_effects.iter().position(|x| x.id == e).unwrap();
l.content_effects.truncate(k + 1);
}
// A paint or fill layer: its own (premultiplied value, coverage), coverage as alpha.
let flat = flatten_layer(&inputs(s, &p, &gbuf), layer, &all_tiles(N, N)).unwrap();
let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
let mut rgba = vec![0u8; (N * N * 4) as usize];
let comps = channel.components();
for (_, _, buf) in flat.iter().filter(|(c, _, _)| *c == channel) {
for (i, px) in buf.chunks_exact(comps + 1).enumerate() {
let a = from_u16(px[comps]);
if a <= 0.0 {
continue;
}
let v: [f32; 3] = std::array::from_fn(|k| {
let raw = px[k.min(comps - 1)];
(if channel.kind() == ChannelKind::Signed { from_u16_signed(raw) } else { from_u16(raw) }) / a
});
let px = match channel.kind() {
ChannelKind::Color => v.map(|c| byte(linear_to_srgb(c.clamp(0.0, 1.0)))),
ChannelKind::Signed => v.map(|c| byte(c * 0.5 + 0.5)),
_ => v.map(byte),
};
rgba[i * 4..i * 4 + 4].copy_from_slice(&[px[0], px[1], px[2], byte(a)]);
}
}
ThumbImage { width: N, height: N, rgba }
}
/// Frames of `svc` until every target is current (or a timeout).
fn settle(svc: &mut ThumbService, s: &Session, targets: &[ThumbTarget], clock: &mut f64) {
let t0 = Instant::now();
loop {
*clock += 0.2;
svc.begin_frame(s, *clock);
for t in targets {
svc.get(s, *t);
}
svc.poll(s);
if targets.iter().all(|t| svc.is_fresh(*t)) {
return;
}
assert!(t0.elapsed() < Duration::from_secs(60), "thumbnails never settled");
std::thread::sleep(Duration::from_millis(2));
}
}
fn image(svc: &mut ThumbService, s: &Session, t: ThumbTarget) -> ThumbImage {
(*svc.get(s, t).image.expect("a picture")).clone()
}
#[test]
fn thumbnails_equal_a_cpu_evaluation_of_the_same_sub_stack() {
let mut session = session();
let stack = stack(&mut session);
let base_color = Channel::BaseColor;
let targets = [
ThumbTarget::Content { layer: stack.layer, channel: base_color },
ThumbTarget::Content { layer: stack.layer, channel: Channel::Roughness },
ThumbTarget::Mask { layer: stack.layer },
ThumbTarget::Stage { effect: stack.invert, channel: base_color },
ThumbTarget::Stage { effect: stack.posterize, channel: base_color },
ThumbTarget::Stage { effect: stack.gen_, channel: base_color },
];
let (mut service, mut clock) = (ThumbService::new(), 0.0);
settle(&mut service, &session, &targets, &mut clock);
for target in targets {
assert_eq!(image(&mut service, &session, target), oracle(&session, target), "{target:?}");
}
// The first stage inverts #336699 in linear light
let inverted = image(&mut service, &session, targets[3]);
let pixel = inverted.rgba.as_chunks::<4>().0.iter().find(|pixel| pixel[3] == 255).unwrap();
let expected = |byte: f32| (linear_to_srgb(1.0 - texturecraft_engine::texel::srgb_to_linear(byte / 255.0)) * 255.0 + 0.5) as i32;
assert!((i32::from(pixel[0]) - expected(51.0)).abs() <= 1 && (i32::from(pixel[2]) - expected(153.0)).abs() <= 1, "{pixel:?}");
// A position generator must produce a nonuniform mask
let mask = image(&mut service, &session, targets[2]);
let grays: Vec<u8> = mask.rgba.as_chunks::<4>().0.iter().filter(|pixel| pixel[3] == 255).map(|pixel| pixel[0]).collect();
assert!(grays.iter().max() != grays.iter().min());
}
#[test]
fn earlier_stages_never_show_later_effects_and_hidden_effects_are_bypassed() {
let mut s = session();
let st = stack(&mut s);
let base = Channel::BaseColor;
let (first, second) = (ThumbTarget::Stage { effect: st.invert, channel: base }, ThumbTarget::Stage { effect: st.posterize, channel: base });
let (mut svc, mut clock) = (ThumbService::new(), 0.0);
settle(&mut svc, &s, &[first, second], &mut clock);
let (a, b) = (image(&mut svc, &s, first), image(&mut svc, &s, second));
// Hide the second effect: its stage now shows the first one's result; the first is unchanged.
execute(&mut s, "effect.set", &json!({"effect": st.posterize.0, "visible": false})).unwrap();
settle(&mut svc, &s, &[first, second], &mut clock);
assert_eq!(image(&mut svc, &s, first), a);
assert_eq!(image(&mut svc, &s, second), a);
assert_ne!(a, b, "posterize should change something for the test to mean anything");
// And the content thumbnail (everything) follows.
let all = ThumbTarget::Content { layer: st.layer, channel: base };
settle(&mut svc, &s, &[all], &mut clock);
assert_eq!(image(&mut svc, &s, all), a);
}
#[test]
fn editing_invalidates_and_unrelated_changes_do_not() {
let mut s = session();
let st = stack(&mut s);
let t = ThumbTarget::Content { layer: st.layer, channel: Channel::BaseColor };
let (mut svc, mut clock) = (ThumbService::new(), 0.0);
settle(&mut svc, &s, &[t], &mut clock);
let before = image(&mut svc, &s, t);
let rendered = svc.rendered;
// A camera move changes the session revision but no thumbnail input: nothing is re-rendered.
execute(&mut s, "camera.set", &json!({"yaw": 0.7})).ok();
s.revision += 1;
for _ in 0..3 {
clock += 0.3;
svc.begin_frame(&s, clock);
svc.get(&s, t);
svc.poll(&s);
}
assert!(svc.is_fresh(t));
assert_eq!(svc.rendered, rendered, "an unrelated change re-rendered a thumbnail");
// An edit of the layer re-renders it, and the new picture is the new oracle.
execute(&mut s, "effect.set", &json!({"effect": st.invert.0, "visible": false})).unwrap();
clock += 0.3;
svc.begin_frame(&s, clock);
assert!(!svc.is_fresh(t));
settle(&mut svc, &s, &[t], &mut clock);
let after = image(&mut svc, &s, t);
assert_ne!(before, after);
assert_eq!(after, oracle(&s, t));
// Undo brings the first picture back.
execute(&mut s, "edit.undo", &Value::Null).unwrap();
settle(&mut svc, &s, &[t], &mut clock);
assert_eq!(image(&mut svc, &s, t), before);
}
#[test]
fn deleting_a_layer_with_a_pending_thumbnail_is_harmless() {
let mut s = session();
let st = stack(&mut s);
let (a, b) = (ThumbTarget::Content { layer: st.layer, channel: Channel::BaseColor }, ThumbTarget::Mask { layer: st.layer });
let mut svc = ThumbService::new();
// Queue the work and hand it to the worker, then delete the layer before collecting.
svc.begin_frame(&s, 1.0);
svc.get(&s, a);
svc.get(&s, b);
svc.poll(&s);
execute(&mut s, "layer.remove", &json!({"layer": st.layer.0})).unwrap();
let mut clock = 2.0;
for _ in 0..200 {
clock += 0.2;
svc.begin_frame(&s, clock);
// The row is gone, so nobody asks for it any more; the pending result is dropped.
svc.poll(&s);
std::thread::sleep(Duration::from_millis(2));
}
assert!(!svc.is_fresh(a) && !svc.is_fresh(b));
assert_eq!(svc.cached(), 0);
assert!(!svc.busy());
// Asking for a layer that no longer exists renders nothing and does not panic either.
settle_gone(&mut svc, &s, a, &mut clock);
}
fn settle_gone(svc: &mut ThumbService, s: &Session, t: ThumbTarget, clock: &mut f64) {
for _ in 0..20 {
*clock += 0.2;
svc.begin_frame(s, *clock);
svc.get(s, t);
svc.poll(s);
std::thread::sleep(Duration::from_millis(2));
}
assert!(svc.get(s, t).image.is_none());
}
#[test]
fn a_result_of_an_older_document_never_replaces_a_newer_one() {
let mut s = session();
let st = stack(&mut s);
let t = ThumbTarget::Content { layer: st.layer, channel: Channel::BaseColor };
let mut svc = ThumbService::new();
svc.begin_frame(&s, 1.0);
svc.get(&s, t);
svc.poll(&s); // the job of the first document is running
execute(&mut s, "effect.set", &json!({"effect": st.invert.0, "visible": false})).unwrap();
let mut clock = 2.0;
settle(&mut svc, &s, &[t], &mut clock);
// Whatever the first job returned, what is shown is the current document.
assert_eq!(image(&mut svc, &s, t), oracle(&s, t));
}
#[test]
fn only_requested_rows_render_and_the_cache_is_bounded() {
let mut session = session();
let layers: Vec<LayerId> = (0..(CACHE_ENTRIES + 30)).map(|_| id(execute(&mut session, "layer.add.paint", &Value::Null).unwrap(), "layer")).collect();
let target = |layer: LayerId| ThumbTarget::Content { layer, channel: Channel::BaseColor };
let mut service = ThumbService::new();
// A frame asks for six rows, then scrolling leaves only one visible
service.begin_frame(&session, 1.0);
for layer in &layers[..6] {
service.get(&session, target(*layer));
}
service.poll(&session);
let mut clock = 2.0;
for _ in 0..300 {
clock += 0.2;
service.begin_frame(&session, clock);
service.get(&session, target(layers[0]));
service.poll(&session);
std::thread::sleep(Duration::from_millis(1));
}
assert!(service.is_fresh(target(layers[0])));
let completed = layers[..6].iter().filter(|layer| service.is_fresh(target(**layer))).count();
assert!(completed <= 3, "{completed} of the scrolled-away rows were rendered");
// Scrolling through every layer evicts pictures and releases their allocations
let mut images = Vec::new();
for chunk in layers.chunks(12) {
let targets: Vec<ThumbTarget> = chunk.iter().map(|layer| target(*layer)).collect();
settle(&mut service, &session, &targets, &mut clock);
for target in targets {
images.push(std::sync::Arc::downgrade(&service.get(&session, target).image.unwrap()));
}
assert!(service.cached() <= CACHE_ENTRIES, "{}", service.cached());
}
clock += 0.2;
service.begin_frame(&session, clock);
service.poll(&session);
assert!(service.cached() <= CACHE_ENTRIES, "{}", service.cached());
assert!(images.len() > CACHE_ENTRIES);
assert!(images.first().unwrap().upgrade().is_none(), "the oldest image was evicted");
assert_eq!(images.iter().filter(|image| image.strong_count() > 0).count(), service.cached());
drop(service);
assert!(images.iter().all(|image| image.upgrade().is_none()), "closing the cache releases every picture");
}
#[test]
fn an_empty_paint_layer_is_transparent_and_a_folder_composites_its_children() {
let mut session = session();
let paint = id(execute(&mut session, "layer.add.paint", &Value::Null).unwrap(), "layer");
let fill = id(execute(&mut session, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer");
let folder = id(execute(&mut session, "layer.group", &json!({"layer": fill.0})).unwrap(), "layer");
let paint_target = ThumbTarget::Content { layer: paint, channel: Channel::BaseColor };
let folder_target = ThumbTarget::Content { layer: folder, channel: Channel::BaseColor };
let (mut service, mut clock) = (ThumbService::new(), 0.0);
settle(&mut service, &session, &[paint_target, folder_target], &mut clock);
assert!(image(&mut service, &session, paint_target).rgba.as_chunks::<4>().0.iter().all(|pixel| pixel[3] == 0), "nothing painted: nothing shown");
let folder_image = image(&mut service, &session, folder_target);
let pixel = folder_image.rgba.as_chunks::<4>().0.iter().find(|pixel| pixel[3] == 255).unwrap();
assert!((i32::from(pixel[0]) - 51).abs() <= 1 && (i32::from(pixel[2]) - 153).abs() <= 1, "{pixel:?}");
}
#[test]
fn instances_preview_the_source_content_and_inherited_mask() {
use texturecraft_engine::thumbs::{GbufCache, ThumbSnapshot};
let mut session = session();
let stack = stack(&mut session);
let instance = id(execute(&mut session, "layer.instance", &json!({"layer": stack.layer.0})).unwrap(), "layer");
let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap();
for channel in [Channel::BaseColor, Channel::Roughness] {
let source = snapshot.render(ThumbTarget::Content { layer: stack.layer, channel }).unwrap();
let preview = snapshot.render(ThumbTarget::Content { layer: instance, channel });
assert!(preview == Some(source), "the instance inherits {channel:?} from its source");
}
assert_eq!(snapshot.render(ThumbTarget::Mask { layer: instance }), snapshot.render(ThumbTarget::Mask { layer: stack.layer }));
}
/// A lower height anchor and an independent upper fill that can read it.
fn anchor_stack() -> (Session, LayerId, LayerId) {
let mut session = session();
execute(&mut session, "layer.add.fill", &json!({"height": 0.25})).unwrap();
let anchor = id(execute(&mut session, "effect.add.anchor", &Value::Null).unwrap(), "effect");
let layer = id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer");
(session, anchor, layer)
}
#[test]
fn thumbnails_keep_anchor_inputs_from_lower_layers() {
use texturecraft_engine::thumbs::{GbufCache, ThumbSnapshot};
let (mut session, anchor, layer) = anchor_stack();
execute(&mut session, "layer.fill.set", &json!({"channel": "roughness", "anchor": anchor.0, "anchorChannel": "height"})).unwrap();
execute(&mut session, "mask.add.black", &Value::Null).unwrap();
let mask_effect = id(execute(&mut session, "effect.add.fill", &json!({"anchor": anchor.0, "anchorChannel": "height"})).unwrap(), "effect");
let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap();
for target in [
ThumbTarget::Content { layer, channel: Channel::Roughness },
ThumbTarget::Mask { layer },
ThumbTarget::Stage { effect: mask_effect, channel: Channel::BaseColor },
] {
let image = snapshot.render(target).unwrap();
let pixel = image.rgba.as_chunks::<4>().0.iter().find(|pixel| pixel[3] == 255).unwrap();
assert!((i32::from(pixel[0]) - 64).abs() <= 1, "{target:?} must read the lower anchor's 0.25, got {pixel:?}");
}
}
#[test]
fn folder_thumbnails_keep_anchors_outside_the_folder() {
use texturecraft_engine::thumbs::{GbufCache, ThumbSnapshot};
let (mut session, anchor, layer) = anchor_stack();
execute(&mut session, "layer.fill.set", &json!({"channel": "roughness", "anchor": anchor.0, "anchorChannel": "height"})).unwrap();
let folder = id(execute(&mut session, "layer.group", &json!({"layer": layer.0})).unwrap(), "layer");
let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap();
let image = snapshot.render(ThumbTarget::Content { layer: folder, channel: Channel::Roughness }).unwrap();
let pixel = image.rgba.as_chunks::<4>().0.iter().find(|pixel| pixel[3] == 255).unwrap();
assert!((i32::from(pixel[0]) - 64).abs() <= 1, "the folder must read the external anchor's 0.25, got {pixel:?}");
}
#[test]
fn effect_only_anchor_reads_keep_the_lower_stack() {
use texturecraft_engine::thumbs::{GbufCache, ThumbSnapshot};
for target_kind in ["content", "mask"] {
let (mut session, anchor, layer) = anchor_stack();
if target_kind == "mask" {
execute(&mut session, "mask.add.black", &Value::Null).unwrap();
}
let effect = id(execute(&mut session, "effect.add.fill", &json!({"target": target_kind})).unwrap(), "effect");
if target_kind == "content" {
execute(&mut session, "layer.fill.set", &json!({"effect": effect.0, "channel": "roughness", "anchor": anchor.0, "anchorChannel": "height"}))
.unwrap();
} else {
execute(&mut session, "effect.set", &json!({"effect": effect.0, "anchor": anchor.0, "anchorChannel": "height"})).unwrap();
}
let target = if target_kind == "content" { ThumbTarget::Content { layer, channel: Channel::Roughness } } else { ThumbTarget::Mask { layer } };
let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap();
for target in [target, ThumbTarget::Stage { effect, channel: Channel::Roughness }] {
let image = snapshot.render(target).unwrap();
let pixel = image.rgba.as_chunks::<4>().0.iter().find(|pixel| pixel[3] == 255).unwrap();
assert!((i32::from(pixel[0]) - 64).abs() <= 1, "{target_kind} {target:?} must read the lower anchor's 0.25, got {pixel:?}");
}
}
}
+66 -2
View File
@@ -2,10 +2,10 @@
//! agents paint.
use serde_json::{Value, json};
use texturecraft_engine::core::Channel;
use texturecraft_engine::core::{Channel, LayerId};
use texturecraft_engine::geom::glam::Vec2;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute};
use texturecraft_engine::{Session, StackTarget, execute};
const RES: f32 = 256.0;
@@ -180,3 +180,67 @@ fn quick_mask_limits_painting() {
dab(&mut s, 150.0, 200.0);
assert!(color_at(&s, 150.0, 200.0)[1] > 0.85, "disabled: everything is open");
}
/// How much redder than green a texel must be to count as painted (faded edges included)
const PAINTED_TINT: f32 = 0.05;
/// Separate painted runs down texture column `x` (base color tinted red)
fn painted_runs(session: &Session, x: u32) -> usize {
let painted = |y: u32| {
let color = session.caches[0].composite.value(Channel::BaseColor, x, y);
color[0] - color[1] > PAINTED_TINT
};
(0..RES as u32).filter(|&y| painted(y) && (y == 0 || !painted(y - 1))).count()
}
#[test]
fn a_stroke_to_the_edge_of_the_mesh_fades_without_breaking_into_dots() {
let mut session = session();
paint_red(&mut session, 4.0);
// From the middle of the view to past the ball's right edge, above center
let points: Vec<Value> = (0..40).map(|step| json!([200.0 + step as f32 * 6.0, 165.0])).collect();
execute(&mut session, "tool.stroke", &json!({"points": points})).unwrap();
session.update();
// The stroke crosses each texture column once, also where the surface turns away from the camera
let broken: Vec<u32> = (0..RES as u32).filter(|&x| painted_runs(&session, x) > 1).collect();
assert!(broken.is_empty(), "columns with gaps: {broken:?}");
}
#[test]
fn swap_mask_value_inverts_only_while_a_mask_is_the_target() {
let mut session = session();
execute(&mut session, "layer.add.paint", &Value::Null).unwrap();
let swap = |session: &mut Session| execute(session, "tool.swapMaskValue", &Value::Null);
let effect_target = |result: Value| StackTarget::Effect(LayerId(result["effect"].as_u64().unwrap()));
assert!(swap(&mut session).is_err(), "painting the layer content: nothing to invert");
let content_effect = effect_target(execute(&mut session, "effect.add.paint", &json!({"target": "content"})).unwrap());
session.target = content_effect;
assert!(swap(&mut session).is_err(), "a content effect is not a mask");
execute(&mut session, "mask.add.white", &Value::Null).unwrap();
session.target = StackTarget::Mask;
session.tool.mask_value = 0.2;
swap(&mut session).unwrap();
assert_eq!(session.tool.mask_value, 0.8);
session.tool.mask_value = 1.0;
swap(&mut session).unwrap();
assert_eq!(session.tool.mask_value, 0.0);
swap(&mut session).unwrap();
assert_eq!(session.tool.mask_value, 1.0, "pressing it again goes back");
session.target = effect_target(execute(&mut session, "effect.add.paint", &json!({"target": "mask"})).unwrap());
swap(&mut session).unwrap();
assert_eq!(session.tool.mask_value, 0.0, "a mask effect paints the mask too");
}
+3
View File
@@ -27,3 +27,6 @@ serde_json = { workspace = true }
thiserror = { workspace = true }
rayon = { workspace = true }
base64 = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
sysinfo = { workspace = true }
+21 -2
View File
@@ -128,6 +128,8 @@ pub fn save_project_bytes(pf: &ProjectFile) -> Result<Vec<u8>>;
pub fn load_project_bytes(bytes: &[u8]) -> Result<ProjectFile>;
pub fn save_project(path: &Path, pf: &ProjectFile) -> Result<()>; // native, atomic
pub fn load_project(path: &Path) -> Result<ProjectFile>; // native
pub fn set_project_open_limit_gib(limit_gib: u32); // subsequent loads, minimum 1 GiB
pub fn project_open_limit_gib() -> u32;
```
`.tcraft` layout (zip, deflate):
@@ -152,8 +154,25 @@ maps retain their working atlas layout.
Loading runs `Project::validate`, refuses a newer `format_version` (`FormatError::NewerVersion`),
checks every tile against its texture set's resolution and component count, rejects repeated or
out-of-range tiles and trailing data, drops pixels of layers that are in no stack, and caps the
total decompressed size at 8 GiB.
out-of-range tiles and trailing data, and drops pixels of layers that are in no stack. Total
decompressed project data is limited to 8 GiB by default. Settings › Project › Max project size on
open changes this limit, in GiB, independently of the save CPU and RAM preferences. Each load keeps
the limit it started with; individual resource, mesh, image and entry-count limits still apply.
The limit counts file data, including binary headers and tile coordinates, rather than peak process
memory. Saves and autosaves are not refused by this open limit; raise it to reopen a larger project.
Opening checks the sum of all declared ZIP payload sizes before decompression, including unknown
entries, and checks actual reads against the same limit independently. Overlapping ZIP entries are
rejected. ZIP indexing is restricted to the final 32 MiB with a 64 MiB read allowance before the
100,000-entry limit can be checked. Baked-map dimensions must agree with the entry size; float data
is read in bounded chunks with fallible allocation. Nested archives are not recursively extracted
by the project reader. Subsequent image and mesh decoding has separate format-specific limits;
the project-open limit is not a combined budget for those decoded assets or the application's heap.
Native saves compress entries in parallel within the configured CPU allowance and an estimated
in-flight byte budget. Stored resources and entries larger than that budget stream directly into
the destination without a whole-entry temporary buffer. The save RAM percentage is an estimate,
excluding compressor, allocator and project-snapshot overhead; it is not a peak process memory cap.
Unreadable bake settings fall back to defaults field by field while readable settings and project
content are retained. Legacy baked-map filenames remain readable; unsupported baked-map types are
+33 -28
View File
@@ -72,34 +72,37 @@ fn collect(dir: &Path, depth: usize, out: &mut Vec<PathBuf>) {
/// The faces of the font file at `path` (each face of a collection).
pub fn faces_of(path: &Path) -> std::io::Result<Vec<FontFace>> {
let mut f = std::fs::File::open(path)?;
let mut at = |offset: u64, len: usize| -> std::io::Result<Vec<u8>> {
f.seek(SeekFrom::Start(offset))?;
let mut buf = vec![0; len];
f.read_exact(&mut buf)?;
let mut file = std::fs::File::open(path)?;
let mut read_at = |offset: u64, length: usize| -> std::io::Result<Vec<u8>> {
file.seek(SeekFrom::Start(offset))?;
let mut buf = vec![0; length];
file.read_exact(&mut buf)?;
Ok(buf)
};
let head = at(0, 12)?;
let offsets: Vec<u64> = if head.get(..4) == Some(b"ttcf") {
let n = u32_at(&head, 8).unwrap_or(0).min(MAX_FACES_PER_FILE);
let table = at(12, 4 * n as usize)?;
(0..n as usize).filter_map(|i| u32_at(&table, 4 * i)).map(u64::from).collect()
let header = read_at(0, 12)?;
let offsets: Vec<u64> = if header.get(..4) == Some(b"ttcf") {
let face_count = u32_at(&header, 8).unwrap_or(0).min(MAX_FACES_PER_FILE);
let table = read_at(12, 4 * face_count as usize)?;
(0..face_count as usize).filter_map(|i| u32_at(&table, 4 * i)).map(u64::from).collect()
} else {
vec![0]
};
let mut faces = Vec::new();
for (index, offset) in offsets.into_iter().enumerate() {
let dir = at(offset, 12)?;
let tables = at(offset + 12, 16 * usize::from(u16_at(&dir, 4).unwrap_or(0)))?;
let Some(rec) = tables.chunks_exact(16).find(|r| r.get(..4) == Some(b"name")) else { continue };
let (Some(off), Some(len)) = (u32_at(rec, 8), u32_at(rec, 12)) else { continue };
let names = at(u64::from(off), len.min(MAX_NAME_TABLE) as usize)?;
let directory = read_at(offset, 12)?;
let tables = read_at(offset + 12, 16 * usize::from(u16_at(&directory, 4).unwrap_or(0)))?;
let Some(record) = tables.as_chunks::<16>().0.iter().find(|r| r.get(..4) == Some(b"name")) else { continue };
let (Some(offset), Some(length)) = (u32_at(record, 8), u32_at(record, 12)) else { continue };
let names = read_at(u64::from(offset), length.min(MAX_NAME_TABLE) as usize)?;
let name = |ids: [u16; 2]| ids.iter().find_map(|id| name_string(&names, *id));
if let Some(family) = name([16, 1]) {
let style = name([17, 2]).unwrap_or_else(|| "Regular".into());
faces.push(FontFace { family, style, path: path.to_path_buf(), index: index as u32 });
}
}
Ok(faces)
}
@@ -113,30 +116,32 @@ fn u32_at(b: &[u8], o: usize) -> Option<u32> {
/// Name `id` of a `name` table, in English when it has several languages: Windows and Unicode
/// records are UTF-16BE, Macintosh ones single-byte (read as Latin-1).
fn name_string(t: &[u8], id: u16) -> Option<String> {
let (count, base) = (usize::from(u16_at(t, 2)?), usize::from(u16_at(t, 4)?));
fn name_string(table: &[u8], id: u16) -> Option<String> {
let (count, base) = (usize::from(u16_at(table, 2)?), usize::from(u16_at(table, 4)?));
let mut best: Option<(u8, String)> = None;
for r in (0..count).filter_map(|i| t.get(6 + 12 * i..18 + 12 * i)) {
let (platform, language, name_id) = (u16_at(r, 0)?, u16_at(r, 4)?, u16_at(r, 6)?);
let (len, off) = (usize::from(u16_at(r, 8)?), usize::from(u16_at(r, 10)?));
let Some(bytes) = t.get(base + off..base + off + len) else { continue };
for record in (0..count).filter_map(|i| table.get(6 + 12 * i..18 + 12 * i)) {
let (platform, language, name_id) = (u16_at(record, 0)?, u16_at(record, 4)?, u16_at(record, 6)?);
let (length, offset) = (usize::from(u16_at(record, 8)?), usize::from(u16_at(record, 10)?));
let Some(bytes) = table.get(base + offset..base + offset + length) else { continue };
if name_id != id {
continue;
}
let (rank, s) = match platform {
let (rank, name) = match platform {
3 | 0 => {
let s = String::from_utf16_lossy(&bytes.chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect::<Vec<_>>());
(if language == 0x409 { 0 } else { 1 }, s)
let name = String::from_utf16_lossy(&bytes.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)).collect::<Vec<_>>());
(if language == 0x409 { 0 } else { 1 }, name)
}
1 => (if language == 0 { 2 } else { 3 }, bytes.iter().map(|b| char::from(*b)).collect()),
_ => continue,
};
let s = s.trim().to_string();
if !s.is_empty() && best.as_ref().is_none_or(|(r, _)| rank < *r) {
best = Some((rank, s));
let name = name.trim().to_string();
if !name.is_empty() && best.as_ref().is_none_or(|(best_rank, _)| rank < *best_rank) {
best = Some((rank, name));
}
}
best.map(|(_, s)| s)
best.map(|(_, name)| name)
}
#[cfg(test)]
+7 -2
View File
@@ -47,14 +47,19 @@ pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_h
#[cfg(not(target_arch = "wasm32"))]
pub use presets::load_preset;
pub use presets::{builtin_preset, builtin_presets, preset_from_json, preset_to_json};
pub use project_file::{BakePaintData, ProjectFile, load_project_bytes, sanitize_resource_name, save_project_bytes};
pub use project_file::{
BakePaintData, DEFAULT_PROJECT_OPEN_LIMIT_GIB, ProjectFile, load_project_bytes, project_open_limit_gib, sanitize_resource_name, save_project_bytes,
set_project_open_limit_gib,
};
#[cfg(not(target_arch = "wasm32"))]
pub use export::write_files;
#[cfg(not(target_arch = "wasm32"))]
pub use mesh_import::{import_mesh, read_mesh_file};
#[cfg(not(target_arch = "wasm32"))]
pub use project_file::{load_project, save_project};
pub use project_file::{
DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_resources, load_project, save_project, save_ram_budget, set_save_resources,
};
#[derive(Debug, thiserror::Error)]
pub enum FormatError {
+23 -20
View File
@@ -67,47 +67,50 @@ pub fn obj_with_mtl(mesh: &Mesh, name: &str, stem: &str, textures: &[Vec<Exporte
}
fn obj_text(mesh: &Mesh, name: &str, mtllib: Option<&str>) -> String {
let mut s = String::with_capacity(mesh.positions.len() * 96 + mesh.indices.len() * 12);
let _ = writeln!(s, "# {}, exported by TextureCraft", token(name));
let mut text = String::with_capacity(mesh.positions.len() * 96 + mesh.indices.len() * 12);
let _ = writeln!(text, "# {}, exported by TextureCraft", token(name));
if let Some(lib) = mtllib {
let _ = writeln!(s, "mtllib {lib}");
let _ = writeln!(text, "mtllib {lib}");
}
let _ = writeln!(s, "o {}", token(name));
let _ = writeln!(text, "o {}", token(name));
for p in &mesh.positions {
let _ = writeln!(s, "v {} {} {}", p.x, p.y, p.z);
let _ = writeln!(text, "v {} {} {}", p.x, p.y, p.z);
}
let uvs = mesh.uvs.len() == mesh.positions.len();
let normals = mesh.normals.len() == mesh.positions.len();
if uvs {
for t in &mesh.uvs {
let _ = writeln!(s, "vt {} {}", t.x, 1.0 - t.y);
let _ = writeln!(text, "vt {} {}", t.x, 1.0 - t.y);
}
}
if normals {
for n in &mesh.normals {
let _ = writeln!(s, "vn {} {} {}", n.x, n.y, n.z);
let _ = writeln!(text, "vn {} {} {}", n.x, n.y, n.z);
}
}
let materials = unique_ids(&mesh.materials, token);
for sm in &parts(mesh, name) {
let material = materials.get(sm.material).map_or("default", String::as_str);
let _ = writeln!(s, "g {}\nusemtl {material}", token(&sm.name));
let (a, b) = (sm.start as usize, sm.start as usize + sm.count as usize);
for tri in mesh.indices.get(a..b).unwrap_or_default().chunks_exact(3) {
s.push('f');
for i in tri {
for part in &parts(mesh, name) {
let material = materials.get(part.material).map_or("default", String::as_str);
let _ = writeln!(text, "g {}\nusemtl {material}", token(&part.name));
let (a, b) = (part.start as usize, part.start as usize + part.count as usize);
for triangle in mesh.indices.get(a..b).unwrap_or_default().as_chunks::<3>().0 {
text.push('f');
for i in triangle {
let i = i + 1;
let _ = match (uvs, normals) {
(true, true) => write!(s, " {i}/{i}/{i}"),
(true, false) => write!(s, " {i}/{i}"),
(false, true) => write!(s, " {i}//{i}"),
(false, false) => write!(s, " {i}"),
(true, true) => write!(text, " {i}/{i}/{i}"),
(true, false) => write!(text, " {i}/{i}"),
(false, true) => write!(text, " {i}//{i}"),
(false, false) => write!(text, " {i}"),
};
}
s.push('\n');
text.push('\n');
}
}
s
text
}
/// `id` of each material name, made unique with `_2`, `_3`… where two would be the same, also
+33 -27
View File
@@ -166,60 +166,64 @@ fn identifier(s: &str, taken: &mut Vec<String>) -> String {
/// The export scene: `/<name>` with the `Mesh` and `Materials`. `files[m]` are the texture
/// file names (by slot) of material `m`.
fn scene(mesh: &Mesh, name: &str, files: &[Vec<(usize, String)>]) -> Result<UsdLayer> {
let n = mesh.positions.len();
if n == 0 || mesh.indices.len() < 3 {
let vertex_count = mesh.positions.len();
if vertex_count == 0 || mesh.indices.len() < 3 {
return Err(FormatError::Invalid("the mesh is empty".into()));
}
let ints =
|v: &[u32]| v.iter().map(|&i| i32::try_from(i).map_err(|_| FormatError::TooLarge("vertex index beyond 2^31".into()))).collect::<Result<Vec<i32>>>();
let mut taken = Vec::new();
let root_name = identifier(name, &mut taken);
let mut root = UsdPrim::new(&root_name, "Xform");
let mut geo = UsdPrim::new(&identifier(&format!("{name}_mesh"), &mut taken), "Mesh");
let mat_names: Vec<String> = mesh.materials.iter().map(|m| identifier(m, &mut taken)).collect();
let mat_path = |m: usize| mat_names.get(m).map(|id| format!("/{root_name}/Materials/{id}"));
let mut geometry = UsdPrim::new(&identifier(&format!("{name}_mesh"), &mut taken), "Mesh");
let material_names: Vec<String> = mesh.materials.iter().map(|m| identifier(m, &mut taken)).collect();
let material_path = |m: usize| material_names.get(m).map(|id| format!("/{root_name}/Materials/{id}"));
let (lo, hi) = mesh.bounds();
// Faces in submesh order; subsets index them.
let mut tris: Vec<u32> = Vec::with_capacity(mesh.indices.len());
// Faces in submesh order; subsets index them
let mut indices: Vec<u32> = Vec::with_capacity(mesh.indices.len());
let mut faces_of: Vec<Vec<i32>> = vec![Vec::new(); mesh.materials.len()];
for sm in parts(mesh, name) {
let range = mesh.indices.get(sm.start as usize..(sm.start as usize).saturating_add(sm.count as usize)).unwrap_or_default();
for t in range.chunks_exact(3) {
if let Some(f) = faces_of.get_mut(sm.material) {
f.push(i32::try_from(tris.len() / 3).map_err(|_| FormatError::TooLarge("triangle count".into()))?);
for part in parts(mesh, name) {
let range = mesh.indices.get(part.start as usize..(part.start as usize).saturating_add(part.count as usize)).unwrap_or_default();
for t in range.as_chunks::<3>().0 {
if let Some(f) = faces_of.get_mut(part.material) {
f.push(i32::try_from(indices.len() / 3).map_err(|_| FormatError::TooLarge("triangle count".into()))?);
}
tris.extend_from_slice(t);
indices.extend_from_slice(t);
}
}
let vertex = |mut a: UsdAttr| {
a.interpolation = Some("vertex");
a
};
geo.attrs = vec![
geometry.attrs = vec![
UsdAttr::new("extent", "float3[]", Some(UsdValue::Vec3fs(vec![lo.to_array(), hi.to_array()]))),
UsdAttr::new("faceVertexCounts", "int[]", Some(UsdValue::Ints(vec![3; tris.len() / 3]))),
UsdAttr::new("faceVertexIndices", "int[]", Some(UsdValue::Ints(ints(&tris)?))),
UsdAttr::new("faceVertexCounts", "int[]", Some(UsdValue::Ints(vec![3; indices.len() / 3]))),
UsdAttr::new("faceVertexIndices", "int[]", Some(UsdValue::Ints(ints(&indices)?))),
UsdAttr::new("points", "point3f[]", Some(UsdValue::Vec3fs(mesh.positions.iter().map(|p| p.to_array()).collect()))),
UsdAttr::new("subdivisionScheme", "token", Some(UsdValue::Token("none".into()))).uniform(),
];
if mesh.normals.len() == n {
geo.attrs.push(vertex(UsdAttr::new("normals", "normal3f[]", Some(UsdValue::Vec3fs(mesh.normals.iter().map(|v| v.to_array()).collect())))));
if mesh.normals.len() == vertex_count {
geometry.attrs.push(vertex(UsdAttr::new("normals", "normal3f[]", Some(UsdValue::Vec3fs(mesh.normals.iter().map(|v| v.to_array()).collect())))));
}
if mesh.uvs.len() == n {
// USD's st origin is bottom-left.
if mesh.uvs.len() == vertex_count {
// USD's st origin is bottom-left
let st = mesh.uvs.iter().map(|t| [t.x, 1.0 - t.y]).collect();
geo.attrs.push(vertex(UsdAttr::new("primvars:st", "texCoord2f[]", Some(UsdValue::Vec2fs(st)))));
geometry.attrs.push(vertex(UsdAttr::new("primvars:st", "texCoord2f[]", Some(UsdValue::Vec2fs(st)))));
}
let used: Vec<usize> = (0..mesh.materials.len()).filter(|m| faces_of.get(*m).is_some_and(|f| !f.is_empty())).collect();
match used.as_slice() {
[] => {}
[m] => {
geo.binding_api = true;
geo.attrs.extend(mat_path(*m).map(|p| UsdAttr::rel("material:binding", p)));
geometry.binding_api = true;
geometry.attrs.extend(material_path(*m).map(|p| UsdAttr::rel("material:binding", p)));
}
_ => {
for &m in &used {
let (Some(id), Some(path)) = (mat_names.get(m), mat_path(m)) else { continue };
let (Some(id), Some(path)) = (material_names.get(m), material_path(m)) else { continue };
let mut subset = UsdPrim::new(id, "GeomSubset");
subset.binding_api = true;
subset.attrs = vec![
@@ -228,18 +232,20 @@ fn scene(mesh: &Mesh, name: &str, files: &[Vec<(usize, String)>]) -> Result<UsdL
UsdAttr::new("indices", "int[]", Some(UsdValue::Ints(faces_of.get(m).cloned().unwrap_or_default()))),
UsdAttr::rel("material:binding", path),
];
geo.children.push(subset);
geometry.children.push(subset);
}
}
}
root.children.push(geo);
root.children.push(geometry);
let mut materials = UsdPrim::new("Materials", "Scope");
for (m, id) in mat_names.iter().enumerate() {
for (m, id) in material_names.iter().enumerate() {
materials.children.push(material(&format!("/{root_name}/Materials/{id}"), id, files.get(m).map_or(&[][..], Vec::as_slice)));
}
if !materials.children.is_empty() {
root.children.push(materials);
}
Ok(UsdLayer { root })
}
+41 -30
View File
@@ -204,37 +204,37 @@ impl<'a> Ogawa<'a> {
}
/// The first sample of a scalar or array property as numbers (`extent` per item).
fn values(&mut self, p: &Prop) -> Result<Vec<f64>> {
let samples = self.group(p.group)?;
fn values(&mut self, property: &Prop) -> Result<Vec<f64>> {
let samples = self.group(property.group)?;
let Some(&first) = samples.first() else { return Ok(Vec::new()) };
let raw = self.data(first)?;
let raw = if raw.is_empty() {
raw
} else {
raw.get(KEY_BYTES..).ok_or_else(|| malformed(KIND, format!("sample of \"{}\" is shorter than its key", p.name)))?
raw.get(KEY_BYTES..).ok_or_else(|| malformed(KIND, format!("sample of \"{}\" is shorter than its key", property.name)))?
};
let size = match p.pod {
let value_bytes = match property.pod {
0..=2 => 1,
3 | 4 => 2,
5 | 6 | 10 => 4,
7 | 8 | 11 => 8,
other => return Err(FormatError::Unsupported(format!("Alembic property \"{}\" of data type {other}", p.name))),
other => return Err(FormatError::Unsupported(format!("Alembic property \"{}\" of data type {other}", property.name))),
};
self.charge((raw.len() / size).saturating_mul(8))?;
fn le<const N: usize>(c: &[u8]) -> [u8; N] {
<[u8; N]>::try_from(c).unwrap_or([0; N])
}
Ok(match p.pod {
self.charge((raw.len() / value_bytes).saturating_mul(8))?;
Ok(match property.pod {
0 | 1 => raw.iter().map(|v| *v as f64).collect(),
2 => raw.iter().map(|v| *v as i8 as f64).collect(),
3 => raw.chunks_exact(2).map(|c| u16::from_le_bytes(le(c)) as f64).collect(),
4 => raw.chunks_exact(2).map(|c| i16::from_le_bytes(le(c)) as f64).collect(),
5 => raw.chunks_exact(4).map(|c| u32::from_le_bytes(le(c)) as f64).collect(),
6 => raw.chunks_exact(4).map(|c| i32::from_le_bytes(le(c)) as f64).collect(),
7 => raw.chunks_exact(8).map(|c| u64::from_le_bytes(le(c)) as f64).collect(),
8 => raw.chunks_exact(8).map(|c| i64::from_le_bytes(le(c)) as f64).collect(),
10 => raw.chunks_exact(4).map(|c| f32::from_le_bytes(le(c)) as f64).collect(),
_ => raw.chunks_exact(8).map(|c| f64::from_le_bytes(le(c))).collect(),
3 => raw.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c) as f64).collect(),
4 => raw.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(*c) as f64).collect(),
5 => raw.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(*c) as f64).collect(),
6 => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(*c) as f64).collect(),
7 => raw.as_chunks::<8>().0.iter().map(|c| u64::from_le_bytes(*c) as f64).collect(),
8 => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(*c) as f64).collect(),
10 => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c) as f64).collect(),
_ => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(*c)).collect(),
})
}
@@ -491,21 +491,23 @@ impl Walk<'_, '_> {
}
fn mesh(&mut self, r: u64, world: Mat4, sets: &[(String, Vec<f64>)]) -> Result<()> {
let props = self.o.compound(r)?;
let properties = self.o.compound(r)?;
let get = |o: &mut Ogawa, name: &str| -> Result<Vec<f64>> {
match find(&props, name) {
match find(&properties, name) {
Some(p) => o.values(p),
None => Err(malformed(KIND, format!("PolyMesh has no {name}"))),
}
};
let p = get(&mut self.o, "P")?;
let indices = get(&mut self.o, ".faceIndices")?;
let counts = get(&mut self.o, ".faceCounts")?;
check_vertices(p.len() / 3)?;
let points: Vec<Vec3> = p.chunks_exact(3).map(|c| world.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect();
let points: Vec<Vec3> = p.as_chunks::<3>().0.iter().map(|c| world.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect();
let n = [points.len(), counts.len(), indices.len()];
let normals = self.param(&props, "N", n)?;
let uvs = self.param(&props, "uv", n)?;
let normals = self.param(&properties, "N", n)?;
let uvs = self.param(&properties, "uv", n)?;
let mut material = vec![None::<usize>; counts.len()];
for (s, (_, faces)) in sets.iter().enumerate() {
for f in faces {
@@ -514,19 +516,26 @@ impl Walk<'_, '_> {
}
}
}
let nm = Mat3::from_mat4(world).inverse().transpose();
// Alembic winds polygons clockwise; a mirroring transform flips them once more.
let normal_transform = Mat3::from_mat4(world).inverse().transpose();
// Alembic winds polygons clockwise; a mirroring transform flips them once more
let keep_order = world.determinant() < 0.0;
let (mut k, mut corners, mut bad_uvs) = (0usize, Vec::new(), 0usize);
for (f, &count) in counts.iter().enumerate() {
let end = (count >= 0.0).then(|| k.checked_add(count as usize)).flatten().filter(|e| *e <= indices.len());
let end = end.ok_or_else(|| malformed(KIND, format!("face {f} has {count} corners past the index list")))?;
corners.clear();
for (kk, &pi) in indices.iter().enumerate().take(end).skip(k) {
let p = points.get(pi as usize).filter(|_| pi >= 0.0).ok_or_else(|| malformed(KIND, format!("point index {pi} out of range")))?;
let pi = pi as usize;
let n = normals.as_ref().and_then(|l| l.get::<3>(kk, pi, f)).map(|[x, y, z]| nm * Vec3::new(x as f32, y as f32, z as f32));
let uv = uvs.as_ref().map(|l| match l.get::<2>(kk, pi, f) {
for (corner_index, &point_index) in indices.iter().enumerate().take(end).skip(k) {
let p = points
.get(point_index as usize)
.filter(|_| point_index >= 0.0)
.ok_or_else(|| malformed(KIND, format!("point index {point_index} out of range")))?;
let point_index = point_index as usize;
let n = normals
.as_ref()
.and_then(|l| l.get::<3>(corner_index, point_index, f))
.map(|[x, y, z]| normal_transform * Vec3::new(x as f32, y as f32, z as f32));
let uv = uvs.as_ref().map(|l| match l.get::<2>(corner_index, point_index, f) {
Some([u, v]) => Vec2::new(u as f32, 1.0 - v as f32),
None => {
bad_uvs += 1;
@@ -542,9 +551,11 @@ impl Walk<'_, '_> {
let name = material.get(f).copied().flatten().and_then(|s| sets.get(s)).map_or(DEFAULT_MATERIAL, |(n, _)| n.as_str());
self.sink.polygon(name, &corners)?;
}
if bad_uvs > 0 {
self.sink.warn(format!("{bad_uvs} polygon corners have no UV in the Alembic uv parameter (set to 0, 0)"));
}
Ok(())
}
}
+43 -36
View File
@@ -254,39 +254,39 @@ impl<'a> Binary<'a> {
})
}
fn array(&mut self, ty: u8) -> Result<Vec<f64>> {
fn array(&mut self, value_type: u8) -> Result<Vec<f64>> {
let (count, encoding, stored) = (self.u32()?, self.u32()?, self.u32()?);
let size = match ty {
let value_bytes = match value_type {
b'd' | b'l' => 8,
b'f' | b'i' => 4,
_ => 1,
};
let len = count.checked_mul(size).ok_or_else(|| malformed(KIND, "array too large"))?;
let decoded_bytes = count.checked_mul(value_bytes).ok_or_else(|| malformed(KIND, "array too large"))?;
self.budget.charge(count.saturating_mul(8))?;
let data = self.take(stored)?;
let raw: Cow<[u8]> = match encoding {
0 if stored == len => Cow::Borrowed(data),
0 if stored == decoded_bytes => Cow::Borrowed(data),
1 => {
let mut out = Vec::new();
flate2::read::ZlibDecoder::new(data)
.take(len as u64 + 1)
.take(decoded_bytes as u64 + 1)
.read_to_end(&mut out)
.map_err(|e| malformed(KIND, format!("bad compressed array: {e}")))?;
if out.len() != len {
if out.len() != decoded_bytes {
return Err(malformed(KIND, "compressed array has the wrong length"));
}
Cow::Owned(out)
}
_ => return Err(malformed(KIND, format!("array encoding {encoding} with {stored} bytes for {count} items"))),
};
fn le<const N: usize>(c: &[u8]) -> [u8; N] {
<[u8; N]>::try_from(c).unwrap_or([0; N])
}
Ok(match ty {
b'd' => raw.chunks_exact(8).map(|c| f64::from_le_bytes(le(c))).collect(),
b'l' => raw.chunks_exact(8).map(|c| i64::from_le_bytes(le(c)) as f64).collect(),
b'f' => raw.chunks_exact(4).map(|c| f32::from_le_bytes(le(c)) as f64).collect(),
b'i' => raw.chunks_exact(4).map(|c| i32::from_le_bytes(le(c)) as f64).collect(),
Ok(match value_type {
b'd' => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(*c)).collect(),
b'l' => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(*c) as f64).collect(),
b'f' => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c) as f64).collect(),
b'i' => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(*c) as f64).collect(),
_ => raw.iter().map(|b| *b as f64).collect(),
})
}
@@ -783,29 +783,34 @@ impl Layer<'_> {
}
}
fn add_geometry(sink: &mut PolygonSink, g: &Node, m: Mat4, slots: &[String]) -> Result<()> {
let verts = g.child("Vertices").map(Node::arr).unwrap_or_default();
check_vertices(verts.len() / 3)?;
let points: Vec<Vec3> = verts.chunks_exact(3).map(|c| m.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect();
let pvi = g.child("PolygonVertexIndex").map(Node::arr).unwrap_or_default();
let normals = Layer::read(g, "LayerElementNormal", "Normals", "NormalsIndex");
let uvs = Layer::read(g, "LayerElementUV", "UV", "UVIndex");
let mats = Layer::read(g, "LayerElementMaterial", "Materials", "");
let nm = Mat3::from_mat4(m).inverse().transpose();
let flip = m.determinant() < 0.0;
let (mut corners, mut poly, mut bad_normals, mut bad_uvs) = (Vec::new(), 0usize, 0usize, 0usize);
for (k, &v) in pvi.iter().enumerate() {
// The last corner of each polygon is stored as -(index + 1).
let (cp, last) = if v < 0.0 { (-v - 1.0, true) } else { (v, false) };
let p = points.get(cp as usize).filter(|_| cp.fract() == 0.0).ok_or_else(|| malformed(KIND, format!("polygon vertex index {v} out of range")))?;
let cp = cp as usize;
fn add_geometry(sink: &mut PolygonSink, geometry: &Node, transform: Mat4, slots: &[String]) -> Result<()> {
let vertices = geometry.child("Vertices").map(Node::arr).unwrap_or_default();
check_vertices(vertices.len() / 3)?;
let points: Vec<Vec3> = vertices.as_chunks::<3>().0.iter().map(|c| transform.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect();
let polygon_indices = geometry.child("PolygonVertexIndex").map(Node::arr).unwrap_or_default();
let normals = Layer::read(geometry, "LayerElementNormal", "Normals", "NormalsIndex");
let uvs = Layer::read(geometry, "LayerElementUV", "UV", "UVIndex");
let materials = Layer::read(geometry, "LayerElementMaterial", "Materials", "");
let normal_transform = Mat3::from_mat4(transform).inverse().transpose();
let flip = transform.determinant() < 0.0;
let (mut corners, mut polygon_index, mut bad_normals, mut bad_uvs) = (Vec::new(), 0usize, 0usize, 0usize);
for (k, &v) in polygon_indices.iter().enumerate() {
// The last corner of each polygon is stored as -(index + 1)
let (control_point, last) = if v < 0.0 { (-v - 1.0, true) } else { (v, false) };
let p = points
.get(control_point as usize)
.filter(|_| control_point.fract() == 0.0)
.ok_or_else(|| malformed(KIND, format!("polygon vertex index {v} out of range")))?;
let control_point = control_point as usize;
let n = normals.as_ref().and_then(|l| {
let n = l.get(k, cp, poly).map(|[x, y, z]| nm * Vec3::new(x as f32, y as f32, z as f32));
let n = l.get(k, control_point, polygon_index).map(|[x, y, z]| normal_transform * Vec3::new(x as f32, y as f32, z as f32));
bad_normals += usize::from(n.is_none());
n
});
// A UV layer with holes keeps its layout: missing items read as 0, 0.
let uv = uvs.as_ref().map(|l| match l.get(k, cp, poly) {
// A UV layer with holes keeps its layout: missing items read as 0, 0
let uv = uvs.as_ref().map(|l| match l.get(k, control_point, polygon_index) {
Some([u, v]) => Vec2::new(u as f32, 1.0 - v as f32),
None => {
bad_uvs += 1;
@@ -813,22 +818,24 @@ fn add_geometry(sink: &mut PolygonSink, g: &Node, m: Mat4, slots: &[String]) ->
}
});
corners.push(Corner { p: *p, n, uv });
if last || k + 1 == pvi.len() {
if last || k + 1 == polygon_indices.len() {
if flip {
corners.reverse();
}
let slot = mats.as_ref().and_then(|l| l.get(poly, poly, poly)).map_or(0.0, |[s]| s);
let slot = materials.as_ref().and_then(|l| l.get(polygon_index, polygon_index, polygon_index)).map_or(0.0, |[s]| s);
let name = slots.get(slot as usize).filter(|_| slot >= 0.0).map_or("Default", String::as_str);
sink.polygon(name, &corners)?;
corners.clear();
poly += 1;
polygon_index += 1;
}
}
if bad_normals > 0 {
sink.warn(format!("{bad_normals} polygon corners have no normal in the FBX normal layer; normals were recomputed"));
}
if bad_uvs > 0 {
sink.warn(format!("{bad_uvs} polygon corners have no UV in the FBX UV layer (set to 0, 0)"));
}
Ok(())
}
+38 -32
View File
@@ -96,33 +96,36 @@ struct Attrs {
color_seen: bool,
}
fn add_primitive(raw: &mut RawMesh, attrs: &mut Attrs, prim: &gltf::Primitive, m: Mat4, buffers: &[gltf::buffer::Data], part: &str) -> Result<()> {
if prim.mode() != Mode::Triangles {
raw.warnings.push(format!("skipped a primitive drawn as {:?} (only triangles are supported)", prim.mode()));
fn add_primitive(raw: &mut RawMesh, attrs: &mut Attrs, primitive: &gltf::Primitive, transform: Mat4, buffers: &[gltf::buffer::Data], part: &str) -> Result<()> {
if primitive.mode() != Mode::Triangles {
raw.warnings.push(format!("skipped a primitive drawn as {:?} (only triangles are supported)", primitive.mode()));
return Ok(());
}
let Some(pacc) = prim.get(&Semantic::Positions) else {
let Some(position_accessor) = primitive.get(&Semantic::Positions) else {
raw.warnings.push("skipped a primitive without positions".into());
return Ok(());
};
check_accessor(&pacc, buffers, Dimensions::Vec3, &[DataType::F32], "position")?;
let nacc = prim.get(&Semantic::Normals);
if let Some(a) = &nacc {
check_accessor(&position_accessor, buffers, Dimensions::Vec3, &[DataType::F32], "position")?;
let normal_accessor = primitive.get(&Semantic::Normals);
if let Some(a) = &normal_accessor {
check_accessor(a, buffers, Dimensions::Vec3, &[DataType::F32], "normal")?;
}
let tacc = prim.get(&Semantic::TexCoords(0));
if let Some(a) = &tacc {
let texcoord_accessor = primitive.get(&Semantic::TexCoords(0));
if let Some(a) = &texcoord_accessor {
check_accessor(a, buffers, Dimensions::Vec2, &[DataType::F32, DataType::U8, DataType::U16], "texcoord")?;
}
let cacc = prim.get(&Semantic::Colors(0));
if let Some(a) = &cacc {
let color_accessor = primitive.get(&Semantic::Colors(0));
if let Some(a) = &color_accessor {
let dims = if a.dimensions() == Dimensions::Vec3 { Dimensions::Vec3 } else { Dimensions::Vec4 };
check_accessor(a, buffers, dims, &[DataType::F32, DataType::U8, DataType::U16], "color")?;
}
if let Some(a) = prim.indices() {
if let Some(a) = primitive.indices() {
check_accessor(&a, buffers, Dimensions::Scalar, &[DataType::U8, DataType::U16, DataType::U32], "index")?;
}
let reader = prim.reader(|b| buffers.get(b.index()).map(|d| &d.0[..]));
let reader = primitive.reader(|b| buffers.get(b.index()).map(|d| &d.0[..]));
let positions: Vec<Vec3> = reader.read_positions().ok_or_else(|| malformed(KIND, "unreadable positions"))?.map(Vec3::from).collect();
let n = positions.len();
check_vertices(raw.positions.len().saturating_add(n))?;
@@ -134,64 +137,67 @@ fn add_primitive(raw: &mut RawMesh, attrs: &mut Attrs, prim: &gltf::Primitive, m
if let Some(bad) = indices.iter().find(|i| **i as usize >= n) {
return Err(malformed(KIND, format!("index {bad} out of range ({n} vertices)")));
}
check_triangles(raw.triangle_count(), indices.len() / 3)?;
let normals: Option<Vec<Vec3>> = nacc.and_then(|_| reader.read_normals()).map(|it| it.map(Vec3::from).collect());
let texcoords: Option<Vec<Vec2>> = tacc.and_then(|_| reader.read_tex_coords(0)).map(|t| t.into_f32().map(Vec2::from).collect());
let normals: Option<Vec<Vec3>> = normal_accessor.and_then(|_| reader.read_normals()).map(|it| it.map(Vec3::from).collect());
let texcoords: Option<Vec<Vec2>> = texcoord_accessor.and_then(|_| reader.read_tex_coords(0)).map(|t| t.into_f32().map(Vec2::from).collect());
let colors: Option<Vec<Vec4>> =
cacc.and_then(|_| reader.read_colors(0)).map(|c| c.into_rgba_f32().map(Vec4::from).collect()).filter(|c: &Vec<Vec4>| c.len() == n);
color_accessor.and_then(|_| reader.read_colors(0)).map(|c| c.into_rgba_f32().map(Vec4::from).collect()).filter(|c: &Vec<Vec4>| c.len() == n);
attrs.color_seen |= colors.is_some();
let color_of = |i: usize| colors.as_ref().and_then(|c| c.get(i)).copied().unwrap_or(Vec4::ONE);
let m3 = Mat3::from_mat4(m);
let nm = m3.inverse().transpose();
let flip = m3.determinant() < 0.0;
let world: Vec<Vec3> = positions.iter().map(|p| m.transform_point3(*p)).collect();
let name = match prim.material().index() {
let linear_transform = Mat3::from_mat4(transform);
let normal_transform = linear_transform.inverse().transpose();
let flip = linear_transform.determinant() < 0.0;
let world: Vec<Vec3> = positions.iter().map(|p| transform.transform_point3(*p)).collect();
let name = match primitive.material().index() {
None => "Default".to_string(),
Some(i) => prim.material().name().map(str::to_string).unwrap_or_else(|| format!("Material_{i}")),
Some(i) => primitive.material().name().map(str::to_string).unwrap_or_else(|| format!("Material_{i}")),
};
if !raw.base_colors.iter().any(|c| c.material == name) {
base_color(raw, &prim.material(), &name, buffers);
base_color(raw, &primitive.material(), &name, buffers);
}
let base = raw.positions.len() as u32;
let tex_ok = texcoords.as_ref().is_some_and(|t| t.len() == n);
if tex_ok {
let has_texcoords = texcoords.as_ref().is_some_and(|t| t.len() == n);
if has_texcoords {
attrs.uv_seen.0 = true
} else {
attrs.uv_seen.1 = true
}
let uv_of = |i: usize| texcoords.as_ref().and_then(|t| t.get(i)).copied().unwrap_or_default();
let raw_normals = raw.normals.get_or_insert_with(Vec::new);
match normals.filter(|v| v.len() == n) {
Some(nrm) => {
raw.positions.extend_from_slice(&world);
raw_normals.extend(nrm.iter().map(|v| (nm * *v).try_normalize().unwrap_or(Vec3::Y)));
raw_normals.extend(nrm.iter().map(|v| (normal_transform * *v).try_normalize().unwrap_or(Vec3::Y)));
attrs.uvs.extend((0..n).map(uv_of));
attrs.colors.extend((0..n).map(color_of));
let group = raw.group(&name, part);
for t in indices.chunks_exact(3) {
for t in indices.as_chunks::<3>().0 {
let (a, b, c) = (t[0] + base, t[1] + base, t[2] + base);
group.extend_from_slice(&if flip { [a, c, b] } else { [a, b, c] });
}
}
None => {
// glTF: flat normals when none are given, so every triangle gets its own corners.
let mut tris = Vec::with_capacity(indices.len());
for t in indices.chunks_exact(3) {
// glTF: flat normals when none are given, so every triangle gets its own corners
let mut triangles = Vec::with_capacity(indices.len());
for t in indices.as_chunks::<3>().0 {
let order = if flip { [t[0], t[2], t[1]] } else { [t[0], t[1], t[2]] };
let p = order.map(|i| world.get(i as usize).copied().unwrap_or_default());
let face = (p[1] - p[0]).cross(p[2] - p[0]).try_normalize().unwrap_or(Vec3::Y);
for (k, i) in order.iter().enumerate() {
tris.push(raw.positions.len() as u32);
triangles.push(raw.positions.len() as u32);
raw.positions.push(p[k]);
raw_normals.push(face);
attrs.uvs.push(uv_of(*i as usize));
attrs.colors.push(color_of(*i as usize));
}
}
raw.group(&name, part).extend_from_slice(&tris);
raw.group(&name, part).extend_from_slice(&triangles);
}
}
Ok(())
}
+16 -8
View File
@@ -379,6 +379,7 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec<String>, Option<Vec<Vec2>>)> {
let RawMesh { positions, normals, uvs, colors, groups, warnings, diagonals, .. } = raw;
check_vertices(positions.len())?;
check_triangles(0, groups.iter().map(|(_, _, g)| g.len() / 3).sum())?;
let mut mesh = Mesh { positions, ..Mesh::default() };
let mut groups: Vec<(usize, String, Vec<u32>)> = groups
.into_iter()
@@ -398,22 +399,27 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec<String>, Option<Vec<Vec2>>)> {
mesh.indices.extend_from_slice(tris.get(..count as usize).unwrap_or_default());
mesh.submeshes.push(SubMesh { name, material, start, count });
}
if mesh.indices.is_empty() {
return Err(FormatError::Invalid("the file contains no triangles".into()));
}
if !diagonals.is_empty() {
let diagonal = |a: u32, b: u32| diagonals.contains(&(a.min(b), a.max(b)));
mesh.diagonals = mesh.indices.chunks_exact(3).map(|t| (0..3).map(|i| u8::from(diagonal(t[i], t[(i + 1) % 3])) << i).sum()).collect();
mesh.diagonals = mesh.indices.as_chunks::<3>().0.iter().map(|t| (0..3).map(|i| u8::from(diagonal(t[i], t[(i + 1) % 3])) << i).sum()).collect();
}
if let Some(bad) = mesh.indices.iter().find(|i| **i as usize >= mesh.positions.len()) {
return Err(FormatError::Invalid(format!("vertex index {bad} out of range ({} vertices)", mesh.positions.len())));
}
if mesh.positions.iter().any(|p| !p.is_finite()) {
return Err(FormatError::Invalid("the mesh has non-finite vertex positions".into()));
}
if all_triangles_degenerate(&mesh) {
return Err(FormatError::Invalid("every triangle of the mesh is degenerate (zero area)".into()));
}
mesh.normals = match normals {
Some(n) if n.len() == mesh.positions.len() => n.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(),
_ => smooth_normals(&mesh),
@@ -421,6 +427,7 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec<String>, Option<Vec<Vec2>>)> {
if let Some(c) = colors.filter(|c| c.len() == mesh.positions.len()) {
mesh.colors = c.into_iter().map(|v| if v.is_finite() { v.clamp(Vec4::ZERO, Vec4::ONE) } else { Vec4::ONE }).collect();
}
Ok((mesh, warnings, uvs))
}
@@ -482,18 +489,19 @@ fn orbit_cameras(raw: &[RawCamera], mesh: &Mesh) -> Vec<texturecraft_core::Camer
/// Area-weighted smooth normals over welded positions (UV seams do not split shading).
fn smooth_normals(mesh: &Mesh) -> Vec<Vec3> {
let weld = weld_ids(&mesh.positions);
let mut acc = vec![Vec3::ZERO; mesh.positions.len()];
for t in mesh.indices.chunks_exact(3) {
let welded_vertices = weld_ids(&mesh.positions);
let mut normals = vec![Vec3::ZERO; mesh.positions.len()];
for triangle in mesh.indices.as_chunks::<3>().0 {
let p = |i: u32| mesh.positions.get(i as usize).copied().unwrap_or_default();
let face = (p(t[1]) - p(t[0])).cross(p(t[2]) - p(t[0]));
for v in t {
if let Some(a) = weld.get(*v as usize).and_then(|w| acc.get_mut(*w as usize)) {
let face = (p(triangle[1]) - p(triangle[0])).cross(p(triangle[2]) - p(triangle[0]));
for v in triangle {
if let Some(a) = welded_vertices.get(*v as usize).and_then(|w| normals.get_mut(*w as usize)) {
*a += face;
}
}
}
weld.iter().map(|w| acc.get(*w as usize).and_then(|n| n.try_normalize()).unwrap_or(Vec3::Y)).collect()
welded_vertices.iter().map(|w| normals.get(*w as usize).and_then(|n| n.try_normalize()).unwrap_or(Vec3::Y)).collect()
}
/// Inspects `mesh` and generates its UV report (overlaps, out-of-range UVs, warnings).
+47 -33
View File
@@ -13,8 +13,8 @@ pub(crate) fn read(bytes: &[u8]) -> Result<RawMesh> {
fn read_inner(bytes: &[u8]) -> Result<RawMesh> {
let text = String::from_utf8_lossy(bytes);
// Material names come from `usemtl` (MTL files are never read): tobj only assigns a face's
// material when a library defines it, so every library request gets a synthetic one.
// A synthetic library lets tobj assign usemtl names without reading external MTL files
let mut names: Vec<&str> = Vec::new();
for line in text.lines().map(str::trim) {
if line.split_whitespace().next() == Some("usemtl")
@@ -25,57 +25,68 @@ fn read_inner(bytes: &[u8]) -> Result<RawMesh> {
names.push(name.trim());
}
}
let library: String = names.iter().map(|n| format!("newmtl {n}\n")).collect();
let library: String = names.iter().map(|name| format!("newmtl {name}\n")).collect();
let source = format!("mtllib texturecraft-usemtl.mtl\n{text}");
// Polygons stay whole so the wireframe can show them; `RawMesh::polygon` triangulates.
let opts = tobj::LoadOptions { single_index: true, triangulate: false, ignore_points: true, ignore_lines: true };
// Polygons stay whole so the wireframe can show them; `RawMesh::polygon` triangulates
let options = tobj::LoadOptions { single_index: true, triangulate: false, ignore_points: true, ignore_lines: true };
let (models, materials) =
tobj::load_obj_buf(&mut source.as_bytes(), &opts, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?;
tobj::load_obj_buf(&mut source.as_bytes(), &options, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?;
let materials = materials.unwrap_or_default();
let mut raw = RawMesh::default();
let (mut normals, mut uvs, mut colors) = (Some(Vec::new()), Some(Vec::new()), Vec::new());
let any_uvs = models.iter().any(|m| !m.mesh.indices.is_empty() && m.mesh.texcoords.len() == (m.mesh.positions.len() / 3) * 2);
let (mut normals, mut uvs, mut colors) = (Some(Vec::new()), any_uvs.then(Vec::new), Vec::new());
let mut partial_uvs = false;
for model in &models {
let m = &model.mesh;
let n = m.positions.len() / 3;
check_vertices(raw.positions.len().saturating_add(n))?;
// Corners per face; without arities every face is a triangle.
let arities: Vec<usize> = if m.face_arities.is_empty() { vec![3; m.indices.len() / 3] } else { m.face_arities.iter().map(|a| *a as usize).collect() };
let mesh = &model.mesh;
if mesh.indices.is_empty() {
continue;
}
let vertex_count = mesh.positions.len() / 3;
check_vertices(raw.positions.len().saturating_add(vertex_count))?;
// Corners per face; without arities every face is a triangle
let arities: Vec<usize> =
if mesh.face_arities.is_empty() { vec![3; mesh.indices.len() / 3] } else { mesh.face_arities.iter().map(|a| *a as usize).collect() };
check_triangles(raw.triangle_count(), arities.iter().map(|a| a.saturating_sub(2)).sum())?;
let base = raw.positions.len() as u32;
raw.positions.extend(m.positions.chunks_exact(3).map(|p| Vec3::new(p[0], p[1], p[2])));
if m.normals.len() == n * 3 {
raw.positions.extend(mesh.positions.as_chunks::<3>().0.iter().map(|p| Vec3::new(p[0], p[1], p[2])));
if mesh.normals.len() == vertex_count * 3 {
if let Some(v) = &mut normals {
v.extend(m.normals.chunks_exact(3).map(|p| Vec3::new(p[0], p[1], p[2])));
v.extend(mesh.normals.as_chunks::<3>().0.iter().map(|p| Vec3::new(p[0], p[1], p[2])));
}
} else {
normals = None;
}
if m.texcoords.len() == n * 2 {
if let Some(v) = &mut uvs {
// OBJ UVs have their origin bottom-left.
v.extend(m.texcoords.chunks_exact(2).map(|t| Vec2::new(t[0], 1.0 - t[1])));
if let Some(v) = &mut uvs {
if mesh.texcoords.len() == vertex_count * 2 {
// OBJ UVs have their origin bottom-left
v.extend(mesh.texcoords.as_chunks::<2>().0.iter().map(|t| Vec2::new(t[0], 1.0 - t[1])));
} else {
v.extend(std::iter::repeat_n(Vec2::ZERO, vertex_count));
partial_uvs = true;
}
} else {
partial_uvs |= n > 0 && !m.indices.is_empty();
uvs = None;
}
// `v x y z r g b`: objects without colors are white.
match m.vertex_color.len() == n * 3 {
true => colors.extend(m.vertex_color.chunks_exact(3).map(|c| Vec4::new(c[0], c[1], c[2], 1.0))),
false => colors.extend(std::iter::repeat_n(Vec4::ONE, n)),
// `v x y z r g b`: objects without colors are white
match mesh.vertex_color.len() == vertex_count * 3 {
true => colors.extend(mesh.vertex_color.as_chunks::<3>().0.iter().map(|c| Vec4::new(c[0], c[1], c[2], 1.0))),
false => colors.extend(std::iter::repeat_n(Vec4::ONE, vertex_count)),
}
let name = match m.material_id {
let name = match mesh.material_id {
Some(id) => materials.get(id).map(|mat| mat.name.clone()).filter(|s| !s.is_empty()).unwrap_or_else(|| format!("Material_{id}")),
None => "Default".to_string(),
};
if let Some(i) = m.indices.iter().find(|i| **i as usize >= n) {
if let Some(i) = mesh.indices.iter().find(|i| **i as usize >= vertex_count) {
return Err(malformed(KIND, format!("face index {i} out of range")));
}
// tobj names models without `o`/`g` "unnamed_object"; an empty name takes the file stem.
// tobj names models without `o`/`g` "unnamed_object"; an empty name takes the file stem
let part = if model.name == "unnamed_object" { "" } else { model.name.as_str() };
let (mut rest, mut corners) = (m.indices.as_slice(), Vec::new());
let (mut rest, mut corners) = (mesh.indices.as_slice(), Vec::new());
for arity in arities {
let Some((face, tail)) = rest.split_at_checked(arity) else { break };
rest = tail;
@@ -86,11 +97,14 @@ fn read_inner(bytes: &[u8]) -> Result<RawMesh> {
}
}
}
if partial_uvs && models.iter().any(|m| !m.mesh.texcoords.is_empty()) {
raw.warnings.push("some objects have no UVs; the whole mesh was unwrapped automatically".into());
if partial_uvs {
raw.warnings.push("some objects have no UVs; default UVs were assigned".into());
}
raw.normals = normals;
raw.uvs = uvs;
raw.colors = models.iter().any(|m| !m.mesh.vertex_color.is_empty()).then_some(colors);
raw.colors = models.iter().any(|model| !model.mesh.vertex_color.is_empty()).then_some(colors);
Ok(raw)
}
+27
View File
@@ -235,6 +235,33 @@ fn obj_without_uvs_or_normals_is_completed() {
assert!(n0.len() > 1 && n0.iter().all(|n| (*n - n0[0]).length() < 1e-5));
}
#[test]
fn obj_with_some_objects_having_uvs_preserves_uvs_without_full_unwrap() {
let obj = "o Body
v 0 0 0
v 1 0 0
v 1 1 0
vt 0 0
vt 1 0
vt 1 1
f 1/1 2/2 3/3
o Helper
v 2 0 0
v 3 0 0
v 3 1 0
f 4 5 6
";
let im = import_mesh_bytes("character.obj", obj.as_bytes()).unwrap();
assert!(!im.report.uvs_generated);
assert_eq!(im.mesh.uvs[0], Vec2::new(0.0, 1.0));
assert_eq!(im.mesh.uvs[1], Vec2::new(1.0, 1.0));
assert_eq!(im.mesh.uvs[2], Vec2::new(1.0, 0.0));
assert_eq!(im.mesh.uvs[3], Vec2::ZERO);
assert_eq!(im.mesh.uvs[4], Vec2::ZERO);
assert_eq!(im.mesh.uvs[5], Vec2::ZERO);
assert!(im.report.warnings.iter().any(|w| w.contains("some objects have no UVs")));
}
#[test]
fn polygons_keep_their_edges_for_the_wireframe() {
// An OBJ quad and pentagon (with UVs, so no unwrap splits them), a triangle, and a PLY quad.
+12 -10
View File
@@ -134,7 +134,7 @@ fn is_quat(t: u8) -> bool {
/// Quaternions are stored imaginary first; values keep USD's text order (real first).
fn quat_order(t: u8, v: &mut [f64]) {
if is_quat(t) {
for q in v.chunks_exact_mut(4) {
for q in v.as_chunks_mut::<4>().0 {
q.rotate_right(1);
}
}
@@ -224,17 +224,19 @@ impl<'a> Crate<'a> {
Ok(())
}
fn read_fields(&mut self, mut s: Cur, budget: &mut Budget) -> Result<()> {
let n = s.count(0)?;
let tokens = s.ints(n, 4, budget)?;
let size = s.u64()?;
let comp = s.bytes(usize::try_from(size).map_err(|_| truncated())?)?;
budget.take(n.saturating_mul(24))?;
let reps = codec::decompress(comp, n.saturating_mul(8))?;
if reps.len() != n * 8 {
fn read_fields(&mut self, mut section: Cur, budget: &mut Budget) -> Result<()> {
let count = section.count(0)?;
let tokens = section.ints(count, 4, budget)?;
let size = section.u64()?;
let compressed = section.bytes(usize::try_from(size).map_err(|_| truncated())?)?;
budget.take(count.saturating_mul(24))?;
let representations = codec::decompress(compressed, count.saturating_mul(8))?;
if representations.len() != count * 8 {
return Err(malformed(KIND, "field values are truncated"));
}
self.fields = tokens.iter().zip(reps.chunks_exact(8)).map(|(t, r)| (*t as u32, u64::from_le_bytes(r.try_into().unwrap_or_default()))).collect();
self.fields = tokens.iter().zip(representations.as_chunks::<8>().0.iter()).map(|(t, r)| (*t as u32, u64::from_le_bytes(*r))).collect();
Ok(())
}
+294
View File
@@ -0,0 +1,294 @@
//! Writing the zip entries of a project file.
//!
//! Compressing the baked maps dominates a save (deflate level 6 over gigabytes of `f32`), and every
//! entry is independent, so on native targets the entries are compressed on several threads. Each
//! worker builds a one-entry zip in memory with the same options the serial writer uses; the writing
//! thread copies those entries into the real file in the original order with
//! [`ZipWriter::raw_copy_file`]. The compressed bytes of every entry and the entry order are
//! therefore the same as in a serial save.
//!
//! Workers share an estimated byte budget for entries started but not yet written. Stored entries
//! and entries larger than that budget stream directly into the destination, without a whole-entry
//! buffer. The estimate excludes allocator and compressor overhead; it is not a process memory cap.
use std::io::{Seek, Write};
use zip::ZipWriter;
use zip::write::SimpleFileOptions;
use super::zip_err;
use crate::Result;
/// Produces the uncompressed bytes of one entry into the zip writer.
pub(super) type Body<'a> = Box<dyn FnOnce(&mut dyn Write) -> std::io::Result<()> + Send + 'a>;
pub(super) struct Entry<'a> {
pub name: String,
pub options: SimpleFileOptions,
/// Estimated entry size in bytes, based on its uncompressed payload.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub weight: u64,
pub body: Body<'a>,
}
/// How much of the machine a save may use. Native targets only; the browser saves on one thread.
#[cfg(not(target_arch = "wasm32"))]
mod limits {
use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering};
/// Cores a save leaves to the UI (an autosave runs while the user keeps painting).
static RESERVED_CORES: AtomicUsize = AtomicUsize::new(DEFAULT_RESERVED_CORES);
/// Share of the available RAM, in percent, that entries in flight may hold.
static RAM_PERCENT: AtomicU8 = AtomicU8::new(DEFAULT_RAM_PERCENT);
pub const DEFAULT_RESERVED_CORES: usize = 1;
pub const DEFAULT_RAM_PERCENT: u8 = 50;
pub fn set(reserved_cores: usize, ram_percent: u8) {
RESERVED_CORES.store(reserved_cores, Ordering::Relaxed);
RAM_PERCENT.store(ram_percent.clamp(1, 100), Ordering::Relaxed);
}
pub fn get() -> (usize, u8) {
(RESERVED_CORES.load(Ordering::Relaxed), RAM_PERCENT.load(Ordering::Relaxed))
}
/// RAM the system can give out now, in bytes (the total when the system does not say it; 8 GiB
/// when the system tells nothing).
pub fn available_ram() -> u64 {
let Ok(mut sys) = sysinfo::System::new() else { return 8 << 30 };
sys.refresh_memory();
match sys.available_memory() {
0 => sys.total_memory(),
n => n,
}
}
}
#[cfg(not(target_arch = "wasm32"))]
pub use limits::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES};
/// Set what saves may use: cores left to the UI (any number; at least one worker always runs) and
/// the percentage (1 to 100) of available RAM used as the estimated in-flight entry budget.
#[cfg(not(target_arch = "wasm32"))]
pub fn set_save_resources(reserved_cores: usize, ram_percent: u8) {
limits::set(reserved_cores, ram_percent);
}
/// Logical CPUs and currently available RAM in bytes, using the same readings as project saves.
#[cfg(not(target_arch = "wasm32"))]
pub fn available_save_resources() -> (usize, u64) {
let cores = std::thread::available_parallelism().map_or(1, usize::from);
(cores, limits::available_ram())
}
/// Estimated in-flight entry budget, shared by the save planner and the Settings readout.
#[cfg(not(target_arch = "wasm32"))]
pub fn save_ram_budget(available_ram_bytes: u64, ram_percent: u8) -> u64 {
u64::try_from(u128::from(available_ram_bytes) * u128::from(ram_percent.clamp(1, 100)) / 100).unwrap_or(u64::MAX)
}
/// Worker threads and in-flight byte budget for a save of `entries` entries.
#[cfg(not(target_arch = "wasm32"))]
pub(super) fn plan(cpus: usize, reserved_cores: usize, entries: usize, available_ram: u64, ram_percent: u8) -> (usize, u64) {
let workers = cpus.saturating_sub(reserved_cores).max(1).min(entries);
(workers, save_ram_budget(available_ram, ram_percent))
}
/// Write `entries` in order: in parallel where threads exist, else one after the other.
pub(super) fn write_entries<W: Write + Seek>(zip: &mut ZipWriter<W>, entries: Vec<Entry<'_>>) -> Result<()> {
#[cfg(not(target_arch = "wasm32"))]
{
let (cores, available_ram_bytes) = available_save_resources();
let (reserved_cores, ram_percent) = limits::get();
let (workers, budget) = plan(cores, reserved_cores, entries.len(), available_ram_bytes, ram_percent);
if workers > 1 {
return parallel::write(zip, entries, workers, budget);
}
}
write_serial(zip, entries)
}
/// One entry after the other straight into `zip`.
pub(super) fn write_serial<W: Write + Seek>(zip: &mut ZipWriter<W>, entries: Vec<Entry<'_>>) -> Result<()> {
for e in entries {
zip.start_file(e.name, e.options).map_err(zip_err)?;
(e.body)(zip)?;
}
Ok(())
}
#[cfg(not(target_arch = "wasm32"))]
pub(super) mod parallel {
use std::collections::BTreeMap;
use std::io::{Cursor, Seek, Write};
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::{Condvar, Mutex, MutexGuard};
use zip::{CompressionMethod, ZipArchive, ZipWriter};
use super::Entry;
use crate::project_file::zip_err;
use crate::{FormatError, Result};
struct State {
/// Next entry to start.
next: usize,
/// Estimated bytes of the entries started and not yet written.
in_flight: u64,
/// Finished entries (one-entry zips) waiting for their turn.
ready: BTreeMap<usize, Result<Vec<u8>>>,
/// The writer failed: start nothing more.
stop: bool,
}
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
}
fn wait<'a>(cv: &Condvar, g: MutexGuard<'a, State>) -> MutexGuard<'a, State> {
cv.wait(g).unwrap_or_else(|e| e.into_inner())
}
/// Compress one entry into a zip of its own.
fn compress(e: Entry<'_>) -> Result<Vec<u8>> {
let mut z = ZipWriter::new(Cursor::new(Vec::new()));
z.start_file(e.name, e.options).map_err(zip_err)?;
(e.body)(&mut z)?;
Ok(z.finish().map_err(zip_err)?.into_inner())
}
fn worker(slots: &[Mutex<Option<Entry<'_>>>], weights: &[u64], budget: u64, state: &Mutex<State>, cv: &Condvar) {
loop {
let entry_index = {
let mut state_guard = lock(state);
loop {
if state_guard.stop || state_guard.next >= slots.len() {
return;
}
let weight = weights.get(state_guard.next).copied().unwrap_or(0);
// Oversized entries stream separately, so every queued weight fits the budget
if state_guard.in_flight <= budget.saturating_sub(weight) {
let entry_index = state_guard.next;
state_guard.next += 1;
state_guard.in_flight = state_guard.in_flight.saturating_add(weight);
break entry_index;
}
state_guard = wait(cv, state_guard);
}
};
let entry = slots.get(entry_index).and_then(|slot| lock(slot).take());
let result = match entry {
Some(entry) => catch_unwind(AssertUnwindSafe(|| compress(entry)))
.unwrap_or_else(|_| Err(FormatError::Invalid("compressing a project entry failed".into()))),
None => Err(FormatError::Invalid("project entry missing".into())),
};
lock(state).ready.insert(entry_index, result);
cv.notify_all();
}
}
/// Copy the compressed entry of a one-entry zip into `zip` without recompressing.
fn copy_entry<W: Write + Seek>(zip: &mut ZipWriter<W>, bytes: Vec<u8>) -> Result<()> {
let mut a = ZipArchive::new(Cursor::new(bytes)).map_err(zip_err)?;
let f = a.by_index_raw(0).map_err(zip_err)?;
zip.raw_copy_file(f).map_err(zip_err)
}
fn streams_directly(entry: &Entry<'_>, budget: u64) -> bool {
let stored_options = entry.options.compression_method(CompressionMethod::Stored);
entry.options == stored_options || entry.weight > budget
}
pub(in crate::project_file) fn write<W: Write + Seek>(zip: &mut ZipWriter<W>, entries: Vec<Entry<'_>>, workers: usize, budget: u64) -> Result<()> {
if workers == 0 {
return super::write_serial(zip, entries);
}
let mut remaining = entries.into_iter().peekable();
while let Some(entry) = remaining.next() {
// Storing bytes gains nothing from a worker; oversized entries must not get a whole-entry buffer
if streams_directly(&entry, budget) {
zip.start_file(entry.name, entry.options).map_err(zip_err)?;
(entry.body)(zip)?;
continue;
}
let mut batch = vec![entry];
while remaining.peek().is_some_and(|entry| !streams_directly(entry, budget)) {
if let Some(entry) = remaining.next() {
batch.push(entry);
}
}
// Finish the workers before direct compression, keeping the CPU allowance shared
write_buffered(zip, batch, workers, budget)?;
}
Ok(())
}
fn write_buffered<W: Write + Seek>(zip: &mut ZipWriter<W>, entries: Vec<Entry<'_>>, workers: usize, budget: u64) -> Result<()> {
if entries.len() == 1 {
return super::write_serial(zip, entries);
}
let weights: Vec<u64> = entries.iter().map(|entry| entry.weight).collect();
let slots: Vec<Mutex<Option<Entry<'_>>>> = entries.into_iter().map(|entry| Mutex::new(Some(entry))).collect();
let state = Mutex::new(State { next: 0, in_flight: 0, ready: BTreeMap::new(), stop: false });
let cv = Condvar::new();
std::thread::scope(|scope| {
let mut started = 0;
for _ in 0..workers.min(slots.len()) {
// If thread creation fails, the workers already started drain the queue
if std::thread::Builder::new().spawn_scoped(scope, || worker(&slots, &weights, budget, &state, &cv)).is_ok() {
started += 1;
}
}
let result = (|| -> Result<()> {
for (entry_index, weight) in weights.iter().enumerate() {
if started == 0 {
// If no workers started, stream directly into the destination
let entry =
slots.get(entry_index).and_then(|slot| lock(slot).take()).ok_or_else(|| FormatError::Invalid("project entry missing".into()))?;
zip.start_file(entry.name, entry.options).map_err(zip_err)?;
(entry.body)(zip)?;
continue;
}
let done = {
let mut state_guard = lock(&state);
loop {
if let Some(result) = state_guard.ready.remove(&entry_index) {
break result;
}
state_guard = wait(&cv, state_guard);
}
};
let copied = done.and_then(|bytes| copy_entry(zip, bytes));
// Release the entry's share only once its bytes are gone
{
let mut state_guard = lock(&state);
state_guard.in_flight = state_guard.in_flight.saturating_sub(*weight);
}
cv.notify_all();
copied?;
}
Ok(())
})();
if result.is_err() {
lock(&state).stop = true;
cv.notify_all();
}
result
})
}
}
@@ -0,0 +1,68 @@
/// Decompressed bytes accepted by one project load, fixed when the load starts.
pub(super) struct LoadBudget {
limit_bytes: u64,
used_bytes: u64,
}
impl LoadBudget {
pub(super) fn new(limit_bytes: u64) -> Self {
Self { limit_bytes, used_bytes: 0 }
}
pub(super) fn remaining(&self) -> u64 {
self.limit_bytes - self.used_bytes
}
/// Reserve bytes before retaining decoded data so entries share one allocation budget.
pub(super) fn take(&mut self, bytes: u64) -> Result<(), String> {
if bytes > self.remaining() {
return Err(format!(
"project file decompresses to more than {} bytes ({:.2} GiB); increase Max project size on open in Settings > Project to open larger files",
self.limit_bytes,
self.limit_bytes as f64 / (1u64 << 30) as f64,
));
}
self.used_bytes += bytes;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::LoadBudget;
#[test]
fn entries_share_the_limit_and_the_exact_boundary_is_allowed() {
let mut budget = LoadBudget::new(10);
budget.take(4).unwrap();
budget.take(6).unwrap();
let error = budget.take(1).unwrap_err();
assert_eq!(budget.remaining(), 0);
assert!(error.contains("10 bytes"), "{error}");
assert!(error.contains("Settings > Project"), "{error}");
}
#[test]
fn a_rejected_entry_does_not_consume_the_remaining_budget() {
let mut budget = LoadBudget::new(10);
budget.take(4).unwrap();
assert!(budget.take(7).is_err());
assert_eq!(budget.remaining(), 6);
assert!(budget.take(6).is_ok());
}
#[test]
fn accounting_cannot_wrap_at_the_integer_boundary() {
let mut budget = LoadBudget::new(u64::MAX);
budget.take(u64::MAX).unwrap();
assert!(budget.take(1).is_err());
assert!(budget.take(0).is_ok());
assert_eq!(budget.remaining(), 0);
}
}
@@ -0,0 +1,81 @@
use std::cell::Cell;
use std::io::{self, Read, Seek, SeekFrom};
/// Restrict ZIP indexing to a bounded tail and read allowance before enabling payload access.
pub(super) struct MetadataReader<'a, R> {
reader: R,
metadata_only: &'a Cell<bool>,
metadata_start: u64,
remaining_bytes: u64,
position: u64,
}
impl<'a, R: Read + Seek> MetadataReader<'a, R> {
pub(super) fn new(mut reader: R, metadata_only: &'a Cell<bool>, metadata_bytes: u64) -> io::Result<Self> {
let end = reader.seek(SeekFrom::End(0))?;
Ok(Self { reader, metadata_only, metadata_start: end.saturating_sub(metadata_bytes), remaining_bytes: metadata_bytes.saturating_mul(2), position: end })
}
}
impl<R: Read> Read for MetadataReader<'_, R> {
fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
if bytes.is_empty() {
return Ok(0);
}
let metadata_only = self.metadata_only.get();
if metadata_only && (self.position < self.metadata_start || self.remaining_bytes == 0) {
return Err(io::Error::new(io::ErrorKind::InvalidData, "project ZIP metadata exceeds the indexing limit"));
}
let length = if metadata_only { bytes.len().min(usize::try_from(self.remaining_bytes).unwrap_or(usize::MAX)) } else { bytes.len() };
let read = self.reader.read(bytes.get_mut(..length).unwrap_or_default())?;
self.position = self.position.saturating_add(read as u64);
if metadata_only {
self.remaining_bytes -= read as u64;
}
Ok(read)
}
}
impl<R: Seek> Seek for MetadataReader<'_, R> {
fn seek(&mut self, position: SeekFrom) -> io::Result<u64> {
self.position = self.reader.seek(position)?;
Ok(self.position)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
#[test]
fn indexing_cannot_read_payloads_outside_the_metadata_window() {
let metadata_only = Cell::new(true);
let mut reader = MetadataReader::new(Cursor::new(vec![7; 100]), &metadata_only, 8).unwrap();
reader.seek(SeekFrom::Start(91)).unwrap();
assert!(reader.read(&mut [0; 1]).is_err());
reader.seek(SeekFrom::Start(92)).unwrap();
reader.read_exact(&mut [0; 8]).unwrap();
metadata_only.set(false);
reader.seek(SeekFrom::Start(0)).unwrap();
reader.read_exact(&mut [0; 100]).unwrap();
}
#[test]
fn repeated_metadata_scans_share_one_read_allowance() {
let metadata_only = Cell::new(true);
let mut reader = MetadataReader::new(Cursor::new(vec![7; 8]), &metadata_only, 8).unwrap();
for _ in 0..2 {
reader.seek(SeekFrom::Start(0)).unwrap();
reader.read_exact(&mut [0; 8]).unwrap();
}
reader.seek(SeekFrom::Start(0)).unwrap();
assert!(reader.read(&mut [0; 1]).is_err());
}
}
+185 -75
View File
@@ -18,6 +18,7 @@
//! count of 0, followed by `width × height × components` f32 LE. Pixels of a UV-tiled texture
//! set cover its whole atlas (`resolution` per tile, see `TileGrid`).
use std::cell::Cell;
use std::collections::{BTreeMap, HashSet};
use std::io::{Cursor, Read, Seek, Write};
use std::sync::Arc;
@@ -28,18 +29,30 @@ use texturecraft_texel::{TILE_AREA, TileImage};
use zip::write::SimpleFileOptions;
use zip::{CompressionMethod, ZipArchive, ZipWriter};
use self::entries::Entry;
use self::load_budget::LoadBudget;
use self::metadata_reader::MetadataReader;
use crate::{FormatError, MAX_IMAGE_SIZE, Result, malformed};
mod entries;
mod load_budget;
mod metadata_reader;
mod project_open_limit;
#[cfg(not(target_arch = "wasm32"))]
pub use entries::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_resources, save_ram_budget, set_save_resources};
pub use project_open_limit::{DEFAULT_PROJECT_OPEN_LIMIT_GIB, project_open_limit_gib, set_project_open_limit_gib};
const KIND: &str = "project file";
const MAGIC: &[u8; 4] = b"TCTX";
/// Version of the `.bin` layout.
const BIN_VERSION: u32 = 1;
const BIN_HEADER_BYTES: usize = 24;
const MAX_JSON: u64 = 256 << 20;
const MAX_THUMBNAIL: u64 = 64 << 20;
const MAX_RESOURCE: u64 = 512 << 20;
const MAX_ENTRIES: usize = 100_000;
/// Total decompressed bytes accepted from one project file (zip-bomb guard).
const MAX_TOTAL: u64 = 8 << 30;
/// Bound ZIP index parsing before the archive exposes its entry count.
const MAX_ZIP_METADATA_BYTES: u64 = 32 << 20;
/// Largest image (texels) of a texture set or baked map: UV-tiled sets hold several tiles.
const MAX_TEXELS: u64 = 1 << 28;
@@ -156,21 +169,42 @@ fn unique_entry_name(dir: &str, name: &str, used: &mut HashSet<String>) -> Strin
entry
}
fn write_project<W: Write + Seek>(out: W, pf: &ProjectFile) -> Result<()> {
let mut zip = ZipWriter::new(out);
/// Floats converted to bytes at a time when a baked map streams into the compressor.
const BAKED_CHUNK: usize = 1 << 16;
fn write_baked(w: &mut dyn Write, res: u32, h: u32, comps: usize, data: &[f32]) -> std::io::Result<()> {
w.write_all(&header(res, h, comps, 0))?;
let mut buf = Vec::with_capacity(BAKED_CHUNK * 4);
for chunk in data.chunks(BAKED_CHUNK) {
buf.clear();
buf.extend(chunk.iter().flat_map(|v| v.to_le_bytes()));
w.write_all(&buf)?;
}
Ok(())
}
/// The zip entries of a project file, in file order. Bodies run later, possibly on other threads.
fn entries(pf: &ProjectFile) -> Result<Vec<Entry<'_>>> {
let deflate = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated).large_file(true);
let stored = SimpleFileOptions::default().compression_method(CompressionMethod::Stored);
let json = serde_json::to_vec_pretty(&pf.project).map_err(|e| FormatError::Invalid(e.to_string()))?;
zip.start_file("project.json", deflate).map_err(zip_err)?;
zip.write_all(&json)?;
let mut out = vec![Entry { name: "project.json".into(), options: deflate, weight: json.len() as u64, body: Box::new(move |w| w.write_all(&json)) }];
if let Some((ext, bytes)) = &pf.mesh {
zip.start_file(format!("mesh.{}", sanitize_ext(ext)), deflate).map_err(zip_err)?;
zip.write_all(bytes)?;
out.push(Entry {
name: format!("mesh.{}", sanitize_ext(ext)),
options: deflate,
weight: bytes.len() as u64,
body: Box::new(move |w| w.write_all(bytes)),
});
}
let mut used = HashSet::new();
for (dir, (name, bytes)) in pf.high_poly.iter().map(|m| ("highpoly", m)).chain(pf.cage.iter().map(|m| ("cage", m))) {
zip.start_file(unique_entry_name(dir, name, &mut used), deflate).map_err(zip_err)?;
zip.write_all(bytes)?;
out.push(Entry {
name: unique_entry_name(dir, name, &mut used),
options: deflate,
weight: bytes.len() as u64,
body: Box::new(move |w| w.write_all(bytes)),
});
}
for ((texture_set, target), map) in &pf.bake_paint {
if map.width == 0 || map.height == 0 || map.values.len() as u64 != u64::from(map.width) * u64::from(map.height) {
@@ -180,23 +214,29 @@ fn write_project<W: Write + Seek>(out: W, pf: &ProjectFile) -> Result<()> {
BakePaintTarget::Cage => "cage",
BakePaintTarget::Skew => "skew",
};
zip.start_file(format!("bake_paint/{texture_set}_{target_name}.bin"), deflate).map_err(zip_err)?;
zip.write_all(&header(map.width, map.height, 1, 0))?;
for value in &map.values {
zip.write_all(&value.to_le_bytes())?;
}
out.push(Entry {
name: format!("bake_paint/{texture_set}_{target_name}.bin"),
options: deflate,
weight: map.values.len() as u64 * 4,
body: Box::new(move |w| write_baked(w, map.width, map.height, 1, &map.values)),
});
}
let mut layers: Vec<_> = pf.pixels.layers.iter().collect();
layers.sort_by_key(|(k, _)| **k);
for ((id, c), img) in layers {
zip.start_file(format!("pixels/layer_{}_{}.bin", id.0, c.id()), deflate).map_err(zip_err)?;
write_tiles(&mut zip, img)?;
let weight = (img.allocated_count() * (TILE_AREA * img.comps() * 2 + 8)) as u64;
out.push(Entry {
name: format!("pixels/layer_{}_{}.bin", id.0, c.id()),
options: deflate,
weight,
body: Box::new(move |mut w| write_tiles(&mut w, img)),
});
}
let mut masks: Vec<_> = pf.pixels.masks.iter().collect();
masks.sort_by_key(|(k, _)| **k);
for (id, img) in masks {
zip.start_file(format!("pixels/mask_{}.bin", id.0), deflate).map_err(zip_err)?;
write_tiles(&mut zip, img)?;
let weight = (img.allocated_count() * (TILE_AREA * img.comps() * 2 + 8)) as u64;
out.push(Entry { name: format!("pixels/mask_{}.bin", id.0), options: deflate, weight, body: Box::new(move |mut w| write_tiles(&mut w, img)) });
}
for (ts, maps) in &pf.baked {
let r = maps.resolution;
@@ -206,21 +246,33 @@ fn write_project<W: Write + Seek>(out: W, pf: &ProjectFile) -> Result<()> {
if h == 0 || data.len() != (r as usize) * (h as usize) * m.components() {
continue;
}
zip.start_file(format!("baked/{ts}_{}.bin", m.id()), deflate).map_err(zip_err)?;
zip.write_all(&header(r, h, m.components(), 0))?;
let bytes: Vec<u8> = data.iter().flat_map(|v| v.to_le_bytes()).collect();
zip.write_all(&bytes)?;
let comps = m.components();
out.push(Entry {
name: format!("baked/{ts}_{}.bin", m.id()),
options: deflate,
weight: data.len() as u64 * 4,
body: Box::new(move |w| write_baked(w, r, h, comps, data)),
});
}
}
if let Some(png) = &pf.thumbnail {
zip.start_file("thumbnail.png", stored).map_err(zip_err)?;
zip.write_all(png)?;
out.push(Entry { name: "thumbnail.png".into(), options: stored, weight: png.len() as u64, body: Box::new(move |w| w.write_all(png)) });
}
used.clear();
for (name, bytes) in &pf.resources {
zip.start_file(unique_entry_name("resources", name, &mut used), stored).map_err(zip_err)?;
zip.write_all(bytes)?;
out.push(Entry {
name: unique_entry_name("resources", name, &mut used),
options: stored,
weight: bytes.len() as u64,
body: Box::new(move |w| w.write_all(bytes)),
});
}
Ok(out)
}
fn write_project<W: Write + Seek>(out: W, pf: &ProjectFile) -> Result<()> {
let mut zip = ZipWriter::new(out);
entries::write_entries(&mut zip, entries(pf)?)?;
zip.finish().map_err(zip_err)?;
Ok(())
}
@@ -238,29 +290,37 @@ pub fn load_project(path: &std::path::Path) -> Result<ProjectFile> {
crate::guard(KIND, || load(std::io::BufReader::new(file)))
}
/// Counts decompressed bytes against [`MAX_TOTAL`].
struct Budget(u64);
impl Budget {
fn take(&mut self, n: u64) -> Result<()> {
self.0 = self.0.saturating_add(n);
if self.0 > MAX_TOTAL {
return Err(FormatError::TooLarge(format!("project file decompresses to more than {MAX_TOTAL} bytes")));
}
Ok(())
}
}
fn read_all(r: &mut impl Read, cap: u64, budget: &mut Budget, what: &str) -> Result<Vec<u8>> {
fn read_all(reader: &mut impl Read, cap: u64, budget: &mut LoadBudget, what: &str) -> Result<Vec<u8>> {
let mut out = Vec::new();
r.take(cap.saturating_add(1)).read_to_end(&mut out).map_err(|e| malformed(KIND, format!("{what}: {e}")))?;
// Read at most one byte beyond either limit to detect overflow without a full entry allocation
let read_limit = cap.min(budget.remaining()).saturating_add(1);
reader.take(read_limit).read_to_end(&mut out).map_err(|e| malformed(KIND, format!("{what}: {e}")))?;
if out.len() as u64 > cap {
return Err(FormatError::TooLarge(format!("{what} is larger than {cap} bytes")));
}
budget.take(out.len() as u64)?;
budget.take(out.len() as u64).map_err(FormatError::TooLarge)?;
Ok(out)
}
/// Decode bounded chunks so a false header cannot allocate an entire missing map.
fn read_f32s(reader: &mut impl Read, count: usize, what: &str) -> Result<Vec<f32>> {
let mut values = Vec::new();
let mut bytes = vec![0u8; BAKED_CHUNK.min(count) * 4];
let mut remaining = count;
while remaining > 0 {
let chunk_values = BAKED_CHUNK.min(remaining);
let chunk = bytes.get_mut(..chunk_values * 4).ok_or_else(|| malformed(KIND, format!("{what}: invalid float chunk")))?;
read_exact(reader, chunk, what)?;
values.try_reserve(chunk_values).map_err(|_| FormatError::TooLarge(format!("{what}: not enough memory for {count} values")))?;
values.extend(chunk.as_chunks::<4>().0.iter().map(|bytes| f32::from_le_bytes(*bytes)));
remaining -= chunk_values;
}
Ok(values)
}
fn read_exact(r: &mut impl Read, buf: &mut [u8], what: &str) -> Result<()> {
r.read_exact(buf).map_err(|e| malformed(KIND, format!("{what}: {e}")))
}
@@ -271,7 +331,7 @@ fn u32_at(b: &[u8], i: usize) -> u32 {
/// Read and check a `.bin` header: returns (width, height, comps, count).
fn read_header(r: &mut impl Read, what: &str) -> Result<(u32, u32, usize, usize)> {
let mut h = [0u8; 24];
let mut h = [0u8; BIN_HEADER_BYTES];
read_exact(r, &mut h, what)?;
if h.get(..4) != Some(MAGIC.as_slice()) {
return Err(malformed(KIND, format!("{what}: bad magic")));
@@ -293,44 +353,61 @@ fn expect_end(r: &mut impl Read, what: &str) -> Result<()> {
}
}
fn read_tiles(r: &mut impl Read, size: (u32, u32), comps: usize, budget: &mut Budget, what: &str) -> Result<TileImage> {
let (w, h, c, count) = read_header(r, what)?;
if (w, h) != size || c != comps {
return Err(malformed(KIND, format!("{what}: {w}×{h}×{c} does not match the texture set ({}×{}×{comps})", size.0, size.1)));
fn read_tiles(reader: &mut impl Read, size: (u32, u32), components: usize, budget: &mut LoadBudget, what: &str) -> Result<TileImage> {
budget.take(BIN_HEADER_BYTES as u64).map_err(FormatError::TooLarge)?;
let (width, height, stored_components, count) = read_header(reader, what)?;
if (width, height) != size || stored_components != components {
return Err(malformed(
KIND,
format!("{what}: {width}×{height}×{stored_components} does not match the texture set ({}×{}×{components})", size.0, size.1),
));
}
let mut img = TileImage::new(w, h, comps);
if count > (img.tiles_x() as usize) * (img.tiles_y() as usize) {
let mut image = TileImage::new(width, height, components);
if count > (image.tiles_x() as usize) * (image.tiles_y() as usize) {
return Err(malformed(KIND, format!("{what}: {count} tiles is more than the image holds")));
}
let mut buf = vec![0u8; TILE_AREA * comps * 2];
let mut pos = [0u8; 8];
let mut bytes = vec![0u8; TILE_AREA * components * 2];
let mut position_bytes = [0u8; 8];
for _ in 0..count {
read_exact(r, &mut pos, what)?;
let (tx, ty) = (u32_at(&pos, 0), u32_at(&pos, 1));
if tx >= img.tiles_x() || ty >= img.tiles_y() || img.is_allocated(tx, ty) {
budget.take((position_bytes.len() + bytes.len()) as u64).map_err(FormatError::TooLarge)?;
read_exact(reader, &mut position_bytes, what)?;
let (tx, ty) = (u32_at(&position_bytes, 0), u32_at(&position_bytes, 1));
if tx >= image.tiles_x() || ty >= image.tiles_y() || image.is_allocated(tx, ty) {
return Err(malformed(KIND, format!("{what}: bad or repeated tile ({tx}, {ty})")));
}
read_exact(r, &mut buf, what)?;
budget.take(buf.len() as u64)?;
let data: Vec<u16> = buf.chunks_exact(2).map(|b| u16::from_le_bytes([b[0], b[1]])).collect();
img.set_tile(tx, ty, Some(Arc::new(data)));
read_exact(reader, &mut bytes, what)?;
let data: Vec<u16> = bytes.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b)).collect();
image.set_tile(tx, ty, Some(Arc::new(data)));
}
expect_end(r, what)?;
Ok(img)
expect_end(reader, what)?;
Ok(image)
}
/// A baked map: (width, height, data).
fn read_baked(r: &mut impl Read, comps: usize, budget: &mut Budget, what: &str) -> Result<(u32, u32, Vec<f32>)> {
let (w, h, c, _) = read_header(r, what)?;
if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_TEXELS || c != comps {
return Err(malformed(KIND, format!("{what}: bad size {w}×{h}×{c}")));
fn read_baked(reader: &mut impl Read, declared_bytes: u64, components: usize, budget: &mut LoadBudget, what: &str) -> Result<(u32, u32, Vec<f32>)> {
budget.take(BIN_HEADER_BYTES as u64).map_err(FormatError::TooLarge)?;
let (width, height, stored_components, _) = read_header(reader, what)?;
if width == 0 || height == 0 || u64::from(width) * u64::from(height) > MAX_TEXELS || stored_components != components {
return Err(malformed(KIND, format!("{what}: bad size {width}×{height}×{stored_components}")));
}
let len = (w as usize) * (h as usize) * comps;
budget.take(len as u64 * 4)?;
let mut bytes = vec![0u8; len * 4];
read_exact(r, &mut bytes, what)?;
expect_end(r, what)?;
Ok((w, h, bytes.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()))
let value_count = u64::from(width) * u64::from(height) * components as u64;
let payload_bytes = value_count * 4;
if declared_bytes != BIN_HEADER_BYTES as u64 + payload_bytes {
return Err(malformed(KIND, format!("{what}: {declared_bytes} bytes for a {width}×{height}×{components} map")));
}
budget.take(payload_bytes).map_err(FormatError::TooLarge)?;
let value_count = usize::try_from(value_count).map_err(|_| FormatError::TooLarge(format!("{what}: too many values for this platform")))?;
let data = read_f32s(reader, value_count, what)?;
expect_end(reader, what)?;
Ok((width, height, data))
}
/// Texture set holding a paint layer, a content effect or a mask effect id.
@@ -340,12 +417,44 @@ fn texture_set_of(project: &Project, id: LayerId) -> Option<usize> {
}
fn load<R: Read + Seek>(reader: R) -> Result<ProjectFile> {
let mut zip = ZipArchive::new(reader).map_err(zip_err)?;
let limit_bytes = u64::from(project_open_limit_gib()) << 30;
load_with_budget(reader, LoadBudget::new(limit_bytes))
}
fn check_archive<R: Read + Seek>(zip: &mut ZipArchive<R>, limit_bytes: u64) -> Result<()> {
if zip.len() > MAX_ENTRIES {
return Err(FormatError::TooLarge(format!("project file has more than {MAX_ENTRIES} entries")));
}
let mut budget = Budget(0);
// Count every declared payload, including ignored entries, before any decompression
let mut declared_budget = LoadBudget::new(limit_bytes);
for index in 0..zip.len() {
let entry = zip.by_index_raw(index).map_err(zip_err)?;
declared_budget.take(entry.size()).map_err(FormatError::TooLarge)?;
}
// Shared compressed ranges can amplify one payload into many apparent files
if zip.has_overlapping_entries().map_err(zip_err)? {
return Err(malformed(KIND, "overlapping ZIP entries are not supported"));
}
Ok(())
}
fn open_archive<'a, R: Read + Seek>(reader: R, metadata_only: &'a Cell<bool>, metadata_bytes: u64) -> Result<ZipArchive<MetadataReader<'a, R>>> {
let reader = MetadataReader::new(reader, metadata_only, metadata_bytes)?;
// Project archives start at byte zero; avoid scanning payloads to guess an embedded ZIP offset
let config = zip::read::Config { archive_offset: zip::read::ArchiveOffset::Known(0) };
let archive = ZipArchive::with_config(config, reader).map_err(zip_err)?;
metadata_only.set(false);
Ok(archive)
}
fn load_with_budget<R: Read + Seek>(reader: R, mut budget: LoadBudget) -> Result<ProjectFile> {
let metadata_only = Cell::new(true);
let mut zip = open_archive(reader, &metadata_only, MAX_ZIP_METADATA_BYTES)?;
check_archive(&mut zip, budget.remaining())?;
let json = read_all(&mut zip.by_name("project.json").map_err(zip_err)?, MAX_JSON, &mut budget, "project.json")?;
#[derive(serde::Deserialize)]
struct Version {
@@ -378,6 +487,7 @@ fn load<R: Read + Seek>(reader: R) -> Result<ProjectFile> {
for i in 0..zip.len() {
let mut f = zip.by_index(i).map_err(zip_err)?;
let declared_bytes = f.size();
let name = f.name().map_err(zip_err)?.into_owned();
let size_of = |id: LayerId| texture_set_of(&pf.project, id).and_then(|ts| pf.project.texture_sets.get(ts)).map(|t| t.size());
if name == "thumbnail.png" {
@@ -411,7 +521,7 @@ fn load<R: Read + Seek>(reader: R) -> Result<ProjectFile> {
"skew" => BakePaintTarget::Skew,
_ => return Err(malformed(KIND, format!("unknown bake paint target in {name}"))),
};
let (width, height, values) = read_baked(&mut f, 1, &mut budget, &name)?;
let (width, height, values) = read_baked(&mut f, declared_bytes, 1, &mut budget, &name)?;
pf.bake_paint.insert((texture_set, target), BakePaintData { width, height, values });
} else if let Some(ext) = name.strip_prefix("mesh.").filter(|e| !e.contains('/')) {
let bytes = read_all(&mut f, crate::mesh_import::MAX_MESH_FILE_BYTES, &mut budget, &name)?;
@@ -443,7 +553,7 @@ fn load<R: Read + Seek>(reader: R) -> Result<ProjectFile> {
continue;
}
let (res, height, data) = read_baked(&mut f, m.components(), &mut budget, &name)?;
let (res, height, data) = read_baked(&mut f, declared_bytes, m.components(), &mut budget, &name)?;
let maps = pf.baked.entry(ts).or_default();
if maps.maps.is_empty() {
maps.resolution = res;
@@ -0,0 +1,41 @@
use std::sync::atomic::{AtomicU32, Ordering};
/// Default maximum decompressed project size, in GiB.
pub const DEFAULT_PROJECT_OPEN_LIMIT_GIB: u32 = 8;
static PROJECT_OPEN_LIMIT_GIB: AtomicU32 = AtomicU32::new(DEFAULT_PROJECT_OPEN_LIMIT_GIB);
/// Set the limit for subsequent project loads, in GiB; zero is clamped to one GiB.
/// An in-progress load keeps the limit it started with. Individual entry limits still apply.
pub fn set_project_open_limit_gib(limit_gib: u32) {
PROJECT_OPEN_LIMIT_GIB.store(limit_gib.max(1), Ordering::Relaxed);
}
/// Maximum decompressed project size accepted by subsequent loads, in GiB.
pub fn project_open_limit_gib() -> u32 {
PROJECT_OPEN_LIMIT_GIB.load(Ordering::Relaxed)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::project_file::load_budget::LoadBudget;
#[test]
fn preferences_apply_to_new_loads_in_gib_without_disabling_existing_guards() {
set_project_open_limit_gib(8);
let mut active_load = LoadBudget::new(u64::from(project_open_limit_gib()) << 30);
set_project_open_limit_gib(16);
let mut next_load = LoadBudget::new(u64::from(project_open_limit_gib()) << 30);
assert!(active_load.take(9 << 30).is_err());
assert!(next_load.take(9 << 30).is_ok());
set_project_open_limit_gib(0);
assert_eq!(project_open_limit_gib(), 1);
set_project_open_limit_gib(u32::MAX);
assert_eq!(u64::from(project_open_limit_gib()) << 30, 4_611_686_017_353_646_080);
set_project_open_limit_gib(DEFAULT_PROJECT_OPEN_LIMIT_GIB);
}
}
+451
View File
@@ -228,6 +228,145 @@ fn duplicate_entry_names_are_made_unique_on_save() {
assert_eq!(res, vec![vec![3], vec![4]]);
}
/// Every entry of a zip in file order: (name, method, crc, sizes, the compressed bytes as stored).
/// The zip headers around them (version fields, zip64 size placeholders) are not part of this:
/// copying an entry between zips rewrites them.
#[allow(clippy::type_complexity)]
fn payloads(zip: &[u8]) -> Vec<(String, CompressionMethod, u32, u64, u64, Vec<u8>)> {
let mut a = ZipArchive::new(Cursor::new(zip)).unwrap();
(0..a.len())
.map(|i| {
let mut f = a.by_index_raw(i).unwrap();
let mut raw = Vec::new();
f.read_to_end(&mut raw).unwrap();
(f.name().unwrap().into_owned(), f.compression(), f.crc32(), f.size(), f.compressed_size(), raw)
})
.collect()
}
/// A project with several baked maps and pixel layers, big enough that entries stream in chunks.
fn big_sample() -> ProjectFile {
let mut s = sample();
let mut x = 12345u32;
let mut noise = |n: usize| -> Vec<f32> {
(0..n)
.map(|i| {
x = x.wrapping_mul(1664525).wrapping_add(1013904223);
(i as f32 * 0.001).sin() * 0.5 + 0.5 + (x >> 24) as f32 * 1e-4
})
.collect()
};
let r = 300usize;
let maps = [BakedMap::AmbientOcclusion, BakedMap::Normal, BakedMap::Curvature, BakedMap::Position]
.into_iter()
.map(|m| (m, Arc::new(noise(r * r * m.components()))))
.collect();
s.pf.baked.insert(1, BakedMaps { resolution: r as u32, maps });
s.pf.mesh = Some(("obj".into(), noise(5000).iter().map(|v| (v * 200.0) as u8).collect()));
s.pf
}
fn serial_bytes(pf: &ProjectFile) -> Vec<u8> {
let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
entries::write_serial(&mut zip, entries(pf).unwrap()).unwrap();
zip.finish().unwrap().into_inner()
}
#[cfg(not(target_arch = "wasm32"))]
fn parallel_bytes(pf: &ProjectFile, workers: usize, budget: u64) -> Vec<u8> {
let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
entries::parallel::write(&mut zip, entries(pf).unwrap(), workers, budget).unwrap();
zip.finish().unwrap().into_inner()
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn save_plan_follows_the_reserved_cores_and_the_ram_share() {
// No cap of 8 workers any more, only the entry count and the cores.
assert_eq!(entries::plan(64, 1, 100, 1000, 50), (63, 500));
assert_eq!(entries::plan(64, 1, 20, 1000, 50).0, 20);
// 0 reserved uses every core; more reserved than cores still leaves one worker.
assert_eq!(entries::plan(16, 0, 100, 1000, 100), (16, 1000));
assert_eq!(entries::plan(4, 9, 100, 1000, 100).0, 1);
assert_eq!(entries::plan(1, 0, 100, 1000, 100).0, 1);
// The share is of the RAM given, clamped to 1..=100 percent, and never overflows.
assert_eq!(entries::plan(2, 1, 5, 1000, 0).1, 10);
assert_eq!(entries::plan(2, 1, 5, 1000, 250).1, 1000);
assert_eq!(entries::plan(2, 1, 5, u64::MAX, 100).1, u64::MAX);
assert_eq!(entries::plan(2, 1, 5, u64::MAX, 50).1, u64::MAX / 2);
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn parallel_save_with_any_reserved_cores_and_ram_share_matches_serial() {
let pf = big_sample();
let want = payloads(&serial_bytes(&pf));
let n = want.len();
// (cpus, reserved cores, available RAM, percent): none reserved, all reserved, a tiny and a huge share.
for (cpus, reserved, ram, percent) in [(8, 0, 1u64 << 40, 100u8), (8, 1, 1 << 40, 50), (8, 99, 1 << 40, 50), (16, 0, 1000, 1), (6, 1, u64::MAX, 100)] {
let (workers, budget) = entries::plan(cpus, reserved, n, ram, percent);
let got = parallel_bytes(&pf, workers, budget);
assert!(payloads(&got) == want, "{cpus} cpus, {reserved} reserved, {ram} bytes at {percent}%");
assert_same(&pf, &load_project_bytes(&got).unwrap());
}
// The setting is read by the public save; extreme values still save the same entries.
for (reserved, percent) in [(0, 100), (1000, 1), (1, 50)] {
set_save_resources(reserved, percent);
assert!(payloads(&save_project_bytes(&pf).unwrap()) == want, "{reserved} reserved, {percent}%");
}
set_save_resources(DEFAULT_RESERVED_CORES, DEFAULT_RAM_PERCENT);
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn parallel_save_writes_the_same_entries_as_serial() {
let pf = big_sample();
let serial = serial_bytes(&pf);
let want = payloads(&serial);
assert!(want.len() > 10);
for (workers, budget) in [(0, 1), (2, u64::MAX), (4, u64::MAX), (8, 1), (3, 100_000)] {
let got = parallel_bytes(&pf, workers, budget);
assert!(payloads(&got) == want, "{workers} workers, budget {budget}");
assert_same(&pf, &load_project_bytes(&got).unwrap());
}
// The public entry point (threads chosen by the machine) agrees too, and loads back.
assert!(payloads(&save_project_bytes(&pf).unwrap()) == want);
assert_same(&pf, &load_project_bytes(&serial).unwrap());
}
/// The files written before entries were compressed in parallel: each entry written in one go.
fn reference_one_shot(pf: &ProjectFile) -> Vec<u8> {
let deflate = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated).large_file(true);
let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
zip.start_file("project.json", deflate).unwrap();
zip.write_all(&serde_json::to_vec_pretty(&pf.project).unwrap()).unwrap();
for (ts, maps) in &pf.baked {
for (m, data) in &maps.maps {
zip.start_file(format!("baked/{ts}_{}.bin", m.id()), deflate).unwrap();
zip.write_all(&header(maps.resolution, maps.height(*m), m.components(), 0)).unwrap();
let bytes: Vec<u8> = data.iter().flat_map(|v| v.to_le_bytes()).collect();
zip.write_all(&bytes).unwrap();
}
}
zip.finish().unwrap().into_inner()
}
/// Streaming a baked map into the compressor in chunks may place deflate block boundaries a few
/// bytes differently than one big write, so the stored bytes can differ slightly; what the entry
/// holds (name, method, CRC, size) must not, and the compressed size stays within 0.01%.
#[test]
fn baked_entries_hold_what_the_one_shot_writer_wrote() {
let mut pf = big_sample();
(pf.mesh, pf.high_poly, pf.cage, pf.bake_paint, pf.thumbnail, pf.resources) = (None, vec![], None, BTreeMap::new(), None, BTreeMap::new());
pf.pixels = PixelStore::default();
let (new, old) = (payloads(&save_project_bytes(&pf).unwrap()), payloads(&reference_one_shot(&pf)));
assert_eq!(new.len(), old.len());
for (n, o) in new.iter().zip(&old) {
assert_eq!((&n.0, n.1, n.2, n.3), (&o.0, o.1, o.2, o.3));
assert!(n.4.abs_diff(o.4) <= 64 + o.4 / 10_000, "{}: {} vs {}", n.0, n.4, o.4);
}
}
#[test]
fn bake_model_options_survive_the_project_archive() {
use texturecraft_core::{BackfaceMode, CageType, HeightNormalization};
@@ -346,6 +485,125 @@ fn recovery_defaults_unreadable_bake_blocks() {
}
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn a_failing_entry_is_an_error_not_a_hang() {
let opts = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
for fail_at in [0usize, 3, 9] {
let list: Vec<Entry<'_>> = (0..10)
.map(|i| Entry {
name: format!("e{i}"),
options: opts,
weight: 10,
body: Box::new(move |w| {
if i == fail_at {
return Err(std::io::Error::other("boom"));
}
if i == 5 && fail_at == 9 {
panic!("worker panic");
}
w.write_all(&[i as u8; 100])
}),
})
.collect();
let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
assert!(entries::parallel::write(&mut zip, list, 4, 25).is_err(), "fail at {fail_at}");
}
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn a_late_failing_entry_after_good_ones_is_its_own_error() {
// Only the last entry fails and nothing panics, so the error must come from that entry.
for (workers, budget) in [(4usize, 25u64), (4, u64::MAX), (2, 1)] {
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let opts = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
let list: Vec<Entry<'_>> = (0..10)
.map(|i| Entry {
name: format!("e{i}"),
options: opts,
weight: 10,
body: Box::new(move |w| if i == 9 { Err(std::io::Error::other("late boom")) } else { w.write_all(&[i as u8; 100]) }),
})
.collect();
let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
let res = entries::parallel::write(&mut zip, list, workers, budget);
let _ = tx.send(res.map_err(|e| matches!(&e, FormatError::Io(io) if io.to_string() == "late boom")));
});
let res =
rx.recv_timeout(std::time::Duration::from_secs(60)).unwrap_or_else(|e| panic!("save did not finish ({e}): {workers} workers, budget {budget}"));
assert_eq!(res, Err(true), "{workers} workers, budget {budget}");
}
}
#[cfg(not(target_arch = "wasm32"))]
fn assert_entry_streams_to_destination(method: CompressionMethod, budget: u64) {
use std::sync::atomic::{AtomicBool, Ordering};
let path = std::env::temp_dir().join(format!("texturecraft-entry-streaming-{}-{method:?}.zip", std::process::id()));
let destination = std::fs::File::create(&path).unwrap();
let observed_destination = destination.try_clone().unwrap();
let reached_destination = AtomicBool::new(false);
let mut random = 12345u32;
let payload: Vec<u8> = (0..131_072)
.map(|_| {
random ^= random << 13;
random ^= random >> 17;
random ^= random << 5;
random as u8
})
.collect();
let compressed = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
let mut list: Vec<Entry<'_>> = (0..2)
.map(|index| Entry { name: format!("before{index}"), options: compressed, weight: 128, body: Box::new(|writer| writer.write_all(&[7; 128])) })
.collect();
list.push(Entry {
name: "target".into(),
options: SimpleFileOptions::default().compression_method(method),
weight: payload.len() as u64,
body: Box::new(|writer| {
let before_bytes = observed_destination.metadata()?.len();
writer.write_all(&payload)?;
writer.flush()?;
reached_destination.store(observed_destination.metadata()?.len() > before_bytes, Ordering::Relaxed);
Ok(())
}),
});
list.push(Entry { name: "after".into(), options: compressed, weight: 128, body: Box::new(|writer| writer.write_all(&[9; 128])) });
let mut writer = ZipWriter::new(destination);
let result = entries::parallel::write(&mut writer, list, 4, budget);
drop(writer.finish().unwrap());
drop(observed_destination);
let bytes = std::fs::read(&path).unwrap();
std::fs::remove_file(&path).unwrap();
result.unwrap();
assert!(reached_destination.load(Ordering::Relaxed), "{method:?} was buffered instead of streamed");
let mut archive = ZipArchive::new(Cursor::new(bytes)).unwrap();
let names: Vec<_> = (0..archive.len()).map(|index| archive.by_index(index).unwrap().name().unwrap().into_owned()).collect();
assert_eq!(names, ["before0", "before1", "target", "after"]);
let mut actual = Vec::new();
archive.by_name("target").unwrap().read_to_end(&mut actual).unwrap();
assert_eq!(actual, payload);
let mut after = Vec::new();
archive.by_name("after").unwrap().read_to_end(&mut after).unwrap();
assert_eq!(after, [9; 128]);
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn stored_entries_reach_the_destination_during_their_body() {
assert_entry_streams_to_destination(CompressionMethod::Stored, 1 << 20);
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn over_budget_entries_reach_the_destination_during_their_body() {
assert_entry_streams_to_destination(CompressionMethod::Deflated, 4096);
}
#[test]
fn recovery_skips_unsupported_baked_map_entries() {
let expected = sample().pf;
@@ -407,3 +665,196 @@ fn recovery_does_not_accept_unrelated_json_errors() {
let error = load_project_bytes(&bytes).unwrap_err();
assert!(error.to_string().contains("duplicate field"), "{error}");
}
#[test]
fn project_open_limit_counts_every_loaded_entry_kind() {
let paint = sample().paint;
let baked = [header(16, 16, 1, 0), vec![0; 16 * 16 * 4]].concat();
let entries = [
("resources/test.bin".to_string(), vec![1; 1024]),
("mesh.obj".to_string(), vec![2; 1024]),
("highpoly/test.obj".to_string(), vec![3; 1024]),
("cage/test.obj".to_string(), vec![4; 1024]),
("thumbnail.png".to_string(), vec![5; 1024]),
(format!("pixels/layer_{}_baseColor.bin", paint.0), tile_bin(128, 4, &[(0, 0)])),
(format!("pixels/mask_{}.bin", paint.0), tile_bin(128, 2, &[(0, 0)])),
("baked/0_ambientOcclusion.bin".to_string(), baked.clone()),
("bake_paint/0_skew.bin".to_string(), baked),
];
for (name, data) in entries {
let bytes = zip_with(&[(&name, data)]);
let mut archive = ZipArchive::new(Cursor::new(&bytes)).unwrap();
let total_bytes: u64 = (0..archive.len()).map(|index| archive.by_index(index).unwrap().size()).sum();
let accepted = load_with_budget(Cursor::new(&bytes), LoadBudget::new(total_bytes)).unwrap();
let error = load_with_budget(Cursor::new(&bytes), LoadBudget::new(total_bytes - 1)).unwrap_err();
let raised_limit = load_with_budget(Cursor::new(&bytes), LoadBudget::new(total_bytes + 1)).unwrap();
assert!(matches!(error, FormatError::TooLarge(_)), "{name}: {error}");
assert!(error.to_string().contains(&format!("{} bytes", total_bytes - 1)), "{name}: {error}");
assert_same(&accepted, &raised_limit);
}
}
#[test]
fn project_open_limit_is_shared_across_the_whole_archive() {
let project = sample().pf;
let bytes = serial_bytes(&project);
let mut archive = ZipArchive::new(Cursor::new(&bytes)).unwrap();
let total_bytes: u64 = (0..archive.len()).map(|index| archive.by_index(index).unwrap().size()).sum();
let accepted = load_with_budget(Cursor::new(&bytes), LoadBudget::new(total_bytes)).unwrap();
let error = load_with_budget(Cursor::new(&bytes), LoadBudget::new(total_bytes - 1)).unwrap_err();
assert_same(&project, &accepted);
assert!(matches!(error, FormatError::TooLarge(_)), "{error}");
}
#[test]
fn entry_reads_stop_at_the_smaller_of_the_entry_and_project_limits() {
for (entry_limit, project_limit, expected_read) in [(8, 100, 9), (100, 8, 9)] {
let mut reader = Cursor::new(vec![1; 1000]);
let mut budget = LoadBudget::new(project_limit);
let error = read_all(&mut reader, entry_limit, &mut budget, "resource").unwrap_err();
assert!(matches!(error, FormatError::TooLarge(_)), "{error}");
assert_eq!(reader.position(), expected_read);
}
}
#[test]
fn oversized_baked_data_is_rejected_before_reading_its_payload() {
let mut reader = Cursor::new(header(16, 16, 1, 0));
let mut budget = LoadBudget::new(BIN_HEADER_BYTES as u64 + 16 * 16 * 4 - 1);
let error = read_baked(&mut reader, BIN_HEADER_BYTES as u64 + 16 * 16 * 4, 1, &mut budget, "baked map").unwrap_err();
assert!(matches!(error, FormatError::TooLarge(_)), "the size guard must run before the truncated read: {error}");
assert_eq!(reader.position(), BIN_HEADER_BYTES as u64);
}
#[test]
fn archive_preflight_counts_ignored_entries_and_allows_the_exact_limit() {
let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
let options = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
for name in ["project.json", "unknown/future-data"] {
writer.start_file(name, options).unwrap();
writer.write_all(&[0; 16]).unwrap();
}
let bytes = writer.finish().unwrap().into_inner();
let mut archive = ZipArchive::new(Cursor::new(bytes)).unwrap();
check_archive(&mut archive, 32).unwrap();
let error = check_archive(&mut archive, 31).unwrap_err();
assert!(matches!(error, FormatError::TooLarge(_)), "{error}");
}
#[test]
fn overlapping_archive_entries_are_rejected_before_decompression() {
let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
writer.start_file("resource", SimpleFileOptions::default()).unwrap();
writer.write_all(&[0; 16]).unwrap();
writer.shallow_copy_file("resource", "copy").unwrap();
let bytes = writer.finish().unwrap().into_inner();
let mut archive = ZipArchive::new(Cursor::new(bytes)).unwrap();
let error = check_archive(&mut archive, 32).unwrap_err();
assert!(error.to_string().contains("overlapping ZIP entries"), "{error}");
}
#[test]
fn actual_decompression_is_bounded_even_when_the_declared_size_is_small() {
let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
writer.start_file("resource", SimpleFileOptions::default().compression_method(CompressionMethod::Deflated)).unwrap();
writer.write_all(&vec![0; 1 << 20]).unwrap();
let mut bytes = writer.finish().unwrap().into_inner();
let directory = ZipArchive::new(Cursor::new(&bytes)).unwrap().central_directory_start() as usize;
// The central header stores the uncompressed size at byte 24
bytes.get_mut(directory + 24..directory + 28).unwrap().copy_from_slice(&1u32.to_le_bytes());
let mut archive = ZipArchive::new(Cursor::new(bytes)).unwrap();
check_archive(&mut archive, 1024).unwrap();
let mut entry = archive.by_index(0).unwrap();
let mut budget = LoadBudget::new(1024);
let error = read_all(&mut entry, MAX_RESOURCE, &mut budget, "resource").unwrap_err();
assert!(
matches!(error, FormatError::TooLarge(_)) || error.to_string().contains("larger than its declared uncompressed size"),
"actual bytes must be bounded independently of ZIP sizes: {error}"
);
}
#[test]
fn baked_dimensions_must_match_the_entry_before_reserving_payload_bytes() {
let mut reader = Cursor::new(header(1024, 1024, 3, 0));
let mut budget = LoadBudget::new(16 << 20);
let error = read_baked(&mut reader, BIN_HEADER_BYTES as u64, 3, &mut budget, "baked map").unwrap_err();
assert!(error.to_string().contains("24 bytes for a 1024×1024×3 map"), "{error}");
assert_eq!(budget.remaining(), (16 << 20) - BIN_HEADER_BYTES as u64);
assert_eq!(reader.position(), BIN_HEADER_BYTES as u64);
}
#[test]
fn streamed_float_chunks_preserve_bits_across_the_chunk_boundary() {
let values: Vec<u32> = (0..BAKED_CHUNK + 3).map(|index| (index as u32).wrapping_mul(0x9e3779b9)).collect();
let bytes: Vec<u8> = values.iter().flat_map(|bits| bits.to_le_bytes()).collect();
let mut reader = Cursor::new(bytes);
let decoded = read_f32s(&mut reader, values.len(), "baked map").unwrap();
assert_eq!(decoded.into_iter().map(f32::to_bits).collect::<Vec<_>>(), values);
assert_eq!(reader.position(), (values.len() * 4) as u64);
}
#[test]
fn archive_indexing_does_not_scan_large_payloads_and_rejects_large_metadata() {
let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
writer.start_file("resource", SimpleFileOptions::default().compression_method(CompressionMethod::Stored)).unwrap();
writer.write_all(&vec![7; 1 << 20]).unwrap();
let bytes = writer.finish().unwrap().into_inner();
let metadata_only = Cell::new(true);
let mut archive = open_archive(Cursor::new(bytes), &metadata_only, 4096).unwrap();
let mut first_byte = [0; 1];
archive.by_index(0).unwrap().read_exact(&mut first_byte).unwrap();
assert_eq!(first_byte, [7]);
assert!(!metadata_only.get());
let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
writer.start_file("a".repeat(5000), SimpleFileOptions::default()).unwrap();
writer.write_all(&[7]).unwrap();
let bytes = writer.finish().unwrap().into_inner();
let metadata_only = Cell::new(true);
assert!(open_archive(Cursor::new(bytes), &metadata_only, 4096).is_err());
assert!(metadata_only.get(), "failed indexing must not enable payload access");
}
#[test]
fn zip64_entry_counts_remain_supported_and_bounded() {
for count in [65_536, MAX_ENTRIES + 1] {
let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
for index in 0..count {
writer.start_file(format!("e{index}"), SimpleFileOptions::default().compression_method(CompressionMethod::Stored)).unwrap();
}
let bytes = writer.finish().unwrap().into_inner();
let metadata_only = Cell::new(true);
let mut archive = open_archive(Cursor::new(bytes), &metadata_only, MAX_ZIP_METADATA_BYTES).unwrap();
let result = check_archive(&mut archive, 0);
assert_eq!(archive.len(), count);
if count <= MAX_ENTRIES {
result.unwrap();
} else {
assert!(matches!(result, Err(FormatError::TooLarge(_))), "{result:?}");
}
}
}
+37 -29
View File
@@ -199,18 +199,19 @@ impl Mesh {
/// Area-weighted smooth normals over the index buffer.
pub fn compute_normals(&mut self) {
let mut n = vec![Vec3::ZERO; self.positions.len()];
for t in self.indices.chunks_exact(3) {
let (a, b, c) = (t[0] as usize, t[1] as usize, t[2] as usize);
let mut normals = vec![Vec3::ZERO; self.positions.len()];
for &[a, b, c] in self.indices.as_chunks::<3>().0 {
let (a, b, c) = (a as usize, b as usize, c as usize);
let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue };
let face = (*pb - *pa).cross(*pc - *pa);
for v in [a, b, c] {
if let Some(x) = n.get_mut(v) {
if let Some(x) = normals.get_mut(v) {
*x += face;
}
}
}
self.normals = n.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect();
self.normals = normals.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect();
}
/// MikkTSpace tangents (falls back to per-triangle tangents if generation fails).
@@ -237,25 +238,27 @@ impl Mesh {
}
fn simple_tangents(&mut self) {
let mut acc = vec![Vec3::ZERO; self.positions.len()];
for t in self.indices.chunks_exact(3) {
let (a, b, c) = (t[0] as usize, t[1] as usize, t[2] as usize);
let mut tangents = vec![Vec3::ZERO; self.positions.len()];
for &[a, b, c] in self.indices.as_chunks::<3>().0 {
let (a, b, c) = (a as usize, b as usize, c as usize);
let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue };
let (Some(ua), Some(ub), Some(uc)) = (self.uvs.get(a), self.uvs.get(b), self.uvs.get(c)) else { continue };
let (e1, e2) = (*pb - *pa, *pc - *pa);
let (d1, d2) = (*ub - *ua, *uc - *ua);
let r = d1.x * d2.y - d2.x * d1.y;
if r.abs() < 1e-12 {
let determinant = d1.x * d2.y - d2.x * d1.y;
if determinant.abs() < 1e-12 {
continue;
}
let tan = (e1 * d2.y - e2 * d1.y) / r;
let tangent = (e1 * d2.y - e2 * d1.y) / determinant;
for v in [a, b, c] {
if let Some(x) = acc.get_mut(v) {
*x += tan;
if let Some(x) = tangents.get_mut(v) {
*x += tangent;
}
}
}
self.tangents = acc.into_iter().map(|t| t.try_normalize().unwrap_or(Vec3::X).extend(1.0)).collect();
self.tangents = tangents.into_iter().map(|t| t.try_normalize().unwrap_or(Vec3::X).extend(1.0)).collect();
}
/// The UV tiles material `m` covers: integer parts of its triangles' UV centroids (v down),
@@ -280,39 +283,44 @@ impl Mesh {
/// material's triangles using the vertex: piecewise maps (UV tiles of different sizes) then
/// place a vertex on a tile border with its own triangle's tile.
pub fn map_material_uvs_with(&mut self, m: usize, f: impl Fn(Vec2, Vec2) -> Vec2) {
let mine: Vec<usize> = self.triangles_of(m).collect();
let mut is_mine = vec![false; self.triangle_count()];
for t in &mine {
if let Some(x) = is_mine.get_mut(*t) {
let material_triangles: Vec<usize> = self.triangles_of(m).collect();
let mut in_material = vec![false; self.triangle_count()];
for t in &material_triangles {
if let Some(x) = in_material.get_mut(*t) {
*x = true;
}
}
let mut shared = vec![false; self.positions.len()];
for (_, tri) in self.indices.chunks_exact(3).enumerate().filter(|(t, _)| !is_mine.get(*t).copied().unwrap_or(false)) {
for (_, tri) in self.indices.as_chunks::<3>().0.iter().enumerate().filter(|(t, _)| !in_material.get(*t).copied().unwrap_or(false)) {
for v in tri {
if let Some(s) = shared.get_mut(*v as usize) {
*s = true;
}
}
}
let mut copies = std::collections::HashMap::new();
for k in mine.iter().flat_map(|t| t * 3..t * 3 + 3) {
let mut duplicates = std::collections::HashMap::new();
for k in material_triangles.iter().flat_map(|t| t * 3..t * 3 + 3) {
let Some(&v) = self.indices.get(k) else { continue };
let v = if shared.get(v as usize).copied().unwrap_or(false) { *copies.entry(v).or_insert_with(|| self.duplicate_vertex(v as usize)) } else { v };
let v =
if shared.get(v as usize).copied().unwrap_or(false) { *duplicates.entry(v).or_insert_with(|| self.duplicate_vertex(v as usize)) } else { v };
if let Some(i) = self.indices.get_mut(k) {
*i = v;
}
}
// (vertex, centroid of its first triangle), each vertex once.
let mut verts = Vec::with_capacity(mine.len() * 3);
for t in &mine {
// (vertex, centroid of its first triangle), each vertex once
let mut vertices = Vec::with_capacity(material_triangles.len() * 3);
for t in &material_triangles {
let Some(tri) = self.tri(*t) else { continue };
let centroid = tri.iter().map(|v| self.uvs.get(*v).copied().unwrap_or_default()).sum::<Vec2>() / 3.0;
verts.extend(tri.map(|v| (v, centroid)));
vertices.extend(tri.map(|v| (v, centroid)));
}
verts.sort_by_key(|(v, _)| *v);
verts.dedup_by_key(|(v, _)| *v);
for (v, centroid) in verts {
vertices.sort_by_key(|(v, _)| *v);
vertices.dedup_by_key(|(v, _)| *v);
for (v, centroid) in vertices {
if let Some(uv) = self.uvs.get_mut(v) {
*uv = f(centroid, *uv);
}
+105 -36
View File
@@ -130,33 +130,82 @@ pub(crate) fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 {
t * t * (3.0 - 2.0 * t)
}
/// Mirror and radial symmetry through the mesh center.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
/// Largest symmetry offset kept from a command or a file (world units), far beyond any mesh
const MAX_SYMMETRY_OFFSET: f32 = 1.0e6;
/// Mirror and radial symmetry through the mesh center, optionally moved by `offset`
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Symmetry {
/// The toolbar's Symmetry toggle: off keeps the settings below but paints no copies
#[serde(default = "enabled_by_default")]
pub enabled: bool,
pub x: bool,
pub y: bool,
pub z: bool,
/// Radial symmetry: copies spread evenly around `axis` (0 or 1: off; at most 32).
/// Radial copies around `axis`, spread over `angle_span` (0 or 1: off; at most [`MAX_RADIAL_COPIES`])
#[serde(default)]
pub radial: u8,
/// Axis of radial symmetry: 0 = X, 1 = Y, 2 = Z.
/// Axis of radial symmetry (0 = X, 1 = Y, 2 = Z), independent of the mirror axes
#[serde(default = "radial_axis")]
pub axis: u8,
/// Where the mirror planes and the radial axis cross, relative to the mesh center (world units)
#[serde(default)]
pub offset: [f32; 3],
/// Degrees the radial copies spread over: a full turn spaces them evenly, less puts the first and last copy at its ends
#[serde(default = "full_turn")]
pub angle_span: f32,
}
fn enabled_by_default() -> bool {
true
}
fn radial_axis() -> u8 {
1
}
fn full_turn() -> f32 {
FULL_TURN_DEGREES
}
/// [`Symmetry::angle_span`] of a full turn
pub const FULL_TURN_DEGREES: f32 = 360.0;
/// Most radial copies a brush paints
pub const MAX_RADIAL_COPIES: u8 = 32;
/// [`Symmetry::axis`] of the last axis, Z
const LAST_AXIS: u8 = 2;
impl Default for Symmetry {
fn default() -> Self {
Symmetry { x: false, y: false, z: false, radial: 0, axis: radial_axis() }
Symmetry { enabled: enabled_by_default(), x: false, y: false, z: false, radial: 0, axis: radial_axis(), offset: [0.0; 3], angle_span: full_turn() }
}
}
impl Symmetry {
/// Whether symmetry is on with an axis to mirror on or radial copies
pub fn any(&self) -> bool {
self.x || self.y || self.z || self.radial > 1
self.enabled && (self.x || self.y || self.z || self.radial > 1)
}
/// Whether radial symmetry is on (see [`Symmetry::radial_on`] for whether it paints copies)
pub fn radial_mode(&self) -> bool {
self.enabled && self.radial > 1
}
/// Whether radial copies are painted: with no angle to spread over they would all land on the stroke
pub fn radial_on(&self) -> bool {
self.radial_mode() && self.angle_span > 0.0
}
/// Rotation (radians) of radial copy number `copy` (0 = the stroke itself) around the axis
pub fn radial_angle(&self, copy: u8) -> f32 {
if self.angle_span >= FULL_TURN_DEGREES {
f32::from(copy) * std::f32::consts::TAU / f32::from(self.radial.max(1))
} else {
f32::from(copy) * self.angle_span.to_radians() / f32::from(self.radial.saturating_sub(1).max(1))
}
}
/// Mirror scales in stroke order, including identity, without allocating
@@ -172,26 +221,39 @@ impl Symmetry {
Vec3::NEG_ONE,
]
.into_iter()
.filter(|sign| (sign.x > 0.0 || self.x) && (sign.y > 0.0 || self.y) && (sign.z > 0.0 || self.z))
.filter(|sign| *sign == Vec3::ONE || (self.enabled && (sign.x > 0.0 || self.x) && (sign.y > 0.0 || self.y) && (sign.z > 0.0 || self.z)))
}
/// Linear maps (through the mesh center) taking a point to each of its symmetry copies,
/// the identity first. Mirrors come first, then radial rotations of the point and its mirrors.
/// The point the mirror planes and the radial axis pass through, for a mesh centered at `center`
pub fn origin(&self, center: Vec3) -> Vec3 {
center + Vec3::from(self.offset)
}
/// [`Symmetry::axis`] as an index (0 = X, 1 = Y, 2 = Z), out-of-range values read as Z
pub fn axis_index(&self) -> usize {
usize::from(self.axis.min(LAST_AXIS))
}
/// Axis of radial symmetry as a unit vector
pub fn radial_axis(&self) -> Vec3 {
[Vec3::X, Vec3::Y, Vec3::Z][self.axis_index()]
}
/// Linear maps `m` taking a point to its copies as `origin + m * (p - origin)`: identity, mirrors, then their radial turns
pub fn transforms(&self) -> Vec<Mat3> {
let mut out: Vec<Mat3> = self.mirror_signs().map(Mat3::from_diagonal).collect();
let mut maps: Vec<Mat3> = self.mirror_signs().map(Mat3::from_diagonal).collect();
if self.radial > 1 {
let axis = [Vec3::X, Vec3::Y, Vec3::Z].get(self.axis as usize).copied().unwrap_or(Vec3::Y);
let base = out.clone();
out.reserve(base.len().saturating_mul(usize::from(self.radial - 1)));
if self.radial_on() {
let mirrors = maps.clone();
maps.reserve(mirrors.len().saturating_mul(usize::from(self.radial - 1)));
for k in 1..self.radial {
let r = Mat3::from_axis_angle(axis, f32::from(k) * std::f32::consts::TAU / f32::from(self.radial));
out.extend(base.iter().map(|m| r * *m));
for copy in 1..self.radial {
let turn = Mat3::from_axis_angle(self.radial_axis(), self.radial_angle(copy));
maps.extend(mirrors.iter().map(|mirror| turn * *mirror));
}
}
out
maps
}
}
@@ -291,30 +353,37 @@ impl Default for BrushSettings {
}
impl BrushSettings {
/// Clamp every value into its valid range (input from UI, CLI or agents).
/// Clamp every value into its valid range (input from UI, CLI or agents)
pub fn sanitized(&self) -> BrushSettings {
let f = |v: f32, lo: f32, hi: f32, d: f32| if v.is_finite() { v.clamp(lo, hi) } else { d };
let clamp_finite = |value: f32, min: f32, max: f32, default: f32| if value.is_finite() { value.clamp(min, max) } else { default };
BrushSettings {
size: f(self.size, 0.0005, 0.5, 0.02),
min_size: f(self.min_size, 0.0, 1.0, 0.05),
flow: f(self.flow, 0.0, 1.0, 1.0),
opacity: f(self.opacity, 0.0, 1.0, 1.0),
spacing: f(self.spacing, 0.01, 10.0, 0.1),
hardness: f(self.hardness, 0.0, 0.999, 0.5),
angle: f(self.angle, -360.0, 360.0, 0.0),
angle_fade: (f(self.angle_fade.0, 0.0, 90.0, 70.0), f(self.angle_fade.1, 0.0, 90.0, 85.0)),
lazy: f(self.lazy, 0.0, 500.0, 0.0),
jitter_size: f(self.jitter_size, 0.0, 1.0, 0.0),
jitter_angle: f(self.jitter_angle, 0.0, 1.0, 0.0),
jitter_flow: f(self.jitter_flow, 0.0, 1.0, 0.0),
jitter_position: f(self.jitter_position, 0.0, 4.0, 0.0),
depth: f(self.depth, 0.05, 4.0, 1.0),
symmetry: Symmetry { radial: self.symmetry.radial.min(32), axis: self.symmetry.axis.min(2), ..self.symmetry },
size: clamp_finite(self.size, 0.0005, 0.5, 0.02),
min_size: clamp_finite(self.min_size, 0.0, 1.0, 0.05),
flow: clamp_finite(self.flow, 0.0, 1.0, 1.0),
opacity: clamp_finite(self.opacity, 0.0, 1.0, 1.0),
spacing: clamp_finite(self.spacing, 0.01, 10.0, 0.1),
hardness: clamp_finite(self.hardness, 0.0, 0.999, 0.5),
angle: clamp_finite(self.angle, -360.0, 360.0, 0.0),
angle_fade: (clamp_finite(self.angle_fade.0, 0.0, 90.0, 70.0), clamp_finite(self.angle_fade.1, 0.0, 90.0, 85.0)),
lazy: clamp_finite(self.lazy, 0.0, 500.0, 0.0),
jitter_size: clamp_finite(self.jitter_size, 0.0, 1.0, 0.0),
jitter_angle: clamp_finite(self.jitter_angle, 0.0, 1.0, 0.0),
jitter_flow: clamp_finite(self.jitter_flow, 0.0, 1.0, 0.0),
jitter_position: clamp_finite(self.jitter_position, 0.0, 4.0, 0.0),
depth: clamp_finite(self.depth, 0.05, 4.0, 1.0),
symmetry: Symmetry {
radial: self.symmetry.radial.min(MAX_RADIAL_COPIES),
axis: self.symmetry.axis.min(LAST_AXIS),
offset: self.symmetry.offset.map(|value| clamp_finite(value, -MAX_SYMMETRY_OFFSET, MAX_SYMMETRY_OFFSET, 0.0)),
angle_span: clamp_finite(self.symmetry.angle_span, 0.0, FULL_TURN_DEGREES, FULL_TURN_DEGREES),
..self.symmetry
},
particles: Particles {
enabled: self.particles.enabled,
count: self.particles.count.clamp(1, 16),
lifetime: self.particles.lifetime.clamp(1, 128),
gravity: f(self.particles.gravity, 0.0, 2.0, 1.0),
gravity: clamp_finite(self.particles.gravity, 0.0, 2.0, 1.0),
},
..self.clone()
}
+4 -2
View File
@@ -19,14 +19,16 @@ pub mod path;
pub mod pickup;
pub mod presets;
pub mod raster;
pub mod stamp_source;
pub mod stroke;
pub mod text;
pub mod visibility;
pub use brush::{Alignment, BrushAlpha, BrushSettings, Particles, Shape, Symmetry, image_alpha};
pub use brush::{Alignment, BrushAlpha, BrushSettings, FULL_TURN_DEGREES, MAX_RADIAL_COPIES, Particles, Shape, Symmetry, image_alpha};
pub use commit::{CommitSource, Staging, TexelFn, commit_coverage, commit_layer, commit_mask};
pub use path::{Lasso, spline};
pub use path::{Lasso, spline, spline_segments};
pub use pickup::{Pickup, PickupMode};
pub use raster::{RasterCtx, StrokeCanvas, UvStamp, fill_coverage, fill_triangles, rasterize, rasterize_uv};
pub use stamp_source::StampSource;
pub use stroke::{PickCtx, Stamp, Stroke, SurfaceHit, pick};
pub use visibility::{EyeDepth, screen_point};
+18 -18
View File
@@ -78,18 +78,16 @@ mod tests {
#[test]
fn particles_slide_down_a_wall_deterministically() {
// A vertical wall: the plane rotated to face +Z.
let mut m = primitives::plane(2.0, 8);
for p in &mut m.positions {
*p = Vec3::new(p.x, -p.z, 0.0);
// A vertical wall: the plane rotated to face +Z
let mut mesh = primitives::plane(2.0, 8);
for position in &mut mesh.positions {
*position = Vec3::new(position.x, -position.z, 0.0);
}
for n in &mut m.normals {
*n = Vec3::Z;
}
let bvh = Bvh::new(&m);
let cam = OrbitCamera::default();
let ctx = PickCtx { mesh: &m, bvh: &bvh, camera: &cam, viewport: Vec2::new(100.0, 100.0) };
let s = Stamp {
mesh.normals.fill(Vec3::Z);
let bvh = Bvh::new(&mesh);
let camera = OrbitCamera::default();
let context = PickCtx { mesh: &mesh, bvh: &bvh, camera: &camera, viewport: Vec2::new(100.0, 100.0) };
let stamp = Stamp {
center: Vec3::ZERO,
normal: Vec3::Z,
tangent: Vec3::X,
@@ -99,14 +97,16 @@ mod tests {
hardness: 0.5,
depth: 1.0,
seed: 3,
copy: false,
source: None,
};
let p = Particles { enabled: true, count: 4, lifetime: 20, gravity: 1.0 };
let a = emit(&ctx, &p, &s);
assert_eq!(a, emit(&ctx, &p, &s));
assert_eq!(a.len(), 80);
let lowest = a.iter().map(|d| d.center.y).fold(f32::MAX, f32::min);
let particles = Particles { enabled: true, count: 4, lifetime: 20, gravity: 1.0 };
let dabs = emit(&context, &particles, &stamp);
assert_eq!(dabs, emit(&context, &particles, &stamp));
assert_eq!(dabs.len(), 80);
let lowest = dabs.iter().map(|d| d.center.y).fold(f32::MAX, f32::min);
assert!(lowest < -0.4, "{lowest}");
assert!(a.iter().all(|d| d.center.z.abs() < 1e-3));
assert!(dabs.iter().all(|d| d.center.z.abs() < 1e-3));
}
}
+28 -14
View File
@@ -6,30 +6,44 @@ use texturecraft_geom::glam::Vec2;
/// Most samples per curve segment.
const MAX_SEGMENT_SAMPLES: f32 = 1024.0;
/// A Catmull-Rom spline through `points`, sampled about every `step` units. Closed curves wrap
/// back to the first point; the result starts at the first point.
/// A Catmull-Rom spline through `points`, sampled about every `step` units, starting on the first point (closed curves end there too)
pub fn spline(points: &[Vec2], closed: bool, step: f32) -> Vec<Vec2> {
let n = points.len();
if n < 2 {
return points.to_vec();
let mut out: Vec<Vec2> = points.first().copied().into_iter().collect();
for segment in segment_samples(points, closed, step) {
out.extend(segment);
}
let at = |i: isize| {
out
}
/// [`spline`]'s samples per segment: segment `s` holds those after point `s`, up to and including the next point
pub fn spline_segments(points: &[Vec2], closed: bool, step: f32) -> Vec<Vec<Vec2>> {
segment_samples(points, closed, step).map(Iterator::collect).collect()
}
/// Stream samples so a flat curve does not allocate and retain every segment alongside its output
fn segment_samples(points: &[Vec2], closed: bool, step: f32) -> impl Iterator<Item = impl Iterator<Item = Vec2>> + '_ {
let n = points.len();
let at = move |i: isize| {
let i = if closed { i.rem_euclid(n as isize) } else { i.clamp(0, n as isize - 1) };
points.get(i as usize).copied().unwrap_or_default()
};
let step = if step.is_finite() && step > 1e-6 { step } else { 1.0 };
let segments = if closed { n } else { n - 1 } as isize;
let mut out = vec![at(0)];
for s in 0..segments {
let segments = if n < 2 {
0
} else if closed {
n
} else {
n - 1
} as isize;
(0..segments).map(move |s| {
let (p0, p1, p2, p3) = (at(s - 1), at(s), at(s + 1), at(s + 2));
let k = ((p2 - p1).length() / step).ceil().clamp(1.0, MAX_SEGMENT_SAMPLES) as usize;
for j in 1..=k {
(1..=k).map(move |j| {
let t = j as f32 / k as f32;
let (t2, t3) = (t * t, t * t * t);
out.push(0.5 * (2.0 * p1 + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (3.0 * p1 - p0 - 3.0 * p2 + p3) * t3));
}
}
out
0.5 * (2.0 * p1 + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (3.0 * p1 - p0 - 3.0 * p2 + p3) * t3)
})
})
}
/// A closed polygon's coverage: 1 inside, 0 outside, a one-unit ramp across the edge.
+112 -59
View File
@@ -82,6 +82,28 @@ impl StrokeCanvas {
}
}
/// Most a texel's eye distance may exceed the nearest surface in its 3×3 pixel neighbourhood, in pixels along the surface
const NEIGHBOUR_REACH: f32 = 1.5;
/// Facing (cosine) below which the allowance stops growing
const MIN_FACING: f32 = 0.05;
/// Height of the view in normalized device coordinates (−1 to 1)
const NDC_HEIGHT: f32 = 2.0;
/// How far toward the eye to test a texel turned `facing` away: at grazing angles the neighbouring pixels of the same surface are much nearer, and the depth test would speckle
fn grazing_allowance(depth: &EyeDepth, point: Vec3, facing: f32, pixels_per_unit: f32) -> f32 {
// Back faces get none, so painting with culling off doesn't reach through thin parts
if facing <= 0.0 {
return 0.0;
}
let clip_w = (depth.view_proj * point.extend(1.0)).w.max(0.0);
let world_per_pixel = clip_w * NDC_HEIGHT / pixels_per_unit;
let facing = facing.clamp(MIN_FACING, 1.0);
world_per_pixel * NEIGHBOUR_REACH * (1.0 - facing * facing).sqrt() / facing
}
/// What the rasterizer reads.
pub struct RasterCtx<'a> {
pub mesh: &'a Mesh,
@@ -103,28 +125,37 @@ fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 {
}
/// Accumulate `stamps` into `canvas` ("over": `m = a + m·(1 − a)`).
pub fn rasterize(canvas: &mut StrokeCanvas, ctx: &RasterCtx, stamps: &[Stamp]) {
let (w, h) = (ctx.gbuf.width, ctx.gbuf.height);
canvas.fit(ctx.gbuf);
let fade_lo = ctx.angle_fade.1.to_radians().cos();
let fade_hi = ctx.angle_fade.0.to_radians().cos();
let mut tris = Vec::new();
for s in stamps {
if s.radius.is_nan() || s.radius <= 0.0 || !s.center.is_finite() {
pub fn rasterize(canvas: &mut StrokeCanvas, context: &RasterCtx, stamps: &[Stamp]) {
let (width, height) = (context.gbuf.width, context.gbuf.height);
canvas.fit(context.gbuf);
let fade_lo = context.angle_fade.1.to_radians().cos();
let fade_hi = context.angle_fade.0.to_radians().cos();
// The camera scale is shared by every candidate texel in this batch
let pixels_per_unit = context.depth.map_or(1.0, |depth| {
let ndc_per_unit = depth.view_proj.row(1).truncate().length();
(depth.height as f32 * ndc_per_unit).max(f32::EPSILON)
});
let mut triangles = Vec::new();
for stamp in stamps {
if stamp.radius.is_nan() || stamp.radius <= 0.0 || !stamp.center.is_finite() {
continue;
}
let ext = Vec3::splat(s.radius * s.depth.max(1.0) * 1.42);
tris.clear();
ctx.bvh.query_box(s.center - ext, s.center + ext, |t| tris.push(t));
// Each texel belongs to one triangle, so triangles scan independently (in parallel for
// large stamps); stamp alphas combine commutatively, so the order does not matter.
let scan = |&t: &u32| scan_triangle(ctx, s, t, w, h, fade_lo, fade_hi);
let parts: Vec<TriTexels> = if tris.len() > 16 { tris.par_iter().filter_map(scan).collect() } else { tris.iter().filter_map(scan).collect() };
// The stamp center in texels: the footprint texel nearest to it on the surface.
let extent = Vec3::splat(stamp.radius * stamp.depth.max(1.0) * 1.42);
triangles.clear();
context.bvh.query_box(stamp.center - extent, stamp.center + extent, |triangle| triangles.push(triangle));
// Each texel belongs to one triangle, so large stamps can scan triangles in parallel
let scan = |&triangle: &u32| scan_triangle(context, stamp, triangle, width, height, fade_lo, fade_hi, pixels_per_unit);
let parts: Vec<TriTexels> =
if triangles.len() > 16 { triangles.par_iter().filter_map(scan).collect() } else { triangles.iter().filter_map(scan).collect() };
// The footprint texel nearest the stamp center supplies the pickup's center
let mut center = ([0.0f32; 2], f32::MAX);
for (texels, c) in parts {
if c.1 < center.1 {
center = c;
for (texels, nearest) in parts {
if nearest.1 < center.1 {
center = nearest;
}
canvas.texels.extend(texels);
}
@@ -136,69 +167,91 @@ pub fn rasterize(canvas: &mut StrokeCanvas, ctx: &RasterCtx, stamps: &[Stamp]) {
type TriTexels = (Vec<(u32, u32, f32)>, ([f32; 2], f32));
#[allow(clippy::too_many_arguments)]
fn scan_triangle(ctx: &RasterCtx, s: &Stamp, t: u32, w: u32, h: u32, fade_lo: f32, fade_hi: f32) -> Option<TriTexels> {
if ctx.mesh.material_of(t as usize) != Some(ctx.material) {
fn scan_triangle(
context: &RasterCtx,
stamp: &Stamp,
triangle: u32,
width: u32,
height: u32,
fade_lo: f32,
fade_hi: f32,
pixels_per_unit: f32,
) -> Option<TriTexels> {
if context.mesh.material_of(triangle as usize) != Some(context.material) {
return None;
}
let [a, b, c] = ctx.mesh.tri(t as usize)?;
let (ua, ub, uc) = (ctx.mesh.uvs.get(a)?, ctx.mesh.uvs.get(b)?, ctx.mesh.uvs.get(c)?);
let (pa, pb, pc) = (ctx.mesh.positions.get(a)?, ctx.mesh.positions.get(b)?, ctx.mesh.positions.get(c)?);
let (na, nb, nc) = (ctx.mesh.normals.get(a)?, ctx.mesh.normals.get(b)?, ctx.mesh.normals.get(c)?);
let x0 = (ua.x.min(ub.x).min(uc.x) * w as f32).floor().max(0.0) as u32;
let x1 = ((ua.x.max(ub.x).max(uc.x) * w as f32).ceil().max(0.0) as u32).min(w);
let y0 = (ua.y.min(ub.y).min(uc.y) * h as f32).floor().max(0.0) as u32;
let y1 = ((ua.y.max(ub.y).max(uc.y) * h as f32).ceil().max(0.0) as u32).min(h);
// Stamp radius in texels on this triangle: texel area over world area.
let uv_area = (*ub - *ua).perp_dot(*uc - *ua).abs() * w as f32 * h as f32;
let world_area = (*pb - *pa).cross(*pc - *pa).length();
let shape = ctx.shape.at_radius(s.radius * (uv_area / world_area).sqrt());
let [first, second, third] = context.mesh.tri(triangle as usize)?;
let (uv_a, uv_b, uv_c) = (context.mesh.uvs.get(first)?, context.mesh.uvs.get(second)?, context.mesh.uvs.get(third)?);
let (position_a, position_b, position_c) = (context.mesh.positions.get(first)?, context.mesh.positions.get(second)?, context.mesh.positions.get(third)?);
let (normal_a, normal_b, normal_c) = (context.mesh.normals.get(first)?, context.mesh.normals.get(second)?, context.mesh.normals.get(third)?);
let x0 = (uv_a.x.min(uv_b.x).min(uv_c.x) * width as f32).floor().max(0.0) as u32;
let x1 = ((uv_a.x.max(uv_b.x).max(uv_c.x) * width as f32).ceil().max(0.0) as u32).min(width);
let y0 = (uv_a.y.min(uv_b.y).min(uv_c.y) * height as f32).floor().max(0.0) as u32;
let y1 = ((uv_a.y.max(uv_b.y).max(uv_c.y) * height as f32).ceil().max(0.0) as u32).min(height);
// Stamp radius in texels on this triangle: texel area over world area
let uv_area = (*uv_b - *uv_a).perp_dot(*uv_c - *uv_a).abs() * width as f32 * height as f32;
let world_area = (*position_b - *position_a).cross(*position_c - *position_a).length();
let shape = context.shape.at_radius(stamp.radius * (uv_area / world_area).sqrt());
let mut texels = Vec::new();
let mut center = ([0.0f32; 2], f32::MAX);
for y in y0..y1 {
for x in x0..x1 {
let i = (y * w + x) as usize;
if ctx.gbuf.tri.get(i).copied().unwrap_or(NO_TRI) != t {
let texel = (y * width + x) as usize;
if context.gbuf.tri.get(texel).copied().unwrap_or(NO_TRI) != triangle {
continue;
}
let Some([b1, b2]) = ctx.gbuf.bary.get(i).copied() else { continue };
let Some([b1, b2]) = context.gbuf.bary.get(texel).copied() else { continue };
let b0 = 1.0 - b1 - b2;
let p = *pa * b0 + *pb * b1 + *pc * b2;
let d = p - s.center;
let lx = d.dot(s.tangent) / s.radius;
let ly = d.dot(s.bitangent) / s.radius;
if lx * lx + ly * ly > 2.0 {
let position = *position_a * b0 + *position_b * b1 + *position_c * b2;
let offset = position - stamp.center;
let local_x = offset.dot(stamp.tangent) / stamp.radius;
let local_y = offset.dot(stamp.bitangent) / stamp.radius;
if local_x * local_x + local_y * local_y > 2.0 {
continue;
}
if d.dot(s.normal).abs() > s.radius * s.depth {
if offset.dot(stamp.normal).abs() > stamp.radius * stamp.depth {
continue;
}
let dist = d.length_squared();
if dist < center.1 {
center = ([x as f32 + 0.5, y as f32 + 0.5], dist);
let distance_squared = offset.length_squared();
if distance_squared < center.1 {
center = ([x as f32 + 0.5, y as f32 + 0.5], distance_squared);
}
let n = (*na * b0 + *nb * b1 + *nc * b2).try_normalize().unwrap_or(s.normal);
let to_eye = (ctx.eye - p).try_normalize().unwrap_or(n);
let facing = n.dot(to_eye);
// Symmetry copies paint where the camera may not see (the back of the model).
let culled = ctx.backface_culling && !s.copy;
if culled && facing <= 0.0 {
let normal = (*normal_a * b0 + *normal_b * b1 + *normal_c * b2).try_normalize().unwrap_or(stamp.normal);
if normal.dot(stamp.normal) <= 0.0 {
continue;
}
if n.dot(s.normal) <= 0.0 {
// Allow half the stamp depth when the mirrored point is off an asymmetric surface
let (seen, seen_normal) = stamp.source.map_or((position, normal), |source| (source.point(position), source.direction(normal)));
let off_surface = if stamp.source.is_some() { stamp.radius * stamp.depth } else { 0.0 };
let to_eye = (context.eye - seen).try_normalize().unwrap_or(seen_normal);
let facing = seen_normal.dot(to_eye);
if context.backface_culling && facing <= 0.0 {
continue;
}
if let Some(depth) = ctx.depth.filter(|_| !s.copy)
&& !depth.visible(p)
if let Some(depth) = context.depth
&& !depth.visible(seen + to_eye * (grazing_allowance(depth, seen, facing, pixels_per_unit) + off_surface))
{
continue;
}
let fade = if culled { smoothstep(fade_lo, fade_hi, facing) } else { 1.0 };
let a = shape.sample(lx, ly, s.hardness, s.seed) * s.flow * fade;
if a > 0.0 {
texels.push((x, y, a));
let fade = if context.backface_culling { smoothstep(fade_lo, fade_hi, facing) } else { 1.0 };
let alpha = shape.sample(local_x, local_y, stamp.hardness, stamp.seed) * stamp.flow * fade;
if alpha > 0.0 {
texels.push((x, y, alpha));
}
}
}
(center.1 < f32::MAX || !texels.is_empty()).then_some((texels, center))
}
@@ -257,7 +310,7 @@ mod tests {
hardness: 0.9,
depth: 1.0,
seed: 0,
copy: false,
source: None,
};
rasterize(&mut canvas, &ctx, &[st]);
// Plane is 2 units over 128 texels: radius 0.25 = 16 texels around the center (64, 64).
+24
View File
@@ -0,0 +1,24 @@
//! Where a symmetry copy of a stamp comes from
use texturecraft_geom::glam::{Mat3, Vec3};
/// The map from a symmetry copy back to its source stamp: a copy paints where its source would be painted
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct StampSource {
/// The point the symmetry maps turn and mirror about
pub origin: Vec3,
/// The inverse of the copy's linear map (mirrors and turns, so its transpose)
pub to_source: Mat3,
}
impl StampSource {
/// The source's point for a point of the copy
pub fn point(&self, copy_point: Vec3) -> Vec3 {
self.origin + self.to_source * (copy_point - self.origin)
}
/// The source's direction for a direction of the copy
pub fn direction(&self, copy_direction: Vec3) -> Vec3 {
self.to_source * copy_direction
}
}
+137 -47
View File
@@ -1,11 +1,12 @@
//! From pointer samples to stamps: picking, lazy mouse, spacing along the surface, stamp
//! frames, jitter and symmetry.
use texturecraft_geom::glam::{Quat, Vec2, Vec3};
use texturecraft_geom::glam::{Mat3, Quat, Vec2, Vec3};
use texturecraft_geom::{Bvh, Mesh, OrbitCamera, surface_at};
use texturecraft_texel::noise::pcg3d;
use crate::brush::{Alignment, BrushSettings};
use crate::stamp_source::StampSource;
/// Scene access for picking.
pub struct PickCtx<'a> {
@@ -37,7 +38,20 @@ pub fn pick(ctx: &PickCtx, screen: Vec2) -> Option<SurfaceHit> {
Some(SurfaceHit { pos: s.pos, nrm: s.nrm, tri: hit.tri, uv: s.uv, material: ctx.mesh.material_of(hit.tri as usize).unwrap_or(0), screen })
}
/// One brush dab in world space.
/// Random channels of a stamp's jitters (each draws its own number from the stamp's seed)
const JITTER_ANGLE: u32 = 1;
const JITTER_SIZE: u32 = 2;
const JITTER_ACROSS: u32 = 3;
const JITTER_ALONG: u32 = 4;
const JITTER_FLOW: u32 = 5;
/// Full angle jitter turns a stamp this far either way (degrees)
const HALF_TURN_DEGREES: f32 = 180.0;
/// Smallest size jitter leaves a stamp, as a fraction of its radius
const MIN_JITTERED_SIZE: f32 = 0.05;
/// One brush dab in world space
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Stamp {
pub center: Vec3,
@@ -47,12 +61,12 @@ pub struct Stamp {
pub radius: f32,
pub flow: f32,
pub hardness: f32,
/// Half-depth of the stamp volume relative to the radius.
/// Half-depth of the stamp volume relative to the radius
pub depth: f32,
/// Varies procedural alphas per stamp.
/// Varies procedural alphas per stamp
pub seed: u32,
/// A symmetry copy: it paints where symmetry puts it, whether the camera sees that or not.
pub copy: bool,
/// A symmetry copy's way back to its source: it paints where the source would, mirrored
pub source: Option<StampSource>,
}
/// An in-progress stroke.
@@ -168,66 +182,87 @@ impl Stroke {
self.last = Some(hit);
}
/// The next stamp at `hit`: oriented to the surface or the camera, then jittered
fn stamp(&mut self, ctx: &PickCtx, hit: &SurfaceHit, radius: f32) -> Stamp {
let s = &self.settings;
let n = self.count;
let settings = &self.settings;
let seed = self.count;
self.count = self.count.wrapping_add(1);
let jitter = |k: u32, amount: f32| if amount > 0.0 { (rand01(n, k) * 2.0 - 1.0) * amount } else { 0.0 };
let normal = match s.alignment {
let jitter = |channel: u32, amount: f32| if amount > 0.0 { (rand01(seed, channel) * 2.0 - 1.0) * amount } else { 0.0 };
// Frame: the normal, and an up direction from the camera or the stroke's path
let normal = match settings.alignment {
Alignment::Tangent => hit.nrm,
Alignment::Camera => -ctx.camera.forward(),
};
let cam_up = {
let f = ctx.camera.forward();
let right = f.cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X);
right.cross(f)
let camera_up = {
let forward = ctx.camera.forward();
let right = forward.cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X);
right.cross(forward)
};
let up_src = if s.follow_path { self.last_dir.unwrap_or(cam_up) } else { cam_up };
let up = (up_src - normal * normal.dot(up_src)).try_normalize().unwrap_or_else(|| normal.any_orthonormal_vector());
let tangent0 = up.cross(normal).try_normalize().unwrap_or_else(|| normal.any_orthonormal_vector());
let angle = (s.angle + jitter(1, s.jitter_angle) * 180.0).to_radians();
let q = Quat::from_axis_angle(normal, angle);
let tangent = q * tangent0;
let up_source = if settings.follow_path { self.last_dir.unwrap_or(camera_up) } else { camera_up };
let up = (up_source - normal * normal.dot(up_source)).try_normalize().unwrap_or_else(|| normal.any_orthonormal_vector());
let unturned_tangent = up.cross(normal).try_normalize().unwrap_or_else(|| normal.any_orthonormal_vector());
// Jitter: angle, size, position and flow
let angle = (settings.angle + jitter(JITTER_ANGLE, settings.jitter_angle) * HALF_TURN_DEGREES).to_radians();
let turn = Quat::from_axis_angle(normal, angle);
let tangent = turn * unturned_tangent;
let bitangent = normal.cross(tangent);
let r = radius * (1.0 + jitter(2, s.jitter_size)).max(0.05);
let offset = (tangent * jitter(3, 1.0) + bitangent * jitter(4, 1.0)) * s.jitter_position * radius;
let flow = (s.flow * (1.0 - jitter(5, s.jitter_flow).abs())).clamp(0.0, 1.0);
Stamp { center: hit.pos + offset, normal, tangent, bitangent, radius: r, flow, hardness: s.hardness, depth: s.depth, seed: n, copy: false }
let jittered_radius = radius * (1.0 + jitter(JITTER_SIZE, settings.jitter_size)).max(MIN_JITTERED_SIZE);
let offset = (tangent * jitter(JITTER_ACROSS, 1.0) + bitangent * jitter(JITTER_ALONG, 1.0)) * settings.jitter_position * radius;
let flow = (settings.flow * (1.0 - jitter(JITTER_FLOW, settings.jitter_flow).abs())).clamp(0.0, 1.0);
Stamp {
center: hit.pos + offset,
normal,
tangent,
bitangent,
radius: jittered_radius,
flow,
hardness: settings.hardness,
depth: settings.depth,
seed,
source: None,
}
}
/// Mirror copies of a stamp for the enabled symmetry axes, then radial copies of it and
/// its mirrors.
fn mirrors(&self, s: &Stamp) -> Vec<Stamp> {
let sym = self.settings.symmetry;
if !sym.any() {
/// Mirror copies of a stamp for the enabled symmetry axes, then radial copies of it and its mirrors
fn mirrors(&self, stamp: &Stamp) -> Vec<Stamp> {
let symmetry = self.settings.symmetry;
if !symmetry.any() {
return Vec::new();
}
let mut out = Vec::new();
for sign in sym.mirror_signs().skip(1) {
let normal = s.normal * sign;
let tangent = s.tangent * sign;
out.push(Stamp { center: self.center + (s.center - self.center) * sign, normal, tangent, bitangent: normal.cross(tangent), copy: true, ..*s });
let origin = symmetry.origin(self.center);
let mut copies = Vec::new();
let mut maps = Vec::new();
for sign in symmetry.mirror_signs().skip(1) {
let normal = stamp.normal * sign;
let tangent = stamp.tangent * sign;
let map = Mat3::from_diagonal(sign);
let source = Some(StampSource { origin, to_source: map.transpose() });
copies.push(Stamp { center: origin + (stamp.center - origin) * sign, normal, tangent, bitangent: normal.cross(tangent), source, ..*stamp });
maps.push(map);
}
if sym.radial > 1 {
let axis = [Vec3::X, Vec3::Y, Vec3::Z].get(sym.axis as usize).copied().unwrap_or(Vec3::Y);
let base: Vec<Stamp> = std::iter::once(*s).chain(out.iter().copied()).collect();
if symmetry.radial_on() {
let axis = symmetry.radial_axis();
let to_turn: Vec<(Stamp, Mat3)> = std::iter::once((*stamp, Mat3::IDENTITY)).chain(copies.iter().copied().zip(maps)).collect();
for k in 1..sym.radial {
let q = Quat::from_axis_angle(axis, f32::from(k) * std::f32::consts::TAU / f32::from(sym.radial));
out.extend(base.iter().map(|b| Stamp {
center: self.center + q * (b.center - self.center),
normal: q * b.normal,
tangent: q * b.tangent,
bitangent: q * b.bitangent,
copy: true,
..*b
for copy in 1..symmetry.radial {
let turn = Quat::from_axis_angle(axis, symmetry.radial_angle(copy));
copies.extend(to_turn.iter().map(|(base, map)| Stamp {
center: origin + turn * (base.center - origin),
normal: turn * base.normal,
tangent: turn * base.tangent,
bitangent: turn * base.bitangent,
source: Some(StampSource { origin, to_source: (Mat3::from_quat(turn) * *map).transpose() }),
..*base
}));
}
}
out
copies
}
pub fn last_hit(&self) -> Option<SurfaceHit> {
@@ -296,6 +331,61 @@ mod tests {
assert_eq!(s.add(&ctx, Vec2::new(250.0, 180.0), 1.0).len(), 8);
}
#[test]
fn symmetry_mirrors_about_the_moved_plane() {
let (mesh, bvh, camera) = ctx_parts();
let ctx = PickCtx { mesh: &mesh, bvh: &bvh, camera: &camera, viewport: Vec2::new(400.0, 400.0) };
let mut settings = BrushSettings::default();
settings.symmetry.x = true;
settings.symmetry.offset = [0.25, 0.0, 0.0];
let mut stroke = Stroke::new(&settings, &mesh);
let stamps = stroke.add(&ctx, Vec2::new(250.0, 200.0), 1.0);
assert_eq!(stamps.len(), 2, "one stamp and its copy");
let (painted, copy) = (stamps[0], stamps[1]);
// Mirrored about x = 0.25 instead of the mesh center (x = 0)
assert!((painted.center.x + copy.center.x - 0.5).abs() < 1e-4, "{} {}", painted.center, copy.center);
assert!((painted.center.y - copy.center.y).abs() < 1e-4 && (painted.center.z - copy.center.z).abs() < 1e-4);
}
#[test]
fn default_symmetry_copies_match_the_mesh_centered_formula_bit_for_bit() {
let (mesh, bvh, camera) = ctx_parts();
let ctx = PickCtx { mesh: &mesh, bvh: &bvh, camera: &camera, viewport: Vec2::new(400.0, 400.0) };
let mut settings = BrushSettings::default();
settings.symmetry = crate::brush::Symmetry { x: true, y: true, radial: 3, axis: 1, ..settings.symmetry };
let mut stroke = Stroke::new(&settings, &mesh);
let stamps = stroke.add(&ctx, Vec2::new(250.0, 180.0), 1.0);
// Copies as painting computed them before the plane could move: mirrors, then radial turns of each
let (lo, hi) = mesh.bounds();
let center = (lo + hi) * 0.5;
let source = stamps[0].center;
let mirrored = [Vec3::new(-1.0, 1.0, 1.0), Vec3::new(1.0, -1.0, 1.0), Vec3::new(-1.0, -1.0, 1.0)].map(|sign| center + (source - center) * sign);
let to_turn: Vec<Vec3> = std::iter::once(source).chain(mirrored).collect();
let turned = (1..3u8).flat_map(|copy| {
let turn = Quat::from_axis_angle(Vec3::Y, f32::from(copy) * std::f32::consts::TAU / 3.0);
to_turn.iter().map(move |point| center + turn * (*point - center)).collect::<Vec<_>>()
});
let expected: Vec<Vec3> = mirrored.into_iter().chain(turned).collect();
let copies: Vec<Vec3> = stamps[1..].iter().map(|stamp| stamp.center).collect();
assert_eq!(copies, expected);
}
#[test]
fn a_zero_angle_span_paints_no_radial_copies() {
let (mesh, bvh, camera) = ctx_parts();
let ctx = PickCtx { mesh: &mesh, bvh: &bvh, camera: &camera, viewport: Vec2::new(400.0, 400.0) };
let mut settings = BrushSettings::default();
settings.symmetry.radial = 6;
settings.symmetry.angle_span = 0.0;
let mut stroke = Stroke::new(&settings, &mesh);
// Six copies with no angle between them would all paint over the stroke
assert_eq!(stroke.add(&ctx, Vec2::new(250.0, 180.0), 1.0).len(), 1);
}
#[test]
fn radial_symmetry_spreads_copies_around_the_axis() {
let (m, b, c) = ctx_parts();
+126 -26
View File
@@ -113,6 +113,11 @@ pub struct GpuTracer {
env: Option<EnvGpu>,
materials: Option<Materials>,
acc: Option<Accum>,
/// Keep the preceding size so motion/full-resolution switches can reuse allocations.
spare_acc: Option<Accum>,
/// How many sets of accumulation buffers were allocated (for tests).
#[cfg(test)]
acc_allocations: u32,
scene: Option<SceneConst>,
bind: Option<wgpu::BindGroup>,
samples: u32,
@@ -309,6 +314,9 @@ impl GpuTracer {
env: None,
materials: None,
acc: None,
spare_acc: None,
#[cfg(test)]
acc_allocations: 0,
scene: None,
bind: None,
samples: 0,
@@ -323,6 +331,7 @@ impl GpuTracer {
/// Free the scene and accumulation memory, keeping the compiled pipelines.
pub fn release(&mut self) {
(self.geometry, self.env, self.materials, self.acc, self.scene, self.bind) = (None, None, None, None, None, None);
self.spare_acc = None;
self.samples = 0;
}
@@ -498,24 +507,42 @@ impl GpuTracer {
Ok(true)
}
/// Start over at `width × height` (the accumulation buffers are cleared or reallocated).
/// Start over at `width × height`, keeping the active render intact if allocation fails.
pub fn reset(&mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, width: u32, height: u32) -> Result<(), String> {
let (w, h) = (width.clamp(1, 8192), height.clamp(1, 8192));
self.samples = 0;
if let Some(a) = self.acc.as_ref().filter(|a| (a.width, a.height) == (w, h)) {
for b in &a.acc {
encoder.clear_buffer(b, 0, None);
let (width, height) = (width.clamp(1, 8192), height.clamp(1, 8192));
let bytes = u64::from(width) * u64::from(height) * 16;
let limits = device.limits();
// Reject unsupported sizes before invalidating the displayed render
if bytes > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) {
return Err(format!("a {width}×{height} render exceeds this GPU's buffer limit"));
}
if let Some(accumulation) = self.acc.as_ref().filter(|accumulation| (accumulation.width, accumulation.height) == (width, height)) {
for buffer in &accumulation.acc {
encoder.clear_buffer(buffer, 0, None);
}
self.samples = 0;
return Ok(());
}
self.acc = None;
self.bind = None;
let bytes = u64::from(w) * u64::from(h) * 16;
let limits = device.limits();
if bytes > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) {
return Err(format!("a {w}×{h} render exceeds this GPU's buffer limit"));
// Reused buffers must not retain samples from the previous view
if let Some(spare) = self.spare_acc.take_if(|accumulation| (accumulation.width, accumulation.height) == (width, height)) {
for buffer in spare.acc.iter().chain(&spare.illum) {
encoder.clear_buffer(buffer, 0, None);
}
self.spare_acc = self.acc.replace(spare);
self.bind = None;
self.samples = 0;
return Ok(());
}
let buf = |label| {
// Retire the obsolete spare before allocating, but keep the active render until success
self.spare_acc = None;
let create_buffer = |label| {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some(label),
size: bytes,
@@ -523,12 +550,20 @@ impl GpuTracer {
mapped_at_creation: false,
})
};
self.acc = Some(scoped(device, "GPU path tracing: accumulation buffers", || Accum {
width: w,
height: h,
acc: ["tc_acc_hit", "tc_acc_albedo", "tc_acc_normal", "tc_acc_env"].map(buf),
illum: ["tc_illum_a", "tc_illum_b"].map(buf),
})?);
let accumulation = scoped(device, "GPU path tracing: accumulation buffers", || Accum {
width,
height,
acc: ["tc_acc_hit", "tc_acc_albedo", "tc_acc_normal", "tc_acc_env"].map(create_buffer),
illum: ["tc_illum_a", "tc_illum_b"].map(create_buffer),
})?;
self.spare_acc = self.acc.replace(accumulation);
self.bind = None;
self.samples = 0;
#[cfg(test)]
{
self.acc_allocations += 1;
}
Ok(())
}
@@ -800,22 +835,87 @@ mod tests {
/// The radiance accumulation, read back.
fn accumulation(h: &Headless, t: &GpuTracer) -> Vec<[f32; 4]> {
let acc = t.acc.as_ref().unwrap();
let bytes = acc.width as u64 * acc.height as u64 * 16;
let staging = h.device.create_buffer(&wgpu::BufferDescriptor {
read_buffer(h, &t.acc.as_ref().unwrap().acc[0])
}
/// Read a completed buffer to check its contents across resets and reuse.
fn read_buffer(headless: &Headless, buffer: &wgpu::Buffer) -> Vec<[f32; 4]> {
let bytes = buffer.size();
let staging = headless.device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: bytes,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let mut enc = h.device.create_command_encoder(&Default::default());
enc.copy_buffer_to_buffer(&acc.acc[0], 0, &staging, 0, bytes);
h.queue.submit([enc.finish()]);
let mut encoder = headless.device.create_command_encoder(&Default::default());
encoder.copy_buffer_to_buffer(buffer, 0, &staging, 0, bytes);
headless.queue.submit([encoder.finish()]);
staging.slice(..).map_async(wgpu::MapMode::Read, |_| {});
h.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }).unwrap();
headless.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }).unwrap();
bytemuck::cast_slice(&staging.slice(..).get_mapped_range().unwrap()).to_vec()
}
/// Two cached sizes reuse cleared buffers, and leaving Rendering mode releases both.
#[test]
fn switching_between_two_sizes_reuses_the_accumulation_buffers() {
let Some((headless, mut tracer)) = gpu() else { return };
for (width, height) in [(64, 48), (32, 24), (64, 48), (32, 24), (64, 48)] {
let mut encoder = headless.device.create_command_encoder(&Default::default());
tracer.reset(&headless.device, &mut encoder, width, height).unwrap();
headless.queue.submit([encoder.finish()]);
let accumulation = tracer.acc.as_ref().unwrap();
assert_eq!((accumulation.width, accumulation.height), (width, height));
assert_eq!(tracer.samples(), 0);
for buffer in accumulation.acc.iter().chain(&accumulation.illum) {
assert!(read_buffer(&headless, buffer).iter().all(|pixel| *pixel == [0.0; 4]), "reused buffers must be cleared");
// Leave nonzero contents to detect stale pixels on the next reuse
let pixels = vec![[1.0f32; 4]; (width * height) as usize];
headless.queue.write_buffer(buffer, 0, bytemuck::cast_slice(&pixels));
}
tracer.samples = 7;
}
assert_eq!(tracer.acc_allocations, 2, "two sizes, two allocations, however often it switches");
let mut encoder = headless.device.create_command_encoder(&Default::default());
tracer.reset(&headless.device, &mut encoder, 16, 16).unwrap();
headless.queue.submit([encoder.finish()]);
assert_eq!(tracer.acc_allocations, 3, "a third size allocates (and drops the oldest set)");
tracer.release();
assert!(tracer.acc.is_none() && tracer.spare_acc.is_none(), "leaving Rendering mode frees both sizes");
}
/// Rejecting an oversized render preserves the image and lets tracing continue.
#[test]
fn failed_reset_retains_the_active_render() {
let Some((mut headless, mut tracer)) = gpu() else { return };
let scene = sphere_scene(&mut headless, crate::ibl::environment("Studio Soft", 32), &WHITE);
let camera = camera();
let settings = TraceSettings::default();
let display = TraceDisplay::from_display(&Default::default());
tracer.render(&headless.device, &headless.queue, &headless.renderer, &scene, &camera, &settings, &display, [32, 24], 2).unwrap();
let before = accumulation(&headless, &tracer);
let mut encoder = headless.device.create_command_encoder(&Default::default());
let error = tracer.reset(&headless.device, &mut encoder, 8192, 8192).unwrap_err();
assert!(error.contains("exceeds this GPU's buffer limit"));
assert!(tracer.acc.is_some(), "a rejected resize must keep the active buffers");
assert!(tracer.bind.is_some(), "a rejected resize must keep the active bindings");
assert_eq!(tracer.samples(), 2, "a rejected resize must keep the accumulated samples");
assert_eq!(accumulation(&headless, &tracer), before);
assert!(tracer.pass(&headless.device, &headless.queue, &mut encoder, &camera, &settings, 1));
let output = GpuTracer::output_texture(&headless.device, 32, 24);
assert!(tracer.resolve(&headless.device, &headless.queue, &mut encoder, &display, &output.create_view(&Default::default())));
headless.queue.submit([encoder.finish()]);
assert!(crate::readback::Readback::blocking(&headless.device, &headless.queue, &output).is_some());
assert_eq!(tracer.samples(), 3);
}
const WHITE: [(Channel, [f32; 3]); 3] = [(Channel::BaseColor, [1.0; 3]), (Channel::Metallic, [0.0; 3]), (Channel::Roughness, [0.5; 3])];
#[test]
+2
View File
@@ -24,6 +24,7 @@ pub mod headless;
mod high_poly_gpu;
pub mod ibl;
pub mod mesh_maps;
pub mod overlay_quad;
pub mod readback;
pub mod renderer;
pub mod set_highlight;
@@ -32,6 +33,7 @@ pub mod trace;
mod uv_seam_gpu;
pub use bake_visualization::BakeVisualization;
pub use overlay_quad::OverlayQuad;
pub use renderer::{COLOR_FORMAT, Frame, MSAA, Renderer, Shade, ViewKind, aux_size, uv_view_scale};
pub use set_highlight::SetHighlight;
pub use wgpu;
+13
View File
@@ -26,6 +26,19 @@ pub fn mesh_map_rgba(baked: Option<&BakedMaps>, m: BakedMap, size: u32, working_
out
}
/// RGBA8 of the neutral value of map `m` (what a map not baked yet shows during a bake: flat
/// normals, white occlusion, mid-gray height ...), `size × size`, encoded like [`mesh_map_rgba`].
pub fn neutral_rgba(m: BakedMap, size: u32) -> Vec<u8> {
let value = m.neutral();
let pixel = [0, 1, 2].map(|k| (value[k].clamp(0.0, 1.0) * 255.0 + 0.5) as u8);
let size = size.max(1);
let mut out = Vec::with_capacity((size * size * 4) as usize);
for _ in 0..size * size {
out.extend_from_slice(&[pixel[0], pixel[1], pixel[2], 255]);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
+11
View File
@@ -0,0 +1,11 @@
//! See-through quads drawn into the 3D view and hidden where the mesh is in front (the symmetry plane and lines)
use texturecraft_geom::glam::Vec3;
/// A flat quad with its corners in order, in a screen color (linear RGB) and opacity
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct OverlayQuad {
pub corners: [Vec3; 4],
pub color: [f32; 3],
pub opacity: f32,
}
+84
View File
@@ -35,6 +35,7 @@ use crate::cage_gpu::CageGpu;
use crate::gpu_trace::{Checked, checked};
use crate::high_poly_gpu::HighPolyGpu;
use crate::ibl;
use crate::overlay_quad::OverlayQuad;
use crate::set_highlight::SetHighlight;
use crate::subdivide::{self, Vertex};
use crate::uv_seam_gpu::UvSeamGpu;
@@ -289,6 +290,8 @@ pub struct Frame {
pub shade: Shade,
/// Visibility per texture set.
pub visible: Vec<bool>,
/// See-through quads in the 3D view, hidden behind the mesh
pub overlay: Vec<OverlayQuad>,
}
struct Tex {
@@ -499,6 +502,9 @@ struct ViewTargets {
behind: Option<Behind>,
blit_buf: wgpu::Buffer,
blit_bg: wgpu::BindGroup,
/// The frame's overlay triangles and how many vertices of the buffer they use
overlay: Option<wgpu::Buffer>,
overlay_vertices: u32,
/// Set by [`Renderer::prepare`]: the view has content to blit.
ready: bool,
}
@@ -535,6 +541,7 @@ pub struct Renderer {
uv_pipeline: wgpu::RenderPipeline,
wire_pipeline: wgpu::RenderPipeline,
wire3d_pipeline: wgpu::RenderPipeline,
overlay_pipeline: wgpu::RenderPipeline,
/// The highlighted set's mesh edges, wider and in the highlight color
highlight_pipeline: wgpu::RenderPipeline,
/// Bake mode: the high poly, the cage's faces and wireframe, the low poly's UV seams
@@ -997,6 +1004,8 @@ impl Renderer {
let uv_seam_pipeline =
pipeline(device, "tc_uv_seam", &layout, &module, "vs_wire3d", &vertex_layout, hdr_target("fs_wire_uv_seam", blend), MSAA, wire3d_depth.clone());
let bg_pipeline = pipeline(device, "tc_bg", &background_layout, &module, "vs_bg", &[], hdr_target("fs_bg", None), MSAA, always());
let overlay_pipeline =
pipeline(device, "tc_overlay", &background_layout, &module, "vs_overlay", &vertex_layout, hdr_target("fs_overlay", blend), MSAA, wire3d_depth);
let blit_pipeline = pipeline(device, "tc_blit", &blit_layout, &util_module, "vs_blit", &[], Some(("fs_blit", target_format, None)), 1, None);
let post_pipeline = pipeline(device, "tc_post", &effect_layout, &post_module, "vs_full", &[], Some(("fs_post", COLOR_FORMAT, None)), 1, None);
let bloom_pipelines = [("fs_bloom_pre", None), ("fs_bloom_down", None), ("fs_bloom_up", Some(ADDITIVE))].map(|(fragment_entry_point, blend)| {
@@ -1121,6 +1130,7 @@ impl Renderer {
uv_pipeline,
wire_pipeline,
wire3d_pipeline,
overlay_pipeline,
highlight_pipeline,
bake_high_pipeline,
cage_pipeline,
@@ -1675,6 +1685,8 @@ impl Renderer {
behind: None,
blit_buf,
blit_bg,
overlay: None,
overlay_vertices: 0,
ready: false,
}
}
@@ -1938,6 +1950,7 @@ impl Renderer {
let Some(v) = self.targets(device, frame.view_id, frame.size, bloom, fx_on, refraction) else { return };
queue.write_buffer(&v.globals, 0, bytemuck::bytes_of(&raw));
queue.write_buffer(&v.post_buf, 0, bytemuck::bytes_of(&post));
upload_overlay(device, queue, v, &frame.overlay, (!data).then_some(s.exposure_ev));
v.ready = true;
v.history = Some((frame.clone(), rev));
v.samples = sample;
@@ -2160,6 +2173,15 @@ impl Renderer {
if let Some(bake) = bake {
self.draw_bake(&mut pass, mesh, frame, bake);
}
// Overlay quads last, so the mesh's depth hides what is behind it
if uv_set.is_none()
&& let Some(overlay) = targets.overlay.as_ref().filter(|_| targets.overlay_vertices > 0)
{
pass.set_pipeline(&self.overlay_pipeline);
pass.set_vertex_buffer(0, overlay.slice(..));
pass.draw(0..targets.overlay_vertices, 0..1);
}
}
/// Bake mode's high poly, UV seams and cages over the low poly `low_poly`
@@ -2261,6 +2283,51 @@ fn drawable_ranges<'a>(
})
}
/// A quad's two triangles, as corner indices
const QUAD_TRIANGLES: [usize; 6] = [0, 1, 2, 0, 2, 3];
/// Write `quads` into the view's overlay buffer, colors divided by the exposure only (undoing ACES makes saturated colors overshoot)
fn upload_overlay(device: &wgpu::Device, queue: &wgpu::Queue, view: &mut ViewTargets, quads: &[OverlayQuad], exposure_ev: Option<f32>) {
view.overlay_vertices = 0;
let Some(vertex_count) = quads.len().checked_mul(QUAD_TRIANGLES.len()).and_then(|count| u32::try_from(count).ok()) else {
log::warn!("Symmetry overlay has too many vertices; hide the intersection or use a simpler mesh");
return;
};
// A valid imported mesh can produce more intersection vertices than the GPU accepts
let byte_count = u64::from(vertex_count) * std::mem::size_of::<Vertex>() as u64;
if byte_count > device.limits().max_buffer_size {
log::warn!("Symmetry overlay exceeds the GPU buffer limit; hide the intersection or use a simpler mesh");
return;
}
if vertex_count == 0 {
return;
}
let vertices: Vec<Vertex> = quads
.iter()
.flat_map(|quad| {
let [r, g, b] = exposure_ev.map_or(quad.color, |exposure_ev| crate::set_highlight::scene_color_showing(quad.color, exposure_ev, false));
let vertex = |corner: Vec3| Vertex { pos: corner.to_array(), nrm: [0.0; 3], tan: [r, g, b, quad.opacity], uv: [0.0; 2] };
QUAD_TRIANGLES.map(|corner| vertex(quad.corners[corner]))
})
.collect();
let bytes: &[u8] = bytemuck::cast_slice(&vertices);
if view.overlay.as_ref().is_none_or(|buffer| buffer.size() < bytes.len() as u64) {
view.overlay = Some(device.create_buffer(&wgpu::BufferDescriptor {
label: Some("tc_overlay"),
size: bytes.len() as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
}));
}
if let Some(buffer) = &view.overlay {
queue.write_buffer(buffer, 0, bytes);
view.overlay_vertices = vertex_count;
}
}
/// Globals `highlight`: the highlight's color and opacity, all zero without one. Data views skip exposure and tone mapping, so they take the color as it is
fn highlight_globals(shade: &Shade, data: bool) -> [f32; 4] {
let Some(highlight) = shade.highlight else { return [0.0; 4] };
@@ -2282,6 +2349,23 @@ mod tests {
use super::*;
use crate::headless::Headless;
#[test]
fn oversized_overlays_leave_the_view_usable() {
let Ok(mut headless) = Headless::new() else { return };
let limit = headless.device.limits().max_buffer_size as usize;
let count = limit / (QUAD_TRIANGLES.len() * std::mem::size_of::<Vertex>()) + 1;
let quad = OverlayQuad { corners: [Vec3::ZERO; 4], color: [1.0, 0.0, 0.0], opacity: 0.5 };
let quads = vec![quad; count];
let view = headless.renderer.targets(&headless.device, 1, [32, 32], false, false, false).unwrap();
upload_overlay(&headless.device, &headless.queue, view, &[quad], None);
upload_overlay(&headless.device, &headless.queue, view, &quads, None);
assert_eq!(view.overlay_vertices, 0, "skip overlays beyond the device limit");
upload_overlay(&headless.device, &headless.queue, view, &[quad], None);
assert_eq!(view.overlay_vertices, 6, "the next frame can draw its overlay");
}
/// A headless renderer with one 256² texture set, and the base color slot's full-size
/// texture handed over as WebGPU would: allocated, with its verdict still to come.
fn awaiting() -> Option<(Headless, std::sync::mpsc::Sender<Option<String>>)> {
+13 -8
View File
@@ -17,17 +17,22 @@ pub struct SetHighlight {
impl SetHighlight {
/// The scene color the lines are drawn with so that exposure `exposure_ev` and the tone curve (ACES when `aces`) show them in [`Self::color`]
pub fn scene_color(&self, exposure_ev: f32, aces: bool) -> [f32; 3] {
let exposure = 2f32.powf(exposure_ev).max(f32::MIN_POSITIVE);
self.color.map(|screen| {
let screen = screen.max(0.0);
let exposed = if aces { inverse_aces(screen.min(MAX_ACES_SCREEN_VALUE)) } else { screen };
exposed / exposure
})
scene_color_showing(self.color, exposure_ev, aces)
}
}
/// The scene color that exposure `exposure_ev` and the tone curve (ACES when `aces`) show as `screen` (linear RGB)
pub(crate) fn scene_color_showing(screen: [f32; 3], exposure_ev: f32, aces: bool) -> [f32; 3] {
let exposure = 2f32.powf(exposure_ev).max(f32::MIN_POSITIVE);
screen.map(|screen| {
let screen = screen.max(0.0);
let exposed = if aces { inverse_aces(screen.min(MAX_ACES_SCREEN_VALUE)) } else { screen };
exposed / exposure
})
}
/// The input of post.wgsl's `aces` that gives `screen`: the positive root of its rational curve solved for the input
fn inverse_aces(screen: f32) -> f32 {
let (a, b, c) = (2.43 * screen - 2.51, 0.59 * screen - 0.03, 0.14 * screen);
+20
View File
@@ -682,6 +682,26 @@ fn fs_wire3d(i: VOut) -> @location(0) vec4<f32> {
return vec4<f32>(0.35, 0.35, 0.35, 0.45);
}
// How far overlay quads move toward the eye, as a fraction of their distance (as the wireframe does)
const OVERLAY_TOWARD_EYE: f32 = 0.002;
// See-through overlay quads (the symmetry plane and the lines on the mesh): the color comes in the tangent slot, nudged toward the eye like the wireframe so lines on the surface win the depth test
@vertex
fn vs_overlay(v: VIn) -> VOut {
var o: VOut;
o.wpos = v.pos;
o.nrm = v.nrm;
o.tan = v.tan;
o.uv = v.uv;
o.clip = g.view_proj * vec4<f32>(v.pos + (g.eye.xyz - v.pos) * OVERLAY_TOWARD_EYE, 1.0);
return o;
}
@fragment
fn fs_overlay(i: VOut) -> @location(0) vec4<f32> {
return i.tan;
}
// The highlighted set's edges: four copies of each line, shifted to the corners of the extra width, make it wider than one pixel
@vertex
fn vs_wire_highlight(v: VIn, @builtin(instance_index) copy: u32) -> VOut {
+37 -32
View File
@@ -65,29 +65,31 @@ fn on_edge(verts: &[Vertex], (p, q): (u32, u32), k: u32, n: u32) -> Option<Verte
/// Split the triangles of `indices` (index ranges `draws`: first, count, material) `level`
/// times. Returns the vertices, indices and the draws over them.
pub(crate) fn subdivide(verts: &[Vertex], indices: &[u32], draws: &[Draw], level: u32) -> (Vec<Vertex>, Vec<u32>, Vec<Draw>) {
let n = 1u32 << level.min(MAX_LEVEL);
let (mut out_v, mut out_i, mut out_d) = (Vec::new(), Vec::new(), Vec::new());
pub(crate) fn subdivide(vertices: &[Vertex], indices: &[u32], draws: &[Draw], level: u32) -> (Vec<Vertex>, Vec<u32>, Vec<Draw>) {
let segments = 1u32 << level.min(MAX_LEVEL);
let (mut output_vertices, mut output_indices, mut output_draws) = (Vec::new(), Vec::new(), Vec::new());
for &(start, count, material) in draws {
let first = out_i.len() as u32;
let tris = indices.get(start as usize..(start as usize).saturating_add(count as usize)).unwrap_or_default();
for t in tris.chunks_exact(3) {
let (Some(a), Some(b), Some(c)) = (verts.get(t[0] as usize), verts.get(t[1] as usize), verts.get(t[2] as usize)) else { continue };
let base = out_v.len() as u32;
// Grid point (i, j), i + j <= n, row by row: row j holds n + 1 - j points. Points on
// the edges are computed the same way from both triangles sharing the edge (no cracks).
for j in 0..=n {
for i in 0..=n - j {
let first = output_indices.len() as u32;
let triangles = indices.get(start as usize..(start as usize).saturating_add(count as usize)).unwrap_or_default();
for t in triangles.as_chunks::<3>().0 {
let (Some(a), Some(b), Some(c)) = (vertices.get(t[0] as usize), vertices.get(t[1] as usize), vertices.get(t[2] as usize)) else { continue };
let base = output_vertices.len() as u32;
// Row j holds segments + 1 - j points inside the triangle
// Shared edges use identical interpolation in both triangles to prevent cracks
for j in 0..=segments {
for i in 0..=segments - j {
let edge = match (i, j) {
(_, 0) => Some(((t[0], t[1]), i)),
(0, _) => Some(((t[0], t[2]), j)),
_ if i + j == n => Some(((t[1], t[2]), j)),
_ if i + j == segments => Some(((t[1], t[2]), j)),
_ => None,
};
let p = match edge.and_then(|(ends, k)| on_edge(verts, ends, k, n)) {
let p = match edge.and_then(|(ends, k)| on_edge(vertices, ends, k, segments)) {
Some(p) => p,
None => {
let w = [1.0 - (i + j) as f32 / n as f32, i as f32 / n as f32, j as f32 / n as f32];
let w = [1.0 - (i + j) as f32 / segments as f32, i as f32 / segments as f32, j as f32 / segments as f32];
Vertex {
pos: mix(a.pos, b.pos, c.pos, w),
nrm: mix(a.nrm, b.nrm, c.nrm, w),
@@ -96,39 +98,42 @@ pub(crate) fn subdivide(verts: &[Vertex], indices: &[u32], draws: &[Draw], level
}
}
};
out_v.push(Vertex { tan: [p.tan[0], p.tan[1], p.tan[2], a.tan[3]], ..p });
output_vertices.push(Vertex { tan: [p.tan[0], p.tan[1], p.tan[2], a.tan[3]], ..p });
}
}
let at = |i: u32, j: u32| base + j * (n + 1) - j * j.saturating_sub(1) / 2 + i;
for j in 0..n {
for i in 0..n - j {
out_i.extend_from_slice(&[at(i, j), at(i + 1, j), at(i, j + 1)]);
if i + j + 1 < n {
out_i.extend_from_slice(&[at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)]);
let at = |i: u32, j: u32| base + j * (segments + 1) - j * j.saturating_sub(1) / 2 + i;
for j in 0..segments {
for i in 0..segments - j {
output_indices.extend_from_slice(&[at(i, j), at(i + 1, j), at(i, j + 1)]);
if i + j + 1 < segments {
output_indices.extend_from_slice(&[at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)]);
}
}
}
}
out_d.push((first, out_i.len() as u32 - first, material));
output_draws.push((first, output_indices.len() as u32 - first, material));
}
(out_v, out_i, out_d)
(output_vertices, output_indices, output_draws)
}
/// World length per unit of UV over the whole mesh (the square root of their area ratio): how
/// far a height change moves the surface for the slope height-to-normal shows.
pub(crate) fn world_per_uv(verts: &[Vertex], indices: &[u32]) -> Option<f32> {
let (mut world, mut uv) = (0.0f64, 0.0f64);
for t in indices.chunks_exact(3) {
let (Some(a), Some(b), Some(c)) = (verts.get(t[0] as usize), verts.get(t[1] as usize), verts.get(t[2] as usize)) else { continue };
pub(crate) fn world_per_uv(vertices: &[Vertex], indices: &[u32]) -> Option<f32> {
let (mut world_area, mut uv_area) = (0.0f64, 0.0f64);
for t in indices.as_chunks::<3>().0 {
let (Some(a), Some(b), Some(c)) = (vertices.get(t[0] as usize), vertices.get(t[1] as usize), vertices.get(t[2] as usize)) else { continue };
let d = |p: [f32; 3], q: [f32; 3]| [f64::from(q[0] - p[0]), f64::from(q[1] - p[1]), f64::from(q[2] - p[2])];
let (e1, e2) = (d(a.pos, b.pos), d(a.pos, c.pos));
let cross = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]];
world += (cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]).sqrt() * 0.5;
world_area += (cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]).sqrt() * 0.5;
let (u1, u2) = ([b.uv[0] - a.uv[0], b.uv[1] - a.uv[1]], [c.uv[0] - a.uv[0], c.uv[1] - a.uv[1]]);
uv += f64::from(u1[0] * u2[1] - u1[1] * u2[0]).abs() * 0.5;
uv_area += f64::from(u1[0] * u2[1] - u1[1] * u2[0]).abs() * 0.5;
}
let r = (world / uv).sqrt() as f32;
(uv > 1e-12 && r.is_finite() && r > 0.0).then_some(r)
let scale = (world_area / uv_area).sqrt() as f32;
(uv_area > 1e-12 && scale.is_finite() && scale > 0.0).then_some(scale)
}
#[cfg(test)]
+16 -2
View File
@@ -66,6 +66,9 @@ pub struct TraceScene {
pub lens: Option<[f32; 2]>,
}
/// Width of the built-in environments traced (texels).
const ENV_SIZE: u32 = 1024;
impl TraceScene {
pub fn new(mesh: Arc<Mesh>, bvh: Arc<Bvh>, sets: Vec<TraceSet>, env: Arc<EnvImage>, env_rotation: f32) -> TraceScene {
let mut tri_set = vec![usize::MAX; mesh.triangle_count()];
@@ -114,13 +117,24 @@ impl TraceScene {
/// The scene as `display` shows it: the imported environment `env_image` (when the display
/// names a resource and it decodes) or the built-in one, its rotation and the shading mode.
pub fn for_display(mesh: Arc<Mesh>, bvh: Arc<Bvh>, sets: Vec<TraceSet>, display: &DisplaySettings, env_image: Option<&ImageRes>) -> TraceScene {
TraceScene::for_display_env(mesh, bvh, sets, display, Arc::new(TraceScene::display_env(display, env_image)))
}
/// The environment [`TraceScene::for_display`] traces under (building it takes a while: a
/// caller that rebuilds scenes often keeps it and passes it to [`TraceScene::for_display_env`]).
pub fn display_env(display: &DisplaySettings, env_image: Option<&ImageRes>) -> EnvImage {
let imported = env_image.and_then(|i| EnvImage::from_rgba(i.width, i.height, &i.rgba, i.srgb));
let env = imported.unwrap_or_else(|| crate::ibl::environment(&display.environment, 1024));
let mut scene = TraceScene::new(mesh, bvh, sets, Arc::new(env), display.env_rotation.to_radians());
imported.unwrap_or_else(|| crate::ibl::environment(&display.environment, ENV_SIZE))
}
/// [`TraceScene::for_display`] under `env`, from [`TraceScene::display_env`] of the same display.
pub fn for_display_env(mesh: Arc<Mesh>, bvh: Arc<Bvh>, sets: Vec<TraceSet>, display: &DisplaySettings, env: Arc<EnvImage>) -> TraceScene {
let mut scene = TraceScene::new(mesh, bvh, sets, env, display.env_rotation.to_radians());
scene.spec_gloss = display.spec_gloss;
scene.set_scatter(display.scatter_color, display.scatter_radius);
scene.ior = display.ior;
scene.lens = display.dof.enabled.then_some([display.dof.focus_distance, display.dof.aperture]);
scene
}
+2 -1
View File
@@ -59,7 +59,8 @@ fn setup() -> Option<(Headless, Frame)> {
let mut cam = OrbitCamera { yaw: 0.6, pitch: 0.25, ..OrbitCamera::default() };
let (lo, hi) = mesh.bounds();
cam.frame(lo, hi);
let frame = Frame { view_id: 1, size: [480, 360], kind: ViewKind::Scene, camera: cam, shade: Shade::default(), visible: vec![true, true] };
let frame =
Frame { view_id: 1, size: [480, 360], kind: ViewKind::Scene, camera: cam, shade: Shade::default(), visible: vec![true, true], overlay: Vec::new() };
Some((h, frame))
}
+2
View File
@@ -55,4 +55,6 @@ web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "H
eframe = { workspace = true, features = ["x11"] }
# Offscreen pictures of the whole window (tests/ui_snapshots.rs).
egui_kittest = { version = "0.37", features = ["wgpu", "eframe"] }
# Fallible setup of the exact GPU device used by rendering regression tests.
pollster = "0.4"
image = { workspace = true }
+8
View File
@@ -0,0 +1,8 @@
use crate::RunningBake;
/// A background bake of one or more texture sets.
pub struct BakeJob {
pub queue: Vec<usize>,
pub current: Option<RunningBake>,
pub total: usize,
}
+48
View File
@@ -184,16 +184,64 @@ fn edit_settings(
app.run("bake.settings", json!({ "ts": texture_sets, "patch": patch }));
}
/// What the 3D view shows while a bake runs: the newest finished map, one finished map or the material
fn preview_control(app: &mut TextureCraftApp, ui: &mut Ui) {
use texturecraft_engine::PreviewShow;
let Some(preview) = app.session.bake_preview.as_ref() else { return };
let show = preview.show;
// Finished maps of the set baking now can be pinned; the others are still neutral
let rows: Vec<(BakedMap, bool)> =
preview.current_set().map(|set| set.order.iter().map(|&map| (map, set.baked.maps.contains_key(&map))).collect()).unwrap_or_default();
let text = match show {
PreviewShow::Follow => tr("Follow Newest Map").to_owned(),
PreviewShow::Material => tr("Material").to_owned(),
PreviewShow::Pin(map) => trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(map)))]),
};
let mut choice = None;
egui::ComboBox::from_id_salt("bake_preview_show")
.selected_text(text)
.show_ui(ui, |ui| {
if ui.selectable_label(show == PreviewShow::Follow, tr("Follow Newest Map")).clicked() {
choice = Some(PreviewShow::Follow);
}
for (map, done) in rows {
let label = trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(map)))]);
if ui.add_enabled(done, egui::Button::selectable(show == PreviewShow::Pin(map), label)).clicked() {
choice = Some(PreviewShow::Pin(map));
}
}
if ui.selectable_label(show == PreviewShow::Material, tr("Material")).clicked() {
choice = Some(PreviewShow::Material);
}
})
.response
.on_hover_text(tr(
"What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.",
));
if let Some(show) = choice {
app.run("bake.preview", json!({ "show": show.id() }));
}
}
pub(crate) fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context, viewport: egui::Rect) {
egui::Area::new(egui::Id::unique("bake_bar")).constrain_to(viewport).anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -16.0)).default_width(0.0).show(
ctx,
|ui| {
if let Some(status) = app.bake_status() {
ui.vertical_centered(|ui| ui.label(egui::RichText::new(status).strong()));
}
ui.horizontal(|ui| {
if let Some(progress) = app.bake_progress() {
ui.add(egui::ProgressBar::new(progress).desired_width(220.0).show_percentage());
if ui.button(tr("Cancel")).clicked() {
app.cancel_bake();
}
preview_control(app, ui);
} else {
let texture_sets: Vec<usize> = app
.session
+39
View File
@@ -73,6 +73,7 @@ pub(crate) fn encode_png(w: u32, h: u32, rgba: Vec<u8>) -> Option<(u32, u32, Vec
}
pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, p: &Value) -> Value {
app.ui.prefs.apply_resource_limits();
match method {
"ping" => ok(json!("pong")),
"ui.resize" => {
@@ -110,9 +111,46 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, p: &
"uiMs": app.ui_ms,
"titleBar": app.title_bar.name(),
"baking": app.bake_progress(),
"bakeStatus": app.bake_status(),
"bakePreview": texturecraft_engine::bake_preview::preview_json(&app.session),
"toasts": app.toasts.iter().map(|t| json!({"text": t.text, "error": t.error})).collect::<Vec<_>>(),
}))
}
"ui.bake.start" => {
// Bake in the background like the Bake button: the 3D view shows the maps as they finish
let count = app.session.doc.project.texture_sets.len();
let sets: Vec<usize> = match p.get("ts") {
Some(value) => match serde_json::from_value::<Vec<usize>>(if value.is_array() { value.clone() } else { json!([value]) }) {
Ok(list) if list.iter().all(|&index| index < count) => list,
_ => return err(format!("`ts` must be texture set indices below {count}")),
},
None => app
.session
.doc
.project
.texture_sets
.iter()
.enumerate()
.filter(|(_, texture_set)| texture_set.bake.common.is_enabled)
.map(|(index, _)| index)
.collect(),
};
if app.bake.is_some() {
return err("a bake is already running");
}
if sets.is_empty() {
return err("no texture set to bake: tick one in Bake mode or pass `ts`");
}
app.ui.mode = crate::state::Mode::Baking;
app.start_bake(sets);
ok(texturecraft_engine::bake_preview::preview_json(&app.session))
}
"ui.bake.cancel" => {
app.cancel_bake();
ok(Value::Null)
}
"ui.menu.list" => ok(json!(
crate::menus::CATALOG
.iter()
@@ -141,6 +179,7 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, p: &
match serde_json::from_value(cur) {
Ok(ui) => {
app.ui = ui;
app.ui.prefs.apply_resource_limits();
ok(Value::Null)
}
Err(e) => err(format!("invalid UI state: {e}")),
+130
View File
@@ -0,0 +1,130 @@
//! A shelf image dropped on the 3D view waits for a menu pick at the drop point: a mask, or a channel of the texture set under it
use egui::{Id, Pos2, Ui, Vec2};
use serde_json::json;
use texturecraft_engine::geom::OrbitCamera;
use crate::TextureCraftApp;
use crate::i18n::tr;
/// What the menu offers besides the texture set's channels: a new fill layer masked by the image
const MASK_CHOICE: &str = "mask";
/// The most of the window's height the channel list takes before it scrolls
const MENU_MAX_HEIGHT_SHARE: f32 = 0.6;
/// An image dropped on the 3D view, placed as a decal once the menu at the drop point is picked
#[derive(Clone)]
pub struct DecalDrop {
/// The image resource
pub image: String,
/// The texture set under the drop point
pub texture_set: usize,
/// The drop point in view pixels
pub view_position: Vec2,
/// The 3D view's size in pixels
pub view_size: Vec2,
/// The camera used to pick the drop point
pub camera: OrbitCamera,
/// The drop point on screen, where the menu opens
pub screen_position: Pos2,
}
impl DecalDrop {
/// Where the waiting drop and its menu's state are kept
fn menu_id() -> Id {
Id::unique("decal_drop_menu")
}
/// Open the menu for this drop (replacing any other waiting drop): it stays open while the drop waits
pub fn open(self, ui: &Ui) {
let frame = ui.ctx().cumulative_frame_nr();
ui.ctx().data_mut(|data| data.insert_temp(Self::menu_id(), (self, frame)));
}
/// Keep input out of both views while the menu waits and for the rest of its closing frame
pub fn blocks_input(ctx: &egui::Context) -> bool {
Self::current(ctx).is_some() || ctx.data(|data| data.get_temp::<u64>(Self::menu_id().with("closed_frame"))) == Some(ctx.cumulative_frame_nr())
}
/// The waiting drop; one whose menu went undrawn for a frame (the 3D view was hidden) is dropped instead of blocking the views
fn current(ctx: &egui::Context) -> Option<DecalDrop> {
let frame = ctx.cumulative_frame_nr();
let (drop, menu_frame) = ctx.data(|data| data.get_temp::<(DecalDrop, u64)>(Self::menu_id()))?;
if frame > menu_frame + 1 {
ctx.data_mut(|data| data.remove::<(DecalDrop, u64)>(Self::menu_id()));
return None;
}
Some(drop)
}
/// Close the menu and consume the rest of this frame's input
fn close(ctx: &egui::Context) {
let id = Self::menu_id();
let frame = ctx.cumulative_frame_nr();
// The 2D view reads input after this menu closes in the 3D view
ctx.data_mut(|data| {
data.remove::<(DecalDrop, u64)>(id);
data.insert_temp(id.with("closed_frame"), frame);
});
}
/// Show the waiting drop's menu over the 3D view `response`; a pick places the decal, a click elsewhere drops nothing
pub fn show_menu(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response) {
let id = Self::menu_id();
let Some(drop) = Self::current(ui.ctx()) else { return };
// Saved view pixels must not be picked through a different camera
if drop.camera != app.session.camera {
Self::close(ui.ctx());
return;
}
let frame = ui.ctx().cumulative_frame_nr();
ui.ctx().data_mut(|data| data.insert_temp(id, (drop.clone(), frame)));
let channels = app.session.doc.project.texture_set(drop.texture_set).map(|set| set.channel_list()).unwrap_or_default();
let mut picked = None;
let shown = egui::Popup::new(id, ui.ctx().clone(), egui::PopupAnchor::Position(drop.screen_position), response.layer_id)
.kind(egui::PopupKind::Menu)
.layout(egui::Layout::top_down_justified(egui::Align::Min))
.style(egui::containers::menu::menu_style)
.open(true)
.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
.show(|ui| {
if ui.button(tr("Mask")).clicked() {
picked = Some(MASK_CHOICE);
}
ui.separator();
// Many channels scroll instead of running off the window
let max_height = ui.ctx().content_rect().height() * MENU_MAX_HEIGHT_SHARE;
egui::ScrollArea::vertical().max_height(max_height).show(ui, |ui| {
for channel in channels {
if ui.button(tr(channel.label())).clicked() {
picked = Some(channel.id());
}
}
});
});
if picked.is_some() || shown.is_none_or(|menu| menu.response.should_close()) {
Self::close(ui.ctx());
}
let Some(channel) = picked else { return };
app.run(
"layer.add.decal",
json!({
"image": drop.image,
"channel": channel,
"x": drop.view_position.x,
"y": drop.view_position.y,
"viewport": [drop.view_size.x, drop.view_size.y],
}),
);
}
}
+462 -212
View File
@@ -4,20 +4,23 @@
use egui::{Color32, Rect, RichText, Sense, Stroke, Ui, pos2, vec2};
use egui_phosphor::regular as ic;
use serde_json::{Value, json};
use texturecraft_engine::compose::ThumbTarget;
use texturecraft_engine::core::{
BakedMap, BlendMode, Channel, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerId, LayerKind,
LinkParam, MaterialLink, ProceduralKind, Projection, Source,
};
use texturecraft_engine::filter_lib::scalar_params;
use texturecraft_engine::paint::{BrushAlpha, alphas};
use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas};
use texturecraft_engine::{CloneFrom, StackTarget, Tool};
use crate::TextureCraftApp;
use crate::i18n::{n_, tr, trf};
use crate::layer_panel::{effect_preview_size, effect_row_height, layer_preview_size, layer_row_height};
use crate::shelf::{Asset, ShelfDrag};
use crate::state::PropsTab;
use crate::theme::{Tokens, caption};
use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, histogram, icon_button, section, slider, slider_edit};
use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE};
use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, section, section_with_reset, slider, slider_edit};
/// The filter Add filter adds: at its defaults it changes nothing, and its slot opens the picker to swap it
const NEW_FILTER: &str = "hsl";
@@ -175,9 +178,12 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) {
ui.add_space(2.0);
let ts = app.session.ts();
let stack: Vec<LayerId> = app.session.doc.project.texture_sets.get(ts).map(|t| t.stack.iter().rev().copied().collect()).unwrap_or_default();
let now = ui.input(|i| i.time);
app.layer_panel.begin(&app.session, now);
egui::ScrollArea::vertical().id_salt("layers_scroll").auto_shrink([false, false]).show(ui, |ui| {
let mut count = 0;
for id in stack {
layer_tree(app, ui, id, 0);
layer_tree(app, ui, id, 0, &mut count);
}
// Click on empty space deselects nothing; the space below the rows drops at the bottom.
let free = ui.available_height();
@@ -202,6 +208,7 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) {
ui.painter().line_segment([rect.left_top(), rect.right_top()], Stroke::new(2.0, tk.accent));
}
});
app.layer_panel.end(ui.ctx(), &app.session);
}
/// Whether the selection targets the layer content (the content or one of its effects) rather
@@ -254,49 +261,134 @@ fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) {
}
}
fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize) {
/// Layer rows alternate between two shades so neighbours read as separate items.
fn row_shade(tk: &Tokens, index: usize) -> Color32 {
if index.is_multiple_of(2) { tk.row } else { tk.row.lerp_to_gamma(tk.row_hover, 0.45) }
}
/// Width of the blend mode / opacity column at the right of a layer row.
const RIGHT_COLUMN: f32 = 58.0;
/// Indent per folder level, and per level of the effect tree.
const INDENT: f32 = 14.0;
/// Height of the "Content effects" / "Mask effects" header rows.
const GROUP_HEADER_H: f32 = 20.0;
/// Keep both thumbnail targets inside the row before spending space on indentation
fn layer_thumbnail_layout(width: f32, depth: usize, folder: bool, preferred_size: f32) -> (f32, f32) {
let controls = 7.0 + 20.0 + if folder { 14.0 } else { 0.0 };
let thumbnail_space = (width - controls - 4.0 - 4.0).max(0.0);
let size = preferred_size.min(thumbnail_space * 0.5);
let indent = (depth as f32 * INDENT).min((thumbnail_space - size * 2.0).max(0.0));
(indent, size)
}
/// Drop secondary controls before allowing them to cover thumbnail targets or the name
fn layer_name_layout(rect: Rect, left: f32) -> (Rect, bool) {
let right = rect.right() - 4.0;
let show_blend = right - RIGHT_COLUMN - 4.0 - left >= 20.0;
let name_right = if show_blend { right - RIGHT_COLUMN - 4.0 } else { right };
(Rect::from_min_max(pos2(left, rect.top() + 4.0), pos2(name_right.max(left), rect.bottom() - 4.0)), show_blend)
}
/// Preserve the effect eye, preview and a readable name before spending space on nesting.
fn effect_row_indent(width: f32, level: usize, preview: f32) -> f32 {
(level as f32 * INDENT).min((width - 7.0 - 22.0 - preview - 8.0 - 20.0 - 6.0).max(0.0))
}
/// X of the centre of the eye column at indent `level` in a row spanning from `left`.
fn level_x(left: f32, level: usize) -> f32 {
left + 7.0 + level as f32 * INDENT + 8.0
}
fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize, count: &mut usize) {
let Some(layer) = app.session.doc.project.layers.get(&id).cloned() else { return };
layer_row(app, ui, &layer, depth);
for e in layer.content_effects.iter().rev() {
effect_row(app, ui, &layer, &layer.content_effects, e, depth + 1, ic::SPHERE);
let index = *count;
*count += 1;
layer_row(app, ui, &layer, depth, index);
let mask_effects = layer.mask.as_ref().map_or(0, |m| m.effects.len());
if !layer.content_effects.is_empty() {
effect_group(app, ui, &layer, depth, false, mask_effects > 0);
}
if let Some(m) = &layer.mask {
for e in m.effects.iter().rev() {
effect_row(app, ui, &layer, &m.effects, e, depth + 1, ic::MAGIC_WAND);
}
if mask_effects > 0 {
effect_group(app, ui, &layer, depth, true, false);
}
// A line under the layer and its effects separates it from the next layer.
let tk = Tokens::get(ui.ctx());
let r = ui.available_rect_before_wrap();
ui.painter().hline(r.x_range(), r.top() - 0.5, Stroke::new(1.0, tk.separator));
if let LayerKind::Group { children, collapsed } = &layer.kind
&& !collapsed
&& depth < 12
{
for c in children.iter().rev() {
layer_tree(app, ui, *c, depth + 1);
layer_tree(app, ui, *c, depth + 1, count);
}
}
}
fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize) {
/// The picture for `target` inside `rect` (drawn over the well), whether there is one yet.
fn thumb_box(ui: &Ui, app: &mut TextureCraftApp, rect: Rect, target: ThumbTarget, dim: bool) -> bool {
let tk = Tokens::get(ui.ctx());
let p = ui.painter();
p.rect_filled(rect, 2.0, tk.field);
// A checkerboard shows through where the layer has nothing (transparent texels).
let cells = 4;
let cell = rect.width() / cells as f32;
let check = tk.field.lerp_to_gamma(tk.row_hover, 0.6);
for y in 0..cells {
for x in (0..cells).filter(|x| (x + y) % 2 == 0) {
p.rect_filled(Rect::from_min_size(rect.min + vec2(x as f32 * cell, y as f32 * cell), vec2(cell, cell)), 0.0, check);
}
}
// Only rows on screen ask for a picture.
if ui.is_rect_visible(rect)
&& let Some(tex) = app.layer_panel.texture(ui.ctx(), &app.session, target)
{
let tint = if dim { Color32::WHITE.gamma_multiply(0.4) } else { Color32::WHITE };
ui.painter().image(tex, rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), tint);
return true;
}
false
}
fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize, index: usize) {
let tk = Tokens::get(ui.ctx());
let selected = app.session.selected_layer() == Some(layer.id);
let h = 38.0;
let content_target = selected && targets_content(app);
let size = layer_preview_size(app);
let h = layer_row_height(size);
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click_and_drag());
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &layer.name));
let p = ui.painter().clone();
let bg = if selected && app.session.target == StackTarget::Content {
let bg = if selected {
tk.row_selected
} else if resp.hovered() {
tk.row_hover
} else {
tk.row
row_shade(&tk, index)
};
p.rect_filled(rect.shrink2(vec2(0.0, 1.0)), 2.0, bg);
p.rect_filled(rect, 0.0, bg);
let (indent, size) = layer_thumbnail_layout(rect.width(), depth, layer.is_group(), size);
// Folder contents hang off lines down the left without crossing compact row controls
let line = Stroke::new(1.0, tk.button_border.gamma_multiply(0.6));
for level in 0..depth {
let x = level_x(rect.left(), level);
if level as f32 * INDENT + 8.0 < indent {
p.vline(x, rect.y_range(), line);
}
}
if depth > 0 && indent >= INDENT {
let x = rect.left() + 15.0 + indent - INDENT;
p.hline(x..=x + INDENT * 0.5, rect.center().y, line);
}
if selected {
p.rect_stroke(rect.shrink2(vec2(0.0, 1.0)), 2.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside);
p.rect_filled(Rect::from_min_size(rect.min, vec2(3.0, h)), 0.0, tk.accent);
}
if let Some(tag) = layer.color_tag.and_then(|t| TAG_COLORS.get(t as usize)) {
p.rect_filled(Rect::from_min_size(rect.min + vec2(0.0, 1.0), vec2(3.0, h - 2.0)), 0.0, *tag);
p.rect_filled(Rect::from_min_size(rect.min + vec2(3.0, 0.0), vec2(3.0, h)), 0.0, *tag);
}
let x0 = rect.left() + 6.0 + depth as f32 * 14.0;
let x0 = rect.left() + 7.0 + indent;
// Eye.
let eye = Rect::from_center_size(pos2(x0 + 8.0, rect.center().y), vec2(18.0, 18.0));
let eye_resp = ui.interact(eye, ui.scope_id().with(("eye", layer.id.0)), Sense::click()).on_hover_text(tr("Show or hide the layer"));
@@ -329,29 +421,24 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
}
x += 14.0;
}
// Thumbnail.
let thumb = Rect::from_min_size(pos2(x, rect.top() + 5.0), vec2(28.0, 28.0));
p.rect_filled(thumb, 2.0, tk.field);
match &layer.kind {
LayerKind::Fill(f) => {
let c = match f.source(Channel::BaseColor) {
Source::Uniform(v) => v,
Source::Procedural { low, high, .. } => [(low[0] + high[0]) * 0.5, (low[1] + high[1]) * 0.5, (low[2] + high[2]) * 0.5],
Source::Image { .. } | Source::Anchor { .. } => [0.5; 3],
};
crate::thumbs::paint_sphere(&p, thumb.center(), 12.0, c);
}
LayerKind::Paint => {
p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::PAINT_BRUSH, egui::FontId::proportional(15.0), tk.text);
}
LayerKind::Group { .. } => {
p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::FOLDER_SIMPLE, egui::FontId::proportional(16.0), tk.text);
}
LayerKind::Instance { .. } => {
p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::LINK, egui::FontId::proportional(16.0), tk.accent);
}
// Content thumbnail: the layer's own result in the displayed channel.
let ch = app.ui.layer_channel;
let thumb = Rect::from_min_size(pos2(x, rect.center().y - size * 0.5), vec2(size, size));
let drawn = thumb_box(ui, app, thumb, ThumbTarget::Content { layer: layer.id, channel: ch }, !layer.visible);
if !drawn {
content_glyph(&p, &tk, thumb, layer);
}
x = thumb.right() + 8.0;
p.rect_stroke(
thumb,
2.0,
Stroke::new(if content_target { 1.5 } else { 1.0 }, if content_target { tk.accent } else { tk.button_border }),
egui::StrokeKind::Outside,
);
let content_resp = ui.interact(thumb, ui.scope_id().with(("content", layer.id.0)), Sense::click()).on_hover_text(tr("Select the layer content"));
if content_resp.clicked() {
app.run("layer.select", json!({"layer": layer.id.0, "target": "content"}));
}
x = thumb.right() + 4.0;
// An instance draws its source's content, blending and (unless it has its own) mask.
let project = &app.session.doc.project;
let source = layer.instance_source().map(|src| {
@@ -359,26 +446,29 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
project.layers.get(&src).map_or_else(|| tr("missing source").to_string(), |l| format!("{} · {set}", l.name))
});
let mask = project.layers.get(&project.mask_owner(layer.id)).and_then(|l| l.mask.clone());
let blend = project.content_layer(layer.id).and_then(|l| l.blend(app.ui.layer_channel));
// Mask thumbnail.
let right_w = 46.0;
let mask_rect = Rect::from_min_size(pos2(rect.right() - right_w - 30.0, rect.top() + 7.0), vec2(24.0, 24.0));
let blend = project.content_layer(layer.id).and_then(|l| l.blend(ch));
// Mask thumbnail, selectable on its own; or the slot that adds one.
let mask_rect;
if let Some(m) = &mask {
let mask_sel = selected && !targets_content(app);
p.rect_filled(
mask_rect,
1.0,
if m.background == texturecraft_engine::core::MaskBackground::White { Color32::from_gray(225) } else { Color32::from_gray(18) },
);
mask_rect = Rect::from_min_size(pos2(x, rect.center().y - size * 0.5), vec2(size, size));
let drawn = thumb_box(ui, app, mask_rect, ThumbTarget::Mask { layer: layer.id }, !layer.visible || !m.enabled);
if !drawn {
p.rect_filled(
mask_rect,
2.0,
if m.background == texturecraft_engine::core::MaskBackground::White { Color32::from_gray(225) } else { Color32::from_gray(18) },
);
if !m.effects.is_empty() {
p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::MAGIC_WAND, egui::FontId::proportional(13.0), tk.text_dim);
}
}
p.rect_stroke(
mask_rect,
1.0,
2.0,
Stroke::new(if mask_sel { 1.5 } else { 1.0 }, if mask_sel { tk.accent } else { tk.button_border }),
egui::StrokeKind::Outside,
);
if !m.effects.is_empty() {
p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::MAGIC_WAND, egui::FontId::proportional(11.0), tk.text_dim);
}
if !m.enabled {
p.line_segment([mask_rect.left_top(), mask_rect.right_bottom()], Stroke::new(1.5, tk.danger));
}
@@ -394,19 +484,33 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
}
}
if app.session.view == texturecraft_engine::ViewMode::Mask(layer.id) {
p.rect_stroke(mask_rect.expand(2.0), 1.0, Stroke::new(1.5, tk.warning), egui::StrokeKind::Outside);
p.rect_stroke(mask_rect.expand(2.0), 2.0, Stroke::new(1.5, tk.warning), egui::StrokeKind::Outside);
}
x = mask_rect.right() + 8.0;
} else {
// The empty slot adds a mask to this layer.
let slot_size = size.min(18.0);
mask_rect = Rect::from_min_size(pos2(x, rect.center().y - slot_size * 0.5), vec2(slot_size, slot_size));
let slot = ui.interact(mask_rect, ui.scope_id().with(("mask_slot", layer.id.0)), Sense::click()).on_hover_text(tr("Add mask"));
p.rect_stroke(mask_rect, 1.0, Stroke::new(1.0, if slot.hovered() { tk.accent } else { tk.field_border }), egui::StrokeKind::Inside);
p.rect_stroke(mask_rect, 2.0, Stroke::new(1.0, if slot.hovered() { tk.accent } else { tk.field_border }), egui::StrokeKind::Inside);
if slot.hovered() {
p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::PLUS, egui::FontId::proportional(12.0), tk.text);
}
egui::Popup::menu(&slot).show(|ui| add_mask_menu(app, ui, Some(layer.id.0)));
x = mask_rect.right() + 8.0;
}
// Blend mode and opacity of the displayed channel, stacked at the right.
let blend_rect = Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - 4.0, rect.center().y - 18.0), vec2(RIGHT_COLUMN, 17.0));
let op_rect = Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - 4.0, rect.center().y + 1.0), vec2(RIGHT_COLUMN, 17.0));
// Name (or rename editor) with the quieter subtitle under it.
let (name_rect, show_blend) = layer_name_layout(rect, x);
let show_name = name_rect.width() >= 20.0;
if !show_name {
resp.clone().on_hover_text(&layer.name);
if app.ui.rename.as_ref().is_some_and(|(id, _)| *id == layer.id.0) {
app.ui.rename = None;
}
}
// Name (or rename editor).
let name_rect = Rect::from_min_max(pos2(x, rect.top() + 4.0), pos2(mask_rect.left() - 4.0, rect.bottom() - 4.0));
let renaming = app.ui.rename.as_ref().is_some_and(|(r, _)| *r == layer.id.0);
if renaming {
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(name_rect).layout(egui::Layout::left_to_right(egui::Align::Center)));
@@ -429,21 +533,30 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
r.request_focus();
}
}
} else {
let galley = elided(&p, layer.name.clone(), 12.0, if layer.visible { tk.text_strong } else { tk.text_dim }, name_rect.width());
let y = if source.is_some() { rect.center().y - 7.0 } else { rect.center().y };
p.galley(pos2(name_rect.left(), y - galley.size().y * 0.5), galley, tk.text);
if let Some(src) = source {
let src = elided(&p, format!("{} {src}", ic::LINK_SIMPLE), 10.0, tk.text_dim, name_rect.width());
p.galley(pos2(name_rect.left(), rect.center().y + 7.0 - src.size().y * 0.5), src, tk.text_dim);
}
} else if show_name {
let galley = elided(&p, layer.name.clone(), 12.5, if layer.visible { tk.text_strong } else { tk.text_dim }, name_rect.width());
p.galley(pos2(name_rect.left(), rect.center().y - 2.0 - galley.size().y), galley, tk.text);
let kind = tr(match &layer.kind {
LayerKind::Paint => "Paint layer",
LayerKind::Fill(_) => "Fill layer",
LayerKind::Group { .. } => "Folder",
LayerKind::Instance { .. } => "Instance",
});
let effects = layer.content_effects.len() + mask.as_ref().map_or(0, |m| m.effects.len());
let subtitle = match (source, effects) {
(Some(src), _) => format!("{kind} · {} {src}", ic::LINK_SIMPLE),
(None, 0) => kind.to_string(),
(None, 1) => format!("{kind} · {}", tr("1 effect")),
(None, n) => format!("{kind} · {}", trf("{count} effects", &[("count", &n)])),
};
let sub = elided(&p, subtitle, 10.0, tk.text_dim, name_rect.width());
p.galley(pos2(name_rect.left(), rect.center().y + 2.0), sub, tk.text_dim);
}
// Blend mode and opacity of the displayed channel.
let ch = app.ui.layer_channel;
let blend_rect = Rect::from_min_size(pos2(rect.right() - right_w - 2.0, rect.top() + 3.0), vec2(right_w, 16.0));
let op_rect = Rect::from_min_size(pos2(rect.right() - right_w - 2.0, rect.top() + 19.0), vec2(right_w, 16.0));
if let Some(b) = blend {
if let Some(b) = blend.filter(|_| show_blend) {
let br = ui.interact(blend_rect, ui.scope_id().with(("blend", layer.id.0)), Sense::click()).on_hover_text(tr("Blending mode of the displayed channel"));
if br.hovered() {
p.rect_filled(blend_rect, 2.0, tk.row_hover);
}
p.text(blend_rect.right_center() - vec2(10.0, 0.0), egui::Align2::RIGHT_CENTER, b.mode.short(), egui::FontId::proportional(11.0), tk.text);
p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(8.0), tk.text_dim);
egui::Popup::menu(&br).show(|ui| {
@@ -468,18 +581,19 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
child.spacing_mut().interact_size.y = op_rect.height();
child.spacing_mut().button_padding = vec2(4.0, 0.0);
child.style_mut().override_text_style = Some(egui::TextStyle::Small);
let r = child.add(egui::DragValue::new(&mut op).range(0.0..=100.0).speed(0.5).max_decimals(0));
let r = child.add(egui::DragValue::new(&mut op).range(0.0..=100.0).speed(0.5).max_decimals(0).suffix("%"));
if r.changed() {
app.run("layer.blend", json!({"layer": layer.id.0, "channel": ch.id(), "opacity": op / 100.0}));
}
} else {
} else if show_blend {
p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, tr("off"), egui::FontId::proportional(11.0), tk.text_dim);
}
// Interaction: select, rename, drag & drop, context menu.
if resp.clicked() && !eye_resp.clicked() && !renaming {
let on_control = eye_resp.clicked() || content_resp.clicked();
if resp.clicked() && !on_control && !renaming {
app.run("layer.select", json!({"layer": layer.id.0}));
}
if resp.double_clicked() && !eye_resp.clicked() && !renaming {
if resp.double_clicked() && !on_control && !renaming && show_name {
app.ui.rename = Some((layer.id.0, layer.name.clone()));
}
if resp.drag_started() && !renaming {
@@ -525,20 +639,101 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
resp.context_menu(|ui| layer_context_menu(app, ui, layer));
}
/// What a content thumbnail shows until its picture arrives (or where the layer has none).
fn content_glyph(p: &egui::Painter, tk: &Tokens, thumb: Rect, layer: &Layer) {
match &layer.kind {
LayerKind::Fill(f) => {
let c = match f.source(Channel::BaseColor) {
Source::Uniform(v) => v,
Source::Procedural { low, high, .. } => [(low[0] + high[0]) * 0.5, (low[1] + high[1]) * 0.5, (low[2] + high[2]) * 0.5],
Source::Image { .. } | Source::Anchor { .. } => [0.5; 3],
};
crate::thumbs::paint_sphere(p, thumb.center(), thumb.width() * 0.34, c);
}
LayerKind::Paint => {
p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::PAINT_BRUSH, egui::FontId::proportional(thumb.width() * 0.45), tk.text_dim);
}
LayerKind::Group { .. } => {
p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::FOLDER_SIMPLE, egui::FontId::proportional(thumb.width() * 0.5), tk.text);
}
LayerKind::Instance { .. } => {
p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::LINK, egui::FontId::proportional(thumb.width() * 0.45), tk.accent);
}
}
}
/// The "Content effects" or "Mask effects" header of `layer` and, unless folded, its effect rows
/// hung off tree lines. `more_below`: a second group follows, so the tree line goes on.
fn effect_group(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize, mask: bool, more_below: bool) {
let tk = Tokens::get(ui.ctx());
let stack: &[Effect] = if mask { layer.mask.as_ref().map_or(&[], |m| &m.effects) } else { &layer.content_effects };
let key = (layer.id.0, mask);
let folded = app.layer_panel.folded.contains(&key);
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), GROUP_HEADER_H), Sense::click());
let label = if mask { tr("Mask effects") } else { tr("Content effects") };
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label));
let p = ui.painter().clone();
p.rect_filled(rect, 0.0, if resp.hovered() { tk.row_hover } else { tk.panel });
let indent = ((depth + 1) as f32 * INDENT).min((rect.width() - 90.0).max(0.0));
tree_lines(&p, &tk, rect, indent, &[], more_below);
let x = rect.left() + 15.0 + indent;
p.text(
pos2(x, rect.center().y),
egui::Align2::CENTER_CENTER,
if folded { ic::CARET_RIGHT } else { ic::CARET_DOWN },
egui::FontId::proportional(10.0),
tk.text_dim,
);
let galley = elided(&p, label.to_string(), 10.5, tk.text_dim, (rect.right() - 28.0 - x - 10.0).max(0.0));
p.galley(pos2(x + 10.0, rect.center().y - galley.size().y * 0.5), galley, tk.text_dim);
p.text(pos2(rect.right() - 8.0, rect.center().y), egui::Align2::RIGHT_CENTER, stack.len().to_string(), egui::FontId::proportional(10.0), tk.text_dim);
if resp.on_hover_text(tr("Fold or unfold these effects")).clicked() && !app.layer_panel.folded.remove(&key) {
app.layer_panel.folded.insert(key);
}
if folded {
return;
}
let trunks: Vec<usize> = if more_below { vec![depth] } else { Vec::new() };
for (i, e) in stack.iter().rev().enumerate() {
effect_row(app, ui, layer, stack, e, depth + 2, &trunks, i + 1 == stack.len(), mask);
}
}
/// Tree connector of a row at the clamped `indent`: a line down from the parent's column (to the middle
/// of the row when `more` is false, the row's end otherwise) and a tick towards the row, with
/// lines straight through for the `trunks` of ancestors that continue.
fn tree_lines(p: &egui::Painter, tk: &Tokens, rect: Rect, indent: f32, trunks: &[usize], more: bool) {
if indent < INDENT {
return;
}
let stroke = Stroke::new(1.0, tk.button_border);
for t in trunks {
if *t as f32 * INDENT + 8.0 < indent {
p.vline(level_x(rect.left(), *t), rect.y_range(), stroke);
}
}
let x = rect.left() + 15.0 + indent - INDENT;
let end = if more { rect.bottom() } else { rect.center().y };
p.vline(x, rect.top()..=end, stroke);
p.hline(x..=x + INDENT * 0.6, rect.center().y, stroke);
}
/// The drag-and-drop payload of an effect row (the effect id).
struct EffectDrag(u64);
/// Effect `e` of `stack`, a layer's content (`glyph` sphere) or mask (`glyph` wand) effects.
fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Effect], e: &Effect, depth: usize, glyph: &str) {
/// Effect `e` of `stack` (a layer's content or, with `in_mask`, mask effects) at indent `level`.
#[allow(clippy::too_many_arguments)]
fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Effect], e: &Effect, level: usize, trunks: &[usize], last: bool, in_mask: bool) {
let tk = Tokens::get(ui.ctx());
let (eid, visible) = (e.id, e.visible);
let selected = app.session.selected_layer() == Some(layer.id) && app.session.target == StackTarget::Effect(eid);
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click_and_drag());
let size = effect_preview_size(layer_preview_size(app));
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), effect_row_height(layer_preview_size(app))), Sense::click_and_drag());
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &e.name));
let p = ui.painter().clone();
p.rect_filled(
rect.shrink2(vec2(0.0, 1.0)),
2.0,
rect,
0.0,
if selected {
tk.row_selected
} else if resp.hovered() {
@@ -547,15 +742,29 @@ fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Ef
tk.panel
},
);
let indent = effect_row_indent(rect.width(), level, size);
tree_lines(&p, &tk, rect, indent, trunks, !last);
if selected {
p.rect_stroke(rect.shrink2(vec2(0.0, 1.0)), 2.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside);
p.rect_filled(Rect::from_min_size(rect.min, vec2(3.0, rect.height())), 0.0, tk.accent);
}
let x0 = rect.left() + 6.0 + depth as f32 * 14.0;
let x0 = rect.left() + 7.0 + indent;
let eye = Rect::from_center_size(pos2(x0 + 8.0, rect.center().y), vec2(16.0, 16.0));
let er = ui.interact(eye, ui.scope_id().with(("eff_eye", eid.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect"));
p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(12.0), tk.text_dim);
p.text(pos2(x0 + 22.0, rect.center().y), egui::Align2::LEFT_CENTER, glyph, egui::FontId::proportional(11.0), tk.text_dim);
p.text(pos2(x0 + 38.0, rect.center().y), egui::Align2::LEFT_CENTER, &e.name, egui::FontId::proportional(11.5), tk.text);
// The stack as it is up to and including this effect; a hidden one shows what it bypasses.
let thumb = Rect::from_min_size(pos2(x0 + 22.0, rect.center().y - size * 0.5), vec2(size, size));
let ch = app.ui.layer_channel;
if !thumb_box(ui, app, thumb, ThumbTarget::Stage { effect: eid, channel: ch }, false) {
let glyph = if in_mask { ic::MAGIC_WAND } else { ic::SPHERE };
p.text(thumb.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(size * 0.5), tk.text_dim);
}
p.rect_stroke(thumb, 2.0, Stroke::new(1.0, tk.button_border), egui::StrokeKind::Outside);
if !visible {
p.line_segment([thumb.left_bottom(), thumb.right_top()], Stroke::new(1.5, tk.text_dim));
}
let name_x = thumb.right() + 8.0;
let galley = elided(&p, e.name.clone(), 11.5, if visible { tk.text } else { tk.text_dim }, (rect.right() - name_x - 6.0).max(20.0));
p.galley(pos2(name_x, rect.center().y - galley.size().y * 0.5), galley, tk.text);
if er.clicked() {
app.run("effect.set", json!({"effect": eid.0, "visible": !visible}));
} else if resp.clicked() {
@@ -928,6 +1137,8 @@ pub(crate) fn properties_title(app: &TextureCraftApp) -> String {
}
pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) {
// A floating scroll bar would cover the right-aligned slider values and section reset icons
ui.spacing_mut().scroll = egui::style::ScrollStyle::solid();
egui::ScrollArea::vertical().id_salt("props").auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui));
}
@@ -1248,104 +1459,130 @@ fn polygon_fill_paints_mask(app: &TextureCraftApp) -> Result<bool, String> {
}
}
/// Font size of the dim hint line under the Brush caption
const HINT_TEXT_SIZE: f32 = 10.5;
fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) {
let b = &mut app.session.tool.brush;
let brush = &mut app.session.tool.brush;
let defaults = BrushSettings::default();
ui.label(caption(tr("Brush")));
let hint = tr("Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.");
ui.label(RichText::new(hint).size(10.5).color(Tokens::get(ui.ctx()).text_dim));
section(ui, "sec_size", tr("Size"), true, |ui| {
let mut size = b.size / 0.25 * 100.0;
if slider(ui, tr("Size"), &mut size, 0.05..=100.0, 1).changed() {
b.size = (size / 100.0 * 0.25).clamp(0.0005, 0.25);
ui.label(RichText::new(hint).size(HINT_TEXT_SIZE).color(Tokens::get(ui.ctx()).text_dim));
// Each section's reset puts back only the fields it shows
let size_fields = |settings: &BrushSettings| (settings.size, settings.min_size, settings.screen_space);
if section_with_reset(ui, "sec_size", tr("Size"), true, size_fields(brush) == size_fields(&defaults), |ui| {
let mut size_percent = brush.size / MAX_BRUSH_SIZE * 100.0;
if slider(ui, tr("Size"), &mut size_percent, 0.05..=100.0, 1).changed() {
brush.size = (size_percent / 100.0 * MAX_BRUSH_SIZE).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE);
}
let mut ms = b.min_size * 100.0;
if slider(ui, tr("Minimum size (%)"), &mut ms, 0.0..=100.0, 0).changed() {
b.min_size = ms / 100.0;
let mut min_size_percent = brush.min_size * 100.0;
if slider(ui, tr("Minimum size (%)"), &mut min_size_percent, 0.0..=100.0, 0).changed() {
brush.min_size = min_size_percent / 100.0;
}
ui.checkbox(&mut b.screen_space, tr("Size in screen space"));
});
section(ui, "sec_flow", tr("Flow and opacity"), true, |ui| {
let mut f = b.flow * 100.0;
if slider(ui, tr("Flow"), &mut f, 0.0..=100.0, 0).changed() {
b.flow = f / 100.0;
ui.checkbox(&mut brush.screen_space, tr("Size in screen space"));
}) {
(brush.size, brush.min_size, brush.screen_space) = size_fields(&defaults);
}
let flow_fields = |settings: &BrushSettings| (settings.flow, settings.opacity, settings.spacing, settings.hardness);
if section_with_reset(ui, "sec_flow", tr("Flow and opacity"), true, flow_fields(brush) == flow_fields(&defaults), |ui| {
let mut flow_percent = brush.flow * 100.0;
if slider(ui, tr("Flow"), &mut flow_percent, 0.0..=100.0, 0).changed() {
brush.flow = flow_percent / 100.0;
}
let mut o = b.opacity * 100.0;
if slider(ui, tr("Stroke opacity"), &mut o, 0.0..=100.0, 0).changed() {
b.opacity = o / 100.0;
let mut opacity_percent = brush.opacity * 100.0;
if slider(ui, tr("Stroke opacity"), &mut opacity_percent, 0.0..=100.0, 0).changed() {
brush.opacity = opacity_percent / 100.0;
}
let mut s = b.spacing * 100.0;
if slider(ui, tr("Spacing"), &mut s, 1.0..=1000.0, 0).changed() {
b.spacing = s / 100.0;
let mut spacing_percent = brush.spacing * 100.0;
if slider(ui, tr("Spacing"), &mut spacing_percent, 1.0..=1000.0, 0).changed() {
brush.spacing = spacing_percent / 100.0;
}
let mut h = b.hardness * 100.0;
if slider(ui, tr("Hardness"), &mut h, 0.0..=99.9, 0).changed() {
b.hardness = h / 100.0;
let mut hardness_percent = brush.hardness * 100.0;
if slider(ui, tr("Hardness"), &mut hardness_percent, 0.0..=99.9, 0).changed() {
brush.hardness = hardness_percent / 100.0;
}
});
section(ui, "sec_angle", tr("Angle"), false, |ui| {
slider(ui, tr("Angle"), &mut b.angle, -180.0..=180.0, 0);
ui.checkbox(&mut b.follow_path, tr("Follow path"));
});
section(ui, "sec_jitter", tr("Jitters"), false, |ui| {
for (label, v) in [(tr("Size jitter"), &mut b.jitter_size), (tr("Angle jitter"), &mut b.jitter_angle), (tr("Flow jitter"), &mut b.jitter_flow)] {
let mut x = *v * 100.0;
if slider(ui, label, &mut x, 0.0..=100.0, 0).changed() {
*v = x / 100.0;
}) {
(brush.flow, brush.opacity, brush.spacing, brush.hardness) = flow_fields(&defaults);
}
let angle_fields = |settings: &BrushSettings| (settings.angle, settings.follow_path);
if section_with_reset(ui, "sec_angle", tr("Angle"), false, angle_fields(brush) == angle_fields(&defaults), |ui| {
slider(ui, tr("Angle"), &mut brush.angle, -180.0..=180.0, 0);
ui.checkbox(&mut brush.follow_path, tr("Follow path"));
}) {
(brush.angle, brush.follow_path) = angle_fields(&defaults);
}
let jitter_fields = |settings: &BrushSettings| (settings.jitter_size, settings.jitter_angle, settings.jitter_flow, settings.jitter_position);
if section_with_reset(ui, "sec_jitter", tr("Jitters"), false, jitter_fields(brush) == jitter_fields(&defaults), |ui| {
let jitters = [(tr("Size jitter"), &mut brush.jitter_size), (tr("Angle jitter"), &mut brush.jitter_angle), (tr("Flow jitter"), &mut brush.jitter_flow)];
for (label, jitter) in jitters {
let mut jitter_percent = *jitter * 100.0;
if slider(ui, label, &mut jitter_percent, 0.0..=100.0, 0).changed() {
*jitter = jitter_percent / 100.0;
}
}
let mut pj = b.jitter_position * 100.0;
if slider(ui, tr("Position jitter"), &mut pj, 0.0..=400.0, 0).changed() {
b.jitter_position = pj / 100.0;
let mut position_jitter_percent = brush.jitter_position * 100.0;
if slider(ui, tr("Position jitter"), &mut position_jitter_percent, 0.0..=400.0, 0).changed() {
brush.jitter_position = position_jitter_percent / 100.0;
}
});
section(ui, "sec_align", tr("Alignment and culling"), false, |ui| {
}) {
(brush.jitter_size, brush.jitter_angle, brush.jitter_flow, brush.jitter_position) = jitter_fields(&defaults);
}
let alignment_fields = |settings: &BrushSettings| (settings.alignment, settings.backface_culling, settings.angle_fade, settings.depth);
if section_with_reset(ui, "sec_align", tr("Alignment and culling"), false, alignment_fields(brush) == alignment_fields(&defaults), |ui| {
use texturecraft_engine::paint::Alignment;
let alignments = [(Alignment::Tangent, tr("Tangent | Wrap")), (Alignment::Camera, tr("Camera"))];
let shown = alignments.iter().find(|(a, _)| *a == b.alignment).map_or("", |(_, l)| l);
let shown = alignments.iter().find(|(alignment, _)| *alignment == brush.alignment).map_or("", |(_, label)| label);
combo(ui, tr("Alignment"), shown, |ui| {
for (a, l) in alignments {
ui.selectable_value(&mut b.alignment, a, l);
for (alignment, label) in alignments {
ui.selectable_value(&mut brush.alignment, alignment, label);
}
});
ui.checkbox(&mut b.backface_culling, tr("Backface culling"));
slider(ui, tr("Angle fade from"), &mut b.angle_fade.0, 0.0..=90.0, 0);
slider(ui, tr("Angle fade to"), &mut b.angle_fade.1, 0.0..=90.0, 0);
slider(ui, tr("Stamp depth"), &mut b.depth, 0.05..=4.0, 2);
});
section(ui, "sec_particles", tr("Particles"), false, |ui| {
let pt = &mut b.particles;
ui.checkbox(&mut pt.enabled, tr("Particle brush (slides down the surface)"));
let mut count = pt.count as f32;
ui.checkbox(&mut brush.backface_culling, tr("Backface culling"));
slider(ui, tr("Angle fade from"), &mut brush.angle_fade.0, 0.0..=90.0, 0);
slider(ui, tr("Angle fade to"), &mut brush.angle_fade.1, 0.0..=90.0, 0);
slider(ui, tr("Stamp depth"), &mut brush.depth, 0.05..=4.0, 2);
}) {
(brush.alignment, brush.backface_culling, brush.angle_fade, brush.depth) = alignment_fields(&defaults);
}
if section_with_reset(ui, "sec_particles", tr("Particles"), false, brush.particles == defaults.particles, |ui| {
let particles = &mut brush.particles;
ui.checkbox(&mut particles.enabled, tr("Particle brush (slides down the surface)"));
let mut count = particles.count as f32;
if slider(ui, tr("Count per stamp"), &mut count, 1.0..=16.0, 0).changed() {
pt.count = count as u32;
particles.count = count as u32;
}
let mut life = pt.lifetime as f32;
if slider(ui, tr("Lifetime (steps)"), &mut life, 1.0..=128.0, 0).changed() {
pt.lifetime = life as u32;
let mut lifetime_steps = particles.lifetime as f32;
if slider(ui, tr("Lifetime (steps)"), &mut lifetime_steps, 1.0..=128.0, 0).changed() {
particles.lifetime = lifetime_steps as u32;
}
slider(ui, tr("Gravity"), &mut pt.gravity, 0.0..=2.0, 2);
});
section(ui, "sec_lazy", tr("Lazy mouse and symmetry"), false, |ui| {
slider(ui, tr("Lazy mouse distance"), &mut b.lazy, 0.0..=200.0, 0);
ui.horizontal(|ui| {
ui.checkbox(&mut b.symmetry.x, tr("Mirror X"));
ui.checkbox(&mut b.symmetry.y, tr("Mirror Y"));
ui.checkbox(&mut b.symmetry.z, tr("Mirror Z"));
});
let mut copies = f32::from(b.symmetry.radial);
if slider(ui, tr("Radial copies"), &mut copies, 0.0..=32.0, 0).changed() {
b.symmetry.radial = copies as u8;
}
ui.add_enabled_ui(b.symmetry.radial > 1, |ui| {
ui.horizontal(|ui| {
ui.label(tr("Radial axis"));
for (k, name) in ["X", "Y", "Z"].into_iter().enumerate() {
ui.selectable_value(&mut b.symmetry.axis, k as u8, name);
}
});
});
});
*b = b.sanitized();
slider(ui, tr("Gravity"), &mut particles.gravity, 0.0..=2.0, 2);
}) {
brush.particles = defaults.particles;
}
if section_with_reset(ui, "sec_lazy", tr("Lazy mouse"), false, brush.lazy == defaults.lazy, |ui| {
slider(ui, tr("Lazy mouse distance"), &mut brush.lazy, 0.0..=200.0, 0);
}) {
brush.lazy = defaults.lazy;
}
*brush = brush.sanitized();
}
/// One alpha in the picker: a 52×64 tile with the shape drawn by `paint` and a label.
@@ -2007,23 +2244,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid:
match &effect.kind {
EffectKind::Generator(generator) => generator_properties(app, ui, id, generator),
EffectKind::Levels(levels) => {
ui.label(caption(tr("Levels")));
levels_histogram(app, ui, layer, eid, (levels.in_low, levels.in_high));
let mut values = [levels.in_low, levels.in_high, levels.gamma, levels.out_low, levels.out_high];
let labels = [tr("Input low"), tr("Input high"), tr("Gamma"), tr("Output low"), tr("Output high")];
let mut edit = None;
for (index, label) in labels.iter().enumerate() {
let range = if index == 2 { 0.1..=5.0 } else { 0.0..=1.0 };
edit = edit.or(slider_edit(ui, label, &mut values[index], range, 2));
}
if let Some(merge) = edit {
app.run(
"effect.set",
json!({"effect": id, "inLow": values[0], "inHigh": values[1], "gamma": values[2], "outLow": values[3], "outHigh": values[4], "merge": merge}),
);
}
}
EffectKind::Levels(levels) => crate::levels_properties::levels_properties(app, ui, layer, eid, levels),
EffectKind::Fill { source, .. } => {
ui.label(caption(tr("Fill")));
let anchors = anchors_below(app, layer.id);
@@ -2191,38 +2412,6 @@ fn curvature_mode_label(mode: CurvatureMode) -> &'static str {
}
}
/// The histogram of what levels effect `eid` of `layer` remaps (its mask, or a content channel
/// picked here), with the input range marked. Recomputed after a document change once no
/// pointer button is held, so dragging a slider keeps the last one.
fn levels_histogram(app: &TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId, range: (f32, f32)) {
let mut channel = layer.channels.keys().next().copied().unwrap_or(Channel::BaseColor);
if layer.content_effects.iter().any(|e| e.id == eid) {
let pick = egui::Id::unique(("levels_channel", eid.0));
let chans: Vec<Channel> = layer.channels.keys().copied().filter(|c| c.kind() != texturecraft_engine::core::ChannelKind::NormalMap).collect();
channel = ui.data(|d| d.get_temp(pick)).filter(|c| chans.contains(c)).or(chans.first().copied()).unwrap_or(channel);
combo(ui, tr("Channel"), tr(channel.label()), |ui| {
for c in chans {
if ui.selectable_label(c == channel, tr(c.label())).clicked() {
ui.data_mut(|d| d.insert_temp(pick, c));
}
}
});
}
let key = egui::Id::unique(("levels_histogram", eid.0, channel));
let rev = app.session.revision;
let counts = match ui.data(|d| d.get_temp::<(u64, std::sync::Arc<Vec<u32>>)>(key)) {
Some((r, h)) if r == rev || ui.input(|i| i.pointer.any_down()) => Some(h),
_ => app.session.effect_histogram(eid, channel, 64).map(|h| {
let h = std::sync::Arc::new(h);
ui.data_mut(|d| d.insert_temp(key, (rev, h.clone())));
h
}),
};
if let Some(counts) = counts {
histogram(ui, &counts, range);
}
}
/// The filter slot and the parameters of filter effect `id`
fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, filter: &Filter) {
let tk = Tokens::get(ui.ctx());
@@ -2317,3 +2506,64 @@ fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, filter: &F
_ => {}
}
}
#[cfg(test)]
mod layer_layout_tests {
use super::*;
#[test]
fn narrow_nested_rows_keep_thumbnail_and_secondary_controls_separate() {
for width in [120.0, 180.0, 260.0, 400.0] {
for depth in 0..=12 {
for folder in [false, true] {
let row = Rect::from_min_size(pos2(100.0, 20.0), vec2(width, 48.0));
let (indent, size) = layer_thumbnail_layout(width, depth, folder, 36.0);
let content_left = row.left() + 7.0 + indent + 20.0 + if folder { 14.0 } else { 0.0 };
let content = Rect::from_min_size(pos2(content_left, row.top() + 6.0), vec2(size, size));
let mask = content.translate(vec2(size + 4.0, 0.0));
let (name, show_blend) = layer_name_layout(row, mask.right() + 8.0);
assert!(size >= 35.0, "minimum-width panels retain usable thumbnail targets");
assert!(row.contains_rect(content) && row.contains_rect(mask), "width={width}, depth={depth}, folder={folder}");
assert!(!content.intersects(mask));
if name.width() >= 20.0 {
assert!(row.contains_rect(name));
assert!(name.left() > mask.right());
}
if show_blend {
let blend_left = row.right() - RIGHT_COLUMN - 4.0;
assert!(name.right() + 4.0 <= blend_left);
assert!(mask.right() < blend_left);
}
}
}
}
}
#[test]
fn narrow_effect_rows_keep_the_eye_preview_and_name_inside() {
for width in [120.0, 180.0, 260.0, 400.0] {
for level in 0..=14 {
for preview in [18.0, 21.6, 28.0] {
let indent = effect_row_indent(width, level, preview);
let eye_right = 7.0 + indent + 16.0;
let preview_left = 7.0 + indent + 22.0;
let name_left = preview_left + preview + 8.0;
assert!(eye_right < preview_left);
assert!(name_left + 20.0 <= width - 6.0 + 0.001);
}
}
}
}
#[test]
fn ordinary_rows_keep_preferred_sizes_and_secondary_controls() {
let row = Rect::from_min_size(pos2(0.0, 0.0), vec2(300.0, 48.0));
let (indent, size) = layer_thumbnail_layout(row.width(), 2, false, 36.0);
let (_, show_blend) = layer_name_layout(row, 7.0 + indent + 20.0 + size * 2.0 + 4.0 + 8.0);
assert_eq!(indent, 28.0);
assert_eq!(size, 36.0);
assert!(show_blend);
}
}
+55 -38
View File
@@ -133,9 +133,7 @@ fn split(axis: SplitAxis, size: SplitSize, first: Node<Panel>, second: Node<Pane
Node::Split { axis, size, first: Box::new(first), second: Box::new(second) }
}
/// The default: assets left of the viewport; texture set list, layers (tabbed with the texture
/// set settings) and properties down the right. Ratios match the 1600x960 window. Display,
/// shader, history and log are closed and open as floating windows.
/// The default: assets left of the viewport, then texture sets, layers (tabbed with texture set settings) and properties; ratios fit 1600x960
pub fn default_workspace() -> Workspace {
use Panel::*;
let column = split(
@@ -147,20 +145,13 @@ pub fn default_workspace() -> Workspace {
let root =
split(SplitAxis::Horizontal, SplitSize::Ratio(0.115), tabs(&[Assets]), split(SplitAxis::Horizontal, SplitSize::Ratio(0.78), tabs(&[Viewport]), column));
let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() });
for panel in Panel::ALL {
if let Some(rect) = panel.float_rect() {
let location = Location {
floating: Some(rect),
anchor: None,
placement: Placement::Tab { before: None },
size: None,
stack: None,
sibling: Vec::new(),
group: None,
};
workspace.hidden.push((panel, location));
workspace.hidden.push((panel, floating_location(rect)));
}
}
for panel in [MeshMapSettings, CommonSettings, MeshMapBakers] {
workspace.hidden.push((
panel,
@@ -175,9 +166,15 @@ pub fn default_workspace() -> Workspace {
},
));
}
workspace
}
/// Where a closed panel reopens as its own floating window at `rect` (`[x, y, width, height]`)
fn floating_location(rect: [f32; 4]) -> Location<Panel> {
Location { floating: Some(rect), anchor: None, placement: Placement::Tab { before: None }, size: None, stack: None, sibling: Vec::new(), group: None }
}
/// craft-ui's checks plus the viewport's: a saved or hand-edited file cannot hide, float, group
/// or collapse it.
pub fn validate(workspace: &Workspace) -> Result<(), String> {
@@ -344,6 +341,13 @@ impl Dock {
}
}
/// Open the closed `panel` as a floating window at `rect` (`[x, y, width, height]`)
pub(crate) fn float_at(&mut self, panel: Panel, rect: [f32; 4]) {
self.workspace.hidden.retain(|(hidden_panel, _)| *hidden_panel != panel);
self.workspace.hidden.push((panel, floating_location(rect)));
self.focus(panel);
}
/// One change from the dock area's gestures. A change that is rejected leaves the layout as
/// it was.
fn apply(&mut self, action: Action<Panel>) {
@@ -415,57 +419,70 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) {
if let Some(panel) = app.ui.dock.raise.take() {
area = area.raise_panel(panel);
}
let output = area.show_content(ui, &layout, &style, &mut Panels { app, tk: tokens });
let output = area.show_content(ui, &layout, &style, &mut Panels { app, tokens });
crate::rail_popup::hand_drag_to_dock(&context, area_id());
// After the dock, which records the viewport the popup reaches into, and before a changed layout returns early
crate::rail_popup::show(app, &context);
#[cfg(not(target_arch = "wasm32"))]
crate::menus::forwarded_shortcuts(app, &context, output.forwarded_events, output.forwarded_modifiers.unwrap_or_default());
if let Some(error) = &output.error {
log::warn!("docking: {error}");
}
// A layout changed by a panel takes priority over gestures from the old layout
if app.ui.dock.workspace.layout != layout {
craft_ui::docking::cancel_drag::<Panel>(&context, area_id());
return;
}
for action in output.actions {
app.ui.dock.apply(action);
}
}
/// The panels' contents, names and limits for the dock area.
/// The panels' contents, names and limits for the dock area
struct Panels<'a> {
app: &'a mut TextureCraftApp,
tk: Tokens,
tokens: Tokens,
}
/// Room between a panel's edges and its contents
const PANEL_BODY_MARGIN: Margin = Margin::symmetric(8, 4);
/// The body of every panel except the viewport, in the dock or on the rail
pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) {
egui::Frame::new().inner_margin(PANEL_BODY_MARGIN).show(ui, |ui| match panel {
Panel::MeshMapSettings => crate::bake_mode::mesh_map_settings_panel(app, ui),
Panel::Assets => crate::shelf::body(app, ui),
Panel::CommonSettings => crate::bake_mode::common_settings_panel(app, ui),
Panel::MeshMapBakers => crate::bake_mode::mesh_map_bakers_panel(app, ui),
Panel::TextureSetList if app.ui.mode == crate::state::Mode::Baking => crate::bake_mode::texture_sets(app, ui),
Panel::TextureSetList => crate::dock::texture_set_list(app, ui),
Panel::Layers => crate::dock::layers(app, ui),
Panel::TextureSetSettings => crate::dock::texture_set_settings(app, ui),
Panel::Properties => crate::dock::properties(app, ui),
// Display and Shader Settings scroll here, as tall as their contents; History and Log scroll their own lists
Panel::Display => egui::ScrollArea::vertical().id_salt("dock-display").auto_shrink([false, true]).show(ui, |ui| crate::windows::display(app, ui)).inner,
Panel::Shader => egui::ScrollArea::vertical().id_salt("dock-shader").auto_shrink([false, true]).show(ui, |ui| crate::windows::shader(app, ui)).inner,
Panel::History => crate::windows::history(app, ui),
Panel::Log => crate::windows::log(app, ui),
Panel::Viewport => {}
});
}
impl DockContent<Panel> for Panels<'_> {
fn body(&mut self, ui: &mut Ui, panel: &Panel) {
let app = &mut *self.app;
if *panel == Panel::Viewport {
ui.painter().rect_filled(ui.max_rect(), 0.0, self.tk.viewport);
crate::rail_popup::remember_viewport(ui.ctx(), ui.max_rect());
ui.painter().rect_filled(ui.max_rect(), 0.0, self.tokens.viewport);
crate::viewport::central(app, ui);
return;
}
egui::Frame::new().inner_margin(Margin::symmetric(8, 4)).show(ui, |ui| match panel {
Panel::MeshMapSettings => crate::bake_mode::mesh_map_settings_panel(app, ui),
Panel::Assets => crate::shelf::body(app, ui),
Panel::CommonSettings => crate::bake_mode::common_settings_panel(app, ui),
Panel::MeshMapBakers => crate::bake_mode::mesh_map_bakers_panel(app, ui),
Panel::TextureSetList if app.ui.mode == crate::state::Mode::Baking => crate::bake_mode::texture_sets(app, ui),
Panel::TextureSetList => crate::dock::texture_set_list(app, ui),
Panel::Layers => crate::dock::layers(app, ui),
Panel::TextureSetSettings => crate::dock::texture_set_settings(app, ui),
Panel::Properties => crate::dock::properties(app, ui),
// The other panels scroll their own lists.
Panel::Display => {
egui::ScrollArea::vertical().id_salt("dock-display").auto_shrink([false, false]).show(ui, |ui| crate::windows::display(app, ui)).inner
}
Panel::Shader => {
egui::ScrollArea::vertical().id_salt("dock-shader").auto_shrink([false, false]).show(ui, |ui| crate::windows::shader(app, ui)).inner
}
Panel::History => crate::windows::history(app, ui),
Panel::Log => crate::windows::log(app, ui),
Panel::Viewport => {}
});
panel_body(app, ui, *panel);
}
fn logical_label(&self, panel: &Panel) -> String {
Loaded 100 of 170 files, more files were not shown because too many files have changed in this diff. Show more