mirror of
https://github.com/storytold/texturecraft.git
synced 2026-12-01 02:24:09 +01:00
Auto: Integrate main and reduce repeated procedural sampling work
Reuse two fur seed tables per worker, share knot noise, and skip invisible decay and brocade detail. Normalize each catalog lookup once while preserving label and saved-name aliases. Consolidate periodic sampling helpers, move FurLock into its own module, and strengthen coverage of coarse-grid fallback and saved pattern names. Preserve main's project and Assets changes and document the expanded catalog.
This commit is contained in:
commit
6f8e984d7a
42 files changed
+3647
-1017
No files matched your search
@@ -157,8 +157,8 @@ cd apps/texturecraft-web && trunk serve # web build
|
||||
cargo xtask ci # fmt, clippy, tests, layering, wasm
|
||||
```
|
||||
|
||||
You need Rust 1.95 or newer. The app opens with no project (**File ▸ Open sample project** loads a baked one; **File ▸ Close** returns to this empty state); **File ▸ New project** starts
|
||||
from a built-in mesh, a project template or your own mesh file (UVs are generated if it has none).
|
||||
You need Rust 1.95 or newer. The app opens with no project (**File ▸ Open sample project** loads a baked one, and **File ▸ Close** returns to the empty state).
|
||||
**File ▸ New project** starts from your own mesh file and a project template. TextureCraft generates UVs if the mesh has none.
|
||||
|
||||
Japanese, Chinese, Korean and Arabic interface text uses the fonts of
|
||||
[storytold/craft-fonts](https://github.com/storytold/craft-fonts) where it has them, an optional
|
||||
|
||||
@@ -9,9 +9,9 @@ use texturecraft_texel::noise;
|
||||
use crate::organic::{smoothstep, unit};
|
||||
|
||||
/// A thread's round cross-section: 0 at its edges, 1 along its crest, for `across` in 0..1
|
||||
fn round(across: f32) -> f32 {
|
||||
let c = 2.0 * across - 1.0;
|
||||
(1.0 - c * c).max(0.0).sqrt()
|
||||
fn thread_profile(across: f32) -> f32 {
|
||||
let centered = 2.0 * across - 1.0;
|
||||
(1.0 - centered * centered).max(0.0).sqrt()
|
||||
}
|
||||
|
||||
/// How a thread swells between the crossings at its ends, for `along` in 0..1
|
||||
@@ -19,11 +19,12 @@ fn bulge(along: f32) -> f32 {
|
||||
0.55 + 0.45 * (std::f32::consts::PI * along).sin()
|
||||
}
|
||||
|
||||
/// Distance from `p` to the segment `a`..`b`, and where along it the nearest point lies (0..1)
|
||||
fn segment(p: Vec2, a: Vec2, b: Vec2) -> (f32, f32) {
|
||||
let ab = b - a;
|
||||
let t = ((p - a).dot(ab) / ab.length_squared().max(1e-9)).clamp(0.0, 1.0);
|
||||
((p - (a + ab * t)).length(), t)
|
||||
/// Distance from `point` to the segment from `start` to `end`, and the fraction along it.
|
||||
fn segment(point: Vec2, start: Vec2, end: Vec2) -> (f32, f32) {
|
||||
const MIN_LENGTH_SQUARED: f32 = 1e-9;
|
||||
let direction = end - start;
|
||||
let along = ((point - start).dot(direction) / direction.length_squared().max(MIN_LENGTH_SQUARED)).clamp(0.0, 1.0);
|
||||
((point - (start + direction * along)).length(), along)
|
||||
}
|
||||
|
||||
/// Stockinette: columns of V-shaped stitches, each of two twisted legs of yarn that lean towards
|
||||
@@ -31,27 +32,28 @@ fn segment(p: Vec2, a: Vec2, b: Vec2) -> (f32, f32) {
|
||||
pub(crate) fn knit(p: Vec3, seed: u32) -> f32 {
|
||||
const COLUMNS: i32 = 10;
|
||||
const ROWS: i32 = 14;
|
||||
// Yarn radius, in stitch widths
|
||||
const RADIUS: f32 = 0.21;
|
||||
let q = unit(p) * Vec2::new(COLUMNS as f32, ROWS as f32);
|
||||
let (ci, cj) = (q.x.floor() as i32, q.y.floor() as i32);
|
||||
const YARN_RADIUS_IN_STITCH_WIDTHS: f32 = 0.21;
|
||||
const TWISTS_PER_LEG: f32 = 2.5;
|
||||
const TWIST_SLOPE: f32 = 0.3;
|
||||
let point = unit(p) * Vec2::new(COLUMNS as f32, ROWS as f32);
|
||||
let (column, row) = (point.x.floor() as i32, point.y.floor() as i32);
|
||||
|
||||
let mut height = 0.0f32;
|
||||
let mut tone = 0.5f32;
|
||||
for j in (cj - 1)..=(cj + 1) {
|
||||
for i in (ci - 1)..=(ci + 1) {
|
||||
let cell = Vec2::new(i as f32, j as f32);
|
||||
let yarn = 0.85 + 0.15 * noise::cell_hash(i.rem_euclid(COLUMNS), j.rem_euclid(ROWS), 0, seed ^ 0x4B);
|
||||
// The two legs: from the top corners to the bottom middle
|
||||
for stitch_row in (row - 1)..=(row + 1) {
|
||||
for stitch_column in (column - 1)..=(column + 1) {
|
||||
let cell = Vec2::new(stitch_column as f32, stitch_row as f32);
|
||||
let yarn = 0.85 + 0.15 * noise::cell_hash(stitch_column.rem_euclid(COLUMNS), stitch_row.rem_euclid(ROWS), 0, seed ^ 0x4B);
|
||||
|
||||
// The two legs share the bottom of the stitch
|
||||
for (side, top) in [(-1.0f32, Vec2::new(0.1, -0.05)), (1.0, Vec2::new(0.9, -0.05))] {
|
||||
let (distance, along) = segment(q, cell + top, cell + Vec2::new(0.5, 1.05));
|
||||
if distance >= RADIUS {
|
||||
let (distance, along) = segment(point, cell + top, cell + Vec2::new(0.5, 1.05));
|
||||
if distance >= YARN_RADIUS_IN_STITCH_WIDTHS {
|
||||
continue;
|
||||
}
|
||||
|
||||
let across = distance / RADIUS;
|
||||
// The yarn is twisted: slanted ridges along the leg
|
||||
let twist = 0.5 + 0.5 * (std::f32::consts::TAU * (along * 2.5 + side * across * 0.3)).cos();
|
||||
let across = distance / YARN_RADIUS_IN_STITCH_WIDTHS;
|
||||
let twist = 0.5 + 0.5 * (std::f32::consts::TAU * (along * TWISTS_PER_LEG + side * across * TWIST_SLOPE)).cos();
|
||||
let leg = (1.0 - across * across).sqrt() * (0.82 + 0.18 * twist) * yarn;
|
||||
if leg > height {
|
||||
height = leg;
|
||||
@@ -69,21 +71,23 @@ pub(crate) fn knit(p: Vec3, seed: u32) -> f32 {
|
||||
pub(crate) fn basket_weave(p: Vec3, seed: u32) -> f32 {
|
||||
// Even, so that the checkerboard lines up again after one unit
|
||||
const BLOCKS: i32 = 4;
|
||||
const PAIR: f32 = 2.0;
|
||||
let q = unit(p) * BLOCKS as f32;
|
||||
let (bx, by) = (q.x.floor() as i32, q.y.floor() as i32);
|
||||
let (fx, fy) = (q.x - bx as f32, q.y - by as f32);
|
||||
const THREADS_PER_BLOCK: i32 = 2;
|
||||
const FIBRES_PER_THREAD: f32 = 6.0;
|
||||
let point = unit(p) * BLOCKS as f32;
|
||||
let (column, row) = (point.x.floor() as i32, point.y.floor() as i32);
|
||||
let local = point - Vec2::new(column as f32, row as f32);
|
||||
|
||||
let across_the_page = (bx + by).rem_euclid(2) == 0;
|
||||
let (along, position) = if across_the_page { (fx, fy) } else { (fy, fx) };
|
||||
let thread = (position * PAIR).floor() as i32;
|
||||
let across = position * PAIR - thread as f32;
|
||||
let horizontal = (column + row).rem_euclid(2) == 0;
|
||||
let (along, position) = if horizontal { (local.x, local.y) } else { (local.y, local.x) };
|
||||
let thread_position = position * THREADS_PER_BLOCK as f32;
|
||||
let thread = thread_position.floor() as i32;
|
||||
let across = thread_position - thread as f32;
|
||||
|
||||
let tone = noise::cell_hash((bx * 2 + thread).rem_euclid(BLOCKS * 2), by.rem_euclid(BLOCKS), across_the_page as i32, seed ^ 0x2D);
|
||||
// Fine fibres along the thread
|
||||
let fibre = 0.9 + 0.1 * (std::f32::consts::TAU * across * 6.0).cos();
|
||||
let crest = round(across) * bulge(along) * fibre;
|
||||
((0.1 + 0.9 * crest) * (0.75 + 0.25 * tone) * if across_the_page { 1.0 } else { 0.9 }).clamp(0.0, 1.0)
|
||||
let tone =
|
||||
noise::cell_hash((column * THREADS_PER_BLOCK + thread).rem_euclid(BLOCKS * THREADS_PER_BLOCK), row.rem_euclid(BLOCKS), horizontal as i32, seed ^ 0x2D);
|
||||
let fibre = 0.9 + 0.1 * (std::f32::consts::TAU * across * FIBRES_PER_THREAD).cos();
|
||||
let crest = thread_profile(across) * bulge(along) * fibre;
|
||||
((0.1 + 0.9 * crest) * (0.75 + 0.25 * tone) * if horizontal { 1.0 } else { 0.9 }).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// Goose-eye twill: a 2/2 twill whose diagonal turns back every few threads, across and down, so
|
||||
@@ -91,28 +95,29 @@ pub(crate) fn basket_weave(p: Vec3, seed: u32) -> f32 {
|
||||
/// brighter than the weft.
|
||||
pub(crate) fn goose_eye(p: Vec3, seed: u32) -> f32 {
|
||||
const THREADS: i32 = 24;
|
||||
// Threads from one turn of the diagonal to the next; two of them go to the repeat
|
||||
const HALF: i32 = 6;
|
||||
const THREADS_BETWEEN_TURNS: i32 = 6;
|
||||
const CROSSINGS_PER_REPEAT: i32 = 4;
|
||||
const WARP_PER_REPEAT: i32 = 2;
|
||||
let q = unit(p) * THREADS as f32;
|
||||
let (i, j) = (q.x.floor() as i32, q.y.floor() as i32);
|
||||
let (fx, fy) = (q.x - i as f32, q.y - j as f32);
|
||||
|
||||
// Threads away from the nearest turn
|
||||
let from_turn = |k: i32| (k.rem_euclid(2 * HALF) - HALF).abs();
|
||||
let warp_over = |i: i32, j: i32| (from_turn(i) + from_turn(j)).rem_euclid(4) < 2;
|
||||
let from_turn = |thread: i32| (thread.rem_euclid(2 * THREADS_BETWEEN_TURNS) - THREADS_BETWEEN_TURNS).abs();
|
||||
let warp_over = |i: i32, j: i32| (from_turn(i) + from_turn(j)).rem_euclid(CROSSINGS_PER_REPEAT) < WARP_PER_REPEAT;
|
||||
|
||||
let tone = noise::cell_hash(i.rem_euclid(THREADS), j.rem_euclid(THREADS), 0, seed ^ 0x3E);
|
||||
// A float runs on over the next crossing when its thread stays on top there; it tucks under
|
||||
// only at its ends
|
||||
|
||||
// Taper the ends only where the thread crosses underneath
|
||||
let tuck = |along: f32, before: bool, after: bool| {
|
||||
let start = if before { 1.0 } else { 0.55 + 0.45 * smoothstep(0.0, 0.3, along) };
|
||||
let end = if after { 1.0 } else { 0.55 + 0.45 * smoothstep(1.0, 0.7, along) };
|
||||
start * end
|
||||
};
|
||||
let (crest, brightness) = if warp_over(i, j) {
|
||||
(round(fx) * tuck(fy, warp_over(i, j - 1), warp_over(i, j + 1)), 1.0)
|
||||
(thread_profile(fx) * tuck(fy, warp_over(i, j - 1), warp_over(i, j + 1)), 1.0)
|
||||
} else {
|
||||
(round(fy) * tuck(fx, !warp_over(i - 1, j), !warp_over(i + 1, j)), 0.4)
|
||||
(thread_profile(fy) * tuck(fx, !warp_over(i - 1, j), !warp_over(i + 1, j)), 0.4)
|
||||
};
|
||||
((0.1 + 0.9 * crest) * brightness * (0.9 + 0.1 * tone)).clamp(0.0, 1.0)
|
||||
}
|
||||
@@ -121,8 +126,11 @@ pub(crate) fn goose_eye(p: Vec3, seed: u32) -> f32 {
|
||||
/// stretch of yarn that floats over the threads it crosses, and each thread has a sheen of its own.
|
||||
pub(crate) fn slub_silk(p: Vec3, seed: u32) -> f32 {
|
||||
const THREADS: i32 = 36;
|
||||
// Slubs along a thread, per unit
|
||||
const SLUBS: i32 = 7;
|
||||
const SLUB_CELLS_PER_THREAD: i32 = 7;
|
||||
const SLUB_START: f32 = 0.74;
|
||||
const SLUB_FULL: f32 = 0.93;
|
||||
const FLOAT_THRESHOLD: f32 = 0.5;
|
||||
const SHEEN_HASH_COMPONENT: i32 = 99;
|
||||
let u = unit(p);
|
||||
let q = u * THREADS as f32;
|
||||
let (i, j) = (q.x.floor() as i32, q.y.floor() as i32);
|
||||
@@ -131,28 +139,30 @@ pub(crate) fn slub_silk(p: Vec3, seed: u32) -> f32 {
|
||||
// Slub strength along a thread: smooth noise, mostly low
|
||||
let slub_of = |thread: i32, along_unit: f32, warp: bool| {
|
||||
let thread = thread.rem_euclid(THREADS);
|
||||
let s = along_unit * SLUBS as f32;
|
||||
let k = s.floor() as i32;
|
||||
let f = s - k as f32;
|
||||
let at = |step: i32| noise::cell_hash(thread, (k + step).rem_euclid(SLUBS), warp as i32, seed ^ 0x5A);
|
||||
smoothstep(0.74, 0.93, at(0) + (at(1) - at(0)) * f * f * (3.0 - 2.0 * f))
|
||||
let along = along_unit * SLUB_CELLS_PER_THREAD as f32;
|
||||
let cell = along.floor() as i32;
|
||||
let fraction = along - cell as f32;
|
||||
let at = |step: i32| noise::cell_hash(thread, (cell + step).rem_euclid(SLUB_CELLS_PER_THREAD), warp as i32, seed ^ 0x5A);
|
||||
let start = at(0);
|
||||
smoothstep(SLUB_START, SLUB_FULL, start + (at(1) - start) * fraction * fraction * (3.0 - 2.0 * fraction))
|
||||
};
|
||||
|
||||
// Warp threads run down the page and weft threads across it
|
||||
let (warp_slub, weft_slub) = (slub_of(i, u.y, true), slub_of(j, u.x, false));
|
||||
|
||||
// A slubbed thread floats over the threads it crosses; elsewhere they interlace one over one
|
||||
let warp_over = if warp_slub > 0.5 {
|
||||
let warp_over = if warp_slub > FLOAT_THRESHOLD {
|
||||
true
|
||||
} else if weft_slub > 0.5 {
|
||||
} else if weft_slub > FLOAT_THRESHOLD {
|
||||
false
|
||||
} else {
|
||||
(i + j).rem_euclid(2) == 0
|
||||
};
|
||||
let (thread, slub, across, along) = if warp_over { (i, warp_slub, fx, fy) } else { (j, weft_slub, fy, fx) };
|
||||
|
||||
let sheen = 0.45 + 0.25 * noise::cell_hash(thread.rem_euclid(THREADS), 99, warp_over as i32, seed ^ 0x6B);
|
||||
let tuck = if slub > 0.5 { 1.0 } else { bulge(along) };
|
||||
let crest = round(across) * tuck * (0.75 + 0.45 * slub);
|
||||
let sheen = 0.45 + 0.25 * noise::cell_hash(thread.rem_euclid(THREADS), SHEEN_HASH_COMPONENT, warp_over as i32, seed ^ 0x6B);
|
||||
let tuck = if slub > FLOAT_THRESHOLD { 1.0 } else { bulge(along) };
|
||||
let crest = thread_profile(across) * tuck * (0.75 + 0.45 * slub);
|
||||
((0.25 + 0.75 * crest) * (sheen + 0.28 * slub)).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
@@ -162,13 +172,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_stitch_is_a_v_and_a_basket_weave_has_pairs() {
|
||||
// Between two stitches of a row the yarn leaves a hollow; in the middle of a stitch it does not
|
||||
let grid = |size: usize| (0..size * size).map(move |i| Vec3::new((i % size) as f32 / size as f32, (i / size) as f32 / size as f32, 0.0));
|
||||
let hollows = grid(128).filter(|p| knit(*p, 1) < 0.15).count();
|
||||
|
||||
assert!((300..8000).contains(&hollows), "hollows cover {hollows} of 16384 samples");
|
||||
|
||||
// Pairs of threads: across a block whose threads run along the page there are two crests,
|
||||
// with a hollow between them and one at each side
|
||||
// A horizontal pair has two crests separated and flanked by hollows
|
||||
let across = |y: f32| basket_weave(Vec3::new(0.125, y, 0.0), 1);
|
||||
for crest in [0.0625, 0.1875] {
|
||||
assert!(across(crest) > 0.5, "no crest at {crest}: {}", across(crest));
|
||||
@@ -180,9 +189,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn goose_eye_turns_its_diagonal() {
|
||||
// A plain twill would repeat every four threads along a row; the turns make the weave differ from block to block
|
||||
let row = |y: f32| (0..48).map(|i| goose_eye(Vec3::new((i as f32 + 0.5) / 48.0 / 2.0, y, 0.0), 1) > 0.5).collect::<Vec<_>>();
|
||||
let (first, second) = (row(0.5 / 24.0), row(5.5 / 24.0));
|
||||
|
||||
assert_ne!(first, second, "every row weaves the same");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
|
||||
/// One lock of fur, with its root relative to its cell.
|
||||
pub(crate) struct FurLock {
|
||||
pub(crate) root: Vec2,
|
||||
/// Length along the axis, in cells.
|
||||
pub(crate) length: f32,
|
||||
pub(crate) angle_sin: f32,
|
||||
pub(crate) angle_cos: f32,
|
||||
/// Total turn of the axis, in radians.
|
||||
pub(crate) curl: f32,
|
||||
pub(crate) strength: f32,
|
||||
}
|
||||
@@ -14,6 +14,7 @@ pub mod curvature_sizes;
|
||||
pub mod display;
|
||||
pub mod eval;
|
||||
mod fabric;
|
||||
mod fur_lock;
|
||||
mod held_fields;
|
||||
mod image_identity;
|
||||
mod organic;
|
||||
|
||||
+255
-201
@@ -1,18 +1,22 @@
|
||||
//! Organic procedural surfaces: fur, clouds, reptile scales, bark, flesh and camouflage.
|
||||
//!
|
||||
//! Every pattern repeats every unit in U and V, tones and details included, so it tiles without
|
||||
//! seams. A point is first moved by whole units into the unit square, so huge or non-finite
|
||||
//! coordinates keep their precision and never overflow a cell index.
|
||||
//! seams. Wrapping finite coordinates before scaling keeps cell indices in range. Non-finite
|
||||
//! components map to zero.
|
||||
|
||||
use std::cell::RefCell;
|
||||
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_texel::noise;
|
||||
|
||||
pub(crate) fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 {
|
||||
let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0);
|
||||
use crate::fur_lock::FurLock;
|
||||
|
||||
pub(crate) fn smoothstep(start: f32, end: f32, value: f32) -> f32 {
|
||||
let t = ((value - start) / (end - start)).clamp(0.0, 1.0);
|
||||
t * t * (3.0 - 2.0 * t)
|
||||
}
|
||||
|
||||
/// `p` moved by whole units into the unit square; a coordinate that is not finite becomes 0
|
||||
/// Wrap the plane coordinates before converting to cell indices. Non-finite components become 0.
|
||||
pub(crate) fn unit(p: Vec3) -> Vec2 {
|
||||
let wrap = |x: f32| if x.is_finite() { x.rem_euclid(1.0) } else { 0.0 };
|
||||
Vec2::new(wrap(p.x), wrap(p.y))
|
||||
@@ -21,71 +25,60 @@ pub(crate) fn unit(p: Vec3) -> Vec2 {
|
||||
/// Smooth value noise in 0..1 on a lattice of `cells` (across, down) per unit whose indices wrap,
|
||||
/// so the noise repeats every unit
|
||||
pub(crate) fn lattice_noise(at: Vec2, cells: (i32, i32), seed: u32) -> f32 {
|
||||
let q = Vec2::new(at.x * cells.0 as f32, at.y * cells.1 as f32);
|
||||
let (i, j) = (q.x.floor() as i32, q.y.floor() as i32);
|
||||
let f = q - Vec2::new(i as f32, j as f32);
|
||||
let s = f * f * (Vec2::splat(3.0) - 2.0 * f);
|
||||
let corner = |di: i32, dj: i32| noise::cell_hash((i + di).rem_euclid(cells.0), (j + dj).rem_euclid(cells.1), 0, seed);
|
||||
let top = corner(0, 0) + (corner(1, 0) - corner(0, 0)) * s.x;
|
||||
let bottom = corner(0, 1) + (corner(1, 1) - corner(0, 1)) * s.x;
|
||||
top + (bottom - top) * s.y
|
||||
let point = Vec2::new(at.x * cells.0 as f32, at.y * cells.1 as f32);
|
||||
let (column, row) = (point.x.floor() as i32, point.y.floor() as i32);
|
||||
let fraction = point - Vec2::new(column as f32, row as f32);
|
||||
let weight = fraction * fraction * (Vec2::splat(3.0) - 2.0 * fraction);
|
||||
let corner = |dx: i32, dy: i32| noise::cell_hash((column + dx).rem_euclid(cells.0), (row + dy).rem_euclid(cells.1), 0, seed);
|
||||
|
||||
let top_left = corner(0, 0);
|
||||
let bottom_left = corner(0, 1);
|
||||
let top = top_left + (corner(1, 0) - top_left) * weight.x;
|
||||
let bottom = bottom_left + (corner(1, 1) - bottom_left) * weight.x;
|
||||
top + (bottom - top) * weight.y
|
||||
}
|
||||
|
||||
/// Fractal [`lattice_noise`] in 0..1: octaves of (cells per unit, weight), the weights adding up to 1
|
||||
pub(crate) fn lattice_fbm(at: Vec2, octaves: &[(i32, f32)], seed: u32) -> f32 {
|
||||
octaves.iter().enumerate().map(|(k, (cells, weight))| weight * lattice_noise(at, (*cells, *cells), seed ^ (k as u32).wrapping_mul(0x9E37))).sum()
|
||||
}
|
||||
|
||||
/// One lock of fur: where its root lies in its cell and how it grows
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Lock {
|
||||
/// Root, in cells from the corner of its cell
|
||||
root: Vec2,
|
||||
/// Length along its axis, in cells
|
||||
length: f32,
|
||||
sin: f32,
|
||||
cos: f32,
|
||||
/// Radians the axis turns over its length
|
||||
curl: f32,
|
||||
strength: f32,
|
||||
const OCTAVE_SALT: u32 = 0x9E37;
|
||||
octaves
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, (cells, weight))| weight * lattice_noise(at, (*cells, *cells), seed ^ (index as u32).wrapping_mul(OCTAVE_SALT)))
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Locks of fur on each side of the repeat
|
||||
const FUR_CELLS: i32 = 6;
|
||||
const FUR_CELLS: usize = 6;
|
||||
const FUR_LOCK_COUNT: usize = FUR_CELLS * FUR_CELLS;
|
||||
|
||||
/// The locks of one seed, one per cell of the repeat. Every texel reads the whole neighbourhood of
|
||||
/// roots, so the last seed's table is kept for the next call.
|
||||
fn locks(seed: u32) -> std::rc::Rc<[Lock]> {
|
||||
thread_local! {
|
||||
static LAST: std::cell::RefCell<Option<(u32, std::rc::Rc<[Lock]>)>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
type FurLocks = [FurLock; FUR_LOCK_COUNT];
|
||||
type FurCacheEntry = Option<(u32, FurLocks)>;
|
||||
|
||||
let build = || -> std::rc::Rc<[Lock]> {
|
||||
(0..FUR_CELLS * FUR_CELLS)
|
||||
.map(|index| {
|
||||
let h = |k: i32| noise::cell_hash(index % FUR_CELLS, index / FUR_CELLS, k, seed ^ 0x6D);
|
||||
let (sin, cos) = (0.1 + (h(3) * 2.0 - 1.0) * 0.45).sin_cos();
|
||||
Lock {
|
||||
root: Vec2::new(0.5 + (h(1) - 0.5) * 0.7, 0.5 + (h(2) - 0.5) * 0.7),
|
||||
length: 3.0 * (1.0 + (h(4) * 2.0 - 1.0) * 0.27),
|
||||
sin,
|
||||
cos,
|
||||
curl: -0.8 * (0.8 + h(5) * 0.4),
|
||||
strength: 0.8 + h(6) * 0.2,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
thread_local! {
|
||||
// Adjacent layers or channels can alternate seeds on the same worker
|
||||
static FUR_CACHE: RefCell<(bool, [FurCacheEntry; 2])> = const { RefCell::new((true, [None, None])) };
|
||||
}
|
||||
|
||||
LAST.with(|last| {
|
||||
let Ok(mut last) = last.try_borrow_mut() else { return build() };
|
||||
match last.as_ref() {
|
||||
Some((cached, table)) if *cached == seed => table.clone(),
|
||||
_ => {
|
||||
let table = build();
|
||||
*last = Some((seed, table.clone()));
|
||||
table
|
||||
}
|
||||
fn build_fur_locks(seed: u32) -> FurLocks {
|
||||
const ROOT_JITTER_CELLS: f32 = 0.7;
|
||||
const AXIS_ANGLE_RADIANS: f32 = 0.1;
|
||||
const ANGLE_JITTER_RADIANS: f32 = 0.45;
|
||||
const LENGTH_CELLS: f32 = 3.0;
|
||||
const LENGTH_JITTER: f32 = 0.27;
|
||||
const CURL_RADIANS: f32 = -0.8;
|
||||
|
||||
std::array::from_fn(|index| {
|
||||
let hash = |component| noise::cell_hash((index % FUR_CELLS) as i32, (index / FUR_CELLS) as i32, component, seed ^ 0x6D);
|
||||
let (angle_sin, angle_cos) = (AXIS_ANGLE_RADIANS + (hash(3) * 2.0 - 1.0) * ANGLE_JITTER_RADIANS).sin_cos();
|
||||
|
||||
FurLock {
|
||||
root: Vec2::new(0.5 + (hash(1) - 0.5) * ROOT_JITTER_CELLS, 0.5 + (hash(2) - 0.5) * ROOT_JITTER_CELLS),
|
||||
length: LENGTH_CELLS * (1.0 + (hash(4) * 2.0 - 1.0) * LENGTH_JITTER),
|
||||
angle_sin,
|
||||
angle_cos,
|
||||
curl: CURL_RADIANS * (0.8 + hash(5) * 0.4),
|
||||
strength: 0.8 + hash(6) * 0.2,
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -94,41 +87,67 @@ fn locks(seed: u32) -> std::rc::Rc<[Lock]> {
|
||||
/// map: buried at the root, round across, rising towards the tip. Where locks cross, the higher
|
||||
/// one shows. Roots sit on a jittered grid whose cells wrap.
|
||||
pub(crate) fn smooth_fur(p: Vec3, seed: u32) -> f32 {
|
||||
// In cells
|
||||
const WIDTH: f32 = 1.55;
|
||||
// No lock, root to tip and half a width aside, reaches further than this
|
||||
const REACH: f32 = 4.0;
|
||||
let q = unit(p) * FUR_CELLS as f32;
|
||||
let (ci, cj) = (q.x.floor() as i32, q.y.floor() as i32);
|
||||
let locks = locks(seed);
|
||||
let point = unit(p) * FUR_CELLS as f32;
|
||||
FUR_CACHE.with(|cache| {
|
||||
let Ok(mut cache) = cache.try_borrow_mut() else {
|
||||
return fur_height(point, &build_fur_locks(seed));
|
||||
};
|
||||
|
||||
let (replace_first, entries) = &mut *cache;
|
||||
if let Some((_, locks)) = entries.iter().flatten().find(|(cached_seed, _)| *cached_seed == seed) {
|
||||
return fur_height(point, locks);
|
||||
}
|
||||
|
||||
let [first, second] = entries;
|
||||
let replacement = if *replace_first { first } else { second };
|
||||
*replace_first = !*replace_first;
|
||||
let (_, locks) = replacement.insert((seed, build_fur_locks(seed)));
|
||||
fur_height(point, locks)
|
||||
})
|
||||
}
|
||||
|
||||
fn fur_height(point: Vec2, locks: &FurLocks) -> f32 {
|
||||
const WIDTH_CELLS: f32 = 1.55;
|
||||
const REACH_CELLS: f32 = 4.0;
|
||||
const EARLIER_ROWS: i32 = 5;
|
||||
const LATER_ROWS: i32 = 1;
|
||||
const COLUMNS_EACH_SIDE: i32 = 5;
|
||||
const TAPER_EXPONENT: f32 = 0.65;
|
||||
const ROOT_FADE: f32 = 0.06;
|
||||
const TIP_FADE: f32 = 0.025;
|
||||
const MIN_RADIUS_CELLS: f32 = 1e-6;
|
||||
let (column, row) = (point.x.floor() as i32, point.y.floor() as i32);
|
||||
|
||||
let mut height = 0.0f32;
|
||||
// Locks grow down the page and a little to either side, so their roots lie above and around
|
||||
for j in (cj - 5)..=(cj + 1) {
|
||||
for i in (ci - 5)..=(ci + 5) {
|
||||
let Some(lock) = locks.get((j.rem_euclid(FUR_CELLS) * FUR_CELLS + i.rem_euclid(FUR_CELLS)) as usize) else { continue };
|
||||
let d = q - (Vec2::new(i as f32, j as f32) + lock.root);
|
||||
if d.length_squared() > REACH * REACH {
|
||||
|
||||
// Locks grow down the page, so roots can reach farther from earlier rows
|
||||
for root_row in (row - EARLIER_ROWS)..=(row + LATER_ROWS) {
|
||||
let row_start = root_row.rem_euclid(FUR_CELLS as i32) as usize * FUR_CELLS;
|
||||
for root_column in (column - COLUMNS_EACH_SIDE)..=(column + COLUMNS_EACH_SIDE) {
|
||||
let index = row_start + root_column.rem_euclid(FUR_CELLS as i32) as usize;
|
||||
let Some(lock) = locks.get(index) else { continue };
|
||||
let delta = point - (Vec2::new(root_column as f32, root_row as f32) + lock.root);
|
||||
if delta.length_squared() > REACH_CELLS * REACH_CELLS {
|
||||
continue;
|
||||
}
|
||||
|
||||
// The point in the lock's own frame: growing along V, turned by its angle
|
||||
let local = Vec2::new(lock.cos * d.x + lock.sin * d.y, -lock.sin * d.x + lock.cos * d.y);
|
||||
// Behind the root or past the tip, whatever the curl
|
||||
if local.y < -WIDTH * 0.5 || local.y > lock.length {
|
||||
// Reject points beyond the root or tip before evaluating the curved axis
|
||||
let local = Vec2::new(lock.angle_cos * delta.x + lock.angle_sin * delta.y, -lock.angle_sin * delta.x + lock.angle_cos * delta.y);
|
||||
if local.y < -WIDTH_CELLS * 0.5 || local.y > lock.length {
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some((t, offset)) = on_arc(local, lock.length, lock.curl) else { continue };
|
||||
let radius = WIDTH * 0.5 * (1.0 - t).powf(0.65);
|
||||
if radius <= 1e-6 || offset.abs() >= radius {
|
||||
let Some((along, offset)) = on_arc(local, lock.length, lock.curl) else { continue };
|
||||
let radius = WIDTH_CELLS * 0.5 * (1.0 - along).powf(TAPER_EXPONENT);
|
||||
if radius <= MIN_RADIUS_CELLS || offset.abs() >= radius {
|
||||
continue;
|
||||
}
|
||||
|
||||
let q = offset.abs() / radius;
|
||||
let round = (1.0 - q * q).sqrt();
|
||||
let h = lock.strength * round * smoothstep(0.0, 1.0, t / 0.06) * smoothstep(0.0, 1.0, (1.0 - t) / 0.025) * (0.28 + 0.72 * t);
|
||||
height = height.max(h);
|
||||
let across = offset.abs() / radius;
|
||||
let profile = (1.0 - across * across).sqrt();
|
||||
let lock_height =
|
||||
lock.strength * profile * smoothstep(0.0, 1.0, along / ROOT_FADE) * smoothstep(0.0, 1.0, (1.0 - along) / TIP_FADE) * (0.28 + 0.72 * along);
|
||||
height = height.max(lock_height);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,61 +158,74 @@ pub(crate) fn smooth_fur(p: Vec3, seed: u32) -> f32 {
|
||||
/// `length`: the fraction of the length it is at and its distance from the axis, or None outside
|
||||
/// the lock's length.
|
||||
fn on_arc(local: Vec2, length: f32, curl: f32) -> Option<(f32, f32)> {
|
||||
if curl.abs() < 1e-4 {
|
||||
let t = local.y / length;
|
||||
return (0.0..=1.0).contains(&t).then_some((t, local.x));
|
||||
const STRAIGHT_CURL_RADIANS: f32 = 1e-4;
|
||||
if curl.abs() < STRAIGHT_CURL_RADIANS {
|
||||
let along = local.y / length;
|
||||
return (0.0..=1.0).contains(&along).then_some((along, local.x));
|
||||
}
|
||||
|
||||
// The axis is an arc of radius `length / curl` around a center beside the root
|
||||
let radius = length / curl;
|
||||
let t = (local.y / radius).atan2((radius - local.x) / radius) / curl;
|
||||
let along = (local.y / radius).atan2((radius - local.x) / radius) / curl;
|
||||
let distance = Vec2::new(local.x - radius, local.y).length();
|
||||
(0.0..=1.0).contains(&t).then_some((t, distance - radius.abs()))
|
||||
(0.0..=1.0).contains(&along).then_some((along, distance - radius.abs()))
|
||||
}
|
||||
|
||||
/// Soft round cloudlets of mixed sizes on a jittered grid, crowded so they overlap; the dark sky
|
||||
/// shows only where none reaches.
|
||||
pub(crate) fn mackerel_sky(p: Vec3, seed: u32) -> f32 {
|
||||
const CELLS: i32 = 6;
|
||||
const CLOUDLET_RADIUS_CELLS: f32 = 0.65;
|
||||
const RADIUS_VARIATION_CELLS: f32 = 0.45;
|
||||
const DOME_FEATHER_START: f32 = 0.2;
|
||||
const DOME_FEATHER_END: f32 = 1.2;
|
||||
|
||||
// A soft maximum, so cloudlets merge where they meet instead of leaving a seam
|
||||
const SOFTNESS: f32 = 14.0;
|
||||
let u = unit(p);
|
||||
let q = u * CELLS as f32;
|
||||
let (ci, cj) = (q.x.floor() as i32, q.y.floor() as i32);
|
||||
let uv = unit(p);
|
||||
let point = uv * CELLS as f32;
|
||||
let (column, row) = (point.x.floor() as i32, point.y.floor() as i32);
|
||||
|
||||
let mut sum = 0.0f32;
|
||||
for j in (cj - 2)..=(cj + 2) {
|
||||
for i in (ci - 2)..=(ci + 2) {
|
||||
let h = |k: i32| noise::cell_hash(i.rem_euclid(CELLS), j.rem_euclid(CELLS), k, seed ^ 0x5F);
|
||||
let center = Vec2::new(i as f32 + h(1), j as f32 + h(2));
|
||||
let t = (q - center).length() / (0.65 + 0.45 * h(3));
|
||||
if t >= 1.2 {
|
||||
for cloud_row in (row - 2)..=(row + 2) {
|
||||
for cloud_column in (column - 2)..=(column + 2) {
|
||||
let hash = |component| noise::cell_hash(cloud_column.rem_euclid(CELLS), cloud_row.rem_euclid(CELLS), component, seed ^ 0x5F);
|
||||
let center = Vec2::new(cloud_column as f32 + hash(1), cloud_row as f32 + hash(2));
|
||||
let radial_fraction = (point - center).length() / (CLOUDLET_RADIUS_CELLS + RADIUS_VARIATION_CELLS * hash(3));
|
||||
if radial_fraction >= DOME_FEATHER_END {
|
||||
continue;
|
||||
}
|
||||
|
||||
// A blurred dome: flat and bright in the middle, fading softly past its rim
|
||||
let dome = smoothstep(1.2, 0.2, t) * (0.85 + 0.15 * (1.0 - t * t).max(0.0).sqrt());
|
||||
sum += (SOFTNESS * dome * (0.6 + 0.4 * h(4))).exp() - 1.0;
|
||||
let dome =
|
||||
smoothstep(DOME_FEATHER_END, DOME_FEATHER_START, radial_fraction) * (0.85 + 0.15 * (1.0 - radial_fraction * radial_fraction).max(0.0).sqrt());
|
||||
sum += (SOFTNESS * dome * (0.6 + 0.4 * hash(4))).exp() - 1.0;
|
||||
}
|
||||
}
|
||||
let value = (1.0 + sum).ln() / SOFTNESS;
|
||||
|
||||
let mottle = lattice_fbm(u, &[(12, 0.5), (24, 0.3), (48, 0.2)], seed ^ 0x3A);
|
||||
let value = (1.0 + sum).ln() / SOFTNESS;
|
||||
let mottle = lattice_fbm(uv, &[(12, 0.5), (24, 0.3), (48, 0.2)], seed ^ 0x3A);
|
||||
(value * (0.88 + 0.12 * mottle)).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// Domain-warped clouds, crossed by fine strands that follow a slowly turning flow: high frequency
|
||||
/// noise averaged along the flow direction (a short line integral).
|
||||
pub(crate) fn billow(p: Vec3, seed: u32) -> f32 {
|
||||
let u = unit(p);
|
||||
let warp = |salt: u32| lattice_fbm(u, &[(2, 0.5), (4, 0.3), (8, 0.2)], seed ^ salt) - 0.5;
|
||||
let q = u + Vec2::new(warp(0x11), warp(0x22)) * 0.2;
|
||||
// Mottled at several scales, like a cloud seen up close
|
||||
let body = lattice_fbm(q, &[(3, 0.3), (6, 0.25), (12, 0.2), (24, 0.15), (48, 0.1)], seed);
|
||||
const WARP_AMPLITUDE: f32 = 0.2;
|
||||
const STRAND_HALF_SAMPLES: i32 = 5;
|
||||
const STRAND_SAMPLE_SPACING: f32 = 0.0045;
|
||||
let uv = unit(p);
|
||||
let warp = |salt: u32| lattice_fbm(uv, &[(2, 0.5), (4, 0.3), (8, 0.2)], seed ^ salt) - 0.5;
|
||||
let warped = uv + Vec2::new(warp(0x11), warp(0x22)) * WARP_AMPLITUDE;
|
||||
|
||||
let angle = std::f32::consts::TAU * lattice_fbm(q, &[(2, 0.6), (4, 0.4)], seed ^ 0x33);
|
||||
let body = lattice_fbm(warped, &[(3, 0.3), (6, 0.25), (12, 0.2), (24, 0.15), (48, 0.1)], seed);
|
||||
let angle = std::f32::consts::TAU * lattice_fbm(warped, &[(2, 0.6), (4, 0.4)], seed ^ 0x33);
|
||||
let flow = Vec2::new(angle.cos(), angle.sin());
|
||||
let strands = (-5..=5).map(|k| lattice_noise(q + flow * (k as f32 * 0.0045), (64, 64), seed ^ 0x44)).sum::<f32>() / 11.0;
|
||||
let speckle = lattice_noise(q, (32, 32), seed ^ 0x55);
|
||||
let strands = (-STRAND_HALF_SAMPLES..=STRAND_HALF_SAMPLES)
|
||||
.map(|sample| lattice_noise(warped + flow * (sample as f32 * STRAND_SAMPLE_SPACING), (64, 64), seed ^ 0x44))
|
||||
.sum::<f32>()
|
||||
/ (2 * STRAND_HALF_SAMPLES + 1) as f32;
|
||||
let speckle = lattice_noise(warped, (32, 32), seed ^ 0x55);
|
||||
|
||||
(0.5 + (body - 0.5) * 1.7 + (strands - 0.5) * 0.45 + (speckle - 0.5) * 0.1).clamp(0.0, 1.0)
|
||||
}
|
||||
@@ -202,52 +234,57 @@ pub(crate) fn billow(p: Vec3, seed: u32) -> f32 {
|
||||
/// own, domed and lit from above, with a dark rim and a shadow cast on the scale below. A scale
|
||||
/// covers the ones under it. The rows wrap, so the pattern repeats every unit.
|
||||
pub(crate) fn reptile_scales(p: Vec3, seed: u32) -> f32 {
|
||||
// The scales overlap, so every point is under one; a dark ground stands in if one is ever missed
|
||||
scale_at(p, seed).unwrap_or(0.1)
|
||||
const GROUND: f32 = 0.1;
|
||||
scale_at(p, seed).unwrap_or(GROUND)
|
||||
}
|
||||
|
||||
/// The value of the scale showing at `p`, or None when no scale covers it
|
||||
fn scale_at(p: Vec3, seed: u32) -> Option<f32> {
|
||||
const COLUMNS: i32 = 8;
|
||||
|
||||
// Even, so that the staggered rows line up again after one unit
|
||||
const ROWS: i32 = 12;
|
||||
let u = unit(p);
|
||||
let q = Vec2::new(u.x * COLUMNS as f32, u.y * ROWS as f32);
|
||||
let (ci, cj) = (q.x.floor() as i32, q.y.floor() as i32);
|
||||
const HALF_WIDTH_CELLS: f32 = 0.62;
|
||||
const HALF_HEIGHT_CELLS: f32 = 1.3;
|
||||
const SHADOW_REACH: f32 = 1.35;
|
||||
let uv = unit(p);
|
||||
let point = Vec2::new(uv.x * COLUMNS as f32, uv.y * ROWS as f32);
|
||||
let (column, row) = (point.x.floor() as i32, point.y.floor() as i32);
|
||||
let light = Vec3::new(-0.35, -0.5, 0.8).normalize();
|
||||
|
||||
// The scale showing here: the one whose center lies highest among those that reach the point
|
||||
// The earliest overlapping row sits above the others
|
||||
let (mut top, mut top_row, mut shadow) = (None, i32::MAX, 0.0f32);
|
||||
for j in (cj - 2)..=(cj + 2) {
|
||||
for i in (ci - 1)..=(ci + 2) {
|
||||
let h = |k: i32| noise::cell_hash(i.rem_euclid(COLUMNS), j.rem_euclid(ROWS), k, seed ^ 0x2B);
|
||||
let stagger = if j.rem_euclid(2) == 1 { 0.5 } else { 0.0 };
|
||||
let center = Vec2::new(i as f32 + 0.5 + stagger + (h(1) - 0.5) * 0.3, j as f32 + 0.5 + (h(2) - 0.5) * 0.4);
|
||||
let (half_width, half_height) = (0.62 * (0.92 + 0.16 * h(3)), 1.3 * (0.92 + 0.16 * h(4)));
|
||||
let d = q - center;
|
||||
for scale_row in (row - 2)..=(row + 2) {
|
||||
let stagger = if scale_row.rem_euclid(2) == 1 { 0.5 } else { 0.0 };
|
||||
for scale_column in (column - 1)..=(column + 2) {
|
||||
let hash = |component| noise::cell_hash(scale_column.rem_euclid(COLUMNS), scale_row.rem_euclid(ROWS), component, seed ^ 0x2B);
|
||||
let center = Vec2::new(scale_column as f32 + 0.5 + stagger + (hash(1) - 0.5) * 0.3, scale_row as f32 + 0.5 + (hash(2) - 0.5) * 0.4);
|
||||
let (half_width, half_height) = (HALF_WIDTH_CELLS * (0.92 + 0.16 * hash(3)), HALF_HEIGHT_CELLS * (0.92 + 0.16 * hash(4)));
|
||||
let delta = point - center;
|
||||
|
||||
// Narrower towards the lower tip
|
||||
let narrowing = 1.0 - 0.3 * (d.y / half_height).clamp(0.0, 1.0);
|
||||
let s = Vec2::new(d.x / (half_width * narrowing), d.y / half_height);
|
||||
let rim = s.length();
|
||||
let narrowing = 1.0 - 0.3 * (delta.y / half_height).clamp(0.0, 1.0);
|
||||
let local = Vec2::new(delta.x / (half_width * narrowing), delta.y / half_height);
|
||||
let rim = local.length();
|
||||
if rim < 1.0 {
|
||||
if j < top_row || (j == top_row && h(5) > 0.5) {
|
||||
top_row = j;
|
||||
top = Some((s, rim, h(6), h(7)));
|
||||
if scale_row < top_row || (scale_row == top_row && hash(5) > 0.5) {
|
||||
top_row = scale_row;
|
||||
top = Some((local, rim, hash(6), hash(7)));
|
||||
}
|
||||
} else if rim < 1.35 && d.y > 0.0 {
|
||||
// Under this scale's lower edge, where it throws a shadow
|
||||
shadow = shadow.max(smoothstep(1.35, 1.0, rim));
|
||||
} else if rim < SHADOW_REACH && delta.y > 0.0 {
|
||||
shadow = shadow.max(smoothstep(SHADOW_REACH, 1.0, rim));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let (s, rim, tone, ridge) = top?;
|
||||
let (local, rim, tone, ridge) = top?;
|
||||
let height = (1.0 - rim * rim).max(0.0).sqrt();
|
||||
// A keel down the middle, stronger on some scales
|
||||
let keel = (-(s.x * 3.2) * (s.x * 3.2)).exp() * (0.1 + 0.25 * ridge);
|
||||
let normal = Vec3::new(s.x * 0.9, s.y * 0.9, height + keel).normalize();
|
||||
|
||||
// The keel catches light along the middle of the scale
|
||||
let keel = (-(local.x * 3.2) * (local.x * 3.2)).exp() * (0.1 + 0.25 * ridge);
|
||||
let normal = Vec3::new(local.x * 0.9, local.y * 0.9, height + keel).normalize();
|
||||
let lit = normal.dot(light).max(0.0);
|
||||
let grain = lattice_noise(u, (96, 96), seed ^ 0x3C);
|
||||
let grain = lattice_noise(uv, (96, 96), seed ^ 0x3C);
|
||||
let body = (0.25 + 0.75 * tone) * (0.35 + 0.65 * lit) * (1.0 - 0.5 * shadow) * (0.86 + 0.14 * grain);
|
||||
Some((body * (0.45 + 0.55 * smoothstep(1.0, 0.8, rim))).clamp(0.0, 1.0))
|
||||
}
|
||||
@@ -257,82 +294,86 @@ fn scale_at(p: Vec3, seed: u32) -> Option<f32> {
|
||||
pub(crate) fn bark(p: Vec3, seed: u32) -> f32 {
|
||||
const COLUMNS: i32 = 7;
|
||||
const ROWS: i32 = 3;
|
||||
// How little a step along the trunk counts against one across it
|
||||
const STRETCH: f32 = 0.38;
|
||||
let u = unit(p);
|
||||
const TRUNK_AXIS_WEIGHT: f32 = 0.38;
|
||||
const PLATE_JITTER_CELLS: f32 = 0.85;
|
||||
const FURROW_FADE_END: f32 = 0.4;
|
||||
let uv = unit(p);
|
||||
|
||||
// The furrows wander
|
||||
let wobble = Vec2::new(lattice_noise(u, (5, 5), seed ^ 0x31), lattice_noise(u, (5, 5), seed ^ 0x32)) - Vec2::splat(0.5);
|
||||
let w = u + wobble * Vec2::new(0.06, 0.14);
|
||||
let wobble = Vec2::new(lattice_noise(uv, (5, 5), seed ^ 0x31), lattice_noise(uv, (5, 5), seed ^ 0x32)) - Vec2::splat(0.5);
|
||||
let warped = uv + wobble * Vec2::new(0.06, 0.14);
|
||||
|
||||
let q = Vec2::new(w.x * COLUMNS as f32, w.y * ROWS as f32);
|
||||
let (ci, cj) = (q.x.floor() as i32, q.y.floor() as i32);
|
||||
let (mut nearest, mut next, mut plate) = (f32::MAX, f32::MAX, 0.0f32);
|
||||
for j in (cj - 2)..=(cj + 2) {
|
||||
for i in (ci - 1)..=(ci + 1) {
|
||||
let h = |k: i32| noise::cell_hash(i.rem_euclid(COLUMNS), j.rem_euclid(ROWS), k, seed ^ 0x27);
|
||||
let center = Vec2::new(i as f32 + 0.5 + (h(1) - 0.5) * 0.85, j as f32 + 0.5 + (h(2) - 0.5) * 0.85);
|
||||
let d = q - center;
|
||||
let distance = Vec2::new(d.x / COLUMNS as f32, d.y / ROWS as f32 * STRETCH).length();
|
||||
let point = Vec2::new(warped.x * COLUMNS as f32, warped.y * ROWS as f32);
|
||||
let (column, row) = (point.x.floor() as i32, point.y.floor() as i32);
|
||||
let (mut nearest, mut next, mut plate_tone) = (f32::MAX, f32::MAX, 0.0f32);
|
||||
for plate_row in (row - 2)..=(row + 2) {
|
||||
for plate_column in (column - 1)..=(column + 1) {
|
||||
let hash = |component| noise::cell_hash(plate_column.rem_euclid(COLUMNS), plate_row.rem_euclid(ROWS), component, seed ^ 0x27);
|
||||
let center =
|
||||
Vec2::new(plate_column as f32 + 0.5 + (hash(1) - 0.5) * PLATE_JITTER_CELLS, plate_row as f32 + 0.5 + (hash(2) - 0.5) * PLATE_JITTER_CELLS);
|
||||
let delta = point - center;
|
||||
let distance = Vec2::new(delta.x / COLUMNS as f32, delta.y / ROWS as f32 * TRUNK_AXIS_WEIGHT).length();
|
||||
if distance < nearest {
|
||||
(next, nearest, plate) = (nearest, distance, h(3));
|
||||
(next, nearest, plate_tone) = (nearest, distance, hash(3));
|
||||
} else if distance < next {
|
||||
next = distance;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Distance to the nearest furrow, in plate widths
|
||||
// The furrow is where the two nearest plates meet
|
||||
let to_furrow = (next - nearest) * COLUMNS as f32;
|
||||
let ridge = smoothstep(0.0, 0.4, to_furrow).sqrt();
|
||||
let fibre = lattice_noise(w, (96, 6), seed ^ 0x52);
|
||||
(ridge * (0.5 + 0.3 * plate + 0.2 * fibre)).clamp(0.0, 1.0)
|
||||
let ridge = smoothstep(0.0, FURROW_FADE_END, to_furrow).sqrt();
|
||||
let fibre = lattice_noise(warped, (96, 6), seed ^ 0x52);
|
||||
(ridge * (0.5 + 0.3 * plate_tone + 0.2 * fibre)).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// Rotting flesh: soft masses of wet tissue, folded and creased, threaded with branching raised
|
||||
/// veins, going dark and mottled in patches of decay where blisters rise. The coordinates are
|
||||
/// warped hard, so nothing is round or straight, and no part of it is built on cells. Higher is
|
||||
/// moister, healthier tissue.
|
||||
/// warped so folds and veins meander. Higher values represent moister, healthier tissue.
|
||||
pub(crate) fn flesh(p: Vec3, seed: u32) -> f32 {
|
||||
const BLISTERS: i32 = 14;
|
||||
let u = unit(p);
|
||||
const BLISTER_CELLS: i32 = 14;
|
||||
const WARP_AMPLITUDE: f32 = 0.24;
|
||||
const DECAY_START: f32 = 0.46;
|
||||
const DECAY_FULL: f32 = 0.58;
|
||||
const BLISTER_CHANCE: f32 = 0.55;
|
||||
let uv = unit(p);
|
||||
let warp = |salt: u32| lattice_fbm(uv, &[(2, 0.5), (4, 0.3), (8, 0.2)], seed ^ salt) - 0.5;
|
||||
let warped = uv + Vec2::new(warp(0x11), warp(0x22)) * WARP_AMPLITUDE;
|
||||
|
||||
// The warp that makes the folds meander
|
||||
let warp = |salt: u32| lattice_fbm(u, &[(2, 0.5), (4, 0.3), (8, 0.2)], seed ^ salt) - 0.5;
|
||||
let w = u + Vec2::new(warp(0x11), warp(0x22)) * 0.24;
|
||||
|
||||
// A lumpy body, folded where a slow noise crosses its middle value
|
||||
let body = lattice_fbm(w, &[(3, 0.35), (6, 0.3), (12, 0.2), (24, 0.15)], seed ^ 0x33);
|
||||
let fold = lattice_fbm(w, &[(5, 0.6), (10, 0.4)], seed ^ 0x44);
|
||||
// Center the creases at the midpoint of the fold noise
|
||||
let body = lattice_fbm(warped, &[(3, 0.35), (6, 0.3), (12, 0.2), (24, 0.15)], seed ^ 0x33);
|
||||
let fold = lattice_fbm(warped, &[(5, 0.6), (10, 0.4)], seed ^ 0x44);
|
||||
let crease = (1.0 - (2.0 * fold - 1.0).abs()).powi(4);
|
||||
|
||||
// Veins that branch: a thick set and, across it, a thinner one
|
||||
// Two vein widths meet to give the appearance of branches
|
||||
let line = |cells: (i32, i32), salt: u32, sharpness: i32| {
|
||||
(1.0 - (2.0 * lattice_fbm(w, &[(cells.0, 0.6), (cells.1, 0.4)], seed ^ salt) - 1.0).abs()).powi(sharpness)
|
||||
(1.0 - (2.0 * lattice_fbm(warped, &[(cells.0, 0.6), (cells.1, 0.4)], seed ^ salt) - 1.0).abs()).powi(sharpness)
|
||||
};
|
||||
let vein = line((3, 7), 0x55, 14).max(0.7 * line((6, 13), 0x56, 20));
|
||||
let healthy = (0.2 + 0.7 * smoothstep(0.2, 0.8, body)) * (1.0 - 0.7 * crease) + 0.3 * vein;
|
||||
|
||||
// Decay: dark mottled patches
|
||||
let decay = smoothstep(0.46, 0.58, lattice_fbm(w, &[(2, 0.5), (5, 0.3), (10, 0.2)], seed ^ 0x66));
|
||||
let mottle = lattice_fbm(w, &[(24, 0.5), (48, 0.5)], seed ^ 0x77);
|
||||
// Mottle and blisters contribute only where the decay layer is visible
|
||||
let decay = smoothstep(DECAY_START, DECAY_FULL, lattice_fbm(warped, &[(2, 0.5), (5, 0.3), (10, 0.2)], seed ^ 0x66));
|
||||
if decay == 0.0 {
|
||||
return healthy.clamp(0.0, 1.0);
|
||||
}
|
||||
|
||||
// Blisters in the decayed patches: round bumps on a jittered grid that wraps
|
||||
let q = w * BLISTERS as f32;
|
||||
let (ci, cj) = (q.x.floor() as i32, q.y.floor() as i32);
|
||||
let mottle = lattice_fbm(warped, &[(24, 0.5), (48, 0.5)], seed ^ 0x77);
|
||||
let point = warped * BLISTER_CELLS as f32;
|
||||
let (column, row) = (point.x.floor() as i32, point.y.floor() as i32);
|
||||
let mut blister = 0.0f32;
|
||||
for j in (cj - 1)..=(cj + 1) {
|
||||
for i in (ci - 1)..=(ci + 1) {
|
||||
let h = |k: i32| noise::cell_hash(i.rem_euclid(BLISTERS), j.rem_euclid(BLISTERS), k, seed ^ 0x88);
|
||||
if h(0) > 0.55 {
|
||||
for blister_row in (row - 1)..=(row + 1) {
|
||||
for blister_column in (column - 1)..=(column + 1) {
|
||||
let hash = |component| noise::cell_hash(blister_column.rem_euclid(BLISTER_CELLS), blister_row.rem_euclid(BLISTER_CELLS), component, seed ^ 0x88);
|
||||
if hash(0) > BLISTER_CHANCE {
|
||||
continue;
|
||||
}
|
||||
|
||||
let center = Vec2::new(i as f32 + h(1), j as f32 + h(2));
|
||||
blister = blister.max(smoothstep(1.0, 0.0, (q - center).length() / (0.3 + 0.4 * h(3))));
|
||||
let center = Vec2::new(blister_column as f32 + hash(1), blister_row as f32 + hash(2));
|
||||
blister = blister.max(smoothstep(1.0, 0.0, (point - center).length() / (0.3 + 0.4 * hash(3))));
|
||||
}
|
||||
}
|
||||
|
||||
let healthy = (0.2 + 0.7 * smoothstep(0.2, 0.8, body)) * (1.0 - 0.7 * crease) + 0.3 * vein;
|
||||
let rotten = healthy * (0.3 + 0.4 * mottle) + 0.35 * blister;
|
||||
(healthy + (rotten - healthy) * decay).clamp(0.0, 1.0)
|
||||
}
|
||||
@@ -342,18 +383,23 @@ pub(crate) fn flesh(p: Vec3, seed: u32) -> f32 {
|
||||
/// across the surface. Every tone is flat, so a gradient map turns it into woodland, desert or
|
||||
/// any other colours.
|
||||
pub(crate) fn camouflage(p: Vec3, seed: u32) -> f32 {
|
||||
let u = unit(p);
|
||||
const EDGE_FEATHER: f32 = 0.012;
|
||||
const EDGE_WOBBLE: f32 = 0.14;
|
||||
const GROUND: f32 = 0.05;
|
||||
let uv = unit(p);
|
||||
|
||||
// Fractal noise on a lattice stretched across the surface
|
||||
let blotches = |cells: (i32, i32), salt: u32| {
|
||||
0.55 * lattice_noise(u, cells, seed ^ salt)
|
||||
+ 0.3 * lattice_noise(u, (cells.0 * 2, cells.1 * 2), seed ^ salt ^ 0x9E)
|
||||
+ 0.15 * lattice_noise(u, (cells.0 * 4, cells.1 * 4), seed ^ salt ^ 0x3F)
|
||||
0.55 * lattice_noise(uv, cells, seed ^ salt)
|
||||
+ 0.3 * lattice_noise(uv, (cells.0 * 2, cells.1 * 2), seed ^ salt ^ 0x9E)
|
||||
+ 0.15 * lattice_noise(uv, (cells.0 * 4, cells.1 * 4), seed ^ salt ^ 0x3F)
|
||||
};
|
||||
// The same ragged edge for every tone
|
||||
let ragged = (lattice_fbm(u, &[(24, 0.6), (48, 0.4)], seed ^ 0x71) - 0.5) * 0.14;
|
||||
|
||||
let layer = |field: f32, threshold: f32| smoothstep(threshold - 0.012, threshold + 0.012, field + ragged);
|
||||
let mut value = 0.05;
|
||||
// The same ragged edge for every tone
|
||||
let ragged = (lattice_fbm(uv, &[(24, 0.6), (48, 0.4)], seed ^ 0x71) - 0.5) * EDGE_WOBBLE;
|
||||
|
||||
let layer = |field: f32, threshold: f32| smoothstep(threshold - EDGE_FEATHER, threshold + EDGE_FEATHER, field + ragged);
|
||||
let mut value = GROUND;
|
||||
for (tone, field, threshold) in [(0.35, blotches((3, 2), 0x11), 0.46), (0.65, blotches((4, 3), 0x22), 0.54), (0.95, blotches((6, 4), 0x33), 0.6)] {
|
||||
value += (tone - value) * layer(field, threshold);
|
||||
}
|
||||
@@ -365,8 +411,8 @@ pub(crate) fn camouflage(p: Vec3, seed: u32) -> f32 {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
type Pattern = fn(Vec3, u32) -> f32;
|
||||
const PATTERNS: [(&str, Pattern); 13] = [
|
||||
type PatternSampler = fn(Vec3, u32) -> f32;
|
||||
const PATTERNS: [(&str, PatternSampler); 13] = [
|
||||
("fur", smooth_fur),
|
||||
("sky", mackerel_sky),
|
||||
("billow", billow),
|
||||
@@ -398,6 +444,7 @@ mod tests {
|
||||
let value = pattern(p, seed);
|
||||
for shift in [Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), Vec3::new(-3.0, 5.0, 0.0)] {
|
||||
let shifted = pattern(p + shift, seed);
|
||||
|
||||
assert!((value - shifted).abs() < 1e-3, "{name} at {p:?} (seed {seed}), shifted by {shift:?}: {value} against {shifted}");
|
||||
}
|
||||
}
|
||||
@@ -415,6 +462,7 @@ mod tests {
|
||||
assert!((0.0..=1.0).contains(&v), "{name} at {p:?}: {v}");
|
||||
(lo, hi) = (lo.min(v), hi.max(v));
|
||||
}
|
||||
|
||||
assert!(hi - lo > 0.4, "{name} is flat: {lo}..{hi}");
|
||||
}
|
||||
}
|
||||
@@ -423,6 +471,7 @@ mod tests {
|
||||
fn the_seed_changes_every_pattern() {
|
||||
for (name, pattern) in PATTERNS {
|
||||
let differs = points().any(|p| (pattern(p, 1) - pattern(p, 2)).abs() > 0.02);
|
||||
|
||||
assert!(differs, "{name} ignores its seed");
|
||||
}
|
||||
}
|
||||
@@ -443,13 +492,16 @@ mod tests {
|
||||
#[test]
|
||||
fn scales_leave_no_gap_and_bark_makes_furrows() {
|
||||
let grid = |size: usize| (0..size * size).map(move |i| Vec3::new((i % size) as f32 / size as f32, (i / size) as f32 / size as f32, 0.0));
|
||||
// A scale covers every point: a point none reaches would read as a gap, however dark the scales are
|
||||
|
||||
// Check actual coverage because a scale can be as dark as the background
|
||||
for seed in 1..=3 {
|
||||
let uncovered = grid(64).filter(|p| scale_at(*p, seed).is_none()).count();
|
||||
|
||||
assert_eq!(uncovered, 0, "{uncovered} of 4096 points are under no scale (seed {seed})");
|
||||
}
|
||||
|
||||
let furrows = grid(64).filter(|p| bark(*p, 1) < 0.1).count();
|
||||
|
||||
assert!((100..1800).contains(&furrows), "furrows cover {furrows} of 4096 samples");
|
||||
}
|
||||
|
||||
@@ -457,7 +509,7 @@ mod tests {
|
||||
fn flesh_has_creases_veins_and_decay() {
|
||||
let values: Vec<f32> = (0..16384).map(|i| flesh(Vec3::new((i % 128) as f32 / 128.0, (i / 128) as f32 / 128.0, 0.0), 1)).collect();
|
||||
let share = |keep: fn(f32) -> bool| values.iter().filter(|v| keep(**v)).count() as f32 / values.len() as f32;
|
||||
// Dark creases and rot, and bright healthy tissue, each over a fair part of the surface
|
||||
|
||||
assert!(share(|v| v < 0.18) > 0.08, "no creases or rot: {}", share(|v| v < 0.18));
|
||||
assert!(share(|v| v > 0.5) > 0.08, "no healthy tissue: {}", share(|v| v > 0.5));
|
||||
}
|
||||
@@ -466,9 +518,9 @@ mod tests {
|
||||
fn the_edges_of_the_unit_are_no_rougher_than_the_middle_of_it() {
|
||||
const STEP: f32 = 1e-4;
|
||||
const SAMPLES: usize = 512;
|
||||
// How many points along a line change by a lot between two points just either side of `at`
|
||||
// (the edge of the unit when `at` is 0, whose other side is the far edge)
|
||||
let jumps = |pattern: Pattern, at: f32, across_u: bool| {
|
||||
|
||||
// Count abrupt changes on either side of the sampled line
|
||||
let jumps = |pattern: PatternSampler, at: f32, across_u: bool| {
|
||||
(0..SAMPLES)
|
||||
.filter(|i| {
|
||||
let t = (*i as f32 + 0.5) / SAMPLES as f32;
|
||||
@@ -479,10 +531,12 @@ mod tests {
|
||||
})
|
||||
.count()
|
||||
};
|
||||
|
||||
for (name, pattern) in PATTERNS {
|
||||
for (edge, across_u) in [("U", true), ("V", false)] {
|
||||
// A pattern on a lattice has cell edges at 0 and at 1/2 alike, which rise and fall at random; a seam would be an extra one
|
||||
// Compare against an interior line to allow normal lattice transitions
|
||||
let (seam, middle) = (jumps(pattern, 0.0, across_u), jumps(pattern, 0.5, across_u));
|
||||
|
||||
assert!(seam <= 3 * middle + SAMPLES / 10, "{name}: {seam} jumps across the {edge} edge of the unit, against {middle} across its middle");
|
||||
}
|
||||
}
|
||||
@@ -493,12 +547,12 @@ mod tests {
|
||||
let mut counts = [0usize; 4];
|
||||
for i in 0..16384 {
|
||||
let v = camouflage(Vec3::new((i % 128) as f32 / 128.0, (i / 128) as f32 / 128.0, 0.0), 1);
|
||||
// The nearest of the four tones
|
||||
let tone = [0.05, 0.35, 0.65, 0.95].iter().enumerate().min_by(|a, b| (a.1 - v).abs().total_cmp(&(b.1 - v).abs())).map_or(0, |(k, _)| k);
|
||||
let tone = [0.05, 0.35, 0.65, 0.95].iter().enumerate().min_by(|a, b| (a.1 - v).abs().total_cmp(&(b.1 - v).abs())).map_or(0, |(index, _)| index);
|
||||
if let Some(count) = counts.get_mut(tone) {
|
||||
*count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
for (tone, count) in counts.iter().enumerate() {
|
||||
assert!(*count > 16384 / 25, "tone {tone} covers only {count} of 16384 samples: {counts:?}");
|
||||
}
|
||||
|
||||
+144
-150
@@ -5,7 +5,11 @@ use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_texel::noise;
|
||||
|
||||
use crate::pattern_context::PatternContext;
|
||||
use crate::{fabric, organic, timber};
|
||||
use crate::{
|
||||
fabric,
|
||||
organic::{self, lattice_fbm, smoothstep, unit},
|
||||
timber,
|
||||
};
|
||||
|
||||
/// Smaller pattern scales are read as this: a pattern stretched over ten thousand repeats of its projection
|
||||
const MIN_PATTERN_SCALE: f32 = 1e-4;
|
||||
@@ -175,22 +179,28 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 {
|
||||
/// and two rows of tiles, a little taller than regular hexagons so that the pattern, tones
|
||||
/// included, repeats every unit.
|
||||
fn hexagon_tiles(p: Vec3, seed: u32) -> f32 {
|
||||
let p = within_unit(p);
|
||||
const ROW: f32 = 1.732_050_8;
|
||||
// Regular hexagons of width 1 in (u, v), centers on two lattices offset by half a repeat
|
||||
let q = Vec2::new(p.x * 2.0, p.y * ROW);
|
||||
let repeat = Vec2::new(1.0, ROW);
|
||||
let wrap = |q: Vec2| q - repeat * (q / repeat).round();
|
||||
let (a, b) = (wrap(q), wrap(q - repeat * 0.5));
|
||||
let local = if a.length_squared() < b.length_squared() { a } else { b };
|
||||
const VERTICAL_REPEAT: f32 = 1.732_050_8;
|
||||
const SIN_60: f32 = 0.866_025_4;
|
||||
const APOTHEM: f32 = 0.5;
|
||||
const JOINT_WIDTH: f32 = 0.012;
|
||||
const JOINT_FADE_END: f32 = 0.045;
|
||||
let uv = unit(p);
|
||||
|
||||
// Distance to the nearest edge: the apothem is 0.5 and the edge normals sit at 0, 60 and 120 degrees
|
||||
let reach = local.x.abs().max((local.x * 0.5 + local.y * 0.866_025_4).abs()).max((local.x * 0.5 - local.y * 0.866_025_4).abs());
|
||||
let joint = smoothstep(0.012, 0.045, 0.5 - reach);
|
||||
// Regular hexagons of width 1 have centers on two lattices half a repeat apart
|
||||
let point = Vec2::new(uv.x * 2.0, uv.y * VERTICAL_REPEAT);
|
||||
let repeat = Vec2::new(1.0, VERTICAL_REPEAT);
|
||||
let wrap = |point: Vec2| point - repeat * (point / repeat).round();
|
||||
let first = wrap(point);
|
||||
let second = wrap(point - repeat * 0.5);
|
||||
let local = if first.length_squared() < second.length_squared() { first } else { second };
|
||||
|
||||
// Project onto the edge normals at 0, 60 and 120 degrees
|
||||
let reach = local.x.abs().max((local.x * 0.5 + local.y * SIN_60).abs()).max((local.x * 0.5 - local.y * SIN_60).abs());
|
||||
let joint = smoothstep(JOINT_WIDTH, JOINT_FADE_END, APOTHEM - reach);
|
||||
|
||||
// Tile centers sit on a half-repeat grid: four columns and two rows of them per unit
|
||||
let center = q - local;
|
||||
let (column, row) = ((center.x * 2.0).round() as i32, (center.y / ROW * 2.0).round() as i32);
|
||||
let center = point - local;
|
||||
let (column, row) = ((center.x * 2.0).round() as i32, (center.y / VERTICAL_REPEAT * 2.0).round() as i32);
|
||||
let tone = noise::cell_hash(column.rem_euclid(4), row.rem_euclid(2), 0, seed);
|
||||
joint * (0.8 + 0.2 * tone)
|
||||
}
|
||||
@@ -199,22 +209,27 @@ fn hexagon_tiles(p: Vec3, seed: u32) -> f32 {
|
||||
/// V grows downwards in texture space, so the row with the largest V covers the others and each
|
||||
/// circle shows its top arcs. Repeats every unit.
|
||||
fn wave_scales(p: Vec3) -> f32 {
|
||||
let p = within_unit(p);
|
||||
let row = (p.y * 4.0).floor() as i32;
|
||||
// Rows from the last one back: the first circle that reaches the point is the one on top
|
||||
for j in ((row - 2)..=(row + 2)).rev() {
|
||||
let dy = p.y - j as f32 * 0.25;
|
||||
if dy.abs() > 0.5 {
|
||||
const ROW_SPACING: f32 = 0.25;
|
||||
const CIRCLE_RADIUS: f32 = 0.5;
|
||||
const NEIGHBOR_ROWS: i32 = 2;
|
||||
const ARC_COUNT: f32 = 3.5;
|
||||
const RIM_START: f32 = 0.9;
|
||||
let uv = unit(p);
|
||||
let row = (uv.y / ROW_SPACING).floor() as i32;
|
||||
|
||||
// Search from the topmost overlapping row so its circle wins
|
||||
for circle_row in ((row - NEIGHBOR_ROWS)..=(row + NEIGHBOR_ROWS)).rev() {
|
||||
let dy = uv.y - circle_row as f32 * ROW_SPACING;
|
||||
if dy.abs() > CIRCLE_RADIUS {
|
||||
continue;
|
||||
}
|
||||
|
||||
let shift = if j.rem_euclid(2) == 1 { 0.5 } else { 0.0 };
|
||||
let dx = p.x - ((p.x - shift).round() + shift);
|
||||
let t = (dx * dx + dy * dy).sqrt() / 0.5;
|
||||
if t <= 1.0 {
|
||||
// Concentric arcs, brighter towards the middle, with a dark rim where the next circle begins
|
||||
let arcs = 0.5 + 0.5 * (std::f32::consts::TAU * 3.5 * t).cos();
|
||||
let rim = 1.0 - 0.7 * smoothstep(0.9, 1.0, t);
|
||||
let shift = if circle_row.rem_euclid(2) == 1 { 0.5 } else { 0.0 };
|
||||
let dx = uv.x - ((uv.x - shift).round() + shift);
|
||||
let radial_fraction = (dx * dx + dy * dy).sqrt() / CIRCLE_RADIUS;
|
||||
if radial_fraction <= 1.0 {
|
||||
let arcs = 0.5 + 0.5 * (std::f32::consts::TAU * ARC_COUNT * radial_fraction).cos();
|
||||
let rim = 1.0 - 0.7 * smoothstep(RIM_START, 1.0, radial_fraction);
|
||||
return ((0.3 + 0.7 * arcs) * rim).clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
@@ -226,27 +241,28 @@ fn wave_scales(p: Vec3) -> f32 {
|
||||
/// grain of its own. Six plank widths make a repeat, so the pattern, tones included, repeats
|
||||
/// every unit.
|
||||
fn herringbone_planks(p: Vec3, seed: u32) -> f32 {
|
||||
let p = within_unit(p);
|
||||
const LENGTH: i32 = 3;
|
||||
const CELLS: i32 = 2 * LENGTH;
|
||||
let (x, y) = (p.x * CELLS as f32, p.y * CELLS as f32);
|
||||
let (i, j) = (x.floor() as i32, y.floor() as i32);
|
||||
let (fx, fy) = (x - i as f32, y - j as f32);
|
||||
const LENGTH_IN_WIDTHS: i32 = 3;
|
||||
const CELLS: i32 = 2 * LENGTH_IN_WIDTHS;
|
||||
const GAP_WIDTH: f32 = 0.015;
|
||||
const GAP_FADE_END: f32 = 0.06;
|
||||
let position = unit(p) * CELLS as f32;
|
||||
let (column, row) = (position.x.floor() as i32, position.y.floor() as i32);
|
||||
let local = position - Vec2::new(column as f32, row as f32);
|
||||
|
||||
// Along the diagonal the planks alternate: LENGTH cells of horizontal plank, then LENGTH of vertical
|
||||
let phase = (i - j).rem_euclid(CELLS);
|
||||
let (along, across, plank) = if phase < LENGTH {
|
||||
(phase as f32 + fx, fy, (i - phase, j, 0))
|
||||
// Alternate a full horizontal plank and a full vertical plank along the diagonal
|
||||
let phase = (column - row).rem_euclid(CELLS);
|
||||
let (along, across, origin_column, origin_row, orientation) = if phase < LENGTH_IN_WIDTHS {
|
||||
(phase as f32 + local.x, local.y, column - phase, row, 0)
|
||||
} else {
|
||||
let step = CELLS - 1 - phase;
|
||||
(step as f32 + fy, fx, (i, j - step, 1))
|
||||
(step as f32 + local.y, local.x, column, row - step, 1)
|
||||
};
|
||||
let along = along / LENGTH as f32;
|
||||
let along = along / LENGTH_IN_WIDTHS as f32;
|
||||
|
||||
// Distance to the plank's border, in plank widths
|
||||
let edge = across.min(1.0 - across).min(along.min(1.0 - along) * LENGTH as f32);
|
||||
let body = smoothstep(0.015, 0.06, edge);
|
||||
let tone = noise::cell_hash(plank.0.rem_euclid(CELLS), plank.1.rem_euclid(CELLS), plank.2, seed);
|
||||
let edge = across.min(1.0 - across).min(along.min(1.0 - along) * LENGTH_IN_WIDTHS as f32);
|
||||
let body = smoothstep(GAP_WIDTH, GAP_FADE_END, edge);
|
||||
let tone = noise::cell_hash(origin_column.rem_euclid(CELLS), origin_row.rem_euclid(CELLS), orientation, seed);
|
||||
let grain = noise::value([along * 3.0, across * 28.0, tone * 31.0], seed ^ 0x7B);
|
||||
body * (0.55 + 0.25 * tone + 0.2 * grain)
|
||||
}
|
||||
@@ -255,86 +271,62 @@ fn herringbone_planks(p: Vec3, seed: u32) -> f32 {
|
||||
/// by a cloudy tone. Each dot keeps the tone at its center and the tone repeats every unit, so the
|
||||
/// pattern does too.
|
||||
fn halftone_dots(p: Vec3, seed: u32) -> f32 {
|
||||
// Even, so that the turned grid lines up again after one unit
|
||||
const DOTS: f32 = 16.0;
|
||||
let p = within_unit(p);
|
||||
let q = Vec2::new(p.x, p.y) * DOTS;
|
||||
// An even grid makes both axes repeat after one unit
|
||||
const GRID_SCALE: f32 = 16.0;
|
||||
const MIN_RADIUS: f32 = 0.12;
|
||||
const RADIUS_VARIATION: f32 = 0.6;
|
||||
const EDGE_FEATHER: f32 = 0.05;
|
||||
const TONE_OCTAVES: [(i32, f32); 3] = [(3, 0.55), (6, 0.3), (12, 0.15)];
|
||||
let point = unit(p) * GRID_SCALE;
|
||||
|
||||
// In (u, v) the turned grid is the integer grid; its points are √2 apart in q. The point lies
|
||||
// in the square of four of them, and the dot that covers it most shows: there is no edge
|
||||
// where the choice of dot jumps, so dots that meet stay continuous
|
||||
const SMALLEST: f32 = 0.12;
|
||||
const GROWTH: f32 = 0.6;
|
||||
const EDGE: f32 = 0.05;
|
||||
let (u, v) = ((q.x + q.y) * 0.5, (q.x - q.y) * 0.5);
|
||||
// Max coverage from the four surrounding centers keeps overlapping dots continuous
|
||||
let cell = Vec2::new((point.x + point.y) * 0.5, (point.x - point.y) * 0.5).floor();
|
||||
let mut coverage = 0.0f32;
|
||||
for (du, dv) in [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)] {
|
||||
let (cu, cv) = (u.floor() + du, v.floor() + dv);
|
||||
let center = Vec2::new(cu + cv, cu - cv);
|
||||
let distance = (q - center).length();
|
||||
// Skips the tone, the costly part, where even the largest dot would not reach
|
||||
if distance >= SMALLEST + GROWTH + EDGE {
|
||||
for offset in [Vec2::ZERO, Vec2::X, Vec2::Y, Vec2::ONE] {
|
||||
let corner = cell + offset;
|
||||
let center = Vec2::new(corner.x + corner.y, corner.x - corner.y);
|
||||
let distance = (point - center).length();
|
||||
|
||||
// Skip tone sampling where even the largest dot cannot reach
|
||||
if distance >= MIN_RADIUS + RADIUS_VARIATION + EDGE_FEATHER {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Stretched, as a sum of octaves gathers around the middle
|
||||
let tone = smoothstep(0.25, 0.75, periodic_fbm(center / DOTS, seed));
|
||||
let radius = SMALLEST + GROWTH * tone;
|
||||
coverage = coverage.max(1.0 - smoothstep(radius - EDGE, radius + EDGE, distance));
|
||||
// Stretch the noise because weighted octaves cluster around the middle
|
||||
let tone = smoothstep(0.25, 0.75, lattice_fbm(center / GRID_SCALE, &TONE_OCTAVES, seed));
|
||||
let radius = MIN_RADIUS + RADIUS_VARIATION * tone;
|
||||
coverage = coverage.max(1.0 - smoothstep(radius - EDGE_FEATHER, radius + EDGE_FEATHER, distance));
|
||||
}
|
||||
|
||||
coverage
|
||||
}
|
||||
|
||||
/// `p` moved by whole units into the unit square, for patterns that repeat every unit: their
|
||||
/// integer cell indices then stay small, and a large coordinate keeps its precision. A coordinate
|
||||
/// that is not finite becomes 0
|
||||
fn within_unit(p: Vec3) -> Vec3 {
|
||||
let wrap = |x: f32| if x.is_finite() { x.rem_euclid(1.0) } else { 0.0 };
|
||||
Vec3::new(wrap(p.x), wrap(p.y), p.z)
|
||||
}
|
||||
|
||||
/// Smooth value noise in 0..1 on a lattice of `cells` × `cells` per unit, whose indices wrap, so
|
||||
/// the noise repeats every unit
|
||||
fn periodic_value_noise(at: Vec2, cells: i32, seed: u32) -> f32 {
|
||||
let q = at * cells as f32;
|
||||
let (i, j) = (q.x.floor() as i32, q.y.floor() as i32);
|
||||
let f = q - Vec2::new(i as f32, j as f32);
|
||||
let s = f * f * (Vec2::splat(3.0) - 2.0 * f);
|
||||
let corner = |di: i32, dj: i32| noise::cell_hash((i + di).rem_euclid(cells), (j + dj).rem_euclid(cells), 0, seed);
|
||||
let top = corner(0, 0) + (corner(1, 0) - corner(0, 0)) * s.x;
|
||||
let bottom = corner(0, 1) + (corner(1, 1) - corner(0, 1)) * s.x;
|
||||
top + (bottom - top) * s.y
|
||||
}
|
||||
|
||||
/// Fractal value noise in 0..1 that repeats every unit: octaves of [`periodic_value_noise`] with
|
||||
/// a whole number of cells per unit each
|
||||
fn periodic_fbm(at: Vec2, seed: u32) -> f32 {
|
||||
const OCTAVES: [(i32, f32); 3] = [(3, 0.55), (6, 0.3), (12, 0.15)];
|
||||
OCTAVES.iter().enumerate().map(|(k, (cells, weight))| weight * periodic_value_noise(at, *cells, seed ^ (k as u32 * 0x9E37))).sum()
|
||||
}
|
||||
|
||||
/// Raised diamonds on a twill ground, four by four per unit. Each diamond is a set of concentric
|
||||
/// rings with a dark border; the ground shows fine diagonal ribs. Repeats every unit.
|
||||
fn diamond_brocade(p: Vec3) -> f32 {
|
||||
use std::f32::consts::{PI, TAU};
|
||||
|
||||
const DIAMONDS: f32 = 4.0;
|
||||
let p = within_unit(p);
|
||||
let q = Vec2::new(p.x, p.y) * DIAMONDS;
|
||||
let local = q - q.floor() - Vec2::splat(0.5);
|
||||
// 0 at a diamond's center, 0.5 at its corners' edge
|
||||
let d = local.x.abs() + local.y.abs();
|
||||
const RIBS_PER_UNIT: f32 = 40.0;
|
||||
const MOTIF_RADIUS: f32 = 0.46;
|
||||
const MOTIF_FEATHER: f32 = 0.03;
|
||||
const MOTIF_RING_COUNT: f32 = 2.5;
|
||||
let point = unit(p) * DIAMONDS;
|
||||
let local = point - point.floor() - Vec2::splat(0.5);
|
||||
let diamond_distance = local.x.abs() + local.y.abs();
|
||||
|
||||
// The twill ground: fine diagonal ribs, a whole number of them per unit
|
||||
let ribs = 0.5 + 0.5 * (TAU * 40.0 * (q.x + q.y) / DIAMONDS).sin();
|
||||
// The twill has a whole number of diagonal ribs per unit
|
||||
let ribs = 0.5 + 0.5 * (TAU * RIBS_PER_UNIT * (point.x + point.y) / DIAMONDS).sin();
|
||||
let ground = 0.22 + 0.12 * ribs;
|
||||
|
||||
// The motif, rising towards the middle in rings, nearly filling its cell
|
||||
const MOTIF: f32 = 0.46;
|
||||
let inside = 1.0 - smoothstep(MOTIF - 0.03, MOTIF, d);
|
||||
let rings = 0.5 + 0.5 * (TAU * 2.5 * d / MOTIF).cos();
|
||||
let rise = (PI * 0.5 * (1.0 - d / MOTIF)).sin().max(0.0);
|
||||
// Only the twill ground is visible beyond the motif
|
||||
if diamond_distance >= MOTIF_RADIUS {
|
||||
return ground;
|
||||
}
|
||||
|
||||
let inside = 1.0 - smoothstep(MOTIF_RADIUS - MOTIF_FEATHER, MOTIF_RADIUS, diamond_distance);
|
||||
let rings = 0.5 + 0.5 * (TAU * MOTIF_RING_COUNT * diamond_distance / MOTIF_RADIUS).cos();
|
||||
let rise = (PI * 0.5 * (1.0 - diamond_distance / MOTIF_RADIUS)).sin().max(0.0);
|
||||
let motif = (0.45 + 0.35 * rise + 0.2 * rings) * (0.9 + 0.1 * ribs);
|
||||
(ground + (motif - ground) * inside).clamp(0.0, 1.0)
|
||||
}
|
||||
@@ -344,21 +336,18 @@ fn diamond_brocade(p: Vec3) -> f32 {
|
||||
/// cells into winding round tubes. The choice comes from the cell's index wrapped to the grid,
|
||||
/// so the pattern repeats every unit.
|
||||
fn truchet_arcs(p: Vec3, seed: u32) -> f32 {
|
||||
let p = within_unit(p);
|
||||
const CELLS: i32 = 8;
|
||||
const TUBE: f32 = 0.13;
|
||||
let q = Vec2::new(p.x, p.y) * CELLS as f32;
|
||||
let (i, j) = (q.x.floor() as i32, q.y.floor() as i32);
|
||||
let local = q - Vec2::new(i as f32, j as f32);
|
||||
const TUBE_RADIUS: f32 = 0.13;
|
||||
let point = unit(p) * CELLS as f32;
|
||||
let (column, row) = (point.x.floor() as i32, point.y.floor() as i32);
|
||||
let local = point - Vec2::new(column as f32, row as f32);
|
||||
|
||||
// Around the top-left and bottom-right corners, or the top-right and bottom-left ones
|
||||
let flipped = noise::cell_hash(i.rem_euclid(CELLS), j.rem_euclid(CELLS), 0, seed) > 0.5;
|
||||
let flipped = noise::cell_hash(column.rem_euclid(CELLS), row.rem_euclid(CELLS), 0, seed) > 0.5;
|
||||
let corners = if flipped { [Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0)] } else { [Vec2::ZERO, Vec2::ONE] };
|
||||
let offset = corners.iter().map(|corner| ((local - *corner).length() - 0.5).abs()).fold(f32::MAX, f32::min);
|
||||
|
||||
// A round tube across, over a dark ground
|
||||
let s = (offset / TUBE).min(1.0);
|
||||
0.05 + 0.9 * (1.0 - s * s).sqrt()
|
||||
let across = (offset / TUBE_RADIUS).min(1.0);
|
||||
0.05 + 0.9 * (1.0 - across * across).sqrt()
|
||||
}
|
||||
|
||||
/// `values` raised to a triplanar `sharpness` (at least 1): whole sharpnesses up to 16 (the usual
|
||||
@@ -400,14 +389,9 @@ fn triplanar_weights(nrm: Vec3, sharpness: f32, gain: f32) -> Vec3 {
|
||||
if retained == Vec3::ZERO { weights } else { retained }
|
||||
}
|
||||
|
||||
fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 {
|
||||
let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0);
|
||||
t * t * (3.0 - 2.0 * t)
|
||||
}
|
||||
|
||||
fn shape(pr: &Procedural, v: f32) -> f32 {
|
||||
let v = ((v - 0.5) * pr.contrast.max(0.0) + 0.5 + pr.balance).clamp(0.0, 1.0);
|
||||
if pr.invert { 1.0 - v } else { v }
|
||||
fn shape(pattern: &Procedural, value: f32) -> f32 {
|
||||
let adjusted = ((value - 0.5) * pattern.contrast.max(0.0) + 0.5 + pattern.balance).clamp(0.0, 1.0);
|
||||
if pattern.invert { 1.0 - adjusted } else { adjusted }
|
||||
}
|
||||
|
||||
/// Evaluate a procedural through a projection, at full resolution and without images
|
||||
@@ -484,7 +468,8 @@ fn plane_value(pattern: &Procedural, point: Vec3, context: &PatternContext) -> f
|
||||
let Some(cells) = cells else { return pattern_value(pattern, point, context) };
|
||||
|
||||
let grid = point.truncate() * cells - 0.5;
|
||||
// A point so far out that the grid overflows has no neighbours to blend: read it exactly
|
||||
|
||||
// Non-finite grid coordinates cannot identify bilinear neighbors
|
||||
if !grid.is_finite() {
|
||||
return pattern_value(pattern, point, context);
|
||||
}
|
||||
@@ -659,7 +644,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn every_pattern_and_projection_stays_in_range() {
|
||||
let projs = [
|
||||
let projections = [
|
||||
Projection::default(),
|
||||
Projection::Triplanar { scale: 1.0, sharpness: 4.0, offset: [0.0; 3] },
|
||||
Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3] },
|
||||
@@ -677,18 +662,21 @@ mod tests {
|
||||
flip: [false; 2],
|
||||
}),
|
||||
];
|
||||
for k in ProceduralKind::ALL {
|
||||
let pr = Procedural::new(k);
|
||||
for proj in &projs {
|
||||
|
||||
for kind in ProceduralKind::ALL {
|
||||
let pattern = Procedural::new(kind);
|
||||
for projection in &projections {
|
||||
for i in 0..50 {
|
||||
let t = i as f32 * 0.13;
|
||||
let c = Coords {
|
||||
let coords = Coords {
|
||||
uv: Vec2::new(t.fract(), (t * 0.7).fract()),
|
||||
pos: Vec3::new(t.sin(), t.cos(), t * 0.1),
|
||||
nrm: Vec3::new(0.3, 0.9, 0.1).normalize(),
|
||||
};
|
||||
let v = procedural(&pr, proj, &c);
|
||||
assert!((0.0..=1.0).contains(&v), "{k:?} {proj:?} {v}");
|
||||
|
||||
let value = procedural(&pattern, projection, &coords);
|
||||
|
||||
assert!((0.0..=1.0).contains(&value), "{kind:?} {projection:?} {value}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -846,8 +834,6 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn geometric_tilings_repeat_every_unit() {
|
||||
// Shifted points round differently, which shows on the steep edges of a joint, so a seam
|
||||
// is anything above that rounding
|
||||
let tilings = [
|
||||
ProceduralKind::HexagonTiles,
|
||||
ProceduralKind::WaveScales,
|
||||
@@ -856,11 +842,14 @@ mod tests {
|
||||
ProceduralKind::DiamondBrocade,
|
||||
ProceduralKind::TruchetArcs,
|
||||
];
|
||||
|
||||
for kind in tilings {
|
||||
for i in 0..400 {
|
||||
let p = Vec3::new((i as f32 * 0.137).fract() * 3.0 - 1.0, (i as f32 * 0.071).fract() * 3.0 - 1.0, 0.0);
|
||||
for index in 0..400 {
|
||||
let p = Vec3::new((index as f32 * 0.137).fract() * 3.0 - 1.0, (index as f32 * 0.071).fract() * 3.0 - 1.0, 0.0);
|
||||
for shift in [Vec3::X, Vec3::Y, Vec3::new(-2.0, 3.0, 0.0)] {
|
||||
let (here, there) = (raw(kind, p, 7), raw(kind, p + shift, 7));
|
||||
|
||||
// Allow coordinate rounding on steep joint edges
|
||||
assert!((here - there).abs() < 2e-3, "{kind:?}: {here} at {p}, {there} at {}", p + shift);
|
||||
}
|
||||
}
|
||||
@@ -868,17 +857,19 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pattern_read_from_a_coarse_image_takes_extreme_coordinates() {
|
||||
let coarse = PatternContext { pixels: Some(4), ..PatternContext::default() };
|
||||
fn a_non_finite_coarse_grid_falls_back_to_exact_sampling() {
|
||||
let coarse = PatternContext { pixels: Some(16), ..PatternContext::default() };
|
||||
let exact = PatternContext::default();
|
||||
let extremes = [f32::MAX, -f32::MAX, f32::INFINITY, f32::NEG_INFINITY, f32::NAN];
|
||||
|
||||
for kind in ProceduralKind::ALL {
|
||||
let pattern = Procedural::new(kind);
|
||||
for x in [f32::MAX, -f32::MAX, f32::INFINITY, f32::NEG_INFINITY] {
|
||||
let point = Vec3::new(x, 0.125, 0.0);
|
||||
// Whatever a pattern does with such a point exactly, the blend must not make it worse
|
||||
if pattern_value(&pattern, point, &exact).is_finite() {
|
||||
let value = plane_value(&pattern, point, &coarse);
|
||||
assert!(value.is_finite(), "{kind:?} at x = {x}: {value}");
|
||||
for extreme in extremes {
|
||||
for point in [Vec3::new(extreme, 0.125, 0.0), Vec3::new(0.125, extreme, 0.0)] {
|
||||
let expected = plane_value(&pattern, point, &exact);
|
||||
let actual = plane_value(&pattern, point, &coarse);
|
||||
|
||||
assert!(actual == expected || (actual.is_nan() && expected.is_nan()), "{kind:?} at {point}: {actual} instead of {expected}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -895,6 +886,7 @@ mod tests {
|
||||
ProceduralKind::TruchetArcs,
|
||||
];
|
||||
let extremes = [0.0, 5.4e8, -5.4e8, f32::MAX, -f32::MAX, f32::INFINITY, f32::NAN];
|
||||
|
||||
for kind in tilings {
|
||||
for x in extremes {
|
||||
for y in extremes {
|
||||
@@ -909,11 +901,12 @@ mod tests {
|
||||
fn halftone_dots_stay_continuous_where_neighbouring_dots_meet() {
|
||||
// Halfway between two dot centers lie the points 1/32 apart on the turned grid
|
||||
for seed in 0..32 {
|
||||
for k in 0..64 {
|
||||
let tie = Vec3::new(k as f32 / 32.0, (k * 7 % 32) as f32 / 32.0, 0.0);
|
||||
for index in 0..64 {
|
||||
let tie = Vec3::new(index as f32 / 32.0, (index * 7 % 32) as f32 / 32.0, 0.0);
|
||||
for step in [Vec3::X, Vec3::Y] {
|
||||
let (before, after) =
|
||||
(raw(ProceduralKind::HalftoneDots, tie - step * 1e-4, seed), raw(ProceduralKind::HalftoneDots, tie + step * 1e-4, seed));
|
||||
|
||||
assert!((before - after).abs() < 0.05, "seed {seed}, {tie}: {before} then {after}");
|
||||
}
|
||||
}
|
||||
@@ -928,22 +921,23 @@ mod tests {
|
||||
assert!(at(ProceduralKind::HexagonTiles, 0.0, 0.0) >= 0.8);
|
||||
assert!(at(ProceduralKind::HexagonTiles, 0.25, 0.0) < 0.05);
|
||||
|
||||
// A unit is six plank widths: a horizontal plank starts at the origin, its middle is a plank and a half to the right
|
||||
// Check the end and midpoint of the horizontal plank starting at the origin
|
||||
assert!(at(ProceduralKind::HerringbonePlanks, 0.000_2, 0.5 / 6.0) < 0.05);
|
||||
assert!(at(ProceduralKind::HerringbonePlanks, 1.5 / 6.0, 0.5 / 6.0) >= 0.55);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_pattern_varies() {
|
||||
for k in ProceduralKind::ALL {
|
||||
let pr = Procedural::new(k);
|
||||
let (mut lo, mut hi) = (f32::MAX, f32::MIN);
|
||||
for kind in ProceduralKind::ALL {
|
||||
let pattern = Procedural::new(kind);
|
||||
let (mut minimum, mut maximum) = (f32::MAX, f32::MIN);
|
||||
for i in 0..4096 {
|
||||
let uv = Vec2::new((i % 64) as f32 / 64.0, (i / 64) as f32 / 64.0);
|
||||
let v = procedural(&pr, &Projection::default(), &Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Y });
|
||||
(lo, hi) = (lo.min(v), hi.max(v));
|
||||
let value = procedural(&pattern, &Projection::default(), &Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Y });
|
||||
(minimum, maximum) = (minimum.min(value), maximum.max(value));
|
||||
}
|
||||
assert!(hi - lo > 0.3, "{k:?} is flat: {lo}..{hi}");
|
||||
|
||||
assert!(maximum - minimum > 0.3, "{kind:?} is flat: {minimum}..{maximum}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,32 +11,34 @@ use crate::organic::{lattice_fbm, lattice_noise, smoothstep, unit};
|
||||
/// are staggered from row to row (0 = gap). Every piece has a tone and growth rings of its own.
|
||||
pub(crate) fn strip_flooring(p: Vec3, seed: u32) -> f32 {
|
||||
const ROWS: i32 = 6;
|
||||
// Pieces along a row, per unit
|
||||
const PIECES: f32 = 2.0;
|
||||
let u = unit(p);
|
||||
let y = u.y * ROWS as f32;
|
||||
const PIECES_PER_ROW: i32 = 2;
|
||||
const GAP_WIDTH: f32 = 0.0012;
|
||||
const GAP_FADE_END: f32 = 0.0035;
|
||||
let uv = unit(p);
|
||||
let y = uv.y * ROWS as f32;
|
||||
let row = y.floor() as i32;
|
||||
let fy = y - row as f32;
|
||||
let across = y - row as f32;
|
||||
|
||||
// Each row starts its pieces somewhere else
|
||||
let row_hash = |k: i32| noise::cell_hash(row.rem_euclid(ROWS), k, 0, seed ^ 0x13);
|
||||
let x = (u.x + row_hash(0)) * PIECES;
|
||||
// Shift the joints independently in each row
|
||||
let wrapped_row = row.rem_euclid(ROWS);
|
||||
let row_offset = noise::cell_hash(wrapped_row, 0, 0, seed ^ 0x13);
|
||||
let x = (uv.x + row_offset) * PIECES_PER_ROW as f32;
|
||||
let piece = x.floor() as i32;
|
||||
let fx = x - piece as f32;
|
||||
let h = |k: i32| noise::cell_hash(row.rem_euclid(ROWS), piece.rem_euclid(PIECES as i32), k + 1, seed ^ 0x13);
|
||||
let along = x - piece as f32;
|
||||
let hash = |component: i32| noise::cell_hash(wrapped_row, piece.rem_euclid(PIECES_PER_ROW), component + 1, seed ^ 0x13);
|
||||
|
||||
// Distances to the board's edge and to the butt joint, in units
|
||||
let to_edge = fy.min(1.0 - fy) / ROWS as f32;
|
||||
let to_joint = fx.min(1.0 - fx) / PIECES;
|
||||
let gap = smoothstep(0.0012, 0.0035, to_edge.min(to_joint));
|
||||
let to_edge = across.min(1.0 - across) / ROWS as f32;
|
||||
let to_joint = along.min(1.0 - along) / PIECES_PER_ROW as f32;
|
||||
let gap = smoothstep(GAP_WIDTH, GAP_FADE_END, to_edge.min(to_joint));
|
||||
|
||||
// Growth rings seen on the face of the board: long cathedrals that wander along the piece
|
||||
let warp = lattice_fbm(u, &[(3, 0.6), (7, 0.4)], seed ^ 0x24) - 0.5;
|
||||
let rings = fy * (1.6 + 1.2 * h(0)) + h(1) * 7.0 + warp * 2.2;
|
||||
// Noise bends the growth rings into long arcs on the face of the board
|
||||
let warp = lattice_fbm(uv, &[(3, 0.6), (7, 0.4)], seed ^ 0x24) - 0.5;
|
||||
let rings = across * (1.6 + 1.2 * hash(0)) + hash(1) * 7.0 + warp * 2.2;
|
||||
let ring = 0.5 + 0.5 * (std::f32::consts::TAU * rings).cos();
|
||||
let fibre = lattice_noise(u, (12, 240), seed ^ 0x35);
|
||||
let fibre = lattice_noise(uv, (12, 240), seed ^ 0x35);
|
||||
|
||||
let tone = 0.42 + 0.4 * h(2);
|
||||
let tone = 0.42 + 0.4 * hash(2);
|
||||
(gap * tone * (0.68 + 0.32 * ring.powf(1.4)) * (0.86 + 0.14 * fibre)).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
@@ -45,42 +47,50 @@ pub(crate) fn strip_flooring(p: Vec3, seed: u32) -> f32 {
|
||||
pub(crate) fn knotty_wood(p: Vec3, seed: u32) -> f32 {
|
||||
const RINGS: f32 = 9.0;
|
||||
const CELLS: i32 = 3;
|
||||
const KNOT_REACH_RADII: f32 = 2.2;
|
||||
const KNOT_FULL_BLEND_RADII: f32 = 0.8;
|
||||
let u = unit(p);
|
||||
|
||||
// Rings across the board, wandering a little
|
||||
let wander = (lattice_fbm(u, &[(2, 0.6), (5, 0.4)], seed ^ 0x14) - 0.5) * 1.4;
|
||||
let base = u.y * RINGS + wander;
|
||||
let mut t = base;
|
||||
let q = u * CELLS as f32;
|
||||
let (ci, cj) = (q.x.floor() as i32, q.y.floor() as i32);
|
||||
let mut phase = u.y * RINGS + wander;
|
||||
let point = u * CELLS as f32;
|
||||
let (column, row) = (point.x.floor() as i32, point.y.floor() as i32);
|
||||
|
||||
let mut core = 0.0f32;
|
||||
for j in (cj - 1)..=(cj + 1) {
|
||||
for i in (ci - 1)..=(ci + 1) {
|
||||
let h = |k: i32| noise::cell_hash(i.rem_euclid(CELLS), j.rem_euclid(CELLS), k, seed ^ 0x47);
|
||||
// Not every cell has a knot
|
||||
if h(0) > 0.45 {
|
||||
let mut ring_noise = None;
|
||||
for knot_row in (row - 1)..=(row + 1) {
|
||||
let wrapped_row = knot_row.rem_euclid(CELLS);
|
||||
for knot_column in (column - 1)..=(column + 1) {
|
||||
let wrapped_column = knot_column.rem_euclid(CELLS);
|
||||
let hash = |component| noise::cell_hash(wrapped_column, wrapped_row, component, seed ^ 0x47);
|
||||
if hash(0) > 0.45 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let center = Vec2::new(i as f32 + 0.2 + 0.6 * h(1), j as f32 + 0.2 + 0.6 * h(2)) / CELLS as f32;
|
||||
let radius = 0.04 + 0.035 * h(3);
|
||||
let center_jitter = Vec2::new(hash(1), hash(2)) * 0.6;
|
||||
let center = Vec2::new(knot_column as f32 + 0.2, knot_row as f32 + 0.2) + center_jitter;
|
||||
let radius = 0.04 + 0.035 * hash(3);
|
||||
|
||||
// Knots are longer along the grain
|
||||
let d = u - center;
|
||||
let distance = Vec2::new(d.x * 0.5, d.y).length() / radius;
|
||||
// The rings turn into circles around the knot; further out they only bend
|
||||
let circle = distance * 1.9 + h(4) * 3.0 + (lattice_noise(u, (24, 24), seed ^ 0x66) - 0.5) * 0.8;
|
||||
// The ring a knot pulls towards is measured from where the knot sits in its own copy of
|
||||
// the unit: a knot just past the bottom edge shapes the rings along the top edge, and
|
||||
// those must come out as the rings along the bottom edge do
|
||||
let home_y = (j.rem_euclid(CELLS) as f32 + 0.2 + 0.6 * h(2)) / CELLS as f32;
|
||||
let ring_here = (home_y + d.y) * RINGS + wander;
|
||||
t += (circle - ring_here) * smoothstep(2.2, 0.8, distance);
|
||||
let delta = u - center / CELLS as f32;
|
||||
let distance = Vec2::new(delta.x * 0.5, delta.y).length() / radius;
|
||||
if distance >= KNOT_REACH_RADII {
|
||||
continue;
|
||||
}
|
||||
|
||||
let noise = *ring_noise.get_or_insert_with(|| (lattice_noise(u, (24, 24), seed ^ 0x66) - 0.5) * 0.8);
|
||||
let circle = distance * 1.9 + hash(4) * 3.0 + noise;
|
||||
|
||||
// Measure the phase in the knot's own repeat to preserve continuity across wrap
|
||||
let home_y = (wrapped_row as f32 + 0.2 + center_jitter.y) / CELLS as f32;
|
||||
let ring_here = (home_y + delta.y) * RINGS + wander;
|
||||
phase += (circle - ring_here) * smoothstep(KNOT_REACH_RADII, KNOT_FULL_BLEND_RADII, distance);
|
||||
core = core.max(smoothstep(0.5, 0.2, distance));
|
||||
}
|
||||
}
|
||||
|
||||
let ring = (0.5 + 0.5 * (std::f32::consts::TAU * t).cos()).powf(1.6);
|
||||
let ring = (0.5 + 0.5 * (std::f32::consts::TAU * phase).cos()).powf(1.6);
|
||||
let fibre = lattice_noise(u, (10, 260), seed ^ 0x58);
|
||||
let base = 0.34 + 0.5 * ring;
|
||||
(base * (0.86 + 0.14 * fibre) * (1.0 - 0.8 * core)).clamp(0.0, 1.0)
|
||||
@@ -94,10 +104,12 @@ mod tests {
|
||||
fn flooring_has_gaps_between_boards_and_pieces() {
|
||||
let grid = |size: usize| (0..size * size).map(move |i| Vec3::new((i % size) as f32 / size as f32, (i / size) as f32 / size as f32, 0.0));
|
||||
let gaps = grid(256).filter(|p| strip_flooring(*p, 1) < 0.02).count();
|
||||
|
||||
assert!((300..6000).contains(&gaps), "gaps cover {gaps} of 65536 samples");
|
||||
|
||||
// The joints of neighbouring rows do not line up
|
||||
let joints = |y: f32| (0..400).filter(|i| strip_flooring(Vec3::new(*i as f32 / 400.0, y, 0.0), 1) < 0.02).map(|i| i / 4).collect::<Vec<_>>();
|
||||
|
||||
assert_ne!(joints(0.5 / 6.0), joints(1.5 / 6.0), "the rows share their joints");
|
||||
}
|
||||
|
||||
@@ -105,6 +117,7 @@ mod tests {
|
||||
fn knotty_wood_has_dark_knots() {
|
||||
let grid = |size: usize| (0..size * size).map(move |i| Vec3::new((i % size) as f32 / size as f32, (i / size) as f32 / size as f32, 0.0));
|
||||
let dark = grid(128).filter(|p| knotty_wood(*p, 1) < 0.12).count();
|
||||
|
||||
assert!(dark > 10, "only {dark} samples are knot-dark");
|
||||
}
|
||||
}
|
||||
@@ -378,6 +378,7 @@ impl ProceduralKind {
|
||||
ProceduralKind::KnottyWood,
|
||||
ProceduralKind::TileGenerator,
|
||||
];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
ProceduralKind::Clouds => "Clouds",
|
||||
@@ -425,9 +426,12 @@ impl ProceduralKind {
|
||||
ProceduralKind::TileGenerator => "Tile Generator",
|
||||
}
|
||||
}
|
||||
pub fn parse(s: &str) -> Option<ProceduralKind> {
|
||||
let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-'], "");
|
||||
ProceduralKind::ALL.into_iter().find(|k| norm(k.label()) == norm(s) || norm(&format!("{k:?}")) == norm(s))
|
||||
|
||||
pub fn parse(name: &str) -> Option<ProceduralKind> {
|
||||
let normalize = |text: &str| text.to_ascii_lowercase().replace([' ', '_', '-'], "");
|
||||
let name = normalize(name);
|
||||
|
||||
ProceduralKind::ALL.into_iter().find(|kind| normalize(kind.label()) == name || normalize(&format!("{kind:?}")) == name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1596,11 +1600,20 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn generator_kinds_parse() {
|
||||
for k in GeneratorKind::ALL {
|
||||
assert_eq!(GeneratorKind::parse(&format!("{k:?}")), Some(k));
|
||||
for kind in GeneratorKind::ALL {
|
||||
assert_eq!(GeneratorKind::parse(&format!("{kind:?}")), Some(kind));
|
||||
}
|
||||
for k in ProceduralKind::ALL {
|
||||
assert_eq!(ProceduralKind::parse(k.label()), Some(k));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn procedural_kinds_parse_labels_and_saved_names() {
|
||||
for kind in ProceduralKind::ALL {
|
||||
let saved_name = format!("{kind:?}");
|
||||
|
||||
assert_eq!(ProceduralKind::parse(kind.label()), Some(kind));
|
||||
assert_eq!(ProceduralKind::parse(&saved_name), Some(kind));
|
||||
assert_eq!(serde_json::to_value(kind).unwrap(), serde_json::Value::String(saved_name));
|
||||
assert_eq!(serde_json::from_value::<ProceduralKind>(serde_json::to_value(kind).unwrap()).unwrap(), kind);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
//! Files: projects (`.tcraft`), mesh import, texture export. Byte-based functions work on the
|
||||
//! web; path-based commands are native only.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use texturecraft_core::{NormalFormat, PROJECT_EXT};
|
||||
@@ -19,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New project from a mesh file",
|
||||
[],
|
||||
None,
|
||||
"{mesh: path to .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl, resolution?: 2048, name?, uvTiles?: bool (UDIM; default: when the UVs leave tile 1001), template?: project template name}",
|
||||
"{mesh: path to .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl, resolution?: 2048, name?, uvTiles?: bool (UDIM; default: when the UVs leave tile 1001), template?: project template name, importCameras?: bool (default true: keep the cameras stored in the file)}",
|
||||
always,
|
||||
new_from_mesh
|
||||
),
|
||||
@@ -156,20 +158,31 @@ impl Session {
|
||||
|
||||
/// [`Session::from_mesh_bytes`] with a UV tile mode (see [`Session::new_project_tiled`]).
|
||||
pub fn from_mesh_bytes_tiled(file_name: &str, bytes: &[u8], resolution: u32, name: &str, uv_tiles: Option<bool>) -> Result<Session> {
|
||||
let imported = texturecraft_formats::import_mesh_bytes(file_name, bytes).map_err(fe)?;
|
||||
let ext = ext_of(file_name);
|
||||
let mut s = Session::new_project_tiled(name, imported.mesh, &format!("mesh.{ext}"), Some((ext, bytes.to_vec())), resolution, uv_tiles)?;
|
||||
s.doc.project.mesh_file = leaf_of(file_name);
|
||||
s.doc.project.cameras = imported.cameras;
|
||||
s.log.extend(imported.report.warnings.iter().cloned());
|
||||
s.log.push(format!(
|
||||
Self::from_mesh_source(file_name, Cow::Borrowed(bytes), resolution, name, uv_tiles)
|
||||
}
|
||||
|
||||
fn from_mesh_source(file_name: &str, bytes: Cow<'_, [u8]>, resolution: u32, name: &str, uv_tiles: Option<bool>) -> Result<Session> {
|
||||
let imported = texturecraft_formats::import_mesh_bytes(file_name, &bytes).map_err(fe)?;
|
||||
let extension = ext_of(file_name);
|
||||
let mut session = Session::new_project_tiled(name, imported.mesh, &format!("mesh.{extension}"), None, resolution, uv_tiles)?;
|
||||
|
||||
// Packed mesh files can have spare capacity that the project would otherwise retain
|
||||
let mut source = bytes.into_owned();
|
||||
source.shrink_to_fit();
|
||||
session.mesh_source = Some((extension, source));
|
||||
session.doc.project.mesh_file = leaf_of(file_name);
|
||||
session.doc.project.cameras = imported.cameras;
|
||||
|
||||
session.log.extend(imported.report.warnings);
|
||||
session.log.push(format!(
|
||||
"Imported {} ({} triangles, {} materials{})",
|
||||
file_name,
|
||||
imported.report.triangles,
|
||||
imported.report.materials,
|
||||
if imported.report.uvs_generated { ", UVs generated" } else { "" }
|
||||
));
|
||||
Ok(s)
|
||||
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
/// Open a `.tcraft` project from bytes.
|
||||
@@ -405,23 +418,32 @@ mod native {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use native::{absolute, open_path, read_mesh};
|
||||
|
||||
/// `file.new {mesh, name?, resolution?, uvTiles?, template?}`: a new project from the mesh file `mesh`,
|
||||
/// remembering its path for Reimport mesh.
|
||||
/// `file.new {mesh, name?, resolution?, uvTiles?, template?, importCameras?}`: a new project from the
|
||||
/// mesh file `mesh`, remembering its path for Reimport mesh.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn new_from_mesh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = native::path_param(p, "mesh", "file.new")?;
|
||||
let f = native::read_mesh("file.new", path)?;
|
||||
let template = crate::template_cmds::template_param(s, p, "file.new")?;
|
||||
let res = u64p(p, "resolution").or(template.as_ref().map(|t| u64::from(t.resolution))).unwrap_or(2048);
|
||||
let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| stem_of(path));
|
||||
let mut next = Session::from_mesh_bytes_tiled(&f.name, &f.bytes, u32::try_from(res).unwrap_or(0), &name, crate::commands::boolp(p, "uvTiles"))?;
|
||||
fn new_from_mesh(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const DEFAULT_RESOLUTION_PX: u64 = 2048;
|
||||
|
||||
let path = native::path_param(params, "mesh", "file.new")?;
|
||||
let template = crate::template_cmds::template_param(session, params, "file.new")?;
|
||||
let resolution = u64p(params, "resolution").or(template.as_ref().map(|template| u64::from(template.resolution))).unwrap_or(DEFAULT_RESOLUTION_PX);
|
||||
let name = strp(params, "name").map(str::to_string).unwrap_or_else(|| stem_of(path));
|
||||
let uv_tiles = crate::commands::boolp(params, "uvTiles");
|
||||
let mesh_file = native::read_mesh("file.new", path)?;
|
||||
|
||||
let mut next = Session::from_mesh_source(&mesh_file.name, Cow::Owned(mesh_file.bytes), u32::try_from(resolution).unwrap_or(0), &name, uv_tiles)?;
|
||||
next.doc.project.mesh_path = native::absolute(path);
|
||||
next.log.extend(f.warnings);
|
||||
if let Some(t) = &template {
|
||||
next.apply_template(t);
|
||||
next.log.extend(mesh_file.warnings);
|
||||
if crate::commands::boolp(params, "importCameras") == Some(false) {
|
||||
next.doc.project.cameras.clear();
|
||||
}
|
||||
s.switch_to(next);
|
||||
Ok(crate::inspect::session(s))
|
||||
if let Some(template) = &template {
|
||||
next.apply_template(template);
|
||||
}
|
||||
|
||||
session.switch_to(next);
|
||||
|
||||
Ok(crate::inspect::session(session))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -693,6 +715,35 @@ fn close(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `file.new` keeps the cameras stored in the mesh file unless `importCameras` is false.
|
||||
#[test]
|
||||
fn new_from_mesh_imports_cameras_unless_told_not_to() {
|
||||
let dir = std::env::temp_dir().join(format!("tc_new_cameras_{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("shot.gltf");
|
||||
let gltf = json!({
|
||||
"asset": {"version": "2.0"},
|
||||
"buffers": [{"byteLength": 36, "uri": "data:application/octet-stream;base64,AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAA"}],
|
||||
"bufferViews": [{"buffer": 0, "byteLength": 36}],
|
||||
"accessors": [{"bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3", "min": [0, 0, 0], "max": [1, 1, 0]}],
|
||||
"meshes": [{"primitives": [{"attributes": {"POSITION": 0}}]}],
|
||||
"cameras": [{"name": "Shot", "type": "perspective", "perspective": {"yfov": 0.8, "znear": 0.1}}],
|
||||
"nodes": [{"mesh": 0}, {"camera": 0, "translation": [0.5, 0.5, 4.0]}],
|
||||
"scenes": [{"nodes": [0, 1]}],
|
||||
"scene": 0
|
||||
});
|
||||
std::fs::write(&file, serde_json::to_vec(&gltf).unwrap()).unwrap();
|
||||
let path = file.display().to_string();
|
||||
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
|
||||
crate::execute(&mut s, "file.new", &json!({"mesh": path, "resolution": 128})).unwrap();
|
||||
assert_eq!(s.doc.project.cameras.len(), 1, "the file's camera comes along by default");
|
||||
|
||||
crate::execute(&mut s, "file.new", &json!({"mesh": path, "resolution": 128, "importCameras": false})).unwrap();
|
||||
assert!(s.doc.project.cameras.is_empty(), "importCameras false leaves the cameras out");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Reimport mesh reads the mesh file again from where it was imported, so a change saved to
|
||||
/// the file since shows up (it used to re-read the project's own copy and change nothing).
|
||||
#[test]
|
||||
|
||||
@@ -6,13 +6,22 @@ use std::sync::Arc;
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_compose::ImageRes;
|
||||
use texturecraft_core::{Channel, Fill, Layer, LayerKind, Source};
|
||||
use texturecraft_formats::{MAX_RESOURCE_NAME_LEN, sanitize_resource_name};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, channel_param, strp};
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("resource.import", "Import resources", ["File"], None, "{path} — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr)", always, import),
|
||||
cmd!(
|
||||
"resource.import",
|
||||
"Import resources",
|
||||
["File"],
|
||||
None,
|
||||
"{path — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr), prefix?: put in front of the resource name (anything outside A-Z a-z 0-9 _ . - becomes _)}",
|
||||
always,
|
||||
import
|
||||
),
|
||||
cmd!("resource.list", "List resources", [], None, "{}", always, |s, _| Ok(list(s))),
|
||||
cmd!("resource.remove", "Remove resource", [], None, "{name}", always, remove),
|
||||
cmd!("file.removeUnused", "Remove unused resources...", ["File"], None, "{}", always, remove_unused),
|
||||
@@ -38,22 +47,48 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc<ImageRes> {
|
||||
impl Session {
|
||||
/// Add an image resource from bytes (one undo step); returns its unique, sanitized name
|
||||
pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec<u8>) -> Result<String> {
|
||||
self.edit("Import resource", |session| session.add_image_resource(file_name, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS))
|
||||
self.import_resource_bytes_prefixed("", file_name, bytes)
|
||||
}
|
||||
|
||||
/// Like [`Self::import_resource_bytes`], with `prefix` put in front of the resource's name
|
||||
pub fn import_resource_bytes_prefixed(&mut self, prefix: &str, file_name: &str, bytes: Vec<u8>) -> Result<String> {
|
||||
self.edit("Import resource", |session| session.add_image_resource_prefixed(prefix, file_name, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS))
|
||||
}
|
||||
|
||||
/// Add an image within a decoded texel budget, inside the caller's edit
|
||||
pub(crate) fn add_image_resource(&mut self, file_name: &str, bytes: Vec<u8>, max_texels: u64) -> Result<String> {
|
||||
self.add_image_resource_prefixed("", file_name, bytes, max_texels)
|
||||
}
|
||||
|
||||
fn add_image_resource_prefixed(&mut self, prefix: &str, file_name: &str, bytes: Vec<u8>, max_texels: u64) -> Result<String> {
|
||||
if bytes.len() > MAX_BYTES {
|
||||
return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20)));
|
||||
}
|
||||
|
||||
let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|error| EngineError::Other(format!("{file_name}: {error}")))?;
|
||||
let leaf = std::path::Path::new(file_name).file_name().and_then(|name| name.to_str()).unwrap_or("image");
|
||||
let base = texturecraft_formats::sanitize_resource_name(leaf);
|
||||
let mut base = sanitize_resource_name(leaf);
|
||||
|
||||
// The file name has priority over the optional prefix
|
||||
let prefix_room = MAX_RESOURCE_NAME_LEN - base.len();
|
||||
let prefix = prefix.trim();
|
||||
if !prefix.is_empty() && prefix_room > 0 {
|
||||
let mut prefix = sanitize_resource_name(prefix);
|
||||
prefix.truncate(prefix_room);
|
||||
base.insert_str(0, &prefix);
|
||||
}
|
||||
|
||||
let (stem, extension) = base.rfind('.').map_or((base.as_str(), ""), |extension_start| base.split_at(extension_start));
|
||||
let mut name = base.clone();
|
||||
let mut duplicate_index = 2;
|
||||
while self.doc.resources.contains_key(&name) {
|
||||
name = format!("{duplicate_index}_{base}");
|
||||
let discriminator = format!("{duplicate_index}_");
|
||||
let available = MAX_RESOURCE_NAME_LEN - discriminator.len();
|
||||
|
||||
// Leave room for a stem even for names that end in an unusually long extension
|
||||
let (stem, extension) = if extension.len() < available { (stem, extension) } else { (base.as_str(), "") };
|
||||
let stem = stem.get(..stem.len().min(available - extension.len())).unwrap_or(stem);
|
||||
name = format!("{discriminator}{stem}{extension}");
|
||||
duplicate_index += 1;
|
||||
}
|
||||
|
||||
@@ -101,7 +136,7 @@ fn list(s: &Session) -> Value {
|
||||
fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?;
|
||||
let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?;
|
||||
let name = s.import_resource_bytes(path, bytes)?;
|
||||
let name = s.import_resource_bytes_prefixed(strp(p, "prefix").unwrap_or(""), path, bytes)?;
|
||||
Ok(json!({ "name": name }))
|
||||
}
|
||||
|
||||
@@ -114,10 +149,12 @@ pub(crate) fn read_image_file(cmd: &str, path: &str, max_bytes: u64) -> Result<V
|
||||
let read_error = |error| bad(cmd, format!("cannot read {path}: {error}"));
|
||||
let too_large = || bad(cmd, format!("{path} is too large (limit {max_bytes} bytes)"));
|
||||
let metadata = std::fs::metadata(path).map_err(read_error)?;
|
||||
|
||||
// Pipes can block on open, and devices may never reach EOF
|
||||
if !metadata.is_file() {
|
||||
return Err(bad(cmd, format!("{path} is not a regular file")));
|
||||
}
|
||||
|
||||
if metadata.len() > max_bytes {
|
||||
return Err(too_large());
|
||||
}
|
||||
@@ -156,8 +193,7 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// Drop resources no layer, mask effect, the projection stencil or the environment uses (one undo
|
||||
/// step).
|
||||
/// Drop resources unused by layers, mask effects, the brush alpha, the stencil or the environment.
|
||||
fn remove_unused(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let mut used = Vec::new();
|
||||
for set in &s.doc.project.texture_sets {
|
||||
@@ -166,6 +202,7 @@ fn remove_unused(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
used.extend(s.tool.stencil.as_ref().map(|st| st.image.clone()));
|
||||
used.extend(s.tool.brush.alpha_image.clone());
|
||||
used.extend(s.doc.project.display.environment_resource().map(str::to_string));
|
||||
let unused: Vec<String> = s.doc.resources.keys().filter(|k| !used.contains(k)).cloned().collect();
|
||||
if !unused.is_empty() {
|
||||
@@ -240,4 +277,43 @@ mod tests {
|
||||
fn devices_are_rejected_before_reading() {
|
||||
assert!(read_image_file("test", "/dev/null", 16).unwrap_err().to_string().contains("not a regular file"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_prefixed_image_names_survive_saving_and_reopening() {
|
||||
let mut session = crate::sample_session(128, 32).unwrap();
|
||||
let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap();
|
||||
let file_name = format!("{}.png", "x".repeat(108));
|
||||
let prefix = "material";
|
||||
let mut names = Vec::new();
|
||||
|
||||
for _ in 0..10 {
|
||||
let name = session.import_resource_bytes_prefixed(prefix, &file_name, png.clone()).unwrap();
|
||||
crate::execute(&mut session, "layer.add.image", &json!({"name": name})).unwrap();
|
||||
names.push(name);
|
||||
}
|
||||
|
||||
let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
|
||||
|
||||
assert_eq!(reopened.images.len(), names.len());
|
||||
for name in names {
|
||||
assert!(reopened.images.contains_key(&name), "missing image after reload: {name}");
|
||||
assert!(name.ends_with(".png"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_unused_resources_keeps_the_active_brush_alpha() {
|
||||
let mut session = crate::sample_session(128, 32).unwrap();
|
||||
let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap();
|
||||
let alpha = session.import_resource_bytes("brush.png", png.clone()).unwrap();
|
||||
let unused = session.import_resource_bytes("unused.png", png).unwrap();
|
||||
crate::execute(&mut session, "tool.brush", &json!({"alpha": {"image": alpha}})).unwrap();
|
||||
|
||||
let result = crate::execute(&mut session, "file.removeUnused", &Value::Null).unwrap();
|
||||
|
||||
assert_eq!(result["removed"], json!([unused]));
|
||||
assert_eq!(session.tool.brush.alpha_image.as_deref(), Some(alpha.as_str()));
|
||||
assert!(session.images.contains_key(&alpha));
|
||||
assert!(!session.images.contains_key(&unused));
|
||||
}
|
||||
}
|
||||
@@ -51,8 +51,8 @@ pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_h
|
||||
pub use presets::load_preset;
|
||||
pub use presets::{builtin_preset, builtin_presets, preset_from_json, preset_to_json};
|
||||
pub use project_file::{
|
||||
BakePaintData, DEFAULT_PROJECT_OPEN_LIMIT_GIB, ProjectFile, load_project_bytes, project_open_limit_gib, sanitize_resource_name, save_project_bytes,
|
||||
set_project_open_limit_gib,
|
||||
BakePaintData, DEFAULT_PROJECT_OPEN_LIMIT_GIB, MAX_RESOURCE_NAME_LEN, ProjectFile, load_project_bytes, project_open_limit_gib, sanitize_resource_name,
|
||||
save_project_bytes, set_project_open_limit_gib,
|
||||
};
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -320,6 +320,46 @@ fn polygons_keep_their_edges_for_the_wireframe() {
|
||||
assert_eq!(tris.wire_edges()[0].len(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imported_quads_get_quad_tangents() {
|
||||
// A non-planar OBJ quad with sheared UVs: the importer keeps the quad for MikkTSpace, so its
|
||||
// tangents differ from the same corners written as two triangles (Blender hands quads over).
|
||||
let corners = "v 0 0 0
|
||||
v 1 0 0
|
||||
v 1 1 0.6
|
||||
v 0 1 0
|
||||
vt 0 0.1
|
||||
vt 1 0
|
||||
vt 0.9 1
|
||||
vt 0.3 0.8
|
||||
";
|
||||
let quad = import_mesh_bytes(
|
||||
"q.obj",
|
||||
format!(
|
||||
"{corners}f 1/1 2/2 3/3 4/4
|
||||
"
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.unwrap()
|
||||
.mesh;
|
||||
let tris = import_mesh_bytes(
|
||||
"t.obj",
|
||||
format!(
|
||||
"{corners}f 1/1 2/2 3/3
|
||||
f 1/1 3/3 4/4
|
||||
"
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.unwrap()
|
||||
.mesh;
|
||||
assert_eq!((quad.indices.clone(), quad.positions.clone()), (tris.indices.clone(), tris.positions.clone()), "the render triangles are the same");
|
||||
let widest = quad.tangents.iter().zip(&tris.tangents).map(|(a, b)| a.truncate().dot(b.truncate()).clamp(-1.0, 1.0).acos().to_degrees()).fold(0.0, f32::max);
|
||||
assert!(widest > 1.0, "quad tangents differ from triangle tangents by only {widest} degrees");
|
||||
assert!(quad.tangents.iter().all(|t| t.is_finite()));
|
||||
}
|
||||
|
||||
fn ply_ascii() -> String {
|
||||
"ply\nformat ascii 1.0\ncomment test\nelement vertex 4\nproperty float x\nproperty float y\nproperty float z\nproperty float s\nproperty float t\n\
|
||||
element face 1\nproperty list uchar int vertex_indices\nend_header\n\
|
||||
|
||||
@@ -81,9 +81,12 @@ pub struct ProjectFile {
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// Maximum length of a resource name after sanitization.
|
||||
pub const MAX_RESOURCE_NAME_LEN: usize = 120;
|
||||
|
||||
/// A resource name safe as a zip entry and a file name: `[A-Za-z0-9_.-]`, at most 120 chars.
|
||||
pub fn sanitize_resource_name(name: &str) -> String {
|
||||
let s: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-') { c } else { '_' }).take(120).collect();
|
||||
let s: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-') { c } else { '_' }).take(MAX_RESOURCE_NAME_LEN).collect();
|
||||
let s = s.trim_start_matches('.').to_string();
|
||||
if s.is_empty() { "resource".into() } else { s }
|
||||
}
|
||||
|
||||
+245
-8
@@ -51,6 +51,11 @@ pub struct Mesh {
|
||||
pub diagonals: Vec<u8>,
|
||||
}
|
||||
|
||||
/// [`Mesh::diagonals`] marks of the two fan triangles of a quad: the first has the diagonal as
|
||||
/// its edge 2 (last corner back to the first), the second as its edge 0.
|
||||
const QUAD_FIRST_MARK: u8 = 0b100;
|
||||
const QUAD_SECOND_MARK: u8 = 0b001;
|
||||
|
||||
/// Hard cap on mesh size accepted from files (triangles).
|
||||
pub const MAX_TRIANGLES: usize = 20_000_000;
|
||||
|
||||
@@ -240,7 +245,68 @@ impl Mesh {
|
||||
self.normals = normals.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect();
|
||||
}
|
||||
|
||||
/// MikkTSpace tangents (falls back to per-triangle tangents if generation fails).
|
||||
/// The faces MikkTSpace sees: each importer quad (a fan pair marked in [`Mesh::diagonals`])
|
||||
/// as one four-corner face, like Blender hands it over, and every other triangle as a
|
||||
/// triangle. Polygons with more than four corners stay fan triangles. The vertex and index
|
||||
/// buffers are untouched; only tangent generation looks at the quads.
|
||||
fn tangent_faces(&self) -> Vec<TangentFace> {
|
||||
let triangles = self.indices.len() / 3;
|
||||
// An empty face table keeps the original constant-space triangle adapter.
|
||||
// Do not allocate a per-triangle table unless a valid quad needs one.
|
||||
if !self.diagonals.contains(&QUAD_FIRST_MARK) || !(0..triangles).any(|t| self.quad_at(t).is_some()) {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut faces = Vec::with_capacity(triangles);
|
||||
let mut t = 0;
|
||||
while t < triangles {
|
||||
if let Some(corners) = self.quad_at(t) {
|
||||
faces.push(TangentFace { corners: [corners[0], corners[1], corners[2], corners[3]], count: 4 });
|
||||
t += 2;
|
||||
continue;
|
||||
}
|
||||
let c = |k: usize| self.indices.get(t * 3 + k).copied().unwrap_or(0);
|
||||
faces.push(TangentFace { corners: [c(0), c(1), c(2), 0], count: 3 });
|
||||
t += 1;
|
||||
}
|
||||
faces
|
||||
}
|
||||
|
||||
/// The four corners of the quad whose fan triangles are `t` and `t + 1`, or `None` when they
|
||||
/// are not an intact quad: the marks must be exactly the shared diagonal (a fan of more
|
||||
/// corners marks more edges), the triangles must share the fan's first corner and the
|
||||
/// diagonal's end, the four vertices must differ, have finite UVs and make two triangles of
|
||||
/// positive area (anything else keeps its triangles, which MikkTSpace already survives).
|
||||
fn quad_at(&self, t: usize) -> Option<[u32; 4]> {
|
||||
if self.diagonals.get(t).copied()? != QUAD_FIRST_MARK || self.diagonals.get(t + 1).copied()? != QUAD_SECOND_MARK {
|
||||
return None;
|
||||
}
|
||||
let a = self.indices.get(t * 3..t * 3 + 3)?;
|
||||
let b = self.indices.get(t * 3 + 3..t * 3 + 6)?;
|
||||
if a[0] != b[0] || a[2] != b[1] {
|
||||
return None;
|
||||
}
|
||||
let corners = [a[0], a[1], a[2], b[2]];
|
||||
if (1..4).any(|i| corners[..i].contains(&corners[i])) {
|
||||
return None;
|
||||
}
|
||||
let point = |c: usize| self.positions.get(corners[c] as usize).copied();
|
||||
let (p0, p1, p2, p3) = (point(0)?, point(1)?, point(2)?, point(3)?);
|
||||
let points = [p0, p1, p2, p3];
|
||||
// Distinct corner indices can still share one position (a seam); MikkTSpace compares
|
||||
// positions exactly and underflows when every triangle of a folded quad is dropped.
|
||||
if (1..4).any(|i| points[..i].contains(&points[i])) {
|
||||
return None;
|
||||
}
|
||||
let area = |p: Vec3, q: Vec3, r: Vec3| (q - p).cross(r - p).length_squared() > 0.0;
|
||||
if area(p0, p1, p2) && area(p0, p2, p3) && corners.iter().all(|&c| self.uvs.get(c as usize).is_some_and(|uv| uv.is_finite())) {
|
||||
Some(corners)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// MikkTSpace tangents (falls back to per-triangle tangents if generation fails). Quads the
|
||||
/// importer split ([`Mesh::diagonals`]) are tangent-generated as quads, as Blender does.
|
||||
pub fn compute_tangents(&mut self) {
|
||||
self.tangents = vec![Vec4::new(1.0, 0.0, 0.0, 1.0); self.positions.len()];
|
||||
if self.normals.len() != self.positions.len() {
|
||||
@@ -250,10 +316,14 @@ impl Mesh {
|
||||
self.uvs = vec![Vec2::ZERO; self.positions.len()];
|
||||
}
|
||||
// mikktspace crashes (out-of-bounds) when every triangle is degenerate; skip it then.
|
||||
let usable = !crate::unwrap::all_triangles_degenerate(self);
|
||||
let mut g = Mikk { mesh: self };
|
||||
if !usable || !mikktspace::generate_tangents(&mut g) {
|
||||
if crate::unwrap::all_triangles_degenerate(self) {
|
||||
self.simple_tangents();
|
||||
} else {
|
||||
let faces = self.tangent_faces();
|
||||
let mut g = Mikk { mesh: self, faces };
|
||||
if !mikktspace::generate_tangents(&mut g) {
|
||||
self.simple_tangents();
|
||||
}
|
||||
}
|
||||
for (t, n) in self.tangents.iter_mut().zip(&self.normals) {
|
||||
// Orthonormalize against the normal; repair degenerate results.
|
||||
@@ -428,22 +498,34 @@ impl Mesh {
|
||||
}
|
||||
}
|
||||
|
||||
/// One MikkTSpace face: a triangle or a quad, as vertex indices.
|
||||
struct TangentFace {
|
||||
corners: [u32; 4],
|
||||
/// 3 or 4 corners in use.
|
||||
count: usize,
|
||||
}
|
||||
|
||||
struct Mikk<'a> {
|
||||
mesh: &'a mut Mesh,
|
||||
faces: Vec<TangentFace>,
|
||||
}
|
||||
|
||||
impl Mikk<'_> {
|
||||
fn vi(&self, face: usize, vert: usize) -> usize {
|
||||
self.mesh.indices.get(face * 3 + vert).copied().unwrap_or(0) as usize
|
||||
if self.faces.is_empty() {
|
||||
self.mesh.indices.get(face * 3 + vert).copied().unwrap_or(0) as usize
|
||||
} else {
|
||||
self.faces.get(face).and_then(|f| f.corners.get(vert)).copied().unwrap_or(0) as usize
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl mikktspace::Geometry for Mikk<'_> {
|
||||
fn num_faces(&self) -> usize {
|
||||
self.mesh.indices.len() / 3
|
||||
if self.faces.is_empty() { self.mesh.indices.len() / 3 } else { self.faces.len() }
|
||||
}
|
||||
fn num_vertices_of_face(&self, _face: usize) -> usize {
|
||||
3
|
||||
fn num_vertices_of_face(&self, face: usize) -> usize {
|
||||
self.faces.get(face).map_or(3, |f| f.count)
|
||||
}
|
||||
fn position(&self, face: usize, vert: usize) -> [f32; 3] {
|
||||
self.mesh.positions.get(self.vi(face, vert)).copied().unwrap_or_default().to_array()
|
||||
@@ -469,6 +551,19 @@ impl mikktspace::Geometry for Mikk<'_> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn unmarked_and_invalid_quad_meshes_need_no_face_table() {
|
||||
let mut mesh = quad();
|
||||
assert_eq!(mesh.tangent_faces().capacity(), 0);
|
||||
mesh.diagonals = vec![QUAD_FIRST_MARK, QUAD_SECOND_MARK];
|
||||
assert_eq!(mesh.tangent_faces().len(), 1);
|
||||
mesh.positions.fill(Vec3::ZERO);
|
||||
mesh.normals.fill(Vec3::X);
|
||||
assert_eq!(mesh.tangent_faces().capacity(), 0);
|
||||
mesh.compute_tangents();
|
||||
assert!(mesh.tangents.iter().all(|t| t.is_finite() && t.truncate().dot(Vec3::X).abs() < 1e-6));
|
||||
}
|
||||
|
||||
fn quad() -> Mesh {
|
||||
Mesh::from_parts(
|
||||
vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 0.0), Vec3::new(0.0, 1.0, 0.0)],
|
||||
@@ -577,6 +672,148 @@ mod tests {
|
||||
assert_eq!(mesh.missing_seam_edges(), vec![Vec::<(u32, u32)>::new(); 2], "a material boundary alone is not a hard edge");
|
||||
}
|
||||
|
||||
/// MikkTSpace run directly on one quad, the way Blender hands it over (the reference the
|
||||
/// triangle-corner results are held to).
|
||||
struct QuadRef<'a> {
|
||||
mesh: &'a Mesh,
|
||||
out: [Vec4; 4],
|
||||
}
|
||||
|
||||
impl mikktspace::Geometry for QuadRef<'_> {
|
||||
fn num_faces(&self) -> usize {
|
||||
1
|
||||
}
|
||||
fn num_vertices_of_face(&self, _face: usize) -> usize {
|
||||
4
|
||||
}
|
||||
fn position(&self, _face: usize, vert: usize) -> [f32; 3] {
|
||||
self.mesh.positions[vert].to_array()
|
||||
}
|
||||
fn normal(&self, _face: usize, vert: usize) -> [f32; 3] {
|
||||
self.mesh.normals[vert].to_array()
|
||||
}
|
||||
fn tex_coord(&self, _face: usize, vert: usize) -> [f32; 2] {
|
||||
[self.mesh.uvs[vert].x, 1.0 - self.mesh.uvs[vert].y]
|
||||
}
|
||||
fn set_tangent_encoded(&mut self, tangent: [f32; 4], _face: usize, vert: usize) {
|
||||
self.out[vert] = Vec4::from_array(tangent);
|
||||
}
|
||||
}
|
||||
|
||||
/// A non-planar quad with a trapezoid UV layout, split as the importer does (two fan
|
||||
/// triangles, the diagonal marked), tangents computed.
|
||||
fn warped_quad() -> Mesh {
|
||||
let mut m = Mesh::from_parts(
|
||||
vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 0.6), Vec3::new(0.0, 1.0, 0.0)],
|
||||
None,
|
||||
vec![Vec2::new(0.0, 0.9), Vec2::new(1.0, 1.0), Vec2::new(0.9, 0.0), Vec2::new(0.3, 0.2)],
|
||||
vec![0, 1, 2, 0, 2, 3],
|
||||
"Default",
|
||||
)
|
||||
.unwrap();
|
||||
m.diagonals = vec![0b100, 0b001];
|
||||
m.compute_tangents();
|
||||
m
|
||||
}
|
||||
|
||||
/// Largest angle in degrees between the tangents of `a` and `b`, and whether any sign differs.
|
||||
fn tangent_gap(a: &[Vec4], b: &[Vec4]) -> (f32, bool) {
|
||||
let angle = a.iter().zip(b).map(|(x, y)| x.truncate().dot(y.truncate()).clamp(-1.0, 1.0).acos().to_degrees()).fold(0.0, f32::max);
|
||||
(angle, a.iter().zip(b).any(|(x, y)| x.w != y.w))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warped_quad_tangents_match_quad_mikktspace() {
|
||||
let m = warped_quad();
|
||||
let mut reference = QuadRef { mesh: &m, out: [Vec4::ZERO; 4] };
|
||||
assert!(mikktspace::generate_tangents(&mut reference));
|
||||
let n = m.normals.clone();
|
||||
let reference: Vec<Vec4> = reference
|
||||
.out
|
||||
.iter()
|
||||
.zip(&n)
|
||||
.map(|(t, n)| {
|
||||
let v = t.truncate();
|
||||
(v - *n * n.dot(v)).normalize().extend(t.w)
|
||||
})
|
||||
.collect();
|
||||
let (angle, sign) = tangent_gap(&m.tangents, &reference);
|
||||
assert!(angle < 0.01 && !sign, "tangents differ from quad MikkTSpace by {angle} degrees (sign differs: {sign})");
|
||||
|
||||
// Without the polygon marks the mesh is two triangles, whose tangents are another frame.
|
||||
let mut tris = m.clone();
|
||||
tris.diagonals.clear();
|
||||
tris.compute_tangents();
|
||||
assert!(tangent_gap(&tris.tangents, &reference).0 > 0.5, "the quad and the triangle frames must differ for this test to mean anything");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn planar_quad_tangents_do_not_change() {
|
||||
let mut m = quad();
|
||||
let before = m.tangents.clone();
|
||||
m.diagonals = vec![0b100, 0b001];
|
||||
m.compute_tangents();
|
||||
let (angle, flipped) = tangent_gap(&m.tangents, &before);
|
||||
assert!(angle < 1e-3 && !flipped, "angle {angle}, flipped {flipped}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folded_quad_sharing_a_position_does_not_crash_mikktspace() {
|
||||
// Corner 3 reuses corner 1's position with its own UV (a 4-line OBJ makes this). With
|
||||
// only this quad in the mesh every MikkTSpace triangle used to be dropped and it crashed.
|
||||
let mut m = Mesh::from_parts(
|
||||
vec![Vec3::ZERO, Vec3::X, Vec3::new(1.0, 1.0, 0.0), Vec3::X],
|
||||
Some(vec![Vec3::Z; 4]),
|
||||
vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.5, 0.5)],
|
||||
vec![0, 1, 2, 0, 2, 3],
|
||||
"Default",
|
||||
)
|
||||
.unwrap();
|
||||
m.diagonals = vec![0b100, 0b001];
|
||||
m.compute_tangents();
|
||||
assert!(m.tangents.iter().all(|t| t.is_finite()), "{:?}", m.tangents);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_quads_keep_triangle_tangents_and_do_not_panic() {
|
||||
// A repeated corner, a non-finite UV and a collapsed quad: no panic, tangents stay finite.
|
||||
for edit in 0..3 {
|
||||
let mut m = warped_quad();
|
||||
match edit {
|
||||
0 => m.indices = vec![0, 1, 1, 0, 1, 3],
|
||||
1 => m.uvs[2] = Vec2::new(f32::NAN, 0.0),
|
||||
_ => m.positions = vec![Vec3::ZERO; 4],
|
||||
}
|
||||
m.compute_tangents();
|
||||
assert!(m.tangents.iter().all(|t| t.is_finite()), "edit {edit}: {:?}", m.tangents);
|
||||
}
|
||||
// Diagonal marks on triangles that are not a fan pair are ignored.
|
||||
let mut m = warped_quad();
|
||||
m.diagonals = vec![0b100, 0b100];
|
||||
m.compute_tangents();
|
||||
let mut plain = warped_quad();
|
||||
plain.diagonals.clear();
|
||||
plain.compute_tangents();
|
||||
assert_eq!(m.tangents, plain.tangents);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polygons_beyond_four_corners_stay_triangles() {
|
||||
// A fan of three triangles (a pentagon) marks 0b100, 0b101, 0b001: no quad is found.
|
||||
let mut m = Mesh::from_parts(
|
||||
vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(1.3, 1.0, 0.4), Vec3::new(0.5, 1.5, 0.0), Vec3::new(-0.3, 1.0, 0.0)],
|
||||
Some(vec![Vec3::Z; 5]),
|
||||
vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(0.8, 0.0), Vec2::new(0.5, 0.0), Vec2::new(0.2, 0.0)],
|
||||
vec![0, 1, 2, 0, 2, 3, 0, 3, 4],
|
||||
"Default",
|
||||
)
|
||||
.unwrap();
|
||||
let before = m.tangents.clone();
|
||||
m.diagonals = vec![0b100, 0b101, 0b001];
|
||||
m.compute_tangents();
|
||||
assert_eq!(m.tangents, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_catches_bad_indices() {
|
||||
let mut m = quad();
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
use crate::i18n::n_;
|
||||
|
||||
/// How a project manages colour. Only Legacy is implemented; OpenColorIO can be chosen to see its
|
||||
/// settings, but they stay disabled and a project is always created and kept as Legacy.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum ColorManagement {
|
||||
#[default]
|
||||
Legacy,
|
||||
OpenColorIo,
|
||||
}
|
||||
|
||||
impl ColorManagement {
|
||||
pub(crate) fn label(self) -> &'static str {
|
||||
match self {
|
||||
ColorManagement::Legacy => n_("Legacy"),
|
||||
ColorManagement::OpenColorIo => "OpenColorIO",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
//! File > Import resources...: a window to collect files, set what each is for, and import them
|
||||
//! together. Images become project resources; materials load as smart materials.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use egui::{Key, Modifiers};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::file_dialogs::{Bound, FileDialog};
|
||||
use crate::i18n::{tr, trf};
|
||||
use crate::state::{ImportResources, ImportRow, ResourceUsage};
|
||||
use crate::web_files::{IMAGE_EXTS, MATERIAL_EXTS};
|
||||
use crate::widgets::primary_button;
|
||||
|
||||
/// Width of the window
|
||||
const WINDOW_WIDTH_POINTS: f32 = 640.0;
|
||||
/// Height of the file list
|
||||
const LIST_HEIGHT_POINTS: f32 = 300.0;
|
||||
/// Width of a row's prefix field and usage dropdown
|
||||
const PREFIX_WIDTH_POINTS: f32 = 160.0;
|
||||
const USAGE_WIDTH_POINTS: f32 = 110.0;
|
||||
/// Width of the destination dropdown
|
||||
const TARGET_WIDTH_POINTS: f32 = 190.0;
|
||||
/// Keep space for the file name in a narrow row
|
||||
const MIN_NAME_WIDTH_POINTS: f32 = 40.0;
|
||||
|
||||
/// Opens the window with an empty list (an open window stays as it is)
|
||||
pub(crate) fn open(app: &mut TextureCraftApp) {
|
||||
static NEXT_OPENING_ID: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
app.ui.windows.project_config = None;
|
||||
if app.ui.windows.import_resources.is_none() {
|
||||
app.ui.windows.import_resources = Some(ImportResources {
|
||||
project: app.session.project_id,
|
||||
opening_id: NEXT_OPENING_ID.fetch_add(1, Ordering::Relaxed),
|
||||
..ImportResources::default()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The keys of the open window: Escape closes it, Enter imports unless a text field or button had
|
||||
/// the keyboard. An open dropdown takes both first.
|
||||
pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState, nothing_focused: bool, popup_open: bool) {
|
||||
if popup_open {
|
||||
return;
|
||||
}
|
||||
|
||||
let escape = input.consume_key(Modifiers::NONE, Key::Escape);
|
||||
let enter = input.consume_key(Modifiers::NONE, Key::Enter);
|
||||
if escape {
|
||||
app.ui.windows.import_resources = None;
|
||||
} else if enter
|
||||
&& nothing_focused
|
||||
&& let Some(window) = app.ui.windows.import_resources.as_mut()
|
||||
{
|
||||
window.confirm = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the file is a material (loaded as a smart material, so it has no usage or prefix)
|
||||
fn is_material(row: &ImportRow) -> bool {
|
||||
row.path.extension().and_then(|e| e.to_str()).is_some_and(|e| MATERIAL_EXTS.contains(&e.to_ascii_lowercase().as_str()))
|
||||
}
|
||||
|
||||
fn file_name(row: &ImportRow) -> String {
|
||||
row.path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| row.path.display().to_string())
|
||||
}
|
||||
|
||||
/// A click on row `id` of the `visible` rows: plain selects only it, Ctrl toggles it, Shift
|
||||
/// selects from the anchor to it
|
||||
fn click_row(window: &mut ImportResources, visible: &[u64], id: u64, modifiers: Modifiers) {
|
||||
let ctrl = modifiers.command || modifiers.ctrl;
|
||||
let from = window.anchor.and_then(|anchor| visible.iter().position(|v| *v == anchor));
|
||||
let to = visible.iter().position(|v| *v == id);
|
||||
|
||||
match (modifiers.shift, from, to) {
|
||||
(true, Some(from), Some(to)) => {
|
||||
let range: BTreeSet<u64> = visible[from.min(to)..=from.max(to)].iter().copied().collect();
|
||||
if ctrl {
|
||||
window.selected.extend(range);
|
||||
} else {
|
||||
window.selected = range;
|
||||
}
|
||||
}
|
||||
_ if ctrl => {
|
||||
if !window.selected.remove(&id) {
|
||||
window.selected.insert(id);
|
||||
}
|
||||
window.anchor = Some(id);
|
||||
}
|
||||
_ => {
|
||||
window.selected = BTreeSet::from([id]);
|
||||
window.anchor = Some(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
let Some(mut window) = app.ui.windows.import_resources.take() else { return };
|
||||
|
||||
// Files chosen for another project cannot be imported here
|
||||
if window.project != app.session.project_id {
|
||||
return;
|
||||
}
|
||||
|
||||
// A filter whose rows are gone shows everything again
|
||||
if window.filter.is_some_and(|usage| !window.rows.iter().any(|row| row.usage == usage)) {
|
||||
window.filter = None;
|
||||
}
|
||||
|
||||
let mut open = true;
|
||||
let (mut import, mut cancel, mut add) = (std::mem::take(&mut window.confirm), false, false);
|
||||
let mut remove = false;
|
||||
|
||||
crate::windows::dialog("import_resources", tr("Import resources"), &mut open).default_width(WINDOW_WIDTH_POINTS).show(ctx, |ui| {
|
||||
ui.set_min_width(WINDOW_WIDTH_POINTS);
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Choose files and assign their roles"));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.add_enabled_ui(!window.selected.is_empty(), |ui| {
|
||||
remove = ui.button(tr("Remove selected resources")).clicked();
|
||||
});
|
||||
add = ui.button(tr("Add resources")).clicked();
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
|
||||
let all_label = trf("All files ({count})", &[("count", &window.rows.len())]);
|
||||
let filter_text = match window.filter {
|
||||
None => all_label.clone(),
|
||||
Some(usage) => trf("{usage} ({count})", &[("usage", &usage.name()), ("count", &window.rows.iter().filter(|row| row.usage == usage).count())]),
|
||||
};
|
||||
egui::ComboBox::from_id_salt("import_filter").width(ui.available_width()).selected_text(filter_text).show_ui(ui, |ui| {
|
||||
if ui.selectable_label(window.filter.is_none(), &all_label).clicked() {
|
||||
window.filter = None;
|
||||
}
|
||||
|
||||
// Only usages some row has, so the list is never empty by filter
|
||||
for usage in ResourceUsage::ALL {
|
||||
let count = window.rows.iter().filter(|row| row.usage == usage).count();
|
||||
if count > 0 && ui.selectable_label(window.filter == Some(usage), format!("{} ({count})", usage.name())).clicked() {
|
||||
window.filter = Some(usage);
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
|
||||
let filter = window.filter;
|
||||
let visible = |row: &ImportRow| filter.is_none_or(|usage| row.usage == usage);
|
||||
let modifiers = ui.input(|i| i.modifiers);
|
||||
let mut clicked = None;
|
||||
|
||||
egui::ScrollArea::vertical().min_scrolled_height(LIST_HEIGHT_POINTS).max_height(LIST_HEIGHT_POINTS).auto_shrink([false, false]).show(ui, |ui| {
|
||||
for row in window.rows.iter_mut().filter(|row| visible(row)) {
|
||||
let material = is_material(row);
|
||||
let selected = window.selected.contains(&row.id);
|
||||
ui.horizontal(|ui| {
|
||||
let name_width =
|
||||
(ui.available_width() - PREFIX_WIDTH_POINTS - USAGE_WIDTH_POINTS - 2.0 * ui.spacing().item_spacing.x).max(MIN_NAME_WIDTH_POINTS);
|
||||
let name = ui.add_sized([name_width, ui.spacing().interact_size.y], egui::Button::selectable(selected, file_name(row)).truncate());
|
||||
if name.on_hover_text(row.path.display().to_string()).clicked() {
|
||||
clicked = Some(row.id);
|
||||
}
|
||||
|
||||
let prefix = ui.add_enabled(
|
||||
!material,
|
||||
egui::TextEdit::singleline(&mut row.prefix).hint_text(tr("Optional prefix/path...")).desired_width(PREFIX_WIDTH_POINTS),
|
||||
);
|
||||
if material {
|
||||
prefix.on_disabled_hover_text(tr("Materials keep their own name"));
|
||||
} else {
|
||||
prefix.on_hover_text(tr("Put in front of the resource's name. Characters other than letters, digits and _ . - become _"));
|
||||
}
|
||||
|
||||
ui.add_enabled_ui(!material, |ui| {
|
||||
egui::ComboBox::from_id_salt(("import_usage", row.id)).width(USAGE_WIDTH_POINTS).selected_text(row.usage.name()).show_ui(ui, |ui| {
|
||||
for usage in ResourceUsage::ALL {
|
||||
let item = ui.add_enabled(usage.available(), egui::Button::selectable(row.usage == usage, usage.name()));
|
||||
if usage.available() {
|
||||
if item.clicked() {
|
||||
row.usage = usage;
|
||||
ui.close();
|
||||
}
|
||||
} else {
|
||||
item.on_disabled_hover_text(tr("Not available yet"));
|
||||
}
|
||||
}
|
||||
});
|
||||
})
|
||||
.response
|
||||
.on_disabled_hover_text(tr("Materials need no usage"));
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
if let Some(id) = clicked {
|
||||
let visible: Vec<u64> = if modifiers.shift { window.rows.iter().filter(|row| visible(row)).map(|row| row.id).collect() } else { Vec::new() };
|
||||
click_row(&mut window, &visible, id, modifiers);
|
||||
}
|
||||
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
egui::ComboBox::from_id_salt("import_target").width(TARGET_WIDTH_POINTS).selected_text(tr("Open project")).show_ui(ui, |ui| {
|
||||
if ui.selectable_label(true, tr("Open project")).clicked() {
|
||||
ui.close();
|
||||
}
|
||||
|
||||
ui.add_enabled(false, egui::Button::selectable(false, tr("Asset library"))).on_disabled_hover_text(tr("Not available yet"));
|
||||
});
|
||||
ui.label(tr("Destination"));
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
cancel = ui.button(tr("Cancel")).clicked();
|
||||
import |= ui.add_enabled(!window.rows.is_empty(), primary_button(ui, tr("Import"))).clicked();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
if cancel || !open {
|
||||
return;
|
||||
}
|
||||
|
||||
if remove {
|
||||
window.rows.retain(|row| !window.selected.contains(&row.id));
|
||||
window.selected.clear();
|
||||
window.anchor = None;
|
||||
}
|
||||
|
||||
if add {
|
||||
let mut extensions: Vec<&str> = IMAGE_EXTS.to_vec();
|
||||
extensions.extend_from_slice(MATERIAL_EXTS);
|
||||
let opening_id = window.opening_id;
|
||||
app.ask_file(FileDialog::open_many().filter(tr("Resources"), &extensions), Bound::Project, move |app, paths| {
|
||||
let Some(stored) = app.ui.windows.import_resources.as_mut().filter(|stored| stored.opening_id == opening_id) else { return };
|
||||
|
||||
for path in paths {
|
||||
if stored.rows.iter().any(|row| row.path == path) {
|
||||
continue;
|
||||
}
|
||||
|
||||
stored.rows.push(ImportRow { id: stored.next_row, path, prefix: String::new(), usage: ResourceUsage::Undefined });
|
||||
stored.next_row += 1;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if import && !window.rows.is_empty() {
|
||||
window.rows.retain(|row| !import_row(app, row));
|
||||
if window.rows.is_empty() {
|
||||
app.ui.dock.focus(crate::docking::Panel::Assets);
|
||||
return;
|
||||
}
|
||||
|
||||
window.selected.clear();
|
||||
window.anchor = None;
|
||||
}
|
||||
|
||||
// File picker answers run between frames after the dialog state is restored
|
||||
app.ui.windows.import_resources = Some(window);
|
||||
}
|
||||
|
||||
/// Import one row. A failed file is left in the dialog with its settings.
|
||||
fn import_row(app: &mut TextureCraftApp, row: &ImportRow) -> bool {
|
||||
let Some(path) = row.path.to_str() else {
|
||||
app.toast(trf("Could not import a path that is not UTF-8: {path}", &[("path", &row.path.display())]), true);
|
||||
return false;
|
||||
};
|
||||
|
||||
if is_material(row) {
|
||||
return app.run("material.load", json!({ "path": path })).is_some();
|
||||
}
|
||||
|
||||
let Some(result) = app.run("resource.import", json!({ "path": path, "prefix": row.prefix })) else { return false };
|
||||
|
||||
let name = result["name"].as_str().unwrap_or_default();
|
||||
app.toast(trf("Imported {name}", &[("name", &name)]), false);
|
||||
|
||||
match row.usage {
|
||||
ResourceUsage::Environment => crate::web_files::use_environment(app, name),
|
||||
ResourceUsage::Alpha => {
|
||||
if app.run("tool.brush", json!({ "alpha": { "image": name } })).is_some() {
|
||||
app.toast(trf("Brush alpha: {name}", &[("name", &name)]), false);
|
||||
}
|
||||
}
|
||||
ResourceUsage::Undefined | ResourceUsage::Texture | ResourceUsage::ColorLut | ResourceUsage::PostFx => {}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const CTRL: Modifiers = Modifiers { ctrl: true, command: true, ..Modifiers::NONE };
|
||||
const SHIFT: Modifiers = Modifiers { shift: true, ..Modifiers::NONE };
|
||||
|
||||
fn selected(window: &ImportResources) -> Vec<u64> {
|
||||
window.selected.iter().copied().collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_click_selects_one_row() {
|
||||
let mut window = ImportResources::default();
|
||||
click_row(&mut window, &[1, 2, 3], 1, Modifiers::NONE);
|
||||
click_row(&mut window, &[1, 2, 3], 3, Modifiers::NONE);
|
||||
|
||||
assert_eq!(selected(&window), [3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_toggles_rows() {
|
||||
let mut window = ImportResources::default();
|
||||
click_row(&mut window, &[1, 2, 3], 1, CTRL);
|
||||
click_row(&mut window, &[1, 2, 3], 3, CTRL);
|
||||
assert_eq!(selected(&window), [1, 3]);
|
||||
|
||||
click_row(&mut window, &[1, 2, 3], 1, CTRL);
|
||||
assert_eq!(selected(&window), [3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_selects_from_the_anchor_in_either_direction() {
|
||||
let mut window = ImportResources::default();
|
||||
click_row(&mut window, &[1, 2, 3, 4], 2, Modifiers::NONE);
|
||||
click_row(&mut window, &[1, 2, 3, 4], 4, SHIFT);
|
||||
assert_eq!(selected(&window), [2, 3, 4]);
|
||||
|
||||
click_row(&mut window, &[1, 2, 3, 4], 1, SHIFT);
|
||||
assert_eq!(selected(&window), [1, 2]);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ mod ask;
|
||||
mod bake_job;
|
||||
pub mod bake_mode;
|
||||
mod bake_scene;
|
||||
mod color_management;
|
||||
mod color_selection_editor;
|
||||
pub mod control;
|
||||
mod decal_drop;
|
||||
@@ -30,6 +31,8 @@ mod gray_slider;
|
||||
mod grid_tile;
|
||||
pub mod i18n;
|
||||
pub mod id_color_pick;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod import_resources;
|
||||
mod inactive_set_hint;
|
||||
pub mod keymap;
|
||||
pub mod layer_panel;
|
||||
@@ -62,6 +65,7 @@ mod preview_worker;
|
||||
pub mod profile;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod project_config;
|
||||
pub mod project_form;
|
||||
pub mod properties_popup;
|
||||
mod rail_popup;
|
||||
pub mod render_mode;
|
||||
|
||||
@@ -175,9 +175,7 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) {
|
||||
return;
|
||||
}
|
||||
|
||||
if matches!(id, "ui.newProject" | "file.open" | "file.close" | "project.sample")
|
||||
&& crate::windows::ask_to_save(app, crate::state::Unsaved::Command(id.into()))
|
||||
{
|
||||
if matches!(id, "file.open" | "file.close" | "project.sample") && crate::windows::ask_to_save(app, crate::state::Unsaved::Command(id.into())) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -191,7 +189,7 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) {
|
||||
}
|
||||
|
||||
match id {
|
||||
"ui.newProject" => app.ui.windows.new_project = true,
|
||||
"ui.newProject" => crate::new_project_advanced::open(app),
|
||||
"ui.export" => app.ui.windows.export = true,
|
||||
"ui.quit" => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -438,6 +436,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
// Its keys are Escape (close) and Enter (OK); a stroke in progress isn't touched
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::project_config::keys_in(app, input, nothing_focused, popup_open);
|
||||
} else if app.ui.windows.import_resources.is_some() {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::import_resources::keys_in(app, input, nothing_focused, popup_open);
|
||||
} else if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
app.properties_popup = None;
|
||||
} else if !popup_open && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
|
||||
@@ -1,68 +1,248 @@
|
||||
//! New project ▸ Advanced settings: the normal map format, and baked map files imported at creation
|
||||
//! File > New project: BASIC SETTINGS (mesh file, template, resolution), ADVANCED SETTINGS (normal
|
||||
//! map format, UV tiles, import settings, baked maps imported at creation, physical size, color
|
||||
//! management), and Cancel / Create fixed below the scrolling form.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use egui::{RichText, Sense, Ui, vec2};
|
||||
use egui::{RichText, Ui, vec2};
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::NormalFormat;
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::i18n::{tr, trf};
|
||||
use crate::state::NewProject;
|
||||
use crate::project_form::{
|
||||
FIELD_WIDTH_POINTS, ROW_INDENT_POINTS, auto_unwrap_row, check_row, collapsible, color_management, note, physical_size, row, sub_title, tangent_space_row,
|
||||
unavailable, uv_tile_radios,
|
||||
};
|
||||
use crate::state::{Mode, NewProject};
|
||||
use crate::theme::{Tokens, caption};
|
||||
use crate::widgets::{section, section_chevron};
|
||||
use crate::windows::file_dialogs_available;
|
||||
|
||||
/// Labels of every New project form row, so Basic and Advanced share one label column
|
||||
const FORM_LABELS: [&str; 6] = ["3D mesh", "Project template", "Document resolution", "UV tiles (UDIM)", "Name", "Normal map format"];
|
||||
use crate::widgets::primary_button;
|
||||
use crate::windows::{dialog, file_dialogs_available};
|
||||
|
||||
/// Each normal map format with its command id and label
|
||||
const NORMAL_FORMATS: [(NormalFormat, &str, &str); 2] = [(NormalFormat::OpenGl, "openGl", "OpenGL"), (NormalFormat::DirectX, "directX", "DirectX")];
|
||||
|
||||
/// Width of the dialog's dropdowns
|
||||
pub(crate) const COMBO_WIDTH: f32 = 200.0;
|
||||
/// Document resolutions offered (texture sets range from 128 to 8192 px)
|
||||
const RESOLUTIONS: [u32; 7] = [128, 256, 512, 1024, 2048, 4096, 8192];
|
||||
|
||||
/// Width of the Add... and Clear buttons
|
||||
const FILE_BUTTON_WIDTH: f32 = 96.0;
|
||||
/// Width of the dialog's form
|
||||
const DIALOG_WIDTH_POINTS: f32 = 560.0;
|
||||
|
||||
/// Tallest the list of added files grows before it scrolls
|
||||
const FILE_LIST_HEIGHT: f32 = 160.0;
|
||||
/// Leave space around the centered dialog on short viewports
|
||||
const DIALOG_VIEWPORT_MARGIN_POINTS: f32 = 32.0;
|
||||
|
||||
/// Width of the widest form label, for the label column of every form grid in the dialog
|
||||
pub(crate) fn form_label_width(ui: &Ui) -> f32 {
|
||||
let font = egui::TextStyle::Body.resolve(ui.style());
|
||||
FORM_LABELS.iter().map(|label| ui.painter().layout_no_wrap(tr(label).to_string(), font.clone(), egui::Color32::WHITE).size().x).fold(0.0, f32::max)
|
||||
/// Room for the title bar and the button row below the scrolling form
|
||||
const DIALOG_CHROME_HEIGHT_POINTS: f32 = 96.0;
|
||||
|
||||
/// Width of the Add and Clear buttons
|
||||
const FILE_BUTTON_WIDTH_POINTS: f32 = 96.0;
|
||||
|
||||
/// Height of the list of added baked map files (it scrolls when longer)
|
||||
const FILE_LIST_HEIGHT_POINTS: f32 = 120.0;
|
||||
|
||||
/// Width of the Cancel and Create buttons
|
||||
const BUTTON_WIDTH_POINTS: f32 = 90.0;
|
||||
|
||||
/// File > New project...: start a fresh form, carrying over failed imports from a closed form.
|
||||
pub(crate) fn open(app: &mut TextureCraftApp) {
|
||||
let baked_maps = if app.ui.windows.new_project { Vec::new() } else { std::mem::take(&mut app.ui.new_project.baked_maps) };
|
||||
|
||||
app.ui.new_project = NewProject { baked_maps, opening_id: next_request_id(), ..NewProject::default() };
|
||||
app.ui.windows.new_project = true;
|
||||
}
|
||||
|
||||
/// The collapsible Advanced settings section (closed until opened)
|
||||
pub(crate) fn advanced_settings(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let id = ui.make_persistent_id("np_advanced");
|
||||
let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, false);
|
||||
let header = ui
|
||||
.horizontal(|ui| {
|
||||
ui.add(egui::Label::new(section_chevron(ui, state.is_open())).selectable(false));
|
||||
ui.add(egui::Label::new(caption(tr("Advanced settings"))).selectable(false));
|
||||
})
|
||||
.response
|
||||
.interact(Sense::click());
|
||||
if header.clicked() {
|
||||
state.toggle(ui);
|
||||
fn next_request_id() -> u64 {
|
||||
static NEXT_REQUEST_ID: AtomicU64 = AtomicU64::new(1);
|
||||
NEXT_REQUEST_ID.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn close(app: &mut TextureCraftApp) {
|
||||
app.ui.windows.new_project = false;
|
||||
app.ui.new_project.clear_mesh();
|
||||
}
|
||||
|
||||
/// The New project dialog.
|
||||
pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
if !app.ui.windows.new_project {
|
||||
return;
|
||||
}
|
||||
|
||||
state.show_body_unindented(ui, |ui| {
|
||||
egui::Grid::new("np_advanced_grid").num_columns(2).spacing(vec2(12.0, 8.0)).min_col_width(form_label_width(ui)).show(ui, |ui| {
|
||||
ui.label(tr("Normal map format"));
|
||||
normal_format_combo(app, ui);
|
||||
ui.end_row();
|
||||
let mut open = true;
|
||||
let (mut create, mut cancel) = (false, false);
|
||||
|
||||
// A fixed height keeps the centered window still while its sections lay out
|
||||
let form_height = (ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN_POINTS - DIALOG_CHROME_HEIGHT_POINTS)
|
||||
.clamp(crate::project_form::MIN_FORM_HEIGHT_POINTS, crate::project_form::FORM_HEIGHT_POINTS);
|
||||
dialog("new_project", tr("New project"), &mut open).default_width(DIALOG_WIDTH_POINTS).show(ctx, |ui| {
|
||||
ui.set_width(DIALOG_WIDTH_POINTS);
|
||||
egui::ScrollArea::vertical().id_salt("np_form").min_scrolled_height(form_height).max_height(form_height).auto_shrink([false, true]).show(ui, |ui| {
|
||||
basic_settings(app, ui);
|
||||
ui.add_space(8.0);
|
||||
advanced_settings(app, ui);
|
||||
});
|
||||
if file_dialogs_available() {
|
||||
ui.add_space(4.0);
|
||||
section(ui, "np_baked_maps", tr("Import baked maps"), false, |ui| {
|
||||
if baked_maps(&mut app.ui.new_project, ui) {
|
||||
ask_baked_map_files(app);
|
||||
}
|
||||
ui.separator();
|
||||
let can_create = app.ui.new_project.file.is_some();
|
||||
ui.horizontal(|ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
create = ui
|
||||
.add_enabled(can_create, primary_button(ui, tr("Create")).min_size(vec2(BUTTON_WIDTH_POINTS, 0.0)))
|
||||
.on_disabled_hover_text(tr("Select a 3D mesh first"))
|
||||
.clicked();
|
||||
cancel = ui.add(egui::Button::new(tr("Cancel")).min_size(vec2(BUTTON_WIDTH_POINTS, 0.0))).clicked();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
if cancel || !open {
|
||||
app.ui.new_project.baked_maps = Vec::new();
|
||||
close(app);
|
||||
} else if create && app.ui.windows.unsaved.is_none() {
|
||||
let opening_id = app.ui.new_project.opening_id;
|
||||
if !crate::windows::ask_to_save(app, crate::state::Unsaved::CreateProject(opening_id)) {
|
||||
finish_create(app, opening_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn finish_create(app: &mut TextureCraftApp, opening_id: u64) -> bool {
|
||||
if !app.ui.windows.new_project || app.ui.new_project.opening_id != opening_id || !create_project(app) {
|
||||
return false;
|
||||
}
|
||||
|
||||
close(app);
|
||||
app.ui.mode = Mode::Painting;
|
||||
apply_after_create(app);
|
||||
true
|
||||
}
|
||||
|
||||
/// The `file.new` command for the form: the chosen mesh file with the settings the engine takes at
|
||||
/// creation (the project is named after the file). None until a mesh file is chosen.
|
||||
pub fn create_command(new_project: &NewProject) -> Option<Value> {
|
||||
let mesh = new_project.file.as_ref()?;
|
||||
Some(json!({
|
||||
"mesh": mesh,
|
||||
"resolution": new_project.resolution,
|
||||
"uvTiles": new_project.uv_tiles == Some(true),
|
||||
"template": new_project.template,
|
||||
"importCameras": new_project.import_cameras,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Create the project; false (with the error reported) when it failed.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn create_project(app: &mut TextureCraftApp) -> bool {
|
||||
create_command(&app.ui.new_project).is_some_and(|params| app.run("file.new", params).is_some())
|
||||
}
|
||||
|
||||
/// Create the project from the mesh file's bytes picked in the browser, as `file.new` does on the
|
||||
/// desktop.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn create_project(app: &mut TextureCraftApp) -> bool {
|
||||
let new_project = &app.ui.new_project;
|
||||
let (Some(name), Some(bytes)) = (new_project.file.as_deref(), new_project.file_bytes.as_deref()) else { return false };
|
||||
|
||||
let stem = std::path::Path::new(name).file_stem().and_then(|stem| stem.to_str()).unwrap_or("Untitled").to_string();
|
||||
let template = app.session.template(&new_project.template);
|
||||
match texturecraft_engine::Session::from_mesh_bytes_tiled(name, bytes, new_project.resolution, &stem, Some(new_project.uv_tiles == Some(true))) {
|
||||
Ok(mut next) => {
|
||||
if !new_project.import_cameras {
|
||||
next.doc.project.cameras.clear();
|
||||
}
|
||||
if let Some(template) = &template {
|
||||
next.apply_template(template);
|
||||
}
|
||||
app.session.switch_to(next);
|
||||
app.pbr_import = None;
|
||||
app.resize = None;
|
||||
app.layer_panel = Default::default();
|
||||
app.camera_glide = None;
|
||||
true
|
||||
}
|
||||
Err(error) => {
|
||||
app.toast(trf("Couldn't open {name}: {error}", &[("name", &name), ("error", &error)]), true);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn basic_settings(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
ui.label(caption(&tr("Basic settings").to_uppercase()));
|
||||
let mut select = false;
|
||||
row(ui, tr("3D mesh"), Some(tr("The mesh file to paint. Create is available once one is selected.")), |ui| {
|
||||
select = ui.add(egui::Button::new(tr("Select...")).min_size(vec2(FILE_BUTTON_WIDTH_POINTS, 0.0))).clicked();
|
||||
match &app.ui.new_project.file {
|
||||
Some(path) => {
|
||||
ui.add(egui::Label::new(file_name(path)).truncate()).on_hover_text(path.as_str());
|
||||
}
|
||||
None => {
|
||||
ui.label(RichText::new(tr("No file selected")).italics().color(tokens.text_dim));
|
||||
}
|
||||
}
|
||||
});
|
||||
if select {
|
||||
ask_mesh_file(app, ui.ctx());
|
||||
}
|
||||
|
||||
row(ui, tr("Project template"), Some(tr("The channels, resolution, normal map format and display settings a project starts with")), |ui| {
|
||||
let new_project = &mut app.ui.new_project;
|
||||
egui::ComboBox::from_id_salt("np_template").width(FIELD_WIDTH_POINTS).selected_text(new_project.template.clone()).show_ui(ui, |ui| {
|
||||
let user_templates = app.session.templates.list.iter();
|
||||
for template in texturecraft_engine::template_cmds::builtin_templates().iter().chain(user_templates) {
|
||||
if ui.selectable_label(template.name == new_project.template, &template.name).clicked() {
|
||||
new_project.template = template.name.clone();
|
||||
new_project.resolution = template.resolution;
|
||||
new_project.normal_format = None;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
row(ui, tr("Document resolution (px)"), Some(tr("The texture size of every texture set. It can be changed later.")), |ui| {
|
||||
let resolution = &mut app.ui.new_project.resolution;
|
||||
egui::ComboBox::from_id_salt("np_res").width(FIELD_WIDTH_POINTS).selected_text(format!("{0} x {0}", *resolution)).show_ui(ui, |ui| {
|
||||
for size in RESOLUTIONS {
|
||||
ui.selectable_value(resolution, size, format!("{size} x {size}"));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// The collapsible ADVANCED SETTINGS section (open at first)
|
||||
fn advanced_settings(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
collapsible(ui, "np_advanced_settings", &tr("Advanced settings").to_uppercase(), true, None, |ui| {
|
||||
row(
|
||||
ui,
|
||||
tr("Normal map format"),
|
||||
Some(tr("Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it.")),
|
||||
|ui| normal_format_combo(app, ui),
|
||||
);
|
||||
tangent_space_row(ui);
|
||||
|
||||
ui.add_space(4.0);
|
||||
sub_title(ui, tr("UV Tile settings (UDIMs)"), Some(tr("Paint meshes whose UVs span several UV tiles (UDIMs)")));
|
||||
note(ui, tr("You can enable or disable UV tiles later in Texture Set Settings."));
|
||||
let new_project = &mut app.ui.new_project;
|
||||
let mut uv_tiles = new_project.uv_tiles == Some(true);
|
||||
if check_row(ui, None, |ui| ui.checkbox(&mut uv_tiles, tr("Use UV Tile workflow")), |_| {}).changed() {
|
||||
new_project.uv_tiles = Some(uv_tiles);
|
||||
}
|
||||
uv_tile_radios(ui, uv_tiles, tr("Tick Use UV Tile workflow first"));
|
||||
|
||||
ui.add_space(4.0);
|
||||
sub_title(ui, tr("Import settings"), None);
|
||||
check_row(ui, Some(tr("Keep the cameras stored in the mesh file")), |ui| ui.checkbox(&mut new_project.import_cameras, tr("Import cameras")), |_| {});
|
||||
auto_unwrap_row(ui);
|
||||
|
||||
ui.add_space(4.0);
|
||||
collapsible(ui, "np_import_baked_maps", tr("Import baked maps"), true, None, |ui| {
|
||||
if baked_maps(&mut app.ui.new_project, ui) {
|
||||
ask_baked_map_files(app);
|
||||
}
|
||||
});
|
||||
physical_size(ui, "np_physical_size", true);
|
||||
color_management(ui, "np_color_management", &mut app.ui.new_project.color_management);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -71,7 +251,7 @@ fn normal_format_combo(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let template_format = app.session.template(&new_project.template).map(|template| template.normal_format).unwrap_or_default();
|
||||
let current = new_project.normal_format.unwrap_or(template_format);
|
||||
let current_label = NORMAL_FORMATS.iter().find(|(format, _, _)| *format == current).map_or("", |(_, _, label)| label);
|
||||
egui::ComboBox::from_id_salt("np_normal_format").width(COMBO_WIDTH).selected_text(current_label).show_ui(ui, |ui| {
|
||||
egui::ComboBox::from_id_salt("np_normal_format").width(FIELD_WIDTH_POINTS).selected_text(current_label).show_ui(ui, |ui| {
|
||||
for (format, _, label) in NORMAL_FORMATS {
|
||||
if ui.selectable_label(format == current, label).clicked() {
|
||||
new_project.normal_format = Some(format);
|
||||
@@ -80,33 +260,43 @@ fn normal_format_combo(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The baked map list and its buttons; true when Add was clicked.
|
||||
/// The baked map hint, buttons, file list and naming scheme; true when Add was clicked.
|
||||
fn baked_maps(new_project: &mut NewProject, ui: &mut Ui) -> bool {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let mut add = false;
|
||||
ui.horizontal(|ui| {
|
||||
let buttons_width = 2.0 * FILE_BUTTON_WIDTH + ui.spacing().item_spacing.x;
|
||||
ui.add_space(ROW_INDENT_POINTS);
|
||||
let buttons_width = 2.0 * FILE_BUTTON_WIDTH_POINTS + ui.spacing().item_spacing.x;
|
||||
let hint_width = (ui.available_width() - buttons_width - ui.spacing().item_spacing.x).max(0.0);
|
||||
ui.allocate_ui_with_layout(vec2(hint_width, 0.0), egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
ui.set_min_width(hint_width);
|
||||
ui.add(egui::Label::new(RichText::new(tr("Name each file after its texture set, like Body_normal.png")).color(tokens.text_dim)).wrap());
|
||||
ui.add(egui::Label::new(tr("Import mesh normal maps and baked maps for all materials.")).wrap());
|
||||
});
|
||||
if ui.add(egui::Button::new(tr("Add...")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))).clicked() {
|
||||
add = true;
|
||||
}
|
||||
if ui.add_enabled(!new_project.baked_maps.is_empty(), egui::Button::new(tr("Clear")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))).clicked() {
|
||||
let add_button = ui.add_enabled(file_dialogs_available(), egui::Button::new(tr("Add")).min_size(vec2(FILE_BUTTON_WIDTH_POINTS, 0.0)));
|
||||
add = unavailable(add_button).clicked();
|
||||
if ui.add_enabled(!new_project.baked_maps.is_empty(), egui::Button::new(tr("Clear")).min_size(vec2(FILE_BUTTON_WIDTH_POINTS, 0.0))).clicked() {
|
||||
new_project.baked_maps.clear();
|
||||
}
|
||||
});
|
||||
if new_project.baked_maps.is_empty() {
|
||||
return add;
|
||||
}
|
||||
|
||||
ui.add_space(4.0);
|
||||
egui::ScrollArea::vertical().max_height(FILE_LIST_HEIGHT).auto_shrink([false, true]).show(ui, |ui| {
|
||||
for path in &new_project.baked_maps {
|
||||
ui.add(egui::Label::new(file_name(path)).truncate()).on_hover_text(path.as_str());
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(ROW_INDENT_POINTS);
|
||||
egui::Frame::new().fill(tokens.field).corner_radius(2.0).inner_margin(4.0).show(ui, |ui| {
|
||||
egui::ScrollArea::vertical().id_salt("np_baked_map_list").max_height(FILE_LIST_HEIGHT_POINTS).auto_shrink([false, false]).show(ui, |ui| {
|
||||
ui.vertical(|ui| {
|
||||
for path in &new_project.baked_maps {
|
||||
ui.add(egui::Label::new(file_name(path)).truncate()).on_hover_text(path.as_str());
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(ROW_INDENT_POINTS);
|
||||
ui.label(RichText::new(tr("Normal map filename: <texture set>_normal")).color(tokens.text_dim))
|
||||
.on_hover_text(tr("Name each file after its texture set, like Body_normal.png"));
|
||||
});
|
||||
add
|
||||
}
|
||||
@@ -121,16 +311,17 @@ pub fn add_baked_map_files(new_project: &mut NewProject, paths: Vec<String>) {
|
||||
}
|
||||
|
||||
/// After creation: set the normal format, import the listed baked maps (one undo step), toast the outcome; a failed import keeps the list
|
||||
pub(crate) fn apply_after_create(app: &mut TextureCraftApp, new_project: &NewProject) {
|
||||
let chosen_format = new_project.normal_format.filter(|format| *format != app.session.doc.project.normal_format);
|
||||
fn apply_after_create(app: &mut TextureCraftApp) {
|
||||
let chosen_format = app.ui.new_project.normal_format.filter(|format| *format != app.session.doc.project.normal_format);
|
||||
if let Some((_, id, _)) = chosen_format.and_then(|chosen| NORMAL_FORMATS.iter().find(|(format, _, _)| *format == chosen)) {
|
||||
app.run("textureSet.settings", json!({ "normalFormat": id }));
|
||||
}
|
||||
if new_project.baked_maps.is_empty() {
|
||||
|
||||
if app.ui.new_project.baked_maps.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let files: Vec<Value> = new_project.baked_maps.iter().map(|path| json!({ "path": path })).collect();
|
||||
let files: Vec<Value> = app.ui.new_project.baked_maps.iter().map(|path| json!({ "path": path })).collect();
|
||||
let Some(result) = app.run("textureSet.meshMap.import", json!({ "files": files })) else {
|
||||
return;
|
||||
};
|
||||
@@ -151,11 +342,38 @@ fn file_name(path: &str) -> String {
|
||||
std::path::Path::new(path).file_name().map_or_else(|| path.to_string(), |name| name.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn ask_mesh_file(app: &mut TextureCraftApp, _ctx: &egui::Context) {
|
||||
use crate::file_dialogs::{Bound, FileDialog};
|
||||
let dialog = FileDialog::open().filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS);
|
||||
let opening_id = app.ui.new_project.opening_id;
|
||||
app.ask_file(dialog, Bound::App, move |app, paths| {
|
||||
if app.ui.windows.new_project
|
||||
&& app.ui.new_project.opening_id == opening_id
|
||||
&& let Some(path) = paths.first()
|
||||
{
|
||||
app.ui.new_project.file = Some(path.display().to_string());
|
||||
app.ui.new_project.file_bytes = None;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn ask_mesh_file(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
let request_id = next_request_id();
|
||||
app.ui.new_project.mesh_request_id = request_id;
|
||||
crate::web_files::pick_new_project_mesh(ctx, request_id);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn ask_baked_map_files(app: &mut TextureCraftApp) {
|
||||
use crate::file_dialogs::{Bound, FileDialog};
|
||||
app.ask_file(FileDialog::open_many().filter(tr("Images"), crate::web_files::IMAGE_EXTS), Bound::App, |app, files| {
|
||||
add_baked_map_files(&mut app.ui.new_project, files.into_iter().map(|path| path.display().to_string()).collect());
|
||||
|
||||
let opening_id = app.ui.new_project.opening_id;
|
||||
app.ask_file(FileDialog::open_many().filter(tr("Images"), crate::web_files::IMAGE_EXTS), Bound::App, move |app, files| {
|
||||
if app.ui.windows.new_project && app.ui.new_project.opening_id == opening_id {
|
||||
add_baked_map_files(&mut app.ui.new_project, files.into_iter().map(|path| path.display().to_string()).collect());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! Edit > Project Configuration...: the project's settings in sections. Today it has one, the
|
||||
//! 3D mesh: pick another mesh file for the project, or read the current one again.
|
||||
//! Edit > Project Configuration...: the project's settings in sections. 3D MESH picks another mesh
|
||||
//! file for the project or reads the current one again; PROJECT SETTINGS sets the normal map format
|
||||
//! and shows the UV tiles. Settings TextureCraft does not have yet (tangent space per fragment,
|
||||
//! physical size, OpenColorIO, import options other than stroke preservation) are shown disabled.
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
@@ -11,18 +13,24 @@ use crate::TextureCraftApp;
|
||||
use crate::dock::info_icon;
|
||||
use crate::file_dialogs::{Bound, FileDialog};
|
||||
use crate::i18n::{tr, trf};
|
||||
use crate::project_form::{
|
||||
FIELD_WIDTH_POINTS, ROW_INDENT_POINTS, auto_unwrap_row, check_row, color_management, note, physical_size, row, sub_title, tangent_space_row, unavailable,
|
||||
uv_tile_radios,
|
||||
};
|
||||
use crate::state::ProjectConfig;
|
||||
use crate::theme::caption;
|
||||
use crate::theme::{Tokens, caption};
|
||||
use crate::widgets::primary_button;
|
||||
|
||||
/// Room for the Select... button and its info icon beside the path.
|
||||
const SELECT_BUTTON_WIDTH_POINTS: f32 = 150.0;
|
||||
/// Room for an info icon at the end of a row.
|
||||
const INFO_WIDTH_POINTS: f32 = 28.0;
|
||||
const SELECT_BUTTON_WIDTH_POINTS: f32 = 190.0;
|
||||
/// Room for the title bar, the note and the button row below the scrolling form.
|
||||
const DIALOG_CHROME_HEIGHT_POINTS: f32 = 120.0;
|
||||
/// Width of the Cancel and OK buttons.
|
||||
const BUTTON_WIDTH_POINTS: f32 = 90.0;
|
||||
/// Keep a usable field when the dialog is narrowed.
|
||||
const MIN_FIELD_WIDTH_POINTS: f32 = 60.0;
|
||||
/// Initial width of the configuration dialog.
|
||||
const DEFAULT_DIALOG_WIDTH_POINTS: f32 = 460.0;
|
||||
const DEFAULT_DIALOG_WIDTH_POINTS: f32 = 560.0;
|
||||
/// Leave space around the centered dialog on short viewports.
|
||||
const DIALOG_VIEWPORT_MARGIN_POINTS: f32 = 32.0;
|
||||
|
||||
@@ -31,11 +39,13 @@ pub(crate) fn open(app: &mut TextureCraftApp) {
|
||||
// Layout resets must not reuse an identity held by a pending file picker
|
||||
static NEXT_OPENING_ID: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
app.ui.windows.import_resources = None;
|
||||
app.ui.windows.project_config = Some(ProjectConfig {
|
||||
mesh: None,
|
||||
reimport: false,
|
||||
preserve: true,
|
||||
normal_format: None,
|
||||
color_management: crate::project_form::ColorManagement::Legacy,
|
||||
confirm: false,
|
||||
project: app.session.project_id,
|
||||
opening_id: NEXT_OPENING_ID.fetch_add(1, Ordering::Relaxed),
|
||||
@@ -106,151 +116,163 @@ fn format_name(format: NormalFormat) -> &'static str {
|
||||
}
|
||||
|
||||
pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
let Some(mut config) = app.ui.windows.project_config.clone() else { return };
|
||||
let Some(mut config) = app.ui.windows.project_config.take() else { return };
|
||||
|
||||
// Choices for another project cannot be applied here
|
||||
if config.project != app.session.project_id {
|
||||
app.ui.windows.project_config = None;
|
||||
return;
|
||||
}
|
||||
|
||||
let project = &app.session.doc.project;
|
||||
let current_mesh_path = project.mesh_path.clone();
|
||||
let current_mesh_path = &project.mesh_path;
|
||||
|
||||
// Show the imported name when there is no file path
|
||||
let mesh_label = if current_mesh_path.is_empty() { project.mesh_file.clone() } else { current_mesh_path.clone() };
|
||||
let mesh_label = if current_mesh_path.is_empty() { &project.mesh_file } else { current_mesh_path };
|
||||
let source_file_available = app.session.remembered_mesh_path().is_some();
|
||||
let current_normal_format = project.normal_format;
|
||||
|
||||
// Keep each texture set's tiles together for the read-only list
|
||||
let texture_set_tiles: Vec<(String, Option<String>)> = project
|
||||
.texture_sets
|
||||
.iter()
|
||||
.map(|set| (set.name.clone(), (!set.uv_tiles.is_empty()).then(|| set.uv_tiles.iter().map(u32::to_string).collect::<Vec<_>>().join(", "))))
|
||||
.collect();
|
||||
|
||||
// Re-selecting the current path cancels an earlier choice
|
||||
let chosen_mesh = config.mesh.as_ref().filter(|chosen| **chosen != current_mesh_path).cloned();
|
||||
let chosen_mesh = config.mesh.as_deref().filter(|chosen| *chosen != current_mesh_path);
|
||||
|
||||
let mut open = true;
|
||||
let (mut ok, mut cancel, mut select) = (std::mem::take(&mut config.confirm), false, false);
|
||||
|
||||
let dialog = crate::windows::dialog("project_config", tr("Project configuration"), &mut open)
|
||||
.default_width(DEFAULT_DIALOG_WIDTH_POINTS)
|
||||
.max_height((ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN_POINTS).max(0.0))
|
||||
.vscroll(true);
|
||||
// A fixed height keeps the centered window still while its sections lay out
|
||||
let form_height = (ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN_POINTS - DIALOG_CHROME_HEIGHT_POINTS)
|
||||
.clamp(crate::project_form::MIN_FORM_HEIGHT_POINTS, crate::project_form::FORM_HEIGHT_POINTS);
|
||||
let dialog = crate::windows::dialog("project_config", tr("Project configuration"), &mut open).default_width(DEFAULT_DIALOG_WIDTH_POINTS);
|
||||
|
||||
dialog.show(ctx, |ui| {
|
||||
// Keep the project sections in the order users expect
|
||||
ui.label(caption(tr("3D MESH")));
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("3D mesh"));
|
||||
info_icon(ui, tr("The mesh file the project is built on. Hover the path to see it in full."));
|
||||
ui.set_width(DEFAULT_DIALOG_WIDTH_POINTS);
|
||||
egui::ScrollArea::vertical().id_salt("project_config_form").min_scrolled_height(form_height).max_height(form_height).auto_shrink([false, true]).show(ui, |ui| {
|
||||
// Keep the project sections in the order users expect
|
||||
ui.label(caption(tr("3D MESH")));
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(ROW_INDENT_POINTS);
|
||||
ui.label(tr("3D mesh"));
|
||||
|
||||
let display_path = chosen_mesh.clone().unwrap_or_else(|| mesh_label.clone());
|
||||
let font = egui::TextStyle::Body.resolve(ui.style());
|
||||
let path_width_points = (ui.available_width() - SELECT_BUTTON_WIDTH_POINTS).max(MIN_FIELD_WIDTH_POINTS);
|
||||
let measure = |text: &str| ui.painter().layout_no_wrap(text.to_string(), font.clone(), egui::Color32::WHITE).rect.width() <= path_width_points;
|
||||
let display_path = chosen_mesh.unwrap_or(mesh_label);
|
||||
let font = egui::TextStyle::Body.resolve(ui.style());
|
||||
let path_width_points = (ui.available_width() - SELECT_BUTTON_WIDTH_POINTS).max(MIN_FIELD_WIDTH_POINTS);
|
||||
let painter = ui.painter().clone();
|
||||
let measure = |text: &str| painter.layout_no_wrap(text.to_string(), font.clone(), egui::Color32::WHITE).rect.width() <= path_width_points;
|
||||
|
||||
if display_path.is_empty() {
|
||||
ui.weak(tr("Built-in mesh"));
|
||||
} else {
|
||||
ui.label(elide_start(&display_path, measure)).on_hover_text(&display_path);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
info_icon(ui, tr("The mesh file the project is built on. Select... chooses another one, read when you press OK."));
|
||||
select = ui.button(tr("Select...")).clicked();
|
||||
if display_path.is_empty() {
|
||||
ui.weak(tr("Built-in mesh"));
|
||||
} else {
|
||||
ui.label(elide_start(display_path, measure)).on_hover_text(display_path);
|
||||
}
|
||||
});
|
||||
});
|
||||
if chosen_mesh.is_none() && !current_mesh_path.is_empty() && !source_file_available {
|
||||
ui.colored_label(ui.visuals().error_fg_color, tr("File not found"));
|
||||
}
|
||||
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
info_icon(ui, tr("Choose another mesh file for the project. It is read when you press OK."));
|
||||
select = ui.button(tr("Select...")).clicked();
|
||||
});
|
||||
});
|
||||
if chosen_mesh.is_none() && !current_mesh_path.is_empty() && !source_file_available {
|
||||
ui.colored_label(ui.visuals().error_fg_color, tr("File not found"));
|
||||
}
|
||||
// A selected replacement always reads the mesh again
|
||||
// A missing source file cannot be reimported
|
||||
let mut reimport = config.reimport || chosen_mesh.is_some();
|
||||
let can_reimport_source = chosen_mesh.is_none() && source_file_available;
|
||||
let reimport_checkbox = check_row(
|
||||
ui,
|
||||
Some(tr("Read the mesh file again, keeping the layers and painted strokes")),
|
||||
|ui| ui.add_enabled(can_reimport_source, egui::Checkbox::new(&mut reimport, tr("Reimport mesh"))),
|
||||
|_| {},
|
||||
);
|
||||
|
||||
ui.add_space(4.0);
|
||||
if can_reimport_source {
|
||||
config.reimport = reimport;
|
||||
} else if chosen_mesh.is_none() {
|
||||
reimport_checkbox.on_disabled_hover_text(tr("There is no mesh file to read again. Select one."));
|
||||
}
|
||||
|
||||
// A selected replacement always reads the mesh again
|
||||
// A missing source file cannot be reimported
|
||||
let mut reimport = config.reimport || chosen_mesh.is_some();
|
||||
let can_reimport_source = chosen_mesh.is_none() && source_file_available;
|
||||
let reimport_checkbox = ui
|
||||
.horizontal(|ui| {
|
||||
let checkbox = ui.add_enabled(can_reimport_source, egui::Checkbox::new(&mut reimport, tr("Reimport mesh")));
|
||||
info_icon(ui, tr("Read the mesh file again, keeping the layers and painted strokes"));
|
||||
checkbox
|
||||
})
|
||||
.inner;
|
||||
ui.add_space(12.0);
|
||||
ui.label(caption(tr("PROJECT SETTINGS")));
|
||||
ui.add_space(4.0);
|
||||
let shown_format = config.normal_format.unwrap_or(current_normal_format);
|
||||
row(
|
||||
ui,
|
||||
tr("Normal map format"),
|
||||
Some(tr("Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it.")),
|
||||
|ui| {
|
||||
egui::ComboBox::from_id_salt(tr("Normal map format"))
|
||||
.width(FIELD_WIDTH_POINTS)
|
||||
.wrap_mode(egui::TextWrapMode::Truncate)
|
||||
.selected_text(format_name(shown_format))
|
||||
.show_ui(ui, |ui| {
|
||||
for format in [NormalFormat::OpenGl, NormalFormat::DirectX] {
|
||||
if ui.selectable_label(format == shown_format, format_name(format)).clicked() {
|
||||
config.normal_format = (format != current_normal_format).then_some(format);
|
||||
}
|
||||
}
|
||||
})
|
||||
.response
|
||||
.on_hover_text(tr(
|
||||
"For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export",
|
||||
));
|
||||
},
|
||||
);
|
||||
tangent_space_row(ui);
|
||||
|
||||
if can_reimport_source {
|
||||
config.reimport = reimport;
|
||||
} else if chosen_mesh.is_none() {
|
||||
reimport_checkbox.on_disabled_hover_text(tr("There is no mesh file to read again. Select one."));
|
||||
}
|
||||
// Texture Set Settings owns UV tile changes
|
||||
ui.add_space(4.0);
|
||||
sub_title(ui, tr("UV Tile settings (UDIMs)"), Some(tr("View the UV tiles assigned to each texture set")));
|
||||
let tiles_hint = tr("Change the UV tiles of a texture set in Texture Set Settings");
|
||||
note(ui, tiles_hint);
|
||||
let mut has_tiles = project.texture_sets.iter().any(|set| !set.uv_tiles.is_empty());
|
||||
|
||||
ui.add_space(8.0);
|
||||
ui.label(caption(tr("Import settings")));
|
||||
check_row(ui, None, |ui| ui.add_enabled(false, egui::Checkbox::new(&mut has_tiles, tr("Use UV Tile workflow"))), |_| {})
|
||||
.on_disabled_hover_ui(|ui| {
|
||||
ui.set_max_width(ui.spacing().tooltip_width);
|
||||
if !has_tiles {
|
||||
ui.label(tr("No UV tiles"));
|
||||
}
|
||||
|
||||
// Import settings matter only when a mesh will be read
|
||||
let importing = chosen_mesh.is_some() || (config.reimport && source_file_available);
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_enabled(importing, egui::Checkbox::new(&mut config.preserve, tr("Preserve stroke positions on mesh")));
|
||||
info_icon(ui, tr("Painted strokes follow the surface when the new mesh's UVs differ"));
|
||||
});
|
||||
|
||||
ui.add_space(12.0);
|
||||
ui.label(caption(tr("PROJECT SETTINGS")));
|
||||
ui.add_space(4.0);
|
||||
let shown_format = config.normal_format.unwrap_or(current_normal_format);
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Normal map format"));
|
||||
egui::ComboBox::from_id_salt(tr("Normal map format"))
|
||||
.width((ui.available_width() - INFO_WIDTH_POINTS).max(MIN_FIELD_WIDTH_POINTS))
|
||||
.wrap_mode(egui::TextWrapMode::Truncate)
|
||||
.selected_text(format_name(shown_format))
|
||||
.show_ui(ui, |ui| {
|
||||
for format in [NormalFormat::OpenGl, NormalFormat::DirectX] {
|
||||
if ui.selectable_label(format == shown_format, format_name(format)).clicked() {
|
||||
config.normal_format = (format != current_normal_format).then_some(format);
|
||||
for set in project.texture_sets.iter().filter(|set| !set.uv_tiles.is_empty()) {
|
||||
let tiles = set.uv_tiles.iter().map(u32::to_string).collect::<Vec<_>>().join(", ");
|
||||
if project.texture_sets.len() > 1 {
|
||||
ui.label(trf("{set}: {tiles}", &[("set", &set.name), ("tiles", &tiles)]));
|
||||
} else {
|
||||
ui.label(tiles);
|
||||
}
|
||||
}
|
||||
})
|
||||
.response
|
||||
.on_hover_text(tr(
|
||||
"For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export",
|
||||
));
|
||||
info_icon(ui, tr("Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it."));
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
});
|
||||
uv_tile_radios(ui, false, tiles_hint);
|
||||
|
||||
// Texture Set Settings owns UV tile changes
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("UV Tile settings (UDIMs)"));
|
||||
info_icon(ui, tr("The UV tiles (UDIMs) of each texture set, shown for reference. Change them in Texture Set Settings."));
|
||||
});
|
||||
if texture_set_tiles.iter().all(|(_, tile_text)| tile_text.is_none()) {
|
||||
ui.label(egui::RichText::new(tr("No UV tiles")).weak());
|
||||
}
|
||||
for (name, tile_text) in texture_set_tiles.iter().filter(|(_, tile_text)| tile_text.is_some()) {
|
||||
let tile_list = tile_text.as_deref().unwrap_or_default();
|
||||
ui.label(
|
||||
egui::RichText::new(if texture_set_tiles.len() > 1 {
|
||||
trf("{set}: {tiles}", &[("set", name), ("tiles", &tile_list)])
|
||||
} else {
|
||||
tile_list.to_string()
|
||||
})
|
||||
.weak(),
|
||||
ui.add_space(4.0);
|
||||
sub_title(ui, tr("Import settings"), None);
|
||||
check_row(
|
||||
ui,
|
||||
Some(tr("Keep the cameras stored in the mesh file")),
|
||||
|ui| unavailable(ui.add_enabled(false, egui::Checkbox::new(&mut false, tr("Import cameras")))),
|
||||
|_| {},
|
||||
);
|
||||
}
|
||||
ui.label(egui::RichText::new(tr("Change them in Texture Set Settings")).small().weak());
|
||||
|
||||
ui.add_space(12.0);
|
||||
ui.label(egui::RichText::new(tr("Choosing or reimporting a mesh recomputes all channels.")).small().weak());
|
||||
// Import settings matter only when a mesh will be read
|
||||
let importing = chosen_mesh.is_some() || (config.reimport && source_file_available);
|
||||
check_row(
|
||||
ui,
|
||||
Some(tr("Painted strokes follow the surface when the new mesh's UVs differ")),
|
||||
|ui| ui.add_enabled(importing, egui::Checkbox::new(&mut config.preserve, tr("Preserve stroke positions on mesh"))),
|
||||
|_| {},
|
||||
);
|
||||
auto_unwrap_row(ui);
|
||||
|
||||
ui.add_space(4.0);
|
||||
physical_size(ui, "project_config_physical_size", false);
|
||||
color_management(ui, "project_config_color_management", &mut config.color_management);
|
||||
});
|
||||
|
||||
ui.add_space(8.0);
|
||||
ui.label(egui::RichText::new(tr("Changing the mesh or normal format can recalculate texture channels.")).color(Tokens::get(ui.ctx()).warning));
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ok |= ui.add(primary_button(ui, tr("OK"))).clicked();
|
||||
cancel = ui.button(tr("Cancel")).clicked();
|
||||
ok |= ui.add(primary_button(ui, tr("OK")).min_size(egui::vec2(BUTTON_WIDTH_POINTS, 0.0))).clicked();
|
||||
cancel = ui.add(egui::Button::new(tr("Cancel")).min_size(egui::vec2(BUTTON_WIDTH_POINTS, 0.0))).clicked();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -261,17 +283,17 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
app.ask_file(dialog, Bound::Project, move |app, paths| {
|
||||
let Some(path) = paths.first().map(|p| p.display().to_string()) else { return };
|
||||
|
||||
let current_mesh_path = app.session.doc.project.mesh_path.clone();
|
||||
let current_mesh_path = &app.session.doc.project.mesh_path;
|
||||
if let Some(config) = app.ui.windows.project_config.as_mut().filter(|config| config.opening_id == opening_id) {
|
||||
// Re-selecting the source file drops an earlier choice
|
||||
config.mesh = (path != current_mesh_path).then_some(path);
|
||||
config.mesh = (path != *current_mesh_path).then_some(path);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Apply the mesh first so a failed mesh change leaves the format untouched
|
||||
let mut mesh_applied = false;
|
||||
let done = ok && {
|
||||
let done = ok && !cancel && open && {
|
||||
let reimport = config.reimport.then(|| app.session.remembered_mesh_path().map(str::to_string)).flatten();
|
||||
mesh_applied = if config.reimport && chosen_mesh.is_none() && reimport.is_none() {
|
||||
// Drop a stale reimport tick so the user can retry the remaining settings
|
||||
@@ -279,7 +301,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
config.reimport = false;
|
||||
false
|
||||
} else {
|
||||
match mesh_command(chosen_mesh.as_deref(), reimport.as_deref(), config.preserve) {
|
||||
match mesh_command(chosen_mesh, reimport.as_deref(), config.preserve) {
|
||||
Some((command, params)) => app.run(command, params).is_some(),
|
||||
None => true,
|
||||
}
|
||||
@@ -296,16 +318,13 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
};
|
||||
|
||||
if done || cancel || !open {
|
||||
app.ui.windows.project_config = None;
|
||||
} else if let Some(stored) = app.ui.windows.project_config.as_mut() {
|
||||
// A file answer arrives later through the stored state
|
||||
(stored.reimport, stored.preserve, stored.normal_format, stored.confirm) = (config.reimport, config.preserve, config.normal_format, false);
|
||||
|
||||
if !done && !cancel && open {
|
||||
// A format retry must not reimport an already changed mesh
|
||||
if ok && mesh_applied {
|
||||
(stored.mesh, stored.reimport) = (None, false);
|
||||
(config.mesh, config.reimport) = (None, false);
|
||||
}
|
||||
|
||||
app.ui.windows.project_config = Some(config);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
//! Rows and sections that New project and Edit > Project Configuration share: the label, control
|
||||
//! and info icon of a setting, collapsible sections, and the settings the engine does not have
|
||||
//! yet (shown disabled, with a hover hint that says so).
|
||||
|
||||
use egui::{Response, RichText, Sense, Ui};
|
||||
|
||||
pub use crate::color_management::ColorManagement;
|
||||
use crate::dock::info_icon;
|
||||
use crate::i18n::{n_, tr};
|
||||
use crate::theme::{Tokens, caption};
|
||||
use crate::widgets::section_chevron;
|
||||
|
||||
/// Hover hint of a control whose function TextureCraft does not have yet.
|
||||
pub const NOT_AVAILABLE: &str = n_("Not available yet");
|
||||
|
||||
/// Hover hint of the Color management dropdown while OpenColorIO is chosen.
|
||||
pub const OCIO_NOT_AVAILABLE: &str = n_("OpenColorIO is not available yet. The project uses Legacy.");
|
||||
|
||||
/// Width of the dropdowns and fields at the right of a row.
|
||||
pub(crate) const FIELD_WIDTH_POINTS: f32 = 220.0;
|
||||
|
||||
/// Tallest the scrolling form of the two windows grows (the rest scrolls).
|
||||
pub(crate) const FORM_HEIGHT_POINTS: f32 = 760.0;
|
||||
|
||||
/// Scrolling form height when viewport space is limited.
|
||||
pub(crate) const MIN_FORM_HEIGHT_POINTS: f32 = 120.0;
|
||||
|
||||
/// Indent of the rows below a section title.
|
||||
pub(crate) const ROW_INDENT_POINTS: f32 = 16.0;
|
||||
|
||||
/// `response` with the not-available hint while it is disabled.
|
||||
pub(crate) fn unavailable(response: Response) -> Response {
|
||||
response.on_disabled_hover_text(tr(NOT_AVAILABLE))
|
||||
}
|
||||
|
||||
/// A row: `label` at the left, then `control` right-aligned before the info icon (`info`).
|
||||
pub(crate) fn row<R>(ui: &mut Ui, label: &str, info: Option<&str>, control: impl FnOnce(&mut Ui) -> R) -> R {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(ROW_INDENT_POINTS);
|
||||
ui.label(label);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
info_slot(ui, info);
|
||||
control(ui)
|
||||
})
|
||||
.inner
|
||||
})
|
||||
.inner
|
||||
}
|
||||
|
||||
/// A row that starts with its control (a checkbox or radio button) and ends with the info icon.
|
||||
/// `trailing` adds a control just before the icon (a button).
|
||||
pub(crate) fn check_row<R>(ui: &mut Ui, info: Option<&str>, control: impl FnOnce(&mut Ui) -> R, trailing: impl FnOnce(&mut Ui)) -> R {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(ROW_INDENT_POINTS);
|
||||
let inner = control(ui);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
info_slot(ui, info);
|
||||
trailing(ui);
|
||||
});
|
||||
inner
|
||||
})
|
||||
.inner
|
||||
}
|
||||
|
||||
fn info_slot(ui: &mut Ui, info: Option<&str>) {
|
||||
match info {
|
||||
Some(text) => info_icon(ui, text),
|
||||
|
||||
// An invisible icon keeps the controls of rows without one in the same column
|
||||
None => {
|
||||
ui.add_visible(false, egui::Label::new(egui_phosphor::regular::INFO));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A bold sub-section title such as Import settings, with an optional info icon at the end.
|
||||
pub(crate) fn sub_title(ui: &mut Ui, title: &str, info: Option<&str>) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(ROW_INDENT_POINTS);
|
||||
ui.label(caption(title));
|
||||
if let Some(text) = info {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| info_icon(ui, text));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A dim italic note in a section.
|
||||
pub(crate) fn note(ui: &mut Ui, text: &str) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(2.0 * ROW_INDENT_POINTS);
|
||||
ui.add(egui::Label::new(RichText::new(text).italics().color(Tokens::get(ui.ctx()).text_dim)).wrap());
|
||||
});
|
||||
}
|
||||
|
||||
/// A dropdown that cannot be opened, showing `value`, with the not-available hint.
|
||||
pub(crate) fn disabled_combo(ui: &mut Ui, id: &str, value: &str) -> Response {
|
||||
let response =
|
||||
ui.add_enabled_ui(false, |ui| egui::ComboBox::from_id_salt(id).width(FIELD_WIDTH_POINTS).selected_text(value).show_ui(ui, |_| {}).response).inner;
|
||||
unavailable(response)
|
||||
}
|
||||
|
||||
/// A collapsible section: a chevron and `title` (clicking either toggles it), an optional info
|
||||
/// icon at the end of the header, and `body` while open.
|
||||
pub(crate) fn collapsible(ui: &mut Ui, id: &str, title: &str, default_open: bool, info: Option<&str>, body: impl FnOnce(&mut Ui)) {
|
||||
let id = ui.make_persistent_id(id);
|
||||
let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, default_open);
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(ROW_INDENT_POINTS);
|
||||
let header = ui
|
||||
.horizontal(|ui| {
|
||||
ui.add(egui::Label::new(section_chevron(ui, state.is_open())).selectable(false));
|
||||
ui.add(egui::Label::new(caption(title)).selectable(false));
|
||||
})
|
||||
.response
|
||||
.interact(Sense::click());
|
||||
if header.clicked() {
|
||||
state.toggle(ui);
|
||||
}
|
||||
if let Some(text) = info {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| info_icon(ui, text));
|
||||
}
|
||||
});
|
||||
state.show_body_unindented(ui, |ui| {
|
||||
ui.indent(id.with("body"), body);
|
||||
});
|
||||
}
|
||||
|
||||
/// "Compute tangent space per fragment" (not available yet, so unticked and disabled).
|
||||
pub(crate) fn tangent_space_row(ui: &mut Ui) {
|
||||
check_row(
|
||||
ui,
|
||||
Some(tr("Compute the tangent space of normal maps per pixel instead of per vertex")),
|
||||
|ui| unavailable(ui.add_enabled(false, egui::Checkbox::new(&mut false, tr("Compute tangent space per fragment")))),
|
||||
|_| {},
|
||||
);
|
||||
}
|
||||
|
||||
/// The UV tile workflow radios under "Use UV Tile workflow": per material (what the UV tile
|
||||
/// workflow does) or one texture set per tile (not available yet). `enabled` while the workflow
|
||||
/// can be chosen and is on.
|
||||
pub(crate) fn uv_tile_radios(ui: &mut Ui, enabled: bool, disabled_hint: &str) {
|
||||
ui.indent("uv_tile_radios", |ui| {
|
||||
let preserve = check_row(
|
||||
ui,
|
||||
Some(tr("Each material keeps its UV tiles in one texture set, and strokes paint across tiles")),
|
||||
|ui| ui.add_enabled(enabled, egui::RadioButton::new(true, tr("Keep UV tiles together per material"))),
|
||||
|_| {},
|
||||
);
|
||||
preserve.on_disabled_hover_text(disabled_hint);
|
||||
check_row(
|
||||
ui,
|
||||
Some(tr("Each UV tile becomes a texture set of its own")),
|
||||
|ui| unavailable(ui.add_enabled(false, egui::RadioButton::new(false, tr("Use a separate texture set for each tile")))),
|
||||
|_| {},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// Import settings ▸ Auto-unwrap and its options. Meshes without UVs are always unwrapped, so the
|
||||
/// box is ticked; turning it off and the options are not available yet.
|
||||
pub(crate) fn auto_unwrap_row(ui: &mut Ui) {
|
||||
check_row(
|
||||
ui,
|
||||
Some(tr("Generate UVs for meshes that have none")),
|
||||
|ui| unavailable(ui.add_enabled(false, egui::Checkbox::new(&mut true, tr("Auto-unwrap")))),
|
||||
|ui| {
|
||||
unavailable(ui.add_enabled(false, egui::Button::new(tr("Auto-unwrap options"))));
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// The Physical size section: the mesh file's own unit scale is what TextureCraft uses; a custom
|
||||
/// scale and physical-size fill layers are not available yet.
|
||||
pub(crate) fn physical_size(ui: &mut Ui, id: &str, default_open: bool) {
|
||||
const UNIT_FIELD_WIDTH_POINTS: f32 = 60.0;
|
||||
|
||||
collapsible(ui, id, tr("Physical size"), default_open, Some(tr("The real-world size of one unit of the mesh")), |ui| {
|
||||
check_row(ui, Some(tr("Use the unit scale stored in the mesh file")), |ui| ui.radio(true, tr("Use the mesh file’s unit scale")), |_| {});
|
||||
check_row(
|
||||
ui,
|
||||
Some(tr("Set the size of one unit yourself")),
|
||||
|ui| unavailable(ui.add_enabled(false, egui::RadioButton::new(false, tr("Custom unit scale")))),
|
||||
|_| {},
|
||||
);
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(3.0 * ROW_INDENT_POINTS);
|
||||
ui.label(tr("1 unit ="));
|
||||
unavailable(ui.add_enabled(false, egui::TextEdit::singleline(&mut String::new()).desired_width(UNIT_FIELD_WIDTH_POINTS)));
|
||||
ui.label(tr("cm"));
|
||||
});
|
||||
check_row(
|
||||
ui,
|
||||
Some(tr("Fill layers of applied materials are scaled in physical size instead of UV space")),
|
||||
|ui| unavailable(ui.add_enabled(false, egui::Checkbox::new(&mut false, tr("Scale material fills in real-world units")))),
|
||||
|_| {},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// Rows of the OpenColorIO settings: (label, shown value, info). They are not available yet.
|
||||
const OCIO_CONFIGURATION: [(&str, &str, Option<&str>); 1] =
|
||||
[(n_("OpenColorIO configuration"), "ACES 2.0", Some(n_("The OpenColorIO configuration that defines the color spaces")))];
|
||||
const OCIO_IMPORT: [(&str, &str, Option<&str>); 4] = [
|
||||
(n_("8 bit images"), "sRGB Encoded Rec.709 (sRGB)", None),
|
||||
(n_("16 bit images"), "sRGB Encoded Rec.709 (sRGB)", None),
|
||||
(n_("Floating point images"), "Linear Rec.709 (sRGB)", None),
|
||||
(n_("Auto detect color spaces"), n_("Parse file name"), Some(n_("Read an imported image's color space from its file name"))),
|
||||
];
|
||||
const OCIO_EXPORT: [(&str, &str, Option<&str>); 3] = [
|
||||
(n_("8 bit images"), "sRGB Encoded Rec.709 (sRGB)", None),
|
||||
(n_("16 bit images"), "sRGB Encoded Rec.709 (sRGB)", None),
|
||||
(n_("Floating point images"), "ACEScg", None),
|
||||
];
|
||||
|
||||
/// The Color management section. `mode` is the dropdown's choice: Legacy shows the working color
|
||||
/// space. OpenColorIO previews disabled settings while the project continues to use Legacy.
|
||||
pub(crate) fn color_management(ui: &mut Ui, id: &str, mode: &mut ColorManagement) {
|
||||
collapsible(ui, id, tr("Color management"), true, None, |ui| {
|
||||
ui.label(caption(tr("Configuration")));
|
||||
row(ui, tr("Color management"), Some(tr("Legacy works in linear sRGB. OpenColorIO manages color through a configuration")), |ui| {
|
||||
let response = egui::ComboBox::from_id_salt(format!("{id}_mode"))
|
||||
.width(FIELD_WIDTH_POINTS)
|
||||
.selected_text(tr(mode.label()))
|
||||
.show_ui(ui, |ui| {
|
||||
for choice in [ColorManagement::Legacy, ColorManagement::OpenColorIo] {
|
||||
ui.selectable_value(mode, choice, tr(choice.label()));
|
||||
}
|
||||
})
|
||||
.response;
|
||||
if *mode == ColorManagement::OpenColorIo {
|
||||
response.on_hover_text(tr(OCIO_NOT_AVAILABLE));
|
||||
}
|
||||
});
|
||||
if *mode == ColorManagement::OpenColorIo {
|
||||
for (label, value, info) in OCIO_CONFIGURATION {
|
||||
row(ui, tr(label), info.map(tr), |ui| disabled_combo(ui, &format!("{id}_{label}"), tr(value)));
|
||||
}
|
||||
row(ui, tr("Configuration file"), Some(tr("A custom OpenColorIO configuration file")), |ui| {
|
||||
unavailable(ui.add_enabled(false, egui::TextEdit::singleline(&mut String::new()).desired_width(FIELD_WIDTH_POINTS)));
|
||||
});
|
||||
}
|
||||
|
||||
ui.add_space(4.0);
|
||||
ui.label(caption(tr("Color settings")));
|
||||
let working_space = if *mode == ColorManagement::OpenColorIo { "ACEScg" } else { "Linear - sRGB Chrominance (ITU-R BT.709)" };
|
||||
row(ui, tr("Working color space"), Some(tr("The color space layers are blended in")), |ui| ui.label(working_space));
|
||||
if *mode != ColorManagement::OpenColorIo {
|
||||
return;
|
||||
}
|
||||
|
||||
row(ui, tr("Standard sRGB color space"), Some(tr("The color space of sRGB images and colors")), |ui| {
|
||||
disabled_combo(ui, &format!("{id}_srgb"), "sRGB Encoded Rec.709 (sRGB)")
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
ui.label(caption(tr("Bitmap import color space defaults")));
|
||||
for (label, value, info) in OCIO_IMPORT {
|
||||
row(ui, tr(label), info.map(tr), |ui| disabled_combo(ui, &format!("{id}_import_{label}"), tr(value)));
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
ui.label(caption(tr("Materials")));
|
||||
row(ui, tr("Material color space default"), Some(tr("The color space of material inputs that do not state one")), |ui| {
|
||||
disabled_combo(ui, &format!("{id}_material"), "sRGB Encoded Rec.709 (sRGB)")
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
ui.label(caption(tr("Export color spaces")));
|
||||
for (label, value, info) in OCIO_EXPORT {
|
||||
row(ui, tr(label), info.map(tr), |ui| disabled_combo(ui, &format!("{id}_export_{label}"), tr(value)));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -255,8 +255,8 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let filter = app.ui.shelf_filter.to_lowercase();
|
||||
scan_library(app);
|
||||
let all = ShelfEntry::all(app);
|
||||
let paths = crate::shelf_folders::with_every_library(crate::shelf_folders::paths(&all));
|
||||
let all_entries = ShelfEntry::all(app);
|
||||
let paths = crate::shelf_folders::with_every_library(crate::shelf_folders::paths(&all_entries));
|
||||
|
||||
// A folder that is gone (its last image removed) shows everything again
|
||||
if !paths.iter().any(|path| path.starts_with(&app.ui.shelf_path)) {
|
||||
@@ -265,12 +265,22 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
|
||||
let folder = app.ui.shelf_path.clone();
|
||||
let picked_tab = app.ui.shelf_tab;
|
||||
let searched: Vec<ShelfEntry> = all.into_iter().filter(|entry| entry.matches(&filter)).collect();
|
||||
let mut applicable = crate::shelf_folders::paths(searched.iter().filter(|entry| crate::shelf_tabs::shows(picked_tab, entry.tab())));
|
||||
let matching: Vec<ShelfEntry> = searched.into_iter().filter(|entry| entry.in_folder(&folder)).collect();
|
||||
let mut matching: Vec<ShelfEntry> = all_entries.into_iter().filter(|entry| entry.matches(&filter)).collect();
|
||||
let path_pane_open = app.ui.shelf_panes.filter_by_path;
|
||||
let mut applicable = if path_pane_open {
|
||||
crate::shelf_folders::paths(matching.iter().filter(|entry| crate::shelf_tabs::shows(picked_tab, entry.tab())))
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
// All libraries includes every result without constructing an asset path
|
||||
if !folder.is_empty() {
|
||||
matching.retain(|entry| entry.in_folder(&folder));
|
||||
}
|
||||
|
||||
let mut counts: Vec<usize> = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect();
|
||||
|
||||
// Saved smart materials list under the grid rather than as tiles, so they count apart
|
||||
// Saved smart materials and masks count toward their tabs even without tiles
|
||||
let in_user_library = folder.len() <= 1 && folder.first().is_none_or(|library| library == crate::shelf_entry::USER);
|
||||
let saved_materials_matching = saved_matching(app, &filter, false);
|
||||
let saved_masks_matching = saved_matching(app, &filter, true);
|
||||
@@ -278,7 +288,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
if in_user_library && let Some(count) = TABS.iter().position(|(shown, _, _)| *shown == tab).and_then(|position| counts.get_mut(position)) {
|
||||
*count += saved;
|
||||
}
|
||||
if saved > 0 && crate::shelf_tabs::shows(picked_tab, tab) {
|
||||
if path_pane_open && saved > 0 && crate::shelf_tabs::shows(picked_tab, tab) {
|
||||
applicable.push(vec![crate::shelf_entry::USER.to_string()]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,29 @@
|
||||
//! The shelf's side panes left of the grid, toggled from the toolbar: saved searches and the folder tree
|
||||
|
||||
use egui::{RichText, Ui};
|
||||
use craft_ui::layout::{ResizeHandle, ResizeHandleStyle, SplitAxis, SplitLayout, SplitSize, split_rect};
|
||||
use egui::{Rect, RichText, Ui, UiBuilder};
|
||||
use egui_phosphor::regular as ic;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::i18n::tr;
|
||||
use crate::i18n::{n_, tr};
|
||||
use crate::saved_search::SavedSearch;
|
||||
use crate::shelf::TABS;
|
||||
use crate::theme::Tokens;
|
||||
use crate::widgets::icon_button;
|
||||
|
||||
/// The panes' column width as a fraction of the panel, and its least width in points
|
||||
const COLUMN_FRACTION: f32 = 0.45;
|
||||
const COLUMN_MIN_WIDTH: f32 = 110.0;
|
||||
/// Maximum share of the column used by saved searches while both panes are open
|
||||
const SAVED_SEARCHES_HEIGHT_FRACTION: f32 = 0.45;
|
||||
const COLUMN_MIN_WIDTH_POINTS: f32 = 110.0;
|
||||
const SPLITTER_HEIGHT_POINTS: f32 = 6.0;
|
||||
const PANE_MIN_HEIGHT_POINTS: f32 = 40.0;
|
||||
/// The hint on rows whose function TextureCraft lacks
|
||||
pub(crate) const NOT_AVAILABLE: &str = n_("Not available yet");
|
||||
/// The reference's built-in saved searches after "All", shown greyed until they work
|
||||
const BUILT_IN_SEARCHES: [&str; 3] = [n_("Favorites"), n_("3D Assets"), n_("Flattened layers")];
|
||||
/// The reference's font libraries after the asset libraries, shown greyed until they work
|
||||
const FONT_LIBRARIES: [&str; 2] = [n_("System fonts"), n_("User fonts")];
|
||||
/// The pane header's caption size in points
|
||||
const HEADER_SIZE: f32 = 10.0;
|
||||
const HEADER_FONT_SIZE_POINTS: f32 = 10.0;
|
||||
|
||||
/// Which side panes are open
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -42,27 +48,80 @@ pub(crate) fn toggles(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) {
|
||||
/// The width of the panes' column in a panel `width` wide, or None while no pane is open
|
||||
pub(crate) fn column_width(app: &TextureCraftApp, width: f32) -> Option<f32> {
|
||||
let panes = &app.ui.shelf_panes;
|
||||
(panes.saved_searches || panes.filter_by_path).then(|| (width * COLUMN_FRACTION).max(COLUMN_MIN_WIDTH).min(width))
|
||||
(panes.saved_searches || panes.filter_by_path).then(|| (width * COLUMN_FRACTION).max(COLUMN_MIN_WIDTH_POINTS).min(width))
|
||||
}
|
||||
|
||||
/// The open panes, top to bottom; the tree shows `paths`, or `applicable` while it hides folders with nothing matching
|
||||
/// Draws the open panes and a divider when both are visible.
|
||||
pub(crate) fn column(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec<String>], applicable: &[Vec<String>]) {
|
||||
// Names past the narrow column end in "…" rather than breaking mid-word
|
||||
// Keep long names on one line in the narrow column
|
||||
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
|
||||
if app.ui.shelf_panes.saved_searches {
|
||||
saved_searches(app, ui);
|
||||
|
||||
let rect = ui.available_rect_before_wrap();
|
||||
if rect.width() <= 0.0 || rect.height() <= 0.0 {
|
||||
return;
|
||||
}
|
||||
if app.ui.shelf_panes.filter_by_path {
|
||||
if app.ui.shelf_panes.saved_searches {
|
||||
ui.separator();
|
||||
|
||||
let show_saved_searches = app.ui.shelf_panes.saved_searches;
|
||||
let show_path_filter = app.ui.shelf_panes.filter_by_path;
|
||||
let (search_rect, path_rect) = if show_saved_searches && show_path_filter {
|
||||
let Some(layout) = splitter(app, ui, rect) else { return };
|
||||
(layout.first, layout.second)
|
||||
} else {
|
||||
(rect, rect)
|
||||
};
|
||||
|
||||
if show_saved_searches && search_rect.height() > 0.0 {
|
||||
let mut pane = ui.new_child(UiBuilder::new().id_salt("saved_searches").max_rect(search_rect));
|
||||
pane.set_clip_rect(search_rect.intersect(ui.clip_rect()));
|
||||
saved_searches(app, &mut pane);
|
||||
}
|
||||
if show_path_filter && path_rect.height() > 0.0 {
|
||||
let mut pane = ui.new_child(UiBuilder::new().id_salt("path_filter").max_rect(path_rect));
|
||||
pane.set_clip_rect(path_rect.intersect(ui.clip_rect()));
|
||||
filter_by_path(app, &mut pane, paths, applicable);
|
||||
}
|
||||
|
||||
ui.allocate_rect(rect, egui::Sense::hover());
|
||||
}
|
||||
|
||||
/// Resize the two panes with the shared pointer, keyboard and accessibility control.
|
||||
fn splitter(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect) -> Option<SplitLayout> {
|
||||
// Callers can set the public share directly without loading settings
|
||||
if !app.ui.shelf_panes_split.is_finite() {
|
||||
app.ui.shelf_panes_split = crate::state::default_shelf_panes_split();
|
||||
}
|
||||
|
||||
// Leave room for a header and a complete row when both minima fit
|
||||
let spacing = ui.spacing();
|
||||
let minimum_points = PANE_MIN_HEIGHT_POINTS.max(2.0 * spacing.interact_size.y + spacing.item_spacing.y);
|
||||
let axis = SplitAxis::Vertical;
|
||||
let size = SplitSize::Ratio(app.ui.shelf_panes_split);
|
||||
let mut layout = split_rect(rect, axis, size, SPLITTER_HEIGHT_POINTS, minimum_points)?;
|
||||
let available_points = layout.available();
|
||||
|
||||
let visuals = ui.visuals();
|
||||
let line_stroke = visuals.widgets.noninteractive.bg_stroke;
|
||||
if available_points > 2.0 * minimum_points {
|
||||
let colors =
|
||||
ResizeHandleStyle { hovered: visuals.widgets.hovered.bg_fill, dragged: visuals.widgets.active.bg_fill, focused: visuals.selection.bg_fill };
|
||||
let resize = ResizeHandle::new(ui.scope_id().with("shelf_panes_splitter"), axis, layout.divider, tr("Resize Assets filter panes"), colors)
|
||||
.hit_margin(0.0)
|
||||
.value(layout.first_size(), minimum_points..=available_points - minimum_points)
|
||||
.show(ui);
|
||||
if resize.delta != 0.0
|
||||
&& let Some(SplitSize::Ratio(share)) = layout.resized(size, resize.delta, minimum_points)
|
||||
{
|
||||
app.ui.shelf_panes_split = share;
|
||||
layout = split_rect(rect, axis, SplitSize::Ratio(share), SPLITTER_HEIGHT_POINTS, minimum_points)?;
|
||||
}
|
||||
let shown = if app.ui.shelf_panes.hide_non_applicable { applicable } else { paths };
|
||||
filter_by_path(app, ui, shown);
|
||||
}
|
||||
|
||||
ui.painter().hline(layout.divider.x_range(), layout.divider.center().y, line_stroke);
|
||||
Some(layout)
|
||||
}
|
||||
|
||||
/// "All libraries", then each library's folders as a tree; a click shows that folder
|
||||
fn filter_by_path(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec<String>]) {
|
||||
fn filter_by_path(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec<String>], applicable: &[Vec<String>]) {
|
||||
let size = ui.spacing().interact_size.y;
|
||||
header(ui, tr("Filter by path"), |ui| {
|
||||
let hiding = app.ui.shelf_panes.hide_non_applicable;
|
||||
@@ -71,13 +130,25 @@ fn filter_by_path(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec<String>])
|
||||
}
|
||||
});
|
||||
|
||||
let hiding = app.ui.shelf_panes.hide_non_applicable;
|
||||
let shown_paths = if hiding { applicable } else { paths };
|
||||
let mut picked = None;
|
||||
egui::ScrollArea::vertical().id_salt("shelf_path_tree").auto_shrink([false, true]).show(ui, |ui| {
|
||||
|
||||
// Use the real pane height so the last row can scroll clear of the clip edge
|
||||
egui::ScrollArea::vertical().id_salt("shelf_path_tree").min_scrolled_height(0.0).auto_shrink([false, true]).show(ui, |ui| {
|
||||
if ui.selectable_label(app.ui.shelf_path.is_empty(), tr("All libraries")).clicked() {
|
||||
picked = Some(Vec::new());
|
||||
}
|
||||
folders(ui, paths, &[], &app.ui.shelf_path, &mut picked);
|
||||
folders(ui, shown_paths, &[], &app.ui.shelf_path, &mut picked);
|
||||
|
||||
// Font libraries contain no matching assets while they are unavailable
|
||||
if !hiding {
|
||||
for library in FONT_LIBRARIES {
|
||||
ui.add_enabled(false, egui::Button::selectable(false, tr(library))).on_disabled_hover_text(tr(NOT_AVAILABLE));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if let Some(path) = picked {
|
||||
app.ui.shelf_path = path;
|
||||
}
|
||||
@@ -89,7 +160,9 @@ fn folders(ui: &mut Ui, paths: &[Vec<String>], prefix: &[String], current: &[Str
|
||||
let path: Vec<String> = prefix.iter().cloned().chain([child.clone()]).collect();
|
||||
let name = crate::shelf_folders::name(prefix.len(), &child);
|
||||
let selected = current == path.as_slice();
|
||||
if crate::shelf_folders::children(paths, &path).is_empty() {
|
||||
let has_children = paths.iter().any(|candidate| candidate.len() > path.len() && candidate.starts_with(&path));
|
||||
|
||||
if !has_children {
|
||||
ui.indent(("shelf_path_leaf", &path), |ui| {
|
||||
if ui.selectable_label(selected, name).clicked() {
|
||||
*picked = Some(path.clone());
|
||||
@@ -114,7 +187,7 @@ fn folders(ui: &mut Ui, paths: &[Vec<String>], prefix: &[String], current: &[Str
|
||||
fn header(ui: &mut Ui, title: &str, button: impl FnOnce(&mut Ui)) {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(title.to_uppercase()).size(HEADER_SIZE).color(tokens.text_dim));
|
||||
ui.label(RichText::new(title.to_uppercase()).size(HEADER_FONT_SIZE_POINTS).color(tokens.text_dim));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), button);
|
||||
});
|
||||
}
|
||||
@@ -122,54 +195,76 @@ fn header(ui: &mut Ui, title: &str, button: impl FnOnce(&mut Ui)) {
|
||||
/// "All", then the saved queries; the header's button saves the current one, a right-click deletes one
|
||||
fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let size = ui.spacing().interact_size.y;
|
||||
let current = current_query(app);
|
||||
header(ui, tr("Saved searches"), |ui| {
|
||||
if icon_button(ui, ic::FLOPPY_DISK, tr("Save the current search"), false, size).clicked() && !app.ui.shelf_saved_searches.contains(¤t) {
|
||||
app.ui.shelf_saved_searches.push(current.clone());
|
||||
}
|
||||
});
|
||||
|
||||
let everything = current.filter.is_empty() && current.path.is_empty() && current.tab == crate::shelf_tabs::NO_TYPE;
|
||||
if ui.selectable_label(everything, tr("All")).clicked() {
|
||||
crate::shelf_toolbar::reset_query(app);
|
||||
}
|
||||
|
||||
let mut deleted = None;
|
||||
let max_height = if app.ui.shelf_panes.filter_by_path { ui.available_height() * SAVED_SEARCHES_HEIGHT_FRACTION } else { ui.available_height() };
|
||||
let row_height = ui.spacing().interact_size.y;
|
||||
let total_rows = app.ui.shelf_saved_searches.len();
|
||||
egui::ScrollArea::vertical().id_salt("shelf_saved_searches").max_height(max_height).show_rows(ui, row_height, total_rows, |ui, visible_rows| {
|
||||
for i in visible_rows {
|
||||
let Some(saved) = app.ui.shelf_saved_searches.get(i) else { continue };
|
||||
|
||||
let same = saved.filter == current.filter && saved.tab == current.tab && saved.path == current.path;
|
||||
let response = ui.selectable_label(same, &saved.name);
|
||||
if response.clicked() {
|
||||
(app.ui.shelf_filter, app.ui.shelf_tab, app.ui.shelf_path) = (saved.filter.clone(), saved.tab, saved.path.clone());
|
||||
if icon_button(ui, ic::FLOPPY_DISK, tr("Save the current search"), false, size).clicked() {
|
||||
let query = current_query(app);
|
||||
if !app.ui.shelf_saved_searches.contains(&query) {
|
||||
app.ui.shelf_saved_searches.push(query);
|
||||
}
|
||||
response.context_menu(|ui| {
|
||||
if ui.button(tr("Delete")).clicked() {
|
||||
deleted = Some(i);
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
if let Some(i) = deleted {
|
||||
app.ui.shelf_saved_searches.remove(i);
|
||||
let all_selected = app.ui.shelf_filter.is_empty() && app.ui.shelf_path.is_empty() && app.ui.shelf_tab == crate::shelf_tabs::NO_TYPE;
|
||||
let first_saved_row = 1 + BUILT_IN_SEARCHES.len();
|
||||
let row_height = ui.spacing().interact_size.y;
|
||||
let total_rows = first_saved_row + app.ui.shelf_saved_searches.len();
|
||||
let mut deleted_index = None;
|
||||
|
||||
// The fixed entries and saved searches share one scroll area
|
||||
egui::ScrollArea::vertical().id_salt("shelf_saved_searches").min_scrolled_height(0.0).auto_shrink([false, true]).show_rows(
|
||||
ui,
|
||||
row_height,
|
||||
total_rows,
|
||||
|ui, visible_rows| {
|
||||
for row in visible_rows {
|
||||
if row == 0 {
|
||||
if ui.selectable_label(all_selected, tr("All")).clicked() {
|
||||
crate::shelf_toolbar::reset_query(app);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(name) = BUILT_IN_SEARCHES.get(row - 1) {
|
||||
ui.add_enabled(false, egui::Button::selectable(false, tr(name))).on_disabled_hover_text(tr(NOT_AVAILABLE));
|
||||
continue;
|
||||
}
|
||||
|
||||
let saved_index = row - first_saved_row;
|
||||
let Some(saved) = app.ui.shelf_saved_searches.get(saved_index) else { continue };
|
||||
|
||||
let selected = saved.filter == app.ui.shelf_filter && saved.tab == app.ui.shelf_tab && saved.path == app.ui.shelf_path;
|
||||
let response = ui.selectable_label(selected, &saved.name);
|
||||
if response.clicked() {
|
||||
(app.ui.shelf_filter, app.ui.shelf_tab, app.ui.shelf_path) = (saved.filter.clone(), saved.tab, saved.path.clone());
|
||||
}
|
||||
|
||||
response.context_menu(|ui| {
|
||||
if ui.button(tr("Delete")).clicked() {
|
||||
deleted_index = Some(saved_index);
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
if let Some(index) = deleted_index {
|
||||
app.ui.shelf_saved_searches.remove(index);
|
||||
}
|
||||
}
|
||||
|
||||
/// The shelf's query, named after its search text, else its folder, else its tab
|
||||
fn current_query(app: &TextureCraftApp) -> SavedSearch {
|
||||
let (filter, tab, path) = (app.ui.shelf_filter.clone(), app.ui.shelf_tab, app.ui.shelf_path.clone());
|
||||
let filter = &app.ui.shelf_filter;
|
||||
let tab = app.ui.shelf_tab;
|
||||
let path = &app.ui.shelf_path;
|
||||
let name = if !filter.is_empty() {
|
||||
filter.clone()
|
||||
filter.as_str()
|
||||
} else if let Some(folder) = path.last() {
|
||||
crate::shelf_folders::name(path.len() - 1, folder).to_string()
|
||||
crate::shelf_folders::name(path.len() - 1, folder)
|
||||
} else {
|
||||
TABS.get(tab).map_or(tr("All"), |(_, _, label)| tr(label)).to_string()
|
||||
TABS.get(tab).map_or_else(|| tr("All"), |(_, _, label)| tr(label))
|
||||
};
|
||||
SavedSearch { name, filter, tab, path }
|
||||
|
||||
SavedSearch { name: name.to_owned(), filter: filter.clone(), tab, path: path.clone() }
|
||||
}
|
||||
@@ -3,14 +3,19 @@
|
||||
use egui::{Ui, vec2};
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::i18n::tr;
|
||||
use crate::i18n::{n_, tr};
|
||||
use crate::shelf::{TABS, Tab};
|
||||
use crate::widgets::{icon_button, icon_dropdown_button};
|
||||
|
||||
/// The gap between the row's icons in points
|
||||
const ICON_GAP: f32 = 2.0;
|
||||
const ICON_GAP_POINTS: f32 = 2.0;
|
||||
/// The size of the dot that marks the collapsed row's dropdown while a type is picked, in points
|
||||
const FILTER_DOT_RADIUS: f32 = 2.5;
|
||||
const FILTER_DOT_RADIUS_POINTS: f32 = 2.5;
|
||||
|
||||
/// The dropdown's entry after the types, greyed until fonts are assets
|
||||
const FONTS: &str = n_("Fonts");
|
||||
/// The dropdown's last entry: no type picked
|
||||
const SHOW_ALL: &str = n_("Show all");
|
||||
|
||||
/// `app.ui.shelf_tab` while no type is picked: every type shows
|
||||
pub(crate) const NO_TYPE: usize = TABS.len();
|
||||
@@ -19,26 +24,27 @@ pub(crate) const NO_TYPE: usize = TABS.len();
|
||||
pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui, counts: &[usize], trailing: impl FnOnce(&mut TextureCraftApp, &mut Ui, f32)) {
|
||||
let size = ui.spacing().interact_size.y;
|
||||
|
||||
// The type icons and one icon after them
|
||||
let row_width = (TABS.len() + 1) as f32 * (size + ICON_GAP);
|
||||
// Reserve a slot for the thumbnail size control after the type buttons
|
||||
let row_width = (TABS.len() + 1) as f32 * (size + ICON_GAP_POINTS);
|
||||
let mut picked = app.ui.shelf_tab.min(NO_TYPE);
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(ICON_GAP, ICON_GAP);
|
||||
ui.spacing_mut().item_spacing = vec2(ICON_GAP_POINTS, ICON_GAP_POINTS);
|
||||
if ui.available_width() >= row_width {
|
||||
for (i, (_, icon, label)) in TABS.iter().enumerate() {
|
||||
// The picked type stays clickable so it can be unpicked
|
||||
let empty = i != picked && counts.get(i).is_none_or(|count| *count == 0);
|
||||
if ui.add_enabled_ui(!empty, |ui| icon_button(ui, icon, tr(label), i == picked, size)).inner.clicked() {
|
||||
picked = if i == picked { NO_TYPE } else { i };
|
||||
// Leave the active type enabled so it can clear the filter
|
||||
for (index, (_, icon, label)) in TABS.iter().enumerate() {
|
||||
let selected = index == picked;
|
||||
let enabled = selected || counts.get(index).is_some_and(|count| *count > 0);
|
||||
if ui.add_enabled_ui(enabled, |ui| icon_button(ui, icon, tr(label), selected, size)).inner.clicked() {
|
||||
picked = if selected { NO_TYPE } else { index };
|
||||
}
|
||||
}
|
||||
} else {
|
||||
collapsed(ui, &mut picked, counts, size);
|
||||
}
|
||||
|
||||
let rest = ui.available_width() - size;
|
||||
ui.add_space(rest.max(0.0));
|
||||
let remaining_width = ui.available_width() - size;
|
||||
ui.add_space(remaining_width.max(0.0));
|
||||
trailing(app, ui, size);
|
||||
});
|
||||
app.ui.shelf_tab = picked;
|
||||
@@ -47,22 +53,32 @@ pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui, counts: &[usize], trai
|
||||
/// One dropdown listing the types, dotted while one is picked
|
||||
fn collapsed(ui: &mut Ui, picked: &mut usize, counts: &[usize], size: f32) {
|
||||
let filtering = *picked != NO_TYPE;
|
||||
let response = icon_dropdown_button(ui, egui_phosphor::regular::FUNNEL_SIMPLE, tr("Filter by type"), filtering, size);
|
||||
let response = response.on_hover_text(tr("Filter by type"));
|
||||
let label = tr("Filter by type");
|
||||
let response = icon_dropdown_button(ui, egui_phosphor::regular::FUNNEL_SIMPLE, label, filtering, size).on_hover_text(label);
|
||||
|
||||
if filtering {
|
||||
let tokens = crate::theme::Tokens::get(ui.ctx());
|
||||
let dot = response.rect.left_top() + vec2(size - FILTER_DOT_RADIUS, FILTER_DOT_RADIUS);
|
||||
ui.painter().circle_filled(dot, FILTER_DOT_RADIUS, tokens.accent);
|
||||
let dot = response.rect.left_top() + vec2(size - FILTER_DOT_RADIUS_POINTS, FILTER_DOT_RADIUS_POINTS);
|
||||
ui.painter().circle_filled(dot, FILTER_DOT_RADIUS_POINTS, tokens.accent);
|
||||
}
|
||||
|
||||
egui::Popup::menu(&response).show(|ui| {
|
||||
for (i, (_, icon, label)) in TABS.iter().enumerate() {
|
||||
let empty = i != *picked && counts.get(i).is_none_or(|count| *count == 0);
|
||||
if ui.add_enabled(!empty, egui::Button::selectable(i == *picked, format!("{icon} {}", tr(label)))).clicked() {
|
||||
*picked = if i == *picked { NO_TYPE } else { i };
|
||||
for (index, (_, _, label)) in TABS.iter().enumerate() {
|
||||
let selected = index == *picked;
|
||||
let enabled = selected || counts.get(index).is_some_and(|count| *count > 0);
|
||||
if ui.add_enabled(enabled, egui::Button::selectable(selected, tr(label))).clicked() {
|
||||
*picked = if selected { NO_TYPE } else { index };
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
|
||||
ui.add_enabled(false, egui::Button::selectable(false, tr(FONTS))).on_disabled_hover_text(tr(crate::shelf_panes::NOT_AVAILABLE));
|
||||
ui.separator();
|
||||
|
||||
if ui.button(tr(SHOW_ALL)).clicked() {
|
||||
*picked = NO_TYPE;
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+74
-12
@@ -9,8 +9,14 @@ use crate::saved_search::SavedSearch;
|
||||
use crate::shelf_panes::ShelfPanes;
|
||||
use crate::shelf_view::ShelfView;
|
||||
|
||||
mod import_resources;
|
||||
mod import_row;
|
||||
mod project_config;
|
||||
mod resource_usage;
|
||||
pub use import_resources::ImportResources;
|
||||
pub use import_row::ImportRow;
|
||||
pub use project_config::ProjectConfig;
|
||||
pub use resource_usage::ResourceUsage;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum Mode {
|
||||
@@ -82,6 +88,9 @@ pub struct Windows {
|
||||
/// Edit > Project Configuration: what is chosen so far, applied by OK.
|
||||
#[serde(skip)]
|
||||
pub project_config: Option<ProjectConfig>,
|
||||
/// File > Import resources: the files added so far, imported by Import.
|
||||
#[serde(skip)]
|
||||
pub import_resources: Option<ImportResources>,
|
||||
/// What waits on the unsaved-changes dialog: save, don't save or cancel.
|
||||
#[serde(skip)]
|
||||
pub unsaved: Option<Unsaved>,
|
||||
@@ -94,8 +103,10 @@ pub struct Windows {
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Unsaved {
|
||||
Quit,
|
||||
/// A menu command (New project, Open, Close, Open sample project).
|
||||
/// A menu command (Open, Close, Open sample project).
|
||||
Command(String),
|
||||
/// Create from the New project form that requested confirmation.
|
||||
CreateProject(u64),
|
||||
/// Open this project or mesh file.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Open(String),
|
||||
@@ -163,22 +174,32 @@ impl Prefs {
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct NewProject {
|
||||
pub mesh: String,
|
||||
pub resolution: u32,
|
||||
pub name: String,
|
||||
/// A mesh file chosen from disk (desktop only).
|
||||
/// The mesh file chosen with Select... (its path on the desktop, its name in the browser).
|
||||
pub file: Option<String>,
|
||||
/// UV tile (UDIM) workflow: on, off, or None for when the mesh's UVs leave tile 1001.
|
||||
/// The browser's copy of the chosen mesh file, read when Create is pressed.
|
||||
#[serde(skip)]
|
||||
pub file_bytes: Option<std::sync::Arc<Vec<u8>>>,
|
||||
/// The active form opening, used to reject late file picker answers.
|
||||
#[serde(skip)]
|
||||
pub opening_id: u64,
|
||||
/// The latest mesh pick requested by this form.
|
||||
#[serde(skip)]
|
||||
pub mesh_request_id: u64,
|
||||
/// Use UV Tile workflow: Some(true) makes UV tile (UDIM) texture sets; otherwise each set paints tile 1001.
|
||||
pub uv_tiles: Option<bool>,
|
||||
/// Project template name (built-in or the user's).
|
||||
#[serde(default = "default_template")]
|
||||
pub template: String,
|
||||
/// Name typed to save the current project's settings as a template.
|
||||
#[serde(skip)]
|
||||
pub template_name: String,
|
||||
/// Normal map format of the project and its imported normal maps; None keeps the template's
|
||||
#[serde(default)]
|
||||
pub normal_format: Option<NormalFormat>,
|
||||
/// Import settings > Import cameras: keep the cameras stored in the mesh file
|
||||
#[serde(default = "import_cameras_default")]
|
||||
pub import_cameras: bool,
|
||||
/// Color management as chosen in the window (the project is always created as Legacy)
|
||||
#[serde(skip)]
|
||||
pub color_management: crate::project_form::ColorManagement,
|
||||
/// Baked map files to import at creation, matched to sets and mesh maps by name (desktop only)
|
||||
#[serde(skip)]
|
||||
pub baked_maps: Vec<String>,
|
||||
@@ -188,17 +209,32 @@ fn default_template() -> String {
|
||||
texturecraft_engine::template_cmds::DEFAULT_TEMPLATE.into()
|
||||
}
|
||||
|
||||
fn import_cameras_default() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
impl NewProject {
|
||||
pub(crate) fn clear_mesh(&mut self) {
|
||||
self.file = None;
|
||||
self.file_bytes = None;
|
||||
self.opening_id = 0;
|
||||
self.mesh_request_id = 0;
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for NewProject {
|
||||
fn default() -> Self {
|
||||
NewProject {
|
||||
mesh: "material_ball".into(),
|
||||
resolution: 2048,
|
||||
name: "Untitled".into(),
|
||||
resolution: 1024,
|
||||
file: None,
|
||||
file_bytes: None,
|
||||
opening_id: 0,
|
||||
mesh_request_id: 0,
|
||||
uv_tiles: None,
|
||||
template: default_template(),
|
||||
template_name: String::new(),
|
||||
normal_format: None,
|
||||
import_cameras: true,
|
||||
color_management: crate::project_form::ColorManagement::Legacy,
|
||||
baked_maps: Vec::new(),
|
||||
}
|
||||
}
|
||||
@@ -274,10 +310,23 @@ fn default_split_ratio() -> f32 {
|
||||
0.5
|
||||
}
|
||||
|
||||
/// Saved searches start with this share of the Assets panel's pane column while Filter by path is open too
|
||||
pub(crate) fn default_shelf_panes_split() -> f32 {
|
||||
0.45
|
||||
}
|
||||
|
||||
fn deserialize_shelf_panes_split<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<f32, D::Error> {
|
||||
let share = f32::deserialize(deserializer)?;
|
||||
|
||||
// A finite JSON number can overflow f32 and prevent the next settings save
|
||||
Ok(if share.is_finite() { share } else { default_shelf_panes_split() })
|
||||
}
|
||||
|
||||
/// Settings that start on, for saved states that predate them
|
||||
fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// The bake layout's version: saved bake docks from an older one load as `Dock::for_baking`
|
||||
const BAKE_LAYOUT_VERSION: u32 = 2;
|
||||
|
||||
@@ -330,6 +379,9 @@ pub struct UiState {
|
||||
/// The asset shelf's saved queries, in the order they were saved
|
||||
#[serde(default)]
|
||||
pub shelf_saved_searches: Vec<SavedSearch>,
|
||||
/// Saved searches' share of the pane column above Filter by path, set by the splitter between them
|
||||
#[serde(default = "default_shelf_panes_split", deserialize_with = "deserialize_shelf_panes_split")]
|
||||
pub shelf_panes_split: f32,
|
||||
pub props_tab: PropsTab,
|
||||
#[serde(default)]
|
||||
pub text: TextUi,
|
||||
@@ -412,6 +464,15 @@ impl UiState {
|
||||
pub fn adopt_layout(&mut self, layout: UiState) {
|
||||
let keep = std::mem::replace(self, layout);
|
||||
self.new_project = keep.new_project;
|
||||
if !self.windows.new_project {
|
||||
self.new_project.clear_mesh();
|
||||
|
||||
// Keep a failed import queued when the form was already closed
|
||||
if keep.windows.new_project {
|
||||
self.new_project.baked_maps = Vec::new();
|
||||
}
|
||||
}
|
||||
|
||||
self.export = keep.export;
|
||||
self.recent = keep.recent;
|
||||
self.prefs = keep.prefs;
|
||||
@@ -454,6 +515,7 @@ impl Default for UiState {
|
||||
shelf_view: ShelfView::default(),
|
||||
shelf_panes: ShelfPanes::default(),
|
||||
shelf_saved_searches: Vec::new(),
|
||||
shelf_panes_split: default_shelf_panes_split(),
|
||||
props_tab: PropsTab::Brush,
|
||||
text: TextUi::default(),
|
||||
rename: None,
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use super::{ImportRow, ResourceUsage};
|
||||
|
||||
/// File > Import resources: the files added so far, imported by the Import button
|
||||
#[derive(Clone, Debug, PartialEq, Default)]
|
||||
pub struct ImportResources {
|
||||
pub rows: Vec<ImportRow>,
|
||||
/// Ids of the selected rows
|
||||
pub selected: BTreeSet<u64>,
|
||||
/// The row a Shift click extends from
|
||||
pub anchor: Option<u64>,
|
||||
/// The usage the list is narrowed to (None: all)
|
||||
pub filter: Option<ResourceUsage>,
|
||||
/// Whether Enter requested the import in the next frame
|
||||
pub confirm: bool,
|
||||
/// The project that was open when this window opened
|
||||
pub project: u64,
|
||||
/// This opening's identity, used to reject late file picker answers
|
||||
pub(crate) opening_id: u64,
|
||||
pub(crate) next_row: u64,
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::ResourceUsage;
|
||||
|
||||
/// One file waiting in the window
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ImportRow {
|
||||
pub id: u64,
|
||||
pub path: PathBuf,
|
||||
pub prefix: String,
|
||||
pub usage: ResourceUsage,
|
||||
}
|
||||
@@ -9,6 +9,8 @@ pub struct ProjectConfig {
|
||||
pub preserve: bool,
|
||||
/// The selected normal map format when it differs from the project's
|
||||
pub normal_format: Option<texturecraft_engine::core::NormalFormat>,
|
||||
/// Color management as chosen in the window; nothing is applied (the project stays Legacy)
|
||||
pub color_management: crate::project_form::ColorManagement,
|
||||
/// Whether Enter requested confirmation in the next frame
|
||||
pub confirm: bool,
|
||||
/// The project that was open when this window opened
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
/// What an imported resource is for
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum ResourceUsage {
|
||||
/// Imported as an image resource, nothing more
|
||||
#[default]
|
||||
Undefined,
|
||||
/// An image resource that also becomes the brush alpha
|
||||
Alpha,
|
||||
/// Color lookup tables (not available yet)
|
||||
ColorLut,
|
||||
/// An image resource that also lights the scene
|
||||
Environment,
|
||||
/// Post effect resources (not available yet)
|
||||
PostFx,
|
||||
/// An image resource for fills and stencils
|
||||
Texture,
|
||||
}
|
||||
|
||||
impl ResourceUsage {
|
||||
/// The usages in the dropdown's order
|
||||
pub const ALL: [ResourceUsage; 6] = [Self::Undefined, Self::Alpha, Self::ColorLut, Self::Environment, Self::PostFx, Self::Texture];
|
||||
|
||||
/// The name shown in the dropdowns (the same in every language, as in the reference)
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Undefined => "undefined",
|
||||
Self::Alpha => "alpha",
|
||||
Self::ColorLut => "colorlut",
|
||||
Self::Environment => "environment",
|
||||
Self::PostFx => "postfx",
|
||||
Self::Texture => "texture",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the app can do something with resources of this usage
|
||||
pub fn available(self) -> bool {
|
||||
!matches!(self, Self::ColorLut | Self::PostFx)
|
||||
}
|
||||
}
|
||||
@@ -544,6 +544,24 @@ pub(crate) mod tests {
|
||||
assert_eq!(storage.values[STORAGE_KEY], saved);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_overflowing_shelf_split_still_allows_saving_other_preferences() {
|
||||
let defaults = UiState::default();
|
||||
let mut saved = serde_json::to_value(&defaults).unwrap();
|
||||
saved["shelf_panes_split"] = serde_json::json!(1e100);
|
||||
let mut storage = MemoryStorage::default();
|
||||
storage.values.insert(STORAGE_KEY.to_owned(), saved.to_string());
|
||||
|
||||
let mut store = UiStateStore::default();
|
||||
let mut ui = store.load(Some(&storage)).expect("settings load with both panes closed");
|
||||
ui.shelf_filter = "rust".to_owned();
|
||||
store.save(&ui, &mut storage);
|
||||
|
||||
let restarted = UiStateStore::default().load(Some(&storage)).unwrap();
|
||||
assert_eq!(restarted.shelf_filter, "rust");
|
||||
assert_eq!(restarted.shelf_panes_split, defaults.shelf_panes_split);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_storage_backup_preserves_the_unreadable_original() {
|
||||
let mut storage = MemoryStorage::default();
|
||||
|
||||
@@ -46,6 +46,8 @@ enum Pick {
|
||||
Cage(u64),
|
||||
/// Export dialog › Output templates: an export template (`.json`).
|
||||
ExportPreset,
|
||||
/// New project › 3D mesh › Select...: the mesh the project is created from.
|
||||
NewProjectMesh(u64),
|
||||
}
|
||||
|
||||
/// Files picked in the browser, waiting for the next frame: (file name, bytes, purpose).
|
||||
@@ -70,13 +72,23 @@ fn apply_picked(app: &mut TextureCraftApp, picked: Vec<(String, Vec<u8>, Pick)>)
|
||||
app.toast(tr("No project is open"), true);
|
||||
continue;
|
||||
}
|
||||
|
||||
Pick::Environment(project_id) | Pick::HighPoly(project_id) | Pick::Cage(project_id) if project_id != app.session.project_id => {
|
||||
app.toast(tr("The project changed while the dialog was open, so nothing was done"), true);
|
||||
continue;
|
||||
}
|
||||
|
||||
Pick::Environment(_) => app.session.import_resource_bytes(&name, bytes).map(|res| use_environment(app, &res)),
|
||||
Pick::HighPoly(_) => app.session.add_high_poly_bytes(&name, bytes).map(|n| app.toast(trf("High poly: {name}", &[("name", &n)]), false)),
|
||||
Pick::Cage(_) => app.session.set_cage_bytes(&name, bytes).map(|n| app.toast(trf("Cage: {name}", &[("name", &n)]), false)),
|
||||
Pick::NewProjectMesh(request_id) => {
|
||||
if app.ui.windows.new_project && app.ui.new_project.mesh_request_id == request_id {
|
||||
app.ui.new_project.file = Some(name);
|
||||
app.ui.new_project.file_bytes = Some(std::sync::Arc::new(bytes));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
Pick::ExportPreset => {
|
||||
match texturecraft_engine::formats::preset_from_json(&String::from_utf8_lossy(&bytes)) {
|
||||
Ok(p) => crate::export_templates::import(app, &p),
|
||||
@@ -121,7 +133,7 @@ pub fn import_environment(app: &mut TextureCraftApp, _ctx: &egui::Context) {
|
||||
}
|
||||
|
||||
/// Make image resource `name` the environment.
|
||||
fn use_environment(app: &mut TextureCraftApp, name: &str) {
|
||||
pub(crate) fn use_environment(app: &mut TextureCraftApp, name: &str) {
|
||||
let env = format!("{}{name}", texturecraft_engine::core::project::ENV_RESOURCE_PREFIX);
|
||||
if app.run("display.set", serde_json::json!({ "environment": env })).is_some() {
|
||||
app.toast(trf("Environment: {name}", &[("name", &name)]), false);
|
||||
@@ -230,8 +242,8 @@ fn zip_files(files: &[ExportedFile]) -> Result<Vec<u8>, String> {
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub use web::{
|
||||
download, export_mesh, export_textures, import_bake_mesh, import_environment, import_images, import_material, import_preset, open, save_project,
|
||||
sync_unsaved, unsaved,
|
||||
download, export_mesh, export_textures, import_bake_mesh, import_environment, import_images, import_material, import_preset, open, pick_new_project_mesh,
|
||||
save_project, sync_unsaved, unsaved,
|
||||
};
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
@@ -284,6 +296,11 @@ mod web {
|
||||
pick(ctx, tr("Export templates"), &["json"], false, Pick::ExportPreset);
|
||||
}
|
||||
|
||||
/// New project › Select...: pick the mesh file; Create reads it once it has arrived.
|
||||
pub fn pick_new_project_mesh(ctx: &egui::Context, request_id: u64) {
|
||||
pick(ctx, tr("3D meshes"), &MESH_EXTENSIONS, false, Pick::NewProjectMesh(request_id));
|
||||
}
|
||||
|
||||
fn pick(ctx: &egui::Context, filter: &'static str, exts: &'static [&'static str], multiple: bool, kind: Pick) {
|
||||
let ctx = ctx.clone();
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
@@ -386,6 +403,28 @@ mod tests {
|
||||
|
||||
use egui_kittest::Harness;
|
||||
|
||||
#[test]
|
||||
fn mesh_picks_only_update_the_current_new_project_request() {
|
||||
let session = Session::closed().unwrap();
|
||||
let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let app = harness.state_mut();
|
||||
crate::new_project_advanced::open(app);
|
||||
app.ui.new_project.mesh_request_id = 2;
|
||||
|
||||
apply_picked(app, vec![("new.obj".into(), vec![2; 4096], Pick::NewProjectMesh(2)), ("stale.obj".into(), vec![1; 8192], Pick::NewProjectMesh(1))]);
|
||||
|
||||
assert_eq!(app.ui.new_project.file.as_deref(), Some("new.obj"));
|
||||
assert_eq!(app.ui.new_project.file_bytes.as_deref().unwrap().as_slice(), &[2; 4096]);
|
||||
let previous_buffer = std::sync::Arc::downgrade(app.ui.new_project.file_bytes.as_ref().unwrap());
|
||||
|
||||
crate::new_project_advanced::open(app);
|
||||
apply_picked(app, vec![("previous.obj".into(), vec![3; 2048], Pick::NewProjectMesh(2))]);
|
||||
|
||||
assert!(app.ui.new_project.file.is_none());
|
||||
assert!(app.ui.new_project.file_bytes.is_none());
|
||||
assert!(previous_buffer.upgrade().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn environment_pick_after_close_does_not_edit_the_placeholder() {
|
||||
let session = texturecraft_engine::sample_session(128, 32).unwrap();
|
||||
|
||||
+34
-167
@@ -5,7 +5,6 @@ use egui_phosphor::regular as ic;
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::core::ToneMapping;
|
||||
use texturecraft_engine::core::project::{DisplaySettings, ENV_RESOURCE_PREFIX};
|
||||
use texturecraft_engine::geom::primitives::BUILTINS;
|
||||
use texturecraft_render::ibl::ENVIRONMENTS;
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
@@ -13,17 +12,20 @@ use crate::TextureCraftApp;
|
||||
use crate::file_dialogs::{Bound, FileDialog};
|
||||
use crate::i18n::LANGUAGES;
|
||||
use crate::i18n::{tr, tr_history, trf};
|
||||
use crate::new_project_advanced::COMBO_WIDTH;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use crate::state::Mode;
|
||||
use crate::theme::{Accent, Brightness, Tokens, caption};
|
||||
use crate::widgets::{color_swatch, combo, icon_button, primary_button, section, section_with_reset, slider};
|
||||
|
||||
pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
new_project(app, ctx);
|
||||
crate::new_project_advanced::show(app, ctx);
|
||||
about(app, ctx);
|
||||
settings(app, ctx);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::project_config::show(app, ctx);
|
||||
{
|
||||
crate::project_config::show(app, ctx);
|
||||
crate::import_resources::show(app, ctx);
|
||||
}
|
||||
crate::keymap::window(app, ctx);
|
||||
crate::windows::export(app, ctx);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
@@ -154,6 +156,7 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
|
||||
let discard_after_create = matches!(pending, Unsaved::CreateProject(_)) && save_first == Some(false) && app.session.modified;
|
||||
match save_first {
|
||||
Some(true) => {
|
||||
// An untitled project is saved from a dialog that answers on a later frame
|
||||
@@ -173,10 +176,16 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
if app.session.modified {
|
||||
return;
|
||||
}
|
||||
|
||||
app.ui.windows.unsaved = None;
|
||||
match pending {
|
||||
Unsaved::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
|
||||
Unsaved::Command(id) => crate::menus::invoke(app, ctx, &id),
|
||||
Unsaved::CreateProject(opening_id) => {
|
||||
if !crate::new_project_advanced::finish_create(app, opening_id) && discard_after_create {
|
||||
app.session.modified = true;
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Unsaved::Open(path) => open_path(app, &path),
|
||||
Unsaved::Load(name, bytes) => crate::web_files::load(app, &name, std::sync::Arc::unwrap_or_clone(bytes)),
|
||||
@@ -445,124 +454,6 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
if !app.ui.windows.new_project {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut open = true;
|
||||
let mut create = false;
|
||||
dialog("new_project", tr("New project"), &mut open).show(ctx, |ui| {
|
||||
ui.label(caption(tr("Basic settings")));
|
||||
egui::Grid::new("np").num_columns(2).spacing(vec2(12.0, 8.0)).min_col_width(crate::new_project_advanced::form_label_width(ui)).show(ui, |ui| {
|
||||
ui.label(tr("3D mesh"));
|
||||
ui.horizontal(|ui| {
|
||||
let label = app.ui.new_project.file.clone().unwrap_or_else(|| {
|
||||
BUILTINS
|
||||
.iter()
|
||||
.find(|(id, _)| *id == app.ui.new_project.mesh)
|
||||
.map(|(_, builtin_label)| trf("Built-in: {mesh}", &[("mesh", &tr(builtin_label))]))
|
||||
.unwrap_or_default()
|
||||
});
|
||||
egui::ComboBox::from_id_salt("np_mesh").width(COMBO_WIDTH).selected_text(label).show_ui(ui, |ui| {
|
||||
for (id, builtin_label) in BUILTINS {
|
||||
if ui
|
||||
.selectable_label(
|
||||
app.ui.new_project.mesh == id && app.ui.new_project.file.is_none(),
|
||||
trf("Built-in: {mesh}", &[("mesh", &tr(builtin_label))]),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
app.ui.new_project.mesh = id.to_string();
|
||||
app.ui.new_project.file = None;
|
||||
}
|
||||
}
|
||||
});
|
||||
if file_dialogs_available() && ui.button(tr("Select...")).clicked() {
|
||||
ask_mesh_file(app);
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tr("Project template"));
|
||||
let new_project = &mut app.ui.new_project;
|
||||
egui::ComboBox::from_id_salt("np_template").width(COMBO_WIDTH).selected_text(new_project.template.clone()).show_ui(ui, |ui| {
|
||||
let user_templates = app.session.templates.list.iter();
|
||||
for template in texturecraft_engine::template_cmds::builtin_templates().iter().chain(user_templates) {
|
||||
if ui.selectable_label(template.name == new_project.template, &template.name).clicked() {
|
||||
new_project.template = template.name.clone();
|
||||
new_project.resolution = template.resolution;
|
||||
new_project.normal_format = None;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label("");
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::TextEdit::singleline(&mut app.ui.new_project.template_name).hint_text(tr("Template name")).desired_width(120.0));
|
||||
let name = app.ui.new_project.template_name.trim().to_string();
|
||||
if ui.add_enabled(!name.is_empty() && app.session.project_open, egui::Button::new(tr("Save current project as template"))).clicked()
|
||||
&& app.run("project.template.save", json!({"name": name})).is_some()
|
||||
{
|
||||
app.ui.new_project.template = name;
|
||||
app.ui.new_project.template_name.clear();
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tr("Document resolution"));
|
||||
egui::ComboBox::from_id_salt("np_res").selected_text(format!("{0} x {0}", app.ui.new_project.resolution)).show_ui(ui, |ui| {
|
||||
for size in [512u32, 1024, 2048, 4096] {
|
||||
ui.selectable_value(&mut app.ui.new_project.resolution, size, format!("{size} x {size}"));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tr("UV tiles (UDIM)"));
|
||||
let tiles_label = |tiles: Option<bool>| match tiles {
|
||||
None => tr("Automatic (from the mesh UVs)"),
|
||||
Some(true) => tr("On"),
|
||||
Some(false) => tr("Off"),
|
||||
};
|
||||
egui::ComboBox::from_id_salt("np_tiles").selected_text(tiles_label(app.ui.new_project.uv_tiles)).show_ui(ui, |ui| {
|
||||
for tiles in [None, Some(true), Some(false)] {
|
||||
ui.selectable_value(&mut app.ui.new_project.uv_tiles, tiles, tiles_label(tiles));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tr("Name"));
|
||||
ui.text_edit_singleline(&mut app.ui.new_project.name);
|
||||
ui.end_row();
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
crate::new_project_advanced::advanced_settings(app, ui);
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.add(primary_button(ui, tr("Create"))).clicked() {
|
||||
create = true;
|
||||
}
|
||||
if ui.button(tr("Cancel")).clicked() {
|
||||
app.ui.windows.new_project = false;
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
if create {
|
||||
let new_project = app.ui.new_project.clone();
|
||||
let (command, mesh) = match &new_project.file {
|
||||
Some(path) => ("file.new", path.clone()),
|
||||
None => ("project.new", new_project.mesh.clone()),
|
||||
};
|
||||
let params = json!({"mesh": mesh, "resolution": new_project.resolution, "name": new_project.name, "uvTiles": new_project.uv_tiles, "template": new_project.template});
|
||||
if app.run(command, params).is_some() {
|
||||
app.ui.windows.new_project = false;
|
||||
app.ui.mode = Mode::Painting;
|
||||
crate::new_project_advanced::apply_after_create(app, &new_project);
|
||||
}
|
||||
}
|
||||
if !open {
|
||||
app.ui.windows.new_project = false;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn settings_resources(ctx: &egui::Context) -> (u32, u64) {
|
||||
let id = egui::Id::unique("settings_resources");
|
||||
@@ -810,19 +701,6 @@ pub fn file_dialogs_available() -> bool {
|
||||
cfg!(not(target_arch = "wasm32"))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn ask_mesh_file(app: &mut TextureCraftApp) {
|
||||
let dialog = FileDialog::open().filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS);
|
||||
app.ask_file(dialog, Bound::App, |app, paths| {
|
||||
if let Some(p) = paths.first() {
|
||||
app.ui.new_project.file = Some(p.display().to_string());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn ask_mesh_file(_app: &mut TextureCraftApp) {}
|
||||
|
||||
/// Remember a project path in File ▸ Recent projects.
|
||||
pub fn remember(app: &mut TextureCraftApp, path: &str) {
|
||||
app.ui.recent.retain(|p| p != path);
|
||||
@@ -871,16 +749,16 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) ->
|
||||
match id {
|
||||
"file.open" => {
|
||||
app.ask_file(FileDialog::open().filter(tr("TextureCraft project or mesh"), crate::web_files::OPEN_EXTS), Bound::App, |app, paths| {
|
||||
if let Some(p) = paths.first() {
|
||||
open_path(app, &p.display().to_string());
|
||||
if let Some(path) = paths.first() {
|
||||
open_path(app, &path.display().to_string());
|
||||
}
|
||||
});
|
||||
true
|
||||
}
|
||||
"file.save" if app.session.path.is_some() => {
|
||||
if let Some(r) = app.run("file.save", json!({})) {
|
||||
let p = r.get("path").and_then(|p| p.as_str()).unwrap_or_default().to_string();
|
||||
app.toast(trf("Saved {path}", &[("path", &p)]), false);
|
||||
if let Some(result) = app.run("file.save", json!({})) {
|
||||
let saved_path = result["path"].as_str().unwrap_or_default();
|
||||
app.toast(trf("Saved {path}", &[("path", &saved_path)]), false);
|
||||
}
|
||||
true
|
||||
}
|
||||
@@ -894,36 +772,24 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) ->
|
||||
}
|
||||
"material.load" => {
|
||||
app.ask_file(FileDialog::open_many().filter(tr("Materials"), crate::web_files::MATERIAL_EXTS), Bound::Project, |app, paths| {
|
||||
for p in paths {
|
||||
app.run("material.load", json!({"path": p.display().to_string()}));
|
||||
for path in paths {
|
||||
app.run("material.load", json!({"path": path.display().to_string()}));
|
||||
}
|
||||
});
|
||||
true
|
||||
}
|
||||
"file.importResources" | "resource.import" => {
|
||||
app.ask_file(FileDialog::open_many().filter(tr("Images"), crate::web_files::IMAGE_EXTS), Bound::Project, |app, paths| {
|
||||
if paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
for p in paths {
|
||||
if let Some(r) = app.run("resource.import", json!({"path": p.display().to_string()})) {
|
||||
let name = r.get("name").and_then(|n| n.as_str()).unwrap_or_default().to_string();
|
||||
app.toast(trf("Imported {name}", &[("name", &name)]), false);
|
||||
}
|
||||
}
|
||||
app.ui.dock.focus(crate::docking::Panel::Assets);
|
||||
});
|
||||
crate::import_resources::open(app);
|
||||
true
|
||||
}
|
||||
"file.importMaterialX" => {
|
||||
app.ask_file(FileDialog::open().filter(tr("MaterialX materials"), &["mtlx"]), Bound::Project, |app, paths| {
|
||||
if let Some(p) = paths.first()
|
||||
&& let Some(r) = app.run("file.importMaterialX", json!({"path": p.display().to_string()}))
|
||||
if let Some(path) = paths.first()
|
||||
&& let Some(result) = app.run("file.importMaterialX", json!({"path": path.display().to_string()}))
|
||||
{
|
||||
let name = r.get("material").and_then(|n| n.as_str()).unwrap_or_default().to_string();
|
||||
for w in r.get("warnings").and_then(|w| w.as_array()).into_iter().flatten().filter_map(|w| w.as_str()) {
|
||||
app.session.log.push(format!("MaterialX {name}: {w}"));
|
||||
let name = result["material"].as_str().unwrap_or_default();
|
||||
for warning in result["warnings"].as_array().into_iter().flatten().filter_map(serde_json::Value::as_str) {
|
||||
app.session.log.push(format!("MaterialX {name}: {warning}"));
|
||||
}
|
||||
app.toast(trf("Imported {name}", &[("name", &name)]), false);
|
||||
app.ui.dock.focus(crate::docking::Panel::Layers);
|
||||
@@ -945,25 +811,26 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) ->
|
||||
.filter(tr("USD binary, textures alongside"), &["usdc"])
|
||||
.file_name(name);
|
||||
app.ask_file(dialog, Bound::Project, |app, paths| {
|
||||
if let Some(p) = paths.first()
|
||||
&& let Some(r) = app.run("file.exportMesh", json!({"path": p.display().to_string()}))
|
||||
if let Some(path) = paths.first()
|
||||
&& let Some(result) = app.run("file.exportMesh", json!({"path": path.display().to_string()}))
|
||||
{
|
||||
let p = r.get("path").and_then(|p| p.as_str()).unwrap_or_default().to_string();
|
||||
app.toast(trf("Exported mesh to {path}", &[("path", &p)]), false);
|
||||
let saved_path = result["path"].as_str().unwrap_or_default();
|
||||
app.toast(trf("Exported mesh to {path}", &[("path", &saved_path)]), false);
|
||||
}
|
||||
});
|
||||
true
|
||||
}
|
||||
"file.reimportMesh" => {
|
||||
// The file the mesh came from is read again from disk; ask only when it's gone.
|
||||
// Ask for a replacement only when the mesh source is missing
|
||||
if let Some(path) = app.session.remembered_mesh_path().map(str::to_string) {
|
||||
reimport_mesh(app, path);
|
||||
return true;
|
||||
}
|
||||
|
||||
let dialog = FileDialog::open().filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS);
|
||||
app.ask_file(dialog, Bound::Project, |app, paths| {
|
||||
if let Some(p) = paths.first() {
|
||||
reimport_mesh(app, p.display().to_string());
|
||||
if let Some(path) = paths.first() {
|
||||
reimport_mesh(app, path.display().to_string());
|
||||
}
|
||||
});
|
||||
true
|
||||
|
||||
@@ -146,7 +146,7 @@ fn answered_after_the_project_changed(ask: impl FnOnce(&mut Harness<'_, TextureC
|
||||
#[test]
|
||||
fn every_project_dialog_does_nothing_for_a_replaced_project() {
|
||||
let file = temp_file("replaced-actions", "chosen.obj");
|
||||
for id in ["material.load", "resource.import", "file.importMaterialX", "file.exportMesh", "file.reimportMesh"] {
|
||||
for id in ["material.load", "file.importMaterialX", "file.exportMesh", "file.reimportMesh"] {
|
||||
let h = answered_after_the_project_changed(|h| invoke(h, id), &file);
|
||||
assert!(h.state().toasts.iter().any(|t| t.error && t.text.starts_with(PROJECT_CHANGED)), "{id}");
|
||||
assert!(!file.exists(), "{id} wrote nothing");
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
//! File > Import resources...: the window that collects files and imports them together. File
|
||||
//! pickers are answered by the override, never shown.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use egui::Role;
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
use texturecraft_engine::Session;
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
use texturecraft_ui_egui::file_dialogs::{Answer, Request};
|
||||
|
||||
use super::temp_dir::TempDir;
|
||||
|
||||
const TITLE: &str = "Import resources";
|
||||
/// The prefix field's tooltip, which is its accessible label.
|
||||
const PREFIX_HINT: &str = "Put in front of the resource's name. Characters other than letters, digits and _ . - become _";
|
||||
|
||||
fn app() -> Harness<'static, TextureCraftApp> {
|
||||
let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
h.state_mut().ui.prefs.language = "en".into();
|
||||
h.run_steps(4);
|
||||
|
||||
h
|
||||
}
|
||||
|
||||
fn png(dir: &Path, name: &str) -> PathBuf {
|
||||
let file = dir.join(name);
|
||||
image::RgbaImage::from_pixel(4, 4, image::Rgba([10, 200, 30, 255])).save(&file).unwrap();
|
||||
|
||||
file
|
||||
}
|
||||
|
||||
fn invoke(h: &mut Harness<'_, TextureCraftApp>) {
|
||||
let ctx = h.ctx.clone();
|
||||
texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "resource.import");
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
fn is_open(h: &Harness<'_, TextureCraftApp>) -> bool {
|
||||
h.query_by_label(TITLE).is_some()
|
||||
}
|
||||
|
||||
fn click(h: &mut Harness<'_, TextureCraftApp>, label: &str) {
|
||||
h.get_by_role_and_label(Role::Button, label).click();
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
/// Add resources, answered with `files`.
|
||||
fn add(h: &mut Harness<'_, TextureCraftApp>, files: &[PathBuf]) {
|
||||
let files = files.to_vec();
|
||||
h.state_mut().file_dialogs.set_override(Some(Box::new(move |_: &Request| Answer::Paths(files.clone()))));
|
||||
click(h, "Add resources");
|
||||
}
|
||||
|
||||
/// The dropdowns showing `value` (they have no label, only a value).
|
||||
fn combos<'h>(h: &'h Harness<'_, TextureCraftApp>, value: &'h str) -> impl Iterator<Item = egui_kittest::Node<'h>> {
|
||||
h.get_all_by_role(Role::ComboBox).filter(move |node| node.value().as_deref() == Some(value))
|
||||
}
|
||||
|
||||
fn resources(h: &Harness<'_, TextureCraftApp>) -> Vec<String> {
|
||||
h.state().session.doc.resources.keys().cloned().collect()
|
||||
}
|
||||
|
||||
/// Pick `usage` in the dropdown of the `n`th row (the dropdowns show "undefined" until changed).
|
||||
fn choose_usage(h: &mut Harness<'_, TextureCraftApp>, n: usize, usage: &str) {
|
||||
let combo = combos(h, "undefined").nth(n).expect("a usage dropdown");
|
||||
combo.click();
|
||||
h.run_steps(3);
|
||||
h.get_by_label(usage).click();
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_menu_opens_the_window_without_importing_or_asking() {
|
||||
let mut h = app();
|
||||
invoke(&mut h);
|
||||
|
||||
assert!(is_open(&h));
|
||||
assert!(resources(&h).is_empty());
|
||||
assert!(h.query_by_label("Choose files and assign their roles").is_some());
|
||||
assert!(combos(&h, "All files (0)").next().is_some());
|
||||
assert!(h.get_by_label("Remove selected resources").accesskit_node().is_disabled(), "nothing is selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn added_files_are_listed_and_import_keeps_their_names() {
|
||||
let dir = TempDir::new("import-resources-add");
|
||||
let (a, b) = (png(&dir, "bluenoise.png"), png(&dir, "scratch.png"));
|
||||
let mut h = app();
|
||||
invoke(&mut h);
|
||||
add(&mut h, &[a.clone(), b]);
|
||||
|
||||
assert!(combos(&h, "All files (2)").next().is_some());
|
||||
assert!(h.query_by_label("bluenoise.png").is_some() && h.query_by_label("scratch.png").is_some());
|
||||
assert!(resources(&h).is_empty(), "adding only lists");
|
||||
|
||||
// The same file twice is one row
|
||||
add(&mut h, &[a]);
|
||||
assert!(combos(&h, "All files (2)").next().is_some());
|
||||
|
||||
click(&mut h, "Import");
|
||||
assert!(!is_open(&h));
|
||||
assert_eq!(resources(&h), ["bluenoise.png", "scratch.png"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_selected_drops_only_the_selected_rows() {
|
||||
let dir = TempDir::new("import-resources-remove");
|
||||
let mut h = app();
|
||||
invoke(&mut h);
|
||||
add(&mut h, &[png(&dir, "one.png"), png(&dir, "two.png")]);
|
||||
|
||||
h.get_by_label("one.png").click();
|
||||
h.run_steps(3);
|
||||
click(&mut h, "Remove selected resources");
|
||||
|
||||
assert!(h.query_by_label("one.png").is_none());
|
||||
assert!(h.query_by_label("two.png").is_some());
|
||||
assert!(combos(&h, "All files (1)").next().is_some());
|
||||
click(&mut h, "Import");
|
||||
assert_eq!(resources(&h), ["two.png"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_usage_defaults_to_undefined_and_the_choice_reaches_the_import() {
|
||||
let dir = TempDir::new("import-resources-usage");
|
||||
let mut h = app();
|
||||
invoke(&mut h);
|
||||
add(&mut h, &[png(&dir, "plain.png"), png(&dir, "brush.png"), png(&dir, "sky.png")]);
|
||||
assert_eq!(combos(&h, "undefined").count(), 3);
|
||||
|
||||
choose_usage(&mut h, 1, "alpha");
|
||||
choose_usage(&mut h, 1, "environment");
|
||||
click(&mut h, "Import");
|
||||
|
||||
assert_eq!(resources(&h), ["brush.png", "plain.png", "sky.png"]);
|
||||
let project = &h.state().session.doc.project;
|
||||
assert_eq!(project.display.environment_resource(), Some("sky.png"), "the environment usage lights the scene");
|
||||
assert_eq!(h.state().session.tool.brush.alpha_image.as_deref(), Some("brush.png"), "the alpha usage sets the brush alpha");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prefix_goes_in_front_of_the_resource_name() {
|
||||
let dir = TempDir::new("import-resources-prefix");
|
||||
let mut h = app();
|
||||
invoke(&mut h);
|
||||
add(&mut h, &[png(&dir, "dust.png")]);
|
||||
|
||||
h.get_by_role_and_label(Role::TextInput, PREFIX_HINT).click();
|
||||
h.run_steps(2);
|
||||
h.get_by_role_and_label(Role::TextInput, PREFIX_HINT).type_text("wear/");
|
||||
h.run_steps(3);
|
||||
click(&mut h, "Import");
|
||||
|
||||
assert_eq!(resources(&h), ["wear_dust.png"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_usages_and_the_user_library_are_listed_but_disabled() {
|
||||
let dir = TempDir::new("import-resources-disabled");
|
||||
let mut h = app();
|
||||
invoke(&mut h);
|
||||
add(&mut h, &[png(&dir, "x.png")]);
|
||||
|
||||
combos(&h, "undefined").next().expect("the dropdown").click();
|
||||
h.run_steps(3);
|
||||
for usage in ["colorlut", "postfx"] {
|
||||
assert!(h.get_by_label(usage).accesskit_node().is_disabled(), "{usage}");
|
||||
}
|
||||
assert!(!h.get_by_label("texture").accesskit_node().is_disabled());
|
||||
h.get_by_label("texture").click();
|
||||
h.run_steps(3);
|
||||
|
||||
combos(&h, "Open project").next().expect("the dropdown").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.get_by_label("Asset library").accesskit_node().is_disabled());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_imports_nothing() {
|
||||
let dir = TempDir::new("import-resources-cancel");
|
||||
let mut h = app();
|
||||
invoke(&mut h);
|
||||
add(&mut h, &[png(&dir, "never.png")]);
|
||||
click(&mut h, "Cancel");
|
||||
|
||||
assert!(!is_open(&h));
|
||||
assert!(resources(&h).is_empty());
|
||||
|
||||
// Reopening starts empty
|
||||
invoke(&mut h);
|
||||
assert!(combos(&h, "All files (0)").next().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_engine_command_still_imports_a_path_with_an_optional_prefix() {
|
||||
let dir = TempDir::new("import-resources-command");
|
||||
let file = png(&dir, "tile.png");
|
||||
let mut session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
|
||||
|
||||
let plain = texturecraft_engine::execute(&mut session, "resource.import", &serde_json::json!({"path": file.display().to_string()})).unwrap();
|
||||
let prefixed =
|
||||
texturecraft_engine::execute(&mut session, "resource.import", &serde_json::json!({"path": file.display().to_string(), "prefix": "a/b/"})).unwrap();
|
||||
|
||||
assert_eq!(plain["name"], "tile.png");
|
||||
assert_eq!(prefixed["name"], "a_b_tile.png");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_failed_rows_remain_after_a_partial_import() {
|
||||
let dir = TempDir::new("import-resources-retry");
|
||||
let good = png(&dir, "good.png");
|
||||
let failed = dir.join("retry.png");
|
||||
let mut h = app();
|
||||
invoke(&mut h);
|
||||
add(&mut h, &[good, failed.clone()]);
|
||||
choose_usage(&mut h, 1, "alpha");
|
||||
{
|
||||
let rows = &mut h.state_mut().ui.windows.import_resources.as_mut().unwrap().rows;
|
||||
rows[1].prefix = "brush_".into();
|
||||
}
|
||||
h.run_steps(2);
|
||||
|
||||
click(&mut h, "Import");
|
||||
|
||||
let rows = &h.state().ui.windows.import_resources.as_ref().expect("failed row stays open").rows;
|
||||
assert_eq!(rows.len(), 1);
|
||||
assert_eq!(rows[0].path, failed);
|
||||
assert_eq!(rows[0].prefix, "brush_");
|
||||
assert_eq!(resources(&h), ["good.png"]);
|
||||
|
||||
png(&dir, "retry.png");
|
||||
click(&mut h, "Import");
|
||||
|
||||
assert!(!is_open(&h));
|
||||
assert_eq!(resources(&h), ["brush_retry.png", "good.png"]);
|
||||
assert_eq!(h.state().session.tool.brush.alpha_image.as_deref(), Some("brush_retry.png"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_import_resources_replaces_project_configuration() {
|
||||
let mut h = app();
|
||||
let ctx = h.ctx.clone();
|
||||
texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "ui.projectConfig");
|
||||
assert!(h.state().ui.windows.project_config.is_some());
|
||||
|
||||
invoke(&mut h);
|
||||
|
||||
assert!(is_open(&h));
|
||||
assert!(h.state().ui.windows.project_config.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "offscreen GPU snapshot; set TC_UI_SNAPSHOTS to an output directory"]
|
||||
fn import_resources_snapshot() {
|
||||
let output_dir = PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS"));
|
||||
let dir = TempDir::new("import-resources-snapshot");
|
||||
let session = Session::new_project("Resources", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
h.run_steps(4);
|
||||
|
||||
invoke(&mut h);
|
||||
add(&mut h, &[png(&dir, "panel_basecolor.png"), png(&dir, "brush_alpha.png")]);
|
||||
choose_usage(&mut h, 1, "alpha");
|
||||
|
||||
std::fs::create_dir_all(&output_dir).unwrap();
|
||||
h.render().unwrap().save(output_dir.join("import-resources.png")).unwrap();
|
||||
}
|
||||
@@ -28,6 +28,7 @@ mod frame_selection;
|
||||
mod generator_panel;
|
||||
mod gradient_map_menu;
|
||||
mod history_panel;
|
||||
mod import_resources;
|
||||
mod inactive_set_hint;
|
||||
mod layer_blending_options;
|
||||
mod layer_clipboard;
|
||||
@@ -40,6 +41,7 @@ mod mask_value_swap;
|
||||
mod named_layouts;
|
||||
mod nav_buttons;
|
||||
mod new_project_baked_maps;
|
||||
mod new_project_window;
|
||||
mod path_in_view;
|
||||
mod path_list;
|
||||
mod pen_pressure;
|
||||
@@ -62,6 +64,7 @@ mod skew_paint;
|
||||
mod smudge_channels;
|
||||
mod snapped_lines;
|
||||
mod split_divider;
|
||||
mod temp_dir;
|
||||
mod template_invert;
|
||||
mod tool_availability;
|
||||
mod tool_settings_saved;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! New project ▸ Import baked maps: added files are listed, Clear empties the list, Create imports them
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
@@ -8,23 +8,33 @@ use texturecraft_engine::core::{BakedMap, NormalFormat};
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
use texturecraft_ui_egui::new_project_advanced::add_baked_map_files;
|
||||
|
||||
fn harness() -> Harness<'static, TextureCraftApp> {
|
||||
use super::temp_dir::TempDir;
|
||||
|
||||
/// Two quads with the materials Ball and Base, like the sample's texture sets
|
||||
const TWO_MATERIALS: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nv 0 0 1\nv 1 0 1\nv 1 1 1\nv 0 1 1\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\n\
|
||||
usemtl Ball\nf 1/1 2/2 3/3 4/4\nusemtl Base\nf 5/1 6/2 7/3 8/4\n";
|
||||
|
||||
/// The New project window with `test`'s mesh file (materials Ball and Base) selected
|
||||
fn harness_for(dir: &Path) -> Harness<'static, TextureCraftApp> {
|
||||
let mesh = dir.join("Ball.obj");
|
||||
std::fs::write(&mesh, TWO_MATERIALS).unwrap();
|
||||
let session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
h.state_mut().ui.windows.new_project = true;
|
||||
h.state_mut().ui.new_project.resolution = 256;
|
||||
h.run_steps(3);
|
||||
h.get_by_label("Advanced settings").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_label("Import baked maps").click();
|
||||
h.state_mut().ui.new_project.file = Some(mesh.display().to_string());
|
||||
h.run_steps(3);
|
||||
h
|
||||
}
|
||||
|
||||
/// Click Create (fixed below the form)
|
||||
fn create(h: &mut Harness<'_, TextureCraftApp>) {
|
||||
h.get_by_label("Create").click();
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
/// 4×4 PNGs named `files` in a fresh folder, as their full paths; green 0.2 shows which way a normal map was read
|
||||
fn bake_files(test: &str, files: &[&str]) -> Vec<String> {
|
||||
let dir = std::env::temp_dir().join(format!("texturecraft-np-baked-maps-{test}-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
fn bake_files(dir: &Path, files: &[&str]) -> Vec<String> {
|
||||
files
|
||||
.iter()
|
||||
.map(|file| {
|
||||
@@ -37,17 +47,19 @@ fn bake_files(test: &str, files: &[&str]) -> Vec<String> {
|
||||
|
||||
#[test]
|
||||
fn added_files_are_listed_once_and_clear_empties_the_list() {
|
||||
let mut h = harness();
|
||||
let paths = bake_files("list", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]);
|
||||
let dir = TempDir::new("new-project-baked-maps-list");
|
||||
let mut h = harness_for(&dir);
|
||||
let paths = bake_files(&dir, &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]);
|
||||
|
||||
add_baked_map_files(&mut h.state_mut().ui.new_project, paths.clone());
|
||||
add_baked_map_files(&mut h.state_mut().ui.new_project, paths);
|
||||
h.run_steps(3);
|
||||
|
||||
assert_eq!(h.state().ui.new_project.baked_maps.len(), 3, "each file once");
|
||||
for file in ["Ball_normal.png", "Base_ao.png", "Ball_notes.png"] {
|
||||
h.get_by_label(file);
|
||||
}
|
||||
let first = h.get_by_label("Ball_normal.png").rect();
|
||||
let second = h.get_by_label("Base_ao.png").rect();
|
||||
let third = h.get_by_label("Ball_notes.png").rect();
|
||||
assert!(first.bottom() < second.top() && second.bottom() < third.top(), "the files appear on separate rows");
|
||||
|
||||
h.get_by_label("Clear").click();
|
||||
h.run_steps(3);
|
||||
@@ -57,14 +69,14 @@ fn added_files_are_listed_once_and_clear_empties_the_list() {
|
||||
|
||||
#[test]
|
||||
fn create_imports_the_listed_maps_in_the_chosen_normal_format() {
|
||||
let mut h = harness();
|
||||
let paths = bake_files("create", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]);
|
||||
let dir = TempDir::new("new-project-baked-maps-create");
|
||||
let mut h = harness_for(&dir);
|
||||
let paths = bake_files(&dir, &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]);
|
||||
add_baked_map_files(&mut h.state_mut().ui.new_project, paths);
|
||||
h.state_mut().ui.new_project.normal_format = Some(NormalFormat::DirectX);
|
||||
h.run_steps(3);
|
||||
|
||||
h.get_by_label("Create").click();
|
||||
h.run_steps(3);
|
||||
create(&mut h);
|
||||
|
||||
let state = h.state();
|
||||
assert!(!state.ui.windows.new_project, "the dialog closes");
|
||||
@@ -83,24 +95,32 @@ fn create_imports_the_listed_maps_in_the_chosen_normal_format() {
|
||||
|
||||
#[test]
|
||||
fn a_failed_import_keeps_the_file_list_and_created_project() {
|
||||
let mut h = harness();
|
||||
let paths = bake_files("failure", &["Ball_normal.png", "Base_ao.png"]);
|
||||
let dir = TempDir::new("new-project-baked-maps-failure");
|
||||
let mut h = harness_for(&dir);
|
||||
let paths = bake_files(&dir, &["Ball_normal.png", "Base_ao.png"]);
|
||||
std::fs::write(&paths[1], b"not an image").unwrap();
|
||||
add_baked_map_files(&mut h.state_mut().ui.new_project, paths.clone());
|
||||
h.state_mut().ui.new_project.name = "Import failure".to_string();
|
||||
h.run_steps(3);
|
||||
|
||||
h.get_by_label("Create").click();
|
||||
h.run_steps(3);
|
||||
create(&mut h);
|
||||
|
||||
let app = h.state();
|
||||
assert!(!app.ui.windows.new_project);
|
||||
assert_eq!(app.session.doc.project.name, "Import failure");
|
||||
assert_eq!(app.session.doc.project.name, "Ball", "the project is named after the mesh file");
|
||||
assert_eq!(app.ui.new_project.baked_maps, paths);
|
||||
assert!(app.session.doc.resources.is_empty() && app.session.images.is_empty());
|
||||
assert!(app.session.doc.baked.values().all(|baked| baked.maps.is_empty()));
|
||||
let toast = app.toasts.last().unwrap();
|
||||
assert!(toast.error && toast.text.contains("Base_ao.png"), "{}", toast.text);
|
||||
|
||||
h.state_mut().ui.adopt_layout(texturecraft_ui_egui::UiState::default());
|
||||
let ctx = h.ctx.clone();
|
||||
texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "ui.newProject");
|
||||
h.run_steps(3);
|
||||
|
||||
assert_eq!(h.state().ui.new_project.baked_maps, paths);
|
||||
h.get_by_label("Ball_normal.png");
|
||||
h.get_by_label("Base_ao.png");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -114,14 +134,14 @@ fn new_project_baked_maps_snapshots() {
|
||||
eprintln!("snapshot adapter: {adapter:?}");
|
||||
TextureCraftApp::new(cc, session)
|
||||
});
|
||||
let dir = TempDir::new("new-project-baked-maps-snapshots");
|
||||
let mesh = dir.join("Ball.obj");
|
||||
std::fs::write(&mesh, TWO_MATERIALS).unwrap();
|
||||
h.state_mut().ui.windows.new_project = true;
|
||||
h.state_mut().ui.new_project.resolution = 256;
|
||||
h.state_mut().ui.new_project.file = Some(mesh.display().to_string());
|
||||
h.run_steps(6);
|
||||
h.get_by_label("Advanced settings").click();
|
||||
h.run_steps(6);
|
||||
h.get_by_label("Import baked maps").click();
|
||||
h.run_steps(6);
|
||||
let paths = bake_files("snapshots", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]);
|
||||
let paths = bake_files(&dir, &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]);
|
||||
add_baked_map_files(&mut h.state_mut().ui.new_project, paths);
|
||||
h.state_mut().ui.new_project.normal_format = Some(NormalFormat::DirectX);
|
||||
h.run_steps(6);
|
||||
@@ -135,11 +155,28 @@ fn new_project_baked_maps_snapshots() {
|
||||
h.run_steps(3);
|
||||
assert!(h.state().session.doc.baked[&0].maps.contains_key(&BakedMap::Normal));
|
||||
h.render().unwrap().save(output_dir.join("new-project-imported.png")).unwrap();
|
||||
|
||||
let ctx = h.ctx.clone();
|
||||
texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "ui.newProject");
|
||||
let paths = bake_files(&dir, &["Ball_normal.png"]);
|
||||
add_baked_map_files(&mut h.state_mut().ui.new_project, paths);
|
||||
h.run_steps(6);
|
||||
h.get_by_label("Ball_normal.png");
|
||||
|
||||
h.get_by_label("Cancel").click();
|
||||
h.run_steps(3);
|
||||
assert!(!h.state().ui.windows.new_project);
|
||||
texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "ui.newProject");
|
||||
h.run_steps(6);
|
||||
|
||||
assert!(h.query_by_label("Ball_normal.png").is_none());
|
||||
h.render().unwrap().save(output_dir.join("new-project-after-cancel.png")).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal_format_preview_uses_the_same_template_lookup_as_creation() {
|
||||
let mut h = harness();
|
||||
let dir = TempDir::new("new-project-baked-maps-template");
|
||||
let mut h = harness_for(&dir);
|
||||
h.state_mut().session.templates.dir = None;
|
||||
h.state_mut().run("textureSet.settings", serde_json::json!({"normalFormat": "directX"})).unwrap();
|
||||
h.state_mut().run("project.template.save", serde_json::json!({"name": "Custom DirectX"})).unwrap();
|
||||
@@ -147,7 +184,6 @@ fn normal_format_preview_uses_the_same_template_lookup_as_creation() {
|
||||
h.run_steps(3);
|
||||
|
||||
h.get_by_value("DirectX");
|
||||
h.get_by_label("Create").click();
|
||||
h.run_steps(3);
|
||||
create(&mut h);
|
||||
assert_eq!(h.state().session.doc.project.normal_format, NormalFormat::DirectX);
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
//! File > New project: the sections and their order, the defaults, settings shown disabled with a
|
||||
//! hint until TextureCraft has them, Create waiting for a mesh file, and the settings that reach
|
||||
//! the `file.new` command.
|
||||
|
||||
use egui::Role;
|
||||
use egui::accesskit::Toggled;
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
use texturecraft_engine::template_cmds::DEFAULT_TEMPLATE;
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
use texturecraft_ui_egui::file_dialogs::Answer;
|
||||
use texturecraft_ui_egui::new_project_advanced::create_command;
|
||||
use texturecraft_ui_egui::project_form::{NOT_AVAILABLE, OCIO_NOT_AVAILABLE};
|
||||
|
||||
use super::temp_dir::TempDir;
|
||||
|
||||
/// A quad whose UVs lie in UV tile 1002 and a camera-free OBJ
|
||||
const TILE_1002_QUAD: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 1.1 0.1\nvt 1.9 0.1\nvt 1.9 0.9\nvt 1.1 0.9\nf 1/1 2/2 3/3 4/4\n";
|
||||
|
||||
/// The app with New project opened from the menu, tall enough to show the whole form
|
||||
fn harness() -> Harness<'static, TextureCraftApp> {
|
||||
harness_sized(egui::vec2(1600.0, 2400.0))
|
||||
}
|
||||
|
||||
fn harness_sized(size: egui::Vec2) -> Harness<'static, TextureCraftApp> {
|
||||
let session = texturecraft_engine::Session::new_project("Open", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
|
||||
let mut h = Harness::builder().with_size(size).build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
h.state_mut().ui.prefs.language = "en".into();
|
||||
h.run_steps(2);
|
||||
let ctx = h.ctx.clone();
|
||||
texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "ui.newProject");
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
|
||||
fn mesh_file(dir: &std::path::Path, contents: &str) -> String {
|
||||
let path = dir.join("tiles.obj");
|
||||
std::fs::write(&path, contents).unwrap();
|
||||
|
||||
path.display().to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_drops_the_selected_mesh_buffer() {
|
||||
let mut h = harness();
|
||||
let bytes = std::sync::Arc::new(vec![0; 1024 * 1024]);
|
||||
let buffer = std::sync::Arc::downgrade(&bytes);
|
||||
h.state_mut().ui.new_project.file = Some("cancel.obj".into());
|
||||
h.state_mut().ui.new_project.file_bytes = Some(bytes);
|
||||
h.run_steps(3);
|
||||
|
||||
h.get_by_role_and_label(Role::Button, "Cancel").click();
|
||||
h.run_steps(3);
|
||||
|
||||
assert!(!h.state().ui.windows.new_project);
|
||||
assert!(buffer.upgrade().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_keeps_the_mesh_buffer_for_retry_and_drops_it_after_success() {
|
||||
let dir = TempDir::new("new-project-create-retry");
|
||||
let path = dir.join("retry.obj");
|
||||
let mut h = harness();
|
||||
let bytes = std::sync::Arc::new(vec![0; 2 * 1024 * 1024]);
|
||||
let buffer = std::sync::Arc::downgrade(&bytes);
|
||||
h.state_mut().ui.new_project.resolution = 128;
|
||||
h.state_mut().ui.new_project.file = Some(path.display().to_string());
|
||||
h.state_mut().ui.new_project.file_bytes = Some(bytes);
|
||||
h.run_steps(3);
|
||||
|
||||
h.get_by_role_and_label(Role::Button, "Create").click();
|
||||
h.run_steps(3);
|
||||
|
||||
assert!(h.state().ui.windows.new_project);
|
||||
assert!(buffer.upgrade().is_some());
|
||||
assert_eq!(h.state().session.doc.project.name, "Open");
|
||||
|
||||
std::fs::write(&path, TILE_1002_QUAD).unwrap();
|
||||
let color_map = dir.join("retry_basecolor.png");
|
||||
image::RgbaImage::new(4, 4).save(&color_map).unwrap();
|
||||
texturecraft_ui_egui::pbr_import::begin(h.state_mut(), serde_json::json!({"files": [color_map]}));
|
||||
assert!(h.state().pbr_import.is_some());
|
||||
h.get_by_role_and_label(Role::Button, "Create").click();
|
||||
h.run_steps(3);
|
||||
|
||||
assert!(!h.state().ui.windows.new_project);
|
||||
assert!(buffer.upgrade().is_none());
|
||||
assert!(h.state().pbr_import.is_none());
|
||||
assert_eq!(h.state().session.doc.project.name, "retry");
|
||||
}
|
||||
|
||||
fn top(h: &Harness<'_, TextureCraftApp>, label: &str) -> f32 {
|
||||
h.get_all_by_label(label).map(|node| node.rect().top()).fold(f32::INFINITY, f32::min)
|
||||
}
|
||||
|
||||
fn disabled(h: &Harness<'_, TextureCraftApp>, role: Role, label: &str) -> bool {
|
||||
h.get_by_role_and_label(role, label).accesskit_node().is_disabled()
|
||||
}
|
||||
|
||||
fn ticked(h: &Harness<'_, TextureCraftApp>, role: Role, label: &str) -> bool {
|
||||
h.get_by_role_and_label(role, label).accesskit_node().toggled() == Some(Toggled::True)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sections_follow_the_project_setup_order() {
|
||||
let h = harness();
|
||||
let order = [
|
||||
"BASIC SETTINGS",
|
||||
"3D mesh",
|
||||
"Project template",
|
||||
"Document resolution (px)",
|
||||
"ADVANCED SETTINGS",
|
||||
"Normal map format",
|
||||
"Compute tangent space per fragment",
|
||||
"UV Tile settings (UDIMs)",
|
||||
"You can enable or disable UV tiles later in Texture Set Settings.",
|
||||
"Use UV Tile workflow",
|
||||
"Keep UV tiles together per material",
|
||||
"Use a separate texture set for each tile",
|
||||
"Import settings",
|
||||
"Import cameras",
|
||||
"Auto-unwrap",
|
||||
"Import baked maps",
|
||||
"Import mesh normal maps and baked maps for all materials.",
|
||||
"Normal map filename: <texture set>_normal",
|
||||
"Physical size",
|
||||
"Use the mesh file’s unit scale",
|
||||
"Custom unit scale",
|
||||
"Scale material fills in real-world units",
|
||||
"Color management",
|
||||
"Working color space",
|
||||
];
|
||||
let tops: Vec<f32> = order.iter().map(|label| top(&h, label)).collect();
|
||||
for (pair, labels) in tops.windows(2).zip(order.windows(2)) {
|
||||
assert!(pair[0] < pair[1], "{} comes before {}: {pair:?}", labels[0], labels[1]);
|
||||
}
|
||||
assert!(h.query_by_label("Linear - sRGB Chrominance (ITU-R BT.709)").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_defaults_match_the_reference() {
|
||||
let h = harness();
|
||||
|
||||
assert!(h.query_by_label("No file selected").is_some());
|
||||
assert!(h.query_by_value(DEFAULT_TEMPLATE).is_some(), "the default template");
|
||||
assert!(h.query_by_value("1024 x 1024").is_some());
|
||||
assert!(h.query_by_value("OpenGL").is_some());
|
||||
assert!(h.query_by_value("Legacy").is_some());
|
||||
assert!(!ticked(&h, Role::CheckBox, "Compute tangent space per fragment"));
|
||||
assert!(!ticked(&h, Role::CheckBox, "Use UV Tile workflow"));
|
||||
assert!(ticked(&h, Role::RadioButton, "Keep UV tiles together per material"));
|
||||
assert!(disabled(&h, Role::RadioButton, "Keep UV tiles together per material"), "greyed while UV tiles are off");
|
||||
assert!(ticked(&h, Role::CheckBox, "Import cameras") && !disabled(&h, Role::CheckBox, "Import cameras"));
|
||||
assert!(ticked(&h, Role::CheckBox, "Auto-unwrap"));
|
||||
assert!(ticked(&h, Role::RadioButton, "Use the mesh file’s unit scale"));
|
||||
assert!(!ticked(&h, Role::CheckBox, "Scale material fills in real-world units"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn template_controls_name_and_built_in_meshes_are_gone() {
|
||||
let h = harness();
|
||||
|
||||
for label in ["Template name", "Save current project as template", "Name", "UV tiles (UDIM)"] {
|
||||
assert!(h.query_by_label(label).is_none(), "{label} is not in the window");
|
||||
}
|
||||
assert!(h.query_by_label_contains("Built-in:").is_none(), "no built-in mesh dropdown");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_waits_for_a_mesh_file() {
|
||||
let mut h = harness();
|
||||
|
||||
assert!(disabled(&h, Role::Button, "Create"));
|
||||
|
||||
let dir = TempDir::new("new-project-create-enabled");
|
||||
h.state_mut().ui.new_project.file = Some(mesh_file(&dir, TILE_1002_QUAD));
|
||||
h.run_steps(2);
|
||||
|
||||
assert!(!disabled(&h, Role::Button, "Create"));
|
||||
assert!(h.query_by_label("tiles.obj").is_some(), "the chosen file is shown");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_not_available_yet_are_disabled_with_a_hint() {
|
||||
let mut h = harness();
|
||||
let unavailable = [
|
||||
(Role::CheckBox, "Compute tangent space per fragment"),
|
||||
(Role::RadioButton, "Use a separate texture set for each tile"),
|
||||
(Role::CheckBox, "Auto-unwrap"),
|
||||
(Role::Button, "Auto-unwrap options"),
|
||||
(Role::RadioButton, "Custom unit scale"),
|
||||
(Role::CheckBox, "Scale material fills in real-world units"),
|
||||
];
|
||||
for (role, label) in unavailable {
|
||||
assert!(disabled(&h, role, label), "{label} is disabled");
|
||||
}
|
||||
assert!(!disabled(&h, Role::RadioButton, "Use the mesh file’s unit scale"));
|
||||
|
||||
for (role, label) in unavailable {
|
||||
let center = h.get_by_role_and_label(role, label).rect().center();
|
||||
h.hover_at(egui::pos2(1.0, 1.0));
|
||||
h.run_steps(2);
|
||||
assert!(h.query_by_label(NOT_AVAILABLE).is_none(), "no hint before hovering {label}");
|
||||
h.hover_at(center);
|
||||
h.run_steps(30);
|
||||
assert!(h.query_by_label(NOT_AVAILABLE).is_some(), "hovering {label} says it is not available yet");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opencolorio_shows_its_settings_disabled_and_creates_legacy() {
|
||||
let mut h = harness();
|
||||
|
||||
assert!(h.query_by_label("OpenColorIO configuration").is_none(), "Legacy shows only the working color space");
|
||||
assert!(h.query_by_label(OCIO_NOT_AVAILABLE).is_none(), "no OpenColorIO hint while Legacy is chosen");
|
||||
|
||||
h.get_by_value("Legacy").scroll_to_me();
|
||||
h.run_steps(3);
|
||||
h.get_by_value("Legacy").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_label("OpenColorIO").click();
|
||||
h.run_steps(3);
|
||||
|
||||
assert!(h.query_by_label(OCIO_NOT_AVAILABLE).is_some(), "the dropdown's hover hint says OpenColorIO is not available yet");
|
||||
for label in ["OpenColorIO configuration", "Configuration file", "Standard sRGB color space", "Auto detect color spaces", "Material color space default"] {
|
||||
assert!(h.query_by_label(label).is_some(), "{label} is shown");
|
||||
}
|
||||
assert!(h.query_by_label("ACEScg").is_some(), "the OpenColorIO working color space");
|
||||
let ocio_config = h.get_by_value("ACES 2.0");
|
||||
assert!(ocio_config.accesskit_node().is_disabled(), "the OpenColorIO settings are disabled");
|
||||
let center = ocio_config.rect().center();
|
||||
h.hover_at(center);
|
||||
h.run_steps(30);
|
||||
assert!(h.query_by_label(NOT_AVAILABLE).is_some(), "with the not-available hint");
|
||||
let params = create_command(&texturecraft_ui_egui::state::NewProject { file: Some("a.obj".into()), ..h.state().ui.new_project.clone() }).unwrap();
|
||||
assert!(params.get("colorManagement").is_none(), "nothing about color management reaches the command");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_menu_opens_a_fresh_form_after_cancel() {
|
||||
let mut h = harness();
|
||||
{
|
||||
let form = &mut h.state_mut().ui.new_project;
|
||||
form.file = Some("/old/mesh.obj".into());
|
||||
form.resolution = 4096;
|
||||
form.uv_tiles = Some(true);
|
||||
form.import_cameras = false;
|
||||
}
|
||||
queue_baked_maps(&mut h);
|
||||
|
||||
h.get_by_role_and_label(Role::Button, "Cancel").click();
|
||||
h.run_steps(3);
|
||||
assert!(!h.state().ui.windows.new_project);
|
||||
let ctx = h.ctx.clone();
|
||||
texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "ui.newProject");
|
||||
h.run_steps(3);
|
||||
|
||||
let form = &h.state().ui.new_project;
|
||||
assert_eq!((form.file.as_deref(), form.resolution, form.uv_tiles, form.import_cameras), (None, 1024, None, true));
|
||||
assert_eq!(form.template, DEFAULT_TEMPLATE);
|
||||
assert!(form.baked_maps.is_empty(), "canceled files stayed queued: {:?}", form.baked_maps);
|
||||
assert!(h.query_by_label("Ball_normal.png").is_none());
|
||||
}
|
||||
|
||||
fn queue_baked_maps(h: &mut Harness<'_, TextureCraftApp>) {
|
||||
h.state_mut().file_dialogs.set_override(Some(Box::new(|_| {
|
||||
Answer::Paths(["Ball_normal.png", "Ball_ao.png", "Ball_curvature.png"].into_iter().map(std::path::PathBuf::from).collect())
|
||||
})));
|
||||
h.get_by_role_and_label(Role::Button, "Add").click();
|
||||
h.run_steps(3);
|
||||
|
||||
h.get_by_label("Ball_normal.png");
|
||||
h.get_by_label("Ball_ao.png");
|
||||
h.get_by_label("Ball_curvature.png");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_the_form_from_its_title_bar_discards_baked_maps() {
|
||||
let mut h = harness();
|
||||
queue_baked_maps(&mut h);
|
||||
|
||||
h.get_by_role_and_label(Role::Button, "Close window").click();
|
||||
h.run_steps(3);
|
||||
|
||||
assert!(!h.state().ui.windows.new_project);
|
||||
assert!(h.state().ui.new_project.baked_maps.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invoking_new_project_again_discards_the_open_forms_baked_maps() {
|
||||
let mut h = harness();
|
||||
queue_baked_maps(&mut h);
|
||||
|
||||
let ctx = h.ctx.clone();
|
||||
texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "ui.newProject");
|
||||
h.run_steps(3);
|
||||
|
||||
assert!(h.state().ui.windows.new_project);
|
||||
assert!(h.query_by_label("Ball_normal.png").is_none());
|
||||
assert!(h.state().ui.new_project.baked_maps.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_supported_settings_reach_the_create_command() {
|
||||
let mut form = texturecraft_ui_egui::state::NewProject::default();
|
||||
|
||||
assert!(create_command(&form).is_none(), "no command without a mesh file");
|
||||
|
||||
form.file = Some("/meshes/robot.fbx".into());
|
||||
let params = create_command(&form).unwrap();
|
||||
|
||||
assert_eq!(params["mesh"], "/meshes/robot.fbx");
|
||||
assert_eq!(params["resolution"], 1024);
|
||||
assert_eq!(params["uvTiles"], false, "UV tiles are off unless ticked");
|
||||
assert_eq!(params["importCameras"], true);
|
||||
assert_eq!(params["template"], DEFAULT_TEMPLATE);
|
||||
assert!(params.get("name").is_none(), "the project is named after the file");
|
||||
|
||||
form.uv_tiles = Some(true);
|
||||
form.import_cameras = false;
|
||||
form.resolution = 2048;
|
||||
let params = create_command(&form).unwrap();
|
||||
|
||||
assert_eq!((params["uvTiles"].as_bool(), params["importCameras"].as_bool(), params["resolution"].as_u64()), (Some(true), Some(false), Some(2048)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ticking_uv_tiles_creates_a_uv_tile_project() {
|
||||
for (tick, expected) in [(false, Vec::<u32>::new()), (true, vec![1002])] {
|
||||
let mut h = harness();
|
||||
let dir = TempDir::new("new-project-udim");
|
||||
h.state_mut().ui.new_project.file = Some(mesh_file(&dir, TILE_1002_QUAD));
|
||||
h.state_mut().ui.new_project.resolution = 128;
|
||||
h.run_steps(2);
|
||||
if tick {
|
||||
h.get_by_role_and_label(Role::CheckBox, "Use UV Tile workflow").click();
|
||||
h.run_steps(3);
|
||||
assert!(!disabled(&h, Role::RadioButton, "Keep UV tiles together per material"));
|
||||
}
|
||||
h.get_by_role_and_label(Role::CheckBox, "Import cameras").click();
|
||||
h.run_steps(2);
|
||||
h.get_by_role_and_label(Role::Button, "Create").click();
|
||||
h.run_steps(3);
|
||||
|
||||
let app = h.state();
|
||||
assert!(!app.ui.windows.new_project, "the window closes");
|
||||
assert_eq!(app.session.doc.project.name, "tiles");
|
||||
assert_eq!(app.session.doc.project.texture_sets[0].uv_tiles, expected, "UV tiles ticked: {tick}");
|
||||
assert_eq!(app.session.doc.project.texture_sets[0].resolution, 128);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_stays_on_screen_in_a_short_window() {
|
||||
let h = harness_sized(egui::vec2(1024.0, 600.0));
|
||||
|
||||
let create = h.get_by_role_and_label(Role::Button, "Create").rect();
|
||||
let cancel = h.get_by_role_and_label(Role::Button, "Cancel").rect();
|
||||
|
||||
assert!(create.bottom() <= 600.0 && create.top() >= 0.0, "Create is visible without scrolling: {create:?}");
|
||||
assert!(cancel.bottom() <= 600.0, "{cancel:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picking_a_template_sets_its_resolution_and_normal_map_format() {
|
||||
let mut h = harness();
|
||||
h.state_mut().session.templates.dir = None;
|
||||
h.state_mut().run("textureSet.settings", serde_json::json!({"normalFormat": "directX"})).unwrap();
|
||||
h.state_mut().run("project.template.save", serde_json::json!({"name": "Small DirectX"})).unwrap();
|
||||
h.run_steps(2);
|
||||
|
||||
h.get_by_value(DEFAULT_TEMPLATE).click();
|
||||
h.run_steps(3);
|
||||
h.get_by_label("Small DirectX").click();
|
||||
h.run_steps(3);
|
||||
|
||||
assert!(h.query_by_value("Small DirectX").is_some());
|
||||
assert!(h.query_by_value("128 x 128").is_some(), "the template's resolution (the open project's 128 px)");
|
||||
assert!(h.query_by_value("DirectX").is_some(), "the template's normal map format");
|
||||
assert_eq!(h.state().ui.new_project.resolution, 128);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_asks_before_discarding_edits_made_after_the_form_opened() {
|
||||
let dir = TempDir::new("new-project-unsaved");
|
||||
let path = dir.join("tiles.obj");
|
||||
let mut h = harness();
|
||||
h.state_mut().ui.new_project.file = Some(path.display().to_string());
|
||||
h.state_mut().ui.new_project.resolution = 128;
|
||||
h.state_mut().run("layer.add.paint", serde_json::Value::Null).unwrap();
|
||||
h.run_steps(3);
|
||||
|
||||
h.get_by_role_and_label(Role::Button, "Create").click();
|
||||
h.run_steps(3);
|
||||
|
||||
assert!(h.query_by_label("Unsaved changes").is_some());
|
||||
assert_eq!(h.state().session.doc.project.name, "Open");
|
||||
|
||||
h.get_by_role_and_label(Role::Button, "Don't save").click();
|
||||
h.run_steps(3);
|
||||
|
||||
assert!(h.state().ui.windows.new_project);
|
||||
assert!(h.state().session.modified, "a failed replacement keeps the old project dirty");
|
||||
assert_eq!(h.state().session.doc.project.name, "Open");
|
||||
|
||||
std::fs::write(path, TILE_1002_QUAD).unwrap();
|
||||
h.get_by_role_and_label(Role::Button, "Create").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_role_and_label(Role::Button, "Don't save").click();
|
||||
h.run_steps(3);
|
||||
|
||||
assert_eq!(h.state().session.doc.project.name, "tiles");
|
||||
assert!(!h.state().ui.windows.new_project);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layout_that_closes_new_project_discards_selected_files() {
|
||||
let mut h = harness();
|
||||
queue_baked_maps(&mut h);
|
||||
let bytes = std::sync::Arc::new(vec![0; 1024 * 1024]);
|
||||
let buffer = std::sync::Arc::downgrade(&bytes);
|
||||
let ui = &mut h.state_mut().ui;
|
||||
ui.new_project.file = Some("reset.obj".into());
|
||||
ui.new_project.file_bytes = Some(bytes);
|
||||
|
||||
let mut open_layout = texturecraft_ui_egui::UiState::default();
|
||||
open_layout.windows.new_project = true;
|
||||
ui.adopt_layout(open_layout);
|
||||
|
||||
assert!(ui.windows.new_project);
|
||||
assert!(buffer.upgrade().is_some());
|
||||
assert!(!ui.new_project.baked_maps.is_empty());
|
||||
|
||||
ui.adopt_layout(texturecraft_ui_egui::UiState::default());
|
||||
|
||||
assert!(!ui.windows.new_project);
|
||||
assert!(buffer.upgrade().is_none());
|
||||
assert!(ui.new_project.baked_maps.is_empty());
|
||||
}
|
||||
@@ -9,8 +9,7 @@ use texturecraft_engine::Session;
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
use texturecraft_ui_egui::file_dialogs::{Answer, Request};
|
||||
|
||||
mod temp_dir;
|
||||
use temp_dir::TempDir;
|
||||
use super::temp_dir::TempDir;
|
||||
|
||||
const QUAD: &str = "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";
|
||||
const TRIANGLE: &str = "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";
|
||||
@@ -136,20 +135,95 @@ fn every_setting_has_an_info_icon_and_the_window_ends_with_a_note() {
|
||||
let icons: Vec<_> = h.get_all_by_label(egui_phosphor::regular::INFO).collect();
|
||||
let tip = "Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it.";
|
||||
|
||||
assert!(h.query_by_label("Choosing or reimporting a mesh recomputes all channels.").is_some(), "the note above the buttons");
|
||||
assert_eq!(icons.len(), 6, "mesh path, Select, Reimport mesh, Preserve strokes, Normal map format, UV tiles");
|
||||
assert!(h.query_by_label("Changing the mesh or normal format can recalculate texture channels.").is_some(), "the note above the buttons");
|
||||
assert_eq!(
|
||||
icons.len(),
|
||||
13,
|
||||
"3D mesh, Reimport mesh, Normal map format, tangent space, UV tiles and its two layouts, Import cameras, Preserve strokes, Auto-unwrap, \
|
||||
Physical size, Color management, Working color space"
|
||||
);
|
||||
assert!(h.query_by_label(tip).is_none(), "no tooltip before hovering");
|
||||
|
||||
// The format icon is fifth in the window's rows
|
||||
// The format icon is third in the window's rows
|
||||
let mut centers: Vec<_> = icons.iter().map(|n| n.rect().center()).collect();
|
||||
centers.sort_by(|a, b| a.y.total_cmp(&b.y));
|
||||
let format_center = centers[4];
|
||||
let format_center = centers[2];
|
||||
h.hover_at(format_center);
|
||||
h.run_steps(30);
|
||||
|
||||
assert!(h.query_by_label(tip).is_some(), "hovering the normal map format icon explains it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_window_follows_the_reference_layout() {
|
||||
let dir = temp_dir("layout");
|
||||
let mut h = app_on_a_quad(&dir);
|
||||
h.set_size(egui::vec2(1600.0, 2000.0));
|
||||
|
||||
open_window(&mut h);
|
||||
|
||||
let order = [
|
||||
"3D MESH",
|
||||
"Reimport mesh",
|
||||
"PROJECT SETTINGS",
|
||||
"Compute tangent space per fragment",
|
||||
"UV Tile settings (UDIMs)",
|
||||
"Change the UV tiles of a texture set in Texture Set Settings",
|
||||
"Use UV Tile workflow",
|
||||
"Use a separate texture set for each tile",
|
||||
"Import settings",
|
||||
"Import cameras",
|
||||
"Preserve stroke positions on mesh",
|
||||
"Auto-unwrap",
|
||||
"Physical size",
|
||||
"Working color space",
|
||||
];
|
||||
let top = |label: &str| h.get_all_by_label(label).map(|n| n.rect().top()).fold(f32::INFINITY, f32::min);
|
||||
for labels in order.windows(2) {
|
||||
assert!(top(labels[0]) < top(labels[1]), "{} comes before {}", labels[0], labels[1]);
|
||||
}
|
||||
assert!(h.query_by_label("Custom unit scale").is_none(), "Physical size starts collapsed");
|
||||
let disabled = |role: Role, label: &str| h.get_by_role_and_label(role, label).accesskit_node().is_disabled();
|
||||
for (role, label) in [
|
||||
(Role::CheckBox, "Compute tangent space per fragment"),
|
||||
(Role::CheckBox, "Use UV Tile workflow"),
|
||||
(Role::RadioButton, "Keep UV tiles together per material"),
|
||||
(Role::RadioButton, "Use a separate texture set for each tile"),
|
||||
(Role::CheckBox, "Import cameras"),
|
||||
(Role::CheckBox, "Auto-unwrap"),
|
||||
(Role::Button, "Auto-unwrap options"),
|
||||
] {
|
||||
assert!(disabled(role, label), "{label} is disabled");
|
||||
}
|
||||
|
||||
let center = h.get_by_role_and_label(Role::CheckBox, "Compute tangent space per fragment").rect().center();
|
||||
h.hover_at(center);
|
||||
h.run_steps(30);
|
||||
assert!(h.query_by_label("Not available yet").is_some(), "the hint of a setting TextureCraft does not have yet");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opencolorio_can_be_looked_at_but_changes_nothing() {
|
||||
let dir = temp_dir("ocio");
|
||||
let mut h = app_on_a_quad(&dir);
|
||||
h.set_size(egui::vec2(1600.0, 2000.0));
|
||||
open_window(&mut h);
|
||||
let before = h.state().session.doc.project.clone();
|
||||
|
||||
h.get_by_value("Legacy").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_label("OpenColorIO").click();
|
||||
h.run_steps(3);
|
||||
|
||||
assert!(h.query_by_label("Bitmap import color space defaults").is_some());
|
||||
assert!(h.query_by_label("Export color spaces").is_some());
|
||||
|
||||
click(&mut h, Role::Button, "OK");
|
||||
|
||||
assert!(!window_is_open(&h));
|
||||
assert_eq!(h.state().session.doc.project, before, "OK applies nothing for color management");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_file_shows_its_path_and_ticks_reimport() {
|
||||
let dir = temp_dir("select");
|
||||
@@ -553,8 +627,9 @@ fn uv_tiles_are_shown_read_only() {
|
||||
open_window(&mut h);
|
||||
|
||||
assert!(h.query_by_label("UV Tile settings (UDIMs)").is_some());
|
||||
assert!(h.query_by_label("No UV tiles").is_some(), "a project without UV tiles");
|
||||
assert!(h.query_by_label("Change them in Texture Set Settings").is_some());
|
||||
hover_uv_tile_box(&mut h);
|
||||
assert!(h.query_by_label_contains("No UV tiles").is_some(), "a project without UV tiles");
|
||||
assert!(h.query_by_label("Change the UV tiles of a texture set in Texture Set Settings").is_some());
|
||||
|
||||
click(&mut h, Role::Button, "Cancel");
|
||||
|
||||
@@ -562,8 +637,16 @@ fn uv_tiles_are_shown_read_only() {
|
||||
|
||||
open_window(&mut h);
|
||||
|
||||
assert!(h.query_by_label("No UV tiles").is_none());
|
||||
assert!(h.query_by_label("1001").is_some(), "the tile list of a UDIM project");
|
||||
hover_uv_tile_box(&mut h);
|
||||
assert!(h.query_by_label_contains("No UV tiles").is_none());
|
||||
assert!(h.query_by_label_contains("1001").is_some(), "the tile list of a UDIM project");
|
||||
}
|
||||
|
||||
/// Hover the disabled Use UV Tile workflow box, whose hint lists the project's UV tiles.
|
||||
fn hover_uv_tile_box(h: &mut Harness<'_, TextureCraftApp>) {
|
||||
let center = h.get_by_role_and_label(Role::CheckBox, "Use UV Tile workflow").rect().center();
|
||||
h.hover_at(center);
|
||||
h.run_steps(30);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -720,3 +803,29 @@ fn a_format_the_project_already_has_is_not_set_again() {
|
||||
assert_eq!(project_normal_format(&h), NormalFormat::DirectX);
|
||||
assert_eq!(h.state().session.history_labels().len(), steps, "no extra undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "offscreen GPU snapshots; set TC_UI_SNAPSHOTS to an output directory"]
|
||||
fn project_config_snapshots() {
|
||||
let output_dir = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS"));
|
||||
std::fs::create_dir_all(&output_dir).unwrap();
|
||||
let dir = temp_dir("snapshots");
|
||||
let file = dir.join("quad.obj");
|
||||
std::fs::write(&file, QUAD).unwrap();
|
||||
let mut session = Session::from_mesh_bytes("quad.obj", QUAD.as_bytes(), 128, "quad").unwrap();
|
||||
session.doc.project.mesh_path = file.display().to_string();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
h.run_steps(6);
|
||||
open_window(&mut h);
|
||||
h.run_steps(6);
|
||||
h.render().unwrap().save(output_dir.join("project-config-legacy.png")).unwrap();
|
||||
h.get_by_value("Legacy").scroll_to_me();
|
||||
h.run_steps(3);
|
||||
h.get_by_value("Legacy").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_label("OpenColorIO").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_label("Export color spaces").scroll_to_me();
|
||||
h.run_steps(6);
|
||||
h.render().unwrap().save(output_dir.join("project-config-ocio.png")).unwrap();
|
||||
}
|
||||
@@ -348,3 +348,193 @@ fn procedurals_are_in_the_textures_type() {
|
||||
|
||||
assert!(harness.query_by_label(ProceduralKind::ALL[0].label()).is_some());
|
||||
}
|
||||
|
||||
/// The reference's type dropdown, top to bottom
|
||||
const TYPE_DROPDOWN: [&str; 10] =
|
||||
["Materials", "Smart materials", "Smart masks", "Filters", "Brushes", "Alphas", "Textures", "Environments", "Fonts", "Show all"];
|
||||
|
||||
/// The node labelled `label` added last (a popup's entry is newer than any other with its label)
|
||||
fn latest_node_with_label<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &'a str) -> egui_kittest::Node<'a> {
|
||||
harness.get_all_by_label(label).last().unwrap_or_else(|| panic!("no {label}"))
|
||||
}
|
||||
|
||||
/// Hover `label` long enough for its tooltip and tell whether the "Not available yet" hint shows
|
||||
fn shows_not_available(harness: &mut Harness<'_, TextureCraftApp>, label: &str) -> bool {
|
||||
let center = latest_node_with_label(harness, label).rect().center();
|
||||
harness.hover_at(center);
|
||||
harness.run_steps(30);
|
||||
|
||||
harness.query_by_label("Not available yet").is_some()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_type_dropdown_lists_the_reference_entries_in_order() {
|
||||
let mut harness = shelf(NARROW_WINDOW);
|
||||
button(&harness, "Filter by type").click();
|
||||
harness.run_steps(3);
|
||||
|
||||
let tops: Vec<f32> = TYPE_DROPDOWN.iter().map(|label| latest_node_with_label(&harness, label).rect().top()).collect();
|
||||
assert!(tops.windows(2).all(|pair| pair[0] < pair[1]), "the entries run top to bottom in the reference order: {tops:?}");
|
||||
for label in TYPE_DROPDOWN {
|
||||
let disabled = latest_node_with_label(&harness, label).accesskit_node().is_disabled();
|
||||
assert_eq!(disabled, label == "Fonts", "only Fonts is greyed: {label}");
|
||||
}
|
||||
assert!(shows_not_available(&mut harness, "Fonts"), "Fonts explains why it is greyed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_all_unpicks_the_type() {
|
||||
let mut harness = shelf(NARROW_WINDOW);
|
||||
button(&harness, "Filter by type").click();
|
||||
harness.run_steps(3);
|
||||
|
||||
latest_node_with_label(&harness, "Show all").click();
|
||||
harness.run_steps(3);
|
||||
|
||||
assert!(harness.query_by_label(SMART_MASKS[0].label).is_some(), "Show all restores assets from another type");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_panes_list_the_reference_rows_and_grey_the_missing_ones() {
|
||||
let mut harness = shelf(REFERENCE_WINDOW);
|
||||
harness.state_mut().ui.shelf_panes.saved_searches = true;
|
||||
harness.state_mut().ui.shelf_panes.filter_by_path = true;
|
||||
harness.run_steps(3);
|
||||
|
||||
let saved = ["SAVED SEARCHES", "All", "Favorites", "3D Assets", "Flattened layers"];
|
||||
let paths = ["FILTER BY PATH", "All libraries", "Project", "Starter assets", "Your assets", "System fonts", "User fonts"];
|
||||
for rows in [&saved[..], &paths[..]] {
|
||||
let tops: Vec<f32> = rows.iter().map(|label| latest_node_with_label(&harness, label).rect().top()).collect();
|
||||
assert!(tops.windows(2).all(|pair| pair[0] < pair[1]), "{rows:?} run top to bottom: {tops:?}");
|
||||
}
|
||||
for label in ["Favorites", "3D Assets", "Flattened layers", "System fonts", "User fonts"] {
|
||||
assert!(latest_node_with_label(&harness, label).accesskit_node().is_disabled(), "{label} is greyed");
|
||||
}
|
||||
for label in ["All", "All libraries", "Project", "Starter assets", "Your assets"] {
|
||||
assert!(!latest_node_with_label(&harness, label).accesskit_node().is_disabled(), "{label} works");
|
||||
}
|
||||
assert!(shows_not_available(&mut harness, "Flattened layers"), "a greyed saved search explains itself");
|
||||
assert!(shows_not_available(&mut harness, "User fonts"), "a greyed library explains itself");
|
||||
|
||||
button(&harness, "Hide non-applicable folders").click();
|
||||
harness.run_steps(3);
|
||||
|
||||
assert!(harness.query_by_label("System fonts").is_none());
|
||||
assert!(harness.query_by_label("User fonts").is_none());
|
||||
assert!(harness.query_by_label("Starter assets").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_splitter_resizes_both_panes_and_the_split_is_saved() {
|
||||
let mut harness = shelf(REFERENCE_WINDOW);
|
||||
harness.state_mut().ui.shelf_panes.saved_searches = true;
|
||||
harness.state_mut().ui.shelf_panes.filter_by_path = true;
|
||||
harness.run_steps(3);
|
||||
|
||||
let initial_share = harness.state().ui.shelf_panes_split;
|
||||
let heading = harness.get_by_label("FILTER BY PATH").rect();
|
||||
let save_button = harness.get_by_label("Save the current search").rect().top();
|
||||
assert!(heading.top() > save_button, "the path pane sits below the saved searches");
|
||||
|
||||
const DRAG_DISTANCE_POINTS: f32 = 120.0;
|
||||
const POSITION_TOLERANCE_POINTS: f32 = 2.0;
|
||||
let divider = harness.get_by_label("Resize Assets filter panes").rect();
|
||||
let from = egui::pos2(divider.center().x, divider.top() + 1.0);
|
||||
let to = from + egui::vec2(0.0, DRAG_DISTANCE_POINTS);
|
||||
harness.hover_at(from);
|
||||
harness.run_steps(1);
|
||||
harness.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
|
||||
harness.run_steps(2);
|
||||
|
||||
assert_eq!(harness.state().ui.shelf_panes_split, initial_share, "an off-center press leaves the splitter in place");
|
||||
|
||||
for step in 1..=4 {
|
||||
harness.hover_at(from + (to - from) * (step as f32 / 4.0));
|
||||
harness.run_steps(1);
|
||||
}
|
||||
harness.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
|
||||
harness.run_steps(3);
|
||||
|
||||
let moved = harness.get_by_label("FILTER BY PATH").rect();
|
||||
assert!((moved.top() - heading.top() - DRAG_DISTANCE_POINTS).abs() < POSITION_TOLERANCE_POINTS, "the path pane follows the drag: {heading:?} to {moved:?}");
|
||||
assert!(harness.state().ui.shelf_panes_split > initial_share, "saved searches take a larger share");
|
||||
assert!(harness.query_by_label("User fonts").is_some(), "the shorter path pane still lists its rows");
|
||||
|
||||
// States saved before the splitter existed still load the default
|
||||
let saved = serde_json::to_value(&harness.state().ui).unwrap();
|
||||
let restored: texturecraft_ui_egui::state::UiState = serde_json::from_value(saved.clone()).unwrap();
|
||||
assert_eq!(restored.shelf_panes_split, harness.state().ui.shelf_panes_split);
|
||||
let mut older = saved;
|
||||
assert!(older.as_object_mut().unwrap().remove("shelf_panes_split").is_some(), "the saved state names the split");
|
||||
let restored: texturecraft_ui_egui::state::UiState = serde_json::from_value(older).unwrap();
|
||||
assert_eq!(restored.shelf_panes_split, initial_share);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_smallest_saved_search_pane_can_scroll_to_and_select_the_last_query() {
|
||||
let mut harness = shelf(REFERENCE_WINDOW);
|
||||
harness.state_mut().ui.shelf_panes.saved_searches = true;
|
||||
harness.state_mut().ui.shelf_panes.filter_by_path = true;
|
||||
harness.state_mut().ui.shelf_panes_split = 0.0;
|
||||
harness.state_mut().ui.shelf_saved_searches =
|
||||
vec![SavedSearch { name: "Rust search".into(), filter: "rust".into(), tab: MATERIALS_TYPE, path: Vec::new() }];
|
||||
harness.run_steps(3);
|
||||
|
||||
scroll_pane_to_end(&mut harness, "SAVED SEARCHES");
|
||||
|
||||
let last_row = harness.get_by_label("Rust search").rect();
|
||||
let next_heading = harness.get_by_label("FILTER BY PATH").rect();
|
||||
assert!(last_row.center().y < next_heading.top(), "the final search should be inside its pane: {last_row:?}");
|
||||
|
||||
harness.get_by_label("Rust search").click();
|
||||
harness.run_steps(3);
|
||||
|
||||
assert_eq!(harness.state().ui.shelf_filter, "rust");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_smallest_path_pane_can_scroll_to_its_last_library() {
|
||||
let mut harness = shelf(REFERENCE_WINDOW);
|
||||
harness.state_mut().ui.shelf_panes.saved_searches = true;
|
||||
harness.state_mut().ui.shelf_panes.filter_by_path = true;
|
||||
harness.state_mut().ui.shelf_panes_split = 1.0;
|
||||
harness.run_steps(3);
|
||||
|
||||
scroll_pane_to_end(&mut harness, "FILTER BY PATH");
|
||||
|
||||
let last_row = harness.get_by_label("User fonts").rect();
|
||||
let toolbar = button(&harness, "Filter by path").rect();
|
||||
assert!(last_row.center().y < toolbar.top(), "the final library should be above the toolbar: {last_row:?}");
|
||||
}
|
||||
|
||||
fn scroll_pane_to_end(harness: &mut Harness<'_, TextureCraftApp>, heading: &str) {
|
||||
let heading = harness.get_by_label(heading).rect();
|
||||
harness.hover_at(egui::pos2(heading.left() + 24.0, heading.bottom() + 12.0));
|
||||
harness.run_steps(1);
|
||||
|
||||
harness.event(egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: egui::vec2(0.0, -1000.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
source: egui::MouseWheelSource::Wheel,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
});
|
||||
harness.run_steps(8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_splitter_is_exposed_as_a_resizable_control() {
|
||||
let mut harness = shelf(REFERENCE_WINDOW);
|
||||
harness.state_mut().ui.shelf_panes.saved_searches = true;
|
||||
harness.state_mut().ui.shelf_panes.filter_by_path = true;
|
||||
harness.run_steps(3);
|
||||
|
||||
let before = harness.state().ui.shelf_panes_split;
|
||||
|
||||
let divider = harness.get_by_label("Resize Assets filter panes");
|
||||
assert_eq!(divider.accesskit_node().role(), egui::accesskit::Role::Splitter);
|
||||
divider.increment_accesskit();
|
||||
harness.run_steps(3);
|
||||
|
||||
assert!(harness.state().ui.shelf_panes_split > before);
|
||||
}
|
||||
+6
-2
@@ -1,12 +1,16 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
/// A test folder removed when its owner drops
|
||||
pub(super) struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
pub(super) fn new(test: &str) -> Self {
|
||||
let path = std::env::temp_dir().join(format!("texturecraft-project-config-{test}-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&path).unwrap();
|
||||
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
|
||||
let path = std::env::temp_dir().join(format!("texturecraft-{test}-{}-{id}", std::process::id()));
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
|
||||
Self(path)
|
||||
}
|
||||
+25
-9
@@ -68,13 +68,15 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
|
||||
effect selected, Ctrl+D and Delete duplicate or remove it.
|
||||
- **Fill layers** take uniform values, **43 procedurals** (clouds, cells, grunge, scratches, wood
|
||||
grain, bricks, fabric weave, twill, leather grain, marble veins, Voronoi, paint chips, hexagon
|
||||
tiles, wave scales, herringbone planks, halftone dots, Truchet arcs, and seamless organic
|
||||
surfaces: smooth fur, mackerel sky, soft billow, reptile scales, young bark, rotting flesh, camouflage, knit, basket
|
||||
weave, goose-eye twill, slub silk, strip flooring, knotty wood…) or your own **images**, through UV, tri-planar, planar, spherical, cylindrical or decal projection, with
|
||||
the UV scale, rotation and offset, the tri-planar blend sharpness and offset, the planar axis
|
||||
and offset, and the cylindrical axis in the fill's properties. Each channel takes its own image (a normal, roughness or height map, say): pick it in the channel's
|
||||
source menu, which also imports one, or drop it from the Assets panel onto the channel. A
|
||||
normal map image made for DirectX (Y down) is marked with **DirectX normal map** under it.
|
||||
tiles, wave scales, herringbone planks, halftone dots, diamond brocade, Truchet arcs, smooth
|
||||
fur, mackerel sky, soft billow, reptile scales, young bark, rotting flesh, camouflage, knit
|
||||
stitches, basket weave, goose-eye twill, slub silk, strip flooring, knotty wood…) or your own
|
||||
**images**. Patterns and images support UV, tri-planar, planar, spherical, cylindrical and
|
||||
decal projection. The fill's properties expose UV scale, rotation and offset, tri-planar blend
|
||||
sharpness and offset, planar axis and offset, and cylindrical axis. Each channel takes its own
|
||||
image (a normal, roughness or height map, say). Pick it in the channel's source menu, which
|
||||
also imports one, or drop it from the Assets panel onto the channel. A normal map image made
|
||||
for DirectX (Y down) is marked with **DirectX normal map** under it.
|
||||
A color channel's procedural or anchor point takes a **gradient map** (*Gradient Map* in the
|
||||
channel's source menu): up to 16 color stops, dark to light, color the pattern, or recolor
|
||||
the stack below by its lightness, without touching the other channels. The **Gradient map**
|
||||
@@ -90,6 +92,11 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
|
||||
the brush's material: the next stroke paints its pattern (colour, metallic, roughness, height),
|
||||
fixed to the surface and sized with the brush. A click on a smart material, which is several
|
||||
layers, only highlights it; drag it to add its layers.
|
||||
- **Import resources:** *File › Import resources...* opens a window: *Add resources* (images and
|
||||
materials), an optional name prefix and a role for each image. Environment images light the scene,
|
||||
and alpha images become the brush alpha. Filter by role or remove selected rows before importing.
|
||||
Failed rows stay in the dialog for retry. Color LUT, post effects and asset-library import are
|
||||
unavailable. The browser imports images straight from its file picker.
|
||||
- **Your own library:** right-click a layer or folder, choose *Create smart material*, and it
|
||||
appears under *My smart materials*, pixels and images included. *Create smart mask* in the same
|
||||
menu saves just the layer's mask (all its effects, painted pixels and images); it appears under
|
||||
@@ -106,14 +113,23 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
|
||||
## Files and texture sets
|
||||
|
||||
- **Open** glTF/GLB, FBX (binary and ASCII), COLLADA, **USD** (usda, usdc, usdz), **Alembic**,
|
||||
OBJ, PLY and STL, or a built-in mesh; UVs are generated when a mesh has none. A `.gltf`'s buffers
|
||||
OBJ, PLY and STL, or a built-in mesh (the `project.new` command; *File › Open sample project...* opens the
|
||||
material ball); UVs are generated when a mesh has none. A `.gltf`'s buffers
|
||||
and images and a loose USD layer's textures are read from its folder and kept in the project.
|
||||
Reimport a changed mesh and your painted strokes stay on the surface. The
|
||||
`file.changeMesh` command (trusted local command API and the control channel) moves the project onto a different mesh file and keeps its layers.
|
||||
**Edit › Project Configuration...** (desktop) does the same from the 3D MESH section: *Select...* picks the
|
||||
file, *Reimport mesh* is ticked for you (or tick it alone to read the same file again), OK applies. *Import settings* decides whether painted
|
||||
strokes follow the surface (on by default), and PROJECT SETTINGS sets the project's normal map format and
|
||||
lists its UV tiles (read only; Texture Set Settings changes them).
|
||||
shows its UV tiles in the UV workflow tooltip. Edit the tiles in Texture Set Settings.
|
||||
Physical size and color management show the same settings as New project.
|
||||
- **File › New project...** opens a setup form with BASIC SETTINGS (*Select...* a mesh file,
|
||||
the project template, the document resolution; Create waits for a mesh) and ADVANCED SETTINGS (normal
|
||||
map format, *Use UV Tile workflow*, *Import cameras*, *Import baked maps*, physical size, color
|
||||
management). The project is named after the mesh file. Settings TextureCraft does not have yet
|
||||
(tangent space per fragment, UV tiles as separate texture sets, turning auto-unwrap off and its
|
||||
options, a custom unit scale, OpenColorIO) are shown disabled with a hint; projects use Legacy color
|
||||
management. In the browser, *Select...* opens the browser's file picker.
|
||||
- **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile (blurs,
|
||||
other filters and height-to-normal slopes keep their size in UV space at any tile resolution)
|
||||
and one texture per tile on export (`$udim`).
|
||||
|
||||
+9
-1
@@ -61,6 +61,14 @@ The relevant implementations are [layer rows, menus and fill/brush editors](../c
|
||||
|---|---|---|---|
|
||||
| UI-12 | Generator depth and property coverage | **UI + source.** The picker contains seven kinds. Switching to Position, changing Global balance and duplicating the effect worked. Shared global adjustments, resolution and input slots already exist; that does not establish the richer generator/control inventory in [#374](https://github.com/storytold/texturecraft/issues/374) | Audit each generator's inputs, micro-detail behavior and controls against the reference; do not count seven shared implementations as equivalent to its whole catalog |
|
||||
| UI-13 | Narrow workspace readability | **UI.** At 1280 × 800 the app rendered, both views stayed visible and the toolbar exposed scroll arrows. Layer names/types became heavily truncated, the layer toolbar wrapped, and Properties needed scrolling. This was not an input-failure or docking-persistence test | Repeat the editing tasks at smaller sizes, widen/rearrange panels, check full-name tooltips and keyboard access, and retain the layout after restart. Since then: the Layers toolbar stays on one row at 1280 × 800 (its channel box shrinks), and a cut-short layer name or type shows in full on hover. Properties scrolling and restart persistence are unchanged |
|
||||
| UI-14 | Assets panel filters | **UI + source.** The type dropdown lists the reference entries in its order, Fonts and Show all included. Saved searches and Filter by path are separate scrollable panes with a divider that supports pointer and keyboard resizing and saves its position with the UI state ([#640](https://github.com/storytold/texturecraft/issues/640)). Fonts, the built-in saved searches Favorites, 3D Assets and Flattened layers, and the System fonts and User fonts libraries are listed but greyed with "Not available yet" | Give fonts, favorites, 3D assets and flattened layers real assets, then enable those rows and check that each one filters the grid |
|
||||
|
||||
File > Import resources ([#638](https://github.com/storytold/texturecraft/issues/638)) queues
|
||||
images and materials for the open project. Images support a name prefix and a usage. Texture
|
||||
and undefined usages store the image, while environment and alpha also apply it to the scene
|
||||
or brush. Filter the list by usage or remove rows before importing. Color LUT, post effects
|
||||
and asset-library import remain unavailable. The browser imports images straight from its file
|
||||
picker.
|
||||
|
||||
Broader properties/filter work remains tracked in
|
||||
[#433](https://github.com/storytold/texturecraft/issues/433). Its individual rows need checking
|
||||
@@ -73,7 +81,7 @@ list, not a feature-completion denominator.
|
||||
|
||||
| Check | Surface | Result | Observable evidence / limit |
|
||||
|---|---|---|---|
|
||||
| F01 New project | UI | Pass | Ctrl+N, built-in Cube, 1024 px, Create produced a new project with one empty paint layer. The native mesh-file selection path was not completed in this deeper pass |
|
||||
| F01 New project | UI | Pass (tests) | The window no longer offers built-in meshes ([#636](https://github.com/storytold/texturecraft/issues/636)). `tests/it/new_project_window.rs` covers the section order, the defaults, the disabled settings and their hint, Create waiting for a mesh file, and a UV tile project created from a mesh file. A manual pass with the native file picker is still to do |
|
||||
| F02 Paint in 3D | UI | Pass | A mouse drag produced a visible stroke in 3D and its UV representation; inspection showed a Paint stroke undo step and painted tiles |
|
||||
| F03 Paint in 2D | UI | Pass | A separate UV-view drag increased painted tiles from 7 to 21 per active channel and changed the visible image |
|
||||
| F04 Undo and redo | UI | Pass | Ctrl+Z restored 7 tiles and history depth 2; Ctrl+Y restored 21 tiles and depth 3 |
|
||||
|
||||
Reference in new issue
Block a user