mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-25 08:50:46 +01:00
Merge main and preserve OBJ declaration identity with shared reader
This commit is contained in:
commit
3e72bd73a4
147 files changed
+20239
-3768
No files matched your search
@@ -229,3 +229,7 @@ after every arc of work that builds and passes.
|
||||
- `docs/releasing.md`: release builds and signing.
|
||||
- `plan/` is an optional gitignored notebook (execution notes). Do not ask for it and do not stop when it is absent.
|
||||
- `log/` (local, gitignored): the dev log.
|
||||
|
||||
## Shared Craft libraries
|
||||
|
||||
Before adding or changing reusable file-format, codec, protocol or UI code, check [craft-libs](https://github.com/storytold/craft-libs) and existing contributor work; reuse its public APIs or extend the appropriate shared library instead of adding an app-local duplicate, keeping app-specific policy and model mapping local and preserving compatibility, security limits and regression coverage.
|
||||
Generated
+62
-12
@@ -755,6 +755,15 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=272a095b61257917693da3d09f2f8ecccd7f0295#272a095b61257917693da3d09f2f8ecccd7f0295"
|
||||
dependencies = [
|
||||
"md-5",
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
@@ -818,9 +827,9 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mcmat"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b6d9feed23ceae249b40593ed84a668343091627#b6d9feed23ceae249b40593ed84a668343091627"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83"
|
||||
dependencies = [
|
||||
"craft-zip",
|
||||
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
@@ -842,7 +851,11 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mesh"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d6ed8c20f12188c1f39c89b3a8436bd0d09c3748#d6ed8c20f12188c1f39c89b3a8436bd0d09c3748"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b952ca0231867c8ad6749ac44cab5fc903c3ad52#b952ca0231867c8ad6749ac44cab5fc903c3ad52"
|
||||
dependencies = [
|
||||
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b952ca0231867c8ad6749ac44cab5fc903c3ad52)",
|
||||
"miniz_oxide 0.9.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
@@ -855,6 +868,17 @@ dependencies = [
|
||||
"objc2-app-kit 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-tcraft"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83"
|
||||
dependencies = [
|
||||
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
@@ -903,6 +927,15 @@ dependencies = [
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-usd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f7655fb3ea59d6b21681700c0ff880823f5bb709#f7655fb3ea59d6b21681700c0ff880823f5bb709"
|
||||
dependencies = [
|
||||
"lz4_flex",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
@@ -927,7 +960,17 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b6d9feed23ceae249b40593ed84a668343091627#b6d9feed23ceae249b40593ed84a668343091627"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b952ca0231867c8ad6749ac44cab5fc903c3ad52#b952ca0231867c8ad6749ac44cab5fc903c3ad52"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2499,6 +2542,16 @@ version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4"
|
||||
|
||||
[[package]]
|
||||
name = "md-5"
|
||||
version = "0.10.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
@@ -4414,10 +4467,13 @@ name = "texturecraft-formats"
|
||||
version = "0.6.1"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"craft-cms",
|
||||
"craft-materialx",
|
||||
"craft-mcmat",
|
||||
"craft-mesh",
|
||||
"craft-zip",
|
||||
"craft-tcraft",
|
||||
"craft-usd",
|
||||
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)",
|
||||
"exr",
|
||||
"flate2",
|
||||
"gltf",
|
||||
@@ -4434,7 +4490,6 @@ dependencies = [
|
||||
"texturecraft-geom",
|
||||
"texturecraft-texel",
|
||||
"thiserror 2.0.21",
|
||||
"tobj",
|
||||
"zip",
|
||||
]
|
||||
|
||||
@@ -4474,6 +4529,7 @@ dependencies = [
|
||||
"log",
|
||||
"pollster 0.4.0",
|
||||
"rayon",
|
||||
"serde",
|
||||
"texturecraft-bake",
|
||||
"texturecraft-compose",
|
||||
"texturecraft-core",
|
||||
@@ -4631,12 +4687,6 @@ dependencies = [
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tobj"
|
||||
version = "4.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6eb8e04167c1c0c76b5de63226fd733485ad63ef71e40de31e16272f47b099e2"
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.53.3"
|
||||
|
||||
+5
-4
@@ -12,6 +12,7 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/texturecraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-usd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f7655fb3ea59d6b21681700c0ff880823f5bb709" }
|
||||
# internal
|
||||
texturecraft-core = { path = "crates/core" }
|
||||
texturecraft-texel = { path = "crates/texel" }
|
||||
@@ -49,7 +50,6 @@ wgpu = "30"
|
||||
rfd = "0.17"
|
||||
zip = { version = "9", default-features = false, features = ["deflate"] }
|
||||
gltf = { version = "1.4", default-features = false, features = ["import", "utils", "names", "KHR_materials_emissive_strength"] }
|
||||
tobj = { version = "4", default-features = false }
|
||||
flate2 = "1"
|
||||
lz4_flex = { version = "0.11", default-features = false, features = ["safe-decode", "safe-encode"] }
|
||||
quick-xml = "0.41"
|
||||
@@ -69,9 +69,10 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr
|
||||
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] }
|
||||
craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" }
|
||||
craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d6ed8c20f12188c1f39c89b3a8436bd0d09c3748", default-features = false, features = ["stl"] }
|
||||
craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "b6d9feed23ceae249b40593ed84a668343091627" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "b6d9feed23ceae249b40593ed84a668343091627" }
|
||||
craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" }
|
||||
craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "b952ca0231867c8ad6749ac44cab5fc903c3ad52", default-features = false, features = ["stl", "ply", "fbx", "obj"] }
|
||||
craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" }
|
||||
# Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs).
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] }
|
||||
# Release checks, the update prompt and the update helper (crates/ui-egui/src/updates_ui.rs).
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ end to end today (engine + UI + automation + tests), not what is planned.
|
||||
| Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, **asks to save unsaved changes** before quitting or replacing the project (in the browser too, and before the tab closes), recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, **MaterialX import** (`file.importMaterialX`: a `.mtlx` material with `open_pbr_surface`, `standard_surface` or `gltf_pbr` becomes one fill layer with its textures and values), image resources, remove unused resources, textured OBJ (MTL), GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) |
|
||||
| Texture sets | 6 | 100% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile** whose filters and height slopes keep their size in UV space, one texture per tile at its own size, `$udim` export), list with visibility (show or hide all, invert, **focus** on one set), sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | — |
|
||||
| Layer stack | 16 | 98% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels (with a histogram of its input), invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; effects **dragged to reorder**, duplicated, and **copied, cut and pasted** across layers, masks and sets (Ctrl+C, Ctrl+X, Ctrl+V, Ctrl+D and Delete act on a selected effect); smart masks; mask view (Alt+click); Alt+click a material channel to keep it alone; duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **30 library filters** (adjustments incl. histogram scan, range and shift, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog |
|
||||
| Painting tools | 14 | 91% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, **Ctrl+drag in a view for size, hardness, flow and angle**, X/Y/Z mirror and **radial symmetry**, pen pressure in the 3D and 2D views (Windows Ink, and touch pens in the browser), procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt, and pen pressure on Linux, macOS and desktop browsers (not exposed by the windowing layer) |
|
||||
| Painting tools | 14 | 91% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, material picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, **Ctrl+drag in a view for size, hardness, flow and angle**, X/Y/Z mirror and **radial symmetry**, pen pressure in the 3D and 2D views (Windows Ink, and touch pens in the browser), procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt, and pen pressure on Linux, macOS and desktop browsers (not exposed by the windowing layer) |
|
||||
| Materials and assets | 8 | 92% | **MaterialCraft materials** (`.mcmat`, sent to the shelf from MaterialCraft) as fill layers whose graph inputs and presets stay editable, re-cooked at the set's resolution with its baked mesh maps; 63 procedural materials (incl. car paint, velvet, brushed steel, skin, wax, ice, snow, bark), 21 smart materials, 24 smart masks, **67 procedural brush alphas**, **18 brush presets** plus user presets, 23 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's |
|
||||
| Baking | 10 | 90% | All ten mesh-map bakers; low-poly and high-to-low baking with CPU/GPU tracing; mesh-name matching, backface filtering, custom and distance-based cages, frontal/rear distances and average normals; undoable 2D cage/skew painting saved per texture set; rectangular output, antialiasing, dilation/diffusion, ID sources, ray filters, AO attenuation/ground plane, curvature controls and map normalization; per-texture-set selection, progress/cancel and mesh-map import | Residual Painter map differences; reference validation for Height, Bent Normal and Opacity and across additional assets; 3D cage-editing overlay |
|
||||
| Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, the baked normal map under the painted normal, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes of the mesh's own polygons, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser**; picks a discrete GPU on multi-GPU machines (`--gpu`, `WGPU_ADAPTER_NAME`, `WGPU_POWER_PREF`), and display textures are made on demand so a mesh with many materials imports on a small GPU | Hardware ray tracing |
|
||||
|
||||
@@ -16,6 +16,8 @@ pub struct CageShell {
|
||||
pub starts: Vec<RayStart>,
|
||||
/// Corner pairs along the low poly's polygon edges, for the wireframe
|
||||
pub edges: Vec<[u32; 2]>,
|
||||
/// Corner pairs along the low poly's hard edges without a UV seam
|
||||
pub missing_seams: Vec<[u32; 2]>,
|
||||
/// World units per unit of the max frontal distance setting
|
||||
pub cage_units: f32,
|
||||
}
|
||||
@@ -24,6 +26,30 @@ impl CageShell {
|
||||
/// The cage of `request`'s texture set, from the same ray starts the bake uses
|
||||
pub fn new(request: &BakeRequest) -> Result<CageShell, BakeError> {
|
||||
let ray_frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?;
|
||||
Self::build(request, ray_frame, || {
|
||||
// Each scan drops other materials' edges before the next scan starts
|
||||
let wire_edges = request.mesh.wire_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect();
|
||||
let missing_seam_edges = request.mesh.missing_seam_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect();
|
||||
(wire_edges, missing_seam_edges)
|
||||
})
|
||||
}
|
||||
|
||||
/// Build a cage using edges already scanned for every material of the low mesh
|
||||
pub fn new_with_edges(request: &BakeRequest, wire_edges: &[Vec<(u32, u32)>], missing_seam_edges: &[Vec<(u32, u32)>]) -> Result<CageShell, BakeError> {
|
||||
let ray_frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?;
|
||||
Self::build(request, ray_frame, || {
|
||||
(
|
||||
wire_edges.get(request.material).into_iter().flatten().copied().collect(),
|
||||
missing_seam_edges.get(request.material).into_iter().flatten().copied().collect(),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn build(
|
||||
request: &BakeRequest,
|
||||
ray_frame: RayFrame,
|
||||
edge_sets: impl FnOnce() -> (HashSet<(u32, u32)>, HashSet<(u32, u32)>),
|
||||
) -> Result<CageShell, BakeError> {
|
||||
let (frame, mesh) = (&ray_frame, request.mesh);
|
||||
let triangles: Vec<usize> = mesh.triangles_of(request.material).collect();
|
||||
let (positions, starts): (Vec<Vec3>, Vec<RayStart>) = triangles
|
||||
@@ -36,8 +62,8 @@ impl CageShell {
|
||||
})
|
||||
.unzip();
|
||||
|
||||
let wire_edges: HashSet<(u32, u32)> = mesh.wire_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect();
|
||||
let mut edge_corners = HashMap::new();
|
||||
let (wire_edges, missing_seam_edges) = edge_sets();
|
||||
let (mut edge_corners, mut seam_corners) = (HashMap::new(), HashMap::new());
|
||||
for (triangle_index, &triangle) in triangles.iter().enumerate() {
|
||||
let Some(vertices) = mesh.tri(triangle) else { continue };
|
||||
|
||||
@@ -45,16 +71,23 @@ impl CageShell {
|
||||
let next = (corner + 1) % 3;
|
||||
let (from, to) = (vertices[corner] as u32, vertices[next] as u32);
|
||||
let key = (from.min(to), from.max(to));
|
||||
let first_corner = (triangle_index * 3) as u32;
|
||||
let corners = [first_corner + corner as u32, first_corner + next as u32];
|
||||
if wire_edges.contains(&key) {
|
||||
let first_corner = (triangle_index * 3) as u32;
|
||||
edge_corners.entry(key).or_insert([first_corner + corner as u32, first_corner + next as u32]);
|
||||
edge_corners.entry(key).or_insert(corners);
|
||||
}
|
||||
if missing_seam_edges.contains(&key) {
|
||||
seam_corners.entry(key).or_insert(corners);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut edges: Vec<[u32; 2]> = edge_corners.into_values().collect();
|
||||
edges.sort_unstable();
|
||||
let sorted = |corners: HashMap<(u32, u32), [u32; 2]>| {
|
||||
let mut pairs: Vec<[u32; 2]> = corners.into_values().collect();
|
||||
pairs.sort_unstable();
|
||||
pairs
|
||||
};
|
||||
|
||||
Ok(CageShell { positions, starts, edges, cage_units: ray_frame.cage_units })
|
||||
Ok(CageShell { positions, starts, edges: sorted(edge_corners), missing_seams: sorted(seam_corners), cage_units: ray_frame.cage_units })
|
||||
}
|
||||
|
||||
/// Each corner's cage position at `max_frontal`, the setting before relative-to-bounding-box scaling
|
||||
|
||||
@@ -9,6 +9,7 @@ mod bake_request;
|
||||
mod cage;
|
||||
mod high_poly;
|
||||
mod mesh_extent;
|
||||
mod name_pair;
|
||||
mod progress;
|
||||
|
||||
pub use bake_error::BakeError;
|
||||
@@ -17,6 +18,7 @@ pub use bake_request::BakeRequest;
|
||||
pub use cage::{CageShell, HighPolyReach, RayStart, VertexReach};
|
||||
pub use high_poly::HighPoly;
|
||||
pub(crate) use mesh_extent::MeshExtent;
|
||||
pub use name_pair::NamePair;
|
||||
pub use progress::Progress;
|
||||
|
||||
mod map;
|
||||
|
||||
@@ -4,8 +4,10 @@ mod curvature_tuning;
|
||||
mod diffusion;
|
||||
mod normal_curvature;
|
||||
mod normalization;
|
||||
mod part_key;
|
||||
pub(crate) use diffusion::diffuse;
|
||||
pub(crate) use normalization::normalize;
|
||||
pub(crate) use part_key::part_key;
|
||||
mod sample;
|
||||
mod seam;
|
||||
pub(crate) use seam::fix_seams;
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// A mesh part's key in `keys` (shared by names that agree once `suffix` is dropped), whether it ignores backfaces, and its lowercase name without that suffix
|
||||
pub(crate) fn part_key(name: &str, suffix: &str, backface_suffix: &str, keys: &mut HashMap<String, u32>) -> (u32, bool, String) {
|
||||
let name = name.trim().to_lowercase();
|
||||
let ignore_backface = !backface_suffix.is_empty() && name.ends_with(backface_suffix);
|
||||
let name = if ignore_backface { name.strip_suffix(backface_suffix).unwrap_or(&name).to_owned() } else { name };
|
||||
|
||||
(match_key(&name, suffix, keys), ignore_backface, name)
|
||||
}
|
||||
|
||||
/// The key in `keys` of the lowercase part name `name` without `suffix`
|
||||
fn match_key(name: &str, suffix: &str, keys: &mut HashMap<String, u32>) -> u32 {
|
||||
let suffix = suffix.trim().to_lowercase();
|
||||
let base = name.strip_suffix(suffix.as_str()).filter(|_| !suffix.is_empty()).unwrap_or(name).to_string();
|
||||
let next = keys.len() as u32;
|
||||
*keys.entry(base).or_insert(next)
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
use super::part_key::part_key;
|
||||
use super::sampling::{generated_hue, interpolate, splitmix64};
|
||||
use crate::BakeRequest;
|
||||
use crate::tracing::{ANY, TraceMesh};
|
||||
@@ -50,21 +51,24 @@ impl<'a> Source<'a> {
|
||||
let mut mesh_ids = Vec::with_capacity(mesh.submeshes.len());
|
||||
let mut part_keys = Vec::with_capacity(mesh.submeshes.len());
|
||||
let backface_suffix = settings.ignore_backface_suffix.trim().to_lowercase();
|
||||
|
||||
for (part_index, submesh) in mesh.submeshes.iter().enumerate() {
|
||||
let first_triangle = (submesh.start / 3) as usize;
|
||||
let last_triangle = (submesh.start.saturating_add(submesh.count) / 3) as usize;
|
||||
let range = first_triangle.min(last_triangle)..last_triangle.min(triangle_count);
|
||||
part.get_mut(range.clone()).unwrap_or_default().fill(part_index as u32);
|
||||
let name = submesh.name.trim().to_lowercase();
|
||||
let ignore_backface = !backface_suffix.is_empty() && name.ends_with(&backface_suffix);
|
||||
|
||||
let (key, ignore_backface, name) = part_key(&submesh.name, suffix, &backface_suffix, keys);
|
||||
backface_culling.get_mut(range).unwrap_or_default().fill(ignore_backface);
|
||||
let name = if ignore_backface { name.strip_suffix(&backface_suffix).unwrap_or(&name) } else { &name };
|
||||
part_keys.push(match_key(name, suffix, keys));
|
||||
part_keys.push(key);
|
||||
|
||||
let next = mesh_keys.len() as u32;
|
||||
let file_id = file_ids.get(part_index).copied().unwrap_or(0);
|
||||
mesh_ids.push(*mesh_keys.entry((file_id, name.to_owned())).or_insert(next));
|
||||
mesh_ids.push(*mesh_keys.entry((file_id, name)).or_insert(next));
|
||||
}
|
||||
|
||||
let key = part.iter().map(|part_index| part_keys.get(*part_index as usize).copied().unwrap_or(ANY)).collect();
|
||||
|
||||
Source {
|
||||
mesh,
|
||||
bvh,
|
||||
@@ -138,11 +142,3 @@ fn base_color(material: &BaseColor, uv: Vec2) -> Vec4 {
|
||||
let color = sampled_color * material.factor;
|
||||
Vec4::new(linear_to_srgb(color.x), linear_to_srgb(color.y), linear_to_srgb(color.z), color.w)
|
||||
}
|
||||
|
||||
fn match_key(name: &str, suffix: &str, keys: &mut HashMap<String, u32>) -> u32 {
|
||||
let name = name.trim().to_lowercase();
|
||||
let suffix = suffix.trim().to_lowercase();
|
||||
let base = name.strip_suffix(suffix.as_str()).filter(|_| !suffix.is_empty()).unwrap_or(&name).to_string();
|
||||
let next = keys.len() as u32;
|
||||
*keys.entry(base).or_insert(next)
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
//! How "By Mesh Name" pairs low-poly parts with high-poly parts, listed before a bake runs
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use texturecraft_core::HighPolySettings;
|
||||
use texturecraft_geom::Mesh;
|
||||
|
||||
use crate::map::part_key;
|
||||
|
||||
/// A low-poly part and the high-poly part its rays may hit under "By Mesh Name"; one side is missing when that part pairs with nothing
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct NamePair {
|
||||
/// The low-poly part's name as in its mesh
|
||||
pub low: Option<String>,
|
||||
/// The high-poly part's name as in its mesh
|
||||
pub high: Option<String>,
|
||||
}
|
||||
|
||||
impl NamePair {
|
||||
/// Each part of `low` in `material` with every `high` part it pairs with (a row per pair), then the `high` parts pairing with none; keyed like the bake, low poly first
|
||||
pub fn list(low: &Mesh, material: usize, high: &Mesh, settings: &HighPolySettings) -> Vec<NamePair> {
|
||||
let backface_suffix = settings.ignore_backface_suffix.trim().to_lowercase();
|
||||
let mut keys = HashMap::new();
|
||||
let mut keyed = |mesh: &Mesh, suffix: &str, only_material: Option<usize>| {
|
||||
let mut seen = HashSet::new();
|
||||
let mut parts = Vec::new();
|
||||
for part in mesh.submeshes.iter().filter(|part| only_material.is_none_or(|material| part.material == material)) {
|
||||
let (key, ..) = part_key(&part.name, suffix, &backface_suffix, &mut keys);
|
||||
if seen.insert(part.name.as_str()) {
|
||||
parts.push((key, part.name.clone()));
|
||||
}
|
||||
}
|
||||
parts
|
||||
};
|
||||
let low_parts = keyed(low, &settings.low_suffix, Some(material));
|
||||
let high_parts = keyed(high, &settings.high_suffix, None);
|
||||
|
||||
let mut pairs = Vec::new();
|
||||
for (key, low_name) in &low_parts {
|
||||
let matches: Vec<&String> = high_parts.iter().filter(|(high_key, _)| high_key == key).map(|(_, name)| name).collect();
|
||||
if matches.is_empty() {
|
||||
pairs.push(NamePair { low: Some(low_name.clone()), high: None });
|
||||
}
|
||||
pairs.extend(matches.into_iter().map(|high_name| NamePair { low: Some(low_name.clone()), high: Some(high_name.clone()) }));
|
||||
}
|
||||
|
||||
let low_keys: HashSet<u32> = low_parts.iter().map(|(key, _)| *key).collect();
|
||||
pairs.extend(high_parts.into_iter().filter(|(key, _)| !low_keys.contains(key)).map(|(_, name)| NamePair { low: None, high: Some(name) }));
|
||||
pairs
|
||||
}
|
||||
|
||||
/// Whether one side is missing: a part the bake will leave unpaired
|
||||
pub fn unpaired(&self) -> bool {
|
||||
self.low.is_none() || self.high.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use texturecraft_geom::SubMesh;
|
||||
|
||||
/// A mesh with one empty part per (name, material)
|
||||
fn parts(names: &[(&str, usize)]) -> Mesh {
|
||||
Mesh {
|
||||
submeshes: names.iter().map(|(name, material)| SubMesh { name: (*name).into(), material: *material, start: 0, count: 0 }).collect(),
|
||||
materials: vec!["first".into(), "second".into()],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn pair(low: Option<&str>, high: Option<&str>) -> NamePair {
|
||||
NamePair { low: low.map(Into::into), high: high.map(Into::into) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parts_pair_by_name_without_their_suffixes() {
|
||||
let low = parts(&[("Barrel_low", 0), ("Base_low", 0), ("Slide_low", 1)]);
|
||||
let high = parts(&[("Barrel_high", 0), ("Slide_high", 0), ("Grip_high", 0), ("BARREL_high_ignorebf", 0)]);
|
||||
let settings = HighPolySettings::default();
|
||||
|
||||
assert_eq!(
|
||||
NamePair::list(&low, 0, &high, &settings),
|
||||
vec![
|
||||
pair(Some("Barrel_low"), Some("Barrel_high")),
|
||||
pair(Some("Barrel_low"), Some("BARREL_high_ignorebf")),
|
||||
pair(Some("Base_low"), None),
|
||||
pair(None, Some("Slide_high")),
|
||||
pair(None, Some("Grip_high")),
|
||||
],
|
||||
"another material's parts are left out, so its high-poly part counts as unpaired here"
|
||||
);
|
||||
assert_eq!(NamePair::list(&low, 1, &high, &settings).iter().filter(|pair| !pair.unpaired()).count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_part_split_over_triangle_ranges_is_listed_once() {
|
||||
let low = parts(&[("Body_low", 0), ("Body_low", 0)]);
|
||||
let high = parts(&[("Body_high", 0), ("Body_high", 0)]);
|
||||
|
||||
assert_eq!(NamePair::list(&low, 0, &high, &HighPolySettings::default()), vec![pair(Some("Body_low"), Some("Body_high"))]);
|
||||
}
|
||||
}
|
||||
@@ -101,3 +101,92 @@ fn the_cage_follows_the_frontal_distance_and_a_cage_mesh() {
|
||||
assert!(corners.iter().all(|corner| (corner.abs().max_element() - 0.75).abs() < 1e-6), "the cage mesh is drawn as it is");
|
||||
assert!(corners.iter().all(|corner| corner.is_finite() && *corner != Vec3::ZERO));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cage_lists_its_hard_edges_without_a_uv_seam() {
|
||||
// A quad whose diagonal is split into two vertices with the same UV, smooth or hard by the copy's normal
|
||||
let quad_with_diagonal_normal = |normal: Vec3| {
|
||||
let mut mesh = Mesh::from_parts(
|
||||
vec![Vec3::ZERO, Vec3::X, Vec3::new(1.0, 1.0, 0.0), Vec3::Y],
|
||||
None,
|
||||
vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 0.0)],
|
||||
vec![0, 1, 2, 0, 2, 3],
|
||||
"Default",
|
||||
)
|
||||
.unwrap();
|
||||
mesh.positions.push(mesh.positions[0]);
|
||||
mesh.normals.push(normal);
|
||||
mesh.tangents.push(mesh.tangents[0]);
|
||||
mesh.uvs.push(mesh.uvs[0]);
|
||||
mesh.indices[3] = 4;
|
||||
mesh
|
||||
};
|
||||
let shell_of = |low: &Mesh| {
|
||||
let bvh = Bvh::new(low);
|
||||
let bake_settings = settings(16, &[BakedMap::Normal]);
|
||||
let request = BakeRequest {
|
||||
low_base_color: &[],
|
||||
mesh: low,
|
||||
bvh: &bvh,
|
||||
material: 0,
|
||||
settings: &bake_settings,
|
||||
high: Some(HighPoly { file_ids: &[], mesh: low, bvh: &bvh, base_color: &[] }),
|
||||
cage: None,
|
||||
skew: None,
|
||||
cage_paint: None,
|
||||
tiles: (1, 1),
|
||||
};
|
||||
let shell = CageShell::new(&request).unwrap();
|
||||
let shared = CageShell::new_with_edges(&request, &low.wire_edges(), &low.missing_seam_edges()).unwrap();
|
||||
assert_eq!(shared.positions, shell.positions);
|
||||
assert_eq!(shared.corners(0.1), shell.corners(0.1));
|
||||
assert_eq!(shared.edges, shell.edges);
|
||||
assert_eq!(shared.missing_seams, shell.missing_seams);
|
||||
shell
|
||||
};
|
||||
|
||||
let smooth = quad_with_diagonal_normal(Vec3::Z);
|
||||
assert!(shell_of(&smooth).missing_seams.is_empty(), "the same normal on both sides is a smooth edge");
|
||||
|
||||
let hard = quad_with_diagonal_normal(Vec3::new(1.0, 0.0, 1.0).normalize());
|
||||
let shell = shell_of(&hard);
|
||||
let diagonal = [Vec3::ZERO, Vec3::new(1.0, 1.0, 0.0)];
|
||||
assert_eq!(shell.missing_seams.len(), 2, "the diagonal, once per triangle");
|
||||
for [from, to] in &shell.missing_seams {
|
||||
let mut ends = [shell.positions[*from as usize], shell.positions[*to as usize]];
|
||||
ends.sort_by(|a, b| a.x.total_cmp(&b.x));
|
||||
assert_eq!(ends, diagonal, "the line runs along the hard diagonal");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_edges_select_the_requested_material() {
|
||||
let mut mesh = primitives::cube(1.0);
|
||||
mesh.append(&primitives::cube(1.0));
|
||||
let bvh = Bvh::new(&mesh);
|
||||
let bake_settings = settings(16, &[BakedMap::Normal]);
|
||||
let wire_edges = mesh.wire_edges();
|
||||
let missing_seam_edges = mesh.missing_seam_edges();
|
||||
|
||||
for material in 0..mesh.materials.len() {
|
||||
let request = BakeRequest {
|
||||
low_base_color: &[],
|
||||
mesh: &mesh,
|
||||
bvh: &bvh,
|
||||
material,
|
||||
settings: &bake_settings,
|
||||
high: None,
|
||||
cage: None,
|
||||
skew: None,
|
||||
cage_paint: None,
|
||||
tiles: (1, 1),
|
||||
};
|
||||
let direct = CageShell::new(&request).unwrap();
|
||||
let shared = CageShell::new_with_edges(&request, &wire_edges, &missing_seam_edges).unwrap();
|
||||
|
||||
assert_eq!(shared.positions, direct.positions);
|
||||
assert_eq!(shared.starts, direct.starts);
|
||||
assert_eq!(shared.edges, direct.edges);
|
||||
assert_eq!(shared.missing_seams, direct.missing_seams);
|
||||
}
|
||||
}
|
||||
@@ -157,6 +157,7 @@ impl StackKey {
|
||||
match &effect.kind {
|
||||
EffectKind::Fill { source, .. } => record_image_reference(source),
|
||||
EffectKind::Material(fill) => fill.sources.values().for_each(&mut record_image_reference),
|
||||
EffectKind::Generator(generator) => generator.inputs.values().for_each(&mut record_image_reference),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -279,7 +280,7 @@ impl BelowCache {
|
||||
self.clock += 1;
|
||||
*stamp = self.clock;
|
||||
self.order.push_back((t, self.clock));
|
||||
// Drop superseded uses once they outnumber the tiles.
|
||||
// Drop superseded uses once they outnumber the tiles
|
||||
if self.order.len() > 2 * self.tiles.len() + 64 {
|
||||
let tiles = &self.tiles;
|
||||
self.order.retain(|(t, s)| tiles.get(t).is_some_and(|(stamp, _)| stamp == s));
|
||||
|
||||
@@ -125,8 +125,7 @@ fn store(curvature: &Arc<Vec<f32>>, key: CacheKey, scales: &BlockScales, sizes:
|
||||
sizes
|
||||
};
|
||||
|
||||
// Keep distinct layouts: thumbnails and the viewport alternate on the same bake.
|
||||
// Replacing only this variant prevents them from repeatedly rebuilding each other.
|
||||
// Keep layout variants so thumbnails and the viewport reuse their own levels
|
||||
cache.retain(|entry| entry.0.strong_count() > 0 && !is_entry_for(entry, curvature, key, scales));
|
||||
let sizes = Arc::new(sizes);
|
||||
cache.push((Arc::downgrade(curvature), key, scales.clone(), sizes.clone()));
|
||||
@@ -410,7 +409,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
// Cache lifecycle tests must not evict each other's entries in parallel.
|
||||
// Cache lifecycle tests must not evict each other's entries in parallel
|
||||
static CACHE_TESTS: Mutex<()> = Mutex::new(());
|
||||
|
||||
#[test]
|
||||
|
||||
+397
-124
@@ -279,12 +279,24 @@ fn neighbourhood(effects: &[Effect], res: u32) -> Option<(usize, f32, Op)> {
|
||||
neighbourhood_filters(effects, res).last()
|
||||
}
|
||||
|
||||
/// Below this a coverage weight counts as no coverage at all.
|
||||
const MIN_COVERAGE_WEIGHT: f32 = 1e-6;
|
||||
/// Filter sizes are texels at this many texels per side (2K), scaled to the resolution they run at.
|
||||
const FILTER_SIZE_RESOLUTION: f32 = 2048.0;
|
||||
/// The smallest radius a filter runs at, in texels.
|
||||
const MIN_FILTER_RADIUS: f32 = 0.5;
|
||||
/// Sharpen's blur radius at [`FILTER_SIZE_RESOLUTION`], and the smallest it runs at, in texels.
|
||||
const SHARPEN_RADIUS: f32 = 1.5;
|
||||
const MIN_SHARPEN_RADIUS: f32 = 0.75;
|
||||
|
||||
/// The neighbourhood filters of an effect stack, bottom → top: index among the visible effects, radius in texels (`res` texels per UV tile across) and what it does.
|
||||
fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator<Item = (usize, f32, Op)> + '_ {
|
||||
let texels = move |size: f32| (size * res as f32 / 2048.0).max(0.5);
|
||||
let texels = move |size: f32| (size * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS);
|
||||
effects.iter().filter(|effect| effect.visible).enumerate().filter_map(move |(index, effect)| match &effect.kind {
|
||||
EffectKind::Filter(Filter::Blur { radius }) if *radius > 0.0 => Some((index, texels(*radius), Op::Blur(None))),
|
||||
EffectKind::Filter(Filter::Sharpen { amount }) => Some((index, (1.5 * res as f32 / 2048.0).max(0.75), Op::Blur(Some(*amount)))),
|
||||
EffectKind::Filter(Filter::Sharpen { amount }) => {
|
||||
Some((index, (SHARPEN_RADIUS * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_SHARPEN_RADIUS), Op::Blur(Some(*amount))))
|
||||
}
|
||||
EffectKind::Filter(Filter::DirectionalBlur { radius, angle }) if *radius > 0.0 => Some((index, texels(*radius), Op::Line(direction(*angle)))),
|
||||
EffectKind::Filter(Filter::Warp { intensity, scale, seed }) if *intensity > 0.0 => {
|
||||
Some((index, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: None }))
|
||||
@@ -298,6 +310,10 @@ fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator<Item = (
|
||||
EffectKind::Filter(Filter::Bevel { width }) => Some((index, texels(*width * 0.5), Op::Bevel)),
|
||||
EffectKind::Filter(Filter::Glow { radius, amount }) => Some((index, texels(*radius), Op::Glow(*amount))),
|
||||
EffectKind::Filter(Filter::Mosaic { size }) => Some((index, texels(*size), Op::Mosaic)),
|
||||
// Independent of `res`, so every caller agrees on which effects are stages; the reach covers the cells, then the blur around them
|
||||
EffectKind::Generator(generator) if generator.global.blur > 0.0 || generator.resolution.can_reduce() => {
|
||||
Some((index, texels(generator.global.blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None)))
|
||||
}
|
||||
EffectKind::Filter(Filter::SlopeBlur { radius, scale, seed }) if *radius > 0.0 => {
|
||||
Some((index, texels(*radius), Op::Slope { scale: *scale, seed: *seed }))
|
||||
}
|
||||
@@ -618,63 +634,74 @@ fn is_box_blur(op: Op) -> bool {
|
||||
/// The stack up to and including neighbourhood filter `filter` over texel `region`, continued from `start` (the filter below's field) when given.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn filter_region(
|
||||
inp: &Inputs,
|
||||
inputs: &Inputs,
|
||||
channels: &[Channel],
|
||||
below: &Fields,
|
||||
id: LayerId,
|
||||
job: Job,
|
||||
effects: &[Effect],
|
||||
(index, radius, op): (usize, f32, Op),
|
||||
(rx0, ry0, w, h): (u32, u32, u32, u32),
|
||||
(region_x, region_y, width, height): (u32, u32, u32, u32),
|
||||
start: Option<(usize, &Field)>,
|
||||
) -> Option<Field> {
|
||||
// Tiny coverage sums make normalization unstable
|
||||
const MIN_FILTER_WEIGHT: f32 = 1e-6;
|
||||
let filter_effect = effects.iter().filter(|effect| effect.visible).nth(index);
|
||||
let opacity = filter_effect.map(|effect| effect.opacity.clamp(0.0, 1.0)).unwrap_or(1.0);
|
||||
let (radius_texels, _) = filter_extent(radius, op, inputs.gbuf.width.max(inputs.gbuf.height));
|
||||
|
||||
let opacity = effects.iter().filter(|effect| effect.visible).nth(index).map(|effect| effect.opacity.clamp(0.0, 1.0)).unwrap_or(1.0);
|
||||
let (radius_texels, _) = filter_extent(radius, op, inp.gbuf.width.max(inp.gbuf.height));
|
||||
let component_count = match job {
|
||||
// Generator stages keep their ramp beside the mask stack below
|
||||
let generator = match (job, filter_effect.map(|effect| (&effect.kind, effect.blend))) {
|
||||
(Job::Mask(_), Some((EffectKind::Generator(generator), blend))) => Some((generator, blend)),
|
||||
_ => None,
|
||||
};
|
||||
let components = match job {
|
||||
Job::Mask(_) if generator.is_some() => 2,
|
||||
Job::Mask(_) => 1,
|
||||
Job::Content(_) => 4,
|
||||
};
|
||||
|
||||
// Evaluate the stack up to the filter, tile by tile (content premultiplied by coverage)
|
||||
let (rx1, ry1) = (rx0 + w, ry0 + h);
|
||||
let region_tiles: Vec<(u32, u32)> = (ry0 / TILE..ry1.div_ceil(TILE)).flat_map(|y| (rx0 / TILE..rx1.div_ceil(TILE)).map(move |x| (x, y))).collect();
|
||||
let (region_right, region_bottom) = (region_x + width, region_y + height);
|
||||
let region_tiles: Vec<(u32, u32)> =
|
||||
(region_y / TILE..region_bottom.div_ceil(TILE)).flat_map(|y| (region_x / TILE..region_right.div_ceil(TILE)).map(move |x| (x, y))).collect();
|
||||
let parts: Vec<Vec<(u32, u32, [f32; 4])>> = region_tiles
|
||||
.par_iter()
|
||||
.map(|&(tx, ty)| {
|
||||
let anchor_nodes = anchor_plan(inp, id, channels, tx, ty, Some(below));
|
||||
let preview_tile = inp.preview.and_then(|preview| preview.alpha.tile(tx, ty));
|
||||
.map(|&(tile_x, tile_y)| {
|
||||
let anchor_nodes = anchor_plan(inputs, id, channels, tile_x, tile_y, Some(below));
|
||||
let preview_tile = inputs.preview.and_then(|preview| preview.alpha.tile(tile_x, tile_y));
|
||||
let mut mask = None;
|
||||
let mut nodes = Vec::new();
|
||||
let mut generator_sizes = None;
|
||||
match job {
|
||||
Job::Mask(layer_mask) => {
|
||||
let Some(mut mask_stack) = mask_plan(inp, id, layer_mask, tx, ty, None) else { return Vec::new() };
|
||||
let Some(mut mask_stack) = mask_plan(inputs, id, layer_mask, tile_x, tile_y, None) else { return Vec::new() };
|
||||
|
||||
generator_sizes = mask_stack.effects.get(index).and_then(|effect| effect.curvature_sizes.clone());
|
||||
mask_stack.effects.truncate(index);
|
||||
mask_stack.start = start;
|
||||
mask = Some(mask_stack);
|
||||
}
|
||||
Job::Content(channel) => {
|
||||
nodes = plan(inp, &[id], &[channel], tx, ty, 0, Some(below));
|
||||
nodes = plan(inputs, &[id], &[channel], tile_x, tile_y, 0, Some(below));
|
||||
if let Some(channel_plan) = nodes.first_mut().and_then(|node| node.chans.first_mut()) {
|
||||
channel_plan.effects.truncate(index);
|
||||
channel_plan.start = start;
|
||||
}
|
||||
}
|
||||
}
|
||||
tile_texels(inp.gbuf, tx, ty)
|
||||
tile_texels(inputs.gbuf, tile_x, tile_y)
|
||||
.map(|(x, y, offset)| {
|
||||
let mut texel = Texel::new(inp, x, y, offset, stroke_at(preview_tile, offset));
|
||||
let mut texel = Texel::new(inputs, x, y, offset, stroke_at(preview_tile, offset));
|
||||
if !anchor_nodes.is_empty() {
|
||||
texel.anchors_below(&anchor_nodes, id);
|
||||
}
|
||||
|
||||
let value = match (&mask, nodes.first()) {
|
||||
(Some(mask_stack), _) => [texel.mask(mask_stack), 0.0, 0.0, 0.0],
|
||||
(Some(mask_stack), _) => {
|
||||
let ramp = generator.map_or(0.0, |(generator, _)| texel.generator_ramp(generator, generator_sizes.as_deref()));
|
||||
[texel.mask(mask_stack), ramp, 0.0, 0.0]
|
||||
}
|
||||
(None, Some(node)) => match node.chans.first().and_then(|channel_plan| texel.content(&node.content, channel_plan)) {
|
||||
Some((color, alpha)) => [color[0] * alpha, color[1] * alpha, color[2] * alpha, alpha],
|
||||
Some((color, coverage)) => [color[0] * coverage, color[1] * coverage, color[2] * coverage, coverage],
|
||||
None => [0.0; 4],
|
||||
},
|
||||
(None, None) => [0.0; 4],
|
||||
@@ -686,103 +713,214 @@ fn filter_region(
|
||||
.collect();
|
||||
|
||||
// Scatter into the region, a row of tiles at a time (the region is tile aligned)
|
||||
let texel_count = (w * h) as usize;
|
||||
let mut original_values = vec![0.0f32; texel_count * component_count];
|
||||
let mut coverage = vec![0.0f32; texel_count];
|
||||
let row_tiles = (rx1.div_ceil(TILE) - rx0 / TILE).max(1) as usize;
|
||||
let band = (TILE * w) as usize;
|
||||
original_values.par_chunks_mut(band * component_count).zip(coverage.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each(
|
||||
|((original_values, coverage), row)| {
|
||||
for &(x, y, value) in row.iter().flatten() {
|
||||
let texel = (((y - ry0) % TILE) * w + (x - rx0)) as usize;
|
||||
if let (Some(covered), Some(pixel)) = (coverage.get_mut(texel), original_values.get_mut(texel * component_count..(texel + 1) * component_count))
|
||||
{
|
||||
*covered = 1.0;
|
||||
pixel.copy_from_slice(&value[..component_count]);
|
||||
}
|
||||
let texel_count = (width * height) as usize;
|
||||
let mut stack_values = vec![0.0f32; texel_count * components];
|
||||
let mut cover = vec![0.0f32; texel_count];
|
||||
let row_tiles = (region_right.div_ceil(TILE) - region_x / TILE).max(1) as usize;
|
||||
let band = (TILE * width) as usize;
|
||||
stack_values.par_chunks_mut(band * components).zip(cover.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each(|((stack_values, cover), row)| {
|
||||
for &(x, y, value) in row.iter().flatten() {
|
||||
let texel = (((y - region_y) % TILE) * width + (x - region_x)) as usize;
|
||||
if let (Some(covered), Some(pixel)) = (cover.get_mut(texel), stack_values.get_mut(texel * components..(texel + 1) * components)) {
|
||||
*covered = 1.0;
|
||||
pixel.copy_from_slice(&value[..components]);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Release scattered texels before allocating filter buffers
|
||||
// Release tile scatter data before allocating filter buffers
|
||||
drop(parts);
|
||||
|
||||
// High pass centers on the channel's midpoint value (0 for signed channels like height)
|
||||
let midpoint = match job {
|
||||
// High pass centers on the channel's middle value (0 for signed channels like height)
|
||||
let middle = match job {
|
||||
Job::Content(channel) if channel.kind() == ChannelKind::Signed => 0.0,
|
||||
_ => 0.5,
|
||||
};
|
||||
|
||||
// A smaller UV tile has fewer texels per UV unit, so its filters reach fewer texels
|
||||
let filtered = |scale: f32| -> Vec<f32> {
|
||||
let sampling_resolution = ((inp.tile_res() as f32 * scale).round() as u32).max(1);
|
||||
let scaled_radius = neighbourhood_filters(effects, sampling_resolution)
|
||||
let tile_resolution = ((inputs.tile_res() as f32 * scale).round() as u32).max(1);
|
||||
if let Some((generator, blend)) = generator {
|
||||
let texture_set = inputs.project.texture_set(inputs.ts).map_or(inputs.tile_res(), |set| set.resolution);
|
||||
return generator_region(generator, blend, opacity, &stack_values, &cover, (region_x, region_y, width, height), (tile_resolution, texture_set));
|
||||
}
|
||||
let scaled_radius = neighbourhood_filters(effects, tile_resolution)
|
||||
.find(|filter| filter.0 == index)
|
||||
.map_or(radius_texels, |filter| filter.1.round().clamp(1.0, radius_texels as f32) as u32);
|
||||
if !is_box_blur(op) {
|
||||
return gather(op, &original_values, &coverage, component_count, (rx0, ry0, w, h), scaled_radius as f32, sampling_resolution, opacity);
|
||||
return gather(op, &stack_values, &cover, components, (region_x, region_y, width, height), scaled_radius as f32, tile_resolution, opacity);
|
||||
}
|
||||
|
||||
// Weighted so uncovered texels don't bleed in
|
||||
let (width, height, blur_radius) = (w as usize, h as usize, scaled_radius as usize);
|
||||
let mut weights = coverage.clone();
|
||||
blur(&mut weights, width, height, blur_radius);
|
||||
let mut data = original_values.clone();
|
||||
for component in 0..component_count {
|
||||
let mut sums: Vec<f32> = original_values
|
||||
.par_chunks(component_count)
|
||||
.with_min_len(MIN_PARALLEL_TEXELS)
|
||||
.map(|pixel| pixel.get(component).copied().unwrap_or(0.0))
|
||||
.collect();
|
||||
blur(&mut sums, width, height, blur_radius);
|
||||
data.par_chunks_mut(component_count).with_min_len(MIN_PARALLEL_TEXELS).zip(sums.par_iter()).zip(weights.par_iter()).for_each(
|
||||
|((pixel, sum), weight)| {
|
||||
// Content is premultiplied, so the midpoint value is too (coverage itself is kept)
|
||||
let alpha = if component_count == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 };
|
||||
if *weight > MIN_FILTER_WEIGHT
|
||||
&& let Some(slot) = pixel.get_mut(component)
|
||||
{
|
||||
let (original, blurred) = (*slot, sum / weight);
|
||||
let result = match op {
|
||||
Op::Blur(Some(amount)) => original + amount * (original - blurred),
|
||||
Op::HighPass if component < 3 => original - blurred + midpoint * alpha,
|
||||
// Away from 0 by at most the value itself: 0 at the edge, full inside
|
||||
Op::Bevel if component < 3 => original.signum() * original.abs().min((2.0 * blurred * original.signum() - original.abs()).max(0.0)),
|
||||
Op::Glow(amount) if component < 3 => original + amount * blurred,
|
||||
Op::HighPass | Op::Bevel | Op::Glow(_) => original,
|
||||
_ => blurred,
|
||||
};
|
||||
*slot = original + (result - original) * opacity;
|
||||
}
|
||||
},
|
||||
);
|
||||
let (columns, rows, blur_radius) = (width as usize, height as usize, scaled_radius as usize);
|
||||
let mut weights = cover.clone();
|
||||
blur(&mut weights, columns, rows, blur_radius);
|
||||
let mut filtered_values = stack_values.clone();
|
||||
for component in 0..components {
|
||||
let mut sums: Vec<f32> = stack_values.par_chunks(components).map(|pixel| pixel.get(component).copied().unwrap_or(0.0)).collect();
|
||||
blur(&mut sums, columns, rows, blur_radius);
|
||||
filtered_values.par_chunks_mut(components).zip(sums.par_iter()).zip(weights.par_iter()).for_each(|((pixel, sum), weight)| {
|
||||
// Content is premultiplied, so the middle value is too (coverage itself is kept)
|
||||
let coverage = if components == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 };
|
||||
if *weight > MIN_COVERAGE_WEIGHT
|
||||
&& let Some(slot) = pixel.get_mut(component)
|
||||
{
|
||||
let (original, blurred) = (*slot, sum / weight);
|
||||
let result = match op {
|
||||
Op::Blur(Some(amount)) => original + amount * (original - blurred),
|
||||
Op::HighPass if component < 3 => original - blurred + middle * coverage,
|
||||
// Away from 0 by at most the value itself: 0 at the edge, full inside
|
||||
Op::Bevel if component < 3 => original.signum() * original.abs().min((2.0 * blurred * original.signum() - original.abs()).max(0.0)),
|
||||
Op::Glow(amount) if component < 3 => original + amount * blurred,
|
||||
Op::HighPass | Op::Bevel | Op::Glow(_) => original,
|
||||
_ => blurred,
|
||||
};
|
||||
*slot = original + (result - original) * opacity;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
data
|
||||
filtered_values
|
||||
};
|
||||
|
||||
// Each block keeps the result at its tile's scale (blocks are TILE aligned)
|
||||
let scales = inp.project.texture_set(inp.ts).map(TextureSet::block_scales).unwrap_or_default();
|
||||
let mut levels: Vec<f32> =
|
||||
(ry0..ry1).step_by(TILE as usize).flat_map(|y| (rx0..rx1).step_by(TILE as usize).map(move |x| (x, y))).map(|(x, y)| scales.at(x, y)).collect();
|
||||
let scales = inputs.project.texture_set(inputs.ts).map(TextureSet::block_scales).unwrap_or_default();
|
||||
let mut levels: Vec<f32> = (region_y..region_bottom)
|
||||
.step_by(TILE as usize)
|
||||
.flat_map(|y| (region_x..region_right).step_by(TILE as usize).map(move |x| (x, y)))
|
||||
.map(|(x, y)| scales.at(x, y))
|
||||
.collect();
|
||||
levels.sort_by(f32::total_cmp);
|
||||
levels.dedup();
|
||||
let (first, rest) = levels.split_first().map_or((1.0, &[][..]), |(first, rest)| (*first, rest));
|
||||
let mut data = filtered(first);
|
||||
|
||||
// A generator stage's field is the mask alone
|
||||
let field_components = if generator.is_some() { 1 } else { components };
|
||||
let mut result = filtered(first);
|
||||
for &scale in rest {
|
||||
let other = filtered(scale);
|
||||
let row = w as usize * component_count;
|
||||
data.par_chunks_mut(row).zip(other.par_chunks(row)).enumerate().for_each(|(y, (dst, src))| {
|
||||
for (x, (target, source)) in dst.chunks_mut(component_count).zip(src.chunks(component_count)).enumerate() {
|
||||
if scales.at(rx0 + x as u32, ry0 + y as u32) == scale {
|
||||
let rescaled = filtered(scale);
|
||||
let row = width as usize * field_components;
|
||||
result.par_chunks_mut(row).zip(rescaled.par_chunks(row)).enumerate().for_each(|(y, (target_row, source_row))| {
|
||||
for (x, (target, source)) in target_row.chunks_mut(field_components).zip(source_row.chunks(field_components)).enumerate() {
|
||||
if scales.at(region_x + x as u32, region_y + y as u32) == scale {
|
||||
target.copy_from_slice(source);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
unpremultiply(&mut data, component_count);
|
||||
Some(Field { x0: rx0, y0: ry0, w, h, comps: component_count, data })
|
||||
unpremultiply(&mut result, field_components);
|
||||
Some(Field { x0: region_x, y0: region_y, w: width, h: height, comps: field_components, data: result })
|
||||
}
|
||||
|
||||
/// The mask over a region after a generator at its own resolution and blur: `stack` is (stack below, generator ramp) per texel, sizes in texels per side.
|
||||
fn generator_region(
|
||||
generator: &Generator,
|
||||
blend: BlendMode,
|
||||
opacity: f32,
|
||||
stack: &[f32],
|
||||
cover: &[f32],
|
||||
(region_x, region_y, width, height): (u32, u32, u32, u32),
|
||||
(uv_tile, texture_set): (u32, u32),
|
||||
) -> Vec<f32> {
|
||||
let (columns, rows) = (width as usize, height as usize);
|
||||
let mut ramps: Vec<f32> = stack.par_chunks(2).map(|texel| texel.get(1).copied().unwrap_or(0.0)).collect();
|
||||
|
||||
// Coarser than the UV tile: averaged over cells, then the blur around them
|
||||
let cell = generator.resolution.cell(uv_tile, texture_set) as usize;
|
||||
if cell > 1 {
|
||||
ramps = resampled_by_cells(&ramps, cover, (region_x as usize, region_y as usize, columns, rows), cell);
|
||||
}
|
||||
|
||||
let blur_radius = generator.global.blur_radius_at(uv_tile).round() as usize;
|
||||
if blur_radius > 0 {
|
||||
let mut weights = cover.to_vec();
|
||||
blur(&mut weights, columns, rows, blur_radius);
|
||||
let mut sums: Vec<f32> = ramps.iter().zip(cover).map(|(ramp, covered)| ramp * covered).collect();
|
||||
blur(&mut sums, columns, rows, blur_radius);
|
||||
ramps.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).for_each(|(ramp, (sum, weight))| {
|
||||
if *weight > MIN_COVERAGE_WEIGHT {
|
||||
*ramp = sum / weight;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Finished and blended over the stack below, like the generator effect itself
|
||||
stack
|
||||
.par_chunks(2)
|
||||
.zip(ramps.par_iter())
|
||||
.map(|(texel, ramp)| {
|
||||
let below = texel.first().copied().unwrap_or(0.0);
|
||||
let generated = finish_generator(generator, *ramp);
|
||||
below + (blend1(blend, below, generated) - below) * opacity
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `values` averaged over `cell` × `cell` texel cells on the mesh (`cover`), read back bilinearly between cell centers.
|
||||
fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, height): (usize, usize, usize, usize), cell: usize) -> Vec<f32> {
|
||||
// Cells are aligned to absolute texel positions, so a texel's cell is the same in every region
|
||||
let (first_column, first_row) = (region_x / cell, region_y / cell);
|
||||
let columns = (region_x + width).div_ceil(cell) - first_column;
|
||||
let rows = (region_y + height).div_ceil(cell) - first_row;
|
||||
|
||||
// Each cell's coverage-weighted average, a row of cells at a time
|
||||
let averages: Vec<Option<f32>> = (0..rows)
|
||||
.into_par_iter()
|
||||
.flat_map_iter(|row| {
|
||||
let mut sums = vec![(0.0f32, 0.0f32); columns];
|
||||
let first_y = ((first_row + row) * cell).saturating_sub(region_y);
|
||||
let last_y = ((first_row + row + 1) * cell).saturating_sub(region_y).min(height);
|
||||
for y in first_y..last_y {
|
||||
for x in 0..width {
|
||||
let texel = y * width + x;
|
||||
let covered = cover.get(texel).copied().unwrap_or(0.0);
|
||||
if let Some((sum, weight)) = sums.get_mut((region_x + x) / cell - first_column) {
|
||||
*sum += values.get(texel).copied().unwrap_or(0.0) * covered;
|
||||
*weight += covered;
|
||||
}
|
||||
}
|
||||
}
|
||||
sums.into_iter().map(|(sum, weight)| (weight > MIN_COVERAGE_WEIGHT).then(|| sum / weight))
|
||||
})
|
||||
.collect();
|
||||
let average = |column: isize, row: isize| -> Option<f32> {
|
||||
let column = column.clamp(0, columns as isize - 1) as usize;
|
||||
let row = row.clamp(0, rows as isize - 1) as usize;
|
||||
averages.get(row * columns + column).copied().flatten()
|
||||
};
|
||||
|
||||
let cell_size = cell as f32;
|
||||
(0..height)
|
||||
.into_par_iter()
|
||||
.flat_map_iter(|y| (0..width).map(move |x| (x, y)))
|
||||
.map(|(x, y)| {
|
||||
// Position in cells, relative to the first cell's center
|
||||
let cell_x = ((region_x + x) as f32 + 0.5) / cell_size - 0.5 - first_column as f32;
|
||||
let cell_y = ((region_y + y) as f32 + 0.5) / cell_size - 0.5 - first_row as f32;
|
||||
let (left, top) = (cell_x.floor(), cell_y.floor());
|
||||
let (offset_x, offset_y) = (cell_x - left, cell_y - top);
|
||||
let (left, top) = (left as isize, top as isize);
|
||||
let corners = [
|
||||
(left, top, (1.0 - offset_x) * (1.0 - offset_y)),
|
||||
(left + 1, top, offset_x * (1.0 - offset_y)),
|
||||
(left, top + 1, (1.0 - offset_x) * offset_y),
|
||||
(left + 1, top + 1, offset_x * offset_y),
|
||||
];
|
||||
let (sum, weight) = corners.iter().fold((0.0, 0.0), |(sum, weight), &(column, row, corner_weight)| match average(column, row) {
|
||||
Some(value) => (sum + value * corner_weight, weight + corner_weight),
|
||||
None => (sum, weight),
|
||||
});
|
||||
if weight > MIN_COVERAGE_WEIGHT { sum / weight } else { values.get(y * width + x).copied().unwrap_or(0.0) }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A generator's (possibly blurred) ramp after balance, contrast, invert and offset.
|
||||
fn finish_generator(generator: &Generator, ramp: f32) -> f32 {
|
||||
let value = generator.global.apply(ramp);
|
||||
let value = if generator.invert { 1.0 - value } else { value };
|
||||
let offset = if generator.offset.is_finite() { generator.offset } else { 0.0 };
|
||||
(value + offset).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// Clamp filtered masks to 0..1, and turn filtered content back into straight values.
|
||||
@@ -1259,15 +1397,21 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
}
|
||||
}
|
||||
|
||||
fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 {
|
||||
/// The generator's ramp at this texel, before its global blur, balance, contrast and invert.
|
||||
fn generator_ramp(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 {
|
||||
let coords = self.coords();
|
||||
let signal = match (generator.kind, &generator.detail) {
|
||||
(GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => self.curvature_detail(detail, curvature_sizes),
|
||||
(GeneratorKind::EdgeWear, None) => (self.baked(BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0,
|
||||
(GeneratorKind::Curvature, None) => self.baked(BakedMap::Curvature).unwrap_or(0.5),
|
||||
(GeneratorKind::Dirt, _) => 1.0 - self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0),
|
||||
(GeneratorKind::AmbientOcclusion, _) => self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0),
|
||||
(GeneratorKind::ThinAreas, _) => 1.0 - self.baked(BakedMap::Thickness).unwrap_or(1.0),
|
||||
(GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => {
|
||||
// Detail sizes are blurred copies of the mesh map, so a replaced curvature input reads at its own size only
|
||||
let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes };
|
||||
let curvature = self.generator_input(generator, BakedMap::Curvature);
|
||||
self.curvature_detail(detail, sizes, curvature)
|
||||
}
|
||||
(GeneratorKind::EdgeWear, None) => (self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0,
|
||||
(GeneratorKind::Curvature, None) => self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5),
|
||||
(GeneratorKind::Dirt, _) => 1.0 - self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0),
|
||||
(GeneratorKind::AmbientOcclusion, _) => self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0),
|
||||
(GeneratorKind::ThinAreas, _) => 1.0 - self.generator_input(generator, BakedMap::Thickness).unwrap_or(1.0),
|
||||
(GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5,
|
||||
(GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5,
|
||||
};
|
||||
@@ -1284,12 +1428,29 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
signal
|
||||
};
|
||||
|
||||
// A smooth step from black to white over 2 × softness around 1 − level, then the offset
|
||||
generator.shape(signal)
|
||||
// A smooth step from black to white over 2 × softness around 1 − level
|
||||
let threshold = 1.0 - generator.level.clamp(0.0, 1.0);
|
||||
let softness = generator.softness.max(Generator::MIN_SOFTNESS);
|
||||
let ramp = ((signal - (threshold - softness)) / (2.0 * softness)).clamp(0.0, 1.0);
|
||||
ramp * ramp * (3.0 - 2.0 * ramp)
|
||||
}
|
||||
|
||||
/// The curvature of `detail`'s mode at this texel: each detail size's edges and cavities, weighted and combined like a screen blend.
|
||||
fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>) -> f32 {
|
||||
/// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]).
|
||||
fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 {
|
||||
let ramp = self.generator_ramp(generator, curvature_sizes);
|
||||
finish_generator(generator, ramp)
|
||||
}
|
||||
|
||||
/// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked).
|
||||
fn generator_input(&mut self, generator: &Generator, map: BakedMap) -> Option<f32> {
|
||||
match generator.inputs.get(&map) {
|
||||
Some(source) => Some(self.source(source, &Projection::default(), ChannelKind::Scalar)[0]),
|
||||
None => self.baked(map),
|
||||
}
|
||||
}
|
||||
|
||||
/// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given.
|
||||
fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option<f32>) -> f32 {
|
||||
let combine = |edges: f32, cavities: f32| match detail.mode {
|
||||
CurvatureMode::Edges => edges,
|
||||
CurvatureMode::Cavities => cavities,
|
||||
@@ -1298,7 +1459,7 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
};
|
||||
|
||||
// Without curvature to read the texel is flat: no edges or cavities
|
||||
let Some(curvature) = self.baked(BakedMap::Curvature) else { return combine(0.0, 0.0) };
|
||||
let Some(curvature) = curvature else { return combine(0.0, 0.0) };
|
||||
|
||||
let working_size = (self.res, self.inp.gbuf.height);
|
||||
let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32];
|
||||
@@ -2392,7 +2553,7 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use texturecraft_core::{ChannelBlend, Effect, Layer, Procedural, ProceduralKind, TextureSet};
|
||||
use texturecraft_core::{ChannelBlend, Effect, Layer, OutputResolution, Procedural, ProceduralKind, ResolutionMode, TextureSet};
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
struct Fixture {
|
||||
@@ -2731,42 +2892,154 @@ mod tests {
|
||||
assert!(blurred_then_warped.iter().zip(&warped).any(|(chained, single)| (chained - single).abs() > 0.1), "the blur under the warp still runs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn larger_curvature_detail_sizes_reach_further_from_an_edge() {
|
||||
/// A 256² set whose curvature map has a one-texel ridge in column `ridge_x` (flat elsewhere), and a white fill layer to mask.
|
||||
fn ridge_fixture(ridge_x: usize) -> (Fixture, LayerId) {
|
||||
let mut fixture = fixture();
|
||||
fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 256, 256);
|
||||
fixture.project.texture_sets[0].resolution = 256;
|
||||
let ridge: Vec<f32> = (0..256 * 256).map(|texel| if texel % 256 == 128 { 1.0 } else { 0.5 }).collect();
|
||||
let ridge: Vec<f32> = (0..256 * 256).map(|texel| if texel % 256 == ridge_x { 1.0 } else { 0.5 }).collect();
|
||||
fixture.baked = BakedMaps { resolution: 256, maps: [(BakedMap::Curvature, Arc::new(ridge))].into() };
|
||||
let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0);
|
||||
let row_with = |fixture: &mut Fixture, weights: [f32; 7]| -> Vec<f32> {
|
||||
(fixture, layer)
|
||||
}
|
||||
|
||||
/// `layer`'s mask made of `effects` (bottom first) on black, read along row 128 over `xs`.
|
||||
fn mask_row(fixture: &mut Fixture, layer: LayerId, effects: Vec<Effect>, xs: std::ops::Range<u32>) -> Vec<f32> {
|
||||
let mut mask = Mask::new(MaskBackground::Black);
|
||||
mask.effects = effects;
|
||||
fixture.project.layer_mut(layer).unwrap().mask = Some(mask);
|
||||
let images = Default::default();
|
||||
let inputs = Inputs {
|
||||
project: &fixture.project,
|
||||
ts: 0,
|
||||
mesh: &fixture.mesh,
|
||||
gbuf: &fixture.gbuf,
|
||||
pixels: &fixture.pixels,
|
||||
baked: &fixture.baked,
|
||||
block_scales: BlockScales::default(),
|
||||
preview: None,
|
||||
images: &images,
|
||||
bounds: fixture.mesh.bounds(),
|
||||
};
|
||||
mask_at(&inputs, layer, &xs.map(|x| (x, 128)).collect::<Vec<_>>()).unwrap()
|
||||
}
|
||||
|
||||
/// A generator effect of `fixture`'s project.
|
||||
fn generator_effect(fixture: &mut Fixture, generator: Generator) -> Effect {
|
||||
Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))
|
||||
}
|
||||
|
||||
/// An edge wear generator that marks exactly the curvature ridge (the map as baked, a hard step).
|
||||
fn ridge_generator() -> Generator {
|
||||
Generator { level: 0.5, softness: 0.01, noise_amount: 0.0, detail: None, ..Generator::new(GeneratorKind::EdgeWear) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn larger_curvature_detail_sizes_reach_further_from_an_edge() {
|
||||
let (mut fixture, layer) = ridge_fixture(128);
|
||||
let mut row_with = |weights: [f32; 7]| {
|
||||
let detail = CurvatureDetail { mode: CurvatureMode::Edges, weights };
|
||||
let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: Some(detail), ..Generator::new(GeneratorKind::Curvature) };
|
||||
let effect = generator_effect(&mut fixture, generator);
|
||||
mask_row(&mut fixture, layer, vec![effect], 120..137)
|
||||
};
|
||||
|
||||
// The sampled ridge is index 8; five texels to its left is index 3
|
||||
let (ridge, five_texels_away) = (8, 3);
|
||||
let finest = row_with([1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
|
||||
let largest = row_with([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]);
|
||||
assert!(finest[ridge] > 0.99 && finest[five_texels_away] < 0.01, "the map itself marks only the ridge: {finest:?}");
|
||||
assert!(largest[ridge] > 0.99 && largest[five_texels_away] > 0.5, "the largest size reaches texels away from it: {largest:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_replaced_curvature_input_is_read_at_its_own_size_only() {
|
||||
let (mut fixture, layer) = ridge_fixture(128);
|
||||
let detail = CurvatureDetail { mode: CurvatureMode::Edges, weights: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0] };
|
||||
let mut generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: Some(detail), ..Generator::new(GeneratorKind::Curvature) };
|
||||
generator.inputs.insert(BakedMap::Curvature, Source::Uniform([0.5; 3]));
|
||||
let effect = generator_effect(&mut fixture, generator);
|
||||
let row = mask_row(&mut fixture, layer, vec![effect], 120..137);
|
||||
|
||||
// The largest size alone would mark the ridge and texels around it; the flat input marks nothing
|
||||
assert!(row.iter().all(|value| *value < 0.01), "the detail sizes of the mesh map are not read: {row:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generator_blur_softens_only_the_generator_not_the_stack_below() {
|
||||
let (mut fixture, layer) = ridge_fixture(100);
|
||||
let mut row_with = |blur: f32| {
|
||||
let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] };
|
||||
let below = Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source: checker, projection: Projection::default() });
|
||||
let mut generator = ridge_generator();
|
||||
generator.global.blur = blur;
|
||||
let mut lighten = generator_effect(&mut fixture, generator);
|
||||
lighten.blend = BlendMode::Lighten;
|
||||
mask_row(&mut fixture, layer, vec![below, lighten], 40..111)
|
||||
};
|
||||
|
||||
// The sampled row crosses a checker edge; indices below 30 are outside the blur
|
||||
let (ridge, five_texels_away, far) = (60, 55, 0..30);
|
||||
let sharp = row_with(0.0);
|
||||
let blurred = row_with(1.0);
|
||||
assert!(sharp[ridge] > 0.99 && sharp[five_texels_away] < 0.01, "unblurred, the ridge is one texel: {sharp:?}");
|
||||
assert!(blurred[ridge] < 0.99 && blurred[ridge] > blurred[five_texels_away], "the blur spreads the ridge: {blurred:?}");
|
||||
assert!(blurred[five_texels_away] > 0.01, "and reaches texels away from it: {blurred:?}");
|
||||
for texel in far {
|
||||
assert_eq!(blurred[texel], sharp[texel], "the checker below keeps its hard edges at texel {texel}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lower_generator_resolution_spreads_a_ridge_over_its_cell() {
|
||||
let (mut fixture, layer) = ridge_fixture(100);
|
||||
let mut row_with = |factor: i8| {
|
||||
let mut generator = ridge_generator();
|
||||
generator.resolution.factor = factor;
|
||||
let effect = generator_effect(&mut fixture, generator);
|
||||
mask_row(&mut fixture, layer, vec![effect], 80..121)
|
||||
};
|
||||
|
||||
// At one eighth resolution, each cell spans eight texels
|
||||
let (ridge, beside, far) = (20, 18, 0);
|
||||
let full = row_with(0);
|
||||
let eighth = row_with(-3);
|
||||
assert!(full[ridge] > 0.99 && full[beside] < 0.01, "at full resolution the ridge is one texel: {full:?}");
|
||||
assert!(eighth[ridge] < 0.5 && eighth[beside] > 0.01, "an eighth of the resolution averages it over its cell: {eighth:?}");
|
||||
assert!(eighth[far] < 0.01, "texels a few cells away stay black: {eighth:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_caller_lists_the_same_generator_stages_whatever_resolution_it_passes() {
|
||||
let custom = OutputResolution { mode: ResolutionMode::Custom, custom: 1024, factor: 0 };
|
||||
let effects = [Effect::new(LayerId(1), EffectKind::Generator(Generator { resolution: custom, ..Generator::new(GeneratorKind::Dirt) }))];
|
||||
|
||||
// Tile and whole-set resolutions must select the same generator stage
|
||||
let at_tile: Vec<usize> = neighbourhood_filters(&effects, 1024).map(|stage| stage.0).collect();
|
||||
let at_set_width: Vec<usize> = neighbourhood_filters(&effects, 2048).map(|stage| stage.0).collect();
|
||||
assert_eq!(at_tile, at_set_width);
|
||||
assert_eq!(at_tile, [0], "a custom resolution can be coarser than some UV tile, so it is a stage");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generator_input_replaced_by_a_value_is_read_instead_of_the_mesh_map() {
|
||||
let mut fixture = fixture();
|
||||
fixture.baked = BakedMaps { resolution: 64, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![1.0; 64 * 64]))].into() };
|
||||
let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0);
|
||||
let value_with = |fixture: &mut Fixture, input: Option<f32>| -> f32 {
|
||||
let mut generator = Generator { level: 0.5, softness: 0.1, noise_amount: 0.0, ..Generator::new(GeneratorKind::Dirt) };
|
||||
if let Some(value) = input {
|
||||
generator.inputs.insert(BakedMap::AmbientOcclusion, Source::Uniform([value; 3]));
|
||||
}
|
||||
let mut mask = Mask::new(MaskBackground::Black);
|
||||
mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator)));
|
||||
fixture.project.layer_mut(layer).unwrap().mask = Some(mask);
|
||||
let images = Default::default();
|
||||
let inputs = Inputs {
|
||||
project: &fixture.project,
|
||||
ts: 0,
|
||||
mesh: &fixture.mesh,
|
||||
gbuf: &fixture.gbuf,
|
||||
pixels: &fixture.pixels,
|
||||
baked: &fixture.baked,
|
||||
block_scales: BlockScales::default(),
|
||||
preview: None,
|
||||
images: &images,
|
||||
bounds: fixture.mesh.bounds(),
|
||||
};
|
||||
mask_at(&inputs, layer, &(120..137).map(|x| (x, 128)).collect::<Vec<_>>()).unwrap()
|
||||
run(fixture, None).value(Channel::BaseColor, 20, 20)[0]
|
||||
};
|
||||
|
||||
// The row starts at x 120: the ridge is its ninth texel, five texels left of it the fourth
|
||||
let (ridge, five_texels_away) = (8, 3);
|
||||
let finest = row_with(&mut fixture, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
|
||||
let largest = row_with(&mut fixture, [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]);
|
||||
assert!(finest[ridge] > 0.99 && finest[five_texels_away] < 0.01, "the map itself marks only the ridge: {finest:?}");
|
||||
assert!(largest[ridge] > 0.99 && largest[five_texels_away] > 0.5, "the largest size reaches texels away from it: {largest:?}");
|
||||
// Dark occlusion reveals dirt while the baked white map stays clear
|
||||
let (baked, black) = (value_with(&mut fixture, None), value_with(&mut fixture, Some(0.0)));
|
||||
assert!(black > 0.99 && baked < black - 0.2, "baked {baked}, black input {black}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -6,8 +6,8 @@ use std::collections::BTreeMap;
|
||||
|
||||
use texturecraft_compose::{BelowCache, Composite, Inputs, PaintTarget, PixelStore, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached};
|
||||
use texturecraft_core::{
|
||||
BlendMode, Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, Procedural,
|
||||
ProceduralKind, Project, Projection, Source, TextureSet,
|
||||
BakedMap, BlendMode, Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground,
|
||||
Procedural, ProceduralKind, Project, Projection, Source, TextureSet,
|
||||
};
|
||||
use texturecraft_geom::{Mesh, UvGBuffer, primitives};
|
||||
use texturecraft_texel::{TILE, TileImage, to_u16};
|
||||
@@ -799,3 +799,36 @@ fn cached_stack_tracks_referenced_images_only() {
|
||||
assert!(output == expected, "{stage}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generator_input_image_changes_invalidate_stack_key() {
|
||||
use std::sync::Arc;
|
||||
use texturecraft_compose::{ImageRes, ImageStore, StackKey};
|
||||
|
||||
let mut fixture = fixture();
|
||||
heavy_stack(&mut fixture);
|
||||
let generated_layer = fixture.project.texture_sets[0].stack[1];
|
||||
let mask = fixture.project.layer_mut(generated_layer).unwrap().mask.as_mut().unwrap();
|
||||
let EffectKind::Generator(generator) = &mut mask.effects[0].kind else { panic!("expected generator") };
|
||||
*generator = Generator::new(GeneratorKind::Dirt);
|
||||
generator.inputs.insert(BakedMap::AmbientOcclusion, Source::image("used"));
|
||||
|
||||
let image = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false });
|
||||
let mut images = ImageStore::default();
|
||||
images.insert("used".into(), image(0.1));
|
||||
let baked = Default::default();
|
||||
let roots = &fixture.project.texture_sets[0].stack;
|
||||
let key = |images: &ImageStore| StackKey::new(&fixture.project, &fixture.pixels, &baked, images, 0, roots).unwrap();
|
||||
let original = key(&images);
|
||||
|
||||
images.insert("unrelated".into(), image(0.5));
|
||||
assert_eq!(key(&images), original, "an unrelated image leaves the key unchanged");
|
||||
|
||||
let old_image = Arc::downgrade(&images["used"]);
|
||||
images.insert("used".into(), image(0.9));
|
||||
assert!(old_image.upgrade().is_none(), "the cache must not retain the old image pixels");
|
||||
assert!(key(&images) != original, "replacing a generator input must invalidate the cache");
|
||||
|
||||
images.remove("used");
|
||||
assert!(key(&images) != original, "removing a generator input must invalidate the cache");
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{CageSettings, CommonBakeSettings, HighPolySettings, MeshMapSettings, SkewSettings};
|
||||
use super::{CageSettings, CageType, CommonBakeSettings, HighPolySettings, MeshMapSettings, SkewSettings};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Persisted clean-room bake settings, grouped by the controls they belong to
|
||||
@@ -11,3 +11,10 @@ pub struct BakeSettings {
|
||||
pub skew: SkewSettings,
|
||||
pub maps: MeshMapSettings,
|
||||
}
|
||||
|
||||
impl BakeSettings {
|
||||
/// Whether a painted skew map steers the rays: it needs a separate high poly and a distance-based cage with averaged normals
|
||||
pub fn skew_applies(&self) -> bool {
|
||||
!self.high_poly.use_low_as_high && self.cage.kind == CageType::DistanceBased && self.cage.average_normals
|
||||
}
|
||||
}
|
||||
+108
-4
@@ -4,13 +4,19 @@ use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{BlendMode, Channel, ChannelKind, lum};
|
||||
use crate::{BakedMap, BlendMode, Channel, ChannelKind, lum};
|
||||
|
||||
mod curvature_detail;
|
||||
mod curvature_mode;
|
||||
mod generator_global;
|
||||
mod output_resolution;
|
||||
mod resolution_mode;
|
||||
|
||||
pub use curvature_detail::CurvatureDetail;
|
||||
pub use curvature_mode::CurvatureMode;
|
||||
pub use generator_global::GeneratorGlobal;
|
||||
pub use output_resolution::OutputResolution;
|
||||
pub use resolution_mode::ResolutionMode;
|
||||
|
||||
/// Id of a layer or effect (one id space per project).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
@@ -526,6 +532,17 @@ impl GeneratorKind {
|
||||
GeneratorKind::Direction => "Light / direction",
|
||||
}
|
||||
}
|
||||
|
||||
/// The mesh maps this kind reads, each an input that an image, a uniform value or an anchor can replace.
|
||||
pub fn inputs(self) -> &'static [BakedMap] {
|
||||
match self {
|
||||
GeneratorKind::EdgeWear | GeneratorKind::Curvature => &[BakedMap::Curvature],
|
||||
GeneratorKind::Dirt | GeneratorKind::AmbientOcclusion => &[BakedMap::AmbientOcclusion],
|
||||
GeneratorKind::ThinAreas => &[BakedMap::Thickness],
|
||||
GeneratorKind::Position | GeneratorKind::Direction => &[],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(s: &str) -> Option<GeneratorKind> {
|
||||
let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', ':'], "");
|
||||
GeneratorKind::ALL.into_iter().find(|k| norm(&format!("{k:?}")) == norm(s) || norm(k.label()) == norm(s))
|
||||
@@ -552,9 +569,25 @@ pub struct Generator {
|
||||
/// Mode and detail sizes of `Curvature` / `EdgeWear` generators (None: the curvature map as baked, as before detail sizes existed).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub detail: Option<CurvatureDetail>,
|
||||
/// Blur, balance and contrast of the finished value (neutral for generators saved before they existed).
|
||||
#[serde(default, skip_serializing_if = "GeneratorGlobal::is_neutral")]
|
||||
pub global: GeneratorGlobal,
|
||||
/// The resolution the generator is computed at (the texture set's for generators saved before it existed).
|
||||
#[serde(default, skip_serializing_if = "OutputResolution::is_default")]
|
||||
pub resolution: OutputResolution,
|
||||
/// What an input reads instead of its mesh map (an image, a uniform value or an anchor); inputs not listed read their mesh map.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub inputs: BTreeMap<BakedMap, Source>,
|
||||
}
|
||||
|
||||
impl Generator {
|
||||
/// The softest a ramp gets, so its threshold never divides by zero.
|
||||
pub const MIN_SOFTNESS: f32 = 1e-3;
|
||||
/// The most noise a generator mixes in, and the range of its noise scale.
|
||||
pub const MAX_NOISE_AMOUNT: f32 = 2.0;
|
||||
pub const MIN_NOISE_SCALE: f32 = 0.01;
|
||||
pub const MAX_NOISE_SCALE: f32 = 1000.0;
|
||||
|
||||
pub fn new(kind: GeneratorKind) -> Generator {
|
||||
let (level, softness, noise_amount) = match kind {
|
||||
GeneratorKind::EdgeWear => (0.5, 0.25, 0.3),
|
||||
@@ -568,7 +601,21 @@ impl Generator {
|
||||
GeneratorKind::EdgeWear => Some(CurvatureDetail { mode: CurvatureMode::Edges, weights: CurvatureDetail::EDGE_WEIGHTS }),
|
||||
_ => None,
|
||||
};
|
||||
Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, offset: 0.0, direction: [0.0, 1.0, 0.0], invert: false, detail }
|
||||
Generator {
|
||||
kind,
|
||||
level,
|
||||
softness,
|
||||
noise_amount,
|
||||
noise_scale: 8.0,
|
||||
seed: 7,
|
||||
offset: 0.0,
|
||||
direction: [0.0, 1.0, 0.0],
|
||||
invert: false,
|
||||
detail,
|
||||
global: GeneratorGlobal::default(),
|
||||
resolution: OutputResolution::default(),
|
||||
inputs: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The mask value for a (noise-broken) signal `s`: the smooth threshold at `level` over
|
||||
@@ -1038,14 +1085,46 @@ impl EffectKind {
|
||||
matches!(self, EffectKind::Paint | EffectKind::Path(_))
|
||||
}
|
||||
|
||||
/// Anchor points read by this effect's sources.
|
||||
/// Whether a source of this effect (a fill, a material or a generator input) reads an anchor point.
|
||||
fn reads_anchor(&self) -> bool {
|
||||
match self {
|
||||
EffectKind::Fill { source, .. } => source.anchor().is_some(),
|
||||
EffectKind::Material(f) => f.sources.values().any(|s| s.anchor().is_some()),
|
||||
EffectKind::Material(fill) => fill.sources.values().any(|source| source.anchor().is_some()),
|
||||
EffectKind::Generator(generator) => generator.inputs.values().any(|source| source.anchor().is_some()),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The anchor points this effect's sources read, with the channel each reads.
|
||||
pub fn anchors_read(&self) -> Vec<(LayerId, Channel)> {
|
||||
let sources: Vec<&Source> = match self {
|
||||
EffectKind::Fill { source, .. } => vec![source],
|
||||
EffectKind::Material(fill) => fill.sources.values().collect(),
|
||||
EffectKind::Generator(generator) => generator.inputs.values().collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
sources
|
||||
.into_iter()
|
||||
.filter_map(|source| match source {
|
||||
Source::Anchor { anchor, channel } => Some((*anchor, *channel)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The image resources this effect's sources read (a fill, material or generator input).
|
||||
pub fn images_read(&self) -> impl Iterator<Item = &str> {
|
||||
let sources: Vec<&Source> = match self {
|
||||
EffectKind::Fill { source, .. } => vec![source],
|
||||
EffectKind::Material(fill) => fill.sources.values().collect(),
|
||||
EffectKind::Generator(generator) => generator.inputs.values().collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
sources.into_iter().filter_map(|source| match source {
|
||||
Source::Image { name, .. } => Some(name.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Layer {
|
||||
@@ -1080,6 +1159,15 @@ impl Effect {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn material_effect_images_are_reported_as_used() {
|
||||
let mut fill = Fill::default();
|
||||
fill.sources.insert(Channel::BaseColor, Source::image("material.png"));
|
||||
let effect = EffectKind::Material(fill);
|
||||
|
||||
assert_eq!(effect.images_read().collect::<Vec<_>>(), vec!["material.png"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generator_offset_shifts_the_mask_value() {
|
||||
let mut g = Generator::new(GeneratorKind::Position);
|
||||
@@ -1115,6 +1203,22 @@ mod tests {
|
||||
assert_eq!(Generator::new(GeneratorKind::Dirt).detail, None, "only curvature and edge wear generators have detail sizes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generators_saved_before_the_new_settings_load_and_save_unchanged() {
|
||||
let saved = serde_json::to_value(Generator::new(GeneratorKind::Dirt)).unwrap();
|
||||
for field in ["global", "resolution", "inputs"] {
|
||||
assert!(saved.get(field).is_none(), "a default `{field}` is not written, so saved files stay as they were");
|
||||
}
|
||||
|
||||
let loaded: Generator = serde_json::from_value(saved).unwrap();
|
||||
assert!(loaded.global.is_neutral());
|
||||
|
||||
let mut blurred = Generator::new(GeneratorKind::Dirt);
|
||||
blurred.global.blur = 0.5;
|
||||
let round_trip: Generator = serde_json::from_value(serde_json::to_value(&blurred).unwrap()).unwrap();
|
||||
assert_eq!(round_trip, blurred);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn levels_map_range_and_gamma() {
|
||||
let l = Levels { in_low: 0.2, in_high: 0.6, gamma: 1.0, out_low: 0.0, out_high: 1.0 };
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Adjustments every generator applies to its finished value: a blur, then balance and contrast.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct GeneratorGlobal {
|
||||
/// Blur of the generated value (0..1 of [`GeneratorGlobal::MAX_BLUR`]).
|
||||
pub blur: f32,
|
||||
/// Shifts the value darker (below 0.5) or brighter (above 0.5); 0.5 leaves it unchanged.
|
||||
pub balance: f32,
|
||||
/// Narrows the ramp around its middle (0 unchanged, 1 a hard step).
|
||||
pub contrast: f32,
|
||||
}
|
||||
|
||||
impl GeneratorGlobal {
|
||||
/// The widest blur, as a radius in texels at [`GeneratorGlobal::BLUR_RESOLUTION`].
|
||||
pub const MAX_BLUR: f32 = 64.0;
|
||||
/// Narrower than this, the balanced range is a hard step.
|
||||
pub const MIN_RANGE: f32 = 1e-6;
|
||||
/// The texels per side the blur radius is measured at (2K).
|
||||
pub const BLUR_RESOLUTION: f32 = 2048.0;
|
||||
|
||||
pub fn is_neutral(&self) -> bool {
|
||||
*self == GeneratorGlobal::default()
|
||||
}
|
||||
|
||||
/// The blur as a radius in texels at [`GeneratorGlobal::BLUR_RESOLUTION`].
|
||||
pub fn blur_radius(&self) -> f32 {
|
||||
self.blur.clamp(0.0, 1.0) * GeneratorGlobal::MAX_BLUR
|
||||
}
|
||||
|
||||
/// The blur as a radius in texels at `resolution` texels per side.
|
||||
pub fn blur_radius_at(&self, resolution: u32) -> f32 {
|
||||
self.blur_radius() * resolution as f32 / GeneratorGlobal::BLUR_RESOLUTION
|
||||
}
|
||||
|
||||
/// `value` after balance and contrast: balance picks the input range stretched to 0..1, contrast narrows it around its middle.
|
||||
pub fn apply(&self, value: f32) -> f32 {
|
||||
if self.balance == 0.5 && self.contrast == 0.0 {
|
||||
return value;
|
||||
}
|
||||
let balance = self.balance.clamp(0.0, 1.0);
|
||||
let (low, high) = ((1.0 - 2.0 * balance).max(0.0), (2.0 - 2.0 * balance).min(1.0));
|
||||
let middle = (low + high) * 0.5;
|
||||
let keep = 1.0 - self.contrast.clamp(0.0, 1.0);
|
||||
let (low, high) = (middle - (middle - low) * keep, middle + (high - middle) * keep);
|
||||
if high - low < GeneratorGlobal::MIN_RANGE {
|
||||
return if value >= middle { 1.0 } else { 0.0 };
|
||||
}
|
||||
((value - low) / (high - low)).clamp(0.0, 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for GeneratorGlobal {
|
||||
fn default() -> Self {
|
||||
GeneratorGlobal { blur: 0.0, balance: 0.5, contrast: 0.0 }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn neutral_settings_leave_the_value_unchanged() {
|
||||
let global = GeneratorGlobal::default();
|
||||
for value in [0.0, 0.1, 0.5, 0.93, 1.0] {
|
||||
assert_eq!(global.apply(value), value);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn balance_darkens_below_the_middle_and_brightens_above() {
|
||||
let darker = GeneratorGlobal { balance: 0.25, ..GeneratorGlobal::default() };
|
||||
assert_eq!(darker.apply(0.4), 0.0, "the lower half goes black");
|
||||
assert!((darker.apply(0.75) - 0.5).abs() < 1e-6, "the upper half stretches over the whole range");
|
||||
|
||||
let brighter = GeneratorGlobal { balance: 0.75, ..GeneratorGlobal::default() };
|
||||
assert!((brighter.apply(0.25) - 0.5).abs() < 1e-6);
|
||||
assert_eq!(brighter.apply(0.6), 1.0, "the upper half goes white");
|
||||
|
||||
assert_eq!(GeneratorGlobal { balance: 0.0, ..GeneratorGlobal::default() }.apply(0.99), 0.0);
|
||||
assert_eq!(GeneratorGlobal { balance: 1.0, ..GeneratorGlobal::default() }.apply(0.01), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_contrast_is_a_step_at_the_middle_of_the_balanced_range() {
|
||||
let step = GeneratorGlobal { contrast: 1.0, ..GeneratorGlobal::default() };
|
||||
assert_eq!(step.apply(0.49), 0.0);
|
||||
assert_eq!(step.apply(0.51), 1.0);
|
||||
|
||||
let half = GeneratorGlobal { contrast: 0.5, ..GeneratorGlobal::default() };
|
||||
assert_eq!(half.apply(0.25), 0.0);
|
||||
assert!((half.apply(0.5) - 0.5).abs() < 1e-6);
|
||||
assert_eq!(half.apply(0.75), 1.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::resolution_mode::ResolutionMode;
|
||||
|
||||
/// The resolution a generator computes its output at, before it is sampled onto the texture set.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct OutputResolution {
|
||||
pub mode: ResolutionMode,
|
||||
/// Texels per side for [`ResolutionMode::Custom`].
|
||||
pub custom: u32,
|
||||
/// Power of two applied to the base size (−3 = 1/8 … 3 = ×8; 0 = the same as the context).
|
||||
pub factor: i8,
|
||||
}
|
||||
|
||||
impl OutputResolution {
|
||||
/// The factors the reference app offers: 1/8 to ×8.
|
||||
pub const FACTORS: std::ops::RangeInclusive<i8> = -3..=3;
|
||||
/// The sizes offered for [`ResolutionMode::Custom`].
|
||||
pub const CUSTOM_SIZES: [u32; 6] = [128, 256, 512, 1024, 2048, 4096];
|
||||
/// The largest output, the largest texture set resolution.
|
||||
pub const MAX_SIZE: u32 = 8192;
|
||||
/// The coarsest output: one value per this many texels of the context per side (a compositing tile).
|
||||
pub const MAX_CELL: u32 = 64;
|
||||
|
||||
pub fn is_default(&self) -> bool {
|
||||
*self == OutputResolution::default()
|
||||
}
|
||||
|
||||
/// Whether some UV tile can get a coarser output than its own resolution (a custom size, the set's size or a factor below 1).
|
||||
pub fn can_reduce(&self) -> bool {
|
||||
matches!(self.mode, ResolutionMode::Custom | ResolutionMode::TextureSet) || self.factor < 0
|
||||
}
|
||||
|
||||
/// The largest cell a UV tile of up to `uv_tile` texels per side can get, whatever its texture set's resolution.
|
||||
pub fn largest_cell(&self, uv_tile: u32) -> u32 {
|
||||
if self.mode == ResolutionMode::TextureSet { OutputResolution::MAX_CELL } else { self.cell(uv_tile, uv_tile) }
|
||||
}
|
||||
|
||||
/// Texels per side of the output for a UV tile of `uv_tile` texels per side in a texture set of `texture_set`.
|
||||
pub fn output_size(&self, uv_tile: u32, texture_set: u32) -> u32 {
|
||||
let base = match self.mode {
|
||||
ResolutionMode::Auto | ResolutionMode::UvTile => uv_tile,
|
||||
ResolutionMode::TextureSet => texture_set,
|
||||
ResolutionMode::Custom => self.custom,
|
||||
};
|
||||
let factor = self.factor.clamp(*OutputResolution::FACTORS.start(), *OutputResolution::FACTORS.end());
|
||||
let scaled = if factor >= 0 { base.saturating_mul(1 << factor) } else { base >> -factor };
|
||||
|
||||
// Hostile tile sizes can make the minimum exceed the supported maximum
|
||||
let minimum = (uv_tile / OutputResolution::MAX_CELL).clamp(1, OutputResolution::MAX_SIZE);
|
||||
scaled.clamp(minimum, OutputResolution::MAX_SIZE)
|
||||
}
|
||||
|
||||
/// How many texels of the UV tile one output texel covers per side (1 when the output is as fine or finer).
|
||||
pub fn cell(&self, uv_tile: u32, texture_set: u32) -> u32 {
|
||||
(uv_tile / self.output_size(uv_tile, texture_set)).max(1)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for OutputResolution {
|
||||
fn default() -> Self {
|
||||
OutputResolution { mode: ResolutionMode::Auto, custom: 2048, factor: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_default_follows_the_uv_tile() {
|
||||
let resolution = OutputResolution::default();
|
||||
assert_eq!(resolution.output_size(1024, 2048), 1024);
|
||||
assert_eq!(resolution.cell(1024, 2048), 1);
|
||||
assert!(!resolution.can_reduce());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_texture_set_mode_reads_the_set_not_the_uv_tile() {
|
||||
let resolution = OutputResolution { mode: ResolutionMode::TextureSet, factor: -1, ..OutputResolution::default() };
|
||||
assert_eq!(resolution.output_size(512, 2048), 1024, "half the set's 2048");
|
||||
assert_eq!(resolution.cell(512, 2048), 1, "finer than the 512 tile: one texel per texel");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn factors_and_custom_sizes_scale_the_output() {
|
||||
let eighth = OutputResolution { factor: -3, ..OutputResolution::default() };
|
||||
assert_eq!((eighth.output_size(2048, 2048), eighth.cell(2048, 2048)), (256, 8));
|
||||
|
||||
let custom = OutputResolution { mode: ResolutionMode::Custom, custom: 512, factor: 1 };
|
||||
assert_eq!((custom.output_size(2048, 2048), custom.cell(2048, 2048)), (1024, 2));
|
||||
|
||||
let finer = OutputResolution { factor: 3, ..OutputResolution::default() };
|
||||
assert_eq!((finer.output_size(2048, 2048), finer.cell(2048, 2048)), (8192, 1), "a finer output than the tile keeps one texel per texel");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_largest_cell_covers_any_texture_set() {
|
||||
let set = OutputResolution { mode: ResolutionMode::TextureSet, ..OutputResolution::default() };
|
||||
assert!(set.can_reduce(), "a UV tile larger than its set gets the set's coarser size");
|
||||
assert_eq!(set.largest_cell(2048), OutputResolution::MAX_CELL);
|
||||
assert_eq!(OutputResolution { factor: -2, ..OutputResolution::default() }.largest_cell(2048), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_sizes_stay_within_the_largest_output_and_the_coarsest_cell() {
|
||||
let huge = OutputResolution { mode: ResolutionMode::Custom, custom: u32::MAX, factor: i8::MAX };
|
||||
assert_eq!(huge.output_size(2048, 2048), OutputResolution::MAX_SIZE);
|
||||
|
||||
let tiny = OutputResolution { mode: ResolutionMode::Custom, custom: 1, factor: -3 };
|
||||
assert_eq!(tiny.cell(4096, 4096), OutputResolution::MAX_CELL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_uv_tile_size_does_not_panic() {
|
||||
let resolution = OutputResolution::default();
|
||||
|
||||
assert_eq!(resolution.output_size(u32::MAX, 2048), OutputResolution::MAX_SIZE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// What a generator's output resolution is based on.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum ResolutionMode {
|
||||
/// The context: the resolution of the UV tile it is computed for.
|
||||
Auto,
|
||||
/// The texture set's resolution.
|
||||
TextureSet,
|
||||
/// The UV tile's resolution.
|
||||
UvTile,
|
||||
/// A size of its own.
|
||||
Custom,
|
||||
}
|
||||
|
||||
impl ResolutionMode {
|
||||
pub const ALL: [ResolutionMode; 4] = [ResolutionMode::Auto, ResolutionMode::TextureSet, ResolutionMode::UvTile, ResolutionMode::Custom];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
ResolutionMode::Auto => "Auto",
|
||||
ResolutionMode::TextureSet => "Texture set",
|
||||
ResolutionMode::UvTile => "UV tile",
|
||||
ResolutionMode::Custom => "Custom",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(name: &str) -> Option<ResolutionMode> {
|
||||
let norm = |text: &str| text.to_ascii_lowercase().replace([' ', '_', '-'], "");
|
||||
ResolutionMode::ALL.into_iter().find(|mode| norm(&format!("{mode:?}")) == norm(name) || norm(mode.label()) == norm(name))
|
||||
}
|
||||
}
|
||||
@@ -24,9 +24,9 @@ pub use bake::{
|
||||
pub use blend::{BlendMode, blend1, blend3, lum, mix3};
|
||||
pub use channel::{Channel, ChannelFormat, ChannelKind};
|
||||
pub use layer::{
|
||||
ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId,
|
||||
LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient,
|
||||
hsl_adjust, per_unit,
|
||||
ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorGlobal, GeneratorKind, HeightMask,
|
||||
Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, OutputResolution, PathShape, Procedural, ProceduralKind,
|
||||
Projection, ResolutionMode, Source, gradient, hsl_adjust, per_unit,
|
||||
};
|
||||
pub use project::{
|
||||
AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, Project,
|
||||
|
||||
@@ -23,6 +23,16 @@ impl BakeCageInputs {
|
||||
CageShell::new(&self.request())
|
||||
}
|
||||
|
||||
/// Whether this set uses the session's shared low mesh
|
||||
pub fn uses_mesh(&self, mesh: &Arc<Mesh>) -> bool {
|
||||
Arc::ptr_eq(&self.mesh, mesh)
|
||||
}
|
||||
|
||||
/// Build a cage from edges shared across sets using the same low mesh
|
||||
pub fn cage_shell_with_edges(&self, wire_edges: &[Vec<(u32, u32)>], missing_seam_edges: &[Vec<(u32, u32)>]) -> Result<CageShell, BakeError> {
|
||||
CageShell::new_with_edges(&self.request(), wire_edges, missing_seam_edges)
|
||||
}
|
||||
|
||||
/// Where each high-poly vertex sits relative to the bake's transfer rays
|
||||
pub fn high_poly_reach(&self) -> Result<HighPolyReach, BakeError> {
|
||||
HighPolyReach::new(&self.request())
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
//! What can spoil a texture set's bake, checked before it runs: overlapping UVs and parts "By Mesh Name" leaves unpaired
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use texturecraft_bake::NamePair;
|
||||
use texturecraft_core::MeshMatchMode;
|
||||
use texturecraft_geom::{Mesh, SubMesh, UvGBuffer, glam::Vec2};
|
||||
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// Side of the UV raster the overlap check counts texels on, per UV tile (as mesh import does)
|
||||
const OVERLAP_CHECK_RESOLUTION: u32 = 512;
|
||||
|
||||
/// The only material of the UV-only mesh the overlap check builds per UV tile
|
||||
const BLOCK_MATERIAL: usize = 0;
|
||||
|
||||
impl Session {
|
||||
/// About the share (0..1) of texture set `texture_set`'s UV layout the bake sees covered more than once, over the UV tiles it bakes: a texel under three triangles counts twice
|
||||
pub fn bake_uv_overlap(&self, texture_set: usize) -> Result<f32> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
let mesh = self.bake_mesh(texture_set)?;
|
||||
let (overlaps, covered) = match set.tile_grid() {
|
||||
Some(grid) => {
|
||||
let baked_blocks: BTreeSet<(u32, u32)> =
|
||||
set.uv_tiles.iter().filter(|tile| !set.bake_excluded_tiles.contains(tile)).filter_map(|tile| grid.block(*tile)).collect();
|
||||
let blocks = triangles_by_block(&mesh, set.material, (grid.cols, grid.rows), &baked_blocks);
|
||||
blocks
|
||||
.values()
|
||||
.map(|block| overlap_counts(block, BLOCK_MATERIAL))
|
||||
.fold((0, 0), |(overlaps, covered), (block_overlaps, block_covered)| (overlaps + block_overlaps, covered + block_covered))
|
||||
}
|
||||
None => overlap_counts(&mesh, set.material),
|
||||
};
|
||||
|
||||
Ok(if covered == 0 { 0.0 } else { (overlaps as f32 / covered as f32).min(1.0) })
|
||||
}
|
||||
|
||||
/// How texture set `texture_set`'s low-poly parts pair with the high-poly parts ([`NamePair::list`]); `None` unless it bakes from a high poly "By Mesh Name"
|
||||
pub fn bake_name_pairs(&self, texture_set: usize) -> Result<Option<Vec<NamePair>>> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
let settings = &set.bake.high_poly;
|
||||
let high = self.bake_meshes.merged_high().filter(|_| settings.match_mode == MeshMatchMode::ByMeshName && !settings.use_low_as_high);
|
||||
|
||||
Ok(high.map(|high| NamePair::list(&self.mesh, set.material, &high.mesh, settings)))
|
||||
}
|
||||
|
||||
/// The high-poly parts none of `texture_sets` bakes from, by name: a set matching "Always" bakes from every part, one matching "By Mesh Name" only from the parts its names pair with
|
||||
pub fn bake_unpaired_high_parts(&self, texture_sets: &[usize]) -> Result<Vec<String>> {
|
||||
let (mut paired, mut unpaired) = (BTreeSet::new(), BTreeSet::new());
|
||||
for &texture_set in texture_sets {
|
||||
let settings = &self.doc.project.texture_set(texture_set)?.bake.high_poly;
|
||||
if !settings.use_low_as_high && settings.match_mode == MeshMatchMode::Always {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
for pair in self.bake_name_pairs(texture_set)?.unwrap_or_default() {
|
||||
match pair {
|
||||
NamePair { low: Some(_), high: Some(high) } => paired.insert(high),
|
||||
NamePair { low: None, high: Some(high) } => unpaired.insert(high),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Ok(unpaired.difference(&paired).cloned().collect())
|
||||
}
|
||||
}
|
||||
|
||||
/// Texels covered more than once and texels covered, rasterizing material `material`'s UVs over 0..1
|
||||
fn overlap_counts(mesh: &Mesh, material: usize) -> (usize, usize) {
|
||||
let gbuffer = UvGBuffer::new(mesh, material, OVERLAP_CHECK_RESOLUTION, OVERLAP_CHECK_RESOLUTION);
|
||||
(gbuffer.overlaps as usize, gbuffer.covered_count())
|
||||
}
|
||||
|
||||
/// Material `material`'s triangles sorted into the `baked_blocks` of a `grid` (columns, rows) atlas their UVs reach, one UV-only mesh per block with the block's UVs over 0..1: a single pass, however many blocks
|
||||
fn triangles_by_block(mesh: &Mesh, material: usize, grid: (u32, u32), baked_blocks: &BTreeSet<(u32, u32)>) -> BTreeMap<(u32, u32), Mesh> {
|
||||
let scale = Vec2::new(grid.0 as f32, grid.1 as f32);
|
||||
let mut blocks: BTreeMap<(u32, u32), Mesh> = BTreeMap::new();
|
||||
for triangle in mesh.triangles_of(material) {
|
||||
let Some([first, second, third]) = mesh.tri(triangle) else { continue };
|
||||
let (Some(first_uv), Some(second_uv), Some(third_uv)) = (mesh.uvs.get(first), mesh.uvs.get(second), mesh.uvs.get(third)) else { continue };
|
||||
let uvs = [*first_uv * scale, *second_uv * scale, *third_uv * scale];
|
||||
|
||||
// Every block the triangle's UV bounds touch, so a triangle across a border counts in both
|
||||
let (uv_min, uv_max) = uvs.iter().fold((Vec2::INFINITY, Vec2::NEG_INFINITY), |(uv_min, uv_max), uv| (uv_min.min(*uv), uv_max.max(*uv)));
|
||||
|
||||
// Capped at the grid: a stray huge UV must not walk billions of blocks
|
||||
let columns = uv_min.x.floor().max(0.0) as u32..=((uv_max.x.ceil() as u32).saturating_sub(1)).min(grid.0 - 1);
|
||||
let rows = uv_min.y.floor().max(0.0) as u32..=((uv_max.y.ceil() as u32).saturating_sub(1)).min(grid.1 - 1);
|
||||
for column in columns {
|
||||
for row in rows.clone() {
|
||||
if !baked_blocks.contains(&(column, row)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let block = blocks.entry((column, row)).or_insert_with(|| Mesh { materials: vec![String::new()], ..Mesh::default() });
|
||||
let offset = Vec2::new(column as f32, row as f32);
|
||||
block.indices.extend(block.uvs.len() as u32..block.uvs.len() as u32 + 3);
|
||||
block.uvs.extend(uvs.iter().map(|uv| *uv - offset));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for block in blocks.values_mut() {
|
||||
block.submeshes = vec![SubMesh { name: String::new(), material: BLOCK_MATERIAL, start: 0, count: block.indices.len() as u32 }];
|
||||
}
|
||||
|
||||
blocks
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_bake::HighPolyReach;
|
||||
|
||||
/// Per high-poly vertex: 1.0 if its owning set's bake misses it, otherwise 0.0
|
||||
/// Distances are each set's (max frontal, max rear); filtered or unavailable sets leave their vertices unmarked
|
||||
/// `vertex_count` is the validated high-poly mesh's vertex count
|
||||
/// The value [`high_poly_missed`] gives a vertex that `only_set` doesn't own, which the 3D view leaves out
|
||||
pub const HIDDEN_HIGH_POLY_VERTEX: f32 = -1.0;
|
||||
|
||||
/// Per vertex of the validated high poly: 1.0 if its owning set's bake misses it at that set's (max frontal, max rear), 0.0 if reached or unknown, [`HIDDEN_HIGH_POLY_VERTEX`] if `only_set` doesn't own it
|
||||
pub fn high_poly_missed(reach: &[Option<HighPolyReach>], distances: &[(f32, f32)], only_set: Option<usize>, vertex_count: usize) -> Vec<f32> {
|
||||
// Ownership is already assigned by HighPolyReach; other sets must not color the vertex
|
||||
let sets: Vec<(&HighPolyReach, f32, f32)> = reach
|
||||
@@ -13,11 +14,21 @@ pub fn high_poly_missed(reach: &[Option<HighPolyReach>], distances: &[(f32, f32)
|
||||
.filter(|(texture_set, _)| only_set.is_none_or(|only| only == *texture_set))
|
||||
.filter_map(|(_, (reach, &(max_frontal, max_rear)))| Some((reach.as_ref()?, max_frontal, max_rear)))
|
||||
.collect();
|
||||
|
||||
(0..vertex_count)
|
||||
.into_par_iter()
|
||||
.map(|vertex| {
|
||||
if only_set.is_some_and(|only| !owns(reach, only, vertex)) {
|
||||
return HIDDEN_HIGH_POLY_VERTEX;
|
||||
}
|
||||
|
||||
let missed = sets.iter().find_map(|(reach, max_frontal, max_rear)| reach.missed(vertex, *max_frontal, *max_rear));
|
||||
f32::from(u8::from(missed.unwrap_or(false)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether texture set `texture_set`'s reach claims high-poly vertex `vertex`
|
||||
fn owns(reach: &[Option<HighPolyReach>], texture_set: usize, vertex: usize) -> bool {
|
||||
reach.get(texture_set).and_then(Option::as_ref).and_then(|set| set.vertices.get(vertex)).is_some_and(Option::is_some)
|
||||
}
|
||||
@@ -182,12 +182,13 @@ impl Session {
|
||||
/// Texture set `texture_set`'s painted skew or cage map, used only when it bakes from a high poly
|
||||
fn bake_paint(&self, texture_set: usize, has_high: bool, target: BakePaintTarget) -> Result<Option<Arc<BakePaintMap>>> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
let paint = self.doc.bake_paint.get(&(texture_set, target)).filter(|_| has_high);
|
||||
let steers = has_high && (target != BakePaintTarget::Skew || set.bake.skew_applies());
|
||||
let paint = self.doc.bake_paint.get(&(texture_set, target)).filter(|_| steers);
|
||||
paint.map(|map| super::layout::paint_for_bake(map, set)).transpose()
|
||||
}
|
||||
|
||||
/// The low poly texture set `texture_set` bakes: UV tiles of mixed resolutions move into its atlas
|
||||
fn bake_mesh(&self, texture_set: usize) -> Result<Arc<Mesh>> {
|
||||
pub(super) fn bake_mesh(&self, texture_set: usize) -> Result<Arc<Mesh>> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
Ok(match set.tile_grid().filter(|_| !set.tile_resolutions.is_empty()) {
|
||||
Some(grid) => {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Baking tasks, commands, settings helpers, and the mesh-map baking API
|
||||
|
||||
mod bake_cage_inputs;
|
||||
mod bake_checks;
|
||||
mod bake_mesh;
|
||||
mod bake_meshes;
|
||||
mod bake_task;
|
||||
@@ -19,7 +20,7 @@ pub use bake_cage_inputs::BakeCageInputs;
|
||||
pub use bake_mesh::BakeMesh;
|
||||
pub use bake_meshes::BakeMeshes;
|
||||
pub use bake_task::BakeTask;
|
||||
pub use high_poly_missed::high_poly_missed;
|
||||
pub use high_poly_missed::{HIDDEN_HIGH_POLY_VERTEX, 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;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! clipboard: it holds a layer or an effect.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{EffectKind, LayerId, Mask, MaskBackground, Source};
|
||||
use texturecraft_core::{EffectKind, LayerId, Mask, MaskBackground};
|
||||
|
||||
use crate::commands::{CommandSpec, bad, has_layer, layer_param, strp};
|
||||
use crate::layer_ops::{empty_texel, fit};
|
||||
@@ -55,26 +55,29 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "cut": eid }))
|
||||
}
|
||||
|
||||
fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn paste(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const CMD: &str = "effect.paste";
|
||||
let (src, eid) = s.clipboard.clone().ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?;
|
||||
let effect = src.project.effect(eid).map(|(_, e)| e.clone()).ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?;
|
||||
let layer = layer_param(s, CMD, p)?;
|
||||
// The selected effect's stack, or the content or mask the selection targets.
|
||||
let selected = match s.target {
|
||||
StackTarget::Effect(x) if s.selected_layer() == Some(layer) => Some(x),
|
||||
let (copied, copied_id) = session.clipboard.clone().ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?;
|
||||
let effect = copied.project.effect(copied_id).map(|(_, effect)| effect.clone()).ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?;
|
||||
let layer = layer_param(session, CMD, params)?;
|
||||
|
||||
// The selected effect's stack, or the content or mask the selection targets
|
||||
let selected = match session.target {
|
||||
StackTarget::Effect(selected) if session.selected_layer() == Some(layer) => Some(selected),
|
||||
_ => None,
|
||||
};
|
||||
let in_content = |s: &Session, x: LayerId| {
|
||||
s.doc.project.effect(x).and_then(|(o, _)| s.doc.project.layers.get(&o)).is_some_and(|l| l.content_effects.iter().any(|e| e.id == x))
|
||||
let in_content = |session: &Session, effect_id: LayerId| {
|
||||
let owner = session.doc.project.effect(effect_id).and_then(|(owner, _)| session.doc.project.layers.get(&owner));
|
||||
owner.is_some_and(|owner| owner.content_effects.iter().any(|effect| effect.id == effect_id))
|
||||
};
|
||||
let asked = strp(p, "target").is_some();
|
||||
let asked = strp(params, "target").is_some();
|
||||
let content = match selected {
|
||||
_ if asked => content_target(p, CMD)?,
|
||||
Some(x) => in_content(s, x),
|
||||
None => s.target == StackTarget::Content && s.selected_layer() == Some(layer),
|
||||
_ if asked => content_target(params, CMD)?,
|
||||
Some(selected) => in_content(session, selected),
|
||||
None => session.target == StackTarget::Content && session.selected_layer() == Some(layer),
|
||||
};
|
||||
// Effects that fit one stack only go there, unless another was asked for.
|
||||
|
||||
// Effects that fit one stack only go there, unless another was asked for
|
||||
let content = match effect.kind.content_only() {
|
||||
Some(only) if only != content && asked => {
|
||||
return Err(bad(CMD, format!("{} effects go on the {}", effect.kind.name(), if only { "layer content" } else { "mask" })));
|
||||
@@ -82,46 +85,54 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(only) => only,
|
||||
None => content,
|
||||
};
|
||||
// An instance's content and (unless it has its own) mask belong to its source.
|
||||
let owner = if content { s.doc.project.content_layer(layer).map_or(layer, |l| l.id) } else { s.doc.project.mask_owner(layer) };
|
||||
let owner_layer = s.doc.project.layer(owner)?;
|
||||
|
||||
// An instance's content and (unless it has its own) mask belong to its source
|
||||
let owner = if content { session.doc.project.content_layer(layer).map_or(layer, |source| source.id) } else { session.doc.project.mask_owner(layer) };
|
||||
let owner_layer = session.doc.project.layer(owner)?;
|
||||
if content && owner_layer.is_group() {
|
||||
return Err(EngineError::Other(format!("\"{}\" is a folder: content effects go on paint and fill layers", owner_layer.name)));
|
||||
}
|
||||
// A fill reading an anchor point needs one below its new layer.
|
||||
if let EffectKind::Fill { source: Source::Anchor { anchor, channel }, .. } = &effect.kind {
|
||||
anchor_source(s, CMD, owner, *anchor, *channel)?;
|
||||
|
||||
// Each anchor point the effect reads must be below its new layer
|
||||
for (anchor, channel) in effect.kind.anchors_read() {
|
||||
anchor_source(session, CMD, owner, anchor, channel)?;
|
||||
}
|
||||
let (ts, _, _) = s.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the layer is not in a stack"))?;
|
||||
let (size, channels) = s.doc.project.texture_set(ts).map(|t| (t.size(), t.channel_list()))?;
|
||||
let new = s.edit("Paste effect", |s| {
|
||||
let new = s.doc.project.alloc_id();
|
||||
let l = s.doc.project.layer_mut(owner)?;
|
||||
let list = if content {
|
||||
&mut l.content_effects
|
||||
|
||||
let (set, _, _) = session.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the layer is not in a stack"))?;
|
||||
let (size, channels) = session.doc.project.texture_set(set).map(|texture_set| (texture_set.size(), texture_set.channel_list()))?;
|
||||
|
||||
let pasted = session.edit("Paste effect", |session| {
|
||||
let pasted = session.doc.project.alloc_id();
|
||||
let owner_layer = session.doc.project.layer_mut(owner)?;
|
||||
let stack = if content {
|
||||
&mut owner_layer.content_effects
|
||||
} else {
|
||||
let bg = if matches!(effect.kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White };
|
||||
&mut l.mask.get_or_insert_with(|| Mask::new(bg)).effects
|
||||
let background =
|
||||
if matches!(effect.kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White };
|
||||
&mut owner_layer.mask.get_or_insert_with(|| Mask::new(background)).effects
|
||||
};
|
||||
let at = selected.and_then(|x| list.iter().position(|e| e.id == x)).map_or(list.len(), |i| i + 1);
|
||||
list.insert(at, texturecraft_core::Effect { id: new, ..effect.clone() });
|
||||
// Painted pixels come along, resampled to the set's size (a mask's paint stays a mask's).
|
||||
if let Some(img) = src.pixels.masks.get(&eid).filter(|_| !content) {
|
||||
s.doc.pixels.masks.insert(new, fit(img, size, &[0, 0]));
|
||||
let index = selected.and_then(|selected| stack.iter().position(|effect| effect.id == selected)).map_or(stack.len(), |position| position + 1);
|
||||
stack.insert(index, texturecraft_core::Effect { id: pasted, ..effect.clone() });
|
||||
|
||||
// Painted pixels come along, resampled to the set's size (a mask's paint stays a mask's)
|
||||
if let Some(image) = copied.pixels.masks.get(&copied_id).filter(|_| !content) {
|
||||
session.doc.pixels.masks.insert(pasted, fit(image, size, &[0, 0]));
|
||||
}
|
||||
for c in channels.iter().copied().filter(|_| content) {
|
||||
if let Some(img) = src.pixels.layer(eid, c) {
|
||||
s.doc.pixels.layers.insert((new, c), fit(img, size, &empty_texel(c)));
|
||||
for channel in channels.iter().copied().filter(|_| content) {
|
||||
if let Some(image) = copied.pixels.layer(copied_id, channel) {
|
||||
session.doc.pixels.layers.insert((pasted, channel), fit(image, size, &empty_texel(channel)));
|
||||
}
|
||||
}
|
||||
// The target belongs to the active set's selection: a paste into another set leaves it.
|
||||
if let Some((lts, _, _)) = s.doc.project.locate(layer) {
|
||||
s.selected.insert(lts, layer);
|
||||
if lts == s.ts() {
|
||||
s.target = StackTarget::Effect(new);
|
||||
|
||||
// The target belongs to the active set's selection: a paste into another set leaves it
|
||||
if let Some((layer_set, _, _)) = session.doc.project.locate(layer) {
|
||||
session.selected.insert(layer_set, layer);
|
||||
if layer_set == session.ts() {
|
||||
session.target = StackTarget::Effect(pasted);
|
||||
}
|
||||
}
|
||||
Ok(new)
|
||||
Ok(pasted)
|
||||
})?;
|
||||
Ok(json!({ "effect": new.0 }))
|
||||
|
||||
Ok(json!({ "effect": pasted.0 }))
|
||||
}
|
||||
@@ -37,6 +37,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
reimport
|
||||
),
|
||||
cmd!(
|
||||
"file.changeMesh",
|
||||
"Change mesh",
|
||||
[],
|
||||
None,
|
||||
"{path: the new mesh file, preserveStrokes?: bool (painted pixels follow the surface where the UVs differ; default true)} → {preserved?: texels re-projected}. Keeps layers, texture sets and settings; texture sets map to the new mesh by material index",
|
||||
always,
|
||||
change_mesh
|
||||
),
|
||||
cmd!(
|
||||
"file.exportTextures",
|
||||
"Export textures",
|
||||
@@ -438,6 +447,16 @@ fn reimport(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn change_mesh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = native::path_param(p, "path", "file.changeMesh")?;
|
||||
let file = native::read_mesh("file.changeMesh", path)?;
|
||||
let reply = s.reimport_mesh(Some(file), crate::commands::boolp(p, "preserveStrokes").unwrap_or(true))?;
|
||||
// Only after the swap succeeded: Reimport mesh and Save keep following the new file.
|
||||
s.doc.project.mesh_path = native::absolute(path);
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Session {
|
||||
/// The file the mesh was imported from, when it is still there: what Reimport mesh reads again.
|
||||
@@ -471,6 +490,19 @@ impl Session {
|
||||
let mut next = Session::new(doc, mesh, source)?;
|
||||
next.log.extend(warnings);
|
||||
next.path = self.path.clone();
|
||||
next.sync_images();
|
||||
// The high polys and the skew map stay. The cage is sampled by triangle index and
|
||||
// barycentrics, so it stays only for an identical mesh; the low poly's base colours are
|
||||
// read again from the new mesh.
|
||||
next.bake_meshes = self.bake_meshes.clone();
|
||||
next.bake_meshes.low_base_color = Default::default();
|
||||
if next.bake_meshes.cage.is_some() && *next.mesh != *self.mesh {
|
||||
next.bake_meshes.cage = None;
|
||||
next.log.push("the cage mesh was dropped: the low-poly mesh changed".into());
|
||||
}
|
||||
if self.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_core::BakePaintTarget::Skew) && self.source.uvs != next.source.uvs {
|
||||
next.log.push("the skew map is laid over the old UV layout; check it in Bake mode".into());
|
||||
}
|
||||
next.modified = true;
|
||||
next.project_id = self.project_id;
|
||||
let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next));
|
||||
@@ -621,6 +653,8 @@ use unsupported as save_copy;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
use unsupported as reimport;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
use unsupported as change_mesh;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
use unsupported as export_textures;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
use unsupported as export_mesh;
|
||||
@@ -764,6 +798,82 @@ f 1/1 2/2 3/3
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A project built on one mesh moves to another mesh file with its layers intact, even when
|
||||
/// it carries its own copy of the mesh (a plain reimport would only re-read that copy).
|
||||
#[test]
|
||||
fn change_mesh_swaps_the_mesh_and_keeps_the_layers() {
|
||||
let dir = std::env::temp_dir().join(format!("tc_change_mesh_{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let quad = dir.join("quad.obj");
|
||||
std::fs::write(&quad, "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n").unwrap();
|
||||
let tri = dir.join("tri.obj");
|
||||
std::fs::write(&tri, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap();
|
||||
let mut s = Session::from_mesh_bytes("quad.obj", &std::fs::read(&quad).unwrap(), 128, "quad").unwrap();
|
||||
crate::execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap();
|
||||
let layers = s.doc.project.layers.len();
|
||||
assert!(crate::execute(&mut s, "file.changeMesh", &json!({})).is_err(), "a path is required");
|
||||
crate::execute(&mut s, "file.changeMesh", &json!({"path": tri.display().to_string()})).unwrap();
|
||||
assert_eq!(s.mesh.triangle_count(), 1, "the new mesh is in use");
|
||||
assert_eq!(s.doc.project.mesh_file, "tri.obj");
|
||||
assert_eq!(s.doc.project.layers.len(), layers, "the layers stay");
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
/// Open A, change to B, edit B on disk: Reimport mesh (also after save and reopen) must read B,
|
||||
/// not A. A failed change leaves the remembered path alone.
|
||||
#[test]
|
||||
fn change_mesh_remembers_the_new_file_for_reimport() {
|
||||
let dir = std::env::temp_dir().join(format!("tc_change_mesh_path_{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let obj = |x: f32| format!("v 0 0 0\nv {x} 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n");
|
||||
let (a, b) = (dir.join("a.obj"), dir.join("b.obj"));
|
||||
std::fs::write(&a, obj(1.0)).unwrap();
|
||||
std::fs::write(&b, obj(2.0)).unwrap();
|
||||
let width = |s: &Session| s.mesh.positions.iter().map(|p| p.x).fold(0.0_f32, f32::max);
|
||||
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
crate::execute(&mut s, "file.new", &json!({"mesh": a.display().to_string(), "resolution": 128})).unwrap();
|
||||
let a_abs = s.remembered_mesh_path().map(str::to_string).unwrap();
|
||||
// A failed change (unreadable file) keeps A.
|
||||
let missing = dir.join("missing.obj");
|
||||
assert!(crate::execute(&mut s, "file.changeMesh", &json!({"path": missing.display().to_string()})).is_err());
|
||||
assert_eq!(s.remembered_mesh_path(), Some(a_abs.as_str()));
|
||||
crate::execute(&mut s, "file.changeMesh", &json!({"path": b.display().to_string()})).unwrap();
|
||||
assert_eq!(width(&s), 2.0);
|
||||
let b_abs = s.remembered_mesh_path().map(str::to_string).expect("B is remembered");
|
||||
assert_ne!(a_abs, b_abs);
|
||||
// The remembered path survives save and reopen.
|
||||
let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
|
||||
assert_eq!(reopened.remembered_mesh_path(), Some(b_abs.as_str()));
|
||||
// Edit B, then Reimport from the remembered path: B's edits arrive, not A.
|
||||
std::fs::write(&b, obj(3.0)).unwrap();
|
||||
let remembered = reopened.remembered_mesh_path().map(str::to_string).unwrap();
|
||||
crate::execute(&mut reopened, "file.reimportMesh", &json!({"path": remembered})).unwrap();
|
||||
assert_eq!(width(&reopened), 3.0);
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn change_mesh_resets_base_colours_and_drops_a_cage_of_another_mesh() {
|
||||
let dir = std::env::temp_dir().join(format!("tc_change_mesh_cage_{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let a = dir.join("a.obj");
|
||||
std::fs::write(&a, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap();
|
||||
// Same triangle count, other vertices.
|
||||
let b = dir.join("b.obj");
|
||||
std::fs::write(&b, "v 0 0 0\nv 2 0 0\nv 0 2 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap();
|
||||
let mut s = Session::from_mesh_bytes("a.obj", &std::fs::read(&a).unwrap(), 128, "a").unwrap();
|
||||
let cage = crate::bake::BakeMesh { name: "cage".into(), bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() };
|
||||
s.bake_meshes.cage = Some(cage);
|
||||
let _ = s.bake_meshes.low_base_color.set(Err("old".into()));
|
||||
// The same mesh again keeps the cage but not the cached colours.
|
||||
crate::execute(&mut s, "file.changeMesh", &json!({"path": a.display().to_string()})).unwrap();
|
||||
assert!(s.bake_meshes.cage.is_some());
|
||||
assert!(s.bake_meshes.low_base_color.get().is_none(), "the colours are read again");
|
||||
crate::execute(&mut s, "file.changeMesh", &json!({"path": b.display().to_string()})).unwrap();
|
||||
assert!(s.bake_meshes.cage.is_none(), "the cage was made for another mesh");
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unnamed_parts_keep_their_names_and_masks_through_save_and_reopen() {
|
||||
// A GLB quad whose mesh and node have no name: its one part is named after the file.
|
||||
|
||||
@@ -69,9 +69,16 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value {
|
||||
out
|
||||
}
|
||||
|
||||
/// A generator's settings, with its curvature mode and detail size weights when it has them.
|
||||
/// A generator's settings: global adjustments, then its resolution, replaced inputs and curvature detail when it has them.
|
||||
fn generator_json(generator: &Generator) -> Value {
|
||||
let mut out = json!({ "type": format!("{:?}", generator.kind), "level": generator.level, "softness": generator.softness, "noise": generator.noise_amount, "offset": generator.offset, "invert": generator.invert });
|
||||
let mut out = json!({ "type": format!("{:?}", generator.kind), "level": generator.level, "softness": generator.softness, "noise": generator.noise_amount, "offset": generator.offset, "invert": generator.invert, "blur": generator.global.blur, "balance": generator.global.balance, "contrast": generator.global.contrast });
|
||||
if !generator.resolution.is_default() {
|
||||
out["resolution"] =
|
||||
json!({ "mode": format!("{:?}", generator.resolution.mode), "custom": generator.resolution.custom, "factor": generator.resolution.factor });
|
||||
}
|
||||
if !generator.inputs.is_empty() {
|
||||
out["inputs"] = generator.inputs.iter().map(|(map, source)| (map.id().to_string(), source_json(source))).collect::<serde_json::Map<_, _>>().into();
|
||||
}
|
||||
if let Some(detail) = &generator.detail {
|
||||
out["mode"] = json!(format!("{:?}", detail.mode));
|
||||
out["sizes"] = json!(detail.weights);
|
||||
@@ -105,7 +112,7 @@ fn layer_json(s: &Session, l: &Layer, depth: usize) -> Value {
|
||||
v["geometryMask"] = json!(parts);
|
||||
}
|
||||
if matches!(l.kind, LayerKind::Paint) {
|
||||
// Sorted: the store is a hash map, and inspect output must be stable.
|
||||
// Sort the hash map entries for stable inspection output
|
||||
let mut painted: Vec<(&str, usize)> =
|
||||
s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == l.id).map(|((_, c), img)| (c.id(), img.allocated_count())).collect();
|
||||
painted.sort_unstable();
|
||||
|
||||
@@ -41,7 +41,7 @@ mod path_draft;
|
||||
pub mod path_tool;
|
||||
mod polygon_fill;
|
||||
mod polygon_fill_drag;
|
||||
// Mesh reimport reads files: native only.
|
||||
// Mesh reimport reads files on native targets only
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod preserve;
|
||||
pub mod preset_cmds;
|
||||
@@ -55,6 +55,7 @@ pub mod smart_masks;
|
||||
pub mod template_cmds;
|
||||
pub mod text_cmds;
|
||||
pub mod thumbs;
|
||||
mod tool_availability;
|
||||
pub mod tool_cmds;
|
||||
mod triangle_partition;
|
||||
mod uv_stroke_state;
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{
|
||||
BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground,
|
||||
Procedural, ProceduralKind, Project, Source,
|
||||
BakedMap, BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask,
|
||||
MaskBackground, OutputResolution, Procedural, ProceduralKind, Project, ResolutionMode, Source,
|
||||
};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p};
|
||||
@@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add generator",
|
||||
["Layers", "Effects"],
|
||||
None,
|
||||
"{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, offset?: -1..1 added to the result, invert?, mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear)}",
|
||||
"{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, offset?: -1..1 added to the result, invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear)}",
|
||||
has_layer,
|
||||
add_generator
|
||||
),
|
||||
@@ -94,7 +94,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit effect",
|
||||
[],
|
||||
None,
|
||||
"{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), level?, softness?, noise?, noiseScale?, offset?, invert?, mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}",
|
||||
"{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}",
|
||||
has_layer,
|
||||
set
|
||||
),
|
||||
@@ -242,7 +242,7 @@ fn push_effect(s: &mut Session, p: &Value, kind: EffectKind, blend: BlendMode) -
|
||||
let label = format!("Add {}", kind.name().to_ascii_lowercase());
|
||||
let eid = with_mask(s, p, "effect.add", &label, |s, id| {
|
||||
let eid = s.doc.project.alloc_id();
|
||||
// An instance's content and (unless it has its own) mask belong to its source.
|
||||
// An instance's content and inherited mask belong to its source
|
||||
let id = if content { s.doc.project.content_layer(id).map_or(id, |l| l.id) } else { s.doc.project.mask_owner(id) };
|
||||
let l = s.doc.project.layer_mut(id)?;
|
||||
let bg = if matches!(kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White };
|
||||
@@ -323,13 +323,13 @@ fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> R
|
||||
generator.softness = softness.clamp(0.0, 1.0);
|
||||
}
|
||||
if let Some(noise) = f32p(params, "noise") {
|
||||
generator.noise_amount = noise.clamp(0.0, 2.0);
|
||||
generator.noise_amount = noise.clamp(0.0, Generator::MAX_NOISE_AMOUNT);
|
||||
}
|
||||
if let Some(offset) = f32p(params, "offset") {
|
||||
generator.offset = offset.clamp(-1.0, 1.0);
|
||||
}
|
||||
if let Some(noise_scale) = f32p(params, "noiseScale") {
|
||||
generator.noise_scale = noise_scale.clamp(0.01, 1000.0);
|
||||
generator.noise_scale = noise_scale.clamp(Generator::MIN_NOISE_SCALE, Generator::MAX_NOISE_SCALE);
|
||||
}
|
||||
if let Some(seed) = u64p(params, "seed") {
|
||||
generator.seed = seed as u32;
|
||||
@@ -340,6 +340,26 @@ fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> R
|
||||
if let Some(direction) = color_param(command, params, "direction")? {
|
||||
generator.direction = direction;
|
||||
}
|
||||
if let Some(blur) = f32p(params, "blur") {
|
||||
generator.global.blur = blur.clamp(0.0, 1.0);
|
||||
}
|
||||
if let Some(balance) = f32p(params, "balance") {
|
||||
generator.global.balance = balance.clamp(0.0, 1.0);
|
||||
}
|
||||
if let Some(contrast) = f32p(params, "contrast") {
|
||||
generator.global.contrast = contrast.clamp(0.0, 1.0);
|
||||
}
|
||||
if let Some(value) = params.get("resolution") {
|
||||
let name = value.as_str().ok_or_else(|| bad(command, "`resolution` must be a string"))?;
|
||||
generator.resolution.mode = ResolutionMode::parse(name).ok_or_else(|| bad(command, format!("unknown resolution `{name}`")))?;
|
||||
}
|
||||
if let Some(custom) = u64p(params, "customResolution") {
|
||||
generator.resolution.custom = custom.clamp(1, u64::from(OutputResolution::MAX_SIZE)) as u32;
|
||||
}
|
||||
if let Some(factor) = params.get("resolutionFactor") {
|
||||
let factor = factor.as_i64().ok_or_else(|| bad(command, "`resolutionFactor` must be a whole number"))?;
|
||||
generator.resolution.factor = factor.clamp(i64::from(*OutputResolution::FACTORS.start()), i64::from(*OutputResolution::FACTORS.end())) as i8;
|
||||
}
|
||||
|
||||
// A mode or sizes also give a curvature generator saved before detail sizes its detail
|
||||
let mode = params
|
||||
@@ -378,6 +398,35 @@ fn size_weights(command: &str, value: &Value) -> Result<[f32; CurvatureDetail::S
|
||||
Ok(weights)
|
||||
}
|
||||
|
||||
/// The generator input named by `input` and what replaces it (None: its mesh map again), for a generator on layer `owner`.
|
||||
fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result<Option<(BakedMap, Option<Source>)>> {
|
||||
const CMD: &str = "effect.set";
|
||||
let Some(name) = params.get("input") else { return Ok(None) };
|
||||
let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id"))?;
|
||||
let map = BakedMap::parse(name).ok_or_else(|| bad(CMD, format!("unknown input `{name}`")))?;
|
||||
|
||||
let image = strp(params, "inputImage");
|
||||
let value = f32p(params, "inputValue");
|
||||
let anchor = u64p(params, "inputAnchor");
|
||||
let baked = boolp(params, "inputBaked") == Some(true);
|
||||
let source = match (image, value, anchor, baked) {
|
||||
(Some(image), None, None, false) => {
|
||||
if !session.images.contains_key(image) {
|
||||
return Err(bad(CMD, format!("no image resource `{image}`")));
|
||||
}
|
||||
Some(Source::Image { name: image.to_string(), normal_format: Default::default() })
|
||||
}
|
||||
(None, Some(value), None, false) => Some(Source::Uniform([value.clamp(0.0, 1.0); 3])),
|
||||
(None, None, Some(anchor), false) => {
|
||||
let channel = channel_param(CMD, params, "anchorChannel")?.unwrap_or(Channel::Height);
|
||||
Some(anchor_source(session, CMD, owner, LayerId(anchor), channel)?)
|
||||
}
|
||||
(None, None, None, true) => None,
|
||||
_ => return Err(bad(CMD, "`input` takes exactly one of inputImage, inputValue, inputAnchor or inputBaked")),
|
||||
};
|
||||
Ok(Some((map, source)))
|
||||
}
|
||||
|
||||
fn add_generator(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let kind = match strp(params, "generator") {
|
||||
Some(name) => GeneratorKind::parse(name).ok_or_else(|| bad("effect.add.generator", format!("unknown generator `{name}`")))?,
|
||||
@@ -458,6 +507,13 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const CMD: &str = "effect.set";
|
||||
let effect = effect_id(session, params, CMD)?;
|
||||
let blend = blend_param(CMD, params, "blend")?;
|
||||
let generator_kind = params
|
||||
.get("generator")
|
||||
.map(|value| {
|
||||
let name = value.as_str().ok_or_else(|| bad(CMD, "`generator` must be a string"))?;
|
||||
GeneratorKind::parse(name).ok_or_else(|| bad(CMD, format!("unknown generator `{name}`")))
|
||||
})
|
||||
.transpose()?;
|
||||
|
||||
// `anchor` picks a fill's anchor point, `anchorChannel` alone re-targets the current one
|
||||
let anchor = match session.doc.project.effect(effect) {
|
||||
@@ -475,6 +531,12 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
_ => None,
|
||||
};
|
||||
|
||||
// `input` names a generator input that `inputImage`, `inputValue` or `inputAnchor` replaces, or `inputBaked` puts back
|
||||
let input = match session.doc.project.effect(effect) {
|
||||
Some((owner, Effect { kind: EffectKind::Generator(_), .. })) => generator_input_param(session, owner, params)?,
|
||||
_ => None,
|
||||
};
|
||||
|
||||
// Naming the filter the effect already is edits its parameters like a plain effect.set
|
||||
let swapped = match strp(params, "filter") {
|
||||
Some(filter) if crate::filter_lib::find(filter).is_some_and(|def| current_filter_id(session, effect) == Some(def.id)) => None,
|
||||
@@ -508,7 +570,26 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
match &mut edited.kind {
|
||||
EffectKind::Generator(generator) => generator_from(CMD, params, generator)?,
|
||||
EffectKind::Generator(generator) => {
|
||||
if let Some(kind) = generator_kind
|
||||
&& kind != generator.kind
|
||||
{
|
||||
generator.kind = kind;
|
||||
generator.detail = Generator::new(kind).detail;
|
||||
generator.inputs.retain(|map, _| kind.inputs().contains(map));
|
||||
}
|
||||
generator_from(CMD, params, generator)?;
|
||||
if let Some((map, source)) = input {
|
||||
if !generator.kind.inputs().contains(&map) {
|
||||
return Err(bad(CMD, format!("this generator has no `{}` input", map.id())));
|
||||
}
|
||||
match source {
|
||||
Some(source) => generator.inputs.insert(map, source),
|
||||
None => generator.inputs.remove(&map),
|
||||
};
|
||||
}
|
||||
}
|
||||
_ if generator_kind.is_some() => return Err(bad(CMD, "`generator` requires a generator effect")),
|
||||
EffectKind::Levels(levels) => levels_from(params, levels),
|
||||
// The swapped filter was built with the parameters already
|
||||
EffectKind::Filter(_) if swaps_filter => {}
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
use texturecraft_compose::PixelStore;
|
||||
use texturecraft_core::{EffectKind, LayerId, LayerKind, Project, Source, TextureSet};
|
||||
use texturecraft_core::{LayerId, LayerKind, Project, Source, TextureSet};
|
||||
|
||||
use crate::commands::{CommandSpec, always, has_layer};
|
||||
use crate::materials::Place;
|
||||
@@ -36,27 +36,26 @@ fn fe(e: texturecraft_formats::FormatError) -> EngineError {
|
||||
EngineError::Other(e.to_string())
|
||||
}
|
||||
|
||||
/// Image resources a layer subtree uses (fill sources and fill effects).
|
||||
pub(crate) fn images_used(p: &Project, id: LayerId, out: &mut Vec<String>, depth: usize) {
|
||||
/// Image resources a layer subtree uses (fill sources and mask or content effects).
|
||||
pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec<String>, depth: usize) {
|
||||
if depth > texturecraft_core::project::MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
let Some(l) = p.layers.get(&id) else { return };
|
||||
if let LayerKind::Fill(f) = &l.kind {
|
||||
for s in f.sources.values() {
|
||||
if let Source::Image { name, .. } = s {
|
||||
let Some(layer) = project.layers.get(&id) else { return };
|
||||
|
||||
if let LayerKind::Fill(fill) = &layer.kind {
|
||||
for source in fill.sources.values() {
|
||||
if let Source::Image { name, .. } = source {
|
||||
out.push(name.clone());
|
||||
}
|
||||
}
|
||||
out.extend(f.link.as_ref().map(|link| link.package.clone()));
|
||||
out.extend(fill.link.as_ref().map(|link| link.package.clone()));
|
||||
}
|
||||
for e in l.mask.iter().flat_map(|m| m.effects.iter()) {
|
||||
if let EffectKind::Fill { source: Source::Image { name, .. }, .. } = &e.kind {
|
||||
out.push(name.clone());
|
||||
}
|
||||
for effect in layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(&layer.content_effects) {
|
||||
out.extend(effect.kind.images_read().map(str::to_string));
|
||||
}
|
||||
for c in l.children() {
|
||||
images_used(p, *c, out, depth + 1);
|
||||
for child in layer.children() {
|
||||
images_used(project, *child, out, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Interactive painting on the session: strokes (begin / continue / end / cancel), polygon fill
|
||||
//! and the color picker. The UI, CLI and agents all go through these.
|
||||
//! and the material picker. The UI, CLI and agents all go through these.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
@@ -553,20 +553,22 @@ impl Session {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Color picker: copy the material under the cursor into the tool's paint values.
|
||||
/// Material picker: copy the material under the cursor into the tool's paint values
|
||||
pub fn color_pick(&mut self, screen: Vec2, viewport: Vec2) -> Result<BTreeMap<Channel, [f32; 3]>> {
|
||||
let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?;
|
||||
let ts = self.texture_set_of_material(hit.material).unwrap_or(self.ts());
|
||||
let cache = self.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?;
|
||||
let (w, h) = (cache.size.0 as f32, cache.size.1 as f32);
|
||||
let (x, y) = ((hit.uv.x * w).clamp(0.0, w - 1.0) as u32, (hit.uv.y * h).clamp(0.0, h - 1.0) as u32);
|
||||
let mut out = BTreeMap::new();
|
||||
for c in cache.composite.channels.keys() {
|
||||
let v = cache.composite.value(*c, x, y);
|
||||
self.tool.values.insert(*c, v);
|
||||
out.insert(*c, v);
|
||||
let texture_set = self.texture_set_of_material(hit.material).unwrap_or(self.ts());
|
||||
let cache = self.caches.get(texture_set).ok_or_else(|| EngineError::Other("texture set not ready".into()))?;
|
||||
|
||||
let (width, height) = (cache.size.0 as f32, cache.size.1 as f32);
|
||||
let (x, y) = ((hit.uv.x * width).clamp(0.0, width - 1.0) as u32, (hit.uv.y * height).clamp(0.0, height - 1.0) as u32);
|
||||
|
||||
let mut picked = BTreeMap::new();
|
||||
for channel in cache.composite.channels.keys() {
|
||||
let value = cache.composite.value(*channel, x, y);
|
||||
self.tool.values.insert(*channel, value);
|
||||
picked.insert(*channel, value);
|
||||
}
|
||||
Ok(out)
|
||||
Ok(picked)
|
||||
}
|
||||
|
||||
/// The stroke canvas alpha of the active stroke (for overlays and tests).
|
||||
|
||||
@@ -12,7 +12,7 @@ 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_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground, PathShape};
|
||||
use texturecraft_geom::glam::{Mat3, Vec2, Vec3};
|
||||
use texturecraft_geom::{OrbitCamera, surface_at};
|
||||
use texturecraft_paint::{BrushSettings, Lasso, PickCtx, fill_coverage, pick, spline, spline_segments};
|
||||
@@ -368,6 +368,10 @@ impl Session {
|
||||
|
||||
/// 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 self.quick_mask.editing {
|
||||
return Err(EngineError::Other("paths can't edit the quick mask: stop editing it first".into()));
|
||||
}
|
||||
|
||||
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))
|
||||
{
|
||||
@@ -396,20 +400,20 @@ impl Session {
|
||||
let shape = self.path_shape(self.camera, viewport);
|
||||
let editing = self.tool.path.editing;
|
||||
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 {
|
||||
let report = self.edit_merging(&label, editing.is_some() && self.tool.path.edited, |session| {
|
||||
let (effect_id, index) = match editing {
|
||||
Some(at) => at,
|
||||
None => (s.path_effect()?, usize::MAX),
|
||||
None => (session.path_effect()?, usize::MAX),
|
||||
};
|
||||
s.put_path(eid, index, shape)
|
||||
session.put_path(effect_id, index, shape)
|
||||
})?;
|
||||
|
||||
if let Some(eid) = out.get("effect").and_then(Value::as_u64) {
|
||||
self.target = StackTarget::Effect(LayerId(eid));
|
||||
if let Some(effect_id) = report.get("effect").and_then(Value::as_u64) {
|
||||
self.target = StackTarget::Effect(LayerId(effect_id));
|
||||
}
|
||||
self.tool.path.clear();
|
||||
|
||||
Ok(out)
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -429,9 +433,13 @@ impl Session {
|
||||
|
||||
/// 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> {
|
||||
if self.quick_mask.editing {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
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)),
|
||||
Some((effect_id, index)) => match self.paths(effect_id).and_then(|paths| paths.get(index)).cloned() {
|
||||
Some(shape) => Some((effect_id, index, shape)),
|
||||
None => {
|
||||
self.stop_path_edit();
|
||||
return Ok(false);
|
||||
@@ -661,6 +669,11 @@ impl Session {
|
||||
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) };
|
||||
|
||||
// Returning false here would let undo/redo consume document history instead.
|
||||
if self.quick_mask.editing {
|
||||
return Err(EngineError::Other("paths can't edit the quick mask: stop editing it first".into()));
|
||||
}
|
||||
|
||||
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() {
|
||||
@@ -706,33 +719,40 @@ impl Session {
|
||||
self.path_steps = Default::default();
|
||||
}
|
||||
|
||||
/// The selected path sublayer, or a new one on the selected layer's content or mask
|
||||
/// (whichever is selected).
|
||||
/// The selected path sublayer, or a new one on the selected paint layer's content or mask
|
||||
fn path_effect(&mut self) -> Result<LayerId> {
|
||||
let id = self.selected_layer().ok_or_else(|| EngineError::Other("select a layer to add the path to".into()))?;
|
||||
let p = &self.doc.project;
|
||||
if self.quick_mask.editing {
|
||||
return Err(EngineError::Other("paths can't edit the quick mask: stop editing it first".into()));
|
||||
}
|
||||
|
||||
let selected = self.selected_layer().ok_or_else(|| EngineError::Other("select a layer to add the path to".into()))?;
|
||||
let project = &self.doc.project;
|
||||
let mask = match self.target {
|
||||
StackTarget::Effect(e) => match p.effect(e) {
|
||||
Some((_, x)) if matches!(x.kind, EffectKind::Path(_)) => return Ok(e),
|
||||
Some((owner, _)) => !p.layer(owner)?.content_effects.iter().any(|x| x.id == e),
|
||||
StackTarget::Effect(effect) => match project.effect(effect) {
|
||||
// Paths saved in a fill layer before paths there were removed stay editable
|
||||
Some((_, found)) if matches!(found.kind, EffectKind::Path(_)) => return Ok(effect),
|
||||
Some((owner, _)) => !project.layer(owner)?.content_effects.iter().any(|candidate| candidate.id == effect),
|
||||
None => false,
|
||||
},
|
||||
StackTarget::Mask => true,
|
||||
StackTarget::Content => false,
|
||||
};
|
||||
// An instance's content and (unless it has its own) mask belong to its source.
|
||||
let owner = if mask { p.mask_owner(id) } else { p.content_layer(id).map_or(id, |l| l.id) };
|
||||
let eid = self.doc.project.alloc_id();
|
||||
let l = self.doc.project.layer_mut(owner)?;
|
||||
let e = Effect::new(eid, EffectKind::Path(Vec::new()));
|
||||
|
||||
// An instance's content and (unless it has its own) mask belong to its source
|
||||
let owner = if mask { project.mask_owner(selected) } else { project.content_layer(selected).map_or(selected, |layer| layer.id) };
|
||||
let path_id = self.doc.project.alloc_id();
|
||||
let layer = self.doc.project.layer_mut(owner)?;
|
||||
let path = Effect::new(path_id, EffectKind::Path(Vec::new()));
|
||||
if mask {
|
||||
l.mask.get_or_insert_with(|| Mask::new(MaskBackground::Black)).effects.push(e);
|
||||
} else if l.is_group() {
|
||||
return Err(EngineError::Other(format!("\"{}\" is a folder: add the path to a layer or a mask", l.name)));
|
||||
layer.mask.get_or_insert_with(|| Mask::new(MaskBackground::Black)).effects.push(path);
|
||||
} else if layer.is_group() {
|
||||
return Err(EngineError::Other(format!("\"{}\" is a folder: add the path to a layer or a mask", layer.name)));
|
||||
} else if matches!(layer.kind, LayerKind::Paint) {
|
||||
layer.content_effects.push(path);
|
||||
} else {
|
||||
l.content_effects.push(e);
|
||||
return Err(EngineError::Other(format!("\"{}\" is not a paint layer: add the path to a paint layer or a mask", layer.name)));
|
||||
}
|
||||
Ok(eid)
|
||||
Ok(path_id)
|
||||
}
|
||||
|
||||
/// [`Session::put_path`] recompositing only the tiles it changed, with no undo step: returns the paint report and the document before
|
||||
@@ -1071,6 +1091,29 @@ mod tests {
|
||||
assert_eq!(changed_tiles(&before, &after, LayerId(8)), BTreeSet::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quick_mask_preserves_pending_path_undo_and_redo() {
|
||||
let mut session = Session::new_project("t", texturecraft_geom::primitives::plane(1.0, 1), "builtin:test", None, 128).unwrap();
|
||||
execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]})).unwrap();
|
||||
session.path_checkpoint();
|
||||
session.tool.path.points[0].y = 0.3;
|
||||
session.path_live().unwrap();
|
||||
for back in [true, false] {
|
||||
let curve = session.tool.path.clone();
|
||||
let steps = (session.path_steps.0.len(), session.path_steps.1.len());
|
||||
let history = (session.history_labels(), session.redo_labels());
|
||||
let pixels = session.doc.pixels.clone();
|
||||
session.quick_mask.editing = true;
|
||||
assert!(if back { session.undo() } else { session.redo() }.is_err());
|
||||
assert!(curve.same_curve(&session.tool.path));
|
||||
assert_eq!(steps, (session.path_steps.0.len(), session.path_steps.1.len()));
|
||||
assert_eq!(history, (session.history_labels(), session.redo_labels()));
|
||||
assert_eq!(format!("{:?}", pixels), format!("{:?}", session.doc.pixels));
|
||||
session.quick_mask.editing = false;
|
||||
if back { session.undo() } else { session.redo() }.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[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();
|
||||
|
||||
@@ -16,8 +16,14 @@ use crate::Session;
|
||||
const REACH: f32 = 0.05;
|
||||
|
||||
/// Re-project the painted pixels of `next` (a session on the reimported mesh holding `old`'s
|
||||
/// document) from `old`'s UV layout. Returns how many texels found the old surface.
|
||||
/// document) from `old`'s UV layout. Returns how many texels found the old surface;
|
||||
/// a texture set where none does keeps its pixels as they are. Nothing is re-projected when the
|
||||
/// UV layout and topology are unchanged (same triangles, materials and UVs): the pixels already
|
||||
/// sit where they belong, however far the mesh moved.
|
||||
pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize {
|
||||
if same_layout(&old.mesh, &next.mesh) {
|
||||
return 0;
|
||||
}
|
||||
let reach = REACH * 2.0 * old.mesh.radius().max(next.mesh.radius());
|
||||
let mut found = 0;
|
||||
for ts in 0..next.set_count() {
|
||||
@@ -52,7 +58,12 @@ pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize {
|
||||
((tx, ty), src)
|
||||
})
|
||||
.collect();
|
||||
found += table.values().flatten().filter(|p| p[0].is_finite()).count();
|
||||
let matched = table.values().flatten().filter(|p| p[0].is_finite()).count();
|
||||
found += matched;
|
||||
// No old surface within reach anywhere (a moved or unrelated mesh): the paint stays where it is.
|
||||
if matched == 0 {
|
||||
continue;
|
||||
}
|
||||
let map = |x: f32, y: f32| {
|
||||
let (xi, yi) = (x as u32, y as u32);
|
||||
table.get(&(xi / TILE, yi / TILE)).and_then(|t| t.get(((yi % TILE) * TILE + xi % TILE) as usize)).filter(|p| p[0].is_finite()).map(|p| (p[0], p[1]))
|
||||
@@ -63,6 +74,12 @@ pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize {
|
||||
found
|
||||
}
|
||||
|
||||
/// Same index buffer, same UVs per vertex and the same material ranges.
|
||||
fn same_layout(a: &texturecraft_geom::Mesh, b: &texturecraft_geom::Mesh) -> bool {
|
||||
let ranges = |m: &texturecraft_geom::Mesh| m.submeshes.iter().map(|s| (s.material, s.start, s.count)).collect::<Vec<_>>();
|
||||
a.indices == b.indices && a.uvs == b.uvs && ranges(a) == ranges(b)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -104,4 +121,50 @@ mod tests {
|
||||
}
|
||||
assert!(right > 10_000 && wrong == 0, "{right} right, {wrong} wrong");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mesh_with_no_surface_in_reach_keeps_the_paint_where_it_is() {
|
||||
let mut s = Session::new_project("p", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap();
|
||||
let id = s.doc.project.texture_sets[0].stack[0];
|
||||
let img = s.doc.pixels.layer_mut(id, Channel::BaseColor, (128, 128));
|
||||
for x in 0..64 {
|
||||
img.set(x, 40, &[65535, 0, 0, 65535]);
|
||||
}
|
||||
// The same plane far away and with mirrored UVs (so the layout differs and the unchanged-layout
|
||||
// shortcut is not taken): nothing of the old surface is within reach.
|
||||
let mut mesh = (*s.mesh).clone();
|
||||
for p in &mut mesh.positions {
|
||||
p.x += 100.0;
|
||||
}
|
||||
for uv in &mut mesh.uvs {
|
||||
*uv = Vec2::new(1.0 - uv.x, uv.y);
|
||||
}
|
||||
let mut next = Session::new(s.doc.clone(), mesh, None).unwrap();
|
||||
assert_eq!(preserve_strokes(&s, &mut next), 0);
|
||||
let img = next.doc.pixels.layer(id, Channel::BaseColor).unwrap();
|
||||
assert_eq!(img.get(10, 40)[3], 65535, "the painted texel is still there");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_translated_mesh_with_the_same_uvs_keeps_every_pixel() {
|
||||
let mut s = Session::new_project("p", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap();
|
||||
let id = s.doc.project.texture_sets[0].stack[0];
|
||||
let img = s.doc.pixels.layer_mut(id, Channel::BaseColor, (128, 128));
|
||||
for x in 0..128 {
|
||||
img.set(x, 40, &[65535, 0, 0, 65535]);
|
||||
}
|
||||
// Slid along its own surface by a fraction of the plane: half of it still overlaps the old one.
|
||||
let mut mesh = (*s.mesh).clone();
|
||||
let shift = mesh.radius() * 0.5;
|
||||
for p in &mut mesh.positions {
|
||||
p.x += shift;
|
||||
}
|
||||
let mut next = Session::new(s.doc.clone(), mesh, None).unwrap();
|
||||
assert_eq!(preserve_strokes(&s, &mut next), 0);
|
||||
let img = next.doc.pixels.layer(id, Channel::BaseColor).unwrap();
|
||||
for x in 0..128 {
|
||||
assert_eq!(img.get(x, 40)[3], 65535, "texel {x} of the painted row moved");
|
||||
assert_eq!(img.get(x, 41)[3], 0, "texel {x} of the next row got paint");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,44 +35,53 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit quick mask",
|
||||
["Viewport"],
|
||||
Some("U"),
|
||||
"{editing?: bool} — toggles when omitted; editing enables the mask",
|
||||
always,
|
||||
"{editing?: bool} — toggles when omitted; needs the quick mask enabled",
|
||||
mask_enabled,
|
||||
edit
|
||||
),
|
||||
cmd!("viewport.quickMask.invert", "Invert quick mask", ["Viewport"], Some("Ctrl+Shift+I"), "{}", always, invert),
|
||||
cmd!("viewport.quickMask.invert", "Invert quick mask", ["Viewport"], Some("Ctrl+Shift+I"), "{}", mask_enabled, invert),
|
||||
]
|
||||
}
|
||||
|
||||
fn state(s: &Session) -> Value {
|
||||
let q = &s.quick_mask;
|
||||
fn mask_enabled(session: &Session) -> std::result::Result<(), String> {
|
||||
if session.quick_mask.enabled { Ok(()) } else { Err("enable the quick mask first".into()) }
|
||||
}
|
||||
|
||||
fn state(session: &Session) -> Value {
|
||||
let mask = &session.quick_mask;
|
||||
json!({
|
||||
"enabled": q.enabled, "editing": q.editing, "inverted": q.inverted,
|
||||
"paintedTiles": q.masks.get(&s.ts()).map(TileImage::allocated_count).unwrap_or(0),
|
||||
"enabled": mask.enabled, "editing": mask.editing, "inverted": mask.inverted,
|
||||
"paintedTiles": mask.masks.get(&session.ts()).map(TileImage::allocated_count).unwrap_or(0),
|
||||
})
|
||||
}
|
||||
|
||||
fn changed(s: &mut Session) -> Result<Value> {
|
||||
s.quick_mask.revision = s.quick_mask.revision.wrapping_add(1);
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
Ok(state(s))
|
||||
fn changed(session: &mut Session) -> Result<Value> {
|
||||
session.quick_mask.revision = session.quick_mask.revision.wrapping_add(1);
|
||||
session.revision = session.revision.wrapping_add(1);
|
||||
Ok(state(session))
|
||||
}
|
||||
|
||||
fn enable(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.quick_mask.enabled = boolp(p, "enabled").unwrap_or(!s.quick_mask.enabled);
|
||||
changed(s)
|
||||
fn enable(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let enabled = boolp(params, "enabled").unwrap_or(!session.quick_mask.enabled);
|
||||
if !enabled && session.quick_mask.editing {
|
||||
session.cancel_stroke();
|
||||
session.quick_mask.editing = false;
|
||||
}
|
||||
|
||||
session.quick_mask.enabled = enabled;
|
||||
changed(session)
|
||||
}
|
||||
|
||||
fn edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.cancel_stroke();
|
||||
let q = &mut s.quick_mask;
|
||||
q.editing = boolp(p, "editing").unwrap_or(!q.editing);
|
||||
q.enabled |= q.editing;
|
||||
changed(s)
|
||||
fn edit(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
session.cancel_stroke();
|
||||
let quick_mask = &mut session.quick_mask;
|
||||
quick_mask.editing = boolp(params, "editing").unwrap_or(!quick_mask.editing);
|
||||
changed(session)
|
||||
}
|
||||
|
||||
fn invert(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
s.quick_mask.inverted = !s.quick_mask.inverted;
|
||||
changed(s)
|
||||
fn invert(session: &mut Session, _: &Value) -> Result<Value> {
|
||||
session.quick_mask.inverted = !session.quick_mask.inverted;
|
||||
changed(session)
|
||||
}
|
||||
|
||||
impl Session {
|
||||
|
||||
@@ -109,7 +109,7 @@ impl Tool {
|
||||
Tool::PolygonFill => "Polygon fill",
|
||||
Tool::Smudge => "Smudge",
|
||||
Tool::Clone => "Clone",
|
||||
Tool::ColorPicker => "Color picker",
|
||||
Tool::ColorPicker => "Material picker",
|
||||
Tool::Path => "Path",
|
||||
Tool::GeometryMask => "Geometry mask",
|
||||
}
|
||||
@@ -595,6 +595,7 @@ impl Session {
|
||||
|| layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects).any(|effect| match &effect.kind {
|
||||
EffectKind::Fill { source, .. } => uses_source(source),
|
||||
EffectKind::Material(fill) => uses_fill(fill),
|
||||
EffectKind::Generator(generator) => generator.inputs.values().any(uses_source),
|
||||
_ => false,
|
||||
})
|
||||
})
|
||||
@@ -764,7 +765,8 @@ impl Session {
|
||||
self.modified = true;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
self.invalidate_changed(other);
|
||||
// An undone add or duplicate takes the selected effect away: select the stack it was in.
|
||||
|
||||
// An undone add or duplicate takes the selected effect away
|
||||
if let StackTarget::Effect(e) = self.target
|
||||
&& self.doc.project.effect(e).is_none()
|
||||
{
|
||||
@@ -1009,14 +1011,22 @@ pub const SETTLE_BUDGET_MS: f64 = 6.0;
|
||||
|
||||
/// Take up to `n` dirty tiles, block by block (16 × 16 tiles) so neighbourhood filters
|
||||
/// evaluate compact regions.
|
||||
fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, n: usize) -> Vec<(u32, u32)> {
|
||||
if dirty.len() <= n {
|
||||
fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, max_tiles: usize) -> Vec<(u32, u32)> {
|
||||
// A zero-sized request cannot select a pivot
|
||||
if max_tiles == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
if dirty.len() <= max_tiles {
|
||||
return std::mem::take(dirty).into_iter().collect();
|
||||
}
|
||||
|
||||
let mut tiles: Vec<(u32, u32)> = dirty.iter().copied().collect();
|
||||
|
||||
// Partition by block order so only the requested chunk needs sorting
|
||||
tiles.select_nth_unstable_by_key(max_tiles - 1, |&(x, y)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK, y, x));
|
||||
tiles.truncate(max_tiles);
|
||||
tiles.sort_by_key(|&(x, y)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK, y, x));
|
||||
tiles.truncate(n);
|
||||
for tile in &tiles {
|
||||
dirty.remove(tile);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
//! Which tools can act on the current selection: the tool shelf and its shortcuts grey the rest
|
||||
|
||||
use texturecraft_core::{EffectKind, LayerKind};
|
||||
|
||||
use crate::{Session, StackTarget, Tool};
|
||||
|
||||
impl Session {
|
||||
/// Whether `tool` can act on the selection (or on the quick mask while it is being edited)
|
||||
pub fn tool_usable(&self, tool: Tool) -> bool {
|
||||
match tool {
|
||||
// The picker reads the composite under the cursor, whatever is selected
|
||||
Tool::ColorPicker => return true,
|
||||
Tool::GeometryMask => return self.selected_layer().is_some(),
|
||||
_ => {}
|
||||
}
|
||||
|
||||
// Brushes paint the quick mask whatever is selected; paths can't edit it
|
||||
if self.quick_mask.editing {
|
||||
return tool != Tool::Path;
|
||||
}
|
||||
|
||||
let project = &self.doc.project;
|
||||
let Some(layer) = self.selected_layer().and_then(|id| project.layers.get(&id)) else { return false };
|
||||
|
||||
// Smudge and Clone read layer content, so they can't yet paint mask values
|
||||
let reads_content = matches!(tool, Tool::Smudge | Tool::Clone);
|
||||
match self.target {
|
||||
StackTarget::Content => matches!(layer.kind, LayerKind::Paint),
|
||||
StackTarget::Mask => !reads_content,
|
||||
StackTarget::Effect(effect) => {
|
||||
let Some((owner, found)) = project.effect(effect) else { return false };
|
||||
let Some(owner_layer) = project.layers.get(&owner) else { return false };
|
||||
let in_content = owner_layer.content_effects.iter().any(|candidate| candidate.id == effect);
|
||||
let in_fill_content = in_content && matches!(owner_layer.kind, LayerKind::Fill(_));
|
||||
|
||||
match found.kind {
|
||||
// Paths saved in a fill layer before paths there were removed stay editable
|
||||
EffectKind::Path(_) => tool == Tool::Path,
|
||||
EffectKind::Paint if tool == Tool::Path => !in_fill_content,
|
||||
EffectKind::Paint => in_content || !reads_content,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("tool.polygonFill", "Polygon fill", ["Tools"], Some("4"), "{}", always, |s, _| set_tool(s, Tool::PolygonFill)),
|
||||
cmd!("tool.smudge", "Smudge", ["Tools"], Some("5"), "{}", always, |s, _| set_tool(s, Tool::Smudge)),
|
||||
cmd!("tool.clone", "Clone", ["Tools"], Some("6"), "{}", always, |s, _| set_tool(s, Tool::Clone)),
|
||||
cmd!("tool.colorPicker", "Color picker", ["Tools"], Some("P"), "{}", always, |s, _| set_tool(s, Tool::ColorPicker)),
|
||||
cmd!("tool.colorPicker", "Material picker", ["Tools"], Some("P"), "{}", always, |s, _| set_tool(s, Tool::ColorPicker)),
|
||||
cmd!(
|
||||
"tool.geometryMask",
|
||||
"Geometry mask",
|
||||
@@ -105,7 +105,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Tool click",
|
||||
[],
|
||||
None,
|
||||
"{x, y, viewport?: [w,h]} — polygon fill / color picker / single dab; polygon fill also takes a box {x0, y0, x1, y1, viewport?}, a 2D view point {uv: [u,v]} or a 2D view box {uv0: [u,v], uv1: [u,v]}",
|
||||
"{x, y, viewport?: [w,h]} — polygon fill / material picker / single dab; polygon fill also takes a box {x0, y0, x1, y1, viewport?}, a 2D view point {uv: [u,v]} or a 2D view box {uv0: [u,v], uv1: [u,v]}",
|
||||
always,
|
||||
click
|
||||
),
|
||||
@@ -115,6 +115,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
pub(crate) fn set_tool(session: &mut Session, tool: Tool) -> Result<Value> {
|
||||
session.cancel_stroke();
|
||||
|
||||
// A box fill under way keeps what it filled as one undo step
|
||||
session.end_polygon_fill_box();
|
||||
session.tool.tool = tool;
|
||||
@@ -342,40 +343,44 @@ fn swap_mask_value(session: &mut Session, _: &Value) -> Result<Value> {
|
||||
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;
|
||||
fn stencil(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
if boolp(params, "clear") == Some(true) {
|
||||
session.tool.stencil = None;
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
if let Some(name) = strp(p, "image") {
|
||||
if !s.doc.resources.contains_key(name) {
|
||||
|
||||
if let Some(name) = strp(params, "image") {
|
||||
if !session.doc.resources.contains_key(name) {
|
||||
return Err(bad("tool.stencil", format!("no resource `{name}` (import it first)")));
|
||||
}
|
||||
let keep = s.tool.stencil.take();
|
||||
let mut st = crate::session::StencilState::new(name);
|
||||
if let Some(k) = keep {
|
||||
st = crate::session::StencilState { image: name.to_string(), ..k };
|
||||
|
||||
let previous_stencil = session.tool.stencil.take();
|
||||
let mut stencil_state = crate::session::StencilState::new(name);
|
||||
if let Some(previous_stencil) = previous_stencil {
|
||||
stencil_state = crate::session::StencilState { image: name.to_string(), ..previous_stencil };
|
||||
}
|
||||
s.tool.stencil = Some(st);
|
||||
session.tool.stencil = Some(stencil_state);
|
||||
}
|
||||
let st = s.tool.stencil.as_mut().ok_or_else(|| bad("tool.stencil", "no stencil: give `image`"))?;
|
||||
if let Some(c) = pair(p, "center").or_else(|| p.get("center").and_then(color_of).map(|c| [c[0], c[1]])) {
|
||||
st.center = c.map(|v| v.clamp(-4.0, 4.0));
|
||||
|
||||
let stencil_state = session.tool.stencil.as_mut().ok_or_else(|| bad("tool.stencil", "no stencil: give `image`"))?;
|
||||
if let Some(center) = pair(params, "center").or_else(|| params.get("center").and_then(color_of).map(|color| [color[0], color[1]])) {
|
||||
stencil_state.center = center.map(|value| value.clamp(-4.0, 4.0));
|
||||
}
|
||||
if let Some(v) = f32p(p, "scale") {
|
||||
st.scale = v.clamp(0.01, 10.0);
|
||||
if let Some(scale) = f32p(params, "scale") {
|
||||
stencil_state.scale = scale.clamp(0.01, 10.0);
|
||||
}
|
||||
if let Some(v) = f32p(p, "rotation") {
|
||||
st.rotation = v.rem_euclid(360.0);
|
||||
if let Some(rotation) = f32p(params, "rotation") {
|
||||
stencil_state.rotation = rotation.rem_euclid(360.0);
|
||||
}
|
||||
if let Some(v) = boolp(p, "tile") {
|
||||
st.tile = v;
|
||||
if let Some(tile) = boolp(params, "tile") {
|
||||
stencil_state.tile = tile;
|
||||
}
|
||||
if let Some(v) = f32p(p, "opacity") {
|
||||
st.opacity = v.clamp(0.0, 1.0);
|
||||
if let Some(opacity) = f32p(params, "opacity") {
|
||||
stencil_state.opacity = opacity.clamp(0.0, 1.0);
|
||||
}
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
Ok(serde_json::to_value(&s.tool.stencil).unwrap_or(Value::Null))
|
||||
|
||||
session.revision = session.revision.wrapping_add(1);
|
||||
Ok(serde_json::to_value(&session.tool.stencil).unwrap_or(Value::Null))
|
||||
}
|
||||
|
||||
/// A `[a, b]` param of two finite numbers.
|
||||
|
||||
@@ -464,7 +464,8 @@ fn leaning_session(lean: bool) -> Session {
|
||||
}
|
||||
let high_text = obj(&mesh, 0.1, f32::MAX, [1.0; 3]);
|
||||
let mut s = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap();
|
||||
// A folder of its own per call: tests run in parallel, and another one removes the shared folder.
|
||||
|
||||
// Tests run in parallel, so each call needs its own folder
|
||||
static CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
let call = CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let dir = std::env::temp_dir().join(format!("texturecraft-lean-test-{}-{call}", std::process::id()));
|
||||
@@ -472,7 +473,8 @@ fn leaning_session(lean: bool) -> Session {
|
||||
let high = dir.join("high.obj");
|
||||
std::fs::write(&high, high_text).unwrap();
|
||||
execute(&mut s, "bake.highPoly.add", &json!({ "path": high.display().to_string() })).unwrap();
|
||||
// The mesh is parsed and kept on add, so the file can go.
|
||||
|
||||
// The imported mesh remains after its source file is removed
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
execute(
|
||||
&mut s,
|
||||
@@ -489,10 +491,12 @@ fn the_skew_map_is_saved_with_the_project() {
|
||||
execute(&mut s, "bake.skew.set", &json!({ "value": 0.25 })).unwrap();
|
||||
let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
|
||||
assert_eq!(back.doc.bake_paint, s.doc.bake_paint);
|
||||
// No skew: none comes back.
|
||||
|
||||
// Clearing skew persists
|
||||
execute(&mut s, "bake.skew.clear", &Value::Null).unwrap();
|
||||
assert!(Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap().doc.bake_paint.is_empty());
|
||||
// A map with a non-finite value is skipped with a log line, and the project still opens.
|
||||
|
||||
// Invalid saved skew is skipped without preventing project load
|
||||
let mut pf = s.project_file();
|
||||
pf.bake_paint.insert((0, texturecraft_core::BakePaintTarget::Skew), texturecraft_formats::BakePaintData { width: 1, height: 1, values: vec![f32::NAN] });
|
||||
let opened = Session::from_project_file(pf).unwrap();
|
||||
@@ -504,27 +508,46 @@ fn the_skew_map_is_saved_with_the_project() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_skew_map_steers_only_a_distance_cage_with_averaged_normals() {
|
||||
let mut s = leaning_session(false);
|
||||
execute(&mut s, "bake.skew.set", &json!({ "value": 0.25 })).unwrap();
|
||||
assert!(s.bake_task(0).unwrap().skew.is_some());
|
||||
|
||||
s.doc.project.texture_sets[0].bake.cage.average_normals = false;
|
||||
assert!(s.bake_task(0).unwrap().skew.is_none(), "without averaged normals the skew map is left out");
|
||||
s.doc.project.texture_sets[0].bake.cage.average_normals = true;
|
||||
let cage = obj(&s.mesh.clone(), 0.05, f32::MAX, [1.0; 3]);
|
||||
s.set_cage_bytes("cage.obj", cage.into_bytes()).unwrap();
|
||||
s.doc.project.texture_sets[0].bake.cage.kind = texturecraft_core::CageType::CustomFile;
|
||||
assert!(s.bake_task(0).unwrap().skew.is_none(), "a cage file sets the rays itself");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn painting_skew_widens_a_map_and_bad_strokes_change_nothing() {
|
||||
let mut s = leaning_session(true);
|
||||
// Painting with no map makes a black one at `size` and puts the dab in it.
|
||||
|
||||
// The first stroke creates a black map at the requested size
|
||||
let r = execute(&mut s, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.1, "size": 64 })).unwrap();
|
||||
assert_eq!(r["skew"]["width"], 64);
|
||||
let map = s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned().unwrap();
|
||||
assert!(map.values.iter().any(|v| *v > 0.99) && map.values.contains(&0.0));
|
||||
let rev = s.revision;
|
||||
// Erasing with value 0 brings it back down; the size stays.
|
||||
|
||||
// Erasing retains the map size
|
||||
execute(&mut s, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.2, "value": 0.0, "hardness": 1.0 })).unwrap();
|
||||
let after = s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned().unwrap();
|
||||
assert_eq!(after.width, 64);
|
||||
assert!(after.values.iter().all(|v| *v < 0.01) && s.revision > rev);
|
||||
// A constant map is widened, keeping its value where nothing is painted.
|
||||
|
||||
// Resizing preserves untouched constant values
|
||||
execute(&mut s, "bake.skew.set", &json!({ "value": 0.5 })).unwrap();
|
||||
execute(&mut s, "bake.skew.paint", &json!({ "points": [[0.1, 0.1]], "radius": 0.05, "size": 32 })).unwrap();
|
||||
let wide = s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned().unwrap();
|
||||
assert_eq!(wide.width, 32);
|
||||
assert!((wide.values[wide.values.len() / 2] - 0.5).abs() < 1e-5, "{}", wide.values[wide.values.len() / 2]);
|
||||
// Hostile input is an error and leaves the map alone.
|
||||
|
||||
// Invalid strokes leave the map unchanged
|
||||
let before = s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned();
|
||||
for bad in [
|
||||
json!({}),
|
||||
@@ -541,7 +564,8 @@ fn painting_skew_widens_a_map_and_bad_strokes_change_nothing() {
|
||||
assert!(execute(&mut s, "bake.skew.paint", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned(), before);
|
||||
// And the painted map is saved with the project.
|
||||
|
||||
// Painted skew survives a project round trip
|
||||
let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
|
||||
assert_eq!(back.doc.bake_paint, s.doc.bake_paint);
|
||||
}
|
||||
@@ -627,3 +651,42 @@ fn obj_submesh_id_separates_objects_with_the_same_name_and_material() {
|
||||
let pixel = |x: usize| &map[(100 * 128 + x) * 3..(100 * 128 + x) * 3 + 3];
|
||||
assert_ne!(pixel(10), pixel(74));
|
||||
}
|
||||
|
||||
/// `file.changeMesh` swaps the mesh under a baked project: the high poly and the skew map stay,
|
||||
/// the project counts as changed, and image resources are decoded in the new session.
|
||||
#[test]
|
||||
fn changing_the_mesh_keeps_the_bake_setup_and_marks_the_project_changed() {
|
||||
let mut s = plane_session();
|
||||
let plane = s.mesh.as_ref().clone();
|
||||
let high = temp_file("change_high.obj", &obj(&plane, 0.002, f32::MAX, [1.0; 3]));
|
||||
execute(&mut s, "bake.highPoly.add", &json!({ "path": high })).unwrap();
|
||||
execute(&mut s, "bake.skew.set", &json!({ "value": 1.0 })).unwrap();
|
||||
// 1x1 PNG as an image resource.
|
||||
let png = [
|
||||
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08,
|
||||
0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xf8, 0xcf, 0xc0, 0xf0, 0x1f, 0x00,
|
||||
0x05, 0x00, 0x01, 0xff, 0x89, 0x99, 0x3d, 0x1d, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
|
||||
];
|
||||
s.import_resource_bytes("dot.png", png.to_vec()).unwrap();
|
||||
s.modified = false;
|
||||
let mesh_id = s.mesh_id;
|
||||
|
||||
let mut low = String::new();
|
||||
for p in &plane.positions {
|
||||
low += &format!("v {} {} {}\n", p.x, p.y, p.z);
|
||||
}
|
||||
for uv in &plane.uvs {
|
||||
low += &format!("vt {} {}\n", uv.x, 1.0 - uv.y);
|
||||
}
|
||||
for t in plane.indices.as_chunks::<3>().0 {
|
||||
low += &format!("f {a}/{a} {b}/{b} {c}/{c}\n", a = t[0] + 1, b = t[1] + 1, c = t[2] + 1);
|
||||
}
|
||||
let low = temp_file("change_low.obj", &low);
|
||||
execute(&mut s, "file.changeMesh", &json!({ "path": low })).unwrap();
|
||||
|
||||
assert_ne!(s.mesh_id, mesh_id, "the session is on a new mesh");
|
||||
assert_eq!(s.bake_meshes.high.len(), 1, "the high poly stays");
|
||||
assert!(s.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_engine::core::BakePaintTarget::Skew), "the skew map stays");
|
||||
assert!(s.modified, "the project differs from the saved one");
|
||||
assert_eq!(s.images.len(), 1, "image resources are decoded in the new session");
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
//! What bake mode lists before a bake: overlapping UVs and parts "By Mesh Name" leaves unpaired
|
||||
|
||||
use texturecraft_engine::Session;
|
||||
use texturecraft_engine::bake::NamePair;
|
||||
use texturecraft_engine::core::MeshMatchMode;
|
||||
|
||||
/// Two quads side by side; `shared_uvs` lays both on the same UV square instead of side by side in UV space
|
||||
fn two_quads(shared_uvs: bool) -> Session {
|
||||
let second_u = if shared_uvs { 0.0 } else { 0.5 };
|
||||
let obj = format!(
|
||||
"o Box_low\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 0.5 0\nvt 0.5 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n\
|
||||
o Lone_low\nv 2 0 0\nv 3 0 0\nv 3 1 0\nv 2 1 0\nvt {second_u} 0\nvt {} 0\nvt {} 1\nvt {second_u} 1\nf 5/5 6/6 7/7 8/8\n",
|
||||
second_u + 0.5,
|
||||
second_u + 0.5
|
||||
);
|
||||
Session::from_mesh_bytes("quads.obj", obj.as_bytes(), 128, "quads").unwrap()
|
||||
}
|
||||
|
||||
const HIGH_POLY: &[u8] = b"o Box_high\nv 0 0 0.01\nv 1 0 0.01\nv 0 1 0.01\nf 1 2 3\no Extra_high\nv 2 0 0.01\nv 3 0 0.01\nv 2 1 0.01\nf 4 5 6\n";
|
||||
|
||||
#[test]
|
||||
fn overlapping_uvs_are_measured_before_the_bake() {
|
||||
assert!(two_quads(true).bake_uv_overlap(0).unwrap() > 0.4, "the second quad covers the first one's UVs");
|
||||
assert_eq!(two_quads(false).bake_uv_overlap(0).unwrap(), 0.0, "side by side in UV space nothing overlaps");
|
||||
const MISSING_TEXTURE_SET: usize = 9;
|
||||
assert!(two_quads(false).bake_uv_overlap(MISSING_TEXTURE_SET).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlap_in_a_uv_tile_left_out_of_the_bake_is_not_counted() {
|
||||
// One quad in tile 1001, two on the same UVs in tile 1002
|
||||
let obj = "o First\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 0.5 0\nvt 0.5 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n\
|
||||
o Second\nv 2 0 0\nv 3 0 0\nv 3 1 0\nv 2 1 0\nvt 1 0\nvt 1.5 0\nvt 1.5 1\nvt 1 1\nf 5/5 6/6 7/7 8/8\n\
|
||||
o Third\nv 4 0 0\nv 5 0 0\nv 5 1 0\nv 4 1 0\nvt 1 0\nvt 1.5 0\nvt 1.5 1\nvt 1 1\nf 9/9 10/10 11/11 12/12\n";
|
||||
let mut session = Session::from_mesh_bytes("tiles.obj", obj.as_bytes(), 128, "tiles").unwrap();
|
||||
assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1002]);
|
||||
assert!(session.bake_uv_overlap(0).unwrap() > 0.4, "the last two quads share tile 1002's UVs");
|
||||
|
||||
session.doc.project.texture_sets[0].bake_excluded_tiles.insert(1002);
|
||||
assert_eq!(session.bake_uv_overlap(0).unwrap(), 0.0, "tile 1001 alone has no overlap");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlap_is_measured_at_the_same_detail_in_every_uv_tile() {
|
||||
// Tiles 1001 and 1010 make a grid ten tiles wide; 512 texels across all ten would give each tile about 51
|
||||
const TEXELS_PER_TILE: f32 = 512.0;
|
||||
const SLIVER_TEXELS: f32 = 4.0;
|
||||
|
||||
// Inside tile 1010 (column 9), clear of the wide raster's texel centres
|
||||
const SLIVER_LEFT_U: f32 = 9.1;
|
||||
let (left, right) = (SLIVER_LEFT_U, SLIVER_LEFT_U + SLIVER_TEXELS / TEXELS_PER_TILE);
|
||||
let sliver = |name: &str, first: u32, x: f32| {
|
||||
let (second, third, fourth) = (first + 1, first + 2, first + 3);
|
||||
let corners = format!("v {x} 0 0\nv {} 0 0\nv {} 1 0\nv {x} 1 0\n", x + 1.0, x + 1.0);
|
||||
format!(
|
||||
"o {name}\n{corners}vt {left} 0\nvt {right} 0\nvt {right} 1\nvt {left} 1\nf {first}/{first} {second}/{second} {third}/{third} {fourth}/{fourth}\n"
|
||||
)
|
||||
};
|
||||
let corner = "o Corner\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 0.5 0\nvt 0.5 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n";
|
||||
let obj = [corner.to_owned(), sliver("First", 5, 2.0), sliver("Second", 9, 4.0)].concat();
|
||||
let session = Session::from_mesh_bytes("wide.obj", obj.as_bytes(), 128, "wide").unwrap();
|
||||
assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1010]);
|
||||
|
||||
assert!(session.bake_uv_overlap(0).unwrap() > 0.0, "two slivers a few texels wide overlap in tile 1010");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_triangle_across_a_uv_tile_border_counts_in_both_tiles() {
|
||||
// Two quads on the same UVs, from u 0.9 in tile 1001 to u 1.1 in tile 1002
|
||||
let obj = "o First\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0.9 0\nvt 1.1 0\nvt 1.1 1\nvt 0.9 1\nf 1/1 2/2 3/3 4/4\n\
|
||||
o Second\nv 2 0 0\nv 3 0 0\nv 3 1 0\nv 2 1 0\nvt 0.9 0\nvt 1.1 0\nvt 1.1 1\nvt 0.9 1\nf 5/5 6/6 7/7 8/8\n";
|
||||
let mut session = Session::from_mesh_bytes("border.obj", obj.as_bytes(), 128, "border").unwrap();
|
||||
assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1002]);
|
||||
|
||||
for (excluded, kept) in [(1002, 1001), (1001, 1002)] {
|
||||
let excluded_tiles = &mut session.doc.project.texture_sets[0].bake_excluded_tiles;
|
||||
excluded_tiles.clear();
|
||||
excluded_tiles.insert(excluded);
|
||||
assert!(session.bake_uv_overlap(0).unwrap() > 0.4, "tile {kept} holds part of the overlap");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unpaired_parts_are_listed_only_when_matching_by_name() {
|
||||
let mut session = two_quads(false);
|
||||
assert_eq!(session.bake_name_pairs(0).unwrap(), None, "no high poly");
|
||||
session.add_high_poly_bytes("high.obj", HIGH_POLY.to_vec()).unwrap();
|
||||
assert_eq!(session.bake_name_pairs(0).unwrap(), None, "\"Always\" pairs every part");
|
||||
|
||||
session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName;
|
||||
let pairs = session.bake_name_pairs(0).unwrap().unwrap();
|
||||
let unpaired: Vec<&NamePair> = pairs.iter().filter(|pair| pair.unpaired()).collect();
|
||||
assert_eq!(unpaired, [&NamePair { low: Some("Lone_low".into()), high: None }, &NamePair { low: None, high: Some("Extra_high".into()) }], "{pairs:?}");
|
||||
assert!(pairs.contains(&NamePair { low: Some("Box_low".into()), high: Some("Box_high".into()) }));
|
||||
|
||||
session.doc.project.texture_sets[0].bake.high_poly.use_low_as_high = true;
|
||||
assert_eq!(session.bake_name_pairs(0).unwrap(), None, "the low poly as its own high poly pairs every part");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_set_matching_always_bakes_from_every_high_poly_part() {
|
||||
let obj = "o Box_low\nusemtl Body\nv 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n\
|
||||
o Lid_low\nusemtl Lid\nv 2 0 0\nv 3 0 0\nv 2 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 4/4 5/5 6/6\n";
|
||||
let mut session = Session::from_mesh_bytes("sets.obj", obj.as_bytes(), 128, "sets").unwrap();
|
||||
session.add_high_poly_bytes("high.obj", HIGH_POLY.to_vec()).unwrap();
|
||||
let both = [0, 1];
|
||||
session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName;
|
||||
assert_eq!(session.bake_unpaired_high_parts(&both).unwrap(), Vec::<String>::new(), "the other set matches \"Always\"");
|
||||
|
||||
session.doc.project.texture_sets[1].bake.high_poly.match_mode = MeshMatchMode::ByMeshName;
|
||||
assert_eq!(session.bake_unpaired_high_parts(&both).unwrap(), ["Extra_high"]);
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//! Generator inputs that read an anchor point or an image, through engine commands.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
use texturecraft_engine::core::{BakedMap, Channel, EffectKind, Source};
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, execute};
|
||||
|
||||
/// The texture set's texels per side.
|
||||
const RESOLUTION: u32 = 256;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap();
|
||||
session.viewport = texturecraft_engine::geom::glam::Vec2::new(400.0, 400.0);
|
||||
session.camera.yaw = 0.0;
|
||||
session.camera.pitch = 0.0;
|
||||
session.update();
|
||||
session
|
||||
}
|
||||
|
||||
/// Composited value of `channel` under the viewport center.
|
||||
fn center(session: &mut Session, channel: Channel) -> [f32; 3] {
|
||||
session.update();
|
||||
let hit = session.pick(session.viewport * 0.5, session.viewport).unwrap();
|
||||
let texels = RESOLUTION as f32;
|
||||
session.caches[0].composite.value(channel, (hit.uv.x * texels) as u32, (hit.uv.y * texels) as u32)
|
||||
}
|
||||
|
||||
fn id(value: Value, key: &str) -> u64 {
|
||||
value[key].as_u64().unwrap()
|
||||
}
|
||||
|
||||
/// A low fill (height 0.8) with an anchor, then a white fill whose black mask holds an AO generator reading it: (anchor, low layer, generator).
|
||||
fn anchored_generator(session: &mut Session) -> (u64, u64, u64) {
|
||||
let low = id(execute(session, "layer.add.fill", &json!({"height": 0.8})).unwrap(), "layer");
|
||||
let anchor = id(execute(session, "effect.add.anchor", &json!({"name": "Height"})).unwrap(), "effect");
|
||||
execute(session, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap();
|
||||
execute(session, "mask.add.black", &Value::Null).unwrap();
|
||||
let generator = id(execute(session, "effect.add.generator", &json!({"generator": "ambientOcclusion", "level": 0.5, "softness": 0.5})).unwrap(), "effect");
|
||||
execute(session, "effect.set", &json!({"effect": generator, "input": "ambientOcclusion", "inputAnchor": anchor, "anchorChannel": "height"})).unwrap();
|
||||
(anchor, low, generator)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generator_input_reads_the_anchor_points_value() {
|
||||
let mut session = session();
|
||||
anchored_generator(&mut session);
|
||||
|
||||
// The low fill's gray, then white through the mask: an occlusion of 0.8 masks most of it, the channel default (0) none
|
||||
let base = center(&mut session, Channel::BaseColor)[0];
|
||||
assert!(base > 0.9, "the generator reads the anchor's height, not the default: {base}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generator_reading_an_anchor_cannot_be_pasted_below_it() {
|
||||
let mut session = session();
|
||||
let (_, low, generator) = anchored_generator(&mut session);
|
||||
execute(&mut session, "effect.copy", &json!({"effect": generator})).unwrap();
|
||||
|
||||
let pasted = execute(&mut session, "effect.paste", &json!({"layer": low, "target": "mask"}));
|
||||
assert!(pasted.is_err(), "the anchor point is on that layer, not below it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_unused_resources_keeps_an_image_read_by_a_generator_input() {
|
||||
let mut session = session();
|
||||
let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 128, 255]));
|
||||
let mut bytes = Vec::new();
|
||||
image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
|
||||
let name = session.import_resource_bytes("occlusion.png", bytes).unwrap();
|
||||
execute(&mut session, "layer.add.fill", &Value::Null).unwrap();
|
||||
execute(&mut session, "mask.add.black", &Value::Null).unwrap();
|
||||
let generator = id(execute(&mut session, "effect.add.generator", &json!({"generator": "dirt"})).unwrap(), "effect");
|
||||
execute(&mut session, "effect.set", &json!({"effect": generator, "input": "ambientOcclusion", "inputImage": name})).unwrap();
|
||||
|
||||
execute(&mut session, "file.removeUnused", &Value::Null).unwrap();
|
||||
assert!(session.doc.resources.contains_key(&name), "the image is still read by the generator input");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_unused_resources_keeps_an_image_read_by_a_content_effect() {
|
||||
let mut session = session();
|
||||
let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 128, 255]));
|
||||
let mut bytes = Vec::new();
|
||||
image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
|
||||
let name = session.import_resource_bytes("content.png", bytes).unwrap();
|
||||
execute(&mut session, "layer.add.fill", &Value::Null).unwrap();
|
||||
let effect = id(execute(&mut session, "effect.add.fill", &json!({"target": "content"})).unwrap(), "effect");
|
||||
execute(&mut session, "layer.fill.set", &json!({"effect": effect, "channel": "baseColor", "image": name})).unwrap();
|
||||
|
||||
execute(&mut session, "file.removeUnused", &Value::Null).unwrap();
|
||||
|
||||
assert!(session.doc.resources.contains_key(&name), "the content effect still reads the image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generator_input_rejects_a_resource_that_is_not_an_image() {
|
||||
let mut session = session();
|
||||
session.doc.resources.insert("linked.mcmat".into(), Arc::new(vec![1, 2, 3]));
|
||||
execute(&mut session, "layer.add.fill", &Value::Null).unwrap();
|
||||
execute(&mut session, "mask.add.black", &Value::Null).unwrap();
|
||||
let generator = id(execute(&mut session, "effect.add.generator", &json!({"generator": "dirt"})).unwrap(), "effect");
|
||||
|
||||
let result = execute(&mut session, "effect.set", &json!({"effect": generator, "input": "ambientOcclusion", "inputImage": "linked.mcmat"}));
|
||||
|
||||
assert!(result.is_err(), "a package resource has no image pixels for the generator to sample");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn importing_a_missing_generator_input_invalidates_the_composite() {
|
||||
let mut session = session();
|
||||
execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap();
|
||||
execute(&mut session, "mask.add.black", &Value::Null).unwrap();
|
||||
let effect = id(execute(&mut session, "effect.add.generator", &json!({"generator": "ambientOcclusion"})).unwrap(), "effect");
|
||||
session
|
||||
.edit("Reference an absent image", |session| {
|
||||
let effect = session.doc.project.effect_mut(texturecraft_engine::core::LayerId(effect)).unwrap();
|
||||
let EffectKind::Generator(generator) = &mut effect.kind else { panic!("expected generator") };
|
||||
generator.inputs.insert(BakedMap::AmbientOcclusion, Source::image("later.png"));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = center(&mut session, Channel::BaseColor)[0];
|
||||
|
||||
let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 0, 0, 255]));
|
||||
let mut bytes = Vec::new();
|
||||
image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
|
||||
session.import_resource_bytes("later.png", bytes).unwrap();
|
||||
let after = center(&mut session, Channel::BaseColor)[0];
|
||||
|
||||
assert!((after - before).abs() > 0.2, "the new image must update the generator's composited mask: {before} -> {after}");
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use texturecraft_engine::bake::{HighPolyReach, RayStart, VertexReach, high_poly_missed};
|
||||
use texturecraft_engine::bake::{HIDDEN_HIGH_POLY_VERTEX, HighPolyReach, RayStart, VertexReach, high_poly_missed};
|
||||
use texturecraft_engine::geom::glam::Vec3;
|
||||
|
||||
fn vertex(height: f32) -> Option<VertexReach> {
|
||||
@@ -30,12 +30,13 @@ fn each_owning_set_uses_its_own_frontal_and_rear_distances() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_set_filter_leaves_other_sets_unmarked() {
|
||||
fn selected_set_filter_hides_other_sets_vertices() {
|
||||
const H: f32 = HIDDEN_HIGH_POLY_VERTEX;
|
||||
let reaches = sets();
|
||||
assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(1), 6), vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
|
||||
assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(2), 6), vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
|
||||
assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(1), 6), vec![1.0, 0.0, H, H, H, H]);
|
||||
assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(2), 6), vec![H, H, 0.0, 1.0, H, H]);
|
||||
for only_set in [0, reaches.len(), usize::MAX] {
|
||||
assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(only_set), 6), vec![0.0; 6]);
|
||||
assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(only_set), 6), vec![H; 6], "a set without a reach shows none of the high poly");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! Keep feature tests in their own modules; the standalone session.rs target remains available.
|
||||
|
||||
mod bake;
|
||||
mod bake_checks;
|
||||
mod bake_resolution;
|
||||
mod bake_settings;
|
||||
mod bake_tiles;
|
||||
@@ -10,6 +11,7 @@ mod content_effects;
|
||||
mod export_colour_space;
|
||||
mod filter_swap;
|
||||
mod filters;
|
||||
mod generator_inputs;
|
||||
mod high_poly_missed;
|
||||
mod instances;
|
||||
mod materialcraft_link;
|
||||
@@ -24,6 +26,7 @@ mod polygon_fill;
|
||||
mod project_recovery;
|
||||
mod sample;
|
||||
mod thumbs;
|
||||
mod tool_availability;
|
||||
mod tools;
|
||||
mod udim;
|
||||
mod uv_strokes;
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
//! Which tools can act on each selection, and that every usable tool acts there in both views
|
||||
|
||||
mod selection;
|
||||
|
||||
use selection::Selection;
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{Effect, EffectKind, LayerId};
|
||||
use texturecraft_engine::geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_engine::{Session, StackTarget, Tool, execute};
|
||||
|
||||
/// Two triangles side by side, each a mesh part with its own corner of the UV square
|
||||
const PARTS_OBJ: &str = "o Lid\nv 0 0 0\nv 2 0 0\nv 0 2 0\nvt 0 0\nvt 0.5 0\nvt 0 0.5\nf 1/1 2/2 3/3\n\
|
||||
o Body\nv 2 2 0\nv 4 2 0\nv 2 4 0\nvt 0.5 0.5\nvt 1 0.5\nvt 0.5 1\nf 4/4 5/5 6/6\n";
|
||||
|
||||
const VIEWPORT_PIXELS: f32 = 400.0;
|
||||
|
||||
fn stencil_png() -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
let green = image::RgbaImage::from_fn(8, 8, |_, _| image::Rgba([0, 255, 0, 255]));
|
||||
green.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
fn base_session() -> Session {
|
||||
let mut session = Session::from_mesh_bytes("parts.obj", PARTS_OBJ.as_bytes(), 256, "parts").unwrap();
|
||||
session.viewport = Vec2::splat(VIEWPORT_PIXELS);
|
||||
(session.camera.yaw, session.camera.pitch) = (0.0, 0.0);
|
||||
let (low, high) = session.mesh.bounds();
|
||||
session.camera.frame(low, high);
|
||||
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})).unwrap();
|
||||
let stencil = session.import_resource_bytes("stencil.png", stencil_png()).unwrap();
|
||||
execute(&mut session, "tool.stencil", &json!({"image": stencil})).unwrap();
|
||||
session
|
||||
}
|
||||
|
||||
fn screen(session: &Session, point: [f32; 3]) -> Vec2 {
|
||||
let ndc = session.camera.project(Vec3::from(point), 1.0).unwrap();
|
||||
Vec2::new((ndc.x + 1.0) * VIEWPORT_PIXELS / 2.0, (1.0 - ndc.y) * VIEWPORT_PIXELS / 2.0)
|
||||
}
|
||||
|
||||
fn add_layer(session: &mut Session, command: &str) -> u64 {
|
||||
execute(session, command, &json!({})).unwrap()["layer"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
fn select(session: &mut Session, layer: u64, target: Value) {
|
||||
execute(session, "layer.select", &json!({"layer": layer, "target": target})).unwrap();
|
||||
}
|
||||
|
||||
fn select_nothing(session: &mut Session) {
|
||||
let set = session.ts();
|
||||
session.selected.remove(&set);
|
||||
session.target = StackTarget::Content;
|
||||
}
|
||||
|
||||
/// Adds an effect with `command` to the layer's content or mask and selects it
|
||||
fn select_new_effect(session: &mut Session, layer: u64, mask: bool, command: &str, effect_params: Value) {
|
||||
if mask {
|
||||
execute(session, "mask.add.black", &json!({"layer": layer})).unwrap();
|
||||
}
|
||||
|
||||
let target = if mask { "mask" } else { "content" };
|
||||
let mut params = effect_params;
|
||||
params["layer"] = json!(layer);
|
||||
params["target"] = json!(target);
|
||||
execute(session, command, ¶ms).unwrap();
|
||||
|
||||
let owner = session.doc.project.layer(LayerId(layer)).unwrap();
|
||||
let effects = if mask { &owner.mask.as_ref().unwrap().effects } else { &owner.content_effects };
|
||||
let effect = effects.last().unwrap().id.0;
|
||||
select(session, layer, json!(effect));
|
||||
}
|
||||
|
||||
fn select_new_mask(session: &mut Session, layer: u64) {
|
||||
execute(session, "mask.add.black", &json!({"layer": layer})).unwrap();
|
||||
select(session, layer, json!("mask"));
|
||||
}
|
||||
|
||||
fn session_with(selection: Selection) -> Session {
|
||||
let mut session = base_session();
|
||||
match selection {
|
||||
Selection::PaintContent => {
|
||||
let layer = add_layer(&mut session, "layer.add.paint");
|
||||
select(&mut session, layer, json!("content"));
|
||||
}
|
||||
Selection::FillContent => {
|
||||
let layer = add_layer(&mut session, "layer.add.fill");
|
||||
select(&mut session, layer, json!("content"));
|
||||
}
|
||||
Selection::PaintMask => {
|
||||
let layer = add_layer(&mut session, "layer.add.paint");
|
||||
select_new_mask(&mut session, layer);
|
||||
}
|
||||
Selection::FillMask => {
|
||||
let layer = add_layer(&mut session, "layer.add.fill");
|
||||
select_new_mask(&mut session, layer);
|
||||
}
|
||||
Selection::FolderMask => {
|
||||
let folder = add_layer(&mut session, "layer.add.group");
|
||||
select_new_mask(&mut session, folder);
|
||||
}
|
||||
Selection::InstanceOwnMask => {
|
||||
let source = add_layer(&mut session, "layer.add.paint");
|
||||
let instance = execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap()["layer"].as_u64().unwrap();
|
||||
select_new_mask(&mut session, instance);
|
||||
}
|
||||
Selection::PaintSublayer => {
|
||||
let layer = add_layer(&mut session, "layer.add.paint");
|
||||
select_new_effect(&mut session, layer, false, "effect.add.paint", json!({}));
|
||||
}
|
||||
Selection::PaintSublayerInMask => {
|
||||
let layer = add_layer(&mut session, "layer.add.paint");
|
||||
select_new_effect(&mut session, layer, true, "effect.add.paint", json!({}));
|
||||
}
|
||||
Selection::PaintSublayerInFill => {
|
||||
let layer = add_layer(&mut session, "layer.add.fill");
|
||||
select_new_effect(&mut session, layer, false, "effect.add.paint", json!({}));
|
||||
}
|
||||
Selection::PathSublayer => {
|
||||
let layer = add_layer(&mut session, "layer.add.paint");
|
||||
select(&mut session, layer, json!("content"));
|
||||
let (start, end) = (screen(&session, [0.2, 0.2, 0.0]), screen(&session, [1.0, 0.4, 0.0]));
|
||||
execute(&mut session, "tool.path", &json!({"points": [[start.x, start.y], [end.x, end.y]]})).unwrap();
|
||||
execute(&mut session, "tool.path", &json!({"commit": true})).unwrap();
|
||||
let path = session.doc.project.layer(LayerId(layer)).unwrap().content_effects.last().unwrap().id.0;
|
||||
select(&mut session, layer, json!(path));
|
||||
}
|
||||
Selection::FilterInPaint | Selection::FilterInFill | Selection::FilterInMask => {
|
||||
let command = if selection == Selection::FilterInFill { "layer.add.fill" } else { "layer.add.paint" };
|
||||
let layer = add_layer(&mut session, command);
|
||||
select_new_effect(&mut session, layer, selection == Selection::FilterInMask, "effect.add.filter", json!({"filter": "invert"}));
|
||||
}
|
||||
Selection::FillEffectInPaint => {
|
||||
let layer = add_layer(&mut session, "layer.add.paint");
|
||||
select_new_effect(&mut session, layer, false, "effect.add.fill", json!({}));
|
||||
}
|
||||
Selection::GeneratorInFillMask => {
|
||||
let layer = add_layer(&mut session, "layer.add.fill");
|
||||
select_new_effect(&mut session, layer, true, "effect.add.generator", json!({}));
|
||||
}
|
||||
Selection::FolderContent => {
|
||||
let folder = add_layer(&mut session, "layer.add.group");
|
||||
select(&mut session, folder, json!("content"));
|
||||
}
|
||||
Selection::InstanceOfPaint | Selection::InstanceOfFill => {
|
||||
let command = if selection == Selection::InstanceOfFill { "layer.add.fill" } else { "layer.add.paint" };
|
||||
let source = add_layer(&mut session, command);
|
||||
let instance = execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap()["layer"].as_u64().unwrap();
|
||||
select(&mut session, instance, json!("content"));
|
||||
}
|
||||
Selection::Nothing => select_nothing(&mut session),
|
||||
Selection::QuickMaskOverPaint | Selection::QuickMaskOverFill => {
|
||||
let command = if selection == Selection::QuickMaskOverFill { "layer.add.fill" } else { "layer.add.paint" };
|
||||
let layer = add_layer(&mut session, command);
|
||||
select(&mut session, layer, json!("content"));
|
||||
execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap();
|
||||
execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap();
|
||||
}
|
||||
Selection::QuickMaskOverNothing => {
|
||||
select_nothing(&mut session);
|
||||
execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap();
|
||||
execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
session
|
||||
}
|
||||
|
||||
/// Uses `tool` once the way the viewport does: a stroke, a click or a committed path
|
||||
fn use_tool(session: &mut Session, tool: Tool, in_2d_view: bool) -> texturecraft_engine::Result<()> {
|
||||
session.tool.tool = tool;
|
||||
if tool == Tool::Clone {
|
||||
let source = screen(session, [1.2, 0.3, 0.0]);
|
||||
execute(session, "tool.cloneSource", &json!({"x": source.x, "y": source.y}))?;
|
||||
}
|
||||
|
||||
let points = [screen(session, [0.3, 0.3, 0.0]), screen(session, [0.6, 0.4, 0.0]), screen(session, [0.9, 0.5, 0.0])];
|
||||
let uv_points = [Vec2::new(0.05, 0.95), Vec2::new(0.1, 0.92), Vec2::new(0.15, 0.9)];
|
||||
if tool == Tool::Path {
|
||||
let params = if in_2d_view {
|
||||
json!({"uvPoints": uv_points.iter().map(|uv| [uv.x, uv.y]).collect::<Vec<_>>()})
|
||||
} else {
|
||||
json!({"points": points.iter().map(|point| [point.x, point.y]).collect::<Vec<_>>()})
|
||||
};
|
||||
execute(session, "tool.path", ¶ms)?;
|
||||
execute(session, "tool.path", &json!({"commit": true}))?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let single_click = matches!(tool, Tool::PolygonFill | Tool::ColorPicker | Tool::GeometryMask);
|
||||
let viewport = session.viewport;
|
||||
if in_2d_view {
|
||||
session.begin_stroke_uv(uv_points[0], 1.0)?;
|
||||
} else {
|
||||
session.begin_stroke(points[0], viewport, 1.0)?;
|
||||
}
|
||||
|
||||
if single_click {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for (point, uv) in points.iter().zip(&uv_points).skip(1) {
|
||||
if in_2d_view {
|
||||
session.continue_stroke_uv(*uv, 1.0);
|
||||
} else {
|
||||
session.continue_stroke(*point, 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
session.end_stroke()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_selection_offers_the_tools_that_can_act_on_it() {
|
||||
let mut wrong = Vec::new();
|
||||
for selection in Selection::ALL {
|
||||
let session = session_with(selection);
|
||||
for tool in Tool::ALL {
|
||||
let usable = session.tool_usable(tool);
|
||||
if usable != selection.offers(tool) {
|
||||
wrong.push(format!("{selection:?} {tool:?}: usable {usable}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_usable_tool_acts_in_both_views() {
|
||||
let mut wrong = Vec::new();
|
||||
for in_2d_view in [false, true] {
|
||||
for selection in Selection::ALL {
|
||||
for tool in Tool::ALL {
|
||||
// The picker and the geometry mask read the 3D view only, whatever is selected
|
||||
if in_2d_view && matches!(tool, Tool::ColorPicker | Tool::GeometryMask) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut session = session_with(selection);
|
||||
let usable = session.tool_usable(tool);
|
||||
|
||||
let result = use_tool(&mut session, tool, in_2d_view);
|
||||
|
||||
let view = if in_2d_view { "2D" } else { "3D" };
|
||||
match result {
|
||||
Err(error) if usable => wrong.push(format!("{view} {selection:?} {tool:?}: usable but {error}")),
|
||||
Ok(()) if !usable && !selection.scripts_still_paint() => wrong.push(format!("{view} {selection:?} {tool:?}: greyed but acts")),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
fn commit_path(session: &mut Session) -> texturecraft_engine::Result<Value> {
|
||||
execute(session, "tool.path", &json!({"uvPoints": [[0.05, 0.95], [0.15, 0.9]], "commit": true}))
|
||||
}
|
||||
|
||||
fn path_count(session: &Session, path_sublayer: LayerId) -> usize {
|
||||
match session.doc.project.effect(path_sublayer).map(|(_, effect)| &effect.kind) {
|
||||
Some(EffectKind::Path(paths)) => paths.len(),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_are_refused_on_fill_layers_and_the_quick_mask_but_saved_ones_stay_editable() {
|
||||
let mut session = session_with(Selection::FillContent);
|
||||
let fill = session.selected_layer().unwrap();
|
||||
|
||||
assert!(commit_path(&mut session).is_err(), "no new paths in a fill layer");
|
||||
assert!(session.doc.project.layer(fill).unwrap().content_effects.is_empty());
|
||||
|
||||
let mut session = session_with(Selection::QuickMaskOverPaint);
|
||||
assert!(commit_path(&mut session).is_err(), "paths can't edit the quick mask");
|
||||
|
||||
// A project saved while paths could go into fill layers
|
||||
let mut session = session_with(Selection::FillContent);
|
||||
let fill = session.selected_layer().unwrap();
|
||||
let saved_path = session.doc.project.alloc_id();
|
||||
session.doc.project.layer_mut(fill).unwrap().content_effects.push(Effect::new(saved_path, EffectKind::Path(Vec::new())));
|
||||
select(&mut session, fill.0, json!(saved_path.0));
|
||||
|
||||
assert!(session.tool_usable(Tool::Path));
|
||||
|
||||
commit_path(&mut session).unwrap();
|
||||
|
||||
assert_eq!(path_count(&session, saved_path), 1, "the saved path sublayer takes the new path");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quick_mask_edit_and_invert_need_the_mask_on() {
|
||||
let mut session = base_session();
|
||||
|
||||
assert!(execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).is_err());
|
||||
assert!(execute(&mut session, "viewport.quickMask.invert", &json!({})).is_err());
|
||||
|
||||
execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap();
|
||||
execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap();
|
||||
execute(&mut session, "viewport.quickMask", &json!({"enabled": false})).unwrap();
|
||||
|
||||
assert!(!session.quick_mask.editing, "turning the mask off stops editing it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_path_cannot_be_committed_while_editing_the_quick_mask() {
|
||||
let mut session = session_with(Selection::PaintContent);
|
||||
commit_path(&mut session).unwrap();
|
||||
let StackTarget::Effect(path_sublayer) = session.target else { panic!("the committed path is not selected") };
|
||||
|
||||
let points_before = match session.doc.project.effect(path_sublayer).map(|(_, effect)| &effect.kind) {
|
||||
Some(EffectKind::Path(paths)) => paths[0].points.clone(),
|
||||
_ => panic!("the committed path is missing"),
|
||||
};
|
||||
|
||||
execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap();
|
||||
execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap();
|
||||
execute(&mut session, "path.edit", &json!({"effect": path_sublayer.0, "index": 0})).unwrap();
|
||||
assert!(!session.tool_usable(Tool::Path));
|
||||
|
||||
execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.8], [0.3, 0.7]]})).unwrap();
|
||||
assert!(!session.path_live().unwrap(), "live preview must leave the stored path alone");
|
||||
let result = execute(&mut session, "tool.path", &json!({"commit": true}));
|
||||
assert!(result.is_err(), "a greyed Path tool must not commit a stored path into the quick mask edit state");
|
||||
|
||||
let points_after = match session.doc.project.effect(path_sublayer).map(|(_, effect)| &effect.kind) {
|
||||
Some(EffectKind::Path(paths)) => paths[0].points.clone(),
|
||||
_ => panic!("the stored path is missing"),
|
||||
};
|
||||
assert_eq!(points_after, points_before);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//! Selection cases for the tool availability tests
|
||||
|
||||
use texturecraft_engine::Tool;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum Selection {
|
||||
PaintContent,
|
||||
FillContent,
|
||||
PaintMask,
|
||||
FillMask,
|
||||
FolderMask,
|
||||
InstanceOwnMask,
|
||||
PaintSublayer,
|
||||
PaintSublayerInMask,
|
||||
PaintSublayerInFill,
|
||||
PathSublayer,
|
||||
FilterInPaint,
|
||||
FilterInFill,
|
||||
FilterInMask,
|
||||
FillEffectInPaint,
|
||||
GeneratorInFillMask,
|
||||
FolderContent,
|
||||
InstanceOfPaint,
|
||||
InstanceOfFill,
|
||||
Nothing,
|
||||
QuickMaskOverPaint,
|
||||
QuickMaskOverFill,
|
||||
QuickMaskOverNothing,
|
||||
}
|
||||
|
||||
impl Selection {
|
||||
pub(super) const ALL: [Selection; 22] = [
|
||||
Selection::PaintContent,
|
||||
Selection::FillContent,
|
||||
Selection::PaintMask,
|
||||
Selection::FillMask,
|
||||
Selection::FolderMask,
|
||||
Selection::InstanceOwnMask,
|
||||
Selection::PaintSublayer,
|
||||
Selection::PaintSublayerInMask,
|
||||
Selection::PaintSublayerInFill,
|
||||
Selection::PathSublayer,
|
||||
Selection::FilterInPaint,
|
||||
Selection::FilterInFill,
|
||||
Selection::FilterInMask,
|
||||
Selection::FillEffectInPaint,
|
||||
Selection::GeneratorInFillMask,
|
||||
Selection::FolderContent,
|
||||
Selection::InstanceOfPaint,
|
||||
Selection::InstanceOfFill,
|
||||
Selection::Nothing,
|
||||
Selection::QuickMaskOverPaint,
|
||||
Selection::QuickMaskOverFill,
|
||||
Selection::QuickMaskOverNothing,
|
||||
];
|
||||
|
||||
/// Whether the shelf offers `tool` for this selection
|
||||
pub(super) fn offers(self, tool: Tool) -> bool {
|
||||
let reads_content = matches!(tool, Tool::Smudge | Tool::Clone);
|
||||
match tool {
|
||||
Tool::ColorPicker => true,
|
||||
Tool::GeometryMask => !matches!(self, Selection::Nothing | Selection::QuickMaskOverNothing),
|
||||
_ => match self {
|
||||
Selection::PaintContent | Selection::PaintSublayer => true,
|
||||
Selection::PaintSublayerInFill => tool != Tool::Path,
|
||||
Selection::PaintMask | Selection::FillMask | Selection::FolderMask | Selection::InstanceOwnMask | Selection::PaintSublayerInMask => {
|
||||
!reads_content
|
||||
}
|
||||
Selection::PathSublayer => tool == Tool::Path,
|
||||
Selection::QuickMaskOverPaint | Selection::QuickMaskOverFill | Selection::QuickMaskOverNothing => tool != Tool::Path,
|
||||
_ => false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Greyed in the shelf, but scripts still paint here: below the effect, or the instance's source
|
||||
pub(super) fn scripts_still_paint(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Selection::FilterInPaint | Selection::FillEffectInPaint | Selection::FilterInMask | Selection::GeneratorInFillMask | Selection::InstanceOfPaint
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -153,32 +153,39 @@ fn library_alphas_shape_the_stamp() {
|
||||
|
||||
#[test]
|
||||
fn quick_mask_limits_painting() {
|
||||
let mut s = session();
|
||||
paint_red(&mut s, 20.0);
|
||||
let r = execute(&mut s, "viewport.quickMask.edit", &Value::Null).unwrap();
|
||||
assert_eq!(r["editing"], json!(true));
|
||||
assert_eq!(r["enabled"], json!(true), "editing enables the mask");
|
||||
let undo = s.history_labels().len();
|
||||
dab(&mut s, 150.0, 200.0);
|
||||
assert!(!red(color_at(&s, 150.0, 200.0)), "mask strokes do not paint the layer");
|
||||
assert_eq!(s.history_labels().len(), undo, "mask strokes stay out of the history");
|
||||
assert!(s.quick_mask_rgba(0, 64).is_some_and(|v| v.len() == 64 * 64 * 4));
|
||||
execute(&mut s, "viewport.quickMask.edit", &Value::Null).unwrap();
|
||||
let mut session = session();
|
||||
paint_red(&mut session, 20.0);
|
||||
execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap();
|
||||
|
||||
execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap();
|
||||
dab(&mut s, 150.0, 200.0);
|
||||
dab(&mut s, 250.0, 200.0);
|
||||
assert!(red(color_at(&s, 150.0, 200.0)), "inside the mask");
|
||||
assert!(!red(color_at(&s, 250.0, 200.0)), "outside the mask");
|
||||
let state = execute(&mut session, "viewport.quickMask.edit", &Value::Null).unwrap();
|
||||
let undo = session.history_labels().len();
|
||||
dab(&mut session, 150.0, 200.0);
|
||||
|
||||
execute(&mut s, "viewport.quickMask.invert", &Value::Null).unwrap();
|
||||
dab(&mut s, 250.0, 200.0);
|
||||
assert!(red(color_at(&s, 250.0, 200.0)), "inverted: outside is open");
|
||||
assert_eq!(state["editing"], json!(true));
|
||||
assert!(!red(color_at(&session, 150.0, 200.0)), "mask strokes do not paint the layer");
|
||||
assert_eq!(session.history_labels().len(), undo, "mask strokes stay out of the history");
|
||||
let overlay_size: u32 = 64;
|
||||
let rgba_bytes = (overlay_size * overlay_size * 4) as usize;
|
||||
assert!(session.quick_mask_rgba(0, overlay_size).is_some_and(|pixels| pixels.len() == rgba_bytes), "an RGBA8 overlay of the requested size");
|
||||
|
||||
execute(&mut s, "viewport.quickMask", &json!({"enabled": false})).unwrap();
|
||||
execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [0.0, 1.0, 0.0]})).unwrap();
|
||||
dab(&mut s, 150.0, 200.0);
|
||||
assert!(color_at(&s, 150.0, 200.0)[1] > 0.85, "disabled: everything is open");
|
||||
execute(&mut session, "viewport.quickMask.edit", &Value::Null).unwrap();
|
||||
execute(&mut session, "tool.brush", &json!({"size": 6})).unwrap();
|
||||
dab(&mut session, 150.0, 200.0);
|
||||
dab(&mut session, 250.0, 200.0);
|
||||
|
||||
assert!(red(color_at(&session, 150.0, 200.0)), "inside the mask");
|
||||
assert!(!red(color_at(&session, 250.0, 200.0)), "outside the mask");
|
||||
|
||||
execute(&mut session, "viewport.quickMask.invert", &Value::Null).unwrap();
|
||||
dab(&mut session, 250.0, 200.0);
|
||||
|
||||
assert!(red(color_at(&session, 250.0, 200.0)), "inverted: outside is open");
|
||||
|
||||
execute(&mut session, "viewport.quickMask", &json!({"enabled": false})).unwrap();
|
||||
execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [0.0, 1.0, 0.0]})).unwrap();
|
||||
dab(&mut session, 150.0, 200.0);
|
||||
|
||||
assert!(color_at(&session, 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)
|
||||
|
||||
@@ -586,6 +586,72 @@ fn curvature_generators_take_a_mode_and_detail_sizes() {
|
||||
assert_eq!(execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(), inspect, "failed commands leave the project unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generators_take_blur_balance_and_contrast() {
|
||||
let mut state = session();
|
||||
execute(&mut state, "layer.add.fill", &json!({})).unwrap();
|
||||
execute(&mut state, "mask.add.black", &Value::Null).unwrap();
|
||||
let added = execute(&mut state, "effect.add.generator", &json!({"generator": "dirt", "blur": 0.25})).unwrap();
|
||||
let effect = added["effect"].clone();
|
||||
|
||||
execute(&mut state, "effect.set", &json!({"effect": effect, "balance": 0.75, "contrast": 2.0})).unwrap();
|
||||
let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string();
|
||||
assert!(inspect.contains(r#""blur":0.25"#) && inspect.contains(r#""balance":0.75"#), "{inspect}");
|
||||
assert!(inspect.contains(r#""contrast":1.0"#), "contrast is clamped to 0..1: {inspect}");
|
||||
|
||||
execute(&mut state, "effect.set", &json!({"effect": effect, "resolution": "custom", "customResolution": 512, "resolutionFactor": -9})).unwrap();
|
||||
let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string();
|
||||
assert!(inspect.contains(r#""resolution":{"custom":512,"factor":-3,"mode":"Custom"}"#), "the factor is clamped to 1/8: {inspect}");
|
||||
assert!(execute(&mut state, "effect.set", &json!({"effect": effect, "resolution": "huge"})).is_err(), "unknown resolutions are rejected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generator_input_reads_a_uniform_value_or_its_mesh_map_again() {
|
||||
let mut state = session();
|
||||
execute(&mut state, "layer.add.fill", &json!({})).unwrap();
|
||||
execute(&mut state, "mask.add.black", &Value::Null).unwrap();
|
||||
let effect = execute(&mut state, "effect.add.generator", &json!({"generator": "dirt"})).unwrap()["effect"].clone();
|
||||
|
||||
execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputValue": 0.25})).unwrap();
|
||||
let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string();
|
||||
assert!(inspect.contains(r#""inputs":{"ambientOcclusion":{"uniform":[0.25,0.25,0.25]}}"#), "{inspect}");
|
||||
|
||||
let wrong_input = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "curvature", "inputValue": 0.5}));
|
||||
assert!(wrong_input.is_err(), "dirt reads ambient occlusion, not curvature");
|
||||
let missing_image = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputImage": "nothing.png"}));
|
||||
assert!(missing_image.is_err(), "the image must be a resource of the project");
|
||||
let two_sources = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputValue": 0.5, "inputBaked": true}));
|
||||
assert!(two_sources.is_err(), "an input takes one source");
|
||||
|
||||
execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputBaked": true})).unwrap();
|
||||
let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string();
|
||||
assert!(!inspect.contains(r#""inputs""#), "the mesh map is read again: {inspect}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_generator_kind_keeps_the_effect_identity_and_settings() {
|
||||
let mut state = session();
|
||||
execute(&mut state, "layer.add.fill", &json!({})).unwrap();
|
||||
execute(&mut state, "mask.add.black", &Value::Null).unwrap();
|
||||
let effect = execute(&mut state, "effect.add.generator", &json!({"generator": "dirt"})).unwrap()["effect"].as_u64().unwrap();
|
||||
execute(&mut state, "effect.set", &json!({"effect": effect, "name": "Keep me", "opacity": 0.4, "level": 0.2})).unwrap();
|
||||
execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputValue": 0.25})).unwrap();
|
||||
let later = execute(&mut state, "effect.add.generator", &json!({"generator": "position"})).unwrap()["effect"].as_u64().unwrap();
|
||||
|
||||
execute(&mut state, "effect.set", &json!({"effect": effect, "generator": "ambientOcclusion"})).unwrap();
|
||||
|
||||
let (owner, edited) = state.doc.project.effect(texturecraft_core::LayerId(effect)).unwrap();
|
||||
assert!(matches!(&edited.kind, texturecraft_core::EffectKind::Generator(generator)
|
||||
if generator.kind == texturecraft_core::GeneratorKind::AmbientOcclusion
|
||||
&& generator.level == 0.2
|
||||
&& matches!(generator.inputs.get(&texturecraft_core::BakedMap::AmbientOcclusion), Some(texturecraft_core::Source::Uniform([0.25, 0.25, 0.25])))));
|
||||
assert_eq!(edited.name, "Keep me");
|
||||
assert_eq!(edited.opacity, 0.4);
|
||||
let layer = state.doc.project.layer(owner).unwrap();
|
||||
let ids: Vec<u64> = layer.mask.as_ref().unwrap().effects.iter().map(|item| item.id.0).collect();
|
||||
assert_eq!(ids, vec![effect, later]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unparseable_color_param_returns_error() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -9,9 +9,13 @@ license.workspace = true
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-usd.workspace = true
|
||||
# ICC v2 serialization prerequisite: craft-libs#1735; app colour policy stays local.
|
||||
craft-cms-icc-v2 = { package = "craft-cms", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "272a095b61257917693da3d09f2f8ecccd7f0295" }
|
||||
craft-materialx = { workspace = true }
|
||||
craft-mesh = { workspace = true }
|
||||
craft-mcmat = { workspace = true }
|
||||
craft-tcraft = { workspace = true }
|
||||
craft-zip = { workspace = true }
|
||||
texturecraft-core = { workspace = true }
|
||||
texturecraft-texel = { workspace = true }
|
||||
@@ -19,7 +23,6 @@ texturecraft-geom = { workspace = true }
|
||||
texturecraft-compose = { workspace = true }
|
||||
image = { workspace = true }
|
||||
gltf = { workspace = true }
|
||||
tobj = { workspace = true }
|
||||
flate2 = { workspace = true }
|
||||
lz4_flex = { workspace = true }
|
||||
half = { workspace = true }
|
||||
|
||||
+31
-110
@@ -1,63 +1,7 @@
|
||||
//! ICC profiles for the export colour spaces: a version 2.1 matrix/curve display profile, small
|
||||
//! (about 1.2 KiB) and readable by every colour-managed viewer and editor.
|
||||
//!
|
||||
//! The colorants come from the space's primaries adapted to the D50 profile connection space
|
||||
//! (see `ColorSpace::to_xyz_d50`). sRGB carries its transfer curve as a sampled table; the linear
|
||||
//! spaces carry a gamma of 1. Written from the ICC.1:2001-04 specification; nothing is copied
|
||||
//! from a colour-management library or from another profile.
|
||||
|
||||
//! ICC v2.1 export policy; byte serialization is shared with craft-cms.
|
||||
use craft_cms_icc_v2::write_v2::{MatrixProfile, ToneCurve, matrix_profile};
|
||||
use texturecraft_texel::{ColorSpace, srgb_to_linear};
|
||||
|
||||
/// Samples of the sRGB curve table.
|
||||
const CURVE_POINTS: usize = 1024;
|
||||
/// The D50 white of the profile connection space.
|
||||
const D50_XYZ: [f64; 3] = [0.9642, 1.0, 0.8249];
|
||||
|
||||
fn s15f16(v: f64) -> [u8; 4] {
|
||||
((v * 65536.0).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32).to_be_bytes()
|
||||
}
|
||||
|
||||
fn xyz_tag(v: [f64; 3]) -> Vec<u8> {
|
||||
let mut b = b"XYZ \0\0\0\0".to_vec();
|
||||
for c in v {
|
||||
b.extend_from_slice(&s15f16(c));
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
fn text_tag(text: &str) -> Vec<u8> {
|
||||
let mut b = b"text\0\0\0\0".to_vec();
|
||||
b.extend_from_slice(text.as_bytes());
|
||||
b.push(0);
|
||||
b
|
||||
}
|
||||
|
||||
/// `textDescriptionType` with the ASCII description only.
|
||||
fn desc_tag(text: &str) -> Vec<u8> {
|
||||
let mut b = b"desc\0\0\0\0".to_vec();
|
||||
b.extend_from_slice(&(text.len() as u32 + 1).to_be_bytes());
|
||||
b.extend_from_slice(text.as_bytes());
|
||||
b.push(0);
|
||||
// No Unicode text and no Macintosh ScriptCode text: empty fields and the 67-byte filler.
|
||||
b.extend_from_slice(&[0; 4 + 4 + 2 + 1 + 67]);
|
||||
b
|
||||
}
|
||||
|
||||
fn curve_tag(space: ColorSpace) -> Vec<u8> {
|
||||
let mut b = b"curv\0\0\0\0".to_vec();
|
||||
if space == ColorSpace::Srgb {
|
||||
b.extend_from_slice(&(CURVE_POINTS as u32).to_be_bytes());
|
||||
for i in 0..CURVE_POINTS {
|
||||
let v = f64::from(srgb_to_linear(i as f32 / (CURVE_POINTS - 1) as f32));
|
||||
b.extend_from_slice(&((v * 65535.0).round().clamp(0.0, 65535.0) as u16).to_be_bytes());
|
||||
}
|
||||
} else {
|
||||
// One entry is a gamma, u8Fixed8: 1.0 is linear.
|
||||
b.extend_from_slice(&1u32.to_be_bytes());
|
||||
b.extend_from_slice(&0x0100u16.to_be_bytes());
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
fn description(space: ColorSpace) -> &'static str {
|
||||
match space {
|
||||
@@ -68,64 +12,41 @@ fn description(space: ColorSpace) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// The ICC profile of `space`, or None if its primaries are degenerate (never for the built-in ones).
|
||||
/// The ICC profile of `space`, or None if its primaries are degenerate.
|
||||
pub fn profile(space: ColorSpace) -> Option<Vec<u8>> {
|
||||
let m = space.to_xyz_d50()?;
|
||||
let column = |c: usize| [m[0][c], m[1][c], m[2][c]];
|
||||
let curve = curve_tag(space);
|
||||
// The green and blue curves are the red one's entry.
|
||||
let tags: [(&[u8; 4], Vec<u8>); 9] = [
|
||||
(b"desc", desc_tag(description(space))),
|
||||
(b"cprt", text_tag("No copyright, generated by TextureCraft")),
|
||||
(b"wtpt", xyz_tag(D50_XYZ)),
|
||||
(b"rXYZ", xyz_tag(column(0))),
|
||||
(b"gXYZ", xyz_tag(column(1))),
|
||||
(b"bXYZ", xyz_tag(column(2))),
|
||||
(b"rTRC", curve.clone()),
|
||||
(b"gTRC", curve.clone()),
|
||||
(b"bTRC", curve),
|
||||
];
|
||||
// Header (128) + tag count (4) + 12 per tag, then the tag data, each tag padded to 4 bytes.
|
||||
let table_end = 128 + 4 + 12 * tags.len();
|
||||
let mut offsets = Vec::new();
|
||||
let mut data: Vec<u8> = Vec::new();
|
||||
for (i, (_, bytes)) in tags.iter().enumerate() {
|
||||
let shared = i >= 7;
|
||||
let at = if shared { offsets.get(6).copied().unwrap_or(0) } else { table_end + data.len() };
|
||||
offsets.push(at);
|
||||
if !shared {
|
||||
data.extend_from_slice(bytes);
|
||||
while !data.len().is_multiple_of(4) {
|
||||
data.push(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
let total = table_end + data.len();
|
||||
let mut out = vec![0u8; 128];
|
||||
out.get_mut(0..4)?.copy_from_slice(&(total as u32).to_be_bytes());
|
||||
out.get_mut(8..12)?.copy_from_slice(&[2, 0x10, 0, 0]); // version 2.1.0
|
||||
out.get_mut(12..16)?.copy_from_slice(b"mntr");
|
||||
out.get_mut(16..20)?.copy_from_slice(b"RGB ");
|
||||
out.get_mut(20..24)?.copy_from_slice(b"XYZ ");
|
||||
// A fixed date (2026-01-01 00:00:00), so a space always gives the same bytes.
|
||||
out.get_mut(24..36)?.copy_from_slice(&[0x07, 0xEA, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0]);
|
||||
out.get_mut(36..40)?.copy_from_slice(b"acsp");
|
||||
for (k, v) in D50_XYZ.iter().enumerate() {
|
||||
out.get_mut(68 + 4 * k..72 + 4 * k)?.copy_from_slice(&s15f16(*v));
|
||||
}
|
||||
out.extend_from_slice(&(tags.len() as u32).to_be_bytes());
|
||||
for ((sig, bytes), at) in tags.iter().zip(&offsets) {
|
||||
out.extend_from_slice(*sig);
|
||||
out.extend_from_slice(&(*at as u32).to_be_bytes());
|
||||
out.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
|
||||
}
|
||||
out.extend_from_slice(&data);
|
||||
Some(out)
|
||||
let matrix = space.to_xyz_d50()?;
|
||||
let samples: Vec<u16> = if space == ColorSpace::Srgb {
|
||||
(0..CURVE_POINTS)
|
||||
.map(|i| {
|
||||
let v = f64::from(srgb_to_linear(i as f32 / (CURVE_POINTS - 1) as f32));
|
||||
(v * 65535.0).round().clamp(0.0, 65535.0) as u16
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
matrix_profile(&MatrixProfile {
|
||||
matrix,
|
||||
curve: if samples.is_empty() { ToneCurve::Linear } else { ToneCurve::Samples(&samples) },
|
||||
description: description(space),
|
||||
copyright: "No copyright, generated by TextureCraft",
|
||||
date: [2026, 1, 1, 0, 0, 0],
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "icc_legacy_test.rs"]
|
||||
mod legacy;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn all_spaces_match_legacy_wire_bytes() {
|
||||
for space in ColorSpace::ALL {
|
||||
assert_eq!(profile(space), legacy::profile(space), "{space:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn u32_at(b: &[u8], i: usize) -> u32 {
|
||||
u32::from_be_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]])
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! ICC profiles for the export colour spaces: a version 2.1 matrix/curve display profile, small
|
||||
//! (about 1.2 KiB) and readable by every colour-managed viewer and editor.
|
||||
//!
|
||||
//! The colorants come from the space's primaries adapted to the D50 profile connection space
|
||||
//! (see `ColorSpace::to_xyz_d50`). sRGB carries its transfer curve as a sampled table; the linear
|
||||
//! spaces carry a gamma of 1. Written from the ICC.1:2001-04 specification; nothing is copied
|
||||
//! from a colour-management library or from another profile.
|
||||
|
||||
use texturecraft_texel::{ColorSpace, srgb_to_linear};
|
||||
|
||||
/// Samples of the sRGB curve table.
|
||||
const CURVE_POINTS: usize = 1024;
|
||||
/// The D50 white of the profile connection space.
|
||||
const D50_XYZ: [f64; 3] = [0.9642, 1.0, 0.8249];
|
||||
|
||||
fn s15f16(v: f64) -> [u8; 4] {
|
||||
((v * 65536.0).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32).to_be_bytes()
|
||||
}
|
||||
|
||||
fn xyz_tag(v: [f64; 3]) -> Vec<u8> {
|
||||
let mut b = b"XYZ \0\0\0\0".to_vec();
|
||||
for c in v {
|
||||
b.extend_from_slice(&s15f16(c));
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
fn text_tag(text: &str) -> Vec<u8> {
|
||||
let mut b = b"text\0\0\0\0".to_vec();
|
||||
b.extend_from_slice(text.as_bytes());
|
||||
b.push(0);
|
||||
b
|
||||
}
|
||||
|
||||
/// `textDescriptionType` with the ASCII description only.
|
||||
fn desc_tag(text: &str) -> Vec<u8> {
|
||||
let mut b = b"desc\0\0\0\0".to_vec();
|
||||
b.extend_from_slice(&(text.len() as u32 + 1).to_be_bytes());
|
||||
b.extend_from_slice(text.as_bytes());
|
||||
b.push(0);
|
||||
// No Unicode text and no Macintosh ScriptCode text: empty fields and the 67-byte filler.
|
||||
b.extend_from_slice(&[0; 4 + 4 + 2 + 1 + 67]);
|
||||
b
|
||||
}
|
||||
|
||||
fn curve_tag(space: ColorSpace) -> Vec<u8> {
|
||||
let mut b = b"curv\0\0\0\0".to_vec();
|
||||
if space == ColorSpace::Srgb {
|
||||
b.extend_from_slice(&(CURVE_POINTS as u32).to_be_bytes());
|
||||
for i in 0..CURVE_POINTS {
|
||||
let v = f64::from(srgb_to_linear(i as f32 / (CURVE_POINTS - 1) as f32));
|
||||
b.extend_from_slice(&((v * 65535.0).round().clamp(0.0, 65535.0) as u16).to_be_bytes());
|
||||
}
|
||||
} else {
|
||||
// One entry is a gamma, u8Fixed8: 1.0 is linear.
|
||||
b.extend_from_slice(&1u32.to_be_bytes());
|
||||
b.extend_from_slice(&0x0100u16.to_be_bytes());
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
fn description(space: ColorSpace) -> &'static str {
|
||||
match space {
|
||||
ColorSpace::Srgb => "sRGB (Rec.709 primaries, sRGB curve)",
|
||||
ColorSpace::LinearRec709 => "Linear Rec.709 (sRGB primaries, D65)",
|
||||
ColorSpace::AcesCg => "ACEScg (AP1 primaries, linear)",
|
||||
ColorSpace::Aces2065 => "ACES2065-1 (AP0 primaries, linear)",
|
||||
}
|
||||
}
|
||||
|
||||
/// The ICC profile of `space`, or None if its primaries are degenerate (never for the built-in ones).
|
||||
pub fn profile(space: ColorSpace) -> Option<Vec<u8>> {
|
||||
let m = space.to_xyz_d50()?;
|
||||
let column = |c: usize| [m[0][c], m[1][c], m[2][c]];
|
||||
let curve = curve_tag(space);
|
||||
// The green and blue curves are the red one's entry.
|
||||
let tags: [(&[u8; 4], Vec<u8>); 9] = [
|
||||
(b"desc", desc_tag(description(space))),
|
||||
(b"cprt", text_tag("No copyright, generated by TextureCraft")),
|
||||
(b"wtpt", xyz_tag(D50_XYZ)),
|
||||
(b"rXYZ", xyz_tag(column(0))),
|
||||
(b"gXYZ", xyz_tag(column(1))),
|
||||
(b"bXYZ", xyz_tag(column(2))),
|
||||
(b"rTRC", curve.clone()),
|
||||
(b"gTRC", curve.clone()),
|
||||
(b"bTRC", curve),
|
||||
];
|
||||
// Header (128) + tag count (4) + 12 per tag, then the tag data, each tag padded to 4 bytes.
|
||||
let table_end = 128 + 4 + 12 * tags.len();
|
||||
let mut offsets = Vec::new();
|
||||
let mut data: Vec<u8> = Vec::new();
|
||||
for (i, (_, bytes)) in tags.iter().enumerate() {
|
||||
let shared = i >= 7;
|
||||
let at = if shared { offsets.get(6).copied().unwrap_or(0) } else { table_end + data.len() };
|
||||
offsets.push(at);
|
||||
if !shared {
|
||||
data.extend_from_slice(bytes);
|
||||
while !data.len().is_multiple_of(4) {
|
||||
data.push(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
let total = table_end + data.len();
|
||||
let mut out = vec![0u8; 128];
|
||||
out.get_mut(0..4)?.copy_from_slice(&(total as u32).to_be_bytes());
|
||||
out.get_mut(8..12)?.copy_from_slice(&[2, 0x10, 0, 0]); // version 2.1.0
|
||||
out.get_mut(12..16)?.copy_from_slice(b"mntr");
|
||||
out.get_mut(16..20)?.copy_from_slice(b"RGB ");
|
||||
out.get_mut(20..24)?.copy_from_slice(b"XYZ ");
|
||||
// A fixed date (2026-01-01 00:00:00), so a space always gives the same bytes.
|
||||
out.get_mut(24..36)?.copy_from_slice(&[0x07, 0xEA, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0]);
|
||||
out.get_mut(36..40)?.copy_from_slice(b"acsp");
|
||||
for (k, v) in D50_XYZ.iter().enumerate() {
|
||||
out.get_mut(68 + 4 * k..72 + 4 * k)?.copy_from_slice(&s15f16(*v));
|
||||
}
|
||||
out.extend_from_slice(&(tags.len() as u32).to_be_bytes());
|
||||
for ((sig, bytes), at) in tags.iter().zip(&offsets) {
|
||||
out.extend_from_slice(*sig);
|
||||
out.extend_from_slice(&(*at as u32).to_be_bytes());
|
||||
out.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
|
||||
}
|
||||
out.extend_from_slice(&data);
|
||||
Some(out)
|
||||
}
|
||||
@@ -154,7 +154,7 @@ impl Writer {
|
||||
UsdValue::Ints(v) if v.len() >= codec::MIN_COMPRESSED_ARRAY => {
|
||||
let at = self.offset();
|
||||
self.out.extend_from_slice(&(v.len() as u64).to_le_bytes());
|
||||
self.ints(&v.iter().map(|&i| i64::from(i)).collect::<Vec<_>>());
|
||||
self.ints(&v.iter().map(|&i| i64::from(i)).collect::<Vec<_>>())?;
|
||||
rep(ty::INT, codec::IS_ARRAY | codec::IS_COMPRESSED, at)
|
||||
}
|
||||
UsdValue::Ints(v) => self.raw_array(ty::INT, v.len(), v.iter().flat_map(|i| i.to_le_bytes())),
|
||||
@@ -174,10 +174,11 @@ impl Writer {
|
||||
}
|
||||
|
||||
/// Compressed integers: their compressed size, then the LZ4-framed coding.
|
||||
fn ints(&mut self, v: &[i64]) {
|
||||
let comp = codec::compress(&codec::encode_ints(v, 4));
|
||||
fn ints(&mut self, v: &[i64]) -> Result<()> {
|
||||
let comp = codec::compress(&codec::encode_ints(v, 4)?)?;
|
||||
self.out.extend_from_slice(&(comp.len() as u64).to_le_bytes());
|
||||
self.out.extend_from_slice(&comp);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn spec(&mut self, path: usize, kind: i64, fields: Vec<(&str, u64)>) {
|
||||
@@ -303,7 +304,7 @@ impl Writer {
|
||||
self.out.extend_from_slice(&(v as u64).to_le_bytes());
|
||||
}
|
||||
|
||||
fn sections(&mut self) {
|
||||
fn sections(&mut self) -> Result<()> {
|
||||
let mut toc = Vec::new();
|
||||
let start = self.offset();
|
||||
let mut raw = Vec::new();
|
||||
@@ -311,7 +312,7 @@ impl Writer {
|
||||
raw.extend_from_slice(t.as_bytes());
|
||||
raw.push(0);
|
||||
}
|
||||
let comp = codec::compress(&raw);
|
||||
let comp = codec::compress(&raw)?;
|
||||
self.u64(self.tokens.len());
|
||||
self.u64(raw.len());
|
||||
self.u64(comp.len());
|
||||
@@ -327,9 +328,9 @@ impl Writer {
|
||||
let start = self.offset();
|
||||
let fields = std::mem::take(&mut self.fields);
|
||||
self.u64(fields.len());
|
||||
self.ints(&fields.iter().map(|f| i64::from(f.0)).collect::<Vec<_>>());
|
||||
self.ints(&fields.iter().map(|f| i64::from(f.0)).collect::<Vec<_>>())?;
|
||||
let reps: Vec<u8> = fields.iter().flat_map(|f| f.1.to_le_bytes()).collect();
|
||||
let comp = codec::compress(&reps);
|
||||
let comp = codec::compress(&reps)?;
|
||||
self.u64(comp.len());
|
||||
self.out.extend_from_slice(&comp);
|
||||
self.section(&mut toc, "FIELDS", start);
|
||||
@@ -337,7 +338,7 @@ impl Writer {
|
||||
let start = self.offset();
|
||||
let sets = std::mem::take(&mut self.fieldsets);
|
||||
self.u64(sets.len());
|
||||
self.ints(&sets);
|
||||
self.ints(&sets)?;
|
||||
self.section(&mut toc, "FIELDSETS", start);
|
||||
|
||||
let start = self.offset();
|
||||
@@ -345,7 +346,7 @@ impl Writer {
|
||||
self.u64(self.paths.len());
|
||||
self.u64(self.paths.len());
|
||||
for column in &table {
|
||||
self.ints(column);
|
||||
self.ints(column)?;
|
||||
}
|
||||
self.section(&mut toc, "PATHS", start);
|
||||
|
||||
@@ -353,7 +354,7 @@ impl Writer {
|
||||
let specs = std::mem::take(&mut self.specs);
|
||||
self.u64(specs.len());
|
||||
for k in 0..3 {
|
||||
self.ints(&specs.iter().map(|s| s.get(k).copied().unwrap_or_default()).collect::<Vec<_>>());
|
||||
self.ints(&specs.iter().map(|s| s.get(k).copied().unwrap_or_default()).collect::<Vec<_>>())?;
|
||||
}
|
||||
self.section(&mut toc, "SPECS", start);
|
||||
|
||||
@@ -371,6 +372,7 @@ impl Writer {
|
||||
if let Some(slot) = self.out.get_mut(16..24) {
|
||||
slot.copy_from_slice(&toc_at.to_le_bytes());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -400,9 +402,9 @@ impl Writer {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finish(mut self) -> Vec<u8> {
|
||||
self.sections();
|
||||
self.out
|
||||
fn finish(mut self) -> Result<Vec<u8>> {
|
||||
self.sections()?;
|
||||
Ok(self.out)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -413,7 +415,7 @@ pub(crate) fn write(layer: &UsdLayer) -> Result<Vec<u8>> {
|
||||
w.add_prim_paths(0, "/", root);
|
||||
w.root_spec(&root.name)?;
|
||||
w.prim_specs(&format!("/{}", root.name), root)?;
|
||||
Ok(w.finish())
|
||||
w.finish()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -504,7 +506,7 @@ mod tests {
|
||||
for (path, value) in attrs.into_iter().zip([points, counts, indices]) {
|
||||
w.spec(path, SPEC_ATTRIBUTE, vec![("default", value)]);
|
||||
}
|
||||
let bytes = w.finish();
|
||||
let bytes = w.finish().unwrap();
|
||||
|
||||
let m = crate::import_mesh_bytes("crafted.usdc", &bytes).unwrap().mesh;
|
||||
assert_eq!(m.triangle_count(), 1, "the class prim itself is not drawn");
|
||||
|
||||
@@ -554,7 +554,7 @@ impl Walk<'_, '_> {
|
||||
Vec2::ZERO
|
||||
}
|
||||
});
|
||||
corners.push(Corner { p: *p, n, uv });
|
||||
corners.push(Corner { p: *p, n, uv, color: None });
|
||||
}
|
||||
k = end;
|
||||
if !keep_order {
|
||||
|
||||
@@ -356,6 +356,7 @@ fn add_geometry(d: &mut Doc, sink: &mut PolygonSink, geom: &El, m: Mat4, bind: &
|
||||
p: m.transform_point3(Vec3::from(pos)),
|
||||
n: n.map(|n| nm * Vec3::from(n)),
|
||||
uv: t.map(|[u, v]| Vec2::new(u, 1.0 - v)),
|
||||
color: None,
|
||||
});
|
||||
}
|
||||
next = next.saturating_add(size);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2,7 +2,7 @@
|
||||
//! world-space [`Mesh`] with one submesh per material and part (glTF node, OBJ object, FBX
|
||||
//! model, COLLADA node, USD Mesh prim, Alembic PolyMesh; unnamed parts take the file stem), materials contiguous,
|
||||
//! glTF UV convention (origin top-left, v down),
|
||||
//! normals (computed when missing), vertex colors (glTF, OBJ, PLY), UVs (auto-unwrapped when
|
||||
//! normals (computed when missing), vertex colors (glTF, FBX, OBJ, PLY), UVs (auto-unwrapped when
|
||||
//! missing) and MikkTSpace tangents. glTF, FBX, COLLADA and USD cameras come along as the
|
||||
//! project's camera list.
|
||||
|
||||
@@ -12,7 +12,6 @@ mod external;
|
||||
mod fbx;
|
||||
mod gltf;
|
||||
mod obj;
|
||||
mod obj_source;
|
||||
mod ply;
|
||||
#[cfg(test)]
|
||||
mod scene_tests;
|
||||
@@ -188,10 +187,11 @@ pub(crate) struct Corner {
|
||||
pub p: Vec3,
|
||||
pub n: Option<Vec3>,
|
||||
pub uv: Option<Vec2>,
|
||||
pub color: Option<Vec4>,
|
||||
}
|
||||
|
||||
/// Collects polygons into a [`RawMesh`]: fan triangulation, one vertex per unique corner, and
|
||||
/// normals / UVs kept only when every corner has them (else computed / unwrapped).
|
||||
/// normals / UVs / colors kept only when every corner has them (else computed / unwrapped / white).
|
||||
#[derive(Default)]
|
||||
pub(crate) struct PolygonSink {
|
||||
/// Part name of the polygons that follow.
|
||||
@@ -199,10 +199,13 @@ pub(crate) struct PolygonSink {
|
||||
raw: RawMesh,
|
||||
normals: Vec<Vec3>,
|
||||
uvs: Vec<Vec2>,
|
||||
/// Allocated by the first coloured corner, so a scene without colors pays nothing for them.
|
||||
colors: Option<Vec<Vec4>>,
|
||||
missing_normals: bool,
|
||||
missing_uvs: bool,
|
||||
some_uvs: bool,
|
||||
ids: HashMap<[u32; 8], u32>,
|
||||
missing_colors: bool,
|
||||
ids: HashMap<[u32; 12], u32>,
|
||||
polygon: Vec<u32>,
|
||||
triangles: usize,
|
||||
}
|
||||
@@ -219,13 +222,24 @@ impl PolygonSink {
|
||||
self.missing_normals |= c.n.is_none();
|
||||
self.missing_uvs |= c.uv.is_none();
|
||||
self.some_uvs |= c.uv.is_some();
|
||||
self.missing_colors |= c.color.is_none();
|
||||
let (n, uv) = (c.n.unwrap_or_default(), c.uv.unwrap_or_default());
|
||||
// A corner without a color must not merge with one that has it.
|
||||
let color_key = c.color.map_or([u32::MAX; 4], |v| v.to_array().map(f32::to_bits));
|
||||
let key = [c.p.x, c.p.y, c.p.z, n.x, n.y, n.z, uv.x, uv.y].map(f32::to_bits);
|
||||
let key = [key[0], key[1], key[2], key[3], key[4], key[5], key[6], key[7], color_key[0], color_key[1], color_key[2], color_key[3]];
|
||||
let id = match self.ids.entry(key) {
|
||||
Entry::Occupied(e) => *e.get(),
|
||||
Entry::Vacant(e) => {
|
||||
let id = self.raw.positions.len();
|
||||
check_vertices(id + 1)?;
|
||||
// White stands in for the corners before the first coloured one.
|
||||
if c.color.is_some() && self.colors.is_none() {
|
||||
self.colors = Some(vec![Vec4::ONE; id]);
|
||||
}
|
||||
if let Some(colors) = self.colors.as_mut() {
|
||||
colors.push(c.color.unwrap_or(Vec4::ONE));
|
||||
}
|
||||
self.raw.positions.push(c.p);
|
||||
self.normals.push(n);
|
||||
self.uvs.push(uv);
|
||||
@@ -248,8 +262,12 @@ impl PolygonSink {
|
||||
if self.missing_uvs && self.some_uvs {
|
||||
self.warn("some polygons have no UVs; the whole mesh was unwrapped automatically".into());
|
||||
}
|
||||
if self.missing_colors && self.colors.is_some() {
|
||||
self.warn("some polygon corners have no color in the color layer; vertex colors were dropped".into());
|
||||
}
|
||||
self.raw.normals = (!self.missing_normals).then_some(self.normals);
|
||||
self.raw.uvs = (!self.missing_uvs).then_some(self.uvs);
|
||||
self.raw.colors = if self.missing_colors { None } else { self.colors.take() };
|
||||
self.raw
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
//! Wavefront OBJ (via `tobj`): polygons fan-triangulated, one vertex per unique v/vt/vn.
|
||||
|
||||
use std::io::BufReader;
|
||||
|
||||
//! Wavefront OBJ through the shared bounded mesh reader.
|
||||
use super::{MAX_VERTICES, RawMesh, check_vertices};
|
||||
use crate::{FormatError, Result, malformed};
|
||||
use std::collections::HashMap;
|
||||
use texturecraft_geom::glam::{Vec2, Vec3, Vec4};
|
||||
|
||||
use super::{RawMesh, check_triangles, check_vertices};
|
||||
use crate::{Result, malformed};
|
||||
|
||||
const KIND: &str = "OBJ";
|
||||
|
||||
pub(crate) fn read(bytes: &[u8]) -> Result<RawMesh> {
|
||||
@@ -14,111 +11,85 @@ pub(crate) fn read(bytes: &[u8]) -> Result<RawMesh> {
|
||||
}
|
||||
|
||||
fn read_inner(bytes: &[u8]) -> Result<RawMesh> {
|
||||
let text = String::from_utf8_lossy(bytes);
|
||||
|
||||
// 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")
|
||||
&& let Some((_, name)) = line.split_once(' ')
|
||||
&& !name.trim().is_empty()
|
||||
&& !names.contains(&name.trim())
|
||||
{
|
||||
names.push(name.trim());
|
||||
}
|
||||
}
|
||||
|
||||
let library: String = names.iter().map(|name| format!("newmtl {name}\n")).collect();
|
||||
// Rewrite declaration keys lazily, preserving main's bounded streaming input
|
||||
let mut source = super::obj_source::ObjSource::new(&text);
|
||||
|
||||
// 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 BufReader::new(&mut source), &options, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?;
|
||||
let materials = materials.unwrap_or_default();
|
||||
|
||||
let limits = craft_mesh::Limits {
|
||||
max_vertices: MAX_VERTICES,
|
||||
max_triangles: texturecraft_geom::MAX_TRIANGLES,
|
||||
max_face_corners: MAX_VERTICES,
|
||||
max_meshes: MAX_VERTICES,
|
||||
max_parts: MAX_VERTICES,
|
||||
max_materials: MAX_VERTICES,
|
||||
max_data_bytes: super::MAX_MESH_FILE_BYTES as usize,
|
||||
..Default::default()
|
||||
};
|
||||
let options = craft_mesh::obj::ReadOptions { strict: true, preserve_runs: true, ignore_material_libraries: true, groups_as_objects: true };
|
||||
let scene = craft_mesh::obj::read_with_options(bytes, &limits, &mut craft_mesh::no_external, &options).map_err(|e| match e {
|
||||
craft_mesh::Error::TooLarge(s) => FormatError::TooLarge(s),
|
||||
e => FormatError::Invalid(e.to_string()),
|
||||
})?;
|
||||
let any_uvs = scene.meshes.iter().flat_map(|mesh| mesh.parts.iter()).flat_map(|part| part.corners.iter()).any(|c| c.uv != craft_mesh::NONE);
|
||||
let any_colors = scene.meshes.iter().any(|mesh| !mesh.colors.is_empty());
|
||||
let mut raw = RawMesh::default();
|
||||
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;
|
||||
let mut triangles = 0;
|
||||
for model in &models {
|
||||
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() };
|
||||
let model_triangles = arities.iter().map(|a| a.saturating_sub(2)).sum();
|
||||
check_triangles(triangles, model_triangles)?;
|
||||
triangles += model_triangles;
|
||||
let base = raw.positions.len() as u32;
|
||||
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(mesh.normals.as_chunks::<3>().0.iter().map(|p| Vec3::new(p[0], p[1], p[2])));
|
||||
}
|
||||
} else {
|
||||
normals = None;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// `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 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) = 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
|
||||
let part = if model.name == "unnamed_object" { "" } else { model.name.as_str() };
|
||||
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;
|
||||
corners.clear();
|
||||
corners.extend(face.iter().map(|i| base + i));
|
||||
if arity >= 3 {
|
||||
raw.polygon(&name, part, &corners);
|
||||
let (mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let (mut missing_normals, mut missing_uvs) = (false, false);
|
||||
for (mesh_id, mesh) in scene.meshes.iter().enumerate() {
|
||||
// The shared reader preserves declarations as meshes, even when their names match
|
||||
let declaration = mesh_id.to_string();
|
||||
for part in &mesh.parts {
|
||||
let material = part.material.and_then(|i| scene.materials.get(i)).map_or("Default", |m| m.name.as_str());
|
||||
// OBJ model/material runs have independent v/vt/vn deduplication.
|
||||
let mut ids = HashMap::new();
|
||||
for face in part.faces() {
|
||||
let mut polygon = Vec::with_capacity(face.len());
|
||||
for corner in face {
|
||||
let id = if let Some(id) = ids.get(corner) {
|
||||
*id
|
||||
} else {
|
||||
let position = mesh.positions.get(corner.position as usize).ok_or_else(|| malformed(KIND, "position index out of range"))?;
|
||||
check_vertices(raw.positions.len().saturating_add(1))?;
|
||||
// Bound both the output pools and the per-run corner map before growth.
|
||||
let staging = raw
|
||||
.positions
|
||||
.len()
|
||||
.checked_add(1)
|
||||
.and_then(|n| n.checked_mul(64))
|
||||
.and_then(|n| ids.len().checked_add(1).and_then(|m| m.checked_mul(48)).and_then(|m| n.checked_add(m)));
|
||||
if staging.is_none_or(|n| n > limits.max_data_bytes) {
|
||||
return Err(FormatError::TooLarge("OBJ mesh exceeds the memory limit".into()));
|
||||
}
|
||||
let id = u32::try_from(raw.positions.len()).map_err(|_| FormatError::TooLarge("OBJ vertex count".into()))?;
|
||||
raw.positions.push(Vec3::new(position[0] as f32, position[1] as f32, position[2] as f32));
|
||||
let normal = mesh.normals.get(corner.normal as usize).map(|n| Vec3::new(n[0] as f32, n[1] as f32, n[2] as f32));
|
||||
missing_normals |= normal.is_none();
|
||||
normals.push(normal.unwrap_or_default());
|
||||
if any_uvs {
|
||||
let uv = mesh.uv_sets.first().and_then(|set| set.get(corner.uv as usize)).map(|v| Vec2::new(v[0], v[1]));
|
||||
missing_uvs |= uv.is_none();
|
||||
uvs.push(uv.unwrap_or_default());
|
||||
}
|
||||
if any_colors {
|
||||
colors.push(mesh.colors.get(corner.position as usize).copied().map(Vec4::from_array).unwrap_or(Vec4::ONE));
|
||||
}
|
||||
ids.insert(*corner, id);
|
||||
id
|
||||
};
|
||||
polygon.push(id);
|
||||
}
|
||||
raw.polygon(material, &declaration, &polygon);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Restore user-facing names after all faces have been grouped by declaration.
|
||||
for (_, part, _) in &mut raw.groups {
|
||||
if let Some(name) = part.parse::<usize>().ok().and_then(|id| source.part_names.get(id)) {
|
||||
*part = (*name).to_owned();
|
||||
// Restore display names only after grouping by declaration and material
|
||||
for (_, name, _) in &mut raw.groups {
|
||||
if let Some(mesh) = name.parse::<usize>().ok().and_then(|id| scene.meshes.get(id)) {
|
||||
*name = mesh.name.clone();
|
||||
}
|
||||
}
|
||||
|
||||
if partial_uvs {
|
||||
if missing_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(|model| !model.mesh.vertex_color.is_empty()).then_some(colors);
|
||||
|
||||
raw.normals = (!missing_normals).then_some(normals);
|
||||
raw.uvs = any_uvs.then_some(uvs);
|
||||
raw.colors = any_colors.then_some(colors);
|
||||
Ok(raw)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
//! Streaming declaration identities without copying the complete OBJ body.
|
||||
use std::borrow::Cow;
|
||||
use std::io::{self, Read};
|
||||
|
||||
pub(super) struct ObjSource<'a> {
|
||||
lines: std::str::SplitInclusive<'a, char>,
|
||||
pending: Cow<'a, [u8]>,
|
||||
offset: usize,
|
||||
pub part_names: Vec<&'a str>,
|
||||
}
|
||||
|
||||
impl<'a> ObjSource<'a> {
|
||||
pub fn new(text: &'a str) -> Self {
|
||||
Self { lines: text.split_inclusive('\n'), pending: Cow::Borrowed(b"mtllib texturecraft-usemtl.mtl\n"), offset: 0, part_names: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Read for ObjSource<'_> {
|
||||
fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
|
||||
if out.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
while self.offset == self.pending.len() {
|
||||
let Some(line) = self.lines.next() else { return Ok(0) };
|
||||
let trimmed = line.trim();
|
||||
self.pending = if matches!(trimmed.split_whitespace().next(), Some("o" | "g")) {
|
||||
let key = format!("o {}\n", self.part_names.len());
|
||||
self.part_names.push(trimmed.get(1..).unwrap_or_default().trim());
|
||||
Cow::Owned(key.into_bytes())
|
||||
} else {
|
||||
Cow::Borrowed(line.as_bytes())
|
||||
};
|
||||
self.offset = 0;
|
||||
}
|
||||
let remaining = self.pending.get(self.offset..).unwrap_or_default();
|
||||
let count = out.len().min(remaining.len());
|
||||
out.iter_mut().zip(remaining.iter()).take(count).for_each(|(dst, src)| *dst = *src);
|
||||
self.offset += count;
|
||||
Ok(count)
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn short_reads_preserve_body_and_distinct_declarations() {
|
||||
let text = "# café\r\n o same\r\nv 0 0 0\r\ng\tsame\nusemtl gold\nf 1 2 3";
|
||||
let mut source = ObjSource::new(text);
|
||||
assert_eq!(source.read(&mut []).unwrap(), 0);
|
||||
let mut actual = Vec::new();
|
||||
let mut byte = [0];
|
||||
while source.read(&mut byte).unwrap() != 0 {
|
||||
actual.push(byte[0]);
|
||||
}
|
||||
assert_eq!(String::from_utf8(actual).unwrap(), "mtllib texturecraft-usemtl.mtl\n# café\r\no 0\nv 0 0 0\r\no 1\nusemtl gold\nf 1 2 3");
|
||||
assert_eq!(source.part_names, ["same", "same"]);
|
||||
assert_eq!(source.read(&mut byte).unwrap(), 0);
|
||||
}
|
||||
}
|
||||
@@ -10,40 +10,20 @@ const KIND: &str = "PLY";
|
||||
/// Longest polygon accepted (a list count above this is treated as corruption).
|
||||
const MAX_FACE_VERTICES: usize = 4096;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Ty {
|
||||
I8,
|
||||
U8,
|
||||
I16,
|
||||
U16,
|
||||
I32,
|
||||
U32,
|
||||
F32,
|
||||
F64,
|
||||
}
|
||||
use craft_mesh::ply::{Encoding as SharedEncoding, Header, Rows, Scalar as Ty};
|
||||
|
||||
impl Ty {
|
||||
fn parse(s: &str) -> Option<Ty> {
|
||||
Some(match s {
|
||||
"char" | "int8" => Ty::I8,
|
||||
"uchar" | "uint8" => Ty::U8,
|
||||
"short" | "int16" => Ty::I16,
|
||||
"ushort" | "uint16" => Ty::U16,
|
||||
"int" | "int32" => Ty::I32,
|
||||
"uint" | "uint32" => Ty::U32,
|
||||
"float" | "float32" => Ty::F32,
|
||||
"double" | "float64" => Ty::F64,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
fn size(self) -> usize {
|
||||
match self {
|
||||
Ty::I8 | Ty::U8 => 1,
|
||||
Ty::I16 | Ty::U16 => 2,
|
||||
Ty::I32 | Ty::U32 | Ty::F32 => 4,
|
||||
Ty::F64 => 8,
|
||||
}
|
||||
}
|
||||
fn parse_type(s: &str) -> Option<Ty> {
|
||||
Some(match s {
|
||||
"char" | "int8" => Ty::I8,
|
||||
"uchar" | "uint8" => Ty::U8,
|
||||
"short" | "int16" => Ty::I16,
|
||||
"ushort" | "uint16" => Ty::U16,
|
||||
"int" | "int32" => Ty::I32,
|
||||
"uint" | "uint32" => Ty::U32,
|
||||
"float" | "float32" => Ty::F32,
|
||||
"double" | "float64" => Ty::F64,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
struct Property {
|
||||
@@ -66,60 +46,36 @@ enum Encoding {
|
||||
Be,
|
||||
}
|
||||
|
||||
/// Reads scalars from the body in either encoding.
|
||||
struct Body<'a> {
|
||||
data: &'a [u8],
|
||||
pos: usize,
|
||||
enc: Encoding,
|
||||
}
|
||||
|
||||
impl Body<'_> {
|
||||
fn next_token(&mut self) -> Option<&str> {
|
||||
let rest = self.data.get(self.pos..)?;
|
||||
let start = rest.iter().position(|b| !b.is_ascii_whitespace())?;
|
||||
let len = rest.get(start..)?.iter().position(|b| b.is_ascii_whitespace()).unwrap_or(rest.len() - start);
|
||||
self.pos += start + len;
|
||||
std::str::from_utf8(rest.get(start..start + len)?).ok()
|
||||
}
|
||||
|
||||
fn read(&mut self, ty: Ty) -> Result<f64> {
|
||||
if self.enc == Encoding::Ascii {
|
||||
let tok = self.next_token().ok_or_else(|| malformed(KIND, "unexpected end of data"))?;
|
||||
return tok.parse::<f64>().map_err(|_| malformed(KIND, format!("bad number \"{tok}\"")));
|
||||
}
|
||||
let n = ty.size();
|
||||
let bytes = self.data.get(self.pos..self.pos + n).ok_or_else(|| malformed(KIND, "unexpected end of data"))?;
|
||||
self.pos += n;
|
||||
let mut b = [0u8; 8];
|
||||
b.get_mut(..n).unwrap_or_default().copy_from_slice(bytes);
|
||||
if self.enc == Encoding::Be {
|
||||
b.get_mut(..n).unwrap_or_default().reverse();
|
||||
}
|
||||
Ok(match ty {
|
||||
Ty::I8 => b[0] as i8 as f64,
|
||||
Ty::U8 => b[0] as f64,
|
||||
Ty::I16 => i16::from_le_bytes([b[0], b[1]]) as f64,
|
||||
Ty::U16 => u16::from_le_bytes([b[0], b[1]]) as f64,
|
||||
Ty::I32 => i32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64,
|
||||
Ty::U32 => u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64,
|
||||
Ty::F32 => f32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64,
|
||||
Ty::F64 => f64::from_le_bytes(b),
|
||||
})
|
||||
}
|
||||
|
||||
fn remaining(&self) -> usize {
|
||||
self.data.len().saturating_sub(self.pos)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn read(bytes: &[u8]) -> Result<RawMesh> {
|
||||
let (elements, enc, body_start) = header(bytes)?;
|
||||
let mut body = Body { data: bytes.get(body_start..).unwrap_or_default(), pos: 0, enc };
|
||||
// Keep the strict app header grammar and mesh policy; delegate only wire scalars.
|
||||
let encoding = match enc {
|
||||
Encoding::Ascii => SharedEncoding::Ascii,
|
||||
Encoding::Le => SharedEncoding::Little,
|
||||
Encoding::Be => SharedEncoding::Big,
|
||||
};
|
||||
let shared_header = Header { encoding, elements: Vec::new(), body: body_start, comments: Vec::new() };
|
||||
let mut body = Rows::new(&shared_header, bytes);
|
||||
let mut raw = RawMesh::default();
|
||||
let (mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new());
|
||||
// Elements may appear in any order, so take the vertex count from the header.
|
||||
let nverts: usize = elements.iter().filter(|e| e.name == "vertex").map(|e| e.count).fold(0, usize::saturating_add);
|
||||
// The shared ASCII reader counts the delimiter after a value as read; the previous reader
|
||||
// left it in the remaining bytes. Only an element without properties can notice the difference.
|
||||
let ascii_slack = usize::from(enc == Encoding::Ascii);
|
||||
for el in &elements {
|
||||
// An element without properties reads nothing, so its rows are skipped. Its count stays
|
||||
// bounded by the bytes left, as the previous reader counted them.
|
||||
if el.props.is_empty() {
|
||||
if el.count > body.remaining().saturating_add(ascii_slack) {
|
||||
return Err(malformed(KIND, format!("element \"{}\" claims {} items but the file is too short", el.name, el.count)));
|
||||
}
|
||||
// A vertex element still needs positions, as below.
|
||||
if el.name == "vertex" {
|
||||
return Err(malformed(KIND, "vertices have no x, y, z"));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Every item takes at least one byte, so the count can never exceed what is left.
|
||||
if el.count > body.remaining() {
|
||||
return Err(malformed(KIND, format!("element \"{}\" claims {} items but the file is too short", el.name, el.count)));
|
||||
@@ -149,17 +105,17 @@ pub(crate) fn read(bytes: &[u8]) -> Result<RawMesh> {
|
||||
match p.list {
|
||||
None => {
|
||||
if let Some(v) = vals.get_mut(k) {
|
||||
*v = body.read(p.ty)?;
|
||||
*v = body.value(p.ty).map_err(|e| malformed(KIND, e.to_string()))?;
|
||||
}
|
||||
}
|
||||
Some(ct) => {
|
||||
let len = body.read(ct)?;
|
||||
let len = body.value(ct).map_err(|e| malformed(KIND, e.to_string()))?;
|
||||
if !(0.0..=MAX_FACE_VERTICES as f64).contains(&len) {
|
||||
return Err(malformed(KIND, format!("bad list length {len}")));
|
||||
}
|
||||
poly.clear();
|
||||
for _ in 0..len as usize {
|
||||
let v = body.read(p.ty)?;
|
||||
let v = body.value(p.ty).map_err(|e| malformed(KIND, e.to_string()))?;
|
||||
if face_list == Some(k) {
|
||||
if !(0.0..nverts as f64).contains(&v) {
|
||||
return Err(malformed(KIND, format!("face index {v} out of range")));
|
||||
@@ -240,13 +196,13 @@ fn header(bytes: &[u8]) -> Result<(Vec<Element>, Encoding, usize)> {
|
||||
}
|
||||
["property", "list", ct, ty, name] => {
|
||||
let el = elements.last_mut().ok_or_else(|| malformed(KIND, "property before element"))?;
|
||||
let (ct, ty) = (Ty::parse(ct), Ty::parse(ty));
|
||||
let (ct, ty) = (parse_type(ct), parse_type(ty));
|
||||
let (Some(ct), Some(ty)) = (ct, ty) else { return Err(malformed(KIND, format!("bad list types in \"{line}\""))) };
|
||||
el.props.push(Property { name: name.to_string(), ty, list: Some(ct) });
|
||||
}
|
||||
["property", ty, name] => {
|
||||
let el = elements.last_mut().ok_or_else(|| malformed(KIND, "property before element"))?;
|
||||
let ty = Ty::parse(ty).ok_or_else(|| malformed(KIND, format!("bad property type {ty}")))?;
|
||||
let ty = parse_type(ty).ok_or_else(|| malformed(KIND, format!("bad property type {ty}")))?;
|
||||
el.props.push(Property { name: name.to_string(), ty, list: None });
|
||||
}
|
||||
["ply"] | [] | ["comment", ..] | ["obj_info", ..] => {}
|
||||
@@ -256,3 +212,52 @@ fn header(bytes: &[u8]) -> Result<(Vec<Element>, Encoding, usize)> {
|
||||
let enc = enc.ok_or_else(|| malformed(KIND, "header has no format line"))?;
|
||||
Ok((elements, enc, pos))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod shared_rows_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn trailing_propertyless_element_after_a_newline_still_opens() {
|
||||
let bytes = b"ply\nformat ascii 1.0\nelement vertex 1\nproperty float x\nproperty float y\nproperty float z\nelement edge 1\nend_header\n0 0 0\n";
|
||||
assert_eq!(read(bytes).unwrap().positions, vec![Vec3::new(0.0, 0.0, 0.0)]);
|
||||
let huge = b"ply\nformat ascii 1.0\nelement vertex 1\nproperty float x\nproperty float y\nproperty float z\nelement edge 3\nend_header\n0 0 0\n";
|
||||
assert!(read(huge).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn propertyless_vertex_element_is_still_rejected() {
|
||||
let bytes = b"ply\nformat ascii 1.0\nelement vertex 1\nelement face 1\nproperty list uchar int vertex_indices\nend_header\n3 0 0 0\n";
|
||||
let Err(e) = read(bytes) else { panic!("a vertex element without x, y, z must not open") };
|
||||
let err = e.to_string();
|
||||
assert!(err.contains("vertices have no x, y, z"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_scalar_endianness_matches_ascii() {
|
||||
for (format, big) in [("binary_little_endian", false), ("binary_big_endian", true)] {
|
||||
let mut bytes =
|
||||
format!("ply\nformat {format} 1.0\nelement vertex 1\nproperty short x\nproperty float y\nproperty double z\nend_header\n").into_bytes();
|
||||
bytes.extend(if big { (-123i16).to_be_bytes() } else { (-123i16).to_le_bytes() });
|
||||
bytes.extend(if big { 1.25f32.to_be_bytes() } else { 1.25f32.to_le_bytes() });
|
||||
bytes.extend(if big { (-2.5f64).to_be_bytes() } else { (-2.5f64).to_le_bytes() });
|
||||
assert_eq!(read(&bytes).unwrap().positions, vec![Vec3::new(-123.0, 1.25, -2.5)]);
|
||||
bytes.pop();
|
||||
assert!(read(&bytes).is_err());
|
||||
}
|
||||
let ascii = b"ply\nformat ascii 1.0\nelement vertex 1\nproperty short x\nproperty float y\nproperty double z\nend_header\n -123 \t1.25\r\n -2.5 ";
|
||||
assert_eq!(read(ascii).unwrap().positions, vec![Vec3::new(-123.0, 1.25, -2.5)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_header_and_invalid_face_policy_remain_local() {
|
||||
for extra in ["unknown directive\n", "property nonsense x\n"] {
|
||||
let bytes = format!("ply\nformat ascii 1.0\nelement vertex 1\n{extra}end_header\n0");
|
||||
assert!(read(bytes.as_bytes()).is_err());
|
||||
}
|
||||
assert!(read(b"ply\nformat ascii 1.0\ncomment \xff\nend_header\n").is_err());
|
||||
let bytes = b"ply\nformat ascii 1.0\nelement face 1\nproperty list uchar int vertex_indices\nelement vertex 1\nproperty float x\nproperty float y\nproperty float z\nend_header\n3 0 0 1\n0 0 0\n";
|
||||
assert!(read(bytes).is_err()); // Do not turn a bad face into a warning/skip.
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use std::io::Write as _;
|
||||
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_geom::glam::{Vec2, Vec3, Vec4};
|
||||
|
||||
use super::tests::hammer;
|
||||
use super::*;
|
||||
@@ -298,6 +298,33 @@ fn fbx_binary_32_and_64_bit_compressed_or_not() {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`scene`] with a per-polygon-vertex color layer: corner `i` gets `(i/8, 1 - i/8, 0.25, 1)`.
|
||||
fn colored_scene() -> Vec<N> {
|
||||
let mut nodes = scene(false);
|
||||
let objects = nodes.iter_mut().find(|node| node.name == "Objects").unwrap();
|
||||
let geometry = objects.children.iter_mut().find(|node| node.name == "Geometry").unwrap();
|
||||
let colors: Vec<f64> = (0..7).flat_map(|i| [i as f64 / 8.0, 1.0 - i as f64 / 8.0, 0.25, 1.0]).collect();
|
||||
geometry.children.push(layer(
|
||||
"LayerElementColor",
|
||||
"ByPolygonVertex",
|
||||
"IndexToDirect",
|
||||
vec![n("Colors", vec![P::Doubles(colors)], vec![]), n("ColorIndex", vec![P::Ints((0..7).collect())], vec![])],
|
||||
));
|
||||
nodes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fbx_vertex_colors_reach_the_mesh_and_high_polys() {
|
||||
let nodes = colored_scene();
|
||||
let expected: Vec<Vec4> = (0..7).map(|i| Vec4::new(i as f32 / 8.0, 1.0 - i as f32 / 8.0, 0.25, 1.0)).collect();
|
||||
for (label, bytes) in [("binary", binary_fbx(&nodes, 7400, false)), ("ascii", ascii_fbx(&nodes).into_bytes())] {
|
||||
let imported = import_mesh_bytes("colors.fbx", &bytes).unwrap_or_else(|e| panic!("{label}: {e}"));
|
||||
assert_eq!(imported.mesh.colors, expected, "{label}: the color layer reaches the mesh");
|
||||
let high = import_high_poly_bytes("colors.fbx", &bytes).unwrap_or_else(|e| panic!("{label}: {e}"));
|
||||
assert_eq!(high.mesh.colors, expected, "{label}: and the high poly used for ID bakes");
|
||||
}
|
||||
}
|
||||
|
||||
/// [`scene`] with a diffuse color on Red and an embedded diffuse texture on Blue.
|
||||
#[test]
|
||||
fn fbx_camera_models_are_capped_during_import() {
|
||||
|
||||
@@ -104,35 +104,13 @@ pub(crate) fn numeric(t: u8) -> Option<(Scalar, usize)> {
|
||||
|
||||
/// Decompress Crate's LZ4 framing into at most `max_out` bytes.
|
||||
pub(crate) fn decompress(input: &[u8], max_out: usize) -> Result<Vec<u8>> {
|
||||
let bad = |e: lz4_flex::block::DecompressError| malformed(KIND, format!("LZ4 data: {e}"));
|
||||
let (&chunks, mut rest) = input.split_first().ok_or_else(|| malformed(KIND, "empty compressed block"))?;
|
||||
// LZ4 expands at most ~255×: never allocate more than the input can produce.
|
||||
let mut out = vec![0u8; max_out.min(input.len().saturating_mul(256).saturating_add(64))];
|
||||
let written = if chunks == 0 {
|
||||
lz4_flex::block::decompress_into(rest, &mut out).map_err(bad)?
|
||||
} else {
|
||||
if chunks > 127 {
|
||||
return Err(malformed(KIND, "bad LZ4 chunk count"));
|
||||
}
|
||||
let mut total = 0usize;
|
||||
for _ in 0..chunks {
|
||||
let size = rest.get(..4).and_then(|b| b.try_into().ok()).map(i32::from_le_bytes).ok_or_else(|| malformed(KIND, "truncated LZ4 chunk"))?;
|
||||
let size = usize::try_from(size).map_err(|_| malformed(KIND, "negative LZ4 chunk size"))?;
|
||||
let chunk = rest.get(4..4usize.saturating_add(size)).ok_or_else(|| malformed(KIND, "truncated LZ4 chunk"))?;
|
||||
rest = rest.get(4 + size..).unwrap_or_default();
|
||||
total += lz4_flex::block::decompress_into(chunk, out.get_mut(total..).unwrap_or_default()).map_err(bad)?;
|
||||
}
|
||||
total
|
||||
};
|
||||
out.truncate(written);
|
||||
Ok(out)
|
||||
craft_usd::decompress(input, max_out).map_err(|e| malformed(KIND, e.to_string()))
|
||||
}
|
||||
|
||||
/// Crate's LZ4 framing for one chunk (inputs are far below LZ4's ~2 GB chunk limit).
|
||||
pub(crate) fn compress(input: &[u8]) -> Vec<u8> {
|
||||
let mut out = vec![0u8];
|
||||
out.extend_from_slice(&lz4_flex::block::compress(input));
|
||||
out
|
||||
pub(crate) fn compress(input: &[u8]) -> Result<Vec<u8>> {
|
||||
// Keep one compressed output reservation within the app's decoded-data ceiling.
|
||||
craft_usd::compress::compress(input, super::MAX_DECODED_BYTES).map_err(|e| malformed(KIND, e.to_string()))
|
||||
}
|
||||
|
||||
/// Upper bound of the encoded size of `n` integers of `width` bytes.
|
||||
@@ -140,89 +118,24 @@ pub(crate) fn encoded_ints_len(n: usize, width: usize) -> usize {
|
||||
if n == 0 { 0 } else { width.saturating_add(n.saturating_mul(2).saturating_add(7) / 8).saturating_add(n.saturating_mul(width)) }
|
||||
}
|
||||
|
||||
fn read_signed(b: &[u8], at: usize, width: usize) -> Option<i64> {
|
||||
let s = b.get(at..at.checked_add(width)?)?;
|
||||
Some(match width {
|
||||
1 => i64::from(i8::from_le_bytes(s.try_into().ok()?)),
|
||||
2 => i64::from(i16::from_le_bytes(s.try_into().ok()?)),
|
||||
4 => i64::from(i32::from_le_bytes(s.try_into().ok()?)),
|
||||
_ => i64::from_le_bytes(s.try_into().ok()?),
|
||||
})
|
||||
}
|
||||
|
||||
/// Decode `n` integers of `width` (4 or 8) bytes; 32-bit values are sign-extended (reinterpret
|
||||
/// as u32 for unsigned data).
|
||||
/// Decode packed integers after the caller charges its aggregate decoded-byte budget.
|
||||
pub(crate) fn decode_ints(data: &[u8], n: usize, width: usize) -> Result<Vec<i64>> {
|
||||
let err = || malformed(KIND, "truncated integer array");
|
||||
if n == 0 {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let common = read_signed(data, 0, width).ok_or_else(err)?;
|
||||
let codes_at = width;
|
||||
let mut at = codes_at + n.div_ceil(4);
|
||||
let mut out = Vec::with_capacity(n);
|
||||
let mut prev = 0i64;
|
||||
for i in 0..n {
|
||||
let code = (data.get(codes_at + i / 4).ok_or_else(err)? >> (2 * (i % 4))) & 3;
|
||||
let delta = match code {
|
||||
0 => common,
|
||||
c => {
|
||||
let w = (width >> (3 - c as usize)).max(1);
|
||||
let v = read_signed(data, at, w).ok_or_else(err)?;
|
||||
at += w;
|
||||
v
|
||||
}
|
||||
};
|
||||
prev = if width == 4 { i64::from((prev as i32).wrapping_add(delta as i32)) } else { prev.wrapping_add(delta) };
|
||||
out.push(prev);
|
||||
}
|
||||
Ok(out)
|
||||
let width = match width {
|
||||
4 => craft_usd::integers::Width::I32,
|
||||
8 => craft_usd::integers::Width::I64,
|
||||
_ => return Err(malformed(KIND, "unsupported integer width")),
|
||||
};
|
||||
craft_usd::integers::decode(data, n, width, super::MAX_DECODED_BYTES).map_err(|e| malformed(KIND, e.to_string()))
|
||||
}
|
||||
|
||||
/// Encode integers of `width` (4 or 8) bytes (values must fit the width).
|
||||
pub(crate) fn encode_ints(values: &[i64], width: usize) -> Vec<u8> {
|
||||
if values.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let wrap = |v: i64| if width == 4 { i64::from(v as i32) } else { v };
|
||||
let mut prev = 0i64;
|
||||
let deltas: Vec<i64> = values
|
||||
.iter()
|
||||
.map(|&v| {
|
||||
let d = wrap(v.wrapping_sub(prev));
|
||||
prev = v;
|
||||
d
|
||||
})
|
||||
.collect();
|
||||
let mut counts = std::collections::HashMap::new();
|
||||
for d in &deltas {
|
||||
*counts.entry(*d).or_insert(0usize) += 1;
|
||||
}
|
||||
let common = counts.into_iter().max_by_key(|&(v, c)| (c, v)).map_or(0, |(v, _)| v);
|
||||
let mut out = Vec::with_capacity(encoded_ints_len(values.len(), width));
|
||||
out.extend_from_slice(&common.to_le_bytes()[..width]);
|
||||
let codes_at = out.len();
|
||||
out.resize(codes_at + values.len().div_ceil(4), 0);
|
||||
for (i, &d) in deltas.iter().enumerate() {
|
||||
let small = |bits: u32| d >= -(1i64 << (bits - 1)) && d < (1i64 << (bits - 1));
|
||||
let code: u8 = if d == common {
|
||||
0
|
||||
} else if small(width as u32 * 2) {
|
||||
1
|
||||
} else if small(width as u32 * 4) {
|
||||
2
|
||||
} else {
|
||||
3
|
||||
};
|
||||
if code > 0 {
|
||||
let w = (width >> (3 - code as usize)).max(1);
|
||||
out.extend_from_slice(&d.to_le_bytes()[..w]);
|
||||
}
|
||||
if let Some(b) = out.get_mut(codes_at + i / 4) {
|
||||
*b |= code << (2 * (i % 4));
|
||||
}
|
||||
}
|
||||
out
|
||||
/// Encode packed integers with a combined scratch/output reservation cap.
|
||||
pub(crate) fn encode_ints(values: &[i64], width: usize) -> Result<Vec<u8>> {
|
||||
let width = match width {
|
||||
4 => craft_usd::integers::Width::I32,
|
||||
8 => craft_usd::integers::Width::I64,
|
||||
_ => return Err(malformed(KIND, "unsupported integer width")),
|
||||
};
|
||||
craft_usd::integers::encode(values, width, super::MAX_DECODED_BYTES).map_err(|e| malformed(KIND, e.to_string()))
|
||||
}
|
||||
|
||||
/// Error for counts that cannot be real (more items than bytes left could describe).
|
||||
|
||||
@@ -576,6 +576,7 @@ impl<'a> Stage<'a> {
|
||||
p: m.transform_point3(Vec3::from(p)),
|
||||
n: normals.as_ref().and_then(|pv| pv.get::<3>(at)).map(|v| nm * Vec3::from(v)),
|
||||
uv: uvs.as_ref().and_then(|pv| pv.get::<2>(at)).map(|[u, v]| Vec2::new(u, 1.0 - v)),
|
||||
color: None,
|
||||
});
|
||||
}
|
||||
if flip {
|
||||
|
||||
@@ -408,18 +408,50 @@ fn usd_extension_detects_the_encoding() {
|
||||
fn integer_coding_round_trips() {
|
||||
let values: Vec<i64> = vec![0, 1, 2, 3, 3, 3, -5, 1000, -70000, i64::from(i32::MAX), i64::from(i32::MIN), 7, 7, 7, 8];
|
||||
for width in [4, 8] {
|
||||
let enc = codec::encode_ints(&values, width);
|
||||
let enc = codec::encode_ints(&values, width).unwrap();
|
||||
assert!(enc.len() <= codec::encoded_ints_len(values.len(), width));
|
||||
assert_eq!(codec::decode_ints(&enc, values.len(), width).unwrap(), values);
|
||||
assert!(codec::decode_ints(&enc[..enc.len() - 1], values.len(), width).is_err());
|
||||
}
|
||||
let wide = vec![i64::MAX, i64::MIN, 0, 1 << 40];
|
||||
assert_eq!(codec::decode_ints(&codec::encode_ints(&wide, 8), 4, 8).unwrap(), wide);
|
||||
assert_eq!(codec::decode_ints(&codec::encode_ints(&wide, 8).unwrap(), 4, 8).unwrap(), wide);
|
||||
let big: Vec<u8> = (0..5000u32).flat_map(|i| (i % 7).to_le_bytes()).collect();
|
||||
assert_eq!(codec::decompress(&codec::compress(&big), big.len()).unwrap(), big);
|
||||
assert_eq!(codec::decompress(&codec::compress(&big).unwrap(), big.len()).unwrap(), big);
|
||||
assert!(codec::decompress(&[0, 0xF0], 10).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_crate_lz4_writer_preserves_bytes() {
|
||||
for len in [0, 1, 15, 16, 255, 4096] {
|
||||
let data: Vec<u8> = (0..len).map(|i| (i % 251) as u8).collect();
|
||||
let mut previous = vec![0];
|
||||
previous.extend(lz4_flex::block::compress(&data));
|
||||
assert_eq!(codec::compress(&data).unwrap(), previous);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_integer_decoder_rejects_unsupported_width_and_oversized_output() {
|
||||
assert!(codec::decode_ints(&[], 1, 3).is_err());
|
||||
assert!(codec::decode_ints(&[], super::MAX_DECODED_BYTES / 8 + 1, 8).is_err());
|
||||
assert!(codec::decode_ints(&[], 0, 4).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_crate_lz4_retains_chunk_and_budget_policy() {
|
||||
let mut frame = vec![2];
|
||||
for raw in [b"abc".as_slice(), b"def".as_slice()] {
|
||||
let block = lz4_flex::block::compress(raw);
|
||||
frame.extend((block.len() as i32).to_le_bytes());
|
||||
frame.extend(block);
|
||||
}
|
||||
frame.extend(b"old reader ignores this tail");
|
||||
assert_eq!(codec::decompress(&frame, 6).unwrap(), b"abcdef");
|
||||
assert!(codec::decompress(&frame, 5).is_err());
|
||||
assert!(codec::decompress(&[1, 255, 255, 255, 255], 64).is_err());
|
||||
assert!(codec::decompress(&[128], 64).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_usd_never_panics() {
|
||||
// A small two-material mesh keeps the byte loops fast.
|
||||
@@ -477,3 +509,10 @@ fn loose_layer_textures_are_packaged() {
|
||||
assert_eq!((f.name, f.bytes == out.bytes, f.warnings.len()), (format!("t.{ext}"), true, 1), "{ext}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_integer_writer_preserves_tie_wire_and_rejects_invalid_width() {
|
||||
assert_eq!(codec::encode_ints(&[1, 3, 4, 6], 4).unwrap(), vec![2, 0, 0, 0, 17, 1, 1]);
|
||||
assert!(codec::encode_ints(&[1], 3).is_err());
|
||||
assert!(codec::encode_ints(&[], 8).unwrap().is_empty());
|
||||
}
|
||||
@@ -660,7 +660,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn compressed_ints(out: &mut Vec<u8>, v: &[i64]) {
|
||||
let comp = codec::compress(&codec::encode_ints(v, 4));
|
||||
let comp = codec::compress(&codec::encode_ints(v, 4).unwrap()).unwrap();
|
||||
out.extend_from_slice(&(comp.len() as u64).to_le_bytes());
|
||||
out.extend_from_slice(&comp);
|
||||
}
|
||||
@@ -721,7 +721,7 @@ mod tests {
|
||||
compressed_ints(&mut b, &idx);
|
||||
let i64_at = b.len() as u64;
|
||||
b.extend_from_slice(&(n as u64).to_le_bytes());
|
||||
let comp = codec::compress(&codec::encode_ints(&(0..n as i64).map(|i| i << 33).collect::<Vec<_>>(), 8));
|
||||
let comp = codec::compress(&codec::encode_ints(&(0..n as i64).map(|i| i << 33).collect::<Vec<_>>(), 8).unwrap()).unwrap();
|
||||
b.extend_from_slice(&(comp.len() as u64).to_le_bytes());
|
||||
b.extend_from_slice(&comp);
|
||||
let c = crate_over(&b, (0, 8, 0));
|
||||
|
||||
@@ -13,14 +13,18 @@ impl LoadBudget {
|
||||
self.limit_bytes - self.used_bytes
|
||||
}
|
||||
|
||||
pub(super) fn exceeded_message(&self) -> String {
|
||||
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,
|
||||
)
|
||||
}
|
||||
|
||||
/// 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,
|
||||
));
|
||||
return Err(self.exceeded_message());
|
||||
}
|
||||
|
||||
self.used_bytes += bytes;
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,6 @@
|
||||
//! 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;
|
||||
@@ -31,21 +30,21 @@ 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";
|
||||
#[cfg(test)]
|
||||
const MAGIC: &[u8; 4] = b"TCTX";
|
||||
/// Version of the `.bin` layout.
|
||||
#[cfg(test)]
|
||||
const BIN_VERSION: u32 = 1;
|
||||
#[cfg(test)]
|
||||
const BIN_HEADER_BYTES: usize = 24;
|
||||
const MAX_JSON: u64 = 256 << 20;
|
||||
const MAX_THUMBNAIL: u64 = 64 << 20;
|
||||
@@ -124,6 +123,7 @@ fn zip_err(e: zip::result::ZipError) -> FormatError {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn header(w: u32, h: u32, comps: usize, count: usize) -> Vec<u8> {
|
||||
let mut b = MAGIC.to_vec();
|
||||
for v in [BIN_VERSION, w, h, comps as u32, count as u32] {
|
||||
@@ -132,19 +132,18 @@ fn header(w: u32, h: u32, comps: usize, count: usize) -> Vec<u8> {
|
||||
b
|
||||
}
|
||||
|
||||
fn write_tiles(w: &mut impl Write, img: &TileImage) -> std::io::Result<()> {
|
||||
w.write_all(&header(img.width(), img.height(), img.comps(), img.allocated_count()))?;
|
||||
let mut buf = Vec::with_capacity(TILE_AREA * img.comps() * 2 + 8);
|
||||
for (tx, ty) in img.allocated() {
|
||||
buf.clear();
|
||||
buf.extend_from_slice(&tx.to_le_bytes());
|
||||
buf.extend_from_slice(&ty.to_le_bytes());
|
||||
for v in img.tile(tx, ty).unwrap_or_default() {
|
||||
buf.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
w.write_all(&buf)?;
|
||||
fn codec_write_error(error: craft_tcraft::Error) -> std::io::Error {
|
||||
match error {
|
||||
craft_tcraft::Error::Io(error) => error,
|
||||
other => std::io::Error::other(other),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_tiles(w: &mut impl Write, img: &TileImage) -> std::io::Result<()> {
|
||||
let layout = craft_tcraft::Layout { width: img.width(), height: img.height(), components: img.comps() };
|
||||
let count = u32::try_from(img.allocated_count()).map_err(std::io::Error::other)?;
|
||||
let tiles = img.allocated().map(|(x, y)| (x, y, img.tile(x, y).unwrap_or_default()));
|
||||
craft_tcraft::write_tiles(w, layout, count, tiles).map_err(codec_write_error)
|
||||
}
|
||||
|
||||
/// Keep `[a-z0-9]`, at most 8 characters (the mesh entry's extension).
|
||||
@@ -169,18 +168,12 @@ fn unique_entry_name(dir: &str, name: &str, used: &mut HashSet<String>) -> Strin
|
||||
entry
|
||||
}
|
||||
|
||||
/// Floats converted to bytes at a time when a baked map streams into the compressor.
|
||||
#[cfg(test)]
|
||||
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(())
|
||||
let layout = craft_tcraft::Layout { width: res, height: h, components: comps };
|
||||
craft_tcraft::write_baked(w, layout, data).map_err(codec_write_error)
|
||||
}
|
||||
|
||||
/// The zip entries of a project file, in file order. Bodies run later, possibly on other threads.
|
||||
@@ -304,110 +297,34 @@ fn read_all(reader: &mut impl Read, cap: u64, budget: &mut LoadBudget, what: &st
|
||||
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}")))
|
||||
}
|
||||
|
||||
fn u32_at(b: &[u8], i: usize) -> u32 {
|
||||
b.get(i * 4..i * 4 + 4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// 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; 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")));
|
||||
}
|
||||
let v = u32_at(&h, 1);
|
||||
if v > BIN_VERSION {
|
||||
return Err(FormatError::NewerVersion { found: v, supported: BIN_VERSION });
|
||||
}
|
||||
Ok((u32_at(&h, 2), u32_at(&h, 3), u32_at(&h, 4) as usize, u32_at(&h, 5) as usize))
|
||||
}
|
||||
|
||||
/// Error unless the entry has no bytes left (also makes the zip reader verify the CRC).
|
||||
fn expect_end(r: &mut impl Read, what: &str) -> Result<()> {
|
||||
let mut b = [0u8; 1];
|
||||
match r.read(&mut b) {
|
||||
Ok(0) => Ok(()),
|
||||
Ok(_) => Err(malformed(KIND, format!("{what}: trailing data"))),
|
||||
Err(e) => Err(malformed(KIND, format!("{what}: {e}"))),
|
||||
}
|
||||
/// Transfer the bytes charged by the shared codec to this project's one load budget.
|
||||
fn codec_result<T>(result: std::result::Result<T, craft_tcraft::Error>, shared: &craft_zip::Budget, budget: &mut LoadBudget, what: &str) -> Result<T> {
|
||||
budget.take(shared.used()).map_err(FormatError::TooLarge)?;
|
||||
result.map_err(|error| match error {
|
||||
craft_tcraft::Error::Budget(_) => FormatError::TooLarge(budget.exceeded_message()),
|
||||
craft_tcraft::Error::Limit(message) => FormatError::TooLarge(format!("{what}: {message}")),
|
||||
craft_tcraft::Error::NewerVersion(found) => FormatError::NewerVersion { found, supported: craft_tcraft::VERSION },
|
||||
other => malformed(KIND, format!("{what}: {other}")),
|
||||
})
|
||||
}
|
||||
|
||||
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 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 bytes = vec![0u8; TILE_AREA * components * 2];
|
||||
let mut position_bytes = [0u8; 8];
|
||||
for _ in 0..count {
|
||||
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(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(reader, what)?;
|
||||
|
||||
Ok(image)
|
||||
let layout = craft_tcraft::Layout { width: size.0, height: size.1, components };
|
||||
let mut shared = craft_zip::Budget::new("project", budget.remaining());
|
||||
let mut image = None;
|
||||
let result = craft_tcraft::read_tiles(reader, layout, MAX_TEXELS, &mut shared, |x, y, values| {
|
||||
image.get_or_insert_with(|| TileImage::new(size.0, size.1, components)).set_tile(x, y, Some(Arc::new(values)));
|
||||
Ok(())
|
||||
});
|
||||
codec_result(result, &shared, budget, what)?;
|
||||
Ok(image.unwrap_or_else(|| TileImage::new(size.0, size.1, components)))
|
||||
}
|
||||
|
||||
/// A baked map: (width, height, data).
|
||||
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 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))
|
||||
let mut shared = craft_zip::Budget::new("project", budget.remaining());
|
||||
let result = craft_tcraft::read_baked(reader, declared_bytes, components, MAX_TEXELS, &mut shared);
|
||||
let (layout, values) = codec_result(result, &shared, budget, what)?;
|
||||
Ok((layout.width, layout.height, values))
|
||||
}
|
||||
|
||||
/// Texture set holding a paint layer, a content effect or a mask effect id.
|
||||
@@ -422,47 +339,31 @@ fn load<R: Read + Seek>(reader: R) -> Result<ProjectFile> {
|
||||
}
|
||||
|
||||
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")));
|
||||
}
|
||||
|
||||
// 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(())
|
||||
craft_zip::inspect_seekable(zip, MAX_ENTRIES, limit_bytes).map_err(|error| match error {
|
||||
craft_zip::InspectError::TooManyEntries { .. } => FormatError::TooLarge(format!("project file has more than {MAX_ENTRIES} entries")),
|
||||
craft_zip::InspectError::DeclaredBytesExceeded { .. } => FormatError::TooLarge(LoadBudget::new(limit_bytes).exceeded_message()),
|
||||
craft_zip::InspectError::OverlappingEntries => malformed(KIND, "overlapping ZIP entries are not supported"),
|
||||
craft_zip::InspectError::Zip(error) => zip_err(error),
|
||||
})
|
||||
}
|
||||
|
||||
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)?;
|
||||
fn open_archive<R: Read + Seek>(reader: R, metadata_bytes: u64) -> Result<ZipArchive<craft_zip::MetadataReader<R>>> {
|
||||
let (reader, indexing) = craft_zip::MetadataReader::new(reader, 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);
|
||||
indexing.finish();
|
||||
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)?;
|
||||
let mut zip = open_archive(reader, 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 {
|
||||
format_version: u32,
|
||||
}
|
||||
let v: Version = serde_json::from_slice(&json).map_err(|e| malformed(KIND, format!("project.json: {e}")))?;
|
||||
if v.format_version > FORMAT_VERSION {
|
||||
return Err(FormatError::NewerVersion { found: v.format_version, supported: FORMAT_VERSION });
|
||||
let version = craft_tcraft::project_version(&json).map_err(|e| malformed(KIND, format!("project.json: {e}")))?;
|
||||
if version > FORMAT_VERSION {
|
||||
return Err(FormatError::NewerVersion { found: version, supported: FORMAT_VERSION });
|
||||
}
|
||||
|
||||
let (project, mut recovered) = recovery::read_project(&json).map_err(|e| malformed(KIND, format!("project.json: {e}")))?;
|
||||
|
||||
@@ -82,6 +82,15 @@ fn round_trip_is_identical_and_deterministic() {
|
||||
assert_same(&builtin, &load_project_bytes(&save_project_bytes(&builtin).unwrap()).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_project_schema_round_trips_the_app_document() {
|
||||
let project = sample().pf.project;
|
||||
let original = serde_json::to_value(&project).unwrap();
|
||||
let document: craft_tcraft::ProjectDocument = serde_json::from_value(original.clone()).unwrap();
|
||||
assert_eq!(document.format_version, project.format_version);
|
||||
assert_eq!(serde_json::to_value(document).unwrap(), original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_bakes_load_as_is_without_layout_conversion() {
|
||||
let mut sample = sample();
|
||||
@@ -803,13 +812,17 @@ fn baked_dimensions_must_match_the_entry_before_reserving_payload_bytes() {
|
||||
#[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 bytes = header(values.len() as u32, 1, 1, 0);
|
||||
bytes.extend(values.iter().flat_map(|bits| bits.to_le_bytes()));
|
||||
let declared = bytes.len() as u64;
|
||||
let mut reader = Cursor::new(bytes);
|
||||
let mut budget = LoadBudget::new(declared);
|
||||
|
||||
let decoded = read_f32s(&mut reader, values.len(), "baked map").unwrap();
|
||||
let (_, _, decoded) = read_baked(&mut reader, declared, 1, &mut budget, "baked map").unwrap();
|
||||
|
||||
assert_eq!(decoded.into_iter().map(f32::to_bits).collect::<Vec<_>>(), values);
|
||||
assert_eq!(reader.position(), (values.len() * 4) as u64);
|
||||
assert_eq!(reader.position(), declared);
|
||||
assert_eq!(budget.remaining(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -818,23 +831,19 @@ fn archive_indexing_does_not_scan_large_payloads_and_rejects_large_metadata() {
|
||||
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 archive = open_archive(Cursor::new(bytes), 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");
|
||||
assert!(open_archive(Cursor::new(bytes), 4096).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -845,9 +854,8 @@ fn zip64_entry_counts_remain_supported_and_bounded() {
|
||||
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 mut archive = open_archive(Cursor::new(bytes), MAX_ZIP_METADATA_BYTES).unwrap();
|
||||
let result = check_archive(&mut archive, 0);
|
||||
|
||||
assert_eq!(archive.len(), count);
|
||||
|
||||
+96
-53
@@ -20,7 +20,7 @@ pub struct UvGBuffer {
|
||||
pub tri: Vec<u32>,
|
||||
/// Barycentric weights of the triangle's second and third vertices.
|
||||
pub bary: Vec<[f32; 2]>,
|
||||
/// Texels written by more than one triangle (overlapping UVs).
|
||||
/// Covers past the first on texels where any cover has the texel center strictly inside (overlapping UVs; an edge two neighbours share is no overlap)
|
||||
pub overlaps: u32,
|
||||
}
|
||||
|
||||
@@ -41,74 +41,95 @@ fn edge(a: Vec2, b: Vec2, p: Vec2) -> f32 {
|
||||
(b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x)
|
||||
}
|
||||
|
||||
/// Twice-areas (in texels²) below this are degenerate triangles, which cover nothing
|
||||
const MIN_DOUBLE_AREA: f32 = 1e-12;
|
||||
|
||||
/// How far outside a triangle (as a share of its double area) a texel center may sit and still count as covered, so shared edges leave no gaps
|
||||
const EDGE_TOLERANCE: f32 = 1e-6;
|
||||
|
||||
impl UvGBuffer {
|
||||
/// Rasterize the triangles of material `material` at `width × height`.
|
||||
/// Rasterize the triangles of material `material` at `width × height`
|
||||
pub fn new(mesh: &Mesh, material: usize, width: u32, height: u32) -> UvGBuffer {
|
||||
let (w, h) = (width.max(1), height.max(1));
|
||||
let size = Vec2::new(w as f32, h as f32);
|
||||
let bands = h.div_ceil(BAND) as usize;
|
||||
let mut bins: Vec<Vec<u32>> = vec![Vec::new(); bands];
|
||||
for t in mesh.triangles_of(material) {
|
||||
let Some([a, b, c]) = mesh.tri(t) else { continue };
|
||||
let (Some(ua), Some(ub), Some(uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue };
|
||||
let y0 = (ua.y.min(ub.y).min(uc.y) * size.y).floor().max(0.0) as i64;
|
||||
let y1 = (ua.y.max(ub.y).max(uc.y) * size.y).ceil().min(size.y) as i64;
|
||||
if y1 <= y0 || !ua.is_finite() || !ub.is_finite() || !uc.is_finite() {
|
||||
let (width, height) = (width.max(1), height.max(1));
|
||||
let size = Vec2::new(width as f32, height as f32);
|
||||
let corner_uvs = |triangle: usize| {
|
||||
let [first, second, third] = mesh.tri(triangle)?;
|
||||
Some([*mesh.uvs.get(first)?, *mesh.uvs.get(second)?, *mesh.uvs.get(third)?])
|
||||
};
|
||||
|
||||
// Sort triangles into bands of rows so each band rasterizes on its own thread
|
||||
let mut bands: Vec<Vec<u32>> = vec![Vec::new(); height.div_ceil(BAND) as usize];
|
||||
for triangle in mesh.triangles_of(material) {
|
||||
let Some(uvs) = corner_uvs(triangle) else { continue };
|
||||
let top = (uvs.iter().map(|uv| uv.y).fold(f32::INFINITY, f32::min) * size.y).floor().max(0.0) as i64;
|
||||
let bottom = (uvs.iter().map(|uv| uv.y).fold(f32::NEG_INFINITY, f32::max) * size.y).ceil().min(size.y) as i64;
|
||||
if bottom <= top || !uvs.iter().all(|uv| uv.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
let (b0, b1) = ((y0 / BAND as i64) as usize, ((y1 - 1).max(0) / BAND as i64) as usize);
|
||||
for bin in bins.iter_mut().take(b1 + 1).skip(b0) {
|
||||
bin.push(t as u32);
|
||||
|
||||
let (first_band, last_band) = ((top / BAND as i64) as usize, ((bottom - 1).max(0) / BAND as i64) as usize);
|
||||
for band in bands.iter_mut().take(last_band + 1).skip(first_band) {
|
||||
band.push(triangle as u32);
|
||||
}
|
||||
}
|
||||
let n = w as usize * h as usize;
|
||||
let mut tri = vec![NO_TRI; n];
|
||||
let mut bary = vec![[0.0f32; 2]; n];
|
||||
let band_len = (BAND * w) as usize;
|
||||
|
||||
let texel_count = width as usize * height as usize;
|
||||
let mut tri = vec![NO_TRI; texel_count];
|
||||
let mut bary = vec![[0.0f32; 2]; texel_count];
|
||||
let band_texels = (BAND * width) as usize;
|
||||
let overlaps: u32 = tri
|
||||
.par_chunks_mut(band_len)
|
||||
.zip(bary.par_chunks_mut(band_len))
|
||||
.par_chunks_mut(band_texels)
|
||||
.zip(bary.par_chunks_mut(band_texels))
|
||||
.enumerate()
|
||||
.map(|(bi, (tri, bary))| {
|
||||
let mut overlaps = 0u32;
|
||||
let row0 = bi as u32 * BAND;
|
||||
let rows = (tri.len() as u32) / w;
|
||||
for &t in bins.get(bi).map(Vec::as_slice).unwrap_or(&[]) {
|
||||
let Some([a, b, c]) = mesh.tri(t as usize) else { continue };
|
||||
let (Some(&ua), Some(&ub), Some(&uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue };
|
||||
let (pa, pb, pc) = (ua * size, ub * size, uc * size);
|
||||
let area = edge(pa, pb, pc);
|
||||
if area.abs() < 1e-12 {
|
||||
.map(|(band_index, (band_tri, band_bary))| {
|
||||
// Keep cover counts and strict interiors independent of triangle order
|
||||
let mut covers = vec![0u32; band_tri.len()];
|
||||
let mut strict_cover = vec![false; band_tri.len()];
|
||||
let first_row = band_index as u32 * BAND;
|
||||
let band_rows = (band_tri.len() as u32) / width;
|
||||
for &triangle in bands.get(band_index).map(Vec::as_slice).unwrap_or(&[]) {
|
||||
let Some(uvs) = corner_uvs(triangle as usize) else { continue };
|
||||
let [a, b, c] = uvs.map(|uv| uv * size);
|
||||
let double_area = edge(a, b, c);
|
||||
if double_area.abs() < MIN_DOUBLE_AREA {
|
||||
continue;
|
||||
}
|
||||
let eps = -1e-6 * area.abs();
|
||||
let x0 = pa.x.min(pb.x).min(pc.x).floor().max(0.0) as u32;
|
||||
let x1 = (pa.x.max(pb.x).max(pc.x).ceil().min(w as f32) as u32).min(w);
|
||||
let y0 = (pa.y.min(pb.y).min(pc.y).floor().max(row0 as f32) as u32).max(row0);
|
||||
let y1 = (pa.y.max(pb.y).max(pc.y).ceil() as u32).min(row0 + rows);
|
||||
for y in y0..y1 {
|
||||
for x in x0..x1 {
|
||||
let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5);
|
||||
let (w0, w1, w2) = (edge(pb, pc, p) * area.signum(), edge(pc, pa, p) * area.signum(), edge(pa, pb, p) * area.signum());
|
||||
if w0 < eps || w1 < eps || w2 < eps {
|
||||
|
||||
let tolerance = EDGE_TOLERANCE * double_area.abs();
|
||||
let (sign, inverse_area) = (double_area.signum(), 1.0 / double_area.abs());
|
||||
let left = a.x.min(b.x).min(c.x).floor().max(0.0) as u32;
|
||||
let right = (a.x.max(b.x).max(c.x).ceil().min(width as f32) as u32).min(width);
|
||||
let top = (a.y.min(b.y).min(c.y).floor().max(first_row as f32) as u32).max(first_row);
|
||||
let bottom = (a.y.max(b.y).max(c.y).ceil() as u32).min(first_row + band_rows);
|
||||
for y in top..bottom {
|
||||
for x in left..right {
|
||||
let center = Vec2::new(x as f32 + 0.5, y as f32 + 0.5);
|
||||
let weights = [edge(b, c, center) * sign, edge(c, a, center) * sign, edge(a, b, center) * sign];
|
||||
if weights.iter().any(|weight| *weight < -tolerance) {
|
||||
continue;
|
||||
}
|
||||
let i = ((y - row0) * w + x) as usize;
|
||||
if let (Some(slot), Some(bw)) = (tri.get_mut(i), bary.get_mut(i)) {
|
||||
if *slot != NO_TRI {
|
||||
overlaps += 1;
|
||||
}
|
||||
*slot = t;
|
||||
let inv = 1.0 / area.abs();
|
||||
*bw = [w1 * inv, w2 * inv];
|
||||
}
|
||||
|
||||
let index = ((y - first_row) * width + x) as usize;
|
||||
let (Some(slot), Some(slot_bary), Some(cover_count), Some(strict)) =
|
||||
(band_tri.get_mut(index), band_bary.get_mut(index), covers.get_mut(index), strict_cover.get_mut(index))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
|
||||
*cover_count += 1;
|
||||
*strict |= weights.iter().all(|weight| *weight > tolerance);
|
||||
*slot = triangle;
|
||||
*slot_bary = [weights[1] * inverse_area, weights[2] * inverse_area];
|
||||
}
|
||||
}
|
||||
}
|
||||
overlaps
|
||||
|
||||
// Every cover past the first overlaps, unless all of them only touch the texel center with an edge (neighbours sharing it)
|
||||
covers.iter().zip(&strict_cover).filter(|(_, strict)| **strict).map(|(count, _)| count.saturating_sub(1)).sum::<u32>()
|
||||
})
|
||||
.sum();
|
||||
UvGBuffer { width: w, height: h, tri, bary, overlaps }
|
||||
|
||||
UvGBuffer { width, height, tri, bary, overlaps }
|
||||
}
|
||||
|
||||
pub fn covered(&self, i: usize) -> bool {
|
||||
@@ -157,7 +178,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn half_triangle_covers_texels_with_centers_inside() {
|
||||
// One triangle covering the lower-left half of UV space (v down: y = v·H).
|
||||
// UV v increases down, so this triangle covers the lower-left half
|
||||
let m =
|
||||
Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y], None, vec![Vec2::new(0.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0)], vec![0, 1, 2], "m")
|
||||
.unwrap();
|
||||
@@ -171,6 +192,28 @@ mod tests {
|
||||
assert_eq!(g.overlaps, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neighbours_sharing_an_edge_through_texel_centers_do_not_overlap() {
|
||||
// An 8×8 grid of quads at 512 texels: each quad's diagonal runs through 64 texel centers
|
||||
let grid = primitives::plane(1.0, 8);
|
||||
let gbuffer = UvGBuffer::new(&grid, 0, 512, 512);
|
||||
assert_eq!(gbuffer.covered_count(), 512 * 512);
|
||||
assert_eq!(gbuffer.overlaps, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edge_through_a_covered_texel_center_counts_both_edge_covers() {
|
||||
// The texel center (0.5, 0.5) lies inside the first triangle and on the diagonal the other two share
|
||||
let uv = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.2), Vec2::new(0.2, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0)];
|
||||
let positions = vec![Vec3::ZERO; uv.len()];
|
||||
|
||||
// In either order: the inside cover first, or the two edge covers first
|
||||
for indices in [vec![0, 1, 2, 0, 3, 4, 0, 5, 3], vec![0, 3, 4, 0, 5, 3, 0, 1, 2]] {
|
||||
let m = Mesh::from_parts(positions.clone(), None, uv.clone(), indices.clone(), "m").unwrap();
|
||||
assert_eq!(UvGBuffer::new(&m, 0, 1, 1).overlaps, 2, "{indices:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_and_degenerate_triangles() {
|
||||
let uv = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(0.5, 0.5)];
|
||||
|
||||
+82
-59
@@ -7,6 +7,9 @@ use crate::{GeomError, Result};
|
||||
/// An edge by the bits of its two end positions, the lower one first
|
||||
type EdgePositions = ([u32; 3], [u32; 3]);
|
||||
|
||||
/// Normals closer than about one degree are the same normal: the edge between them is smooth
|
||||
const SAME_NORMAL_MIN_COSINE: f32 = 0.9998;
|
||||
|
||||
/// A contiguous index range drawn with one material.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SubMesh {
|
||||
@@ -85,36 +88,37 @@ impl Mesh {
|
||||
/// split it from its twin), per material in `0..materials.len().max(1)`.
|
||||
pub fn wire_edges(&self) -> Vec<Vec<(u32, u32)>> {
|
||||
(0..self.materials.len().max(1))
|
||||
.map(|m| {
|
||||
// Edge → (real in some triangle, triangles using it), in first-seen order.
|
||||
.map(|material| {
|
||||
// Keep first-seen edge order while counting its triangle uses
|
||||
let mut edges: Vec<((u32, u32), bool, u8)> = Vec::new();
|
||||
let mut at: std::collections::HashMap<(u32, u32), usize> = std::collections::HashMap::new();
|
||||
for t in self.triangles_of(m) {
|
||||
let Some(v) = self.indices.get(t * 3..t * 3 + 3) else { continue };
|
||||
let hidden = self.diagonals.get(t).copied().unwrap_or(0);
|
||||
for (i, (a, b)) in [(v[0], v[1]), (v[1], v[2]), (v[2], v[0])].into_iter().enumerate() {
|
||||
let key = (a.min(b), a.max(b));
|
||||
let real = hidden >> i & 1 == 0;
|
||||
let e = *at.entry(key).or_insert_with(|| {
|
||||
let mut edge_indices: std::collections::HashMap<(u32, u32), usize> = std::collections::HashMap::new();
|
||||
for triangle in self.triangles_of(material) {
|
||||
let Some(vertices) = self.indices.get(triangle * 3..triangle * 3 + 3) else { continue };
|
||||
let hidden = self.diagonals.get(triangle).copied().unwrap_or(0);
|
||||
for (side, (from, to)) in [(vertices[0], vertices[1]), (vertices[1], vertices[2]), (vertices[2], vertices[0])].into_iter().enumerate() {
|
||||
let key = (from.min(to), from.max(to));
|
||||
let is_polygon_edge = hidden >> side & 1 == 0;
|
||||
let edge_index = *edge_indices.entry(key).or_insert_with(|| {
|
||||
edges.push((key, false, 0));
|
||||
edges.len() - 1
|
||||
});
|
||||
if let Some((_, r, n)) = edges.get_mut(e) {
|
||||
*r |= real;
|
||||
*n = n.saturating_add(1);
|
||||
if let Some((_, edge_is_polygon_side, triangle_count)) = edges.get_mut(edge_index) {
|
||||
*edge_is_polygon_side |= is_polygon_edge;
|
||||
*triangle_count = triangle_count.saturating_add(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
edges.into_iter().filter(|(_, real, n)| *real || *n == 1).map(|(k, ..)| k).collect()
|
||||
edges.into_iter().filter(|(_, is_polygon_edge, triangle_count)| *is_polygon_edge || *triangle_count == 1).map(|(edge, ..)| edge).collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)`
|
||||
pub fn uv_seam_edges(&self) -> Vec<Vec<(u32, u32)>> {
|
||||
/// Hard edges the UV layout does not split, which bake visible lines into the normal map: two triangles meet there with different normals but the same UVs, per material in `0..materials.len().max(1)`
|
||||
pub fn missing_seam_edges(&self) -> Vec<Vec<(u32, u32)>> {
|
||||
// Signed zero denotes the same position on either side of an imported seam
|
||||
let bits = |position: Vec3| position.to_array().map(|coordinate| if coordinate == 0.0 { 0 } else { coordinate.to_bits() });
|
||||
let mut seams = vec![Vec::new(); self.materials.len().max(1)];
|
||||
|
||||
// Match across materials before grouping the lines for texture-set visibility
|
||||
let mut sides: std::collections::HashMap<EdgePositions, Vec<(u32, u32, usize)>> = std::collections::HashMap::new();
|
||||
for material in 0..seams.len() {
|
||||
@@ -132,10 +136,19 @@ impl Mesh {
|
||||
}
|
||||
|
||||
let uv = |index: u32| self.uvs.get(index as usize).copied();
|
||||
|
||||
// Imported normals need not be unit length; two missing normals agree
|
||||
let direction = |index: u32| self.normals.get(index as usize).map_or(Vec3::ZERO, |normal| normal.normalize_or_zero());
|
||||
let same_normal = |a: u32, b: u32| {
|
||||
let (a, b) = (direction(a), direction(b));
|
||||
a == b || a.dot(b) >= SAME_NORMAL_MIN_COSINE
|
||||
};
|
||||
for pairs in sides.into_values() {
|
||||
let Some(&(first_from, first_to, _)) = pairs.first() else { continue };
|
||||
|
||||
if pairs.iter().any(|&(from, to, _)| (uv(from), uv(to)) != (uv(first_from), uv(first_to))) {
|
||||
let uv_split = pairs.iter().any(|&(from, to, _)| (uv(from), uv(to)) != (uv(first_from), uv(first_to)));
|
||||
let hard = pairs.iter().any(|&(from, to, _)| !same_normal(from, first_from) || !same_normal(to, first_to));
|
||||
if hard && !uv_split {
|
||||
for (from, to, material) in pairs {
|
||||
if let Some(edges) = seams.get_mut(material) {
|
||||
edges.push((from.min(to), from.max(to)));
|
||||
@@ -471,67 +484,77 @@ mod tests {
|
||||
fn wire_edges_leave_out_polygon_diagonals() {
|
||||
let mut m = quad();
|
||||
assert_eq!(m.wire_edges(), vec![vec![(0, 1), (1, 2), (0, 2), (2, 3), (0, 3)]], "triangles show every edge");
|
||||
// Edge 2 of (0, 1, 2) and edge 0 of (0, 2, 3) split the quad.
|
||||
|
||||
// Hide the quad's shared diagonal
|
||||
m.diagonals = vec![0b100, 0b001];
|
||||
assert_eq!(m.wire_edges(), vec![vec![(0, 1), (1, 2), (2, 3), (0, 3)]]);
|
||||
// A diagonal whose twin a seam split off (vertex 4 copies vertex 0) stays.
|
||||
|
||||
// Keep the diagonal when a seam splits its twin
|
||||
let mut seam = m.clone();
|
||||
seam.indices[3] = 4;
|
||||
assert_eq!(seam.wire_edges()[0].len(), 6);
|
||||
// Appending keeps each side's diagonals on its own triangles.
|
||||
|
||||
// Appending preserves each side's own diagonals
|
||||
let mut a = Mesh::from_parts(m.positions.clone(), None, m.uvs.clone(), vec![0, 1, 2], "A").unwrap();
|
||||
a.append(&m);
|
||||
assert_eq!(a.diagonals, vec![0, 0b100, 0b001]);
|
||||
assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_seams_are_where_the_uv_layout_splits() {
|
||||
let mesh = quad();
|
||||
assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()], "one UV island has no seam");
|
||||
|
||||
// Vertex 4 copies vertex 0's position with another UV: the diagonal (0, 2) / (4, 2) is cut
|
||||
let mut seam = mesh.clone();
|
||||
seam.positions.push(seam.positions[0]);
|
||||
seam.normals.push(seam.normals[0]);
|
||||
seam.tangents.push(seam.tangents[0]);
|
||||
seam.uvs.push(Vec2::new(0.9, 0.9));
|
||||
seam.indices[3] = 4;
|
||||
assert_eq!(seam.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]);
|
||||
|
||||
// The same split with the same UV is a hard edge, not a seam
|
||||
let mut hard = seam.clone();
|
||||
hard.uvs[4] = hard.uvs[0];
|
||||
assert_eq!(hard.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_seams_join_positions_with_opposite_signed_zero() {
|
||||
let mut mesh = quad();
|
||||
mesh.positions.push(Vec3::new(-0.0, 0.0, 0.0));
|
||||
mesh.normals.push(mesh.normals[0]);
|
||||
mesh.tangents.push(mesh.tangents[0]);
|
||||
mesh.uvs.push(Vec2::new(0.9, 0.9));
|
||||
mesh.indices[3] = 4;
|
||||
assert_eq!(mesh.positions[0], mesh.positions[4]);
|
||||
assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_seams_between_materials_belong_to_both_materials() {
|
||||
/// `quad` with vertex 4 a copy of vertex 0 at `uv` with `normal`, used by the second triangle: the diagonal (0, 2) / (4, 2) has two sides
|
||||
fn split_quad(uv: Vec2, normal: Vec3) -> Mesh {
|
||||
let mut mesh = quad();
|
||||
mesh.positions.push(mesh.positions[0]);
|
||||
mesh.normals.push(mesh.normals[0]);
|
||||
mesh.normals.push(normal);
|
||||
mesh.tangents.push(mesh.tangents[0]);
|
||||
mesh.uvs.push(Vec2::new(0.9, 0.9));
|
||||
mesh.uvs.push(uv);
|
||||
mesh.indices[3] = 4;
|
||||
mesh
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_seams_are_hard_edges_the_uv_layout_does_not_split() {
|
||||
let none = vec![Vec::<(u32, u32)>::new()];
|
||||
assert_eq!(quad().missing_seam_edges(), none, "a smooth quad has no hard edge");
|
||||
|
||||
let shared_uv = quad().uvs[0];
|
||||
let smooth_split = split_quad(shared_uv, Vec3::Z);
|
||||
assert_eq!(smooth_split.missing_seam_edges(), none, "the same normal on both sides is a smooth edge");
|
||||
|
||||
let hard = split_quad(shared_uv, Vec3::new(1.0, 0.0, 1.0).normalize());
|
||||
assert_eq!(hard.missing_seam_edges(), vec![vec![(0, 2), (2, 4)]], "a hard edge inside one UV island");
|
||||
|
||||
let seamed = split_quad(Vec2::new(0.9, 0.9), hard.normals[4]);
|
||||
assert_eq!(seamed.missing_seam_edges(), none, "a hard edge on a UV seam is fine");
|
||||
|
||||
let mut short_normals = quad();
|
||||
short_normals.normals.iter_mut().for_each(|normal| *normal *= 0.5);
|
||||
assert_eq!(short_normals.missing_seam_edges(), none, "normals shorter than unit length point the same way");
|
||||
assert_eq!(split_quad(shared_uv, Vec3::Z * 0.5).missing_seam_edges(), none, "normals of different lengths point the same way");
|
||||
|
||||
let mut no_normals = quad();
|
||||
no_normals.normals.fill(Vec3::ZERO);
|
||||
assert_eq!(no_normals.missing_seam_edges(), none, "two missing normals agree");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_seams_join_positions_with_opposite_signed_zero() {
|
||||
let mut mesh = split_quad(quad().uvs[0], Vec3::X);
|
||||
mesh.positions[4] = Vec3::new(-0.0, 0.0, 0.0);
|
||||
assert_eq!(mesh.positions[0], mesh.positions[4]);
|
||||
assert_eq!(mesh.missing_seam_edges(), vec![vec![(0, 2), (2, 4)]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_seams_between_materials_belong_to_both_materials() {
|
||||
let mut mesh = split_quad(quad().uvs[0], Vec3::X);
|
||||
mesh.materials.push("second".into());
|
||||
mesh.submeshes[0].count = 3;
|
||||
mesh.submeshes.push(SubMesh { name: "second".into(), material: 1, start: 3, count: 3 });
|
||||
|
||||
assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2)], vec![(2, 4)]]);
|
||||
mesh.uvs[4] = mesh.uvs[0];
|
||||
assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new(); 2], "a material boundary alone is not a UV seam");
|
||||
assert_eq!(mesh.missing_seam_edges(), vec![vec![(0, 2)], vec![(2, 4)]]);
|
||||
mesh.normals[4] = mesh.normals[0];
|
||||
assert_eq!(mesh.missing_seam_edges(), vec![Vec::<(u32, u32)>::new(); 2], "a material boundary alone is not a hard edge");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -19,6 +19,7 @@ bytemuck = { workspace = true }
|
||||
half = { workspace = true }
|
||||
log = { workspace = true }
|
||||
rayon = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
pollster = "0.4"
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
//! One overlay of bake mode's 3D view: whether it shows, its color and its opacity
|
||||
|
||||
/// Whether a part of the bake setup shows in the 3D view, and in which color and opacity
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct BakeOverlay {
|
||||
pub shown: bool,
|
||||
/// Linear RGB
|
||||
pub color: [f32; 3],
|
||||
/// 0 transparent, 1 opaque; the matching error mixes into the high poly by it
|
||||
pub opacity: f32,
|
||||
}
|
||||
|
||||
impl BakeOverlay {
|
||||
/// A hidden overlay in `color`, fully opaque
|
||||
pub const fn hidden(color: [f32; 3]) -> Self {
|
||||
Self { shown: false, color, opacity: 1.0 }
|
||||
}
|
||||
|
||||
/// The overlay's shader globals: rgb its color, a its opacity (0 while hidden)
|
||||
pub(crate) fn globals(&self) -> [f32; 4] {
|
||||
let [red, green, blue] = self.color;
|
||||
[red, green, blue, if self.shown { self.opacity.clamp(0.0, 1.0) } else { 0.0 }]
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,58 @@
|
||||
//! What bake mode's 3D view draws while a bake is set up: the high poly, the cage, the UV seams and the low poly
|
||||
//! What bake mode's 3D view draws while a bake is set up: the high poly, the cage, the missing seams and the low poly
|
||||
|
||||
/// Which parts of the bake setup the 3D view draws
|
||||
use crate::bake_overlay::BakeOverlay;
|
||||
use crate::neutral_material::NeutralMaterial;
|
||||
|
||||
/// Default overlay colors, linear RGB
|
||||
const HIGH_POLY_COLOR: [f32; 3] = [0.0, 0.216, 0.521];
|
||||
const MATCHING_ERROR_COLOR: [f32; 3] = [1.0, 0.0, 0.0];
|
||||
const CAGE_SURFACE_COLOR: [f32; 3] = [0.604, 0.451, 0.216];
|
||||
const CAGE_WIRE_COLOR: [f32; 3] = [0.604, 0.604, 0.604];
|
||||
const MISSING_SEAM_COLOR: [f32; 3] = [0.451, 0.0, 0.451];
|
||||
const LOW_POLY_COLOR: [f32; 3] = [0.216, 0.216, 0.216];
|
||||
|
||||
/// Which parts of the bake setup the 3D view draws, and how
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct BakeVisualization {
|
||||
pub high_poly: bool,
|
||||
pub cage: bool,
|
||||
pub uv_seams: bool,
|
||||
pub low_poly: bool,
|
||||
/// Draw the cage, seams and low poly of only this texture set
|
||||
pub high_poly: BakeOverlay,
|
||||
/// Tints the high poly where the bake's rays miss it
|
||||
pub matching_error: BakeOverlay,
|
||||
pub cage_surface: BakeOverlay,
|
||||
pub cage_wire: BakeOverlay,
|
||||
/// The low poly's hard edges that are not UV seams
|
||||
pub missing_seams: BakeOverlay,
|
||||
/// The low poly; its color is the neutral material's color
|
||||
pub low_poly: BakeOverlay,
|
||||
/// Shade the low poly with this plain material instead of its painted one
|
||||
pub neutral: Option<NeutralMaterial>,
|
||||
/// Draw the cage and high poly of only this texture set (the high poly's vertices of other sets come marked hidden)
|
||||
pub only_set: Option<usize>,
|
||||
}
|
||||
|
||||
impl Default for BakeVisualization {
|
||||
/// Every part hidden, in its default color, the low poly with its painted material
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
high_poly: BakeOverlay::hidden(HIGH_POLY_COLOR),
|
||||
matching_error: BakeOverlay::hidden(MATCHING_ERROR_COLOR),
|
||||
cage_surface: BakeOverlay::hidden(CAGE_SURFACE_COLOR),
|
||||
cage_wire: BakeOverlay::hidden(CAGE_WIRE_COLOR),
|
||||
missing_seams: BakeOverlay::hidden(MISSING_SEAM_COLOR),
|
||||
low_poly: BakeOverlay::hidden(LOW_POLY_COLOR),
|
||||
neutral: None,
|
||||
only_set: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BakeVisualization {
|
||||
/// Whether any part of the cage shows
|
||||
pub fn cage_shown(&self) -> bool {
|
||||
self.cage_surface.shown || self.cage_wire.shown
|
||||
}
|
||||
|
||||
/// The neutral material while the low poly shows with it
|
||||
pub fn shown_neutral(&self) -> Option<NeutralMaterial> {
|
||||
self.neutral.filter(|_| self.low_poly.shown)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
//! A texture set's cage as the renderer takes it
|
||||
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
|
||||
/// A cage for [`crate::Renderer::set_bake_cage`]: three corners per low-poly triangle, and lines as corner pairs
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct CageGeometry<'a> {
|
||||
pub corners: &'a [Vec3],
|
||||
/// The low poly's polygon edges, for the wireframe
|
||||
pub edges: &'a [[u32; 2]],
|
||||
/// The low poly's hard edges without a UV seam
|
||||
pub missing_seams: &'a [[u32; 2]],
|
||||
}
|
||||
@@ -6,4 +6,7 @@ pub(crate) struct CageGpu {
|
||||
pub(crate) corner_count: u32,
|
||||
pub(crate) edges: wgpu::Buffer,
|
||||
pub(crate) edge_index_count: u32,
|
||||
/// Corner pairs along the low poly's hard edges without a UV seam
|
||||
pub(crate) missing_seams: wgpu::Buffer,
|
||||
pub(crate) missing_seam_index_count: u32,
|
||||
}
|
||||
@@ -13,7 +13,9 @@
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod bake_overlay;
|
||||
pub mod bake_visualization;
|
||||
pub mod cage_geometry;
|
||||
mod cage_gpu;
|
||||
pub mod displace;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -24,15 +26,19 @@ pub mod headless;
|
||||
mod high_poly_gpu;
|
||||
pub mod ibl;
|
||||
pub mod mesh_maps;
|
||||
mod missing_seam_gpu;
|
||||
pub mod neutral_material;
|
||||
pub mod overlay_quad;
|
||||
pub mod readback;
|
||||
pub mod renderer;
|
||||
pub mod set_highlight;
|
||||
mod subdivide;
|
||||
pub mod trace;
|
||||
mod uv_seam_gpu;
|
||||
|
||||
pub use bake_overlay::BakeOverlay;
|
||||
pub use bake_visualization::BakeVisualization;
|
||||
pub use cage_geometry::CageGeometry;
|
||||
pub use neutral_material::NeutralMaterial;
|
||||
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;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/// The low poly's UV seams as a line list over its vertex buffer
|
||||
pub(crate) struct UvSeamGpu {
|
||||
/// The low poly's hard edges without a UV seam, as a line list over its vertex buffer
|
||||
pub(crate) struct MissingSeamGpu {
|
||||
/// The low-poly mesh the lines belong to
|
||||
pub(crate) mesh_id: u64,
|
||||
pub(crate) lines: wgpu::Buffer,
|
||||
@@ -0,0 +1,75 @@
|
||||
//! The plain material bake mode can show the low poly with, so the bake reads without the painted colours
|
||||
|
||||
/// The highest Quality: reflection samples per pixel
|
||||
pub const MAX_SAMPLES_PER_PIXEL: u32 = 256;
|
||||
|
||||
/// A plain material for the low poly in bake mode: its color comes from the low poly's overlay; its normal and occlusion are the texture set's as shown (the bake under any painted normal, height or AO)
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct NeutralMaterial {
|
||||
pub roughness: f32,
|
||||
pub metallic: f32,
|
||||
/// How much the texture set's ambient occlusion (baked × painted) darkens the material (0 none, 1 fully)
|
||||
pub ao_intensity: f32,
|
||||
/// Environment reflection samples per pixel, taken by every frame so a moving view looks like a still one
|
||||
pub samples_per_pixel: u32,
|
||||
/// Light the material along the baked bent normal: the open direction above each point
|
||||
pub bent_normal: bool,
|
||||
/// How far the diffuse light turns to the bent normal, and how much reflections facing away from it dim (0..1)
|
||||
pub bent_normal_diffuse: f32,
|
||||
pub bent_normal_specular: f32,
|
||||
}
|
||||
|
||||
impl Default for NeutralMaterial {
|
||||
/// Low quality (16 samples per pixel), a slightly rough half metal, most of the baked occlusion, no bent normal
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
roughness: 0.3,
|
||||
metallic: 0.6,
|
||||
ao_intensity: 0.75,
|
||||
samples_per_pixel: 16,
|
||||
bent_normal: false,
|
||||
bent_normal_diffuse: 1.0,
|
||||
bent_normal_specular: 1.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NeutralMaterial {
|
||||
/// The material's shader globals: x roughness, y metallic, z AO intensity, w 1 (on)
|
||||
pub(crate) fn globals(&self) -> [f32; 4] {
|
||||
[self.roughness, self.metallic, self.ao_intensity, 1.0]
|
||||
}
|
||||
|
||||
/// Reflection samples each frame takes: the whole quality, from 1 to [`MAX_SAMPLES_PER_PIXEL`] (a damaged settings file can't stall the GPU)
|
||||
pub(crate) fn samples_per_frame(&self) -> u32 {
|
||||
self.samples_per_pixel.clamp(1, MAX_SAMPLES_PER_PIXEL)
|
||||
}
|
||||
|
||||
/// The bent normal's shader globals: x diffuse amount, y specular amount (both 0 while off), zw -
|
||||
pub(crate) fn bent_normal_globals(&self) -> [f32; 4] {
|
||||
if self.bent_normal { [self.bent_normal_diffuse, self.bent_normal_specular, 0.0, 0.0] } else { [0.0; 4] }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_frame_takes_the_whole_quality() {
|
||||
let quality = |samples_per_pixel| NeutralMaterial { samples_per_pixel, ..NeutralMaterial::default() };
|
||||
assert_eq!(quality(16).samples_per_frame(), 16);
|
||||
assert_eq!(quality(256).samples_per_frame(), 256);
|
||||
assert_eq!(quality(u32::MAX).samples_per_frame(), MAX_SAMPLES_PER_PIXEL, "a damaged file is held to the highest quality");
|
||||
assert_eq!(quality(0).samples_per_frame(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bent_normal_reaches_the_shader_only_when_on() {
|
||||
let off = NeutralMaterial::default();
|
||||
assert_eq!(off.bent_normal_globals(), [0.0; 4]);
|
||||
let on = NeutralMaterial { bent_normal: true, bent_normal_diffuse: 0.5, bent_normal_specular: 0.25, ..off };
|
||||
assert_eq!(on.bent_normal_globals(), [0.5, 0.25, 0.0, 0.0]);
|
||||
}
|
||||
}
|
||||
+148
-62
@@ -31,14 +31,15 @@ use texturecraft_geom::{Mesh, OrbitCamera};
|
||||
use texturecraft_texel::TILE;
|
||||
|
||||
use crate::bake_visualization::BakeVisualization;
|
||||
use crate::cage_geometry::CageGeometry;
|
||||
use crate::cage_gpu::CageGpu;
|
||||
use crate::gpu_trace::{Checked, checked};
|
||||
use crate::high_poly_gpu::HighPolyGpu;
|
||||
use crate::ibl;
|
||||
use crate::missing_seam_gpu::MissingSeamGpu;
|
||||
use crate::overlay_quad::OverlayQuad;
|
||||
use crate::set_highlight::SetHighlight;
|
||||
use crate::subdivide::{self, Vertex};
|
||||
use crate::uv_seam_gpu::UvSeamGpu;
|
||||
|
||||
pub const MSAA: u32 = 4;
|
||||
pub const COLOR_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
|
||||
@@ -84,6 +85,14 @@ struct GlobalsRaw {
|
||||
refr: [f32; 4],
|
||||
highlight: [f32; 4],
|
||||
highlight_shift: [f32; 4],
|
||||
bake_high: [f32; 4],
|
||||
bake_matching_error: [f32; 4],
|
||||
bake_cage: [f32; 4],
|
||||
bake_cage_wire: [f32; 4],
|
||||
bake_missing_seam: [f32; 4],
|
||||
bake_neutral_color: [f32; 4],
|
||||
bake_neutral: [f32; 4],
|
||||
bake_bent_normal: [f32; 4],
|
||||
}
|
||||
|
||||
/// The post pass uniform (see `Post` in post.wgsl).
|
||||
@@ -548,7 +557,10 @@ pub struct Renderer {
|
||||
bake_high_pipeline: wgpu::RenderPipeline,
|
||||
cage_pipeline: wgpu::RenderPipeline,
|
||||
cage_wire_pipeline: wgpu::RenderPipeline,
|
||||
uv_seam_pipeline: wgpu::RenderPipeline,
|
||||
missing_seam_pipeline: wgpu::RenderPipeline,
|
||||
/// The missing seams along the cage, and in the 2D view
|
||||
cage_missing_seam_pipeline: wgpu::RenderPipeline,
|
||||
uv_missing_seam_pipeline: wgpu::RenderPipeline,
|
||||
bg_pipeline: wgpu::RenderPipeline,
|
||||
blit_pipeline: wgpu::RenderPipeline,
|
||||
post_pipeline: wgpu::RenderPipeline,
|
||||
@@ -585,7 +597,7 @@ pub struct Renderer {
|
||||
bake_high: Option<HighPolyGpu>,
|
||||
/// Each texture set's cage, by set index
|
||||
cages: Vec<Option<CageGpu>>,
|
||||
uv_seams: Option<UvSeamGpu>,
|
||||
missing_seams: Option<MissingSeamGpu>,
|
||||
sets: Vec<SetGpu>,
|
||||
/// Viewport texture resolution: display textures at 1/2^shift of each set's size (at least
|
||||
/// as reduced as the device's texture limit needs).
|
||||
@@ -872,8 +884,10 @@ impl Renderer {
|
||||
fragment_entry(4, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison)),
|
||||
],
|
||||
);
|
||||
|
||||
// The display textures, the aux texture, the sampler
|
||||
let textures = DisplayKind::ALL.len() as u32 + 1;
|
||||
|
||||
// Displacement reads the height (and the sampler) in the vertex shader
|
||||
let height = DisplayKind::ALL.iter().position(|kind| *kind == DisplayKind::Height).unwrap_or(0) as u32;
|
||||
let set_entries: Vec<_> = (0..textures)
|
||||
@@ -910,7 +924,7 @@ impl Renderer {
|
||||
attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Float32x4, 3 => Float32x2],
|
||||
})];
|
||||
|
||||
// shortcut: the RGBA8 fallback clips highlights above 1 and bands in the darks; encode (e.g. RGBM) if WebGL2 without float color buffers turns out to matter
|
||||
// RGBA8 fallback clips bright highlights and dark gradients
|
||||
let hdr_format = if hdr_renderable(device) { HDR_FORMAT } else { COLOR_FORMAT };
|
||||
let hdr_target = |fragment_entry_point, blend| Some((fragment_entry_point, hdr_format, blend));
|
||||
let always = || Some(depth_state(false, wgpu::CompareFunction::Always));
|
||||
@@ -1001,8 +1015,30 @@ impl Renderer {
|
||||
MSAA,
|
||||
wire3d_depth.clone(),
|
||||
);
|
||||
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 cage_missing_seam_pipeline = pipeline(
|
||||
device,
|
||||
"tc_cage_missing_seam",
|
||||
&background_layout,
|
||||
&module,
|
||||
"vs_bake_cage_wire",
|
||||
&corner_layout,
|
||||
hdr_target("fs_wire_cage_missing_seam", blend),
|
||||
MSAA,
|
||||
wire3d_depth.clone(),
|
||||
);
|
||||
let uv_missing_seam_pipeline =
|
||||
pipeline(device, "tc_uv_missing_seam", &layout, &module, "vs_uv", &vertex_layout, hdr_target("fs_wire_missing_seam", blend), MSAA, always());
|
||||
let missing_seam_pipeline = pipeline(
|
||||
device,
|
||||
"tc_missing_seam",
|
||||
&layout,
|
||||
&module,
|
||||
"vs_wire3d",
|
||||
&vertex_layout,
|
||||
hdr_target("fs_wire_missing_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);
|
||||
@@ -1135,7 +1171,9 @@ impl Renderer {
|
||||
bake_high_pipeline,
|
||||
cage_pipeline,
|
||||
cage_wire_pipeline,
|
||||
uv_seam_pipeline,
|
||||
missing_seam_pipeline,
|
||||
cage_missing_seam_pipeline,
|
||||
uv_missing_seam_pipeline,
|
||||
bg_pipeline,
|
||||
blit_pipeline,
|
||||
post_pipeline,
|
||||
@@ -1162,7 +1200,7 @@ impl Renderer {
|
||||
mesh: None,
|
||||
bake_high: None,
|
||||
cages: Vec::new(),
|
||||
uv_seams: None,
|
||||
missing_seams: None,
|
||||
sets: Vec::new(),
|
||||
display_shift: 0,
|
||||
material_sets: Vec::new(),
|
||||
@@ -1223,6 +1261,7 @@ impl Renderer {
|
||||
if self.mesh.as_ref().is_some_and(|m| m.id == id) {
|
||||
return;
|
||||
}
|
||||
|
||||
let verts = subdivide::vertices(mesh);
|
||||
let mk = |label: &str, data: &[u8], usage: wgpu::BufferUsages| upload_buffer(device, queue, label, data, usage);
|
||||
let mut idx_bytes = bytemuck::cast_slice::<u32, u8>(&mesh.indices).to_vec();
|
||||
@@ -1230,7 +1269,8 @@ impl Renderer {
|
||||
let vb = mk("tc_vb", bytemuck::cast_slice(&verts), wgpu::BufferUsages::VERTEX);
|
||||
let ib = mk("tc_ib", &idx_bytes, wgpu::BufferUsages::INDEX);
|
||||
let draws: Vec<(u32, u32, usize)> = mesh.submeshes.iter().map(|s| (s.start, s.count, s.material)).collect();
|
||||
// Mesh edges per material (polygons, not their triangles), for the wireframes.
|
||||
|
||||
// Use polygon edges for each material's wireframe
|
||||
let mut line_idx: Vec<u32> = Vec::new();
|
||||
let mut line_draws = Vec::new();
|
||||
for (m, edges) in mesh.wire_edges().into_iter().enumerate() {
|
||||
@@ -1289,8 +1329,8 @@ impl Renderer {
|
||||
self.content_rev += 1;
|
||||
}
|
||||
|
||||
/// Texture set `texture_set`'s cage: `corners` three per triangle and `edges` as corner pairs; `None` removes it. The same `topology` as before only rewrites the corners
|
||||
pub fn set_bake_cage(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, texture_set: usize, cage: Option<(&[Vec3], &[[u32; 2]])>, topology: u64) {
|
||||
/// Texture set `texture_set`'s cage; `None` removes it. The same `topology` as before only rewrites the corners
|
||||
pub fn set_bake_cage(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, texture_set: usize, cage: Option<CageGeometry<'_>>, topology: u64) {
|
||||
if self.cages.len() <= texture_set {
|
||||
self.cages.resize_with(texture_set + 1, || None);
|
||||
}
|
||||
@@ -1298,16 +1338,18 @@ impl Renderer {
|
||||
|
||||
match (cage, slot.as_mut()) {
|
||||
(None, _) => *slot = None,
|
||||
(Some((corners, _)), Some(gpu)) if gpu.topology == topology && gpu.corner_count as usize == corners.len() => {
|
||||
queue.write_buffer(&gpu.corners, 0, bytemuck::cast_slice(corners));
|
||||
(Some(cage), Some(gpu)) if gpu.topology == topology && gpu.corner_count as usize == cage.corners.len() => {
|
||||
queue.write_buffer(&gpu.corners, 0, bytemuck::cast_slice(cage.corners));
|
||||
}
|
||||
(Some((corners, edges)), _) => {
|
||||
(Some(cage), _) => {
|
||||
*slot = Some(CageGpu {
|
||||
topology,
|
||||
corners: upload_buffer(device, queue, "tc_cage_vb", bytemuck::cast_slice(corners), wgpu::BufferUsages::VERTEX),
|
||||
corner_count: corners.len() as u32,
|
||||
edges: upload_buffer(device, queue, "tc_cage_ib", bytemuck::cast_slice(edges), wgpu::BufferUsages::INDEX),
|
||||
edge_index_count: (edges.len() * 2) as u32,
|
||||
corners: upload_buffer(device, queue, "tc_cage_vb", bytemuck::cast_slice(cage.corners), wgpu::BufferUsages::VERTEX),
|
||||
corner_count: cage.corners.len() as u32,
|
||||
edges: upload_buffer(device, queue, "tc_cage_ib", bytemuck::cast_slice(cage.edges), wgpu::BufferUsages::INDEX),
|
||||
edge_index_count: (cage.edges.len() * 2) as u32,
|
||||
missing_seams: upload_buffer(device, queue, "tc_cage_seam_ib", bytemuck::cast_slice(cage.missing_seams), wgpu::BufferUsages::INDEX),
|
||||
missing_seam_index_count: (cage.missing_seams.len() * 2) as u32,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1322,8 +1364,8 @@ impl Renderer {
|
||||
}
|
||||
}
|
||||
|
||||
/// The low poly's UV seams as vertex pairs per material ([`Mesh::uv_seam_edges`]) for mesh `mesh_id`
|
||||
pub fn set_uv_seams(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh_id: u64, seams: &[Vec<(u32, u32)>]) {
|
||||
/// The low poly's hard edges without a UV seam as vertex pairs per material ([`Mesh::missing_seam_edges`]) for mesh `mesh_id`
|
||||
pub fn set_missing_seams(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh_id: u64, seams: &[Vec<(u32, u32)>]) {
|
||||
let mut line_indices: Vec<u32> = Vec::new();
|
||||
let mut line_draws = Vec::new();
|
||||
for (material, edges) in seams.iter().enumerate() {
|
||||
@@ -1332,8 +1374,8 @@ impl Renderer {
|
||||
line_draws.push((start, line_indices.len() as u32 - start, material));
|
||||
}
|
||||
|
||||
let lines = upload_buffer(device, queue, "tc_uv_seams", bytemuck::cast_slice(&line_indices), wgpu::BufferUsages::INDEX);
|
||||
self.uv_seams = Some(UvSeamGpu { mesh_id, lines, line_draws });
|
||||
let lines = upload_buffer(device, queue, "tc_missing_seams", bytemuck::cast_slice(&line_indices), wgpu::BufferUsages::INDEX);
|
||||
self.missing_seams = Some(MissingSeamGpu { mesh_id, lines, line_draws });
|
||||
self.content_rev += 1;
|
||||
}
|
||||
|
||||
@@ -1858,10 +1900,11 @@ impl Renderer {
|
||||
if sample >= TAA_SAMPLES {
|
||||
return;
|
||||
}
|
||||
|
||||
let aspect = frame.size[0].max(1) as f32 / frame.size[1].max(1) as f32;
|
||||
let mut vp = frame.camera.view_proj(aspect);
|
||||
if sample > 0 {
|
||||
// Sub-pixel jitter in clip space: a box filter over the pixel once averaged.
|
||||
// Sub-pixel jitter averages into a box filter
|
||||
let (jx, jy) = (halton(sample, 2) - 0.5, halton(sample, 3) - 0.5);
|
||||
vp = Mat4::from_translation(Vec3::new(2.0 * jx / frame.size[0].max(1) as f32, 2.0 * jy / frame.size[1].max(1) as f32, 0.0)) * vp;
|
||||
}
|
||||
@@ -1873,13 +1916,13 @@ impl Renderer {
|
||||
(1.0, [sx, sy, pan[0], pan[1]])
|
||||
}
|
||||
};
|
||||
// Data views (channels, mesh maps, UV checker, the 2D view) show values as they are: no
|
||||
// exposure, tone mapping, effects or shadows.
|
||||
|
||||
// Data views bypass exposure, tone mapping, effects and shadows
|
||||
let data = uv_view > 0.5 || s.view_mode != 0;
|
||||
let fx = |v: f32| if s.post_effects && !data { v.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let bloom = fx(s.bloom) > 0.0;
|
||||
// The key light lives in the environment: turn it with it (the inverse of env_rotate in
|
||||
// mesh.wgsl maps environment directions to world directions).
|
||||
|
||||
// Turn the key light with the environment
|
||||
let (sin, cos) = s.env_rotation_deg.to_radians().sin_cos();
|
||||
let [lx, ly, lz, lw] = s.light;
|
||||
let light = Vec3::new(cos * lx + sin * lz, ly, cos * lz - sin * lx);
|
||||
@@ -1888,19 +1931,19 @@ impl Renderer {
|
||||
self.ensure_dense(device, queue);
|
||||
}
|
||||
let disp = match self.mesh.as_ref().filter(|_| displace) {
|
||||
// Height-to-normal's slope: strength 1 tilts 45° for a height change of 1 over 1/16 of
|
||||
// the UV square; the vertex shader samples the mip whose texels match the vertex spacing.
|
||||
// A unit height across 1/16 of UV space tilts 45°; use the mip nearest vertex spacing
|
||||
Some(m) => [1.0, m.world_per_uv / 16.0, 1.0 / (m.dense.as_ref().unwrap_or(&m.geo).triangles.max(1) as f32 * 0.5).sqrt(), 0.0],
|
||||
None => [0.0; 4],
|
||||
};
|
||||
let shadow_disp = [disp[0], disp[1] * s.height_strength, disp[2], 0.0];
|
||||
let shadow_vp = if !data && s.shadows && lw > 0.0 { self.update_shadow(device, queue, encoder, light, shadow_disp, &frame.visible) } else { None };
|
||||
let radius = self.mesh.as_ref().map_or(1.0, |m| m.radius);
|
||||
// Background rays come from a perspective camera even in orthographic views (an ortho
|
||||
// ray grid would show a single flat environment color).
|
||||
|
||||
// Perspective background rays prevent flat color in orthographic views
|
||||
let bg_vp = OrbitCamera { ortho: false, ..frame.camera }.view_proj(aspect);
|
||||
let e = frame.camera.eye();
|
||||
// Scene effects (3D material view; they need float targets for depths and signed light).
|
||||
|
||||
// Scene effects need float targets for depths and signed light
|
||||
let scene_fx = !data && frame.kind == ViewKind::Scene && self.hdr_format == HDR_FORMAT && self.mesh.is_some();
|
||||
let dof = s.dof.filter(|_| scene_fx);
|
||||
let sss = s.sss_blur.filter(|m| scene_fx && m.iter().any(|v| *v > 0.0));
|
||||
@@ -1909,7 +1952,8 @@ impl Renderer {
|
||||
let cam = &frame.camera;
|
||||
let half_h = (cam.fov.clamp(5.0, 150.0).to_radians() * 0.5).tan();
|
||||
let height = frame.size[1].max(1) as f32;
|
||||
// Pixels per world unit at view depth z: k / z in perspective, k in orthographic views.
|
||||
|
||||
// Perspective pixels per world unit vary with depth
|
||||
let k = if cam.ortho { height / (2.0 * cam.distance.max(1e-6) * half_h) } else { height / (2.0 * half_h) };
|
||||
let ppw = |z: f32| if cam.ortho { k } else { k / z.max(1e-6) };
|
||||
let dof_c = dof.map_or([0.0; 4], |[focus, aperture]| {
|
||||
@@ -1929,7 +1973,7 @@ impl Renderer {
|
||||
uv_xform,
|
||||
light: [light.x, light.y, light.z, lw],
|
||||
light_vp: shadow_vp.unwrap_or(Mat4::IDENTITY).to_cols_array_2d(),
|
||||
// Normal offset: 1.5 shadow texels of the light frustum (2 × radius wide).
|
||||
// Offset by 1.5 shadow texels to avoid self-shadowing
|
||||
shadow: [if shadow_vp.is_some() { 1.0 } else { 0.0 }, 1.0 / SHADOW_SIZE as f32, radius * 3.0 / SHADOW_SIZE as f32, 0.0],
|
||||
material: [if s.spec_gloss { 1.0 } else { 0.0 }, if s.parallax { 1.0 } else { 0.0 }, sample as f32, s.ior],
|
||||
scatter: [s.scatter[0], s.scatter[1], s.scatter[2], if sss.is_some() { 1.0 } else { 0.0 }],
|
||||
@@ -1938,6 +1982,7 @@ impl Renderer {
|
||||
refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, 0.0],
|
||||
highlight: highlight_globals(s, data),
|
||||
highlight_shift: highlight_shift(frame.size),
|
||||
..bake_globals(s.bake)
|
||||
};
|
||||
let flag = |b: bool| if b { 1.0 } else { 0.0 };
|
||||
let post = PostRaw {
|
||||
@@ -1961,9 +2006,7 @@ impl Renderer {
|
||||
}
|
||||
let weight = 1.0 / f64::from(sample + 1);
|
||||
match v.fx.as_ref().filter(|_| fx_on) {
|
||||
// The effects run on every frame before it joins the average, so idle accumulation
|
||||
// also smooths the depth of field's sampling pattern (turned each frame). Their
|
||||
// G-buffer (unjittered) stays valid while the view accumulates.
|
||||
// Effects run before averaging; the unjittered G-buffer remains valid
|
||||
Some(f) => {
|
||||
self.scene_pass(encoder, v, &v.hdr, globals_bg, frame);
|
||||
if sample == 0 {
|
||||
@@ -2099,7 +2142,8 @@ impl Renderer {
|
||||
None => (&self.mesh_pipeline, frame.shade.wireframe_3d.then_some(&self.wire3d_pipeline)),
|
||||
Some(_) => (&self.uv_pipeline, frame.shade.wireframe.then_some(&self.wire_pipeline)),
|
||||
};
|
||||
// Transmissive surfaces refract what the behind pass rendered this frame.
|
||||
|
||||
// Transmissive surfaces refract the current behind pass
|
||||
let refr = v.behind.as_ref().filter(|_| frame.shade.refraction).map_or(&self.refr_black, |b| &b.bg);
|
||||
let highlight = frame.shade.highlight.filter(|_| uv_ts.is_none()).map(|highlight| (&self.highlight_pipeline, highlight.set));
|
||||
self.draw_scene(encoder, v, resolve, globals_bg, frame, pipe, wire, highlight, refr);
|
||||
@@ -2148,14 +2192,13 @@ impl Renderer {
|
||||
pass.set_bind_group(2, refraction_source, &[]);
|
||||
let geometry = self.geometry(mesh, frame);
|
||||
let bake = frame.shade.bake.filter(|_| uv_set.is_none());
|
||||
let low_poly_shown = bake.is_none_or(|bake| bake.low_poly);
|
||||
let low_poly_set = bake.and_then(|bake| bake.only_set).or(uv_set);
|
||||
let (highlight, highlight_set) = highlight.filter(|(_, set)| low_poly_shown && low_poly_set.is_none_or(|only| only == *set)).unzip();
|
||||
let low_poly_shown = bake.is_none_or(|bake| bake.low_poly.shown);
|
||||
let (highlight, highlight_set) = highlight.filter(|(_, set)| low_poly_shown && uv_set.is_none_or(|only| only == *set)).unzip();
|
||||
|
||||
// The wireframe and the highlight draw the mesh's own edges (displaced in the vertex shader too)
|
||||
let passes = [
|
||||
(low_poly_shown.then_some(mesh_pipeline), &geometry.vb, &geometry.ib, &geometry.draws, low_poly_set, 1),
|
||||
(wire.filter(|_| low_poly_shown), &mesh.geo.vb, &mesh.lines, &mesh.line_draws, low_poly_set, 1),
|
||||
(low_poly_shown.then_some(mesh_pipeline), &geometry.vb, &geometry.ib, &geometry.draws, uv_set, 1),
|
||||
(wire.filter(|_| low_poly_shown), &mesh.geo.vb, &mesh.lines, &mesh.line_draws, uv_set, 1),
|
||||
(highlight, &mesh.geo.vb, &mesh.lines, &mesh.line_draws, highlight_set, HIGHLIGHT_SHIFTS),
|
||||
];
|
||||
for (pipeline, vertices, indices, ranges, only_set, instances) in passes {
|
||||
@@ -2173,6 +2216,18 @@ impl Renderer {
|
||||
if let Some(bake) = bake {
|
||||
self.draw_bake(&mut pass, mesh, frame, bake);
|
||||
}
|
||||
if let Some(texture_set) = uv_set
|
||||
&& frame.shade.bake.is_some_and(|bake| bake.missing_seams.shown)
|
||||
&& let Some(seams) = self.missing_seams.as_ref().filter(|seams| seams.mesh_id == mesh.id)
|
||||
{
|
||||
pass.set_pipeline(&self.uv_missing_seam_pipeline);
|
||||
pass.set_vertex_buffer(0, mesh.geo.vb.slice(..));
|
||||
pass.set_index_buffer(seams.lines.slice(..), wgpu::IndexFormat::Uint32);
|
||||
for (range, set) in self.drawable(&seams.line_draws, &frame.visible, Some(texture_set)) {
|
||||
pass.set_bind_group(1, &set.bind_group, &[]);
|
||||
pass.draw_indexed(range, 0, 0..1);
|
||||
}
|
||||
}
|
||||
|
||||
// Overlay quads last, so the mesh's depth hides what is behind it
|
||||
if uv_set.is_none()
|
||||
@@ -2184,9 +2239,9 @@ impl Renderer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Bake mode's high poly, UV seams and cages over the low poly `low_poly`
|
||||
/// Bake mode's high poly, missing seams and cages over the low poly `low_poly`
|
||||
fn draw_bake(&self, pass: &mut wgpu::RenderPass<'_>, low_poly: &MeshGpu, frame: &Frame, bake: BakeVisualization) {
|
||||
if bake.high_poly
|
||||
if bake.high_poly.shown
|
||||
&& let Some(high) = &self.bake_high
|
||||
{
|
||||
pass.set_pipeline(&self.bake_high_pipeline);
|
||||
@@ -2196,35 +2251,46 @@ impl Renderer {
|
||||
pass.draw_indexed(0..high.index_count, 0, 0..1);
|
||||
}
|
||||
|
||||
if bake.uv_seams
|
||||
&& let Some(seams) = self.uv_seams.as_ref().filter(|seams| seams.mesh_id == low_poly.id)
|
||||
if bake.missing_seams.shown
|
||||
&& let Some(seams) = self.missing_seams.as_ref().filter(|seams| seams.mesh_id == low_poly.id)
|
||||
{
|
||||
pass.set_pipeline(&self.uv_seam_pipeline);
|
||||
pass.set_pipeline(&self.missing_seam_pipeline);
|
||||
pass.set_vertex_buffer(0, low_poly.geo.vb.slice(..));
|
||||
pass.set_index_buffer(seams.lines.slice(..), wgpu::IndexFormat::Uint32);
|
||||
for (range, set) in self.drawable(&seams.line_draws, &frame.visible, bake.only_set) {
|
||||
for (range, set) in self.drawable(&seams.line_draws, &frame.visible, None) {
|
||||
pass.set_bind_group(1, &set.bind_group, &[]);
|
||||
pass.draw_indexed(range, 0, 0..1);
|
||||
}
|
||||
}
|
||||
|
||||
if !bake.cage {
|
||||
return;
|
||||
}
|
||||
|
||||
let shown = |texture_set: usize| bake.only_set.is_none_or(|only| only == texture_set) && frame.visible.get(texture_set).copied().unwrap_or(true);
|
||||
let cages = || self.cages.iter().enumerate().filter(move |(texture_set, _)| shown(*texture_set)).filter_map(|(_, cage)| cage.as_ref());
|
||||
|
||||
// The translucent faces first, then the wireframe over them
|
||||
pass.set_pipeline(&self.cage_pipeline);
|
||||
for cage in cages() {
|
||||
pass.set_vertex_buffer(0, cage.corners.slice(..));
|
||||
pass.draw(0..cage.corner_count, 0..1);
|
||||
if bake.cage_surface.shown {
|
||||
pass.set_pipeline(&self.cage_pipeline);
|
||||
for cage in cages() {
|
||||
pass.set_vertex_buffer(0, cage.corners.slice(..));
|
||||
pass.draw(0..cage.corner_count, 0..1);
|
||||
}
|
||||
}
|
||||
pass.set_pipeline(&self.cage_wire_pipeline);
|
||||
for cage in cages() {
|
||||
pass.set_vertex_buffer(0, cage.corners.slice(..));
|
||||
pass.set_index_buffer(cage.edges.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.draw_indexed(0..cage.edge_index_count, 0, 0..1);
|
||||
|
||||
if bake.cage_wire.shown {
|
||||
pass.set_pipeline(&self.cage_wire_pipeline);
|
||||
for cage in cages() {
|
||||
pass.set_vertex_buffer(0, cage.corners.slice(..));
|
||||
pass.set_index_buffer(cage.edges.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.draw_indexed(0..cage.edge_index_count, 0, 0..1);
|
||||
}
|
||||
}
|
||||
|
||||
if bake.missing_seams.shown && bake.cage_shown() {
|
||||
pass.set_pipeline(&self.cage_missing_seam_pipeline);
|
||||
for cage in cages() {
|
||||
pass.set_vertex_buffer(0, cage.corners.slice(..));
|
||||
pass.set_index_buffer(cage.missing_seams.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.draw_indexed(0..cage.missing_seam_index_count, 0, 0..1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2336,6 +2402,26 @@ fn highlight_globals(shade: &Shade, data: bool) -> [f32; 4] {
|
||||
[r, g, b, HIGHLIGHT_OPACITY]
|
||||
}
|
||||
|
||||
/// The globals of bake mode's overlays and neutral material for `bake` (all zero without it)
|
||||
fn bake_globals(bake: Option<BakeVisualization>) -> GlobalsRaw {
|
||||
let Some(bake) = bake else { return GlobalsRaw::zeroed() };
|
||||
|
||||
let [red, green, blue] = bake.low_poly.color;
|
||||
let neutral = bake.shown_neutral();
|
||||
let samples_per_frame = neutral.map_or(0, |neutral| neutral.samples_per_frame());
|
||||
GlobalsRaw {
|
||||
bake_high: bake.high_poly.globals(),
|
||||
bake_matching_error: bake.matching_error.globals(),
|
||||
bake_cage: bake.cage_surface.globals(),
|
||||
bake_cage_wire: bake.cage_wire.globals(),
|
||||
bake_missing_seam: bake.missing_seams.globals(),
|
||||
bake_neutral_color: [red, green, blue, samples_per_frame as f32],
|
||||
bake_neutral: neutral.map_or([0.0; 4], |neutral| neutral.globals()),
|
||||
bake_bent_normal: neutral.map_or([0.0; 4], |neutral| neutral.bent_normal_globals()),
|
||||
..GlobalsRaw::zeroed()
|
||||
}
|
||||
}
|
||||
|
||||
/// Globals `highlight_shift`: how far each of the highlight's line copies moves sideways, in clip units of a `size` pixel target
|
||||
fn highlight_shift(size: [u32; 2]) -> [f32; 4] {
|
||||
let half_extra_width = (HIGHLIGHT_WIDTH_PX - 1.0) * 0.5;
|
||||
|
||||
@@ -1,19 +1,46 @@
|
||||
// Bake mode's 3D view: the high poly, the cage around the low poly and the UV seams
|
||||
// Bake mode's 3D view: the high poly, the cage around the low poly, the missing seams and the neutral material
|
||||
|
||||
struct BakeViewOut {
|
||||
@builtin(position) clip: vec4<f32>,
|
||||
@location(0) world_position: vec3<f32>,
|
||||
@location(1) normal: vec3<f32>,
|
||||
// 1 where the bake's rays miss the high poly, 0 where they reach it
|
||||
// 1 where the bake's rays miss the high poly, 0 where they reach it, negative where another texture set owns it (hidden)
|
||||
@location(2) missed: f32,
|
||||
};
|
||||
|
||||
const HIGH_POLY_COLOR: vec3<f32> = vec3<f32>(0.10, 0.36, 0.56);
|
||||
const MISSED_COLOR: vec3<f32> = vec3<f32>(0.80, 0.01, 0.01);
|
||||
const CAGE_COLOR: vec3<f32> = vec3<f32>(0.55, 0.42, 0.26);
|
||||
const CAGE_OPACITY: f32 = 0.16;
|
||||
const CAGE_WIRE_COLOR: vec4<f32> = vec4<f32>(0.75, 0.62, 0.42, 0.7);
|
||||
const UV_SEAM_COLOR: vec4<f32> = vec4<f32>(0.20, 0.85, 0.30, 1.0);
|
||||
// Reflectance of the neutral material's dielectric part facing the camera
|
||||
const NEUTRAL_F0: f32 = 0.04;
|
||||
|
||||
// Lowest roughness the neutral material shades with: below it the GGX lobe is too narrow for its samples
|
||||
const MIN_NEUTRAL_ROUGHNESS: f32 = 0.045;
|
||||
|
||||
// How fast reflections fade as they dip below the mesh surface (larger = sooner)
|
||||
const HORIZON_FADE: f32 = 1.3;
|
||||
|
||||
// Floor of the cosines that divide the reflection terms, so grazing angles stay finite
|
||||
const MIN_COSINE: f32 = 1e-4;
|
||||
|
||||
// A normal closer than this to +-Z builds its tangent frame from X, where the cross product with Z would vanish
|
||||
const TANGENT_HELPER_MAX_Z: f32 = 0.999;
|
||||
|
||||
// One mip coarser than each sample's share of the lobe: hides the gaps between few samples (filtered importance sampling)
|
||||
const FILTERED_SAMPLING_LOD_BIAS: f32 = 1.0;
|
||||
|
||||
// A packed bent normal shorter than this is the unbaked gray, not a direction
|
||||
const BENT_NORMAL_MIN_LENGTH: f32 = 0.5;
|
||||
|
||||
// Cosines between a reflection and the bent normal over which the reflection goes from occluded to open
|
||||
const BENT_OCCLUSION_START: f32 = -0.25;
|
||||
const BENT_OCCLUSION_END: f32 = 0.75;
|
||||
|
||||
// Floor of the GGX distribution's denominator, which reaches 0 at the peak of a mirror-like lobe
|
||||
const MIN_GGX_DENOMINATOR: f32 = 1e-6;
|
||||
|
||||
// Fractional part of the golden ratio: shifts each accumulated frame's samples around the lobe
|
||||
const GOLDEN_RATIO_FRACTION: f32 = 0.618034;
|
||||
|
||||
// High-poly surface where the interpolated `missed` falls below this belongs to a hidden texture set
|
||||
const HIDDEN_BELOW: f32 = -0.5;
|
||||
|
||||
// Brightness of surfaces seen edge-on; facing the camera adds the rest
|
||||
const HEADLIGHT_AMBIENT: f32 = 0.3;
|
||||
@@ -45,7 +72,11 @@ fn vs_bake_high(@location(0) position: vec3<f32>, @location(1) normal: vec3<f32>
|
||||
|
||||
@fragment
|
||||
fn fs_bake_high(surface: BakeViewOut) -> @location(0) vec4<f32> {
|
||||
let color = mix(HIGH_POLY_COLOR, MISSED_COLOR, surface.missed);
|
||||
if (surface.missed < HIDDEN_BELOW) {
|
||||
discard;
|
||||
}
|
||||
|
||||
let color = mix(g.bake_high.rgb, g.bake_matching_error.rgb, max(surface.missed, 0.0) * g.bake_matching_error.a);
|
||||
return vec4<f32>(headlight(color, normalize(surface.normal), surface.world_position), 1.0);
|
||||
}
|
||||
|
||||
@@ -63,7 +94,7 @@ fn vs_bake_cage(@location(0) position: vec3<f32>) -> BakeViewOut {
|
||||
@fragment
|
||||
fn fs_bake_cage(surface: BakeViewOut) -> @location(0) vec4<f32> {
|
||||
let face_normal = normalize(cross(dpdx(surface.world_position), dpdy(surface.world_position)));
|
||||
return vec4<f32>(headlight(CAGE_COLOR, face_normal, surface.world_position), CAGE_OPACITY);
|
||||
return vec4<f32>(headlight(g.bake_cage.rgb, face_normal, surface.world_position), g.bake_cage.a);
|
||||
}
|
||||
|
||||
// Pulled toward the camera like the 3D wireframe, so the lines win against the cage's faces
|
||||
@@ -79,10 +110,112 @@ fn vs_bake_cage_wire(@location(0) position: vec3<f32>) -> BakeViewOut {
|
||||
|
||||
@fragment
|
||||
fn fs_wire_bake_cage(surface: BakeViewOut) -> @location(0) vec4<f32> {
|
||||
return CAGE_WIRE_COLOR;
|
||||
return g.bake_cage_wire;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_wire_uv_seam(surface: VOut) -> @location(0) vec4<f32> {
|
||||
return UV_SEAM_COLOR;
|
||||
fn fs_wire_missing_seam(surface: VOut) -> @location(0) vec4<f32> {
|
||||
return g.bake_missing_seam;
|
||||
}
|
||||
|
||||
// The missing seams along the cage, whose vertices carry the bake view's outputs
|
||||
@fragment
|
||||
fn fs_wire_cage_missing_seam(surface: BakeViewOut) -> @location(0) vec4<f32> {
|
||||
return g.bake_missing_seam;
|
||||
}
|
||||
|
||||
// Shade the neutral material using the texture set's normal, occlusion and optional bent normal
|
||||
fn neutral_color(n: vec3<f32>, n_geo: vec3<f32>, v: vec3<f32>, world_position: vec3<f32>, ao_channel: f32, packed_bent: vec3<f32>) -> vec4<f32> {
|
||||
let albedo = g.bake_neutral_color.rgb;
|
||||
let rough = clamp(g.bake_neutral.x, MIN_NEUTRAL_ROUGHNESS, 1.0);
|
||||
let metal = g.bake_neutral.y;
|
||||
let ao = mix(1.0, ao_channel, g.bake_neutral.z);
|
||||
let f0 = mix(vec3<f32>(NEUTRAL_F0), albedo, metal);
|
||||
let diffuse_col = albedo * (1.0 - metal);
|
||||
let nov = clamp(abs(dot(n, v)), MIN_COSINE, 1.0);
|
||||
|
||||
// An unbaked bent normal reads as the neutral gray (length 0): the surface normal stands in
|
||||
var bent = packed_bent * 2.0 - 1.0;
|
||||
bent = select(n, normalize(bent), dot(bent, bent) > BENT_NORMAL_MIN_LENGTH * BENT_NORMAL_MIN_LENGTH);
|
||||
let diffuse = sh_irradiance(normalize(mix(n, bent, g.bake_bent_normal.x)), vec3<f32>(0.0)) * diffuse_col * ao;
|
||||
let r = reflect(-v, n);
|
||||
let horizon = clamp(1.0 + HORIZON_FADE * dot(r, n_geo), 0.0, 1.0);
|
||||
|
||||
// Reflections pointing away from the open direction are occluded
|
||||
let bent_occlusion = mix(1.0, smoothstep(BENT_OCCLUSION_START, BENT_OCCLUSION_END, dot(bent, r)), g.bake_bent_normal.y);
|
||||
let spec = sampled_reflection(n, v, rough, f0, nov) * ao * bent_occlusion * horizon * horizon;
|
||||
|
||||
var direct = vec3<f32>(0.0);
|
||||
if (g.light.w > 0.0) {
|
||||
let l = normalize(g.light.xyz);
|
||||
let h = normalize(l + v);
|
||||
let nol = clamp(dot(n, l), 0.0, 1.0);
|
||||
let f = f0 + (vec3<f32>(1.0) - f0) * pow(1.0 - clamp(dot(v, h), 0.0, 1.0), 5.0);
|
||||
direct = ((vec3<f32>(1.0) - f) * diffuse_col / PI + ggx_dv(rough * rough, nov, nol, clamp(dot(n, h), 0.0, 1.0)) * f) * nol * g.light.w;
|
||||
if (g.shadow.x > 0.5 && nol > 0.0) {
|
||||
direct *= shadow_factor(world_position, n_geo);
|
||||
}
|
||||
}
|
||||
let color = diffuse + spec + direct;
|
||||
return vec4<f32>(select(color, vec3<f32>(0.0), any(color != color)), 1.0);
|
||||
}
|
||||
|
||||
// Importance sample the environment's GGX reflection with a new sequence each frame
|
||||
fn sampled_reflection(n: vec3<f32>, v: vec3<f32>, rough: f32, f0: vec3<f32>, nov: f32) -> vec3<f32> {
|
||||
let count = max(u32(g.bake_neutral_color.w), 1u);
|
||||
let a = rough * rough;
|
||||
let a2 = a * a;
|
||||
let env_size = vec2<f32>(textureDimensions(env_tex));
|
||||
let texel_solid_angle = 4.0 * PI / (env_size.x * env_size.y);
|
||||
let side = select(vec3<f32>(1.0, 0.0, 0.0), vec3<f32>(0.0, 0.0, 1.0), abs(n.z) < TANGENT_HELPER_MAX_Z);
|
||||
let tangent = normalize(cross(side, n));
|
||||
let bitangent = cross(n, tangent);
|
||||
let frame_offset = u32(g.material.z) * count;
|
||||
|
||||
// Schlick-GGX geometry term at k = a / 2
|
||||
let k = a * 0.5;
|
||||
let view_visibility = nov / (nov * (1.0 - k) + k);
|
||||
|
||||
var sum = vec3<f32>(0.0);
|
||||
for (var index = 0u; index < count; index++) {
|
||||
let xi = vec2<f32>(fract((f32(index) + 0.5) / f32(count) + f32(g.material.z) * GOLDEN_RATIO_FRACTION), radical_inverse(index + frame_offset));
|
||||
let phi = 2.0 * PI * xi.x;
|
||||
|
||||
// Clamp cosine before computing its sine to avoid NaN near zero roughness
|
||||
let cos_theta = clamp(sqrt((1.0 - xi.y) / (1.0 + (a2 - 1.0) * xi.y)), 0.0, 1.0);
|
||||
let sin_theta = sqrt(1.0 - cos_theta * cos_theta);
|
||||
let h = normalize(tangent * (cos(phi) * sin_theta) + bitangent * (sin(phi) * sin_theta) + n * cos_theta);
|
||||
let l = reflect(-v, h);
|
||||
let nol = min(dot(n, l), 1.0);
|
||||
if (nol <= 0.0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Capped at 1: a dot product rounding past it makes pow(1 - voh, 5) NaN on GPUs that compute pow through log2
|
||||
let noh = clamp(dot(n, h), MIN_COSINE, 1.0);
|
||||
let voh = clamp(dot(v, h), MIN_COSINE, 1.0);
|
||||
let denominator = max(noh * noh * (a2 - 1.0) + 1.0, MIN_GGX_DENOMINATOR);
|
||||
let pdf = a2 / (PI * denominator * denominator) * noh / (4.0 * voh);
|
||||
|
||||
// Filtered importance sampling: each sample reads the mip that covers its share of the lobe
|
||||
let lod = clamp(0.5 * log2(1.0 / (f32(count) * pdf * texel_solid_angle)) + FILTERED_SAMPLING_LOD_BIAS, 0.0, g.env.y);
|
||||
let light = textureSampleLevel(env_tex, env_samp, env_uv(l), lod).rgb;
|
||||
let fresnel = f0 + (vec3<f32>(1.0) - f0) * pow(1.0 - voh, 5.0);
|
||||
let visibility = view_visibility * nol / (nol * (1.0 - k) + k);
|
||||
let contribution = light * fresnel * (visibility * voh / (noh * nov));
|
||||
|
||||
// Drop NaN samples before they contaminate the frame average
|
||||
sum += select(contribution, vec3<f32>(0.0), any(contribution != contribution));
|
||||
}
|
||||
return sum / f32(count);
|
||||
}
|
||||
|
||||
// Van der Corput: the bits of `index` mirrored behind the binary point (swapped by hand: WebGL2 lacks a bit reverse)
|
||||
fn radical_inverse(index: u32) -> f32 {
|
||||
var bits = (index << 16u) | (index >> 16u);
|
||||
bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
|
||||
bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
|
||||
bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
|
||||
bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
|
||||
return f32(bits) / 4294967296.0;
|
||||
}
|
||||
@@ -26,6 +26,14 @@ struct Globals {
|
||||
refr: vec4<f32>, // x screen-space refraction on (1), y lods of the scene behind, z refraction depth (world units), w -
|
||||
highlight: vec4<f32>, // rgb highlighted set's edge color in the scene (before exposure and tone mapping), a opacity
|
||||
highlight_shift: vec4<f32>, // xy sideways shift of each highlight line copy (clip units), zw -
|
||||
bake_high: vec4<f32>, // bake mode: rgb high poly color, a -
|
||||
bake_matching_error: vec4<f32>, // rgb color where the bake's rays miss the high poly, a its strength (0 hidden)
|
||||
bake_cage: vec4<f32>, // rgb cage surface color, a opacity
|
||||
bake_cage_wire: vec4<f32>, // rgb cage wireframe color, a opacity
|
||||
bake_missing_seam: vec4<f32>, // rgb color of hard edges without a UV seam, a opacity
|
||||
bake_neutral_color: vec4<f32>, // rgb the neutral material's color, a its reflection samples this frame
|
||||
bake_neutral: vec4<f32>, // x roughness, y metallic, z AO intensity of the neutral material, w on (1)
|
||||
bake_bent_normal: vec4<f32>, // x, y how much the bent normal (in the aux texture) turns the diffuse light and dims reflections, zw -
|
||||
};
|
||||
|
||||
@group(0) @binding(0) var<uniform> g: Globals;
|
||||
@@ -403,8 +411,8 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
|
||||
let hu = textureSample(t_height, samp, uv - vec2<f32>(0.0, ts.y)).r;
|
||||
let hd = textureSample(t_height, samp, uv + vec2<f32>(0.0, ts.y)).r;
|
||||
|
||||
// Tangent-space normal: height gradient (+Y = up the image) combined with the normal channel.
|
||||
// Same slope rule as texture export: strength 1 tilts 45° for a height change of 1 over 1/16 of the width.
|
||||
// Match export: a unit height over 1/16 of the width tilts 45°
|
||||
// Combine the height gradient with the tangent-space normal
|
||||
let k = g.mode.z * dims.x / 16.0 * tile_scale(uv);
|
||||
let n_height = normalize(vec3<f32>(-(hr - hl) * 0.5 * k, (hd - hu) * 0.5 * k, 1.0));
|
||||
var n_detail = snorm8(nrm_s);
|
||||
@@ -418,6 +426,7 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
|
||||
if (ch >= 11) {
|
||||
return unlit(lobe_view(ch, lobes, sheen_t, nrm_t.a, emis_t.a, extra));
|
||||
}
|
||||
|
||||
switch ch {
|
||||
case 0: { return unlit(data_out(base_s.rgb)); }
|
||||
case 1: { return unlit(data_out(vec3<f32>(orm.b))); }
|
||||
@@ -435,6 +444,7 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
|
||||
if (mode == 2) {
|
||||
return unlit(raw_out(aux.rgb));
|
||||
}
|
||||
|
||||
if (mode == 3) {
|
||||
let c = floor(uv * 32.0);
|
||||
let chk = (c.x + c.y) - 2.0 * floor((c.x + c.y) * 0.5);
|
||||
@@ -446,7 +456,11 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
|
||||
return unlit(data_out((col + tint) * diff));
|
||||
}
|
||||
|
||||
// Opacity: dithered alpha test (a new pattern per accumulated frame, so it averages out).
|
||||
if (g.bake_neutral.w > 0.5) {
|
||||
return Shaded(neutral_color(n, n_geo, v, i.wpos, orm.r, aux.rgb), vec3<f32>(0.0));
|
||||
}
|
||||
|
||||
// Change the alpha dither each frame so accumulation smooths it
|
||||
if (base_s.a < hash12(i.clip.xy + g.material.z * vec2<f32>(17.0, 59.0))) {
|
||||
discard;
|
||||
}
|
||||
@@ -459,25 +473,27 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
|
||||
var f0 = mix(vec3<f32>(0.08 * orm.a), albedo, metal);
|
||||
var diffuse_col = albedo * (1.0 - metal);
|
||||
if (g.material.x > 0.5) {
|
||||
// Specular/glossiness: the Specular color is F0 and base color the diffuse color, with
|
||||
// the energy the specular takes removed (roughness already is 1 - glossiness).
|
||||
// Specular color gives F0; remove its energy from diffuse
|
||||
f0 = hgt.gba;
|
||||
diffuse_col = albedo * (1.0 - max(f0.r, max(f0.g, f0.b)));
|
||||
}
|
||||
// Transmission: that part of the dielectric base refracts instead of reflecting diffusely.
|
||||
|
||||
// Transmission removes energy from the dielectric diffuse base
|
||||
let trans = extra.b * (1.0 - metal);
|
||||
diffuse_col *= 1.0 - trans;
|
||||
|
||||
// The extra lobes; their defaults (weights 0) leave the base shading as it is.
|
||||
// Zero lobe weights preserve the base shading
|
||||
let coat_w = lobes.r;
|
||||
let coat_rough = clamp(lobes.g, 0.045, 1.0);
|
||||
let aniso = lobes.b;
|
||||
let sheen_col = sheen_t.rgb * sheen_t.a;
|
||||
let sheen_max = max3(sheen_col);
|
||||
let sheen_rough = clamp(nrm_t.a, 0.07, 1.0);
|
||||
// Subsurface scattering: wrapped diffuse, wider for the channels the scatter color carries further.
|
||||
|
||||
// Scatter color controls each channel's diffuse wrap
|
||||
let wrap = emis_t.a * g.scatter.xyz;
|
||||
// Anisotropy: GGX roughness stretched along the mesh tangent turned by the angle (0..1 → 0..π).
|
||||
|
||||
// Stretch GGX along the tangent rotated by 0..π
|
||||
let a = rough * rough;
|
||||
let at = max(a * (1.0 + aniso), 0.002);
|
||||
let ab = max(a * (1.0 - aniso), 0.002);
|
||||
@@ -486,8 +502,8 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
|
||||
let ta1 = ta0 - n * dot(n, ta0);
|
||||
let ta = ta1 * inverseSqrt(max(dot(ta1, ta1), 1e-8));
|
||||
let ba = cross(n, ta);
|
||||
// The clear coat follows the mesh normal (not the normal and height channels), turned by the
|
||||
// coat normal channel where it is painted (the flat default keeps the mesh normal exactly).
|
||||
|
||||
// Coat normals perturb the geometric normal independently of base detail
|
||||
var n_c = n_geo;
|
||||
let cn = coat_normal_ts(extra);
|
||||
if (coat_w > 0.0 && max(abs(cn.x), abs(cn.y)) > 0.004) {
|
||||
@@ -495,7 +511,8 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
|
||||
}
|
||||
let nov_c = clamp(abs(dot(n_c, v)), 1e-4, 1.0);
|
||||
let coat_t = 1.0 - coat_w * schlick(0.04, nov_c);
|
||||
// What reaches the layers below: the coat's transmission and the sheen albedo scaling.
|
||||
|
||||
// Coat transmission and sheen albedo limit energy reaching the base
|
||||
var base_scale = coat_t;
|
||||
var sheen_e = 0.0;
|
||||
if (sheen_max > 0.0) {
|
||||
@@ -506,12 +523,13 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
|
||||
let diffuse = sh_irradiance(n, wrap) * diffuse_col * ao;
|
||||
var r = reflect(-v, n);
|
||||
if (aniso > 0.0) {
|
||||
// Bent reflection vector: the standard real-time approximation of anisotropic IBL.
|
||||
// Bend the reflection to approximate anisotropic IBL
|
||||
let bent = cross(cross(ba, v), ba);
|
||||
r = reflect(-v, normalize(mix(n, bent, aniso * clamp(5.0 * rough, 0.0, 1.0))));
|
||||
}
|
||||
let pre = textureSampleLevel(env_tex, env_samp, env_uv(r), rough * g.env.y).rgb;
|
||||
// Horizon fading: reflections that point below the geometric surface are dimmed.
|
||||
|
||||
// Fade reflections below the geometric surface
|
||||
let horizon = clamp(1.0 + 1.3 * dot(r, n_geo), 0.0, 1.0);
|
||||
let spec = pre * env_brdf(f0, rough, nov) * ao * horizon * horizon;
|
||||
var layers = vec3<f32>(0.0);
|
||||
@@ -525,16 +543,14 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
|
||||
}
|
||||
|
||||
if (trans > 0.0) {
|
||||
// shortcut: one refraction interface (no exit); the path tracer refracts through the
|
||||
// whole mesh.
|
||||
// Approximate one refraction interface; the path tracer also handles the exit
|
||||
var td = refract(-v, n, 1.0 / max(g.material.w, 1.0));
|
||||
if (dot(td, td) < 1e-6) {
|
||||
td = reflect(-v, n);
|
||||
}
|
||||
var behind = textureSampleLevel(env_tex, env_samp, env_uv(td), rough * g.env.y).rgb;
|
||||
if (g.refr.x > 0.5) {
|
||||
// Screen-space refraction: the opaque scene where the refracted ray lands on screen,
|
||||
// over the environment where that shows nothing (or the ray leaves the view).
|
||||
// Composite the refracted screen sample over the environment fallback
|
||||
let p = g.view_proj * vec4<f32>(i.wpos + td * g.refr.z, 1.0);
|
||||
let s = p.xy / max(p.w, 1e-6);
|
||||
let suv = vec2<f32>(s.x * 0.5 + 0.5, 0.5 - s.y * 0.5);
|
||||
@@ -563,7 +579,8 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
|
||||
dv = ggx_dv(a, nov, nol, noh);
|
||||
}
|
||||
let f = f0 + (vec3<f32>(1.0) - f0) * pow(1.0 - voh, 5.0);
|
||||
// Energy-conserving wrapped Lambert (plain Lambert where nothing scatters).
|
||||
|
||||
// Normalize wrapped Lambert to conserve energy
|
||||
let diff_nol = max((nol_raw + wrap) / ((1.0 + wrap) * (1.0 + wrap)), vec3<f32>(0.0));
|
||||
direct_diffuse = (vec3<f32>(1.0) - f) * diffuse_col / PI * diff_nol * (g.light.w * base_scale);
|
||||
direct = ((vec3<f32>(1.0) - f) * diffuse_col / PI * diff_nol + dv * f * nol) * (g.light.w * base_scale);
|
||||
|
||||
+150
-24
@@ -3,7 +3,7 @@ use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::{OrbitCamera, primitives};
|
||||
use texturecraft_render::headless::Headless;
|
||||
use texturecraft_render::renderer::TAA_SAMPLES;
|
||||
use texturecraft_render::{BakeVisualization, Frame, Shade, ViewKind};
|
||||
use texturecraft_render::{BakeOverlay, BakeVisualization, CageGeometry, Frame, NeutralMaterial, Shade, ViewKind};
|
||||
|
||||
/// The UI's key light (`viewport::shade`).
|
||||
const LIGHT: [f32; 4] = [0.5, 0.8, 0.4, 2.5];
|
||||
@@ -226,6 +226,92 @@ fn wireframe_3d_overlays_the_mesh() {
|
||||
assert_eq!(a.at(5, 5), b.at(5, 5), "the background stays clean");
|
||||
}
|
||||
|
||||
/// `overlay` shown
|
||||
fn shown(overlay: BakeOverlay) -> BakeOverlay {
|
||||
BakeOverlay { shown: true, ..overlay }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bake_neutral_material_shades_the_low_poly_in_its_settings() {
|
||||
const COLOR_LEAD: i32 = 30;
|
||||
let Some((mut h, frame)) = setup() else { return };
|
||||
|
||||
let neutral = NeutralMaterial { roughness: 0.5, metallic: 0.0, ao_intensity: 1.0, samples_per_pixel: 16, ..NeutralMaterial::default() };
|
||||
let low_poly = BakeOverlay { color: [0.0, 0.0, 0.8], ..shown(BakeVisualization::default().low_poly) };
|
||||
let painted_parts = BakeVisualization { low_poly, ..BakeVisualization::default() };
|
||||
let neutral_parts = BakeVisualization { neutral: Some(neutral), ..painted_parts };
|
||||
let painted = render(&mut h, &shaded(&frame, |s| s.bake = Some(painted_parts)), "bake_neutral_off");
|
||||
let blue = render(&mut h, &shaded(&frame, |s| s.bake = Some(neutral_parts)), "bake_neutral_blue");
|
||||
let center = (frame.size[0] / 2, frame.size[1] / 2);
|
||||
let [red, green, blue_channel] = blue.at(center.0, center.1).map(i32::from);
|
||||
assert!(
|
||||
blue_channel > red + COLOR_LEAD && blue_channel > green + COLOR_LEAD,
|
||||
"the neutral material takes the project mesh's color: {:?}",
|
||||
[red, green, blue_channel]
|
||||
);
|
||||
assert_ne!(blue.px, painted.px, "the painted material is replaced");
|
||||
|
||||
let metal = BakeVisualization { neutral: Some(NeutralMaterial { metallic: 1.0, roughness: 0.1, ..neutral }), ..neutral_parts };
|
||||
assert_ne!(render(&mut h, &shaded(&frame, |s| s.bake = Some(metal)), "bake_neutral_metal").px, blue.px, "roughness and metallic reach the shader");
|
||||
|
||||
let hidden_low_poly = BakeVisualization { low_poly: BakeOverlay { shown: false, ..low_poly }, ..neutral_parts };
|
||||
let background = render(&mut h, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_neutral_background");
|
||||
assert_same(
|
||||
&render(&mut h, &shaded(&frame, |s| s.bake = Some(hidden_low_poly)), "bake_neutral_hidden"),
|
||||
&background,
|
||||
"a hidden project mesh draws nothing",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bake_neutral_material_looks_the_same_moving_as_still() {
|
||||
// Full quality keeps the first frame near settled; one sample missed by 6.6 levels
|
||||
const MAX_MEAN_LEVELS: f32 = 4.0;
|
||||
let Some((mut h, frame)) = setup() else { return };
|
||||
|
||||
let neutral = NeutralMaterial { roughness: 0.5, metallic: 1.0, ..NeutralMaterial::default() };
|
||||
let parts = BakeVisualization { low_poly: shown(BakeVisualization::default().low_poly), neutral: Some(neutral), ..BakeVisualization::default() };
|
||||
let still = shaded(&frame, |s| {
|
||||
s.taa = true;
|
||||
s.bake = Some(parts);
|
||||
});
|
||||
let first = render(&mut h, &still, "bake_neutral_first_frame");
|
||||
for _ in 1..TAA_SAMPLES {
|
||||
render(&mut h, &still, "bake_neutral_settling");
|
||||
}
|
||||
let settled = render(&mut h, &still, "bake_neutral_settled");
|
||||
|
||||
// Compared on the ball in the middle of the view, where the reflections are
|
||||
let (width, height) = (frame.size[0], frame.size[1]);
|
||||
let ball = (width * 3 / 8..width * 5 / 8).flat_map(|x| (height / 4..height / 2).map(move |y| (x, y)));
|
||||
let differences: Vec<f32> = ball.map(|(x, y)| (first.luma(x, y) - settled.luma(x, y)).abs()).collect();
|
||||
let mean_difference = differences.iter().sum::<f32>() / differences.len() as f32;
|
||||
assert!(mean_difference < MAX_MEAN_LEVELS, "the first frame is {mean_difference} levels off the settled one on average");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bake_neutral_material_stays_lit_at_any_roughness_once_settled() {
|
||||
// Near roughness 0 a bad sample gave NaN, and the settled average of all frames went black
|
||||
const MIN_BALL_LUMA: f32 = 20.0;
|
||||
let Some((mut h, frame)) = setup() else { return };
|
||||
|
||||
for roughness in [0.0, 0.05, 0.1] {
|
||||
let neutral = NeutralMaterial { roughness, ..NeutralMaterial::default() };
|
||||
let parts = BakeVisualization { low_poly: shown(BakeVisualization::default().low_poly), neutral: Some(neutral), ..BakeVisualization::default() };
|
||||
let still = shaded(&frame, |s| {
|
||||
s.taa = true;
|
||||
s.bake = Some(parts);
|
||||
});
|
||||
for _ in 0..TAA_SAMPLES {
|
||||
render(&mut h, &still, "bake_neutral_mirror_settling");
|
||||
}
|
||||
let settled = render(&mut h, &still, "bake_neutral_mirror_settled");
|
||||
let (width, height) = (frame.size[0], frame.size[1]);
|
||||
let ball = settled.mean(width * 3 / 8, height / 4, width * 5 / 8, height / 2);
|
||||
assert!(ball > MIN_BALL_LUMA, "roughness {roughness}: the settled ball is black ({ball})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bake_visualization_draws_the_high_poly_and_the_cage() {
|
||||
// A high poly inside the material ball, a cage around it, and how far a color must lead the others to count as that color
|
||||
@@ -246,15 +332,17 @@ fn bake_visualization_draws_the_high_poly_and_the_cage() {
|
||||
}
|
||||
h.renderer.set_bake_high(&h.device, &h.queue, Some(&high), HIGH_POLY_ID).unwrap();
|
||||
let corners: Vec<Vec3> = high.indices.iter().map(|index| (high.positions[*index as usize] - ball_center) * CAGE_SCALE + ball_center).collect();
|
||||
h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&corners, &CAGE_EDGES)), CAGE_TOPOLOGY);
|
||||
let bake = BakeVisualization { high_poly: false, cage: false, uv_seams: false, low_poly: true, only_set: None };
|
||||
h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some(CageGeometry { corners: &corners, edges: &CAGE_EDGES, missing_seams: &CAGE_EDGES }), CAGE_TOPOLOGY);
|
||||
let bake = BakeVisualization { low_poly: shown(BakeVisualization::default().low_poly), ..BakeVisualization::default() };
|
||||
let center = (frame.size[0] / 2, frame.size[1] / 2);
|
||||
|
||||
let only = |h: &mut Headless, parts: BakeVisualization, name: &str| render(h, &shaded(&frame, |s| s.bake = Some(parts)), name);
|
||||
let low_only = only(&mut h, bake, "bake_low_only");
|
||||
let hidden = only(&mut h, BakeVisualization { low_poly: false, ..bake }, "bake_low_hidden");
|
||||
let high_poly = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_poly");
|
||||
let caged = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage");
|
||||
let high_only = BakeVisualization { high_poly: shown(bake.high_poly), matching_error: shown(bake.matching_error), ..BakeVisualization::default() };
|
||||
let caged_parts = BakeVisualization { cage_surface: shown(bake.cage_surface), cage_wire: shown(bake.cage_wire), ..bake };
|
||||
let hidden = only(&mut h, BakeVisualization::default(), "bake_low_hidden");
|
||||
let high_poly = only(&mut h, high_only, "bake_high_poly");
|
||||
let caged = only(&mut h, caged_parts, "bake_cage");
|
||||
assert_same(&low_only, &render(&mut h, &frame, "bake_off"), "every part off draws only the low poly");
|
||||
let background = render(&mut h, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_background");
|
||||
assert_same(&hidden, &background, "without the low poly only the background is left");
|
||||
@@ -270,26 +358,63 @@ fn bake_visualization_draws_the_high_poly_and_the_cage() {
|
||||
|
||||
// Vertices the bake's rays miss turn red
|
||||
h.renderer.set_bake_high_missed(&h.queue, HIGH_POLY_ID, &vec![1.0; high.positions.len()]);
|
||||
let missed = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_missed");
|
||||
let missed = only(&mut h, high_only, "bake_high_missed");
|
||||
let [red, green, blue] = missed.at(center.0, center.1).map(i32::from);
|
||||
assert!(red > blue + COLOR_LEAD && red > green + COLOR_LEAD, "missed vertices draw red: {:?}", [red, green, blue]);
|
||||
let no_error = only(&mut h, BakeVisualization { matching_error: bake.matching_error, ..high_only }, "bake_high_missed_hidden");
|
||||
assert_same(&no_error, &high_poly, "with the matching error hidden the missed vertices keep the high poly's color");
|
||||
let green_error = BakeOverlay { color: [0.0, 1.0, 0.0], ..high_only.matching_error };
|
||||
let [red, green, blue] =
|
||||
only(&mut h, BakeVisualization { matching_error: green_error, ..high_only }, "bake_high_missed_green").at(center.0, center.1).map(i32::from);
|
||||
assert!(green > red + COLOR_LEAD && green > blue + COLOR_LEAD, "the matching error's color reaches the shader: {:?}", [red, green, blue]);
|
||||
|
||||
// Show for selected texture set only: the other set's low poly and the cage of set 0 drop out
|
||||
let first_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(0), ..bake }, "bake_only_first_set");
|
||||
let second_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(1), ..bake }, "bake_only_second_set");
|
||||
assert_ne!(first_set.px, caged.px, "the second set's low poly is left out");
|
||||
assert_ne!(second_set.px, caged.px, "the first set's low poly and cage are left out");
|
||||
assert_ne!(first_set.px, second_set.px);
|
||||
// Show for selected texture set only filters the cage (only set 0 has one here), never the low poly
|
||||
let first_set = only(&mut h, BakeVisualization { only_set: Some(0), ..caged_parts }, "bake_only_first_set");
|
||||
let second_set = only(&mut h, BakeVisualization { only_set: Some(1), ..caged_parts }, "bake_only_second_set");
|
||||
assert_same(&first_set, &caged, "set 0's cage stays and both sets' low poly draws");
|
||||
assert_same(&second_set, &low_only, "set 0's cage drops out, the low poly stays");
|
||||
|
||||
// UV seams draw over the low poly
|
||||
h.renderer.set_uv_seams(&h.device, &h.queue, MESH_ID, &ball.uv_seam_edges());
|
||||
let seams = only(&mut h, BakeVisualization { uv_seams: true, ..bake }, "bake_uv_seams");
|
||||
// The cage's surface and wireframe show apart, in their own color and opacity
|
||||
let surface_only = only(&mut h, BakeVisualization { cage_surface: shown(bake.cage_surface), ..bake }, "bake_cage_surface");
|
||||
let wire_only = only(&mut h, BakeVisualization { cage_wire: shown(bake.cage_wire), ..bake }, "bake_cage_wire");
|
||||
assert!(surface_only.px != low_only.px && wire_only.px != low_only.px && surface_only.px != wire_only.px, "each part of the cage draws on its own");
|
||||
let opaque_blue = BakeOverlay { color: [0.0, 0.0, 1.0], opacity: 1.0, ..caged_parts.cage_surface };
|
||||
let [red, green, blue] =
|
||||
only(&mut h, BakeVisualization { cage_surface: opaque_blue, ..bake }, "bake_cage_surface_blue").at(center.0, center.1).map(i32::from);
|
||||
assert!(blue > red + COLOR_LEAD && blue > green + COLOR_LEAD, "an opaque blue cage hides the ball: {:?}", [red, green, blue]);
|
||||
let clear = only(&mut h, BakeVisualization { cage_surface: BakeOverlay { opacity: 0.0, ..opaque_blue }, ..bake }, "bake_cage_surface_clear");
|
||||
assert_same(&clear, &low_only, "a fully transparent cage leaves the ball as it is");
|
||||
|
||||
// High-poly vertices another set owns are left out
|
||||
h.renderer.set_bake_high_missed(&h.queue, HIGH_POLY_ID, &vec![-1.0; high.positions.len()]);
|
||||
let background = render(&mut h, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_high_hidden_background");
|
||||
assert_same(&only(&mut h, high_only, "bake_high_other_set"), &background, "a high poly owned by other sets draws nothing");
|
||||
h.renderer.set_bake_high_missed(&h.queue, HIGH_POLY_ID, &vec![0.0; high.positions.len()]);
|
||||
|
||||
// The missing seams draw over the low poly in their color
|
||||
h.renderer.set_missing_seams(&h.device, &h.queue, MESH_ID, &ball.wire_edges());
|
||||
let seams = only(&mut h, BakeVisualization { missing_seams: shown(bake.missing_seams), ..bake }, "bake_missing_seams");
|
||||
assert_ne!(seams.px, low_only.px, "the seams show");
|
||||
let green_seams = BakeOverlay { color: [0.0, 1.0, 0.0], ..shown(bake.missing_seams) };
|
||||
assert_ne!(
|
||||
only(&mut h, BakeVisualization { missing_seams: green_seams, ..bake }, "bake_missing_seams_green").px,
|
||||
seams.px,
|
||||
"the seams' color reaches the shader"
|
||||
);
|
||||
let uv = Frame { view_id: 2, kind: ViewKind::Uv { ts: 0, zoom: 1.0, pan: [0.0, 0.0] }, ..frame.clone() };
|
||||
let uv_plain = render(&mut h, &shaded(&uv, |s| s.bake = Some(bake)), "bake_missing_seams_uv_off");
|
||||
let uv_seams = render(&mut h, &shaded(&uv, |s| s.bake = Some(BakeVisualization { missing_seams: green_seams, ..bake })), "bake_missing_seams_uv");
|
||||
assert_ne!(uv_seams.px, uv_plain.px, "the seams show in the 2D view too");
|
||||
let caged_seams = only(&mut h, BakeVisualization { missing_seams: green_seams, ..caged_parts }, "bake_missing_seams_cage");
|
||||
let uncaged_seams = only(&mut h, BakeVisualization { missing_seams: green_seams, ..bake }, "bake_missing_seams_no_cage");
|
||||
let caged_plain = only(&mut h, caged_parts, "bake_cage_no_seams");
|
||||
assert_ne!(caged_seams.px, caged_plain.px, "the seams show with the cage");
|
||||
assert_ne!(caged_seams.px, uncaged_seams.px);
|
||||
|
||||
// A new distance with the same topology only moves the corners
|
||||
let grown: Vec<Vec3> = corners.iter().map(|corner| (*corner - ball_center) * 2.0 + ball_center).collect();
|
||||
h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&grown, &CAGE_EDGES)), CAGE_TOPOLOGY);
|
||||
let bigger = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage_grown");
|
||||
h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some(CageGeometry { corners: &grown, edges: &CAGE_EDGES, missing_seams: &CAGE_EDGES }), CAGE_TOPOLOGY);
|
||||
let bigger = only(&mut h, caged_parts, "bake_cage_grown");
|
||||
assert_ne!(caged.px, bigger.px, "the cage grew");
|
||||
}
|
||||
|
||||
@@ -300,6 +425,7 @@ fn oversized_bake_high_poly_leaves_the_view_renderable() {
|
||||
let high = primitives::sphere(0.5, 16, 8);
|
||||
headless.renderer.set_bake_high(&headless.device, &headless.queue, Some(&high), 1).unwrap();
|
||||
let limit = headless.device.limits().max_buffer_size;
|
||||
|
||||
// The viewport vertex contains position, normal, tangent and UV: twelve f32 values
|
||||
let vertex_count = limit as usize / (12 * std::mem::size_of::<f32>()) + 1;
|
||||
let oversized = texturecraft_geom::Mesh { positions: vec![Vec3::ZERO; vertex_count], ..Default::default() };
|
||||
@@ -307,7 +433,7 @@ fn oversized_bake_high_poly_leaves_the_view_renderable() {
|
||||
assert!(error.contains("GPU buffer limit"), "{error}");
|
||||
|
||||
headless.renderer.set_bake_high_missed(&headless.queue, 2, &[]);
|
||||
let bake = BakeVisualization { high_poly: true, cage: false, uv_seams: false, low_poly: false, only_set: None };
|
||||
let bake = BakeVisualization { high_poly: shown(BakeVisualization::default().high_poly), ..BakeVisualization::default() };
|
||||
let cleared = render(&mut headless, &shaded(&frame, |shade| shade.bake = Some(bake)), "bake_oversized_cleared");
|
||||
let background = render(&mut headless, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_oversized_background");
|
||||
assert_same(&cleared, &background, "an oversized replacement must not leave the previous high poly visible");
|
||||
@@ -317,10 +443,10 @@ fn oversized_bake_high_poly_leaves_the_view_renderable() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bake_low_poly_visibility_also_filters_its_wireframe() {
|
||||
fn bake_low_poly_visibility_also_filters_its_wireframe_but_not_by_selected_set() {
|
||||
let Some((mut headless, frame)) = setup() else { return };
|
||||
|
||||
let bake = BakeVisualization { high_poly: false, cage: false, uv_seams: false, low_poly: false, only_set: None };
|
||||
let bake = BakeVisualization::default();
|
||||
let hidden = shaded(&frame, |shade| {
|
||||
shade.bake = Some(bake);
|
||||
shade.wireframe_3d = true;
|
||||
@@ -332,13 +458,13 @@ fn bake_low_poly_visibility_also_filters_its_wireframe() {
|
||||
|
||||
for texture_set in [0, 1] {
|
||||
let selected = shaded(&hidden, |shade| {
|
||||
shade.bake = Some(BakeVisualization { low_poly: true, only_set: Some(texture_set), ..bake });
|
||||
shade.bake = Some(BakeVisualization { low_poly: shown(bake.low_poly), only_set: Some(texture_set), ..bake });
|
||||
shade.highlight = Some(texturecraft_render::SetHighlight { set: 1 - texture_set, color: [1.0, 0.5, 0.0] });
|
||||
});
|
||||
let expected = Frame { visible: vec![texture_set == 0, texture_set == 1], ..selected.clone() };
|
||||
let expected = shaded(&selected, |shade| shade.bake = Some(BakeVisualization { only_set: None, ..shade.bake.unwrap_or(bake) }));
|
||||
let actual = render(&mut headless, &selected, &format!("bake_wire_selected_{texture_set}"));
|
||||
let expected = render(&mut headless, &expected, &format!("bake_wire_expected_{texture_set}"));
|
||||
assert_same(&actual, &expected, "the wireframe and highlight respect the selected texture set");
|
||||
assert_same(&actual, &expected, "the selected-set filter leaves the low poly, its wireframe and highlight alone");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ use std::path::PathBuf;
|
||||
/// has a download budget: of the CJK faces only the Japanese one, ~4.5 MB).
|
||||
const MANIFESTS: &[(&str, Faces, Faces)] = &[
|
||||
("fonts/manifest.txt", &[("BIZ UDPGothic", "Regular"), ("Noto Sans CJK SC", "Regular"), ARABIC], &[("BIZ UDPGothic", "Regular"), ARABIC]),
|
||||
// The interface font, regular and semibold (0.8 MB).
|
||||
// The interface font has regular and semibold faces
|
||||
(LATIN_MANIFEST, LATIN, LATIN),
|
||||
];
|
||||
/// The Arabic face (0.8 MB, so the web build has it too).
|
||||
@@ -38,6 +38,7 @@ fn main() {
|
||||
Err(e) => println!("cargo::warning=building without craft-fonts: CRAFT_FONTS_DIR={}: {e}", dir.display()),
|
||||
}
|
||||
}
|
||||
|
||||
src.push_str("];\n");
|
||||
let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_fonts.rs");
|
||||
if let Err(e) = std::fs::write(&out, src) {
|
||||
@@ -52,6 +53,7 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web:
|
||||
if rel == LATIN_MANIFEST && !manifest.exists() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
|
||||
let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e}", manifest.display()))?;
|
||||
let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32");
|
||||
let wanted = if wasm { web } else { desktop };
|
||||
@@ -61,9 +63,11 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web:
|
||||
let [family, style, file, scripts, ..] = f.as_slice() else {
|
||||
return Err(format!("malformed manifest line: {line}"));
|
||||
};
|
||||
|
||||
if !wanted.contains(&(*family, *style)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?;
|
||||
println!("cargo::rerun-if-changed={}", path.display());
|
||||
if rel == LATIN_MANIFEST {
|
||||
@@ -72,6 +76,7 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web:
|
||||
std::fs::write(&out, without_private_use(&bytes).map_err(|e| format!("{file}: {e}"))?).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
path = out;
|
||||
}
|
||||
|
||||
let scripts: Vec<String> = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
@@ -80,6 +85,7 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web:
|
||||
path.display().to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
|
||||
@@ -13,9 +13,11 @@ pub fn generate(dir: Option<&Path>, required: bool) -> Result<String, String> {
|
||||
source.push_str("];\n");
|
||||
return Ok(source);
|
||||
};
|
||||
|
||||
if !dir.is_absolute() {
|
||||
return Err("CRAFT_I18N_DIR must be an absolute path".into());
|
||||
}
|
||||
|
||||
let locales = dir.join("locales");
|
||||
let entries = std::fs::read_dir(&locales).map_err(|e| format!("{}: {e}", locales.display()))?;
|
||||
println!("cargo::rerun-if-changed={}", locales.display());
|
||||
@@ -26,23 +28,26 @@ pub fn generate(dir: Option<&Path>, required: bool) -> Result<String, String> {
|
||||
paths.push(entry.path());
|
||||
}
|
||||
}
|
||||
|
||||
paths.sort();
|
||||
let mut count = 0;
|
||||
let mut catalogs = Vec::new();
|
||||
for path in paths {
|
||||
// Watch directories too: adding/removing an app catalog must rebuild the embedding.
|
||||
// Watch directories so adding or removing an app catalog rebuilds the embedding
|
||||
println!("cargo::rerun-if-changed={}", path.display());
|
||||
let app = path.join("texturecraft.tsv");
|
||||
if !app.is_file() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let locale = path.file_name().and_then(|n| n.to_str()).ok_or("non-UTF-8 locale")?;
|
||||
let common = path.join("common.tsv");
|
||||
let embed = |file: &Path| -> Result<(String, &'static str), String> {
|
||||
let text = std::fs::read_to_string(file).map_err(|e| format!("{}: {e}", file.display()))?;
|
||||
let name = file.to_str().ok_or("non-UTF-8 catalog path")?;
|
||||
println!("cargo::rerun-if-changed={name}");
|
||||
// The shared runtime requires static inputs; this short-lived build process owns them.
|
||||
|
||||
// The shared runtime needs static inputs for this short-lived build process
|
||||
Ok((format!("include_str!({name:?})"), Box::leak(text.into_boxed_str())))
|
||||
};
|
||||
let (shared, shared_text) = if common.is_file() { embed(&common)? } else { ("\"\"".into(), "") };
|
||||
@@ -55,12 +60,14 @@ pub fn generate(dir: Option<&Path>, required: bool) -> Result<String, String> {
|
||||
if required && count == 0 {
|
||||
return Err("no TextureCraft translation catalogs found".into());
|
||||
}
|
||||
// Reject the same rows the runtime would skip, before required builds can ship English fallbacks.
|
||||
|
||||
// Reject rows the runtime would skip before required builds can ship English fallbacks
|
||||
let (runtime, mut problems) = craft_i18n::I18n::new(Box::leak(catalogs.into_boxed_slice()), &[]);
|
||||
problems.extend(runtime.check_all());
|
||||
if !problems.is_empty() {
|
||||
return Err(format!("invalid translation catalogs in {}: {}", locales.display(), problems.join("; ")));
|
||||
}
|
||||
|
||||
source.push_str("];\n");
|
||||
Ok(source)
|
||||
}
|
||||
@@ -83,6 +90,7 @@ pub fn embed() {
|
||||
"pub static CRAFT_I18N: &craft_i18n::Embedded = &[];\n".into()
|
||||
}
|
||||
};
|
||||
|
||||
let out = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_i18n.rs");
|
||||
if let Err(error) = std::fs::write(&out, source) {
|
||||
println!("cargo::error=writing {}: {error}", out.display());
|
||||
|
||||
@@ -5,4 +5,6 @@ pub struct BakeJob {
|
||||
pub queue: Vec<usize>,
|
||||
pub current: Option<RunningBake>,
|
||||
pub total: usize,
|
||||
/// The mesh the job was started on: a result for another mesh (changed or reimported meanwhile) is not applied.
|
||||
pub mesh_id: u64,
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
//! Problems the next bake would have, listed above the bake bar before Bake is pressed
|
||||
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use egui_phosphor::regular as icon;
|
||||
use texturecraft_engine::Session;
|
||||
use texturecraft_engine::geom::Mesh;
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::i18n::trf;
|
||||
use crate::theme::Tokens;
|
||||
|
||||
/// Share of a texture set's UV layout that may overlap before it is listed (as mesh import warns)
|
||||
const UV_OVERLAP_WARNING: f32 = 0.01;
|
||||
|
||||
/// How many part names a warning spells out before "and N more"
|
||||
const NAMES_SHOWN: usize = 3;
|
||||
|
||||
/// The warnings' gap above the bake bar
|
||||
const WARNINGS_GAP: f32 = 8.0;
|
||||
|
||||
/// The warnings above bake mode's bake bar in the 3D view `viewport`, until a bake starts
|
||||
pub(crate) fn bake_warnings(app: &TextureCraftApp, ctx: &egui::Context, viewport: egui::Rect) {
|
||||
if app.bake_progress().is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
let warnings = cached_warnings(ctx, &app.session);
|
||||
if warnings.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let tokens = Tokens::get(ctx);
|
||||
let above_bar = super::BAKE_BAR_MARGIN + ctx.global_style().spacing.interact_size.y + WARNINGS_GAP;
|
||||
egui::Area::new(egui::Id::unique("bake_warnings")).constrain_to(viewport).anchor(egui::Align2::CENTER_BOTTOM, egui::vec2(0.0, -above_bar)).show(
|
||||
ctx,
|
||||
|ui| {
|
||||
egui::Frame::popup(ui.style()).fill(tokens.panel).show(ui, |ui| {
|
||||
for warning in warnings.iter() {
|
||||
ui.label(egui::RichText::new(format!("{} {warning}", icon::WARNING)).color(tokens.warning));
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// The warnings for the texture sets the next bake includes, worked out again only when what they read changes
|
||||
pub(crate) fn cached_warnings(ctx: &egui::Context, session: &Session) -> Arc<Vec<String>> {
|
||||
let id = egui::Id::unique("bake_check_warnings");
|
||||
let key = inputs_key(session);
|
||||
|
||||
// A handle, not an address: a rebuilt high poly could reuse a dropped one's address
|
||||
let high = session.bake_meshes.merged_high().map_or_else(Weak::new, |high| Arc::downgrade(&high.mesh));
|
||||
if let Some((cached_key, cached_high, cached)) = ctx.data(|data| data.get_temp::<(String, Weak<Mesh>, Arc<Vec<String>>)>(id))
|
||||
&& cached_key == key
|
||||
&& cached_high.ptr_eq(&high)
|
||||
{
|
||||
return cached;
|
||||
}
|
||||
|
||||
let fresh = Arc::new(warnings(session));
|
||||
ctx.data_mut(|data| data.insert_temp(id, (key, high, fresh.clone())));
|
||||
fresh
|
||||
}
|
||||
|
||||
/// Everything the warnings read or show apart from the high poly (cached as a handle): the low poly, the UI language, and per included set its name, material, high-poly settings, UV tile resolutions and the tiles left out of the bake
|
||||
fn inputs_key(session: &Session) -> String {
|
||||
let sets: Vec<_> = baked_sets(session)
|
||||
.filter_map(|index| {
|
||||
let set = session.doc.project.texture_sets.get(index)?;
|
||||
Some((index, &set.name, set.material, &set.bake.high_poly, &set.tile_resolutions, &set.bake_excluded_tiles))
|
||||
})
|
||||
.collect();
|
||||
|
||||
format!("{}|{}|{sets:?}", session.mesh_id, crate::i18n::current().code)
|
||||
}
|
||||
|
||||
/// The texture sets the next bake includes
|
||||
fn baked_sets(session: &Session) -> impl Iterator<Item = usize> + '_ {
|
||||
session.doc.project.texture_sets.iter().enumerate().filter(|(_, set)| set.bake.common.is_enabled && set.has_enabled_bake_tiles()).map(|(index, _)| index)
|
||||
}
|
||||
|
||||
/// Overlapping UVs per included set, its low-poly parts "By Mesh Name" pairs with nothing, then the high-poly parts no included set bakes from
|
||||
pub(crate) fn warnings(session: &Session) -> Vec<String> {
|
||||
let mut lines = Vec::new();
|
||||
let included: Vec<usize> = baked_sets(session).collect();
|
||||
for &index in &included {
|
||||
let Some(set) = session.doc.project.texture_sets.get(index) else { continue };
|
||||
|
||||
let overlap = session.bake_uv_overlap(index).unwrap_or(0.0);
|
||||
if overlap > UV_OVERLAP_WARNING {
|
||||
let percent = format!("{:.1}", overlap * 100.0);
|
||||
lines.push(trf(
|
||||
"{set}: {percent}% of the UV layout overlaps, so those texels bake one place for several",
|
||||
&[("set", &set.name), ("percent", &percent)],
|
||||
));
|
||||
}
|
||||
|
||||
let Ok(Some(pairs)) = session.bake_name_pairs(index) else { continue };
|
||||
|
||||
let unpaired_low: Vec<&str> = pairs.iter().filter(|pair| pair.high.is_none()).filter_map(|pair| pair.low.as_deref()).collect();
|
||||
if !unpaired_low.is_empty() {
|
||||
lines.push(trf("{set}: no high poly part matches {names}", &[("set", &set.name), ("names", &listed(&unpaired_low))]));
|
||||
}
|
||||
}
|
||||
|
||||
let unpaired_high = session.bake_unpaired_high_parts(&included).unwrap_or_default();
|
||||
if !unpaired_high.is_empty() {
|
||||
let names: Vec<&str> = unpaired_high.iter().map(String::as_str).collect();
|
||||
lines.push(trf("No low poly part matches {names}", &[("names", &listed(&names))]));
|
||||
}
|
||||
|
||||
lines
|
||||
}
|
||||
|
||||
/// `names` joined, the first few spelled out and the rest counted
|
||||
fn listed(names: &[&str]) -> String {
|
||||
let shown = names.iter().take(NAMES_SHOWN).copied().collect::<Vec<_>>().join(", ");
|
||||
match names.len().checked_sub(NAMES_SHOWN).filter(|more| *more > 0) {
|
||||
Some(more) => trf("{names} and {count} more", &[("names", &shown), ("count", &more)]),
|
||||
None => shown,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use texturecraft_engine::core::MeshMatchMode;
|
||||
|
||||
/// Part `index` named `name` (an OBJ object): a quad at x offset `x` whose UVs span `u` to `u` + 0.2
|
||||
fn quad(name: &str, index: usize, x: f32, u: f32) -> String {
|
||||
let first = index * 4 + 1;
|
||||
format!(
|
||||
"o {name}\nv {x} 0 0\nv {} 0 0\nv {} 1 0\nv {x} 1 0\nvt {u} 0\nvt {} 0\nvt {} 1\nvt {u} 1\nf {first}/{first} {}/{} {}/{} {}/{}\n",
|
||||
x + 1.0,
|
||||
x + 1.0,
|
||||
u + 0.2,
|
||||
u + 0.2,
|
||||
first + 1,
|
||||
first + 1,
|
||||
first + 2,
|
||||
first + 2,
|
||||
first + 3,
|
||||
first + 3
|
||||
)
|
||||
}
|
||||
|
||||
fn session(overlapping: bool) -> Session {
|
||||
let names = ["Box_low", "Lid_low", "Bolt_low", "Nut_low", "Pin_low"];
|
||||
let obj: String =
|
||||
names.iter().enumerate().map(|(index, name)| quad(name, index, index as f32 * 2.0, if overlapping { 0.0 } else { index as f32 * 0.2 })).collect();
|
||||
Session::from_mesh_bytes("parts.obj", obj.as_bytes(), 128, "parts").unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clean_setup_lists_nothing() {
|
||||
let mut session = session(false);
|
||||
assert_eq!(warnings(&session), Vec::<String>::new());
|
||||
session.add_high_poly_bytes("high.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap();
|
||||
assert_eq!(warnings(&session), Vec::<String>::new(), "\"Always\" pairs every part");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_a_set_refreshes_the_cached_warnings() {
|
||||
let mut session = session(true);
|
||||
let ctx = egui::Context::default();
|
||||
let before = cached_warnings(&ctx, &session);
|
||||
assert!(before.iter().any(|line| line.starts_with(&session.doc.project.texture_sets[0].name)), "{before:?}");
|
||||
|
||||
session.doc.project.texture_sets[0].name = "Renamed".into();
|
||||
let after = cached_warnings(&ctx, &session);
|
||||
assert!(after.iter().any(|line| line.starts_with("Renamed:")), "{after:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swapping_the_high_poly_refreshes_the_cached_warnings() {
|
||||
let mut session = session(false);
|
||||
session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName;
|
||||
session.add_high_poly_bytes("spare.obj", b"o Spare_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
assert!(cached_warnings(&ctx, &session).contains(&"No low poly part matches Spare_high".to_owned()));
|
||||
|
||||
// The new high poly's mesh may take the dropped one's address
|
||||
drop(session.remove_high_poly(0).unwrap());
|
||||
session.add_high_poly_bytes("box.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap();
|
||||
let after = cached_warnings(&ctx, &session);
|
||||
assert!(!after.iter().any(|line| line.contains("Spare_high")), "{after:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaving_the_overlapping_tile_out_refreshes_the_cached_warnings() {
|
||||
// One quad in tile 1001, two on the same UVs in tile 1002
|
||||
let obj = [quad("First_low", 0, 0.0, 0.0), quad("Second_low", 1, 2.0, 1.0), quad("Third_low", 2, 4.0, 1.0)].concat();
|
||||
let mut session = Session::from_mesh_bytes("tiles.obj", obj.as_bytes(), 128, "tiles").unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
assert_eq!(cached_warnings(&ctx, &session).len(), 1, "tile 1002 overlaps");
|
||||
|
||||
session.doc.project.texture_sets[0].bake_excluded_tiles.insert(1002);
|
||||
assert_eq!(*cached_warnings(&ctx, &session), Vec::<String>::new(), "tile 1001 alone has no overlap");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_uvs_and_unpaired_parts_are_listed() {
|
||||
let mut session = session(true);
|
||||
session
|
||||
.add_high_poly_bytes("high.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\no Spare_high\nv 2 0 0\nv 3 0 0\nv 2 1 0\nf 4 5 6\n".to_vec())
|
||||
.unwrap();
|
||||
session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName;
|
||||
let set = session.doc.project.texture_sets[0].name.clone();
|
||||
|
||||
assert_eq!(
|
||||
warnings(&session),
|
||||
[
|
||||
format!("{set}: 100.0% of the UV layout overlaps, so those texels bake one place for several"),
|
||||
format!("{set}: no high poly part matches Lid_low, Bolt_low, Nut_low and 1 more"),
|
||||
"No low poly part matches Spare_high".to_owned(),
|
||||
]
|
||||
);
|
||||
|
||||
session.doc.project.texture_sets[0].bake.common.is_enabled = false;
|
||||
assert_eq!(warnings(&session), Vec::<String>::new(), "a set the bake leaves out is not checked");
|
||||
}
|
||||
}
|
||||
@@ -1,58 +1,191 @@
|
||||
use egui::collapsing_header::CollapsingState;
|
||||
use egui::{Rect, Ui, vec2};
|
||||
use egui_phosphor::regular as icon;
|
||||
use texturecraft_render::BakeOverlay;
|
||||
|
||||
use super::BakeVisualizationToggles;
|
||||
use super::section_opening::SectionOpening;
|
||||
use crate::TextureCraftApp;
|
||||
use crate::i18n::tr;
|
||||
use crate::i18n::{n_, tr, trf};
|
||||
use crate::screen_color_pick::eyedropper;
|
||||
use crate::theme::Tokens;
|
||||
use crate::widgets::{icon_button_without_tooltip, section_chevron};
|
||||
use crate::widgets::{color_swatch, combo, icon_button, section_chevron, slider};
|
||||
|
||||
/// The panel's width and its gap from the 3D view's top-left corner
|
||||
const PANEL_WIDTH: f32 = 280.0;
|
||||
const PANEL_MARGIN: f32 = 12.0;
|
||||
|
||||
/// Size of the panel's eye buttons
|
||||
/// Opacity of the panel's backing
|
||||
const PANEL_OPACITY: f32 = 0.92;
|
||||
|
||||
/// Size of the panel's eye button, and of the smaller buttons on its rows
|
||||
const EYE_BUTTON_SIZE: f32 = 22.0;
|
||||
const ROW_BUTTON_SIZE: f32 = 18.0;
|
||||
|
||||
/// Width of an overlay's color swatch
|
||||
const SWATCH_WIDTH: f32 = 44.0;
|
||||
|
||||
/// The neutral material's quality steps: samples per pixel and their names
|
||||
const QUALITIES: [(u32, &str); 6] = [
|
||||
(4, n_("Very Low (4 spp)")),
|
||||
(16, n_("Low (16 spp)")),
|
||||
(32, n_("Medium (32 spp)")),
|
||||
(64, n_("High (64 spp)")),
|
||||
(128, n_("Very High (128 spp)")),
|
||||
(256, n_("Ultra (256 spp)")),
|
||||
];
|
||||
|
||||
/// The Baking Visualization panel in the top-left corner of bake mode's 3D view `view`
|
||||
pub(crate) fn bake_visualization_panel(app: &mut TextureCraftApp, ui: &Ui, view: Rect) {
|
||||
let toggles = &mut app.ui.bake_visualization;
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
egui::Area::new(ui.scope_id().with("bake_visualization_panel")).fixed_pos(view.left_top() + vec2(PANEL_MARGIN, PANEL_MARGIN)).constrain_to(view).show(
|
||||
ui.ctx(),
|
||||
|ui| {
|
||||
ui.set_width(PANEL_WIDTH);
|
||||
let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("bake_visualization_open"), true);
|
||||
let header = eye_row(ui, &mut toggles.on, tr("Baking Visualization"), Some(collapsing_state.is_open()));
|
||||
if header.clicked() {
|
||||
collapsing_state.toggle(ui);
|
||||
}
|
||||
// Its own backing, so the panel reads in every theme over whatever the 3D view shows
|
||||
egui::Frame::popup(ui.style()).fill(tokens.panel.gamma_multiply(PANEL_OPACITY)).show(ui, |ui| {
|
||||
ui.set_width(PANEL_WIDTH);
|
||||
|
||||
collapsing_state.show_body_unindented(ui, |ui| {
|
||||
ui.add_enabled_ui(toggles.on, |ui| {
|
||||
ui.checkbox(&mut toggles.selected_set_only, tr("Show for Selected Texture Set Only"));
|
||||
eye_row(ui, &mut toggles.high_poly, tr("High Definition Mesh (HP)"), None);
|
||||
eye_row(ui, &mut toggles.cage, tr("Cage"), None);
|
||||
eye_row(ui, &mut toggles.uv_seams, tr("UV Seams"), None);
|
||||
eye_row(ui, &mut toggles.low_poly, tr("Project Mesh (LP)"), None);
|
||||
});
|
||||
// Ids renamed with the reference defaults, so open/closed states saved by earlier builds don't carry over
|
||||
let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("baking_visualization_open"), true);
|
||||
if header(ui, toggles, collapsing_state.is_open()).clicked() {
|
||||
collapsing_state.toggle(ui);
|
||||
}
|
||||
|
||||
collapsing_state.show_body_unindented(ui, |ui| sections(ui, toggles));
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// A row with `label`, a chevron when `open` is given, and an eye button on the right that switches `shown`; returns the label's response
|
||||
fn eye_row(ui: &mut Ui, shown: &mut bool, label: &str, open: Option<bool>) -> egui::Response {
|
||||
/// The panel's sections below its header
|
||||
fn sections(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.checkbox(&mut toggles.selected_set_only, tr("Show for Selected Texture Set Only"));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.label(egui::RichText::new(icon::INFO).color(Tokens::get(ui.ctx()).text_dim))
|
||||
.on_hover_text(tr("Only the cage and the high poly meshes of the selected texture set show."));
|
||||
});
|
||||
});
|
||||
|
||||
// The eye greys what it hides, and holds the project mesh shown
|
||||
let meshes_editable = !toggles.hide_baking_meshes;
|
||||
if collapsible(ui, "high_poly", tr("High Definition Mesh (HP)"), SectionOpening::Open, true, meshes_editable, |ui| {
|
||||
overlay_row(ui, "bake_high_poly_color", tr("Mesh"), &mut toggles.high_poly_mesh);
|
||||
overlay_row(ui, "bake_matching_error_color", tr("Matching Error"), &mut toggles.matching_error);
|
||||
}) {
|
||||
toggles.reset_high_poly();
|
||||
}
|
||||
|
||||
if collapsible(ui, "cage", tr("Cage"), SectionOpening::Open, true, meshes_editable, |ui| {
|
||||
overlay_row(ui, "bake_cage_surface_color", tr("Cage Surface"), &mut toggles.cage_surface);
|
||||
ui.add_enabled_ui(toggles.cage_surface.shown, |ui| slider(ui, tr("Cage Surface Opacity"), &mut toggles.cage_surface.opacity, 0.0..=1.0, 2));
|
||||
overlay_row(ui, "bake_cage_wire_color", tr("Cage Wireframe"), &mut toggles.cage_wire);
|
||||
ui.add_enabled_ui(toggles.cage_wire.shown, |ui| slider(ui, tr("Cage Wireframe Opacity"), &mut toggles.cage_wire.opacity, 0.0..=1.0, 2));
|
||||
}) {
|
||||
toggles.reset_cage();
|
||||
}
|
||||
|
||||
if collapsible(ui, "seams", tr("UV Seams"), SectionOpening::Closed, true, true, |ui| {
|
||||
overlay_row(ui, "bake_missing_seam_color", tr("Missing Seams on Hard Edges"), &mut toggles.missing_seams);
|
||||
}) {
|
||||
toggles.reset_seams();
|
||||
}
|
||||
|
||||
if collapsible(ui, "project_mesh", tr("Project Mesh (LP)"), SectionOpening::Closed, true, true, |ui| {
|
||||
ui.add_enabled_ui(meshes_editable, |ui| overlay_row(ui, "bake_project_mesh_color", tr("Project Mesh"), &mut toggles.project_mesh));
|
||||
ui.add_enabled_ui(toggles.project_mesh.shown, |ui| {
|
||||
collapsible(ui, "neutral_material", tr("Neutral Material"), SectionOpening::Open, false, true, |ui| neutral_material(ui, toggles))
|
||||
});
|
||||
}) {
|
||||
toggles.reset_project_mesh();
|
||||
}
|
||||
}
|
||||
|
||||
/// The project mesh's neutral material (picked in the 3D view's view menu): its quality, roughness, metallic, occlusion strength and bent normal
|
||||
fn neutral_material(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) {
|
||||
ui.add_enabled_ui(toggles.neutral_shown, |ui| {
|
||||
let neutral = &mut toggles.neutral;
|
||||
let selected = QUALITIES.iter().find(|(samples, _)| *samples == neutral.samples_per_pixel).map_or("", |(_, name)| tr(name));
|
||||
combo(ui, tr("Quality"), selected, |ui| {
|
||||
for (samples, name) in QUALITIES {
|
||||
ui.selectable_value(&mut neutral.samples_per_pixel, samples, tr(name));
|
||||
}
|
||||
});
|
||||
slider(ui, tr("Roughness"), &mut neutral.roughness, 0.0..=1.0, 2);
|
||||
slider(ui, tr("Metallic"), &mut neutral.metallic, 0.0..=1.0, 2);
|
||||
slider(ui, tr("AO intensity"), &mut neutral.ao_intensity, 0.0..=1.0, 2);
|
||||
ui.checkbox(&mut neutral.bent_normal, tr("Bent Normal"));
|
||||
ui.add_enabled_ui(neutral.bent_normal, |ui| {
|
||||
slider(ui, tr("Bent Normal Diffuse Amount"), &mut neutral.bent_normal_diffuse, 0.0..=1.0, 2);
|
||||
slider(ui, tr("Bent Normal Specular Amount"), &mut neutral.bent_normal_specular, 0.0..=1.0, 2);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// A section `title`, open or closed at first as `opening` says, with a reset button on its header when `resettable` and its contents greyed unless `editable`; returns whether the reset was clicked
|
||||
fn collapsible(ui: &mut Ui, id: &str, title: &str, opening: SectionOpening, resettable: bool, editable: bool, body: impl FnOnce(&mut Ui)) -> bool {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let mut collapsing_state =
|
||||
CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id(("baking_visualization_section", id)), opening == SectionOpening::Open);
|
||||
let (header, reset) = ui
|
||||
.horizontal(|ui| {
|
||||
ui.set_min_height(EYE_BUTTON_SIZE);
|
||||
let text = egui::RichText::new(format!("{} {title}", section_chevron(ui, collapsing_state.is_open()).text())).strong().color(tokens.text_strong);
|
||||
let header = ui.add(egui::Label::new(text).selectable(false).sense(egui::Sense::click()));
|
||||
|
||||
// Dimmed while the section is closed, as the reference draws it
|
||||
let reset = resettable.then(|| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.add_enabled_ui(collapsing_state.is_open() && editable, |ui| {
|
||||
icon_button(ui, icon::CLOCK_COUNTER_CLOCKWISE, &trf("Reset {section}", &[("section", &title)]), false, ROW_BUTTON_SIZE)
|
||||
})
|
||||
.inner
|
||||
})
|
||||
.inner
|
||||
});
|
||||
(header, reset)
|
||||
})
|
||||
.inner;
|
||||
if header.clicked() {
|
||||
collapsing_state.toggle(ui);
|
||||
}
|
||||
|
||||
collapsing_state.show_body_indented(&header, ui, |ui| {
|
||||
ui.add_enabled_ui(editable, body);
|
||||
});
|
||||
reset.is_some_and(|reset| reset.clicked())
|
||||
}
|
||||
|
||||
/// A checkbox for whether `overlay` shows, with its color swatch and an eyedropper for it on the right
|
||||
fn overlay_row(ui: &mut Ui, id: &str, label: &str, overlay: &mut BakeOverlay) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.checkbox(&mut overlay.shown, label);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.add_enabled_ui(overlay.shown, |ui| {
|
||||
eyedropper(
|
||||
ui,
|
||||
ui.make_persistent_id(id),
|
||||
&mut overlay.color,
|
||||
&trf("Pick the {overlay} Color from the Screen", &[("overlay", &label)]),
|
||||
ROW_BUTTON_SIZE,
|
||||
);
|
||||
color_swatch(ui, id, &mut overlay.color, SWATCH_WIDTH);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// The panel's title with a chevron showing whether the panel is `open`, and the eye that hides the baking meshes; returns the title's response
|
||||
fn header(ui: &mut Ui, toggles: &mut BakeVisualizationToggles, open: bool) -> egui::Response {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
ui.horizontal(|ui| {
|
||||
ui.set_min_height(EYE_BUTTON_SIZE);
|
||||
let text = match open {
|
||||
Some(is_open) => egui::RichText::new(format!("{} {label}", section_chevron(ui, is_open).text())),
|
||||
None => egui::RichText::new(label),
|
||||
};
|
||||
let response = ui.add(egui::Label::new(text.color(tokens.text_strong)).selectable(false).sense(egui::Sense::click()));
|
||||
let text = egui::RichText::new(format!("{} {}", section_chevron(ui, open).text(), tr("Baking Visualization"))).color(tokens.text_strong);
|
||||
let response = ui.add(egui::Label::new(text).selectable(false).sense(egui::Sense::click()));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if icon_button_without_tooltip(ui, if *shown { icon::EYE } else { icon::EYE_SLASH }, label, false, EYE_BUTTON_SIZE).clicked() {
|
||||
*shown = !*shown;
|
||||
if icon_button(ui, icon::EYE_SLASH, tr("Hide Baking Meshes"), toggles.hide_baking_meshes, EYE_BUTTON_SIZE).clicked() {
|
||||
toggles.toggle_hiding();
|
||||
}
|
||||
});
|
||||
response
|
||||
|
||||
@@ -1,34 +1,140 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use texturecraft_render::BakeVisualization;
|
||||
use texturecraft_render::{BakeOverlay, BakeVisualization, NeutralMaterial};
|
||||
|
||||
/// The Baking Visualization panel's switches in bake mode's 3D view
|
||||
/// Opacity of the cage's surface and wireframe until changed
|
||||
const CAGE_OPACITY: f32 = 0.4;
|
||||
|
||||
/// The Baking Visualization panel's settings for bake mode's 3D view (view state, not saved in the project)
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct BakeVisualizationToggles {
|
||||
/// The panel's eye: the whole visualization on or off
|
||||
pub on: bool,
|
||||
/// The panel's eye: hides the high poly and the cage, whatever their own switches say
|
||||
pub hide_baking_meshes: bool,
|
||||
pub selected_set_only: bool,
|
||||
pub high_poly: bool,
|
||||
pub cage: bool,
|
||||
pub uv_seams: bool,
|
||||
pub low_poly: bool,
|
||||
pub high_poly_mesh: BakeOverlay,
|
||||
pub matching_error: BakeOverlay,
|
||||
pub cage_surface: BakeOverlay,
|
||||
pub cage_wire: BakeOverlay,
|
||||
pub missing_seams: BakeOverlay,
|
||||
pub project_mesh: BakeOverlay,
|
||||
/// Show the project mesh with [`Self::neutral`] instead of its painted material
|
||||
pub neutral_shown: bool,
|
||||
pub neutral: NeutralMaterial,
|
||||
}
|
||||
|
||||
impl Default for BakeVisualizationToggles {
|
||||
fn default() -> Self {
|
||||
Self { on: true, selected_set_only: false, high_poly: true, cage: true, uv_seams: false, low_poly: true }
|
||||
let parts = BakeVisualization::default();
|
||||
let shown = |overlay: BakeOverlay| BakeOverlay { shown: true, ..overlay };
|
||||
Self {
|
||||
hide_baking_meshes: false,
|
||||
selected_set_only: false,
|
||||
high_poly_mesh: shown(parts.high_poly),
|
||||
matching_error: shown(parts.matching_error),
|
||||
cage_surface: BakeOverlay { opacity: CAGE_OPACITY, ..shown(parts.cage_surface) },
|
||||
cage_wire: BakeOverlay { opacity: CAGE_OPACITY, ..shown(parts.cage_wire) },
|
||||
missing_seams: shown(parts.missing_seams),
|
||||
project_mesh: shown(parts.low_poly),
|
||||
neutral_shown: true,
|
||||
neutral: NeutralMaterial::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BakeVisualizationToggles {
|
||||
/// What the renderer draws with these switches while texture set `selected_set` is selected
|
||||
pub fn visualization(&self, selected_set: usize) -> Option<BakeVisualization> {
|
||||
self.on.then_some(BakeVisualization {
|
||||
high_poly: self.high_poly,
|
||||
cage: self.cage,
|
||||
uv_seams: self.uv_seams,
|
||||
low_poly: self.low_poly,
|
||||
/// What the renderer draws with these settings while texture set `selected_set` is selected
|
||||
pub fn visualization(&self, selected_set: usize) -> BakeVisualization {
|
||||
let unless_hidden = |overlay: BakeOverlay| BakeOverlay { shown: overlay.shown && !self.hide_baking_meshes, ..overlay };
|
||||
BakeVisualization {
|
||||
high_poly: unless_hidden(self.high_poly_mesh),
|
||||
matching_error: self.matching_error,
|
||||
cage_surface: unless_hidden(self.cage_surface),
|
||||
cage_wire: unless_hidden(self.cage_wire),
|
||||
missing_seams: self.missing_seams,
|
||||
low_poly: self.project_mesh,
|
||||
neutral: self.neutral_shown.then_some(self.neutral),
|
||||
only_set: self.selected_set_only.then_some(selected_set),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the project mesh shows the neutral material lit along the bent normal, which the 3D view then reads in place of a mesh map
|
||||
pub fn bent_normal_shown(&self) -> bool {
|
||||
self.project_mesh.shown && self.neutral_shown && self.neutral.bent_normal
|
||||
}
|
||||
|
||||
/// Switch the panel's eye; hiding the baking meshes shows the project mesh, so the view never goes empty
|
||||
pub fn toggle_hiding(&mut self) {
|
||||
self.hide_baking_meshes = !self.hide_baking_meshes;
|
||||
self.project_mesh.shown |= self.hide_baking_meshes;
|
||||
}
|
||||
|
||||
/// Put the High Definition Mesh section back to its defaults
|
||||
pub fn reset_high_poly(&mut self) {
|
||||
let defaults = Self::default();
|
||||
(self.high_poly_mesh, self.matching_error) = (defaults.high_poly_mesh, defaults.matching_error);
|
||||
}
|
||||
|
||||
/// Put the Cage section back to its defaults
|
||||
pub fn reset_cage(&mut self) {
|
||||
let defaults = Self::default();
|
||||
(self.cage_surface, self.cage_wire) = (defaults.cage_surface, defaults.cage_wire);
|
||||
}
|
||||
|
||||
/// Put the UV Seams section back to its defaults
|
||||
pub fn reset_seams(&mut self) {
|
||||
self.missing_seams = Self::default().missing_seams;
|
||||
}
|
||||
|
||||
/// Put the Project Mesh section back to its defaults
|
||||
pub fn reset_project_mesh(&mut self) {
|
||||
let defaults = Self::default();
|
||||
(self.project_mesh, self.neutral_shown, self.neutral) = (defaults.project_mesh, defaults.neutral_shown, defaults.neutral);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn panel_settings_saved_by_earlier_builds_start_over_from_the_defaults() {
|
||||
let mut saved = serde_json::to_value(crate::state::UiState::default()).unwrap();
|
||||
let fields = saved.as_object_mut().unwrap();
|
||||
fields.remove("baking_visualization");
|
||||
fields.insert(
|
||||
"bake_visualization".into(),
|
||||
serde_json::json!({"hide_baking_meshes": false, "missing_seams": {"shown": false, "color": [1, 0, 0], "opacity": 1}}),
|
||||
);
|
||||
let state: crate::state::UiState = serde_json::from_value(saved).unwrap();
|
||||
assert_eq!(state.bake_visualization, BakeVisualizationToggles::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_settings_reach_the_renderer() {
|
||||
let mut toggles = BakeVisualizationToggles::default();
|
||||
toggles.cage_wire.color = [0.1, 0.2, 0.3];
|
||||
toggles.neutral_shown = false;
|
||||
let visualization = toggles.visualization(2);
|
||||
assert_eq!(visualization.cage_wire, toggles.cage_wire);
|
||||
assert_eq!(visualization.neutral, None);
|
||||
assert_eq!(visualization.only_set, None);
|
||||
toggles.selected_set_only = true;
|
||||
assert_eq!(toggles.visualization(2).only_set, Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_eye_hides_the_baking_meshes_and_keeps_the_project_mesh() {
|
||||
let mut toggles = BakeVisualizationToggles::default();
|
||||
let shown = toggles.visualization(0);
|
||||
assert!(shown.high_poly.shown && shown.cage_surface.shown && shown.cage_wire.shown, "the eye starts off, as in the reference");
|
||||
|
||||
toggles.project_mesh.shown = false;
|
||||
toggles.toggle_hiding();
|
||||
let hidden = toggles.visualization(0);
|
||||
assert!(!hidden.high_poly.shown && !hidden.cage_surface.shown && !hidden.cage_wire.shown);
|
||||
assert!(hidden.low_poly.shown, "hiding the baking meshes brings the project mesh back");
|
||||
|
||||
toggles.toggle_hiding();
|
||||
assert!(toggles.visualization(0).high_poly.shown, "the eye switches back");
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::controls::{choice, hint, integer, number, section, text_input};
|
||||
use crate::TextureCraftApp;
|
||||
use crate::i18n::tr;
|
||||
use crate::theme::Tokens;
|
||||
use crate::widgets::icon_button;
|
||||
use egui::Ui;
|
||||
use egui_phosphor::regular as icon;
|
||||
@@ -9,7 +10,16 @@ use texturecraft_engine::core::{
|
||||
BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, CageType, CommonBakeSettings, MeshMatchMode, SkewCorrectionMethod,
|
||||
};
|
||||
|
||||
/// The output and high-poly sections, then cage (needs a high poly) and skew (needs a distance cage)
|
||||
/// How many rows the high poly list box is tall
|
||||
const HIGH_POLY_LIST_ROWS: f32 = 5.0;
|
||||
|
||||
/// Space between the panel's sections, in points
|
||||
const SECTION_GAP: f32 = 8.0;
|
||||
|
||||
/// Widest dilation the slider offers, in texels (the bake settings command accepts the same)
|
||||
const MAX_DILATION_WIDTH: u32 = 128;
|
||||
|
||||
/// The output and high-poly sections, then cage and skew, greyed with the reason when they can't apply
|
||||
pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) -> Option<Value> {
|
||||
let mut reset = Map::new();
|
||||
ui.push_id("common", |ui| {
|
||||
@@ -28,7 +38,7 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe
|
||||
(BakeAntialiasing::Subsampling8x8, tr("Subsampling 8x8")),
|
||||
],
|
||||
);
|
||||
integer(ui, tr("Dilation Width"), &mut settings.common.dilation, 0..=128);
|
||||
integer(ui, tr("Dilation Width"), &mut settings.common.dilation, 0..=MAX_DILATION_WIDTH);
|
||||
ui.checkbox(&mut settings.common.apply_diffusion, tr("Apply Diffusion"));
|
||||
}) {
|
||||
settings.common = CommonBakeSettings { is_enabled, ..CommonBakeSettings::default() };
|
||||
@@ -40,12 +50,14 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe
|
||||
}
|
||||
});
|
||||
|
||||
ui.add_space(8.0);
|
||||
// Without a high poly the reference shows everything that needs one greyed, not hidden
|
||||
let has_high = !app.session.bake_meshes.high.is_empty();
|
||||
ui.add_space(SECTION_GAP);
|
||||
ui.push_id("high_poly", |ui| {
|
||||
if section(ui, tr("High-Poly Parameters"), |ui| {
|
||||
ui.checkbox(&mut settings.high_poly.use_low_as_high, tr("Use Low Poly Mesh as High Poly Mesh"));
|
||||
high_poly_files(app, ui);
|
||||
if !app.session.bake_meshes.high.is_empty() {
|
||||
high_poly_scene(app, ui);
|
||||
ui.add_enabled_ui(has_high, |ui| {
|
||||
ui.checkbox(&mut settings.high_poly.ignore_backface, tr("Ignore Backface"));
|
||||
choice(
|
||||
ui,
|
||||
@@ -56,67 +68,89 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe
|
||||
text_input(ui, tr("Low Poly Mesh Suffix"), &mut settings.high_poly.low_suffix);
|
||||
text_input(ui, tr("High Poly Mesh Suffix"), &mut settings.high_poly.high_suffix);
|
||||
text_input(ui, tr("Ignore Backface Suffix"), &mut settings.high_poly.ignore_backface_suffix);
|
||||
}
|
||||
});
|
||||
}) {
|
||||
settings.high_poly = Default::default();
|
||||
reset.insert("high_poly".into(), json!(settings.high_poly));
|
||||
}
|
||||
});
|
||||
|
||||
if !app.session.bake_meshes.high.is_empty() {
|
||||
ui.add_space(8.0);
|
||||
ui.push_id("cage", |ui| {
|
||||
if section(ui, tr("Cage"), |ui| {
|
||||
ui.add_space(SECTION_GAP);
|
||||
ui.push_id("cage", |ui| {
|
||||
if section(ui, tr("Cage"), |ui| {
|
||||
// The cage steers rays toward a separate high poly, so it has nothing to do without one
|
||||
let cage_applies = has_high && !settings.high_poly.use_low_as_high;
|
||||
if !has_high {
|
||||
hint(ui, tr("The cage applies once a high poly mesh is loaded."));
|
||||
} else if !cage_applies {
|
||||
hint(ui, tr("The cage is not used while the low poly mesh is used as the high poly mesh."));
|
||||
}
|
||||
ui.add_enabled_ui(cage_applies, |ui| {
|
||||
choice(
|
||||
ui,
|
||||
tr("Cage Type"),
|
||||
&mut settings.cage.kind,
|
||||
&[(CageType::DistanceBased, tr("Distance-Based")), (CageType::CustomFile, tr("Custom File"))],
|
||||
);
|
||||
match settings.cage.kind {
|
||||
CageType::DistanceBased => {
|
||||
paint_brush(app, ui, BakePaintTarget::Cage);
|
||||
number(ui, tr("Max Frontal Distance"), &mut settings.cage.max_frontal, 0.0..=0.05, 4);
|
||||
number(ui, tr("Max Rear Distance"), &mut settings.cage.max_rear, 0.0..=0.05, 4);
|
||||
ui.checkbox(&mut settings.cage.relative_to_bounding_box, tr("Relative to Bounding Box"));
|
||||
ui.checkbox(&mut settings.cage.average_normals, tr("Average Normals"));
|
||||
}
|
||||
CageType::CustomFile => cage_file(app, ui),
|
||||
}
|
||||
}) {
|
||||
settings.cage = Default::default();
|
||||
reset.insert("cage".into(), json!(settings.cage));
|
||||
}
|
||||
});
|
||||
|
||||
if settings.cage.kind == CageType::DistanceBased {
|
||||
ui.add_space(8.0);
|
||||
ui.push_id("skew", |ui| {
|
||||
if section(ui, tr("Skew Correction"), |ui| {
|
||||
choice(
|
||||
ui,
|
||||
tr("Skew Correction Method"),
|
||||
&mut settings.skew.method,
|
||||
&[
|
||||
(SkewCorrectionMethod::MeshNormalsBased, tr("Mesh Normals Based")),
|
||||
(SkewCorrectionMethod::FaceNormalsBased, tr("Face Normals Based")),
|
||||
],
|
||||
);
|
||||
paint_brush(app, ui, BakePaintTarget::Skew);
|
||||
ui.checkbox(&mut settings.skew.edge_protection, tr("Edge Protection"));
|
||||
number(ui, tr("Edge Distance"), &mut settings.skew.edge_distance, 0.0..=1.0, 2);
|
||||
number(ui, tr("Edge Contrast"), &mut settings.skew.edge_contrast, 0.0..=1.0, 2);
|
||||
}) {
|
||||
settings.skew = Default::default();
|
||||
reset.insert("skew".into(), json!(settings.skew));
|
||||
if settings.cage.kind == CageType::DistanceBased {
|
||||
paint_brush(app, ui, BakePaintTarget::Cage);
|
||||
number(ui, tr("Max Frontal Distance"), &mut settings.cage.max_frontal, 0.0..=0.05, 4);
|
||||
number(ui, tr("Max Rear Distance"), &mut settings.cage.max_rear, 0.0..=0.05, 4);
|
||||
ui.checkbox(&mut settings.cage.relative_to_bounding_box, tr("Relative to Bounding Box"));
|
||||
ui.checkbox(&mut settings.cage.average_normals, tr("Average Normals"));
|
||||
}
|
||||
});
|
||||
if settings.cage.kind == CageType::CustomFile {
|
||||
cage_file(app, ui, cage_applies);
|
||||
}
|
||||
}) {
|
||||
settings.cage = Default::default();
|
||||
reset.insert("cage".into(), json!(settings.cage));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Shown greyed when it can't apply, as the reference does, with the reason on top
|
||||
let skew_applies = has_high && settings.skew_applies();
|
||||
ui.add_space(SECTION_GAP);
|
||||
ui.push_id("skew", |ui| {
|
||||
if section(ui, tr("Skew Correction"), |ui| {
|
||||
if !skew_applies {
|
||||
hint(ui, skew_unavailable_reason(settings, has_high));
|
||||
}
|
||||
ui.add_enabled_ui(skew_applies, |ui| {
|
||||
choice(
|
||||
ui,
|
||||
tr("Skew Correction Method"),
|
||||
&mut settings.skew.method,
|
||||
&[(SkewCorrectionMethod::MeshNormalsBased, tr("Mesh Normals Based")), (SkewCorrectionMethod::FaceNormalsBased, tr("Face Normals Based"))],
|
||||
);
|
||||
paint_brush(app, ui, BakePaintTarget::Skew);
|
||||
ui.checkbox(&mut settings.skew.edge_protection, tr("Edge Protection"));
|
||||
number(ui, tr("Edge Distance"), &mut settings.skew.edge_distance, 0.0..=1.0, 2);
|
||||
number(ui, tr("Edge Contrast"), &mut settings.skew.edge_contrast, 0.0..=1.0, 2);
|
||||
});
|
||||
}) {
|
||||
settings.skew = Default::default();
|
||||
reset.insert("skew".into(), json!(settings.skew));
|
||||
}
|
||||
});
|
||||
|
||||
(!reset.is_empty()).then_some(Value::Object(reset))
|
||||
}
|
||||
|
||||
/// Why Skew Correction can't apply: no high poly (`has_high` false), or `settings` rule it out (see [`BakeSettings::skew_applies`])
|
||||
fn skew_unavailable_reason(settings: &BakeSettings, has_high: bool) -> &'static str {
|
||||
if !has_high {
|
||||
tr("Skew Correction applies once a high poly mesh is loaded.")
|
||||
} else if settings.high_poly.use_low_as_high {
|
||||
tr("Skew Correction is not available while the low poly mesh is used as the high poly mesh.")
|
||||
} else if settings.cage.kind == CageType::CustomFile {
|
||||
tr("Skew Correction needs a distance-based cage: a custom cage file sets the ray directions itself.")
|
||||
} else {
|
||||
tr("Skew Correction needs Average Normals turned on in the cage settings.")
|
||||
}
|
||||
}
|
||||
|
||||
fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) {
|
||||
ui.label(tr("Output Size"));
|
||||
ui.horizontal(|ui| {
|
||||
@@ -144,42 +178,65 @@ fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) {
|
||||
});
|
||||
}
|
||||
|
||||
fn high_poly_files(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
ui.label(tr("High Poly Scene"));
|
||||
let meshes: Vec<_> = app.session.bake_meshes.high.iter().map(|mesh| mesh.name.clone()).collect();
|
||||
let mut remove = None;
|
||||
for (index, name) in meshes.iter().enumerate() {
|
||||
ui.horizontal(|ui| {
|
||||
let button_size = ui.spacing().interact_size.y;
|
||||
let label_width = (ui.available_width() - button_size - ui.spacing().item_spacing.x).max(0.0);
|
||||
ui.add_sized([label_width, ui.spacing().interact_size.y], egui::Label::new(name).truncate()).on_hover_text(name);
|
||||
if icon_button(ui, icon::TRASH, tr("Remove"), false, button_size).clicked() {
|
||||
remove = Some(index);
|
||||
}
|
||||
});
|
||||
}
|
||||
/// The high poly meshes as a list box, with + to add some and − to remove the selected one
|
||||
fn high_poly_scene(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let names: Vec<String> = app.session.bake_meshes.high.iter().map(|mesh| mesh.name.clone()).collect();
|
||||
let selected_id = ui.make_persistent_id("high_poly_selected");
|
||||
let mut selected = ui.data(|data| data.get_temp::<usize>(selected_id)).filter(|index| *index < names.len());
|
||||
|
||||
if meshes.is_empty() {
|
||||
hint(ui, tr("No High-Poly Meshes"));
|
||||
}
|
||||
if let Some(index) = remove {
|
||||
ui.label(tr("High Poly Scene"));
|
||||
let (mut add, mut remove) = (false, false);
|
||||
ui.horizontal_top(|ui| {
|
||||
let button_size = ui.spacing().interact_size.y;
|
||||
let list_width = (ui.available_width() - button_size - ui.spacing().item_spacing.x).max(0.0);
|
||||
let list_height = HIGH_POLY_LIST_ROWS * ui.spacing().interact_size.y;
|
||||
egui::Frame::NONE.fill(tokens.field).stroke(egui::Stroke::new(1.0, tokens.field_border)).corner_radius(tokens.cr()).show(ui, |ui| {
|
||||
ui.set_min_size(egui::vec2(list_width, list_height));
|
||||
ui.set_max_width(list_width);
|
||||
egui::ScrollArea::both().id_salt("high_poly_list").max_height(list_height).auto_shrink([false; 2]).show(ui, |ui| {
|
||||
for (index, name) in names.iter().enumerate() {
|
||||
if ui.selectable_label(selected == Some(index), name).on_hover_text(name).clicked() {
|
||||
selected = Some(index);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.vertical(|ui| {
|
||||
add = icon_button(ui, icon::PLUS, tr("Add High-Poly Meshes"), false, button_size).clicked();
|
||||
remove = ui.add_enabled_ui(selected.is_some(), |ui| icon_button(ui, icon::MINUS, tr("Remove"), false, button_size)).inner.clicked();
|
||||
});
|
||||
});
|
||||
|
||||
if let (true, Some(index)) = (remove, selected) {
|
||||
app.run("bake.highPoly.remove", json!({ "index": index }));
|
||||
selected = None;
|
||||
}
|
||||
if ui.button(tr("Add High-Poly Meshes")).clicked() {
|
||||
ui.data_mut(|data| {
|
||||
if let Some(index) = selected {
|
||||
data.insert_temp(selected_id, index);
|
||||
} else {
|
||||
data.remove_temp::<usize>(selected_id);
|
||||
}
|
||||
});
|
||||
if add {
|
||||
crate::web_files::import_bake_mesh(app, &ui.ctx().clone(), false);
|
||||
}
|
||||
}
|
||||
|
||||
fn cage_file(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
ui.label(tr("Cage Scene"));
|
||||
/// The cage file row; while the cage can't `apply` only removing a loaded one stays available, so a saved cage can still be dropped
|
||||
fn cage_file(app: &mut TextureCraftApp, ui: &mut Ui, apply: bool) {
|
||||
ui.add_enabled(apply, egui::Label::new(tr("Cage Scene")));
|
||||
let cage = app.session.bake_meshes.cage.as_ref().map(|mesh| mesh.name.clone());
|
||||
ui.horizontal(|ui| {
|
||||
let button_size = ui.spacing().interact_size.y;
|
||||
let label_width = (ui.available_width() - 2.0 * (button_size + ui.spacing().item_spacing.x)).max(0.0);
|
||||
ui.add_sized([label_width, ui.spacing().interact_size.y], egui::Label::new(cage.as_deref().unwrap_or("")).truncate());
|
||||
if icon_button(ui, icon::FOLDER_OPEN, tr("Load Cage"), false, button_size).clicked() {
|
||||
crate::web_files::import_bake_mesh(app, &ui.ctx().clone(), true);
|
||||
}
|
||||
ui.add_enabled_ui(apply, |ui| {
|
||||
ui.add_sized([label_width, ui.spacing().interact_size.y], egui::Label::new(cage.as_deref().unwrap_or("")).truncate());
|
||||
if icon_button(ui, icon::FOLDER_OPEN, tr("Load Cage"), false, button_size).clicked() {
|
||||
crate::web_files::import_bake_mesh(app, &ui.ctx().clone(), true);
|
||||
}
|
||||
});
|
||||
if cage.is_some() && icon_button(ui, icon::TRASH, tr("Remove Cage"), false, button_size).clicked() {
|
||||
app.run("bake.cage.clear", json!({}));
|
||||
}
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
//! Bake Mode presentation; persisted settings live in core and edits use engine commands
|
||||
|
||||
mod bake_checks;
|
||||
mod bake_paint_brush;
|
||||
mod bake_visualization_panel;
|
||||
mod bake_visualization_toggles;
|
||||
mod breadcrumb;
|
||||
mod common_settings;
|
||||
mod section_opening;
|
||||
pub(crate) use bake_checks::bake_warnings;
|
||||
pub use bake_paint_brush::BakePaintBrush;
|
||||
pub(crate) use bake_visualization_panel::bake_visualization_panel;
|
||||
pub use bake_visualization_toggles::BakeVisualizationToggles;
|
||||
@@ -47,18 +50,23 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
if ui.checkbox(&mut is_enabled, "").on_hover_text(tr("Include in Bake")).changed() {
|
||||
app.run("bake.settings", json!({ "ts": set_index, "enabled": is_enabled }));
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if let Some(selected) = resolution_menu(ui, tr("Texture set resolution"), format!("{resolution} × {resolution}"), resolution, None)
|
||||
&& selected != resolution
|
||||
{
|
||||
app.start_resize(set_index, selected);
|
||||
}
|
||||
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
if ui.add(egui::Button::selectable(set_index == app.session.ts(), &name).truncate()).on_hover_text(&name).clicked() {
|
||||
app.run("textureSet.select", json!({ "ts": set_index }));
|
||||
}
|
||||
});
|
||||
|
||||
// The name takes the room the resolution leaves, so it only shortens when the row is too narrow
|
||||
let resolution_text = format!("{resolution}x{resolution}");
|
||||
let name_width = (ui.available_width() - resolution_menu_width(ui, &resolution_text) - ui.spacing().item_spacing.x).max(0.0);
|
||||
let name_size = egui::vec2(name_width, ui.spacing().interact_size.y);
|
||||
let name_button = ui.allocate_ui_with_layout(name_size, egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
ui.set_min_width(name_width);
|
||||
ui.add(egui::Button::selectable(set_index == app.session.ts(), &name).truncate())
|
||||
});
|
||||
if name_button.inner.on_hover_text(&name).clicked() {
|
||||
app.run("textureSet.select", json!({ "ts": set_index }));
|
||||
}
|
||||
if let Some(selected) = resolution_menu(ui, tr("Texture set resolution"), resolution_text, resolution, None)
|
||||
&& selected != resolution
|
||||
{
|
||||
app.start_resize(set_index, selected);
|
||||
}
|
||||
});
|
||||
|
||||
if !tiles.is_empty() {
|
||||
@@ -71,7 +79,7 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
app.run("bake.tile.set", json!({"ts": set_index, "tile": tile, "enabled": enabled}));
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let text = override_resolution.map(|value| format!("{value} × {value}*")).unwrap_or_default();
|
||||
let text = override_resolution.map(|value| format!("{value}x{value}*")).unwrap_or_default();
|
||||
let label = trf("UV tile {tile} resolution", &[("tile", &tile.to_string())]);
|
||||
if let Some(selected) = resolution_menu(
|
||||
ui,
|
||||
@@ -93,12 +101,17 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
});
|
||||
}
|
||||
|
||||
/// How wide [`resolution_menu`] draws `text`, with a button's padding on both sides
|
||||
fn resolution_menu_width(ui: &Ui, text: &str) -> f32 {
|
||||
let font = egui::TextStyle::Button.resolve(ui.style());
|
||||
ui.painter().layout_no_wrap(text.to_owned(), font, ui.visuals().text_color()).size().x + ui.spacing().button_padding.x * 2.0
|
||||
}
|
||||
|
||||
fn resolution_menu(ui: &mut Ui, label: &str, text: String, resolution: u32, inherited_resolution: Option<u32>) -> Option<u32> {
|
||||
let effective_size = format!("{resolution} × {resolution}");
|
||||
let effective_size = format!("{resolution}x{resolution}");
|
||||
let measured = if text.is_empty() { &effective_size } else { &text };
|
||||
let font = egui::TextStyle::Button.resolve(ui.style());
|
||||
let text_width = ui.painter().layout_no_wrap(measured.clone(), font.clone(), ui.visuals().text_color()).size().x;
|
||||
let width = text_width + ui.spacing().button_padding.x * 2.0;
|
||||
let width = resolution_menu_width(ui, measured);
|
||||
let response = ui.add_sized([width, ui.spacing().interact_size.y], egui::Button::new("").frame(false));
|
||||
let popup_id = response.id.with("resolution_menu");
|
||||
let open = egui::Popup::is_id_open(ui.ctx(), popup_id) || response.clicked();
|
||||
@@ -115,7 +128,7 @@ fn resolution_menu(ui: &mut Ui, label: &str, text: String, resolution: u32, inhe
|
||||
ui.separator();
|
||||
}
|
||||
for candidate in [128, 256, 512, 1024, 2048, 4096, 8192] {
|
||||
if ui.selectable_label(candidate == resolution, format!("{candidate} × {candidate}")).clicked() {
|
||||
if ui.selectable_label(candidate == resolution, format!("{candidate}x{candidate}")).clicked() {
|
||||
selected = Some(candidate);
|
||||
}
|
||||
}
|
||||
@@ -228,10 +241,27 @@ fn preview_control(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
/// How many maps baking `texture_sets` makes, counted as the reference's Bake button counts them: checked maps × included UV tiles, per set
|
||||
fn maps_to_bake(app: &TextureCraftApp, texture_sets: &[usize]) -> usize {
|
||||
texture_sets
|
||||
.iter()
|
||||
.filter_map(|index| app.session.doc.project.texture_sets.get(*index))
|
||||
.map(|set| {
|
||||
let tiles = if set.uv_tiles.is_empty() { 1 } else { set.uv_tiles.iter().filter(|tile| !set.bake_excluded_tiles.contains(tile)).count() };
|
||||
set.bake.maps.enabled().count() * tiles
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// The bake bar's gap from the bottom of the 3D view, in points (the pre-bake warnings sit above it)
|
||||
pub(super) const BAKE_BAR_MARGIN: f32 = 16.0;
|
||||
|
||||
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| {
|
||||
egui::Area::new(egui::Id::unique("bake_bar"))
|
||||
.constrain_to(viewport)
|
||||
.anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -BAKE_BAR_MARGIN))
|
||||
.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()));
|
||||
}
|
||||
@@ -253,8 +283,9 @@ pub(crate) fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context, viewport:
|
||||
.filter(|(_, texture_set)| texture_set.bake.common.is_enabled && texture_set.has_enabled_bake_tiles())
|
||||
.map(|(index, _)| index)
|
||||
.collect();
|
||||
let label = trf("Bake Selected Textures ({n})", &[("n", &texture_sets.len())]);
|
||||
if ui.add_enabled(!texture_sets.is_empty(), primary_button(ui, &label)).clicked() {
|
||||
let maps = maps_to_bake(app, &texture_sets);
|
||||
let label = trf("Bake ({n})", &[("n", &maps)]);
|
||||
if ui.add_enabled(maps > 0, primary_button(ui, &label)).clicked() {
|
||||
app.start_bake(texture_sets);
|
||||
}
|
||||
}
|
||||
@@ -263,6 +294,5 @@ pub(crate) fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context, viewport:
|
||||
app.ui.mode = Mode::Painting;
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
/// Whether a Baking Visualization section starts open, as the reference shows the panel at first launch (HP and Cage open, UV seams and Project mesh closed)
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(super) enum SectionOpening {
|
||||
Open,
|
||||
Closed,
|
||||
}
|
||||
@@ -11,7 +11,7 @@ use super::reach_link::ReachLink;
|
||||
use super::shared_handle::SharedHandle;
|
||||
use crate::gpu::SceneSync;
|
||||
|
||||
/// What the GPU has of bake mode's visualization: the high poly, each set's cage and the UV seams
|
||||
/// What the GPU has of bake mode's visualization: the high poly, each set's cage and the missing seams
|
||||
#[derive(Default)]
|
||||
pub struct BakeSceneLink {
|
||||
/// The high poly sent to the GPU and the id it was sent under (each new high poly gets the next one)
|
||||
@@ -51,7 +51,7 @@ impl BakeSceneLink {
|
||||
|
||||
let Some(visualization) = visualization else { return };
|
||||
|
||||
if visualization.high_poly {
|
||||
if visualization.high_poly.shown {
|
||||
let high = session.bake_meshes.merged_high().map(|high| high.mesh.clone());
|
||||
let handle = SharedHandle::of(high.as_ref());
|
||||
if handle != self.high {
|
||||
@@ -64,14 +64,19 @@ impl BakeSceneLink {
|
||||
self.high_sent = true;
|
||||
}
|
||||
self.reach.sync(session, self.high_id, visualization.only_set, out);
|
||||
} else if self.high_sent {
|
||||
// Drop the hidden GPU mesh but keep its id so its reach can be reused
|
||||
out.bake_high = Some((None, self.high_id));
|
||||
self.high_sent = false;
|
||||
self.reach.resend();
|
||||
}
|
||||
|
||||
if visualization.uv_seams && self.seams_mesh_id != Some(session.mesh_id) {
|
||||
if visualization.missing_seams.shown && self.seams_mesh_id != Some(session.mesh_id) {
|
||||
self.seams_mesh_id = Some(session.mesh_id);
|
||||
out.uv_seams = Some((session.mesh_id, session.mesh.uv_seam_edges()));
|
||||
out.missing_seams = Some((session.mesh_id, session.mesh.missing_seam_edges()));
|
||||
}
|
||||
|
||||
if visualization.cage {
|
||||
if visualization.cage_shown() {
|
||||
self.sync_cages(session, out);
|
||||
}
|
||||
}
|
||||
@@ -85,6 +90,7 @@ impl BakeSceneLink {
|
||||
}
|
||||
self.cages.truncate(set_count);
|
||||
self.cages.resize_with(set_count, || None);
|
||||
let mut shared_edges = None;
|
||||
|
||||
for (texture_set, link) in self.cages.iter_mut().enumerate() {
|
||||
let (Some(key), Some(set)) = (CageShellKey::of(session, texture_set), session.doc.project.texture_sets.get(texture_set)) else { continue };
|
||||
@@ -95,11 +101,26 @@ impl BakeSceneLink {
|
||||
if link.max_frontal == max_frontal {
|
||||
continue;
|
||||
}
|
||||
|
||||
link.max_frontal = max_frontal;
|
||||
}
|
||||
_ => {
|
||||
self.next_topology += 1;
|
||||
let shell = session.bake_cage_inputs(texture_set).ok().flatten().and_then(|inputs| inputs.cage_shell().ok()).map(Arc::new);
|
||||
let shell = session
|
||||
.bake_cage_inputs(texture_set)
|
||||
.ok()
|
||||
.flatten()
|
||||
.and_then(|inputs| {
|
||||
let result = if inputs.uses_mesh(&session.mesh) {
|
||||
let (wire_edges, missing_seam_edges) =
|
||||
shared_edges.get_or_insert_with(|| (session.mesh.wire_edges(), session.mesh.missing_seam_edges()));
|
||||
inputs.cage_shell_with_edges(wire_edges, missing_seam_edges)
|
||||
} else {
|
||||
inputs.cage_shell()
|
||||
};
|
||||
result.ok()
|
||||
})
|
||||
.map(Arc::new);
|
||||
*link = Some(CageLink { key, shell, topology: self.next_topology, max_frontal });
|
||||
}
|
||||
}
|
||||
@@ -117,7 +138,20 @@ mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
const EVERYTHING: BakeVisualization = BakeVisualization { high_poly: true, cage: true, uv_seams: true, low_poly: true, only_set: None };
|
||||
/// Every part of the visualization shown
|
||||
fn everything() -> BakeVisualization {
|
||||
let parts = BakeVisualization::default();
|
||||
let shown = |overlay: texturecraft_render::BakeOverlay| texturecraft_render::BakeOverlay { shown: true, ..overlay };
|
||||
BakeVisualization {
|
||||
high_poly: shown(parts.high_poly),
|
||||
matching_error: shown(parts.matching_error),
|
||||
cage_surface: shown(parts.cage_surface),
|
||||
cage_wire: shown(parts.cage_wire),
|
||||
missing_seams: shown(parts.missing_seams),
|
||||
low_poly: shown(parts.low_poly),
|
||||
..parts
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a test waits for the reach worker: frames, and the pause between them
|
||||
const WAIT_FRAMES: usize = 2000;
|
||||
@@ -165,41 +199,62 @@ mod tests {
|
||||
#[test]
|
||||
fn a_new_distance_moves_the_corners_and_new_settings_rebuild_the_cage() {
|
||||
let (mut session, mut link) = (session(), BakeSceneLink::default());
|
||||
let first = sync(&mut link, &session, EVERYTHING);
|
||||
assert!(first.bake_high.is_some() && first.uv_seams.is_some() && first.bake_cage_count == Some(session.doc.project.texture_sets.len()));
|
||||
let first = sync(&mut link, &session, everything());
|
||||
assert!(first.bake_high.is_some() && first.missing_seams.is_some() && first.bake_cage_count == Some(session.doc.project.texture_sets.len()));
|
||||
let (_, Some(cage), topology) = first.bake_cages.first().unwrap() else { panic!("set 0 has a cage") };
|
||||
|
||||
let unchanged = sync(&mut link, &session, EVERYTHING);
|
||||
assert!(unchanged.bake_high.is_none() && unchanged.bake_cages.is_empty() && unchanged.uv_seams.is_none(), "nothing changed, nothing is sent");
|
||||
let unchanged = sync(&mut link, &session, everything());
|
||||
assert!(unchanged.bake_high.is_none() && unchanged.bake_cages.is_empty() && unchanged.missing_seams.is_none(), "nothing changed, nothing is sent");
|
||||
|
||||
set_distances(&mut session, 0.03);
|
||||
let moved = sync(&mut link, &session, EVERYTHING);
|
||||
let moved = sync(&mut link, &session, everything());
|
||||
let (_, Some(moved_cage), moved_topology) = moved.bake_cages.first().unwrap() else { panic!("set 0 has a cage") };
|
||||
assert_eq!(moved_topology, topology, "a distance only moves the corners");
|
||||
assert_ne!(moved_cage.corners, cage.corners);
|
||||
|
||||
texturecraft_engine::execute(&mut session, "bake.settings", &json!({"ts": "all", "averageNormals": false})).unwrap();
|
||||
let rebuilt = sync(&mut link, &session, EVERYTHING);
|
||||
let rebuilt = sync(&mut link, &session, everything());
|
||||
assert_ne!(rebuilt.bake_cages.first().unwrap().2, *topology, "new settings rebuild the cage");
|
||||
|
||||
// The rebuilt cage starts a new reach: let it finish so the last check sees only what the resend starts
|
||||
red_share(&mut link, &session, EVERYTHING);
|
||||
red_share(&mut link, &session, everything());
|
||||
|
||||
link.resend();
|
||||
let resent = sync(&mut link, &session, EVERYTHING);
|
||||
assert!(resent.bake_high.is_some() && resent.uv_seams.is_some() && resent.bake_cage_count.is_some(), "a lost frame sends everything again");
|
||||
let resent = sync(&mut link, &session, everything());
|
||||
assert!(resent.bake_high.is_some() && resent.missing_seams.is_some() && resent.bake_cage_count.is_some(), "a lost frame sends everything again");
|
||||
assert_eq!(resent.bake_cages.len(), rebuilt.bake_cages.len());
|
||||
assert_eq!(resent.bake_cages.first().unwrap().2, rebuilt.bake_cages.first().unwrap().2, "the cages are not rebuilt for a lost frame");
|
||||
assert_eq!(resent.bake_high.unwrap().1, first.bake_high.unwrap().1, "the high poly goes again under the same id");
|
||||
assert!(!link.busy(), "a lost frame doesn't work out the reach again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_high_poly_leaves_the_gpu_and_comes_back_without_a_new_reach() {
|
||||
let (session, mut link) = (session(), BakeSceneLink::default());
|
||||
let sent = |out: SceneSync| out.bake_high.map(|(high, id)| (high.is_some(), id));
|
||||
let hidden = BakeVisualization { high_poly: BakeVisualization::default().high_poly, ..everything() };
|
||||
let first = sent(sync(&mut link, &session, everything()));
|
||||
red_share(&mut link, &session, everything());
|
||||
let dropped = sent(sync(&mut link, &session, hidden));
|
||||
assert!(sync(&mut link, &session, hidden).bake_high.is_none(), "dropped once");
|
||||
let back = sync(&mut link, &session, everything());
|
||||
assert!(!link.busy(), "showing it again starts no new reach");
|
||||
assert!(back.bake_high_missed.is_some(), "its colours are sent again with it");
|
||||
|
||||
let (Some((true, first_id)), Some((false, dropped_id)), Some((true, back_id))) = (first, dropped, sent(back)) else {
|
||||
panic!("the high poly is sent, dropped, then sent again")
|
||||
};
|
||||
|
||||
assert_eq!((dropped_id, back_id), (first_id, first_id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reach_finishes_while_nothing_is_drawn() {
|
||||
let session = session();
|
||||
let no_high_poly = BakeVisualization { high_poly: false, ..EVERYTHING };
|
||||
let no_high_poly = BakeVisualization { high_poly: BakeVisualization::default().high_poly, ..everything() };
|
||||
for hidden in [None, Some(no_high_poly)] {
|
||||
let mut link = BakeSceneLink::default();
|
||||
sync(&mut link, &session, EVERYTHING);
|
||||
sync(&mut link, &session, everything());
|
||||
assert!(link.busy(), "the first frame starts working out the reach");
|
||||
|
||||
let finished = (0..WAIT_FRAMES).any(|_| {
|
||||
@@ -215,11 +270,11 @@ mod tests {
|
||||
fn the_red_follows_the_distances_and_the_selected_set() {
|
||||
let (mut session, mut link) = (session(), BakeSceneLink::default());
|
||||
set_distances(&mut session, 0.0);
|
||||
let at_zero = red_share(&mut link, &session, EVERYTHING);
|
||||
let at_zero = red_share(&mut link, &session, everything());
|
||||
assert!(at_zero > 0.5, "at frontal 0 the high poly outside the low poly is red: {at_zero}");
|
||||
|
||||
set_distances(&mut session, 0.05);
|
||||
let covered = red_share(&mut link, &session, EVERYTHING);
|
||||
let covered = red_share(&mut link, &session, everything());
|
||||
assert!(covered < at_zero / 10.0, "a cage past the high poly reaches it: {covered}");
|
||||
|
||||
set_distances(&mut session, 0.0);
|
||||
@@ -230,10 +285,11 @@ mod tests {
|
||||
}
|
||||
};
|
||||
by_name(&mut session, "_no_such_suffix");
|
||||
let by_name_red = red_share(&mut link, &session, EVERYTHING);
|
||||
let by_name_red = red_share(&mut link, &session, everything());
|
||||
assert!(by_name_red > 0.5, "matching by name and other suffixes works out the reach again: {by_name_red}");
|
||||
|
||||
let no_set = BakeVisualization { only_set: Some(session.doc.project.texture_sets.len()), ..EVERYTHING };
|
||||
assert_eq!(red_share(&mut link, &session, no_set), 0.0, "sets left out by the filter color nothing");
|
||||
let no_set = BakeVisualization { only_set: Some(session.doc.project.texture_sets.len()), ..everything() };
|
||||
let hidden = texturecraft_engine::bake::HIDDEN_HIGH_POLY_VERTEX;
|
||||
assert_eq!(red_share(&mut link, &session, no_set), hidden, "a filter that keeps no set hides the whole high poly");
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,11 @@ impl ReachLink {
|
||||
.enumerate()
|
||||
.map(|(texture_set, set)| Some((CageShellKey::of(session, texture_set)?, set.bake.high_poly.clone())))
|
||||
.collect();
|
||||
|
||||
if keys != self.keys || high_id != self.high_id {
|
||||
// The GPU keeps displayed colors; stale CPU arrays need not overlap the rebuild
|
||||
self.reach.clear();
|
||||
|
||||
let inputs: Vec<_> = (0..set_count).map(|texture_set| session.bake_cage_inputs(texture_set).ok().flatten()).collect();
|
||||
self.job = Some(crate::spawn_worker("texturecraft-bake-reach", move || {
|
||||
inputs.iter().map(|inputs| inputs.as_ref().and_then(|inputs| inputs.high_poly_reach().ok())).collect()
|
||||
@@ -99,8 +103,31 @@ mod tests {
|
||||
use texturecraft_engine::core::BakePaintTarget;
|
||||
use texturecraft_engine::geom::primitives;
|
||||
|
||||
#[test]
|
||||
fn rebuilding_reach_releases_previous_vertex_arrays_before_starting_work() {
|
||||
const PREVIOUS_SET_COUNT: usize = 2;
|
||||
const PREVIOUS_VERTEX_COUNT: usize = 64;
|
||||
|
||||
let mut session = Session::new_project("Reach", primitives::plane(1.0, 1), "plane", None, 128).unwrap();
|
||||
session.add_high_poly_bytes("high.obj", b"v 0 0.1 0\nv 0.1 0.1 0\nv 0 0.1 0.1\nf 1 2 3\n".to_vec()).unwrap();
|
||||
let mut link = ReachLink {
|
||||
reach: (0..PREVIOUS_SET_COUNT).map(|_| Some(HighPolyReach { vertices: vec![None; PREVIOUS_VERTEX_COUNT], ..Default::default() })).collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut out = SceneSync::default();
|
||||
|
||||
link.sync(&session, 1, None, &mut out);
|
||||
|
||||
let retained_slots: usize = link.reach.iter().flatten().map(|reach| reach.vertices.capacity()).sum();
|
||||
assert_eq!(retained_slots, 0, "obsolete CPU arrays must not overlap their replacements");
|
||||
assert!(out.bake_high_missed.is_none(), "the GPU keeps its displayed colors until the replacement arrives");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn input_changes_wait_for_the_running_reach_then_use_the_latest_inputs() {
|
||||
const WAIT_FRAMES: usize = 2000;
|
||||
const WAIT_FRAME_PAUSE: Duration = Duration::from_millis(5);
|
||||
|
||||
let mut session = Session::new_project("Reach", primitives::plane(1.0, 1), "plane", None, 128).unwrap();
|
||||
session.add_high_poly_bytes("high.obj", b"v 0 0.1 0\nv 0.1 0.1 0\nv 0 0.1 0.1\nf 1 2 3\n".to_vec()).unwrap();
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
@@ -113,6 +140,7 @@ mod tests {
|
||||
link.sync(&session, 2, None, &mut out);
|
||||
assert!(out.bake_high_missed.is_none());
|
||||
}
|
||||
|
||||
assert!(sender.send(Vec::new()).is_ok(), "input changes must keep the running job's receiver");
|
||||
link.poll();
|
||||
|
||||
@@ -123,13 +151,15 @@ mod tests {
|
||||
assert!(link.busy());
|
||||
assert!(out.bake_high_missed.is_none());
|
||||
|
||||
for _ in 0..2000 {
|
||||
for _ in 0..WAIT_FRAMES {
|
||||
link.poll();
|
||||
if !link.busy() {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
|
||||
std::thread::sleep(WAIT_FRAME_PAUSE);
|
||||
}
|
||||
|
||||
assert!(!link.busy(), "the latest reach must finish");
|
||||
link.sync(&session, 2, None, &mut out);
|
||||
let (high_id, missed) = out.bake_high_missed.unwrap();
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
//! Saving the current brush as a preset (Properties › Brush › Preset); presets show on the shelf's Brushes tab
|
||||
|
||||
use egui::Ui;
|
||||
use serde_json::json;
|
||||
use std::path::Path;
|
||||
use texturecraft_engine::brush_preset_cmds::BRUSH_EXT;
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::i18n::tr;
|
||||
|
||||
/// The preset name field's width in points
|
||||
const NAME_WIDTH: f32 = 110.0;
|
||||
|
||||
/// A name field and a button that saves the current brush under that name
|
||||
pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let dir = crate::user_dir("brushes");
|
||||
let name_id = ui.make_persistent_id("brush_preset_name");
|
||||
let confirm_id = ui.make_persistent_id("brush_preset_overwrite");
|
||||
let mut new_name: String = ui.data_mut(|data| data.get_temp(name_id)).unwrap_or_default();
|
||||
let mut pending_path: Option<std::path::PathBuf> = ui.data_mut(|data| data.get_temp(confirm_id));
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::TextEdit::singleline(&mut new_name).hint_text(tr("Brush name")).desired_width(NAME_WIDTH));
|
||||
|
||||
if ui.add_enabled(!new_name.trim().is_empty(), egui::Button::new(tr("Save current brush"))).clicked() {
|
||||
let path = dir.join(format!("{}.{BRUSH_EXT}", preset_file_stem(new_name.trim())));
|
||||
match std::fs::symlink_metadata(&path) {
|
||||
Ok(_) => pending_path = Some(path),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
if save_brush(app, &dir, &path) {
|
||||
new_name.clear();
|
||||
}
|
||||
}
|
||||
Err(_) => pending_path = Some(path),
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if let Some(path) = pending_path.clone() {
|
||||
let mut replace = false;
|
||||
let mut cancel = false;
|
||||
egui::Window::new(tr("Replace"))
|
||||
.id(ui.make_persistent_id("brush_preset_replace_dialog"))
|
||||
.collapsible(false)
|
||||
.resizable(false)
|
||||
.anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO)
|
||||
.show(ui.ctx(), |ui| {
|
||||
ui.label(path.file_name().and_then(|name| name.to_str()).unwrap_or_default());
|
||||
ui.horizontal(|ui| {
|
||||
replace = ui.button(tr("Replace")).clicked();
|
||||
cancel = ui.button(tr("Cancel")).clicked();
|
||||
});
|
||||
});
|
||||
if replace {
|
||||
if save_brush(app, &dir, &path) {
|
||||
new_name.clear();
|
||||
}
|
||||
pending_path = None;
|
||||
} else if cancel {
|
||||
pending_path = None;
|
||||
}
|
||||
}
|
||||
|
||||
ui.data_mut(|data| {
|
||||
data.insert_temp(name_id, new_name);
|
||||
data.insert_temp(confirm_id, pending_path);
|
||||
});
|
||||
}
|
||||
|
||||
/// Preserve Unicode names and encode filename punctuation without collisions
|
||||
fn preset_file_stem(name: &str) -> String {
|
||||
let mut stem = String::new();
|
||||
|
||||
// Six digits cover every Unicode scalar and separate adjacent escapes
|
||||
for character in name.chars() {
|
||||
if character.is_alphanumeric() || character == '-' || character == '_' || character == ' ' {
|
||||
stem.push(character);
|
||||
} else {
|
||||
stem.push_str(&format!("~{:06X}", character as u32));
|
||||
}
|
||||
}
|
||||
let uppercase = stem.to_ascii_uppercase();
|
||||
if matches!(
|
||||
uppercase.as_str(),
|
||||
"CON"
|
||||
| "PRN"
|
||||
| "AUX"
|
||||
| "NUL"
|
||||
| "COM1"
|
||||
| "COM2"
|
||||
| "COM3"
|
||||
| "COM4"
|
||||
| "COM5"
|
||||
| "COM6"
|
||||
| "COM7"
|
||||
| "COM8"
|
||||
| "COM9"
|
||||
| "LPT1"
|
||||
| "LPT2"
|
||||
| "LPT3"
|
||||
| "LPT4"
|
||||
| "LPT5"
|
||||
| "LPT6"
|
||||
| "LPT7"
|
||||
| "LPT8"
|
||||
| "LPT9"
|
||||
) {
|
||||
stem.insert_str(0, "brush-");
|
||||
}
|
||||
stem
|
||||
}
|
||||
|
||||
/// Save a preset and invalidate cached tiles only when the write succeeds
|
||||
fn save_brush(app: &mut TextureCraftApp, dir: &Path, path: &Path) -> bool {
|
||||
// A folder that cannot be made is reported by the save command
|
||||
let _ = std::fs::create_dir_all(dir);
|
||||
if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_none() {
|
||||
return false;
|
||||
}
|
||||
|
||||
app.brushes = None;
|
||||
app.thumbs.forget_saved_files();
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::preset_file_stem;
|
||||
|
||||
#[test]
|
||||
fn distinct_unicode_brush_names_have_distinct_safe_file_stems() {
|
||||
assert_ne!(preset_file_stem("水彩"), preset_file_stem("油画"));
|
||||
assert_ne!(preset_file_stem("a/b"), preset_file_stem("a~00002Fb"));
|
||||
assert_eq!(preset_file_stem("水彩"), "水彩");
|
||||
assert!(!preset_file_stem("a/b").contains('/'));
|
||||
assert_eq!(preset_file_stem("CON"), "brush-CON");
|
||||
}
|
||||
}
|
||||
+557
-420
File diff suppressed because it is too large.
Load diff
@@ -133,17 +133,28 @@ 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, then texture sets, layers (tabbed with texture set settings) and properties; ratios fit 1600x960
|
||||
/// The default: assets (4 tile columns at 1920 px) left of the viewport, then texture sets, layers (tabbed with texture set settings) and properties
|
||||
pub fn default_workspace() -> Workspace {
|
||||
use Panel::*;
|
||||
|
||||
// The Assets split keeps four tiles visible at the reference window width
|
||||
const ASSETS_SPLIT_RATIO: f32 = 0.16;
|
||||
const VIEWPORT_SPLIT_RATIO: f32 = 0.80;
|
||||
const TEXTURE_SET_SPLIT_RATIO: f32 = 0.125;
|
||||
const LAYERS_SPLIT_RATIO: f32 = 0.57;
|
||||
|
||||
let column = split(
|
||||
SplitAxis::Vertical,
|
||||
SplitSize::Ratio(0.125),
|
||||
SplitSize::Ratio(TEXTURE_SET_SPLIT_RATIO),
|
||||
tabs(&[TextureSetList]),
|
||||
split(SplitAxis::Vertical, SplitSize::Ratio(0.57), tabs(&[Layers, TextureSetSettings]), tabs(&[Properties])),
|
||||
split(SplitAxis::Vertical, SplitSize::Ratio(LAYERS_SPLIT_RATIO), tabs(&[Layers, TextureSetSettings]), tabs(&[Properties])),
|
||||
);
|
||||
let root = split(
|
||||
SplitAxis::Horizontal,
|
||||
SplitSize::Ratio(ASSETS_SPLIT_RATIO),
|
||||
tabs(&[Assets]),
|
||||
split(SplitAxis::Horizontal, SplitSize::Ratio(VIEWPORT_SPLIT_RATIO), tabs(&[Viewport]), column),
|
||||
);
|
||||
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 {
|
||||
@@ -215,8 +226,11 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> {
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The live dock
|
||||
|
||||
/// Width of the bake layout's texture set and mesh map bakers column, in points
|
||||
const BAKERS_COLUMN_WIDTH: f32 = 200.0;
|
||||
/// Height of a panel group's tab strip, in points
|
||||
pub(crate) const TAB_HEIGHT: f32 = 30.0;
|
||||
|
||||
/// Width of the bake layout's texture set and mesh map bakers column in points: the reference's scaled to our larger font
|
||||
const BAKERS_COLUMN_WIDTH: f32 = 232.0;
|
||||
/// Width of the bake layout's common and mesh map settings column, in points
|
||||
const SETTINGS_COLUMN_WIDTH: f32 = 330.0;
|
||||
/// Height of the log under the bake layout's columns, in points
|
||||
@@ -367,29 +381,42 @@ fn area_id() -> Id {
|
||||
Id::unique("texturecraft-docking")
|
||||
}
|
||||
|
||||
/// The dock look: every panel group is a card on the window's frame colour, its tab strip
|
||||
/// without hard lines, the shown tab a pill.
|
||||
fn style(ui: &Ui, t: &Tokens) -> DockStyle {
|
||||
let mut s = DockStyle::from_ui(ui);
|
||||
s.gap = f32::from(crate::theme::GUTTER);
|
||||
// Smallest panel extent a divider drag leaves.
|
||||
s.min_pane = 60.0;
|
||||
s.background = t.panel;
|
||||
s.tab_background = t.panel;
|
||||
s.active_background = t.button;
|
||||
s.text = t.text_strong;
|
||||
s.inactive_text = t.text_dim;
|
||||
s.border = egui::Stroke::NONE;
|
||||
s.accent = t.accent;
|
||||
s.floating_background = t.panel;
|
||||
s.floating_stroke = egui::Stroke::new(1.0, t.button_border);
|
||||
s.font = egui::FontId::proportional(12.5);
|
||||
s.min_tab_width = 54.0;
|
||||
s.tab_height = 30.0;
|
||||
// Panels arrange in a split tree around the viewport; floating title bars only move windows.
|
||||
s.new_dock_zones = false;
|
||||
s.title_bar_docks = false;
|
||||
s
|
||||
/// Smallest panel extent a divider drag leaves, in points
|
||||
const MIN_PANE_EXTENT: f32 = 60.0;
|
||||
|
||||
/// Border width of a floating panel, in points
|
||||
const FLOATING_BORDER_WIDTH: f32 = 1.0;
|
||||
|
||||
/// Text size of the panel tabs, in points
|
||||
const TAB_TEXT_SIZE: f32 = 12.5;
|
||||
|
||||
/// Narrowest panel tab, in points
|
||||
const MIN_TAB_WIDTH: f32 = 54.0;
|
||||
|
||||
/// The dock look: each panel group a card on the window's frame colour, tab strips without hard lines, the shown tab a pill
|
||||
fn style(ui: &Ui, tokens: &Tokens) -> DockStyle {
|
||||
let mut dock_style = DockStyle::from_ui(ui);
|
||||
dock_style.gap = f32::from(crate::theme::GUTTER);
|
||||
dock_style.min_pane = MIN_PANE_EXTENT;
|
||||
|
||||
dock_style.background = tokens.panel;
|
||||
dock_style.tab_background = tokens.panel;
|
||||
dock_style.active_background = tokens.button;
|
||||
dock_style.text = tokens.text_strong;
|
||||
dock_style.inactive_text = tokens.text_dim;
|
||||
dock_style.border = egui::Stroke::NONE;
|
||||
dock_style.accent = tokens.accent;
|
||||
dock_style.floating_background = tokens.panel;
|
||||
dock_style.floating_stroke = egui::Stroke::new(FLOATING_BORDER_WIDTH, tokens.button_border);
|
||||
|
||||
dock_style.font = egui::FontId::proportional(TAB_TEXT_SIZE);
|
||||
dock_style.min_tab_width = MIN_TAB_WIDTH;
|
||||
dock_style.tab_height = TAB_HEIGHT;
|
||||
|
||||
// Panels arrange in a split tree around the viewport; floating title bars only move windows
|
||||
dock_style.new_dock_zones = false;
|
||||
dock_style.title_bar_docks = false;
|
||||
dock_style
|
||||
}
|
||||
|
||||
/// Whether a modal layer or update dialog holds the input, so the panels, floating ones included,
|
||||
|
||||
@@ -0,0 +1,394 @@
|
||||
//! A generator effect's properties, laid out like the reference app's: attributes, resolution, parameters, image inputs.
|
||||
|
||||
use egui::{RichText, Ui};
|
||||
use egui_phosphor::regular as ic;
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, OutputResolution, ResolutionMode, Source};
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::dock::{anchor_label, anchors_below, image_drop, image_menu, mesh_map_color};
|
||||
use crate::i18n::{baked_map_label, tr, trf};
|
||||
use crate::theme::{Tokens, caption};
|
||||
use crate::widgets::{combo, section, slider_edit};
|
||||
|
||||
/// Random seeds stay below this, short enough to read and type.
|
||||
const SEED_RANGE: u32 = 10_000;
|
||||
/// Knuth's multiplicative hash constant: spreads the clock's nanoseconds over the seed range.
|
||||
const SEED_MIX: u32 = 2_654_435_761;
|
||||
|
||||
/// Font size of the notes under a control.
|
||||
const NOTE_FONT_SIZE: f32 = 10.5;
|
||||
|
||||
/// Edge of the picture beside each image input, its corner rounding and the size of an icon drawn in it.
|
||||
const INPUT_TILE_SIZE: f32 = 32.0;
|
||||
const INPUT_TILE_ROUNDING: f32 = 2.0;
|
||||
const INPUT_TILE_ICON_SIZE: f32 = 16.0;
|
||||
|
||||
/// Width of the names in the Attributes section, so their values line up.
|
||||
const ATTRIBUTE_KEY_WIDTH: f32 = 80.0;
|
||||
|
||||
/// The settings of generator effect `id`.
|
||||
pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, id: u64, generator: &Generator) {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
ui.label(caption(tr("Generator")));
|
||||
egui::ComboBox::from_id_salt("gen_kind").selected_text(tr(generator.kind.label())).show_ui(ui, |ui| {
|
||||
for kind in GeneratorKind::ALL {
|
||||
if ui.selectable_label(kind == generator.kind, tr(kind.label())).clicked() && kind != generator.kind {
|
||||
app.run("effect.set", json!({"effect": id, "generator": format!("{kind:?}")}));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
section(ui, "generator_attributes", tr("Attributes"), false, |ui| attributes(ui, generator.kind));
|
||||
section(ui, "generator_resolution", tr("Resolution"), false, |ui| resolution(app, ui, id, generator.resolution));
|
||||
section(ui, "generator_parameters", tr("Parameters"), true, |ui| {
|
||||
global_adjustments(app, ui, id, generator);
|
||||
ramp_parameters(app, ui, id, generator);
|
||||
if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) {
|
||||
curvature_detail_properties(app, ui, id, generator.detail.as_ref());
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button(tr("Restore defaults")).clicked() {
|
||||
app.run("effect.set", defaults_of(id, generator.kind));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
if !generator.kind.inputs().is_empty() {
|
||||
section(ui, "generator_inputs", tr("Image inputs"), true, |ui| {
|
||||
for map in generator.kind.inputs() {
|
||||
input_slot(app, ui, (layer, id), *map, generator.inputs.get(map), generator.detail.is_some());
|
||||
}
|
||||
});
|
||||
}
|
||||
if !app.session.doc.baked.contains_key(&app.session.ts()) {
|
||||
ui.label(
|
||||
RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (F8) for curvature, AO and thickness based generators."))).color(tokens.warning),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// What a generator kind makes, its category and its tags (read only).
|
||||
fn attributes(ui: &mut Ui, kind: GeneratorKind) {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let (description, tags) = match kind {
|
||||
GeneratorKind::EdgeWear => (
|
||||
tr("Convex edges from the curvature map, broken up by noise: worn paint and polished edges."),
|
||||
[tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")],
|
||||
),
|
||||
GeneratorKind::Dirt => (
|
||||
tr("Crevices and occluded areas from the ambient occlusion map: dirt and grime."),
|
||||
[tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")],
|
||||
),
|
||||
GeneratorKind::ThinAreas => (tr("Thin parts of the mesh from the thickness map."), [tr("mask"), tr("generator"), tr("grayscale"), tr("thickness")]),
|
||||
GeneratorKind::Curvature => (
|
||||
tr("Convex edges, cavities or both from the curvature map, at several detail sizes."),
|
||||
[tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")],
|
||||
),
|
||||
GeneratorKind::AmbientOcclusion => {
|
||||
(tr("Occluded areas from the ambient occlusion map."), [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")])
|
||||
}
|
||||
GeneratorKind::Position => (tr("A gradient along a world direction across the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]),
|
||||
GeneratorKind::Direction => (tr("Surfaces facing a direction, as if lit from it."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]),
|
||||
};
|
||||
|
||||
// Wrapped rows: a long line must not widen the panel past its edge
|
||||
let tags = tags.join(", ");
|
||||
for (key, value) in [(tr("Description"), description), (tr("Category"), tr("Generators")), (tr("Tags"), tags.as_str())] {
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.add_sized([ATTRIBUTE_KEY_WIDTH, 0.0], egui::Label::new(RichText::new(key).color(tokens.text_dim)));
|
||||
ui.add(egui::Label::new(value).wrap());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// What the generator's output resolution is based on, the factor applied to it, and the size it comes to.
|
||||
fn resolution(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, resolution: OutputResolution) {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
combo(ui, tr("Resolution"), tr(resolution.mode.label()), |ui| {
|
||||
for mode in ResolutionMode::ALL {
|
||||
if ui.selectable_label(mode == resolution.mode, tr(mode.label())).clicked() {
|
||||
app.run("effect.set", json!({"effect": id, "resolution": format!("{mode:?}")}));
|
||||
}
|
||||
}
|
||||
})
|
||||
.on_hover_text(tr("Auto and UV tile use the UV tile's resolution, Texture set the texture set's, Custom a size of its own."));
|
||||
if resolution.mode == ResolutionMode::Custom {
|
||||
combo(ui, tr("Size"), format!("{0} × {0}", resolution.custom), |ui| {
|
||||
for size in OutputResolution::CUSTOM_SIZES {
|
||||
if ui.selectable_label(size == resolution.custom, format!("{size} × {size}")).clicked() {
|
||||
app.run("effect.set", json!({"effect": id, "customResolution": size}));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
combo(ui, tr("Factor"), factor_label(resolution.factor), |ui| {
|
||||
for factor in OutputResolution::FACTORS {
|
||||
if ui.selectable_label(factor == resolution.factor, factor_label(factor)).clicked() {
|
||||
app.run("effect.set", json!({"effect": id, "resolutionFactor": factor}));
|
||||
}
|
||||
}
|
||||
})
|
||||
.on_hover_text(tr("Scales the base resolution: below 1 the generator is computed coarser and smoothed back up."));
|
||||
|
||||
let Ok(texture_set) = app.session.doc.project.texture_set(app.session.ts()) else { return };
|
||||
|
||||
let (smallest, largest) = texture_set
|
||||
.uv_tiles
|
||||
.iter()
|
||||
.map(|&udim| resolution.output_size(texture_set.tile_resolution(udim), texture_set.resolution))
|
||||
.fold((u32::MAX, 0), |(smallest, largest), size| (smallest.min(size), largest.max(size)));
|
||||
let (smallest, largest) = if largest == 0 {
|
||||
let size = resolution.output_size(texture_set.resolution, texture_set.resolution);
|
||||
(size, size)
|
||||
} else {
|
||||
(smallest, largest)
|
||||
};
|
||||
let size_label = if smallest == largest { format!("{smallest} × {smallest}") } else { format!("{smallest}–{largest} × {smallest}–{largest}") };
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(tr("Output size")).color(tokens.text_dim));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(size_label));
|
||||
})
|
||||
.response
|
||||
.on_hover_text(tr("An output finer than a UV tile gives the same result as that tile's resolution."));
|
||||
}
|
||||
|
||||
/// The most powers of two a resolution factor scales by, either way.
|
||||
const LARGEST_FACTOR_STEPS: u8 = OutputResolution::FACTORS.end().unsigned_abs();
|
||||
|
||||
/// "Same as context", or the fraction or multiple a resolution factor stands for.
|
||||
fn factor_label(factor: i8) -> String {
|
||||
match factor {
|
||||
0 => tr("Same as context").to_string(),
|
||||
negative if negative < 0 => format!("1/{}", 1u32 << negative.unsigned_abs().min(LARGEST_FACTOR_STEPS)),
|
||||
positive => format!("×{}", 1u32 << positive.unsigned_abs().min(LARGEST_FACTOR_STEPS)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Global invert, blur, balance and contrast: what every generator applies to its finished value.
|
||||
fn global_adjustments(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) {
|
||||
let (mut invert, mut global) = (generator.invert, generator.global);
|
||||
let invert_edit = ui.checkbox(&mut invert, tr("Global invert")).changed().then_some(false);
|
||||
let blur_edit = slider_edit(ui, tr("Global blur"), &mut global.blur, 0.0..=1.0, 2);
|
||||
let balance_edit = slider_edit(ui, tr("Global balance"), &mut global.balance, 0.0..=1.0, 2);
|
||||
let contrast_edit = slider_edit(ui, tr("Global contrast"), &mut global.contrast, 0.0..=1.0, 2);
|
||||
if let Some(merge) = invert_edit.or(blur_edit).or(balance_edit).or(contrast_edit) {
|
||||
app.run(
|
||||
"effect.set",
|
||||
json!({"effect": id, "invert": invert, "blur": global.blur, "balance": global.balance, "contrast": global.contrast, "merge": merge}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the generator's ramp starts, how soft it is, the noise breaking it up, its offset and its seed.
|
||||
fn ramp_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) {
|
||||
let (mut level, mut softness, mut noise, mut noise_scale, mut offset) =
|
||||
(generator.level, generator.softness, generator.noise_amount, generator.noise_scale, generator.offset);
|
||||
let level_edit = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2);
|
||||
let softness_edit = slider_edit(ui, tr("Softness"), &mut softness, 0.0..=1.0, 2);
|
||||
let noise_edit = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2);
|
||||
let noise_scale_edit = slider_edit(ui, tr("Noise scale"), &mut noise_scale, 0.1..=64.0, 1);
|
||||
let offset_edit = slider_edit(ui, tr("Offset"), &mut offset, -1.0..=1.0, 2);
|
||||
if let Some(merge) = level_edit.or(softness_edit).or(noise_edit).or(noise_scale_edit).or(offset_edit) {
|
||||
app.run(
|
||||
"effect.set",
|
||||
json!({"effect": id, "level": level, "softness": softness, "noise": noise, "noiseScale": noise_scale, "offset": offset, "merge": merge}),
|
||||
);
|
||||
}
|
||||
seed_row(app, ui, id, generator.seed);
|
||||
}
|
||||
|
||||
/// The seed with a button that picks a new one and a pencil that opens a field to type it, as in the reference.
|
||||
fn seed_row(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, seed: u32) {
|
||||
let typing_id = ui.make_persistent_id(("generator_seed_typing", id));
|
||||
let mut typing = ui.data(|data| data.get_temp::<bool>(typing_id)).unwrap_or(false);
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Seed"));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.selectable_label(typing, ic::PENCIL_SIMPLE).on_hover_text(tr("Type the seed")).clicked() {
|
||||
typing = !typing;
|
||||
}
|
||||
if typing {
|
||||
let mut typed = seed;
|
||||
let field = ui.add(egui::DragValue::new(&mut typed).speed(1.0));
|
||||
if field.changed() {
|
||||
// The later changes of one drag continue its first undo step
|
||||
let merge = field.dragged() && !field.drag_started();
|
||||
app.run("effect.set", json!({"effect": id, "seed": typed, "merge": merge}));
|
||||
}
|
||||
} else if ui.button(tr("Random")).on_hover_text(trf("Seed {seed}", &[("seed", &seed)])).clicked() {
|
||||
app.run("effect.set", json!({"effect": id, "seed": random_seed(seed)}));
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.data_mut(|data| data.insert_temp(typing_id, typing));
|
||||
}
|
||||
|
||||
/// A seed different from `current`, from the clock.
|
||||
fn random_seed(current: u32) -> u32 {
|
||||
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |elapsed| elapsed.subsec_nanos());
|
||||
let mixed = nanos.wrapping_mul(SEED_MIX) % SEED_RANGE;
|
||||
if mixed == current { (mixed + 1) % SEED_RANGE } else { mixed }
|
||||
}
|
||||
|
||||
/// The `effect.set` params that put generator effect `id` back to the defaults of its kind.
|
||||
fn defaults_of(id: u64, kind: GeneratorKind) -> Value {
|
||||
let defaults = Generator::new(kind);
|
||||
let mut params = json!({
|
||||
"effect": id,
|
||||
"level": defaults.level,
|
||||
"softness": defaults.softness,
|
||||
"noise": defaults.noise_amount,
|
||||
"noiseScale": defaults.noise_scale,
|
||||
"offset": defaults.offset,
|
||||
"seed": defaults.seed,
|
||||
"direction": defaults.direction,
|
||||
"invert": defaults.invert,
|
||||
"blur": defaults.global.blur,
|
||||
"balance": defaults.global.balance,
|
||||
"contrast": defaults.global.contrast,
|
||||
"resolution": format!("{:?}", defaults.resolution.mode),
|
||||
"customResolution": defaults.resolution.custom,
|
||||
"resolutionFactor": defaults.resolution.factor,
|
||||
});
|
||||
if let Some(detail) = defaults.detail {
|
||||
params["mode"] = json!(format!("{:?}", detail.mode));
|
||||
params["sizes"] = json!(detail.weights);
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
/// The curvature mode and detail size weights of generator effect `id` (`detail` None: saved before detail sizes).
|
||||
fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, detail: Option<&CurvatureDetail>) {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let shown = detail.cloned().unwrap_or_default();
|
||||
combo(ui, tr("Mode"), curvature_mode_label(shown.mode), |ui| {
|
||||
for mode in CurvatureMode::ALL {
|
||||
if ui.selectable_label(mode == shown.mode, curvature_mode_label(mode)).clicked() {
|
||||
app.run("effect.set", json!({"effect": id, "mode": format!("{mode:?}")}));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
ui.label(caption(tr("Detail sizes")));
|
||||
let mut weights = shown.weights;
|
||||
let mut edit = None;
|
||||
for (weight, size) in weights.iter_mut().zip(CurvatureDetail::SIZES) {
|
||||
edit = edit.or(slider_edit(ui, &format!("{size} px"), weight, 0.0..=1.0, 2));
|
||||
}
|
||||
if let Some(merge) = edit {
|
||||
app.run("effect.set", json!({"effect": id, "sizes": weights, "merge": merge}));
|
||||
}
|
||||
if detail.is_none() {
|
||||
ui.label(RichText::new(tr("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.")).color(tokens.text_dim));
|
||||
}
|
||||
}
|
||||
|
||||
/// The translated name of curvature mode `mode`.
|
||||
fn curvature_mode_label(mode: CurvatureMode) -> &'static str {
|
||||
match mode {
|
||||
CurvatureMode::Edges => tr("Edges"),
|
||||
CurvatureMode::Cavities => tr("Cavities"),
|
||||
CurvatureMode::Both => tr("Edges and cavities"),
|
||||
CurvatureMode::Raw => tr("Raw curvature"),
|
||||
}
|
||||
}
|
||||
|
||||
/// One input of generator effect `id` on `layer`: what it reads (its mesh map unless `source` replaces it), a menu to replace it, and a button to read the mesh map again.
|
||||
fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64), map: BakedMap, source: Option<&Source>, detail_sizes: bool) {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let input = map.id();
|
||||
let current = match source {
|
||||
None => trf("Mesh map: {map}", &[("map", &tr(baked_map_label(map)))]),
|
||||
Some(Source::Image { name, .. }) => trf("Image: {name}", &[("name", name)]),
|
||||
Some(Source::Uniform(_)) => tr("Uniform value").to_string(),
|
||||
Some(Source::Anchor { anchor, channel }) => anchor_label(app, *anchor, *channel),
|
||||
Some(Source::Procedural { .. }) => tr("Procedural").to_string(),
|
||||
};
|
||||
let group = ui.group(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
input_tile(app, ui, map, source);
|
||||
ui.vertical(|ui| {
|
||||
ui.label(RichText::new(tr(baked_map_label(map))).strong());
|
||||
ui.label(RichText::new(¤t).size(NOTE_FONT_SIZE).color(tokens.text_dim));
|
||||
});
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if source.is_some() && ui.button(ic::X).on_hover_text(tr("Read the mesh map again")).clicked() {
|
||||
app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true}));
|
||||
}
|
||||
});
|
||||
});
|
||||
combo(ui, tr("Source"), current.clone(), |ui| {
|
||||
let anchors = anchors_below(app, layer);
|
||||
if ui.selectable_label(source.is_none(), tr("Mesh map")).clicked() {
|
||||
app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true}));
|
||||
}
|
||||
if ui.selectable_label(matches!(source, Some(Source::Uniform(_))), tr("Uniform value")).clicked() {
|
||||
app.run("effect.set", json!({"effect": id, "input": input, "inputValue": map.neutral()[0]}));
|
||||
}
|
||||
for (anchor, label) in &anchors {
|
||||
if ui
|
||||
.selectable_label(
|
||||
matches!(source, Some(Source::Anchor { anchor: picked, .. }) if picked == anchor),
|
||||
trf("Anchor: {name}", &[("name", label)]),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
app.run("effect.set", json!({"effect": id, "input": input, "inputAnchor": anchor.0}));
|
||||
}
|
||||
}
|
||||
if let Some(name) = image_menu(app, ui) {
|
||||
app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name}));
|
||||
}
|
||||
});
|
||||
if let Some(Source::Uniform(value)) = source {
|
||||
let mut value = value[0];
|
||||
if let Some(merge) = slider_edit(ui, tr("Value"), &mut value, 0.0..=1.0, 2) {
|
||||
app.run("effect.set", json!({"effect": id, "input": input, "inputValue": value, "merge": merge}));
|
||||
}
|
||||
}
|
||||
if detail_sizes && map == BakedMap::Curvature && source.is_some_and(|source| !matches!(source, Source::Uniform(_))) {
|
||||
ui.label(
|
||||
RichText::new(tr("Detail sizes blur the mesh map, so a replaced curvature input is read at its own size only."))
|
||||
.size(NOTE_FONT_SIZE)
|
||||
.color(tokens.text_dim),
|
||||
);
|
||||
}
|
||||
});
|
||||
if let Some(name) = image_drop(ui, &group.response) {
|
||||
app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name}));
|
||||
}
|
||||
}
|
||||
|
||||
/// The picture of what an input reads: the image itself, the uniform value's gray, or the mesh map's swatch (as in the texture set's list).
|
||||
fn input_tile(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, source: Option<&Source>) {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let (rect, _) = ui.allocate_exact_size(egui::vec2(INPUT_TILE_SIZE, INPUT_TILE_SIZE), egui::Sense::hover());
|
||||
let painter = ui.painter();
|
||||
let whole = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0));
|
||||
match source {
|
||||
Some(Source::Image { name, .. }) => match app.session.images.get(name) {
|
||||
Some(image) => {
|
||||
let texture = app.thumbs.image(ui.ctx(), name, image);
|
||||
painter.image(texture.id(), rect, whole, egui::Color32::WHITE);
|
||||
}
|
||||
None => {
|
||||
painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button);
|
||||
}
|
||||
},
|
||||
Some(Source::Uniform(value)) => {
|
||||
painter.rect_filled(rect, INPUT_TILE_ROUNDING, egui::Color32::from_gray((value[0].clamp(0.0, 1.0) * 255.0).round() as u8));
|
||||
}
|
||||
Some(Source::Anchor { .. } | Source::Procedural { .. }) => {
|
||||
let glyph = if matches!(source, Some(Source::Anchor { .. })) { ic::ANCHOR } else { ic::MAGIC_WAND };
|
||||
painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button);
|
||||
painter.text(rect.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(INPUT_TILE_ICON_SIZE), tokens.text_dim);
|
||||
}
|
||||
None => {
|
||||
let baked = app.session.doc.baked.get(&app.session.ts()).is_some_and(|baked| baked.maps.contains_key(&map));
|
||||
painter.rect_filled(rect, INPUT_TILE_ROUNDING, if baked { mesh_map_color(map) } else { tokens.button });
|
||||
}
|
||||
}
|
||||
painter.rect_stroke(rect, INPUT_TILE_ROUNDING, egui::Stroke::new(1.0, tokens.button_border), egui::StrokeKind::Outside);
|
||||
}
|
||||
@@ -11,7 +11,7 @@ use texturecraft_engine::Session;
|
||||
use texturecraft_engine::compose::{DisplayKind, ImageRes, tile_bytes};
|
||||
use texturecraft_engine::core::BakedMap;
|
||||
use texturecraft_engine::geom::Mesh;
|
||||
use texturecraft_render::{BakeVisualization, Frame, Renderer, wgpu};
|
||||
use texturecraft_render::{BakeVisualization, CageGeometry, Frame, Renderer, wgpu};
|
||||
|
||||
use crate::bake_scene::{BakeSceneLink, CageUpload};
|
||||
|
||||
@@ -27,8 +27,8 @@ pub enum AuxView {
|
||||
/// A texture set's texels across and down, and its mesh material.
|
||||
pub type SetLayout = ((u32, u32), usize);
|
||||
|
||||
/// The low poly's UV seam edges (vertex pairs) per material
|
||||
pub type UvSeamEdges = Vec<Vec<(u32, u32)>>;
|
||||
/// The low poly's hard edges without a UV seam (vertex pairs) per material
|
||||
pub type MissingSeamEdges = Vec<Vec<(u32, u32)>>;
|
||||
|
||||
/// What the renderer must catch up with before drawing.
|
||||
#[derive(Default)]
|
||||
@@ -49,8 +49,8 @@ pub struct SceneSync {
|
||||
pub bake_cages: Vec<(usize, Option<CageUpload>, u64)>,
|
||||
/// Texture sets left after some were removed: their cages go too
|
||||
pub bake_cage_count: Option<usize>,
|
||||
/// The low poly's UV seams per material, for mesh id
|
||||
pub uv_seams: Option<(u64, UvSeamEdges)>,
|
||||
/// The low poly's hard edges without a UV seam per material, for mesh id
|
||||
pub missing_seams: Option<(u64, MissingSeamEdges)>,
|
||||
}
|
||||
|
||||
/// Lives in egui's callback resources.
|
||||
@@ -366,11 +366,15 @@ impl CallbackTrait for ViewCallback {
|
||||
gpu.renderer.truncate_bake_cages(count);
|
||||
}
|
||||
for (texture_set, cage, topology) in &sync.bake_cages {
|
||||
let cage = cage.as_ref().map(|upload| (upload.corners.as_slice(), upload.shell.edges.as_slice()));
|
||||
let cage = cage.as_ref().map(|upload| CageGeometry {
|
||||
corners: &upload.corners,
|
||||
edges: &upload.shell.edges,
|
||||
missing_seams: &upload.shell.missing_seams,
|
||||
});
|
||||
gpu.renderer.set_bake_cage(device, queue, *texture_set, cage, *topology);
|
||||
}
|
||||
if let Some((mesh_id, seams)) = &sync.uv_seams {
|
||||
gpu.renderer.set_uv_seams(device, queue, *mesh_id, seams);
|
||||
if let Some((mesh_id, seams)) = &sync.missing_seams {
|
||||
gpu.renderer.set_missing_seams(device, queue, *mesh_id, seams);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -384,6 +388,7 @@ impl CallbackTrait for ViewCallback {
|
||||
reports.memory.push(texture_set);
|
||||
}
|
||||
}
|
||||
|
||||
// This frame's report drain already ran: the next frame shows the toast
|
||||
gpu.ctx.request_repaint();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
//! A grid tile's measurements in the shelf's small, medium and large views
|
||||
|
||||
/// A grid tile's size and its thumbnail's size and center below the tile's top, in points
|
||||
pub(crate) struct GridTile {
|
||||
pub(crate) width: f32,
|
||||
pub(crate) height: f32,
|
||||
pub(crate) thumbnail_size: f32,
|
||||
pub(crate) thumbnail_center_y: f32,
|
||||
}
|
||||
+39
-36
@@ -158,35 +158,36 @@ mod tests {
|
||||
fn catalog_keys() -> Vec<&'static str> {
|
||||
use texturecraft_engine::core::{BlendMode, Channel, EffectKind, GeneratorKind, ProceduralKind};
|
||||
use texturecraft_engine::filter_lib::{FILTERS, build, scalar_params};
|
||||
let mut k: Vec<&'static str> = Vec::new();
|
||||
k.extend(crate::menus::TOP);
|
||||
for i in crate::menus::CATALOG.iter().filter(|i| i.label != "-") {
|
||||
k.push(i.label);
|
||||
k.extend(i.sub);
|
||||
let mut keys: Vec<&'static str> = Vec::new();
|
||||
keys.extend(crate::menus::TOP);
|
||||
for item in crate::menus::CATALOG.iter().filter(|item| item.label != "-") {
|
||||
keys.push(item.label);
|
||||
keys.extend(item.sub);
|
||||
}
|
||||
k.extend(crate::docking::VIEWS.iter().map(|(_, p)| p.name()));
|
||||
for b in crate::keymap::bindings() {
|
||||
k.push(b.label);
|
||||
k.push(b.group);
|
||||
keys.extend(crate::docking::VIEWS.iter().map(|(_, panel)| panel.name()));
|
||||
for binding in crate::keymap::bindings() {
|
||||
keys.push(binding.label);
|
||||
keys.push(binding.group);
|
||||
}
|
||||
k.extend(crate::shelf::TABS.iter().map(|t| t.2));
|
||||
k.extend(Channel::ALL.iter().flat_map(|c| [c.label(), c.short()]));
|
||||
k.extend(BlendMode::all().map(|m| m.label()));
|
||||
k.extend(texturecraft_engine::formats::export::VirtualMap::ALL.iter().map(|m| m.label()));
|
||||
k.extend(texturecraft_engine::Tool::ALL.iter().map(|t| t.label()));
|
||||
k.extend(ProceduralKind::ALL.iter().map(|p| p.label()));
|
||||
k.extend(GeneratorKind::ALL.iter().map(|g| g.label()));
|
||||
k.extend(texturecraft_engine::paint::BrushAlpha::ALL.iter().map(|a| a.label()));
|
||||
k.extend(texturecraft_engine::geom::primitives::BUILTINS.iter().map(|(_, l)| *l));
|
||||
for f in FILTERS {
|
||||
k.extend([f.label, f.group]);
|
||||
if let Ok(EffectKind::Filter(x)) = build(f.id, &serde_json::Value::Null) {
|
||||
k.push(x.label());
|
||||
k.extend(scalar_params(&x).into_iter().map(|p| p.1));
|
||||
keys.extend(crate::shelf::TABS.iter().map(|tab| tab.2));
|
||||
keys.extend(Channel::ALL.iter().flat_map(|channel| [channel.label(), channel.short()]));
|
||||
keys.extend(BlendMode::all().map(|mode| mode.label()));
|
||||
keys.extend(texturecraft_engine::formats::export::VirtualMap::ALL.iter().map(|map| map.label()));
|
||||
keys.extend(texturecraft_engine::Tool::ALL.iter().map(|tool| tool.label()));
|
||||
keys.extend(ProceduralKind::ALL.iter().map(|kind| kind.label()));
|
||||
keys.extend(GeneratorKind::ALL.iter().map(|kind| kind.label()));
|
||||
keys.extend(texturecraft_engine::paint::BrushAlpha::ALL.iter().map(|alpha| alpha.label()));
|
||||
keys.extend(texturecraft_engine::geom::primitives::BUILTINS.iter().map(|(_, label)| *label));
|
||||
for filter in FILTERS {
|
||||
keys.extend([filter.label, filter.group]);
|
||||
if let Ok(EffectKind::Filter(effect)) = build(filter.id, &serde_json::Value::Null) {
|
||||
keys.push(effect.label());
|
||||
keys.extend(scalar_params(&effect).into_iter().map(|parameter| parameter.1));
|
||||
}
|
||||
}
|
||||
// Effect, view and camera names the engine gives.
|
||||
k.extend([
|
||||
|
||||
// Include effect, view and camera names supplied by the engine
|
||||
keys.extend([
|
||||
"Paint",
|
||||
"Path",
|
||||
"Fill",
|
||||
@@ -199,8 +200,8 @@ mod tests {
|
||||
texturecraft_engine::camera_cmds::DEFAULT_CAMERA,
|
||||
crate::dock::SOLO_HINT,
|
||||
]);
|
||||
k.retain(|s| !s.is_empty() && !UNTRANSLATED.contains(s));
|
||||
k
|
||||
keys.retain(|key| !key.is_empty() && !UNTRANSLATED.contains(key));
|
||||
keys
|
||||
}
|
||||
|
||||
/// String literals passed straight to `tr(` or `trf(` in `src`.
|
||||
@@ -254,7 +255,8 @@ mod tests",
|
||||
for &(locale, common, app) in CRAFT_I18N {
|
||||
let Some(lang) = I18N.from_code(locale) else { continue };
|
||||
let missing: Vec<_> = keys.iter().filter(|key| I18N.get(lang, "", key).is_none()).collect();
|
||||
// Decode TSV escapes for comparison with the literal source strings.
|
||||
|
||||
// Decode TSV escapes to compare with literal source strings
|
||||
let mut rows = HashMap::new();
|
||||
for text in [common, app] {
|
||||
for line in text.lines().filter(|l| !l.starts_with('#')) {
|
||||
@@ -335,17 +337,18 @@ mod tests",
|
||||
let _lock = LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let keys = keys();
|
||||
set_language("ja");
|
||||
let t = std::time::Instant::now();
|
||||
let mut n = 0usize;
|
||||
let started = std::time::Instant::now();
|
||||
let mut total_chars = 0usize;
|
||||
for _ in 0..100 {
|
||||
for k in &keys {
|
||||
n += tr(k).len();
|
||||
for key in &keys {
|
||||
total_chars += tr(key).len();
|
||||
}
|
||||
}
|
||||
let per = t.elapsed().as_secs_f64() * 1e9 / (100 * keys.len()) as f64;
|
||||
let ns_per_lookup = started.elapsed().as_secs_f64() * 1e9 / (100 * keys.len()) as f64;
|
||||
set_language("en");
|
||||
assert!(n > 0);
|
||||
// A frame looks up a few hundred strings: well under a microsecond each.
|
||||
assert!(per < 1000.0, "{per:.0} ns per lookup");
|
||||
assert!(total_chars > 0);
|
||||
|
||||
// A frame looks up a few hundred strings, each expected below one microsecond
|
||||
assert!(ns_per_lookup < 1000.0, "{ns_per_lookup:.0} ns per lookup");
|
||||
}
|
||||
}
|
||||
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user