mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-30 02:04:32 +01:00
Merge main into feat/craft-xtask-pins-one-commit
This commit is contained in:
commit
13a06bccd9
422 files changed
+49308
-2117
No files matched your search
@@ -27,6 +27,7 @@ author, source and license. Library code and original assets are under the repos
|
||||
| `crates/text/assets/hyphen/en-us.pat` | DesignCraft contributors, trained from the Moby Hyphenator II list | `crates/text/examples/hyphgen.rs` | CC0-1.0 |
|
||||
| Patterns embedded through `hypher` (optional `craft-text` language features) | hyph-utf8 authors, per language | [tex-hyphen](https://github.com/hyphenation/tex-hyphen), as packaged in [hypher](https://github.com/typst/hypher/tree/main/patterns) | Per file header: LPPL, MIT, BSD-3-Clause, Unlicense or a permit-any-use notice (or a choice including one); Slovak (`hyph-sk.tex`, embedded whenever `hypher/slovak` is on: feature `slovak-gpl`, or another dependency through feature unification) is GPL-2.0-or-later; Spanish (`hyph-es.tex` 5.0, Javier Bezos, CervanTeX) is MIT |
|
||||
| Word-break dictionaries and LSTM models embedded through `icu_segmenter_data` (optional `craft-text` features `thai`, `lao`, `khmer`, `burmese`) | Unicode, Inc. and ICU4X contributors | [ICU4X](https://github.com/unicode-org/icu4x) | Unicode-3.0 |
|
||||
| MikkTSpace tangent generation compiled in through `mikktspace` (`craft-mesh-ops`) | Benjamin Wasty, David Harvey-Macaulay and Layl Bongers; translated from the C original by Morten S. Mikkelsen | [mikktspace 0.3.0](https://crates.io/crates/mikktspace/0.3.0), [gltf-rs/mikktspace](https://github.com/gltf-rs/mikktspace) | MIT OR Apache-2.0 (the package's `license` field); its `src/generated.rs` also carries the C original's 2011 notice, reproduced in [`crates/mesh-ops/ATTRIBUTION.md`](crates/mesh-ops/ATTRIBUTION.md) |
|
||||
| `crates/ui/tests/fonts/NotoSansArabic-test.ttf` (subset to the test strings, default weight set to 100, width axis dropped) | The Noto Project Authors | [google/fonts@7085eb8 `ofl/notosansarabic`](https://github.com/google/fonts/tree/7085eb89a950e85db5b166b7a58d414544b4140c/ofl/notosansarabic), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansArabic.txt`) |
|
||||
| `crates/ui/tests/fonts/NotoSansCJKsc-test.otf` (subset to the test strings) | The Noto Project Authors (Adobe, Google) | [notofonts/noto-cjk@f8d1575 `Sans/OTF/SimplifiedChinese`](https://github.com/notofonts/noto-cjk/tree/f8d157532fbfaeda587e826d4cd5b21a49186f7c/Sans/OTF/SimplifiedChinese), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansCJK.txt`) |
|
||||
| `crates/imaging/tests/fonts/NotoSansArabic-digits.ttf` (instance at weight 400 and width 100, subset to the Arabic-Indic digits and separators U+0660–U+066C) | The Noto Project Authors | [google/fonts@7085eb8 `ofl/notosansarabic`](https://github.com/google/fonts/tree/7085eb89a950e85db5b166b7a58d414544b4140c/ofl/notosansarabic), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansArabic.txt`) |
|
||||
|
||||
Generated
+44
-2
@@ -1865,6 +1865,7 @@ dependencies = [
|
||||
"craft-media-source",
|
||||
"craft-menu",
|
||||
"craft-mesh",
|
||||
"craft-mesh-ops",
|
||||
"craft-metadata",
|
||||
"craft-metafile",
|
||||
"craft-midi",
|
||||
@@ -3445,6 +3446,17 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-mesh-ops"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"glam 0.30.10",
|
||||
"mikktspace",
|
||||
"rayon",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
@@ -3607,6 +3619,9 @@ version = "0.1.0"
|
||||
name = "craft-pbr"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-materialx",
|
||||
"craft-mesh",
|
||||
"craft-pbr",
|
||||
"craft-texture",
|
||||
"glam 0.30.10",
|
||||
"naga",
|
||||
@@ -4330,10 +4345,13 @@ name = "craft-testkit"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"png 0.18.1",
|
||||
"rustix 1.1.6",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"skrifa 0.47.0",
|
||||
"tempfile",
|
||||
"toml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4367,8 +4385,12 @@ name = "craft-texture"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"craft-exr",
|
||||
"craft-hdr",
|
||||
"craft-image-codecs",
|
||||
"dds",
|
||||
"half",
|
||||
"png 0.18.1",
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -4970,10 +4992,14 @@ name = "craft-xtask"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"flate2",
|
||||
"libc",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"toml_edit",
|
||||
"unicode-normalization",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6847,6 +6873,12 @@ dependencies = [
|
||||
"xml-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glam"
|
||||
version = "0.15.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3abb554f8ee44336b72d522e0a7fe86a29e09f839a36022fa869a7dfe941a54b"
|
||||
|
||||
[[package]]
|
||||
name = "glam"
|
||||
version = "0.25.0"
|
||||
@@ -6858,6 +6890,9 @@ name = "glam"
|
||||
version = "0.30.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glifo"
|
||||
@@ -8386,8 +8421,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "kurbo"
|
||||
version = "0.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"euclid",
|
||||
@@ -8703,6 +8736,15 @@ version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a86d3146ed3995b5913c414f6664344b9617457320782e64f0bb44afd49d74"
|
||||
|
||||
[[package]]
|
||||
name = "mikktspace"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d0b56b403871a8f992ca626d52cc0a690d4841baea8955dc4af6304ac62f8b0"
|
||||
dependencies = [
|
||||
"glam 0.15.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mime"
|
||||
version = "0.3.17"
|
||||
|
||||
+3
-1
@@ -1,7 +1,7 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/*"]
|
||||
exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2", "vendor/hayro-cmap", "vendor/hayro-postscript", "vendor/linesweeper", "vendor/vello_common", "vendor/vello_cpu"]
|
||||
exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2", "vendor/hayro-cmap", "vendor/hayro-postscript", "vendor/linesweeper", "vendor/vello_common", "vendor/vello_cpu", "vendor/kurbo"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
@@ -136,6 +136,7 @@ craft-gcode = { path = "crates/gcode" }
|
||||
craft-gif = { path = "crates/gif" }
|
||||
craft-hdr = { path = "crates/hdr" }
|
||||
craft-mesh = { path = "crates/mesh" }
|
||||
craft-mesh-ops = { path = "crates/mesh-ops" }
|
||||
craft-html = { path = "crates/html" }
|
||||
craft-ipp = { path = "crates/ipp" }
|
||||
craft-heif = { path = "crates/heif" }
|
||||
@@ -324,6 +325,7 @@ hayro-postscript = { path = "vendor/hayro-postscript" }
|
||||
linesweeper = { path = "vendor/linesweeper" }
|
||||
vello_common = { path = "vendor/vello_common" }
|
||||
vello_cpu = { path = "vendor/vello_cpu" }
|
||||
kurbo = { path = "vendor/kurbo" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
|
||||
@@ -63,6 +63,10 @@ craft-proof Language data, embedded at build time from craft-i18n's language-dat
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
|
||||
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
mikktspace 0.3.0 (https://crates.io/crates/mikktspace/0.3.0), a dependency of crates/mesh-ops,
|
||||
is MIT OR Apache-2.0. Its src/generated.rs, a translation of Morten S. Mikkelsen's C
|
||||
MikkTSpace, carries that original's 2011 zlib-style notice, which must not be removed or
|
||||
altered; crates/mesh-ops/ATTRIBUTION.md reproduces it in full.
|
||||
crates/text/assets/hyphen/en-us.pat: CC0-1.0, trained from en-us.dic by DesignCraft's trainer.
|
||||
crates/text/assets/spell/en-us-scowl-50.txt.deflate: SCOWL (Spell Checker Oriented Word Lists)
|
||||
2020.12.07, size 50, American English, Copyright 2000-2018 by Kevin Atkinson, http://wordlist.aspell.net/.
|
||||
@@ -229,6 +233,17 @@ The colour management module in crates/cms is extracted from:
|
||||
Licensed MIT OR Apache-2.0. Its generated ICC profile is dedicated to the public domain
|
||||
(CC0-1.0); see ATTRIBUTION.md.
|
||||
|
||||
The mesh operations in crates/mesh-ops are moved from:
|
||||
- TextureCraft, crates/geom (src/mesh.rs, bvh.rs, primitives.rs, gbuffer.rs, unwrap.rs,
|
||||
camera.rs and their tests), revision 386630ee85cb22679295b24013575d1aecb39ad2.
|
||||
https://github.com/storytold/texturecraft
|
||||
Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors.
|
||||
- MaterialCraft, crates/geom/src/mesh.rs (subdivision and its test), revision
|
||||
3133062968b8a1566eda12a357cb06062db16687.
|
||||
https://github.com/storytold/materialcraft
|
||||
Copyright (c) 2026 ArtCraft Team and the MaterialCraft contributors.
|
||||
All licensed MIT OR Apache-2.0.
|
||||
|
||||
The image-based lighting in crates/pbr (craft-pbr) is adapted from:
|
||||
- TextureCraft, crates/render/src/ibl.rs, revision fe8ee1bdb0243335560d3e726633cc0433ee99fc,
|
||||
copied without its tests to crates/pbr/tests/it/reference/texturecraft.rs.
|
||||
@@ -288,11 +303,18 @@ applications retain their own document-font selection and licensing policy.
|
||||
linesweeper
|
||||
|
||||
linesweeper 0.5.0 (https://crates.io/crates/linesweeper/0.5.0), MIT OR Apache-2.0, is stored in
|
||||
vendor/linesweeper with its upstream license files and local patches, to src/sweep/sweep_line.rs,
|
||||
src/segments.rs, src/curve/transverse.rs, src/curve/mod.rs, src/curve/line.rs and docs/sweep.typ. Its
|
||||
manifest names Joe Neeman as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See
|
||||
vendor/linesweeper with its upstream license files and local changes. Its manifest names Joe Neeman
|
||||
as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See
|
||||
vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local
|
||||
patches and the files left out.
|
||||
changes and the files left out.
|
||||
|
||||
kurbo
|
||||
|
||||
kurbo 0.13.1 (https://crates.io/crates/kurbo/0.13.1, https://github.com/linebender/kurbo), MIT OR
|
||||
Apache-2.0, is stored in vendor/kurbo with its upstream license files and local patches, to
|
||||
src/stroke.rs. Its source files carry "Copyright <year> the Kurbo Authors" lines (2018 to 2026),
|
||||
and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See vendor/kurbo/README.craft.md and
|
||||
vendor/kurbo/SOURCE.json for provenance and the local patches.
|
||||
|
||||
Platform lifecycle source provenance
|
||||
|
||||
|
||||
@@ -329,6 +329,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
of polygons with per-corner indices, materials, a node hierarchy): STL, OBJ with MTL, PLY,
|
||||
glTF 2.0 / GLB, FBX and 3MF, one feature each. Readers are bounded by `Limits`, never open a file
|
||||
themselves and never panic. Carved from EffectCraft, SolidCraft, TextureCraft and MaterialCraft.
|
||||
- [`craft-mesh-ops`](crates/mesh-ops/README.md): operations on triangle meshes: smooth normals,
|
||||
MikkTSpace tangents, welding, UV unwrapping, a UV-space G-buffer, primitives with UVs and a
|
||||
BVH for ray casts, and an orbit camera. From TextureCraft and MaterialCraft.
|
||||
- [`craft-midi`](crates/midi/README.md): Standard MIDI Files: a bounded reader for formats 0, 1 and
|
||||
2 and a format-1 writer, over a neutral model of notes and channel events in ticks at 960 per
|
||||
quarter note. From SoundCraft.
|
||||
@@ -432,7 +435,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
prints a `SKIPPED:` line when a test lacks a program, a corpus or the craft-fonts faces, or fails the
|
||||
test when the variable the caller names is `1`. Any other value of that variable except empty fails
|
||||
the test as a configuration error. Its `corpus` module (the `corpus` feature) checks a corpus folder
|
||||
against a pinned SHA-256 list. Not published.
|
||||
against a pinned SHA-256 list. Its `fixtures` module (native targets only) generates test fixtures
|
||||
under `target/fixtures` and publishes each one under a lock. Not published.
|
||||
- [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds
|
||||
hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns
|
||||
for 47 more languages (one cargo feature each). With `ui`, the canvas text editor, Character and
|
||||
@@ -440,8 +444,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
(ruler, Tabs, Paragraph, Columns and Hyperlink dialogs, notes editor, find); `spell` and `find`
|
||||
(regex) are features.
|
||||
- [`craft-texture`](crates/texture/README.md): linear float image planes, gray or RGBA, with
|
||||
nearest and bilinear sampling that repeats or clamps, resizing and display conversion. Sizes are
|
||||
bounded by `Limits`. From MaterialCraft.
|
||||
nearest and bilinear sampling that repeats or clamps, resizing and display conversion, and
|
||||
(optional features) PNG, TIFF, Radiance HDR and OpenEXR decoding that keeps 16-bit and float
|
||||
samples. Sizes are bounded by `Limits`. From MaterialCraft.
|
||||
- [`craft-timeline`](crates/timeline/README.md): timelines: exact media time, frame rates,
|
||||
timecode, the playback clock, a frame cache and frame server, and editorial interchange (ALE,
|
||||
CMX 3600 EDL, Final Cut Pro 7 XML, FCPXML, OpenTimelineIO), all egui-free; the timeline panel,
|
||||
|
||||
@@ -257,3 +257,11 @@ pub fn container(entries: &[(&str, &[u8], Method)], thumbnail_png: Option<&[u8]>
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What `f` gives, and how many paragraph ends the reader looked up on this thread while it ran
|
||||
/// to give each character run its paragraph's format.
|
||||
pub fn count_paragraph_lookups<T>(f: impl FnOnce() -> T) -> (T, usize) {
|
||||
crate::text::MATCH_READS.with(|reads| reads.set(0));
|
||||
let value = f();
|
||||
(value, crate::text::MATCH_READS.with(std::cell::Cell::get))
|
||||
}
|
||||
@@ -240,12 +240,26 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<Te
|
||||
// Sorted by end (they are in order in every file), so both lookups below are binary
|
||||
// searches: a block can have as many paragraphs and runs as characters.
|
||||
paragraphs.sort_by_key(|(end, _)| *end);
|
||||
let align_at = |i: usize| paragraphs.get(paragraphs.partition_point(|(end, _)| *end <= i)).map(|(_, a)| *a).or(open).unwrap_or_default();
|
||||
let align_at = |i: usize| {
|
||||
let at = paragraphs.partition_point(|(end, _)| {
|
||||
count_match_read();
|
||||
*end <= i
|
||||
});
|
||||
paragraphs.get(at).map(|(_, a)| *a).or(open).unwrap_or_default()
|
||||
};
|
||||
let mut cuts: Vec<usize> = paragraphs.iter().map(|(end, _)| *end).filter(|e| *e < chars.len()).collect();
|
||||
cuts.dedup();
|
||||
let push = |r: &mut Reader, runs: &mut Vec<TextRun>, attrs: Option<ObjId>, from: usize, to: usize, budget: &mut Option<usize>| {
|
||||
// Split at paragraph ends so every run has one paragraph format.
|
||||
let inside = cuts.get(cuts.partition_point(|c| *c <= from)..cuts.partition_point(|c| *c < to)).unwrap_or_default();
|
||||
let first = cuts.partition_point(|c| {
|
||||
count_match_read();
|
||||
*c <= from
|
||||
});
|
||||
let past = cuts.partition_point(|c| {
|
||||
count_match_read();
|
||||
*c < to
|
||||
});
|
||||
let inside = cuts.get(first..past).unwrap_or_default();
|
||||
let mut a = from;
|
||||
for &c in inside.iter().chain(std::iter::once(&to)) {
|
||||
push_run(r, runs, attrs, characters(&chars, a, c), world, budget, align_at(a));
|
||||
@@ -282,6 +296,18 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<Te
|
||||
(runs, first_align.unwrap_or(Align::Left))
|
||||
}
|
||||
|
||||
// Each paragraph end `story_runs` reads to match character runs to paragraphs, on this thread.
|
||||
#[cfg(any(test, feature = "synth"))]
|
||||
std::thread_local! {
|
||||
pub(crate) static MATCH_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn count_match_read() {
|
||||
#[cfg(any(test, feature = "synth"))]
|
||||
MATCH_READS.with(|reads| reads.set(reads.get().saturating_add(1)));
|
||||
}
|
||||
|
||||
fn characters(chars: &[char], start: usize, end: usize) -> String {
|
||||
chars.get(start..end).unwrap_or_default().iter().filter(|c| **c != '\0' && **c != '\u{FFFC}').collect()
|
||||
}
|
||||
|
||||
@@ -111,25 +111,32 @@ fn a_shared_story_is_read_within_the_characters_of_one_document() {
|
||||
|
||||
#[test]
|
||||
fn many_paragraphs_and_runs_are_matched_in_about_linear_time() {
|
||||
// 200 000 paragraphs, each with its own run and format.
|
||||
let n = 200_000;
|
||||
let text = "a\u{2029}".repeat(n);
|
||||
let fmt =
|
||||
|end: usize| vec![(tag(b"Indx"), F::I32(end as i32)), (tag(b"Item"), F::Obj(tag(b"PAtt"), vec![(tag(b"Ints"), array_i32(b"Ints", &[1]))]))];
|
||||
let blk = F::Obj(
|
||||
tag(b"StBl"),
|
||||
vec![
|
||||
(tag(b"Glyp"), utf8(&text)),
|
||||
(tag(b"GAtt"), F::Obj(tag(b"GlAS"), vec![(tag(b"Runs"), F::Objs(tag(b"GlAR"), (1..=n).map(|i| run(2 * i as i32, None)).collect()))])),
|
||||
(tag(b"PAtt"), F::Obj(tag(b"PaAS"), vec![(tag(b"Runs"), F::Objs(tag(b"PaAR"), (1..=n).map(|i| fmt(2 * i)).collect()))])),
|
||||
],
|
||||
);
|
||||
let started = std::time::Instant::now();
|
||||
let d = open(vec![artistic(F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(vec![blk]))]))]);
|
||||
let Kind::Text(t) = &d.spreads[0].nodes[0].kind else { panic!("text") };
|
||||
assert_eq!(t.runs.len(), n);
|
||||
// (About half a second; quadratic matching took over half a minute on the same machine.)
|
||||
assert!(started.elapsed().as_secs() < 10, "{:?}", started.elapsed());
|
||||
// `n` paragraphs, each with its own run and format, and how many paragraph ends matching
|
||||
// them looks up.
|
||||
let lookups = |n: usize| {
|
||||
let text = "a\u{2029}".repeat(n);
|
||||
let fmt = |end: usize| {
|
||||
vec![(tag(b"Indx"), F::I32(end as i32)), (tag(b"Item"), F::Obj(tag(b"PAtt"), vec![(tag(b"Ints"), array_i32(b"Ints", &[1]))]))]
|
||||
};
|
||||
let blk = F::Obj(
|
||||
tag(b"StBl"),
|
||||
vec![
|
||||
(tag(b"Glyp"), utf8(&text)),
|
||||
(tag(b"GAtt"), F::Obj(tag(b"GlAS"), vec![(tag(b"Runs"), F::Objs(tag(b"GlAR"), (1..=n).map(|i| run(2 * i as i32, None)).collect()))])),
|
||||
(tag(b"PAtt"), F::Obj(tag(b"PaAS"), vec![(tag(b"Runs"), F::Objs(tag(b"PaAR"), (1..=n).map(|i| fmt(2 * i)).collect()))])),
|
||||
],
|
||||
);
|
||||
let story = artistic(F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(vec![blk]))]));
|
||||
let (d, lookups) = synth::count_paragraph_lookups(|| open(vec![story]));
|
||||
let Kind::Text(t) = &d.spreads[0].nodes[0].kind else { panic!("text") };
|
||||
assert_eq!(t.runs.len(), n);
|
||||
lookups
|
||||
};
|
||||
// Four times the paragraphs and runs: a few binary searches each, so about four times the
|
||||
// lookups (a little more for the longer searches), where matching each run against every
|
||||
// paragraph is sixteen times.
|
||||
let (quarter, full) = (lookups(50_000), lookups(200_000));
|
||||
assert!(full <= 5 * quarter, "{quarter} lookups for 50,000 paragraphs, {full} for 200,000");
|
||||
}
|
||||
|
||||
/// A shape node of `size` px.
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
/// The longest step motion integrates, in seconds, so a stalled pass never jumps the view.
|
||||
pub const FRAME_STEP_MAX: f64 = 0.1;
|
||||
|
||||
/// The step of a pass that came `dt` seconds after the previous one, `dt` being the time between two readings of the
|
||||
/// caller's pass clock: `dt` within `0..=FRAME_STEP_MAX`, and 0 where it is not a number.
|
||||
/// The step of a pass that came `dt` seconds after the previous one, kept within `0..=FRAME_STEP_MAX`.
|
||||
///
|
||||
/// `dt` is the time between two readings of the caller's pass clock; where it is not a number, the step is 0.
|
||||
pub fn frame_step(dt: f64) -> f64 {
|
||||
if dt.is_finite() { dt.clamp(0.0, FRAME_STEP_MAX) } else { 0.0 }
|
||||
}
|
||||
@@ -155,14 +155,13 @@ file is committed.
|
||||
| R72 | In the version 15 samples an `mcfg` chunk starts with the tag 1300 and the length of the rest of the chunk, then 4 bytes of 0 (the 12 bytes R10 names), and each `fild` chunk sits in a `LIST filc` of its own inside `LIST filt` | S: the 15 LT `testset/15` files without text (every `mcfg` starts with 1300 and its size less 8; each of their 31 `fild` chunks is the only chunk of a `LIST filc`) | sample (the reader skips the 12 bytes and finds `fild` chunks at any depth) |
|
||||
| R73 | The specification reads the id in a container's argument 8005 (R46) as the stored u32 plus 1, halved, and the `spnd` id as stored. Sample files hold the same stored u32 in both places, even ids included, which the halved reading would not match. The writer numbers containers 1, 2, 3 and so on, and writes the same number in the clipped group's `spnd` | KF L799-L807 (`powerclip_id`), L2305-L2312 (`spnd`); S: the container and `spnd` of LT `powerclipsquare_blackfill_whiterectangleinside.cdr` of `testset/12` (156091928) and `powerclipsquare_blackfill_whiterectangleinside_cdr15.cdr` (1), the eight UC files `corel_powerclip_*` of versions 7 to 13 (47834832) and TDF 114901 (515235504) | sample (the halved reading: not followed) |
|
||||
| R74 | `rscr`: a u16 count, then one field list per screen entry, which a `rotl` entry names (R58). The reader does not read it; the `.cmx` writer writes one entry whose field 1 holds the 13 bytes `00 00 3c 00 00 00 00 00 40 a5 ae 02 00` | S: each of the nine CX files with 32-bit coordinates has an `rscr` of one entry with a 13-byte field 1, these bytes in seven of them (`bars.cmx` and `thatch.cmx` differ in bytes 2 and 8 to 11) | sample |
|
||||
| R77 | The index of a file with 32-bit coordinates, which the reader does not read. `cont` bytes 84, 88 and 92 hold the u32 file offsets of the master index `ixmr`, of `LIST INFO` and of the picture of the drawing (`DISP`), 0xFFFFFFFF for one the file does not hold. Each offset here names where a chunk's id starts. `LIST indx` holds a layer table `ixlr`, then `ixtl`, `ixpg` and `ixmr`. `ixmr`: the u16 values 1 and 24, a u16 count, then a u16 id and a u32 offset for each entry: 1 `ixmr` itself, 2 `ixpg`, 3 `ixtl`, 15 `rotl`, 16 `rott`, 17 `rota`, 18 `rscr`, 19 `rpen`, 20 `rdot`, 21 `rclr`, 22 `ccmm`; a table the file does not hold has no entry. `ixpg`: a u16 count, then for each page a u16 record size of 16 and four u32: the page chunk, its layer table, its picture (0xFFFFFFFF for none) and its reference list `rlst`. `ixtl`: a u16 count, a u16 record size of 4, the u16 type 3 (layer tables), then the u32 offset of each layer table. `ixlr`: a u16 count of the page's layers and the u16 value 1, then for each layer in file order a u16 size (8 plus the name's length), the u32 offset of its begin-layer instruction, its name as a u16 count and 8-bit characters, and 0xFFFFFFFF after the size. `rlst`: a u16 count of the page's layers, then the u16 values 2 and 9 and the layer's number for each. Begin page's field 1 ends with the u32 offset of the end-page instruction, a u16 count of the page's layers and a u32 count of its instructions, begin and end page included; begin layer's field 1 holds a u32 count of the layer's instructions, begin and end layer included, at bytes 8 to 12; begin group's field 1 holds the left, top, right and bottom edges of its curves (i32), a u16 count of the groups directly inside it, a u32 count of its instructions, begin and end group included, and the u32 offset of the instruction after its end | LC `CMXParser.cpp` L260-L286 (the three offsets, 0xFFFFFFFF for none), L346-L413 (`ixmr`: two u16, the count, the id and offset pairs), L545-L590 (begin group: the edges, a u16, the command count and the end address), L1974-L2019 (`ixtl`: the count, the record size, the type), L2060-L2096 (`ixpg`: the count, the record size and four offsets for each page), `CMXParser.h` L24-L41 (the ids); S: every CX file with 32-bit coordinates holds these chunks in this order, its `ixmr` entries name these chunks with these ids, the values 1 and 24 and `ixtl` type 3, its `ixpg` names its one page, the one `ixlr` and the `rlst`, its `ixlr` names its layers' begin-layer instructions with their names and the value 1, its `rlst` holds 2, 9 and the number of each of its layers, and the counts and offsets in its 9 pages, 33 layers and 12 groups match the instructions; 8 of the 12 groups hold the edges of their curves' points | sample (the order, `ixlr`, `rlst`, the values 1 and 24, the counts and offsets in the records), public-reader (the header's offsets, the `ixmr` ids, `ixpg`, `ixtl` and the order of begin group's fields; the samples agree), unconfirmed (the group count counting only the groups directly inside, as no sample nests groups two deep; the value 1 in a layer table of a page after the first) |
|
||||
| R77 | The index of a file with 32-bit coordinates, which the reader does not read. `cont` bytes 84, 88 and 92 hold the u32 file offsets of the master index `ixmr`, of `LIST INFO` and of the picture of the drawing (`DISP`), 0xFFFFFFFF for one the file does not hold. Each offset here names where a chunk's id starts. `cont` bytes 96 to 112 hold four i32 edges, the same bytes as the edges in the page's begin-page record, and bytes 112 to 116 a u32, the page's instruction count as begin page holds it. `LIST indx` holds a layer table `ixlr`, then `ixtl`, `ixpg` and `ixmr`. `ixmr`: the u16 values 1 and 24, a u16 count, then a u16 id and a u32 offset for each entry: 1 `ixmr` itself, 2 `ixpg`, 3 `ixtl`, 15 `rotl`, 16 `rott`, 17 `rota`, 18 `rscr`, 19 `rpen`, 20 `rdot`, 21 `rclr`, 22 `ccmm`; a table the file does not hold has no entry. `ixpg`: a u16 count, then for each page a u16 record size of 16 and four u32: the page chunk, its layer table, its picture (0xFFFFFFFF for none) and its reference list `rlst`. `ixtl`: a u16 count, a u16 record size of 4, the u16 type 3 (layer tables), then the u32 offset of each layer table. `ixlr`: a u16 count of the page's layers and the u16 value 1, then for each layer in file order a u16 size (8 plus the name's length), the u32 offset of its begin-layer instruction, its name as a u16 count and 8-bit characters, and 0xFFFFFFFF after the size. `rlst`: a u16 count of the page's layers, then the u16 values 2 and 9 and the layer's number for each. Begin page's field 1 ends with the u32 offset of the end-page instruction, a u16 count of the page's layers and a u32 count of its instructions, begin and end page included; begin layer's field 1 holds a u32 count of the layer's instructions, begin and end layer included, at bytes 8 to 12; begin group's field 1 holds the left, top, right and bottom edges of its curves (i32), a u16 count of the groups directly inside it, a u32 count of its instructions, begin and end group included, and the u32 offset of the instruction after its end | LC `CMXParser.cpp` L260-L286 (the three offsets, 0xFFFFFFFF for none; four coordinates after them, read only for a debug message), L1011-L1019 (the four coordinates of a box), L346-L413 (`ixmr`: two u16, the count, the id and offset pairs), L545-L590 (begin group: the edges, a u16, the command count and the end address), L1974-L2019 (`ixtl`: the count, the record size, the type), L2060-L2096 (`ixpg`: the count, the record size and four offsets for each page), `CMXParser.h` L24-L41 (the ids); S: every CX file with 32-bit coordinates holds these chunks in this order, its `ixmr` entries name these chunks with these ids, the values 1 and 24 and `ixtl` type 3, its `ixpg` names its one page, the one `ixlr` and the `rlst`, its `ixlr` names its layers' begin-layer instructions with their names and the value 1, its `rlst` holds 2, 9 and the number of each of its layers, and the counts and offsets in its 9 pages, 33 layers and 12 groups match the instructions; in each of the 9 files, `cont` bytes 96 to 116 match its one page's edges and instruction count; 8 of the 12 groups hold the edges of their curves' points | sample (the order, `ixlr`, `rlst`, the values 1 and 24, the counts and offsets in the records, the header's edges and instruction count), public-reader (the header's offsets, the `ixmr` ids, `ixpg`, `ixtl` and the order of begin group's fields; the samples agree), unconfirmed (the group count counting only the groups directly inside, as no sample nests groups two deep; the value 1 in a layer table of a page after the first) |
|
||||
|
||||
## Written fields
|
||||
|
||||
`src/cmx_write.rs` writes `.cmx` files in the layouts of the rows above, nothing else. The table
|
||||
lists every field it sets. `own` marks a value the reader does not read, which the writer sets as
|
||||
the synthetic test files of `src/synth_cmx.rs` set it. The header's bounds and instruction count
|
||||
at bytes 96 to 116 are not written.
|
||||
the synthetic test files of `src/synth_cmx.rs` set it.
|
||||
|
||||
| Field written | Rows | Status |
|
||||
|---|---|---|
|
||||
@@ -170,6 +169,7 @@ at bytes 96 to 116 are not written.
|
||||
| Chunk order: `cont`, each `page` chunk followed by its `rlst`, then `rclr`, `rpen`, `rott`, `rdot`, `rotl`, `rota` and `rscr`, then `LIST indx` | R53, R77 | sample (`page`, `rlst`, the tables, `LIST indx`), own (the order of the tables; the `rlst` of a page after the first) |
|
||||
| `cont`: `4` at byte 52, the unit 1e-7 m as an f64 at bytes 64 to 72 | R54 | sample |
|
||||
| `cont`: the offset of `ixmr` at bytes 84 to 88, 0xFFFFFFFF for the information list and the picture at bytes 88 to 96 | R77 | public-reader, sample (the picture), own (no information list) |
|
||||
| `cont`: the first page's edges at bytes 96 to 112 and its instruction count at bytes 112 to 116, as its begin-page record holds them; zeros for a file with no page | R77 | sample (one page), the writer's choice (the first page of several, and zeros) |
|
||||
| `cont`: `2` at bytes 48 and 54, zeros elsewhere, 180 bytes | R54 | own |
|
||||
| `LIST indx`: a layer table `ixlr` for each page, `ixtl` listing them, `ixpg` with each page, and `ixmr` with itself, `ixpg`, `ixtl` and the seven tables | R77 | sample (one page), own (a layer table for each page, `ixtl` listing each, and the page number after the count) |
|
||||
| `rlst` for each page: its layers' numbers | R77 | sample |
|
||||
|
||||
@@ -131,7 +131,7 @@ by their chunk ids, opens it: the header gives where the master index starts, th
|
||||
layer and group records give their instruction counts. A page's record also gives where its
|
||||
end-page instruction starts, and a group's record gives where the instruction after its end-group
|
||||
instruction starts and the edges of its curves. The record of a page with a size holds the edges of its curves, or
|
||||
of the page when it has none. The header's bounds and instruction count are not written.
|
||||
of the page when it has none. The header repeats the first page's edges and instruction count.
|
||||
`PROVENANCE.md`'s "Written fields" table lists every field the `.cmx` writer sets.
|
||||
|
||||
## Writing
|
||||
|
||||
+56
-32
@@ -131,20 +131,20 @@ pub fn write(drawing: &Drawing, limits: crate::Limits) -> Result<Written, Error>
|
||||
Ok(())
|
||||
};
|
||||
// The header's index offset is set once the index is placed.
|
||||
add(chunk(b"cont", &cont(0))?)?;
|
||||
add(chunk(b"cont", &cont(0, PageHead::default()))?)?;
|
||||
// Each page chunk and its reference list, with where they start in the file and the start and
|
||||
// name of each of the page's layers.
|
||||
let mut pages = Vec::new();
|
||||
let mut page = |w: &mut Writer, n: usize, size: Option<(f64, f64)>, layers: &[Layer]| -> Result<(), Error> {
|
||||
let at = w.file_bytes;
|
||||
let (c, written) = w.page(n, size, layers)?;
|
||||
let (c, written, head) = w.page(n, size, layers)?;
|
||||
add(c)?;
|
||||
let refs = w.file_bytes;
|
||||
let r = chunk(b"rlst", &reference_list(written.len()))?;
|
||||
w.check_bytes(r.len())?;
|
||||
w.file_bytes += r.len();
|
||||
add(r)?;
|
||||
pages.push(PageAt { at, refs, layers: written });
|
||||
pages.push(PageAt { at, refs, layers: written, head });
|
||||
Ok(())
|
||||
};
|
||||
for (n, p) in drawing.pages.iter().enumerate() {
|
||||
@@ -181,7 +181,7 @@ pub fn write(drawing: &Drawing, limits: crate::Limits) -> Result<Written, Error>
|
||||
if total > w.limits.input {
|
||||
return Err(Error::Limit("input size"));
|
||||
}
|
||||
children[0] = chunk(b"cont", &cont(ixmr))?;
|
||||
children[0] = chunk(b"cont", &cont(ixmr, pages.first().map(|p| p.head).unwrap_or_default()))?;
|
||||
let mut bytes = Vec::new();
|
||||
bytes.try_reserve_exact(total).map_err(|_| Error::Limit("file size"))?;
|
||||
bytes.extend(b"RIFF");
|
||||
@@ -222,8 +222,9 @@ fn chunk(id: &[u8; 4], body: &[u8]) -> Result<Vec<u8>, Error> {
|
||||
/// The header (R54): the coordinate size digit `4` at byte 52 and the unit in meters at bytes 64
|
||||
/// to 72. Bytes 48 and 54 hold the digit `2`, as in the sample files. Bytes 84 to 96 hold the file
|
||||
/// offset of the master index `ixmr`, then 0xFFFFFFFF for the information list and for the
|
||||
/// picture of the drawing, which the file does not hold (R77); the rest are zeros.
|
||||
fn cont(ixmr: u32) -> Vec<u8> {
|
||||
/// picture of the drawing, which the file does not hold (R77). Bytes 96 to 116 hold the edges and
|
||||
/// the instruction count of `first`, the first page's begin-page record (R77); the rest are zeros.
|
||||
fn cont(ixmr: u32, first: PageHead) -> Vec<u8> {
|
||||
let mut c = vec![0u8; 180];
|
||||
c[48] = b'2';
|
||||
c[52] = b'4';
|
||||
@@ -231,9 +232,21 @@ fn cont(ixmr: u32) -> Vec<u8> {
|
||||
c[64..72].copy_from_slice(&UNIT_METERS.to_le_bytes());
|
||||
c[84..88].copy_from_slice(&ixmr.to_le_bytes());
|
||||
c[88..96].fill(0xFF);
|
||||
for (i, v) in first.edges.iter().enumerate() {
|
||||
c[96 + 4 * i..100 + 4 * i].copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
c[112..116].copy_from_slice(&first.instructions.to_le_bytes());
|
||||
c
|
||||
}
|
||||
|
||||
/// What a page's begin-page record holds that the header repeats: its left, top, right and bottom
|
||||
/// edges and its instruction count, begin and end page included.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct PageHead {
|
||||
edges: [i32; 4],
|
||||
instructions: u32,
|
||||
}
|
||||
|
||||
/// Where a layer's begin-layer instruction starts in the file, and the layer's 8-bit name.
|
||||
type LayerAt = (usize, Vec<u8>);
|
||||
|
||||
@@ -243,6 +256,8 @@ struct PageAt {
|
||||
/// The page's reference list `rlst`.
|
||||
refs: usize,
|
||||
layers: Vec<LayerAt>,
|
||||
/// What the header repeats of its begin-page record.
|
||||
head: PageHead,
|
||||
}
|
||||
|
||||
/// A page's reference list (R77): a u16 count of its layers, then for each layer from 1 the u16
|
||||
@@ -733,9 +748,10 @@ impl Writer {
|
||||
}
|
||||
|
||||
/// A `page` chunk: begin page `n` (from 0), its shown layers back to front, end the page (R60),
|
||||
/// with the file offset of each layer's begin-layer instruction and the layer's 8-bit name.
|
||||
/// The chunk starts at the file offset [`Writer::file_bytes`] gives.
|
||||
fn page(&mut self, n: usize, size: Option<(f64, f64)>, layers: &[Layer]) -> Result<(Vec<u8>, Vec<LayerAt>), Error> {
|
||||
/// with the file offset of each layer's begin-layer instruction and the layer's 8-bit name, and
|
||||
/// what the header repeats of the begin-page record. The chunk starts at the file offset
|
||||
/// [`Writer::file_bytes`] gives.
|
||||
fn page(&mut self, n: usize, size: Option<(f64, f64)>, layers: &[Layer]) -> Result<(Vec<u8>, Vec<LayerAt>, PageHead), Error> {
|
||||
let mut out = Vec::new();
|
||||
self.bounds = None;
|
||||
self.instructions = 1;
|
||||
@@ -803,7 +819,7 @@ impl Writer {
|
||||
self.check_bytes(c.len())?;
|
||||
let layers = starts.into_iter().map(|(at, name)| (base.saturating_add(at), name)).collect();
|
||||
self.file_bytes += c.len();
|
||||
Ok((c, layers))
|
||||
Ok((c, layers, PageHead { edges: page_edges(size, bounds)?, instructions: tail.instructions }))
|
||||
}
|
||||
|
||||
/// An [`Error::Limit`] when the file would be longer than the input size of the limits with
|
||||
@@ -1164,29 +1180,15 @@ fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>, tail
|
||||
let mut d = number.to_le_bytes().to_vec();
|
||||
d.extend(0u32.to_le_bytes());
|
||||
let mut list = Vec::new();
|
||||
let mut size_field = None;
|
||||
let mut edges = [0i32; 4];
|
||||
if let Some((w, h)) = size {
|
||||
// A negative or NaN side counts as 0.
|
||||
let (wu, hu) = (width_units(w)?, width_units(h)?);
|
||||
// A side that rounds to nothing would make the reader drop the page's whole size.
|
||||
if wu == 0 || hu == 0 {
|
||||
return Err(Error::Limit("page size"));
|
||||
let edges = page_edges(size, bounds)?;
|
||||
let size_field = match size {
|
||||
Some((w, h)) => {
|
||||
let mut s = width_units(w)?.to_le_bytes().to_vec();
|
||||
s.extend(width_units(h)?.to_le_bytes());
|
||||
Some(s)
|
||||
}
|
||||
edges = match bounds {
|
||||
Some([x0, y0, x1, y1]) => [x0, y1, x1, y0],
|
||||
None => {
|
||||
// The page around its center; an odd size keeps its extra unit on the left and
|
||||
// bottom, where the edge reaches -2^31.
|
||||
let edge = |v: i64| i32::try_from(v).map_err(|_| Error::Limit("page size"));
|
||||
let (w, h) = (i64::from(wu), i64::from(hu));
|
||||
[edge(w / 2 - w)?, edge(h / 2)?, edge(w / 2)?, edge(h / 2 - h)?]
|
||||
}
|
||||
};
|
||||
let mut s = wu.to_le_bytes().to_vec();
|
||||
s.extend(hu.to_le_bytes());
|
||||
size_field = Some(s);
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
for v in edges {
|
||||
d.extend(v.to_le_bytes());
|
||||
}
|
||||
@@ -1200,6 +1202,28 @@ fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>, tail
|
||||
Ok(instr(BEGIN_PAGE, &fields(&list)))
|
||||
}
|
||||
|
||||
/// The left, top, right and bottom edges begin page holds for a page of `size` whose art reaches
|
||||
/// `bounds`, as [`begin_page`] describes. A page side that rounds to 0 is an [`Error::Limit`].
|
||||
fn page_edges(size: Option<(f64, f64)>, bounds: Option<[i32; 4]>) -> Result<[i32; 4], Error> {
|
||||
let Some((w, h)) = size else { return Ok([0; 4]) };
|
||||
// A negative or NaN side counts as 0.
|
||||
let (wu, hu) = (width_units(w)?, width_units(h)?);
|
||||
// A side that rounds to nothing would make the reader drop the page's whole size.
|
||||
if wu == 0 || hu == 0 {
|
||||
return Err(Error::Limit("page size"));
|
||||
}
|
||||
Ok(match bounds {
|
||||
Some([x0, y0, x1, y1]) => [x0, y1, x1, y0],
|
||||
None => {
|
||||
// The page around its center; an odd size keeps its extra unit on the left and
|
||||
// bottom, where the edge reaches -2^31.
|
||||
let edge = |v: i64| i32::try_from(v).map_err(|_| Error::Limit("page size"));
|
||||
let (w, h) = (i64::from(wu), i64::from(hu));
|
||||
[edge(w / 2 - w)?, edge(h / 2)?, edge(w / 2)?, edge(h / 2 - h)?]
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// `c` as a Windows-1252 byte, or `?` when the code page has no byte for it.
|
||||
fn windows_1252_byte(c: char) -> u8 {
|
||||
match u8::try_from(u32::from(c)) {
|
||||
|
||||
@@ -153,8 +153,8 @@ pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result<Drawing, Error> {
|
||||
/// page, layer and group records give their instruction counts. A page's record also gives where
|
||||
/// its end-page instruction starts, and a group's record gives where the instruction after its
|
||||
/// end-group instruction starts and the edges of its curves. The record of a page with a size holds the edges of
|
||||
/// its curves, or of the page when it has none. The header's bounds and instruction count are not
|
||||
/// written.
|
||||
/// its curves, or of the page when it has none. The header repeats the first page's edges and
|
||||
/// instruction count.
|
||||
pub fn write_cmx(drawing: &Drawing, limits: Limits) -> Result<Written, Error> {
|
||||
cmx_write::write(drawing, limits)
|
||||
}
|
||||
@@ -1078,6 +1078,35 @@ fn the_index_and_the_records_give_where_everything_is() {
|
||||
assert_eq!(groups, [(0, 3), (1, 7)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_header_repeats_the_first_pages_edges_and_instruction_count() {
|
||||
let plain = |x: f64| Object::Shape(Box::new(Shape::new(square(x, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)));
|
||||
let pages = vec![
|
||||
Page { size: Some((200.0, 100.0)), layers: vec![layer("Front", vec![plain(0.0), plain(20.0)]), layer("Back", vec![plain(5.0)])] },
|
||||
Page { size: Some((300.0, 100.0)), layers: vec![layer("Only", vec![plain(1.0)])] },
|
||||
];
|
||||
let b = write_cmx(&drawing(pages)).unwrap().bytes;
|
||||
let cont = 12 + 8;
|
||||
let chunk = page_index(&b)[0][0];
|
||||
let page = chunk + 8;
|
||||
// Begin page's field 1: the page number, the flags, the edges, the end offset, the layer count
|
||||
// and the instruction count.
|
||||
let fields = field_starts(&b, page + 4, page + instruction_size(&b, page, page + u32_at(&b, chunk + 4)));
|
||||
assert_eq!(fields[0].0, 1);
|
||||
let f1 = fields[0].1;
|
||||
assert_eq!(&b[cont + 96..cont + 112], &b[f1 + 6..f1 + 22]);
|
||||
// The curves of the first page reach from 0 to 30 pt across and 0 to 10 pt down.
|
||||
let edges: Vec<i32> = (0..4).map(|i| i32::from_le_bytes(b[cont + 96 + 4 * i..cont + 100 + 4 * i].try_into().unwrap())).collect();
|
||||
let unit = |pt: f64| (pt * 0.0254 / 72.0 / 1e-7).round() as i32;
|
||||
assert_eq!(edges, [0, unit(10.0), unit(30.0), 0]);
|
||||
// Begin and end page, two begin and end layers and three curves.
|
||||
assert_eq!(u32_at(&b, cont + 112), 9);
|
||||
assert_eq!(u32_at(&b, f1 + 28), 9);
|
||||
// A drawing without pages leaves them 0.
|
||||
let b = write_cmx(&drawing(Vec::new())).unwrap().bytes;
|
||||
assert!(b[cont + 96..cont + 116].iter().all(|v| *v == 0));
|
||||
}
|
||||
|
||||
/// The page index of a written file of two pages, each entry's page chunk, layer table, picture
|
||||
/// and reference list, checked through the header and the master index.
|
||||
fn page_index(b: &[u8]) -> Vec<[usize; 4]> {
|
||||
|
||||
+29
-6
@@ -361,17 +361,35 @@ fn edge_index(t: &[f32], start: bool) -> f32 {
|
||||
if start {
|
||||
let v = t[0];
|
||||
// The first value that differs, given they do so from there on.
|
||||
let first_other = t.partition_point(|x| (*x - v).abs() <= 1e-7);
|
||||
let first_other = t.partition_point(|x| {
|
||||
count_edge_read();
|
||||
(*x - v).abs() <= 1e-7
|
||||
});
|
||||
let i = if first_other >= n { n - 1 } else { first_other.saturating_sub(1) };
|
||||
i as f32 / (n - 1) as f32
|
||||
} else {
|
||||
let v = t[n - 1];
|
||||
// The start of the trailing run equal to the last value.
|
||||
let i = t.partition_point(|x| (*x - v).abs() > 1e-7);
|
||||
let i = t.partition_point(|x| {
|
||||
count_edge_read();
|
||||
(*x - v).abs() > 1e-7
|
||||
});
|
||||
i as f32 / (n - 1) as f32
|
||||
}
|
||||
}
|
||||
|
||||
// Each table entry `edge_index` reads on this thread.
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
static EDGE_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn count_edge_read() {
|
||||
#[cfg(test)]
|
||||
EDGE_READS.with(|reads| reads.set(reads.get().saturating_add(1)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -381,13 +399,18 @@ mod tests {
|
||||
// Four million zeros and a one: a scan per call would be 8·10¹¹ steps for these calls.
|
||||
let mut t = vec![0.0f32; 4_000_000];
|
||||
t.push(1.0);
|
||||
// Bisection reads one entry per halving of the table, and a scan reads the whole run.
|
||||
let per_call = t.len().ilog2() as usize + 2;
|
||||
let c = Curve::Table(t);
|
||||
let started = std::time::Instant::now();
|
||||
let mut last = 0.0;
|
||||
for _ in 0..200_000 {
|
||||
EDGE_READS.with(|reads| reads.set(0));
|
||||
let mut last = c.eval_inverse(0.0);
|
||||
let one_call = EDGE_READS.with(std::cell::Cell::get);
|
||||
assert!(one_call <= per_call, "one inversion read {one_call} entries");
|
||||
for _ in 1..200_000 {
|
||||
last = c.eval_inverse(0.0);
|
||||
}
|
||||
assert!(last > 0.99, "the flat start ends at the last zero: {last}");
|
||||
assert!(started.elapsed().as_secs() < 10, "{:?}", started.elapsed());
|
||||
let total = EDGE_READS.with(std::cell::Cell::get);
|
||||
assert!(total <= 200_000 * per_call, "200,000 inversions read {total} entries");
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ use crate::AreaMode;
|
||||
use craft_behavior::{EditEvent, EditEvents, Metrics, PartKey, Sense};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::{
|
||||
Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, EscapeEdit, MeasureCx, Outcome, POPUP_PAD, PaintUi, PartsCx,
|
||||
Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, EscapeEdit, MeasureCx, Outcome, POPOVER_PAD, PaintUi, PartsCx,
|
||||
Pattern, Props as _, Role, Show as _, ShowContainer as _, pad_of,
|
||||
};
|
||||
use craft_ui::popover::Popover;
|
||||
@@ -77,7 +77,7 @@ fn start_point(geometry: Geometry, start: Option<Srgba>) -> Pos2 {
|
||||
/// The popover's top left, so that the start colour's point in the area sits at `at`.
|
||||
fn origin(tokens: &UiTokens, at: Pos2, start: Option<Srgba>) -> Pos2 {
|
||||
let point = start_point(Geometry::of(tokens), start);
|
||||
let pad = pad_of(tokens, POPUP_PAD);
|
||||
let pad = pad_of(tokens, POPOVER_PAD);
|
||||
pos2(at.x - pad - point.x, at.y - pad - point.y)
|
||||
}
|
||||
|
||||
|
||||
@@ -68,14 +68,14 @@ pub use paint_chip::{
|
||||
PaintListEvent, PaintListOptions, PaintListOutput, PaintRow, PaintWords,
|
||||
};
|
||||
pub use pair::{DropAccepts, PairWell, SwatchPair, SwatchPairOutput, Well};
|
||||
pub use palette::{SwatchPalette, SwatchPaletteOutput};
|
||||
pub use palette::{PaletteCell, SwatchPalette, SwatchPaletteOutput};
|
||||
pub use panel::{
|
||||
ColorPanel, ColorPanelAction, ColorPanelCommand, ColorPanelLayout, ColorPanelMenu, ColorPanelMode, ColorPanelOutput, ColorPanelRamp,
|
||||
ColorPanelShown, ColorPanelState, ColorPanelWords, PanelTarget, TintRow,
|
||||
};
|
||||
pub use picker::{
|
||||
ChannelRow, ChannelRule, ChannelUnit, ColorConstraint, ColorPicker, ColorPickerLayout, ColorPickerOutput, ColorPickerWords, PickedColor,
|
||||
ScreenPickGesture, TrackRamp,
|
||||
ChannelRow, ChannelRowOutput, ChannelRule, ChannelUnit, ColorConstraint, ColorPicker, ColorPickerLayout, ColorPickerOutput, ColorPickerWords,
|
||||
PickedColor, ScreenPickGesture, TrackRamp,
|
||||
};
|
||||
pub use picker_dialog::{
|
||||
ColorPickerDialog, ColorPickerDialogLayout, ColorPickerDialogWords, ColorPickerMemory, ColorPickerResult, ColorPickerTab, PickerLibrary,
|
||||
|
||||
@@ -38,6 +38,18 @@ pub struct SwatchPaletteOutput {
|
||||
/// The picked entry's index in the palette, including a swatch with the bound colour or a duplicate colour.
|
||||
/// The recent row and the Other… cell do not report a swatch index.
|
||||
pub picked_swatch: Option<usize>,
|
||||
/// The cell `picked` came from, so a host can tell apart cells that show the same color.
|
||||
pub cell: Option<PaletteCell>,
|
||||
}
|
||||
|
||||
/// A cell of a [`SwatchPalette`] by its place in the host's lists.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum PaletteCell {
|
||||
/// The swatch at this index of the palette's swatches.
|
||||
Swatch(usize),
|
||||
/// The color at this index of the recent row's colors.
|
||||
Recent(usize),
|
||||
}
|
||||
|
||||
impl Outcome for SwatchPaletteOutput {
|
||||
@@ -112,8 +124,8 @@ impl PaletteColor<'_> {
|
||||
/// What the body picked in its pass.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Pick {
|
||||
/// A swatch or a recent colour.
|
||||
Color { color: Srgba, swatch: Option<usize> },
|
||||
/// A swatch or a recent color, and its cell.
|
||||
Color(Srgba, PaletteCell),
|
||||
/// The Other… cell.
|
||||
Other,
|
||||
}
|
||||
@@ -235,7 +247,7 @@ impl<'a> SwatchPalette<'a> {
|
||||
// The Other… cell is keyed `swatches.len()`, past the swatches. A click selects on its press and activates
|
||||
// on its release, so only the activation files the request: one request for one click.
|
||||
pick = picked_cell(&table, ui).and_then(|at| match swatches.get(at) {
|
||||
Some((_, picked)) => Some(Pick::Color { color: *picked, swatch: Some(at) }),
|
||||
Some((_, picked)) => Some(Pick::Color(*picked, PaletteCell::Swatch(at))),
|
||||
None => (other.is_some() && table.open == Some(at) && at == swatches.len()).then_some(Pick::Other),
|
||||
});
|
||||
}
|
||||
@@ -249,8 +261,8 @@ impl<'a> SwatchPalette<'a> {
|
||||
.space(SpaceAction::ActivateLead)
|
||||
.selection(Bind::bound(&mut current))
|
||||
.show_all(ui);
|
||||
if let Some((_, picked)) = picked_cell(&row, ui).and_then(|at| recent_cells.get(at)) {
|
||||
pick = Some(Pick::Color { color: *picked, swatch: None });
|
||||
if let Some((at, (_, picked))) = picked_cell(&row, ui).and_then(|at| recent_cells.get(at).map(|cell| (at, cell))) {
|
||||
pick = Some(Pick::Color(*picked, PaletteCell::Recent(at)));
|
||||
}
|
||||
}
|
||||
Some((before, pick))
|
||||
@@ -265,19 +277,23 @@ impl<'a> SwatchPalette<'a> {
|
||||
let key = other.as_ref().map(|(key, _)| key.clone())?;
|
||||
Some((None, None, Some(ColorRequest::new(key, bound).title(name.clone())), None))
|
||||
}
|
||||
Pick::Color { color: after, swatch } => {
|
||||
Pick::Color(after, cell) => {
|
||||
let unchanged = bound.is_some_and(|bound| bound.to_rgba() == after.to_rgba());
|
||||
let edit = (!unchanged).then(|| {
|
||||
color.write(cx, before, after, name.as_str());
|
||||
let reported = bound.map_or(Mixed::Mixed, Mixed::Same);
|
||||
EditEvent::set(reported, after, Arc::from(name.as_str()), None)
|
||||
});
|
||||
Some((Some(after), edit, None, swatch))
|
||||
Some((Some(after), edit, None, Some(cell)))
|
||||
}
|
||||
}
|
||||
})
|
||||
.flatten();
|
||||
let (picked, edit, pick_color, picked_swatch) = settled.unwrap_or((None, None, None, None));
|
||||
SwatchPaletteOutput { response: shown.output, edit, pick_color, picked, picked_swatch }
|
||||
let (picked, edit, pick_color, cell) = settled.unwrap_or((None, None, None, None));
|
||||
let picked_swatch = match cell {
|
||||
Some(PaletteCell::Swatch(at)) => Some(at),
|
||||
_ => None,
|
||||
};
|
||||
SwatchPaletteOutput { response: shown.output, edit, pick_color, picked, picked_swatch, cell }
|
||||
}
|
||||
}
|
||||
@@ -245,7 +245,8 @@ pub struct ColorPanelState {
|
||||
pub hide_options: bool,
|
||||
/// The FillStroke layout shows the Recent Colors slot.
|
||||
pub recent_colors: bool,
|
||||
/// The R, G and B rows count percents, 0 to 100, in place of 0 to 255.
|
||||
/// The R, G and B rows count percents, 0 to 100, in place of 0 to 255; Web Color's rows keep 0 to 255. A double
|
||||
/// click on a units cell ([`ColorPanel::rgb_units_cell`]) switches it.
|
||||
pub rgb_percent: bool,
|
||||
}
|
||||
|
||||
@@ -446,12 +447,14 @@ pub struct ColorPanel<'a> {
|
||||
cmyk: Option<&'a CmykConverter>,
|
||||
rgb: Option<&'a dyn ColorModel>,
|
||||
dynamic: bool,
|
||||
rgb_units: bool,
|
||||
layout: ColorPanelLayout,
|
||||
wells: Option<([PairWell; 2], Bind<'a, Well>)>,
|
||||
buttons: Option<[Label; 2]>,
|
||||
edited: Option<Option<PickedColor>>,
|
||||
shown: Option<ColorPanelShown>,
|
||||
recent: Option<&'a [Srgba]>,
|
||||
recent_models: &'a [Option<ModelValues>],
|
||||
recent_setup: Option<RecentSetup>,
|
||||
gamut: Option<Gamut<'a>>,
|
||||
}
|
||||
@@ -476,6 +479,7 @@ struct Inputs<'a> {
|
||||
edited: Option<&'a Option<PickedColor>>,
|
||||
shown: &'a ColorPanelShown,
|
||||
recent: Option<&'a [Srgba]>,
|
||||
recent_models: &'a [Option<ModelValues>],
|
||||
recent_setup: Option<&'a RecentSetup>,
|
||||
}
|
||||
|
||||
@@ -488,12 +492,14 @@ impl<'a> ColorPanel<'a> {
|
||||
cmyk: None,
|
||||
rgb: None,
|
||||
dynamic: true,
|
||||
rgb_units: false,
|
||||
layout: ColorPanelLayout::default(),
|
||||
wells: None,
|
||||
buttons: None,
|
||||
edited: None,
|
||||
shown: None,
|
||||
recent: None,
|
||||
recent_models: &[],
|
||||
recent_setup: None,
|
||||
gamut: None,
|
||||
}
|
||||
@@ -520,6 +526,14 @@ impl<'a> ColorPanel<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// A units cell right of each R, G and B field (not Web Color's): a double click on it switches
|
||||
/// [`ColorPanelState::rgb_percent`]. The cell has no keyboard stop, so a host that turns it on offers the same
|
||||
/// switch as a command that writes `rgb_percent`. Off by default.
|
||||
pub fn rgb_units_cell(mut self, on: bool) -> Self {
|
||||
self.rgb_units = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// How the panel arranges its body; the Photoshop foreground and background arrangement by default.
|
||||
pub fn layout(mut self, layout: ColorPanelLayout) -> Self {
|
||||
self.layout = layout;
|
||||
@@ -563,6 +577,15 @@ impl<'a> ColorPanel<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The model values of each Recent Colors chip, in the order of [`recent`](Self::recent). A pick on a chip that has
|
||||
/// them reports them with its color (`PickedColor::in_model`), so a CMYK recent color stays CMYK, and a chip
|
||||
/// that shows the edited color's sRGB in another model still sets it. A chip with `None`, or past the end of
|
||||
/// `models`, works as without this call: a pick sets its sRGB, and a pick of the color already shown sets nothing.
|
||||
pub fn recent_models(mut self, models: &'a [Option<ModelValues>]) -> Self {
|
||||
self.recent_models = models;
|
||||
self
|
||||
}
|
||||
|
||||
/// The payload a Recent Colors chip drags.
|
||||
pub fn recent_payload<P: Send + Sync + 'static>(mut self, map: impl Fn(usize) -> Option<P> + Send + Sync + 'static) -> Self {
|
||||
self.recent_setup = Some(recent_setup(map));
|
||||
@@ -577,7 +600,23 @@ impl<'a> ColorPanel<'a> {
|
||||
|
||||
/// Shows the panel and returns this pass's edits and requests.
|
||||
pub fn show(self, ui: &mut Ui) -> ColorPanelOutput {
|
||||
let ColorPanel { state, colors, cmyk, rgb, dynamic, layout, wells, buttons, edited, shown: rows, recent, recent_setup, gamut } = self;
|
||||
let ColorPanel {
|
||||
state,
|
||||
colors,
|
||||
cmyk,
|
||||
rgb,
|
||||
dynamic,
|
||||
rgb_units,
|
||||
layout,
|
||||
wells,
|
||||
buttons,
|
||||
edited,
|
||||
shown: rows,
|
||||
recent,
|
||||
recent_models,
|
||||
recent_setup,
|
||||
gamut,
|
||||
} = self;
|
||||
let env = Env::of(ui);
|
||||
let (words, dialog) = (env.words::<ColorPanelWords>(), env.words::<ColorPickerDialogWords>());
|
||||
let mut held = Held::new(state);
|
||||
@@ -609,6 +648,7 @@ impl<'a> ColorPanel<'a> {
|
||||
rgb,
|
||||
gamut: &gamut,
|
||||
dynamic,
|
||||
rgb_units,
|
||||
words: &words,
|
||||
dialog: &dialog,
|
||||
inputs: Inputs {
|
||||
@@ -617,6 +657,7 @@ impl<'a> ColorPanel<'a> {
|
||||
edited: edited.as_ref(),
|
||||
shown: rows.as_ref().unwrap_or(&default_rows),
|
||||
recent,
|
||||
recent_models,
|
||||
recent_setup: recent_setup.as_ref(),
|
||||
},
|
||||
now: before,
|
||||
@@ -908,6 +949,8 @@ struct Body<'a> {
|
||||
rgb: &'a dyn ColorModel,
|
||||
gamut: &'a Gamut<'a>,
|
||||
dynamic: bool,
|
||||
/// The R, G and B rows have units cells ([`ColorPanel::rgb_units_cell`]).
|
||||
rgb_units: bool,
|
||||
words: &'a ColorPanelWords,
|
||||
dialog: &'a ColorPickerDialogWords,
|
||||
/// The state as this pass leaves it.
|
||||
@@ -1159,15 +1202,18 @@ impl Body<'_> {
|
||||
self.kept.tracks.retain(|(id, target, _)| (*id, *target) != slot);
|
||||
self.kept.tracks.push((slot.0, slot.1, current));
|
||||
}
|
||||
// The R, G and B rows are not Web Color's. The units are read once, so a double click on one units cell
|
||||
// switches all three rows together, from the next pass.
|
||||
let rgb = !web && model.id() == self.rgb.id();
|
||||
let rgb_percent = self.now.rgb_percent;
|
||||
for (i, ch) in model.channels().iter().enumerate() {
|
||||
let mut rule = ChannelRule::of(ch);
|
||||
if web {
|
||||
rule.step = WEB_STEP;
|
||||
}
|
||||
// The R, G and B rows count percents of the channel's range; an edit goes back through `scale`.
|
||||
// PLAN: a double click on the units cell flips `rgb_percent` while the rows are enabled; `ChannelRow`
|
||||
// (color-w2) reports no signal for its units cell, so the panel cannot read it.
|
||||
let percent = self.now.rgb_percent && model.id() == self.rgb.id();
|
||||
// With `rgb_percent` the R, G and B rows count percents of the channel's range; an edit goes back through
|
||||
// `scale`.
|
||||
let percent = rgb && rgb_percent;
|
||||
let scale = if percent { 100.0 / *rule.range.end() } else { 1.0 };
|
||||
let unit = if percent { ChannelUnit::Percent } else { ChannelUnit::of(ch.unit) };
|
||||
if percent {
|
||||
@@ -1183,8 +1229,17 @@ impl Body<'_> {
|
||||
// The field shows the channel's places, as Photoshop's; the edits start from the unrounded values.
|
||||
let places = 10f64.powi(i32::from(rule.decimals));
|
||||
let shown = (f64::from(current.values[i]) * scale * places).round() / places;
|
||||
let row = ChannelRow::new(channel_name(model, i, &[model]), Bind::given(shown), rule).short(ch.label).unit(unit).track(track).show(ui);
|
||||
for event in row.into_iter().flat_map(|row| row.events) {
|
||||
let row = ChannelRow::new(channel_name(model, i, &[model]), Bind::given(shown), rule).short(ch.label).unit(unit).track(track);
|
||||
let edit = if rgb && self.rgb_units {
|
||||
let row = row.show_with_units(ui);
|
||||
if row.units_double_clicked {
|
||||
self.now.rgb_percent = !rgb_percent;
|
||||
}
|
||||
row.edit
|
||||
} else {
|
||||
row.show(ui)
|
||||
};
|
||||
for event in edit.into_iter().flat_map(|row| row.events) {
|
||||
self.channel_event(model, current, i, event.map(|x| x / scale));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! same `Body` as the Photoshop layout and shares its rows, wells, warnings and ramp helpers.
|
||||
|
||||
use craft_behavior::{EditEvent, Mixed};
|
||||
use craft_theme::Srgba;
|
||||
use craft_theme::{ModelValues, Srgba};
|
||||
use craft_ui::choice::{Swatch, SwatchSpacing};
|
||||
use craft_ui::contract::{Bind, Gap, LabelScheme, Props as _, Scroll, Show as _, ShowContainer as _, Sizing};
|
||||
use craft_ui::display::{Shade, Text};
|
||||
@@ -15,7 +15,7 @@ use craft_ui::text::{HexField, TextField};
|
||||
use egui::Ui;
|
||||
|
||||
use super::{Body, ColorPanelMode, ColorPanelShown, PanelTarget, TintRow};
|
||||
use crate::ui::{ChannelRow, ChannelRule, ChannelUnit, ColorRamp, PickedColor, RampKind, SwatchPalette};
|
||||
use crate::ui::{ChannelRow, ChannelRule, ChannelUnit, ColorRamp, PaletteCell, PickedColor, RampKind, SwatchPalette};
|
||||
|
||||
impl Body<'_> {
|
||||
/// The layout. The options (rows, quick wells, recent colours) go when the state hides them; the proxy and the
|
||||
@@ -156,8 +156,8 @@ impl Body<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Recent Colors caption over a spaced palette; a pick sets the color. The caption shows while the host's list
|
||||
/// is empty, where the first applied color will go.
|
||||
/// The Recent Colors caption over a spaced palette; a pick sets the color, in the chip's model when the host gave it.
|
||||
/// The caption shows while the host's list is empty, where the first applied color will go.
|
||||
// PLAN: Alt on a recent colour or a warning chip should set the other colour; `SwatchPaletteOutput` and
|
||||
// `ColorWarningChipOutput` report no modifiers (color-w1 for the palette, the owner of warning.rs for the chip).
|
||||
fn recent(&mut self, ui: &mut Ui) {
|
||||
@@ -174,13 +174,34 @@ impl Body<'_> {
|
||||
if let Some(setup) = self.inputs.recent_setup {
|
||||
palette = setup(palette);
|
||||
}
|
||||
if let Some(event) = palette.show(ui).edit
|
||||
let out = palette.show(ui);
|
||||
let values = match out.cell {
|
||||
Some(PaletteCell::Swatch(at)) => self.inputs.recent_models.get(at).copied().flatten(),
|
||||
_ => None,
|
||||
};
|
||||
if let (Some(color), Some(values)) = (out.picked, values) {
|
||||
self.set_in_model(color, values);
|
||||
} else if let Some(event) = out.edit
|
||||
&& let Some(color) = event.value()
|
||||
{
|
||||
self.set_color(self.target, *color);
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the edited color to `color` in the model of `values`, keeping its alpha. It sets nothing when the host's
|
||||
/// color already has those values and shows that color.
|
||||
fn set_in_model(&mut self, color: Srgba, values: ModelValues) {
|
||||
let before = self.picked().copied().unwrap_or_else(|| PickedColor::rgb(self.colors[self.target.index()]));
|
||||
let after = PickedColor::in_model(color.with_alpha(before.color.a), values);
|
||||
if before.model == after.model && before.color.to_rgba() == after.color.to_rgba() {
|
||||
return;
|
||||
}
|
||||
// The rows' kept values in the chip's model would win over a host that keeps only sRGB (a grey's HSB hue).
|
||||
self.kept.values[self.target.index()].retain(|v| v.model != values.model);
|
||||
let name = self.words.title.as_str();
|
||||
self.push(self.target, EditEvent::set(Mixed::Same(before), after, name.into(), None));
|
||||
}
|
||||
|
||||
/// Sets `target`'s colour to `color`, keeping its alpha.
|
||||
fn set_color(&mut self, target: PanelTarget, color: Srgba) {
|
||||
let before = self.colors[target.index()];
|
||||
|
||||
@@ -3,14 +3,18 @@
|
||||
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use craft_behavior::{Axis, Sense};
|
||||
use craft_behavior::press::MULTI_CLICK_TIME;
|
||||
use craft_behavior::{Axis, Metrics, PartKey, PressPhase, Sense};
|
||||
use craft_theme::{Channel, ColorModel, Srgba};
|
||||
use craft_ui::contract::{
|
||||
Bind, Common, Component, Cx, DisabledLook, EditResponse, GlyphLabel, LabelKind, MeasureCx, Role, Show as _, ShowContainer as _, SideLabel, Sizing,
|
||||
Bind, Common, Component, Cx, DisabledLook, EditResponse, Gap, GlyphLabel, LabelKind, MeasureCx, NoValue, Outcome, PartsCx, Pointer as _, Role,
|
||||
Show as _, ShowContainer as _, SideLabel, Sizing,
|
||||
};
|
||||
use craft_ui::form::{Field, SliderField, SliderFieldLayout};
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::primitives::{PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::env::{Label, UnitKind};
|
||||
use craft_ui::runtime::pointer;
|
||||
use craft_ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx};
|
||||
use craft_ui::value_drag::{SliderThumb, TrackFace};
|
||||
use egui::{Color32, CornerRadius, Ui, Vec2};
|
||||
@@ -183,6 +187,15 @@ pub struct ChannelRow<'a> {
|
||||
marks: &'a [f64],
|
||||
}
|
||||
|
||||
/// What [`ChannelRow::show_with_units`] reports.
|
||||
#[non_exhaustive]
|
||||
pub struct ChannelRowOutput {
|
||||
/// The edit of the slider or the field, `None` when the row did not run.
|
||||
pub edit: Option<EditResponse<f64>>,
|
||||
/// The units cell was double-clicked in this pass: the host switches the units the row counts in.
|
||||
pub units_double_clicked: bool,
|
||||
}
|
||||
|
||||
impl<'a> ChannelRow<'a> {
|
||||
/// A row named `label` over `value`, ruled by `rule`.
|
||||
pub fn new(label: impl Into<Label>, value: Bind<'a, f64>, rule: ChannelRule) -> Self {
|
||||
@@ -223,22 +236,140 @@ impl<'a> ChannelRow<'a> {
|
||||
|
||||
/// Shows the row; the edit of the slider or the field, `None` when the row did not run.
|
||||
pub fn show(self, ui: &mut Ui) -> Option<EditResponse<f64>> {
|
||||
self.show_row(ui, false).edit
|
||||
}
|
||||
|
||||
/// Shows the row with a blank units cell after the number field, for a row whose host can switch the units the
|
||||
/// value counts in: the edit of the slider or the field, and whether the cell was double-clicked. The cell is
|
||||
/// highlighted under the pointer and takes no keyboard focus, so the host offers the same switch as a command; in
|
||||
/// a disabled container it does not report a double click. The slider gives up the cell's width, so the row keeps
|
||||
/// its width.
|
||||
pub fn show_with_units(self, ui: &mut Ui) -> ChannelRowOutput {
|
||||
self.show_row(ui, true)
|
||||
}
|
||||
|
||||
fn show_row(self, ui: &mut Ui, units_cell: bool) -> ChannelRowOutput {
|
||||
let ChannelRow { label, short, mut value, rule, track, checker, unit, marks } = self;
|
||||
let side = match short {
|
||||
Some(short) => SideLabel::new().kind(LabelKind::Glyph(GlyphLabel::text(Label::from(short)))),
|
||||
None => SideLabel::new(),
|
||||
};
|
||||
Field::new(label.clone())
|
||||
.side(side.scrub(true))
|
||||
.show(ui, |ui, _| {
|
||||
channel_slider(label.clone(), value.reborrowed(), &rule, unit, track.clone().map(|stops| (stops, checker)))
|
||||
.marks(marks)
|
||||
.layout(SliderFieldLayout::Inline)
|
||||
.field_sizing(Sizing::Content)
|
||||
.thumb(SliderThumb::Triangle)
|
||||
.show(ui)
|
||||
.edit
|
||||
})
|
||||
.inner
|
||||
let mut field = |ui: &mut Ui| {
|
||||
Field::new(label.clone())
|
||||
.side(side.clone().scrub(true))
|
||||
.show(ui, |ui, _| {
|
||||
channel_slider(label.clone(), value.reborrowed(), &rule, unit, track.clone().map(|stops| (stops, checker)))
|
||||
.marks(marks)
|
||||
.layout(SliderFieldLayout::Inline)
|
||||
.field_sizing(Sizing::Content)
|
||||
.thumb(SliderThumb::Triangle)
|
||||
.show(ui)
|
||||
.edit
|
||||
})
|
||||
.inner
|
||||
};
|
||||
if !units_cell {
|
||||
return ChannelRowOutput { edit: field(ui), units_double_clicked: false };
|
||||
}
|
||||
let shown = Row::new().fill_width().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
let edit = field(ui);
|
||||
let cell = UnitsCell::new().show(ui);
|
||||
(edit, cell.double_clicked)
|
||||
});
|
||||
let (edit, units_double_clicked) = shown.inner.unwrap_or((None, false));
|
||||
ChannelRowOutput { edit, units_double_clicked }
|
||||
}
|
||||
}
|
||||
|
||||
/// The units cell's one part, which takes the pointer.
|
||||
const UNITS: PartKey = PartKey::new("units");
|
||||
|
||||
/// The style of a units cell: its size.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct UnitsCellStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
/// The cell's size: `size.icon.glyph_sm` wide, a control high, so it fills the row's line.
|
||||
size: Vec2,
|
||||
}
|
||||
|
||||
/// The blank cell after a channel row's number field ([`ChannelRow::show_with_units`]): highlighted under the pointer, it
|
||||
/// reports a double click. It has no keyboard stop and no node: the host's command that switches the units is its
|
||||
/// keyboard path.
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
#[component(sample = UnitsCell::new)]
|
||||
struct UnitsCell {
|
||||
#[common]
|
||||
common: Common,
|
||||
double_clicked: bool,
|
||||
}
|
||||
|
||||
impl UnitsCell {
|
||||
fn new() -> Self {
|
||||
UnitsCell { common: Common::new(), double_clicked: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// What a units cell reports: its response and whether it was double-clicked in this pass.
|
||||
struct UnitsCellOutput {
|
||||
response: egui::Response,
|
||||
double_clicked: bool,
|
||||
}
|
||||
|
||||
impl Outcome for UnitsCellOutput {
|
||||
type Value = NoValue;
|
||||
|
||||
fn response(&self) -> &egui::Response {
|
||||
&self.response
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for UnitsCell {
|
||||
const ROLE: Role = Role::None;
|
||||
const OVERLAYS: bool = false;
|
||||
const STOPS: bool = false;
|
||||
type Style = UnitsCellStyle;
|
||||
type Output = UnitsCellOutput;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: UnitsCellStyleKey) -> UnitsCellStyle {
|
||||
UnitsCellStyle { metrics: Metrics::new(), size: Vec2::new(cx.tokens.size.icon.glyph_sm, cx.control().height) }
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
cx.style.size
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
fn parts(&mut self, rect: egui::Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
cx.part(UNITS, rect).sense(Sense::CLICK).state_layer().pointer_only("the host's command switches the units");
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
let first = cx.id.with("units-first-click");
|
||||
let ctx = &cx.response.ctx;
|
||||
// A press off the cell ends the cell's click run, even when it starts a new count that the next click on the
|
||||
// cell continues.
|
||||
if pointer::frame(ctx).press.is_some_and(|press| !cx.response.rect.contains(press.origin)) {
|
||||
ctx.data_mut(|data| data.remove::<(f64, u32)>(first));
|
||||
}
|
||||
let PressPhase::Release { start, click: true, .. } = cx.part(UNITS).press.phase else { return };
|
||||
// The click count also counts a press just beside the cell, on the number field, so a click is the second of a
|
||||
// double click only when the click just before it, by the count, was a click on this cell.
|
||||
let earlier = ctx.data(|data| data.get_temp::<(f64, u32)>(first));
|
||||
let follows = earlier.is_some_and(|(time, clicks)| start.clicks == clicks + 1 && start.time - time <= MULTI_CLICK_TIME);
|
||||
if start.clicks >= 2 && follows {
|
||||
self.double_clicked = true;
|
||||
ctx.data_mut(|data| data.remove::<(f64, u32)>(first));
|
||||
} else {
|
||||
ctx.data_mut(|data| data.insert_temp(first, (start.time, start.clicks)));
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> UnitsCellOutput {
|
||||
UnitsCellOutput { response: cx.response.clone(), double_clicked: self.double_clicked }
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ use egui::{Pos2, Response, Ui};
|
||||
|
||||
use super::{AreaMode, ColorWarning};
|
||||
pub(crate) use channel::channel_name;
|
||||
pub use channel::{ChannelRow, ChannelRule, ChannelUnit, TrackRamp};
|
||||
pub use channel::{ChannelRow, ChannelRowOutput, ChannelRule, ChannelUnit, TrackRamp};
|
||||
pub(crate) use full::TWO_COLUMNS;
|
||||
pub use value::ColorConstraint;
|
||||
use value::Rules;
|
||||
|
||||
@@ -24,7 +24,7 @@ use craft_ui::dialog::{
|
||||
ButtonPlace, Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id, serde_fields, set_serde_field,
|
||||
};
|
||||
use craft_ui::layout::{CellAlign, GridFit};
|
||||
use craft_ui::layout_components::{Grid, Stack};
|
||||
use craft_ui::layout_components::{Grid, Row, Stack};
|
||||
use craft_ui::notices::{Notice, NoticeLayout};
|
||||
use craft_ui::patterns::form_dialogs::{HostRequests, ResetFooter};
|
||||
use craft_ui::pickers::Select;
|
||||
@@ -41,7 +41,7 @@ use std::borrow::Cow;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::picker::TWO_COLUMNS;
|
||||
use super::{ColorPicker, ColorPickerLayout, ColorWarning, Gamut, PickedColor, ScreenPickGesture, SwatchPalette};
|
||||
use super::{ColorPicker, ColorPickerLayout, ColorPickerWords, ColorWarning, CompareSwatch, Gamut, PickedColor, ScreenPickGesture, SwatchPalette};
|
||||
use crate::{AreaMode, CmykModel, not_web_safe, web_safe};
|
||||
|
||||
type StandardColors = (Vec<(Label, Srgba)>, Vec<(Label, Srgba)>);
|
||||
@@ -318,27 +318,47 @@ impl TabbedBody<'_> {
|
||||
let (cells, greys) = self.standard.map_or((&[][..], &[][..]), |(cells, greys)| (cells.as_slice(), greys.as_slice()));
|
||||
let current = held.same().map(|picked| picked.color);
|
||||
let mut pick = None;
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
let honeycomb = SwatchTable::new(self.words.standard_colors.clone(), cells)
|
||||
.arrangement(SwatchArrangement::Honeycomb)
|
||||
.tips(true)
|
||||
.selection(Bind::given(chosen(cells, current)))
|
||||
.show_all(ui);
|
||||
if let Some(at) = honeycomb.selected {
|
||||
pick = cells.get(at).map(|(_, color)| *color);
|
||||
}
|
||||
let row = SwatchTable::new(self.words.greys.clone(), greys)
|
||||
.per_row(greys.len().max(1))
|
||||
.tips(true)
|
||||
.selection(Bind::given(chosen(greys, current)))
|
||||
.show_all(ui);
|
||||
if let Some(at) = row.selected {
|
||||
pick = greys.get(at).map(|(_, color)| *color);
|
||||
let mut restore = None;
|
||||
// The compare block stands beside the honeycomb, as it does beside the Custom page's area.
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
let honeycomb = SwatchTable::new(self.words.standard_colors.clone(), cells)
|
||||
.arrangement(SwatchArrangement::Honeycomb)
|
||||
.tips(true)
|
||||
.selection(Bind::given(chosen(cells, current)))
|
||||
.show_all(ui);
|
||||
if let Some(at) = honeycomb.selected {
|
||||
pick = cells.get(at).map(|(_, color)| *color);
|
||||
}
|
||||
let row = SwatchTable::new(self.words.greys.clone(), greys)
|
||||
.per_row(greys.len().max(1))
|
||||
.tips(true)
|
||||
.selection(Bind::given(chosen(greys, current)))
|
||||
.show_all(ui);
|
||||
if let Some(at) = row.selected {
|
||||
pick = greys.get(at).map(|(_, color)| *color);
|
||||
}
|
||||
});
|
||||
if let Some(compare) = self.compare {
|
||||
let new = held.same().map_or(Mixed::Mixed, |picked| Mixed::Same(picked.color));
|
||||
let current = match compare {
|
||||
Mixed::Same(current) => Mixed::Same(current.color),
|
||||
Mixed::Mixed => Mixed::Mixed,
|
||||
};
|
||||
let label = Env::of(ui).words::<ColorPickerWords>().new_color.clone();
|
||||
if CompareSwatch::new(label, new, current).show(ui).restore
|
||||
&& let Mixed::Same(current) = compare
|
||||
{
|
||||
restore = Some(current);
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some(color) = pick {
|
||||
*held = Mixed::Same(PickedColor::rgb(color));
|
||||
}
|
||||
if let Some(current) = restore {
|
||||
*held = Mixed::Same(current);
|
||||
}
|
||||
}
|
||||
|
||||
/// The compact picker over the colour, the compare swatch beside its area; the model switch is the memory's.
|
||||
|
||||
@@ -97,8 +97,8 @@ pub struct SwatchesPanel<'a> {
|
||||
search: bool,
|
||||
row_icons: Option<RowIconsFn<'a>>,
|
||||
select: SelectMode,
|
||||
drops: Vec<DropMaker<'a>>,
|
||||
report_invalid_renames: bool,
|
||||
takes_drop: Option<DropMaker<'a>>,
|
||||
payloads: Vec<PayloadAdder<'a>>,
|
||||
row_items: Option<RowItemsFn<'a>>,
|
||||
document: Option<IdSalt>,
|
||||
@@ -131,8 +131,8 @@ impl<'a> SwatchesPanel<'a> {
|
||||
search: true,
|
||||
row_icons: None,
|
||||
select: SelectMode::Single,
|
||||
drops: Vec::new(),
|
||||
report_invalid_renames: false,
|
||||
takes_drop: None,
|
||||
payloads: Vec::new(),
|
||||
row_items: None,
|
||||
document: None,
|
||||
@@ -211,12 +211,12 @@ impl<'a> SwatchesPanel<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// A host payload of type `P` can be dropped onto a swatch or between swatches at `place` where `accepts` agrees;
|
||||
/// the drop comes back as `PresetEvent::Dropped`.
|
||||
/// Adds a target for host payloads of type `P` at `place` where `accepts` agrees.
|
||||
/// Each drop comes back as `PresetEvent::Dropped`.
|
||||
pub fn takes_drop<P: Send + Sync + 'static>(mut self, place: DropPlace, accepts: impl Fn(&P, &DropAt<SwatchKey>) -> bool + 'a) -> Self {
|
||||
// The body can run more than once a pass, and a `PresetDrop` is used up by the browser: it is built per run.
|
||||
let accepts = Rc::new(accepts);
|
||||
self.takes_drop = Some(Box::new(move || {
|
||||
self.drops.push(Box::new(move || {
|
||||
let accepts = Rc::clone(&accepts);
|
||||
PresetDrop::new::<P>(place, move |payload: &P, at: &DropAt<SwatchKey>| accepts(payload, at))
|
||||
}));
|
||||
@@ -270,8 +270,8 @@ impl<'a> SwatchesPanel<'a> {
|
||||
search,
|
||||
row_icons,
|
||||
select,
|
||||
drops,
|
||||
report_invalid_renames,
|
||||
takes_drop,
|
||||
payloads,
|
||||
row_items,
|
||||
document,
|
||||
@@ -331,7 +331,7 @@ impl<'a> SwatchesPanel<'a> {
|
||||
if let Some(items) = &row_items {
|
||||
browser = browser.row_menu(PresetRowMenu::Host).row_items(|key: &SwatchKey| items(key));
|
||||
}
|
||||
if let Some(make) = &takes_drop {
|
||||
for make in &drops {
|
||||
browser = browser.takes_drop(make());
|
||||
}
|
||||
for add in &payloads {
|
||||
|
||||
@@ -8,11 +8,11 @@ use craft_behavior::{EditEvent, Mixed, Selection};
|
||||
use craft_color_ui::palette::{SwatchColor, SwatchGroup};
|
||||
use craft_color_ui::ui::{
|
||||
ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelShown, ColorPanelState, HarmonyPanel, HarmonyPanelState, HarmonyPicked, HarmonyWheel,
|
||||
PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesState,
|
||||
SwatchesWords, swatch_rows,
|
||||
PaletteCell, PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel,
|
||||
SwatchesState, SwatchesWords, swatch_rows,
|
||||
};
|
||||
use craft_host::target::Os;
|
||||
use craft_theme::{ColorModel as _, HsbModel, Srgba};
|
||||
use craft_theme::{ColorModel as _, HsbModel, ModelValues, Srgba};
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::choice::SwatchTable;
|
||||
use craft_ui::contract::Role;
|
||||
@@ -38,6 +38,7 @@ type Edits = Rc<RefCell<Vec<(PanelTarget, EditEvent<PickedColor>)>>>;
|
||||
/// The Color panel on a state and two colours the test can change, collecting what it reports.
|
||||
struct PanelRig {
|
||||
fixture: Fixture,
|
||||
state: Rc<RefCell<ColorPanelState>>,
|
||||
colors: Rc<Cell<[Srgba; 2]>>,
|
||||
edits: Edits,
|
||||
}
|
||||
@@ -48,15 +49,19 @@ impl PanelRig {
|
||||
}
|
||||
|
||||
fn in_room(mode: ColorPanelMode, room: Vec2) -> Self {
|
||||
let start = ColorPanelState { mode, ..Default::default() };
|
||||
Self::with_state(ColorPanelState { mode, ..Default::default() }, room, true)
|
||||
}
|
||||
|
||||
/// The panel from `start`, with the RGB units cells where `units` is set.
|
||||
fn with_state(start: ColorPanelState, room: Vec2, units: bool) -> Self {
|
||||
let state = Rc::new(RefCell::new(start));
|
||||
let colors = Rc::new(Cell::new([RED, BLUE]));
|
||||
type Shared = (Edits, Rc<RefCell<Vec<ColorRequest>>>, Rc<RefCell<Vec<PanelTarget>>>);
|
||||
let (edits, opened, added): Shared = Default::default();
|
||||
let (s, c, e, o, a) = (state, colors.clone(), edits.clone(), opened, added);
|
||||
let (s, c, e, o, a) = (state.clone(), colors.clone(), edits.clone(), opened, added);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut current = *s.borrow();
|
||||
let shown = ColorPanel::new(Bind::bound(&mut current), c.get()).show(ui);
|
||||
let shown = ColorPanel::new(Bind::bound(&mut current), c.get()).rgb_units_cell(units).show(ui);
|
||||
*s.borrow_mut() = current;
|
||||
e.borrow_mut().extend(shown.edits);
|
||||
o.borrow_mut().extend(shown.pick_color);
|
||||
@@ -64,7 +69,7 @@ impl PanelRig {
|
||||
});
|
||||
fixture.room(room);
|
||||
fixture.settle();
|
||||
PanelRig { fixture, colors, edits }
|
||||
PanelRig { fixture, state, colors, edits }
|
||||
}
|
||||
|
||||
fn set_colors(&mut self, colors: [Srgba; 2]) {
|
||||
@@ -197,6 +202,145 @@ fn a_channel_step_keeps_the_other_channels_unrounded() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A point in the units cell right of `field`, on its line.
|
||||
fn right_of(field: &craft_ui::testing::Target) -> egui::Pos2 {
|
||||
egui::pos2(field.rect.right() + 6.0, field.rect.center().y)
|
||||
}
|
||||
|
||||
/// The number fields' values, top to bottom, and the end of the first one's range.
|
||||
fn field_values(fixture: &Fixture) -> (Vec<f64>, f64) {
|
||||
let tree = fixture.tree();
|
||||
let fields = fixture.by_role(Role::SPIN_BUTTON);
|
||||
let numbers: Vec<_> = fields.iter().map(|field| tree.numeric_of(field.node).expect("a field's value and range")).collect();
|
||||
let values = numbers.iter().map(|number| number.value.expect("a field's value")).collect();
|
||||
(values, *numbers[0].range.end())
|
||||
}
|
||||
|
||||
/// A double click right of the R, G or B field switches all three rows between 0 to 255 and percent, and the next one
|
||||
/// switches them back. The colour does not change.
|
||||
#[trial]
|
||||
fn a_double_click_right_of_an_rgb_field_switches_the_rgb_units() {
|
||||
let mut rig = PanelRig::new(ColorPanelMode::RgbSliders);
|
||||
rig.set_colors([Srgba::rgb(1.0, 0.5, 0.0), BLUE]);
|
||||
let (bytes, end) = field_values(&rig.fixture);
|
||||
assert!(!rig.state.borrow().rgb_percent && end > 100.0, "the rows start at 0 to 255 ({bytes:?}, to {end})");
|
||||
|
||||
let fields = rig.fixture.by_role(Role::SPIN_BUTTON);
|
||||
let at = right_of(&fields[0]);
|
||||
rig.fixture.click_at(at).click_at(at).settle();
|
||||
assert!(rig.state.borrow().rgb_percent, "a double click right of R switches to percent");
|
||||
let (percents, end) = field_values(&rig.fixture);
|
||||
assert_eq!(end, 100.0, "the fields count to 100 %");
|
||||
for (percent, byte) in percents.iter().zip(&bytes) {
|
||||
assert!((percent - byte / 2.55).abs() < 0.51, "every row shows its percent ({percents:?}, {bytes:?})");
|
||||
}
|
||||
|
||||
rig.fixture.advance(1.0);
|
||||
let fields = rig.fixture.by_role(Role::SPIN_BUTTON);
|
||||
let at = right_of(&fields[2]);
|
||||
rig.fixture.click_at(at).click_at(at).settle();
|
||||
assert!(!rig.state.borrow().rgb_percent, "a double click right of B switches back");
|
||||
assert_eq!(field_values(&rig.fixture).0, bytes, "the rows count 0 to 255 again");
|
||||
assert!(rig.edits.borrow().is_empty(), "switching the units changes no colour: {:?}", rig.edits.borrow());
|
||||
}
|
||||
|
||||
/// A single click right of an RGB field, and a double click on the field itself, leave the units as they are.
|
||||
#[trial]
|
||||
fn only_a_double_click_on_the_units_cell_switches_the_rgb_units() {
|
||||
let mut rig = PanelRig::new(ColorPanelMode::RgbSliders);
|
||||
let fields = rig.fixture.by_role(Role::SPIN_BUTTON);
|
||||
rig.fixture.click_at(right_of(&fields[1])).settle();
|
||||
assert!(!rig.state.borrow().rgb_percent, "a single click right of G switches nothing");
|
||||
rig.fixture.advance(1.0);
|
||||
let field = rig.fixture.by_role(Role::SPIN_BUTTON).remove(1);
|
||||
rig.fixture.click(&field).click(&field).settle();
|
||||
assert!(!rig.state.borrow().rgb_percent, "a double click on the G field switches nothing");
|
||||
}
|
||||
|
||||
/// A click at the right edge of an RGB field followed at once by a click on the units cell beside it is not a double
|
||||
/// click on the cell, though the two presses are close enough to count as one, nor are two clicks on the cell with a
|
||||
/// click on the field between them.
|
||||
#[trial]
|
||||
fn a_click_on_the_field_then_one_on_the_units_cell_switches_nothing() {
|
||||
let mut rig = PanelRig::new(ColorPanelMode::RgbSliders);
|
||||
let field = rig.fixture.by_role(Role::SPIN_BUTTON).remove(0);
|
||||
let (edge, cell) = (egui::pos2(field.rect.right() - 0.4, field.rect.center().y), egui::pos2(field.rect.right() + 2.4, field.rect.center().y));
|
||||
rig.fixture.click_at(cell).click_at(cell).settle();
|
||||
assert!(rig.state.borrow().rgb_percent, "a double click at {cell:?} is on the units cell");
|
||||
rig.fixture.advance(1.0);
|
||||
rig.fixture.click_at(edge).click_at(cell).settle();
|
||||
assert!(rig.state.borrow().rgb_percent, "a click on the field's edge and one on the cell switch nothing");
|
||||
rig.fixture.advance(1.0);
|
||||
rig.fixture.click_at(cell).click_at(edge).click_at(cell).settle();
|
||||
assert!(rig.state.borrow().rgb_percent, "two clicks on the cell with one on the field between them switch nothing");
|
||||
}
|
||||
|
||||
/// Two clicks on the units cell with a click on the field between them switch nothing when the field click is too far
|
||||
/// from the first to continue its click run, and the second cell click is close enough to the field click to count as
|
||||
/// its second click.
|
||||
#[trial]
|
||||
fn a_field_click_that_starts_a_new_run_between_two_units_cell_clicks_switches_nothing() {
|
||||
let mut rig = PanelRig::new(ColorPanelMode::RgbSliders);
|
||||
let field = rig.fixture.by_role(Role::SPIN_BUTTON).remove(0);
|
||||
let (top, bottom) = (field.rect.top() + 1.0, field.rect.bottom() - 1.0);
|
||||
let (first, edge, second) =
|
||||
(egui::pos2(field.rect.right() + 2.4, top), egui::pos2(field.rect.right() - 0.4, bottom), egui::pos2(field.rect.right() + 2.4, bottom));
|
||||
rig.fixture.click_at(second).click_at(second).settle();
|
||||
assert!(rig.state.borrow().rgb_percent, "a double click at {second:?} is on the units cell");
|
||||
rig.fixture.advance(1.0);
|
||||
rig.fixture.click_at(first).click_at(edge).click_at(second).settle();
|
||||
assert!(rig.state.borrow().rgb_percent, "a field click that starts a new run between two cell clicks switches nothing");
|
||||
}
|
||||
|
||||
/// Rows of other modes have no units cell, nor do the RGB rows of a panel whose host did not ask for them, and Web
|
||||
/// Color keeps 0 to 255 while the RGB rows show percent.
|
||||
#[trial]
|
||||
fn rows_other_than_rgb_keep_their_units() {
|
||||
let rgb = ColorPanelState { mode: ColorPanelMode::RgbSliders, ..Default::default() };
|
||||
let mut rigs = vec![("RGB without units cells".to_owned(), PanelRig::with_state(rgb, COLOR_ROOM, false))];
|
||||
for mode in [ColorPanelMode::CmykSliders, ColorPanelMode::HsbSliders, ColorPanelMode::WebColorSliders] {
|
||||
rigs.push((format!("{mode:?}"), PanelRig::new(mode)));
|
||||
}
|
||||
for (case, mut rig) in rigs {
|
||||
let fields = rig.fixture.by_role(Role::SPIN_BUTTON);
|
||||
let at = right_of(&fields[0]);
|
||||
rig.fixture.click_at(at).click_at(at).settle();
|
||||
assert!(!rig.state.borrow().rgb_percent, "{case}: a double click right of a field switches nothing");
|
||||
}
|
||||
let start = ColorPanelState { mode: ColorPanelMode::WebColorSliders, rgb_percent: true, ..Default::default() };
|
||||
let rig = PanelRig::with_state(start, COLOR_ROOM, true);
|
||||
let (_, end) = field_values(&rig.fixture);
|
||||
assert!(end > 100.0, "Web Color counts 0 to 255 while the RGB rows show percent (to {end})");
|
||||
}
|
||||
|
||||
/// The FillStroke layout's RGB rows switch their units the same way, and not while a mixed selection disables them.
|
||||
#[trial]
|
||||
fn a_disabled_fill_stroke_rgb_row_does_not_switch_its_units() {
|
||||
let state = Rc::new(RefCell::new(ColorPanelState::default()));
|
||||
let edited = Rc::new(Cell::new(Some(PickedColor::rgb(RED))));
|
||||
let (s, e) = (state.clone(), edited.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut current = *s.borrow();
|
||||
let _ = ColorPanel::new(Bind::bound(&mut current), [RED, BLUE])
|
||||
.layout(ColorPanelLayout::FillStroke)
|
||||
.shown(ColorPanelShown::Mode(ColorPanelMode::RgbSliders))
|
||||
.rgb_units_cell(true)
|
||||
.edited(e.get())
|
||||
.show(ui);
|
||||
*s.borrow_mut() = current;
|
||||
});
|
||||
fixture.room(COLOR_ROOM).settle();
|
||||
let fields = fixture.by_role(Role::SPIN_BUTTON);
|
||||
let at = right_of(&fields[0]);
|
||||
fixture.click_at(at).click_at(at).settle();
|
||||
assert!(state.borrow().rgb_percent, "a double click right of R switches the FillStroke rows to percent");
|
||||
|
||||
edited.set(None);
|
||||
fixture.settle().advance(1.0);
|
||||
fixture.click_at(at).click_at(at).settle();
|
||||
assert!(state.borrow().rgb_percent, "with the rows disabled a double click switches nothing");
|
||||
}
|
||||
|
||||
/// A Color panel whose host supplies authoritative native CMYK components.
|
||||
fn native_cmyk_panel(picked: PickedColor) -> (Fixture, Rc<RefCell<PickedColor>>, Edits) {
|
||||
let host = Rc::new(RefCell::new(picked));
|
||||
@@ -367,6 +511,88 @@ fn the_fill_stroke_spectrums_tooltip_names_the_shown_mode_and_shift_click_cycles
|
||||
assert!(edits.borrow().is_empty(), "a Shift click picks nothing: {:?}", edits.borrow());
|
||||
}
|
||||
|
||||
/// A Recent Colors pick in the FillStroke layout reports the chip's model values with its color, also when the chip
|
||||
/// shows the edited color's sRGB in another model or without one; a chip whose values the edited color already has
|
||||
/// sets nothing.
|
||||
#[trial]
|
||||
fn a_fill_stroke_recent_pick_keeps_the_chips_model() {
|
||||
let chip = RECENT[0];
|
||||
let cmyk = ModelValues::new("cmyk", &[60.0, 90.0, 0.0, 0.0]);
|
||||
let pick = |edited: PickedColor| {
|
||||
let edits: Edits = Default::default();
|
||||
let seen = Rc::clone(&edits);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut state = ColorPanelState::default();
|
||||
let out = ColorPanel::new(Bind::bound(&mut state), [edited.color, BLUE])
|
||||
.layout(ColorPanelLayout::FillStroke)
|
||||
.edited(Some(edited))
|
||||
.recent(&RECENT)
|
||||
.recent_models(&[Some(cmyk)])
|
||||
.show(ui);
|
||||
seen.borrow_mut().extend(out.edits);
|
||||
});
|
||||
fixture.room(COLOR_ROOM).settle();
|
||||
let recent = fixture.by_label(&chip.to_hex()).expect("the recent chip is named by its hex");
|
||||
fixture.click(&recent).settle();
|
||||
edits.take()
|
||||
};
|
||||
let rgb_of = |color: Srgba| ModelValues::new("rgb", &[color.r * 255.0, color.g * 255.0, color.b * 255.0]);
|
||||
for edited in [PickedColor::in_model(RED, rgb_of(RED)), PickedColor::in_model(chip, rgb_of(chip)), PickedColor::rgb(chip)] {
|
||||
let edits = pick(edited);
|
||||
assert!(
|
||||
matches!(edits.as_slice(), [(PanelTarget::Foreground, EditEvent::Set { after, .. })]
|
||||
if after.model == Some(cmyk) && after.color.to_rgba() == chip.to_rgba()),
|
||||
"one Set to the chip in CMYK from {edited:?}: {edits:?}"
|
||||
);
|
||||
}
|
||||
let edits = pick(PickedColor::in_model(chip, cmyk));
|
||||
assert!(edits.is_empty(), "the chip's own values set nothing: {edits:?}");
|
||||
}
|
||||
|
||||
/// A Recent Colors pick drops the HSB values the rows kept for a grey: after a host that keeps only sRGB applies a grey
|
||||
/// chip with HSB values, the Hue row reads the grey afresh instead of the hue of the earlier row edits.
|
||||
#[trial]
|
||||
fn a_fill_stroke_recent_pick_drops_the_rows_kept_hue() {
|
||||
let grey = Srgba::rgb(0.5, 0.5, 0.5);
|
||||
let chip = [grey];
|
||||
let chip_hsb = ModelValues::new("hsb", &[0.0, 0.0, 50.0]);
|
||||
let host = Rc::new(RefCell::new(grey));
|
||||
let color = Rc::clone(&host);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let current = *color.borrow();
|
||||
let mut state = ColorPanelState { mode: ColorPanelMode::HsbSliders, ..Default::default() };
|
||||
let shown = ColorPanel::new(Bind::bound(&mut state), [current, BLUE])
|
||||
.layout(ColorPanelLayout::FillStroke)
|
||||
.edited(Some(PickedColor::rgb(current)))
|
||||
.shown(ColorPanelShown::Mode(ColorPanelMode::HsbSliders))
|
||||
.recent(&chip)
|
||||
.recent_models(&[Some(chip_hsb)])
|
||||
.show(ui);
|
||||
for (_, event) in &shown.edits {
|
||||
if let Some(picked) = event.landed() {
|
||||
*color.borrow_mut() = picked.color;
|
||||
}
|
||||
}
|
||||
});
|
||||
fixture.room(COLOR_ROOM).settle();
|
||||
let hue = fixture.by_role(Role::SLIDER).into_iter().next().expect("the hue slider");
|
||||
fixture.access(AccessActionKind::Focus, &hue).settle();
|
||||
for _ in 0..20 {
|
||||
fixture.key(Key::ArrowRight, Modifiers::NONE).settle();
|
||||
}
|
||||
let hue_value = |fixture: &mut Fixture| {
|
||||
let hue = fixture.by_role(Role::SLIDER).into_iter().next().expect("the hue slider");
|
||||
fixture.access(AccessActionKind::Focus, &hue).settle();
|
||||
let id = fixture.focused().expect("the hue slider takes the focus");
|
||||
fixture.tree().value(id).expect("the hue slider reports its value").to_owned()
|
||||
};
|
||||
let stepped = hue_value(&mut fixture);
|
||||
assert_ne!(stepped, "0", "the steps moved the kept hue of the grey");
|
||||
let recent = fixture.by_label(&grey.to_hex()).expect("the recent chip is named by its hex");
|
||||
fixture.click(&recent).settle();
|
||||
assert_eq!(hue_value(&mut fixture), "0", "the pick drops the kept hue {stepped}");
|
||||
}
|
||||
|
||||
/// In a host sized by its content (a floating Color panel) the FillStroke spectrum is as tall as its end boxes stacked,
|
||||
/// each at least as tall as it is wide, not a thin band; in a short group it keeps that height and the body scrolls.
|
||||
#[trial]
|
||||
@@ -471,6 +697,7 @@ struct PaletteReports {
|
||||
edits: Vec<EditEvent<Srgba>>,
|
||||
requests: Vec<ColorRequest>,
|
||||
picked: Vec<Srgba>,
|
||||
cells: Vec<PaletteCell>,
|
||||
swatches: Vec<usize>,
|
||||
}
|
||||
|
||||
@@ -482,6 +709,7 @@ fn collect(reports: &Reports, shown: craft_color_ui::ui::SwatchPaletteOutput) {
|
||||
reports.edits.extend(shown.edit);
|
||||
reports.requests.extend(shown.pick_color);
|
||||
reports.picked.extend(shown.picked);
|
||||
reports.cells.extend(shown.cell);
|
||||
reports.swatches.extend(shown.picked_swatch);
|
||||
}
|
||||
|
||||
@@ -539,11 +767,13 @@ fn the_other_cell_files_a_request_at_the_colour_and_a_recent_pick_sets_it() {
|
||||
taken.edits[0]
|
||||
);
|
||||
assert_eq!(bound.get().to_rgba(), RECENT[0].to_rgba(), "the recent pick is written");
|
||||
assert_eq!(taken.cells, [PaletteCell::Recent(0)], "the pick names its cell in the recent row");
|
||||
|
||||
let violet = fixture.by_label("Violet").expect("violet");
|
||||
fixture.click(&violet).settle();
|
||||
let _ = std::mem::take(&mut *reports.borrow_mut());
|
||||
let taken = std::mem::take(&mut *reports.borrow_mut());
|
||||
assert_eq!(bound.get().to_rgba(), swatch("Violet").to_rgba());
|
||||
assert_eq!(taken.cells, [PaletteCell::Swatch(5)], "the pick names its swatch");
|
||||
// Past the double-click time, so the repeat is a single click of its own.
|
||||
fixture.advance(1.0);
|
||||
let violet = fixture.by_label("Violet").expect("violet");
|
||||
@@ -908,6 +1138,56 @@ fn a_dragged_swatch_carries_the_hosts_payload_beside_the_panels_own_move() {
|
||||
assert_eq!(edits.borrow().len(), 1, "a drop outside the panel edits nothing: {:?}", edits.borrow());
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn swatches_keep_both_host_drop_places() {
|
||||
use craft_color_ui::palette::SwatchEntry;
|
||||
use craft_ui::contract::{DropAt, DropPlace, ListDrag, ShowCollection as _};
|
||||
use craft_ui::list::{List, ListRow};
|
||||
use craft_ui::patterns::presets::{PresetEvent, PresetView};
|
||||
use egui::{Pos2, Rect, UiBuilder};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Art;
|
||||
|
||||
const SWATCHES: Rect = Rect { min: Pos2::ZERO, max: Pos2::new(300.0, 300.0) };
|
||||
const LAYERS: Rect = Rect { min: Pos2::new(320.0, 0.0), max: Pos2::new(460.0, 120.0) };
|
||||
let groups = vec![SwatchGroup {
|
||||
name: String::new(),
|
||||
entries: vec![SwatchEntry::new("Red", SwatchColor::Rgb([1.0, 0.0, 0.0])), SwatchEntry::new("Blue", SwatchColor::Rgb([0.0, 0.0, 1.0]))],
|
||||
}];
|
||||
let received = Rc::new(RefCell::new(Vec::new()));
|
||||
let seen = Rc::clone(&received);
|
||||
let mut state = SwatchesState::default();
|
||||
state.browser.view = PresetView::List;
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
ui.scope_builder(UiBuilder::new().max_rect(LAYERS), |ui| {
|
||||
let ids = [7_u32];
|
||||
let source = craft_behavior::keyed(&ids, |id: &u32| *id);
|
||||
List::<u32>::new("Layers").drag_payload(|_: &ListDrag<u32>| Some(Art)).show_items(ui, &source, &mut |_, _| ListRow::new("Art"));
|
||||
});
|
||||
ui.scope_builder(UiBuilder::new().max_rect(SWATCHES), |ui| {
|
||||
let out = SwatchesPanel::new(&groups, Bind::bound(&mut state), RED)
|
||||
.takes_drop::<Art>(DropPlace::Between, |_, _| true)
|
||||
.takes_drop::<Art>(DropPlace::Onto, |_, _| true)
|
||||
.show(ui);
|
||||
seen.borrow_mut().extend(
|
||||
out.events
|
||||
.into_iter()
|
||||
.filter_map(|event| if let PresetEvent::Dropped { at, payload, .. } = event { payload.get::<Art>().map(|_| at) } else { None }),
|
||||
);
|
||||
});
|
||||
});
|
||||
fixture.room(Vec2::new(480.0, 320.0)).settle();
|
||||
let blue = fixture.by_label("Blue, #0000ff").expect("the Blue swatch").rect;
|
||||
let gap = Pos2::new(blue.center().x, blue.min.y + 2.0);
|
||||
for to in [gap, blue.center()] {
|
||||
let from = fixture.by_label("Art").expect("the layer row").center();
|
||||
fixture.drag_at(from, to - from).settle();
|
||||
}
|
||||
let blue = SwatchKey::Swatch("Blue".into());
|
||||
assert_eq!(*received.borrow(), [DropAt::gap(Some(blue.clone()), 1), DropAt::Onto(blue)]);
|
||||
}
|
||||
|
||||
/// A panel shown for one document after another keeps a rename left open with its document: the other document's
|
||||
/// swatch of the same name opens no field, and Enter there renames nothing.
|
||||
#[trial]
|
||||
|
||||
@@ -5,12 +5,12 @@ use std::rc::Rc;
|
||||
|
||||
use craft_behavior::Mixed;
|
||||
use craft_color_ui::ui::{
|
||||
ColorPicker, ColorPickerDialog, ColorPickerDialogLayout, ColorPickerLayout, ColorPickerTab, ColorPopover, ColorReadout, ColorWarning,
|
||||
PickedColor, PickerLibrary, PickerSwatches,
|
||||
ChannelRow, ChannelRowOutput, ChannelRule, ColorPicker, ColorPickerDialog, ColorPickerDialogLayout, ColorPickerLayout, ColorPickerTab,
|
||||
ColorPopover, ColorReadout, ColorWarning, PickedColor, PickerLibrary, PickerSwatches,
|
||||
};
|
||||
use craft_host::{AppInfo, Host};
|
||||
use craft_theme::{ColorModel, HsbModel, LabModel, ModelValues, OklchModel, RgbModel, Rgba, Size, Srgba, ThemeId};
|
||||
use craft_ui::contract::{Bind, Role, ShowContainer as _};
|
||||
use craft_ui::contract::{Bind, EditResponse, Role, ShowContainer as _};
|
||||
use craft_ui::dialog::{DialogHost, DialogResult, StackDialog, dialog_id};
|
||||
use craft_ui::layout::RowAlign;
|
||||
use craft_ui::layout_components::Row;
|
||||
@@ -177,6 +177,45 @@ fn the_dialogs_rgb_fields_show_the_hosts_working_values() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `ChannelRow::show` returns the row's edit, and `show_with_units` returns the same edit with the units cell's
|
||||
/// double click, which typing into the field does not report.
|
||||
#[trial]
|
||||
fn a_channel_rows_show_returns_its_edit_and_show_with_units_adds_the_units_cell() {
|
||||
let rule = ChannelRule { range: 0.0..=100.0, step: 1.0, decimals: 0 };
|
||||
/// Each edit: the row, the value and whether the units cell was double-clicked.
|
||||
type Seen = Rc<RefCell<Vec<(&'static str, f64, bool)>>>;
|
||||
let got: Seen = Rc::default();
|
||||
let seen = Rc::clone(&got);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let edit: Option<EditResponse<f64>> = ChannelRow::new("Plain", Bind::given(40.0), rule.clone()).show(ui);
|
||||
for event in edit.into_iter().flat_map(|edit| edit.events) {
|
||||
if let Some(v) = event.value() {
|
||||
seen.borrow_mut().push(("Plain", *v, false));
|
||||
}
|
||||
}
|
||||
let row: ChannelRowOutput = ChannelRow::new("Units", Bind::given(40.0), rule.clone()).show_with_units(ui);
|
||||
for event in row.edit.into_iter().flat_map(|edit| edit.events) {
|
||||
if let Some(v) = event.value() {
|
||||
seen.borrow_mut().push(("Units", *v, row.units_double_clicked));
|
||||
}
|
||||
}
|
||||
});
|
||||
fixture.room(vec2(320.0, 200.0));
|
||||
fixture.idle(2);
|
||||
for (i, text) in [(0, "70"), (1, "20")] {
|
||||
let field = fixture.by_role(Role::SPIN_BUTTON).into_iter().nth(i).unwrap_or_else(|| panic!("number field {i}"));
|
||||
fixture.click(&field);
|
||||
fixture.key(Key::A, Modifiers::COMMAND);
|
||||
fixture.type_text(text);
|
||||
fixture.key(Key::Enter, Modifiers::NONE);
|
||||
fixture.settle();
|
||||
}
|
||||
let got = got.borrow();
|
||||
assert!(got.iter().any(|&(row, v, _)| row == "Plain" && v == 70.0), "show reports the typed value: {got:?}");
|
||||
assert!(got.iter().any(|&(row, v, _)| row == "Units" && v == 20.0), "show_with_units reports the typed value: {got:?}");
|
||||
assert!(got.iter().all(|&(_, _, clicked)| !clicked), "typing is not a double click on the units cell: {got:?}");
|
||||
}
|
||||
|
||||
/// The densities and themes every layout trial runs in: compact and comfortable, a Pro and a Studio theme.
|
||||
const LOOKS: [(Size, &str); 4] =
|
||||
[(Size::Compact, "craft.pro"), (Size::Comfortable, "craft.pro"), (Size::Compact, "craft.studio"), (Size::Comfortable, "craft.studio")];
|
||||
@@ -558,6 +597,15 @@ fn the_tabbed_colors_dialog_opens_on_its_tab_and_answers_from_either_page() {
|
||||
fixture.click(&cell);
|
||||
fixture.idle(4);
|
||||
assert_eq!(dialog_color(&dialogs).as_deref(), Some("#0000ff"), "a honeycomb pick is the colour");
|
||||
// #7984: the Standard page shows the compare block too, and its current half restores the opening colour.
|
||||
assert!(fixture.by_label("New color").is_some(), "the Standard page shows the compare block");
|
||||
let restore = fixture.by_label("Restore current color").expect("the compare block's current half");
|
||||
fixture.click(&restore);
|
||||
fixture.idle(4);
|
||||
assert_eq!(dialog_color(&dialogs).as_deref(), Some("#123456"), "the current half restores the opening colour");
|
||||
let cell = fixture.by_label("Standard 2").expect("the honeycomb shows its cells");
|
||||
fixture.click(&cell);
|
||||
fixture.idle(4);
|
||||
|
||||
assert!(dialogs.borrow_mut().confirm::<ColorPickerDialog>(&ctx), "OK answers");
|
||||
let answered = dialogs.borrow_mut().take::<ColorPickerDialog>().and_then(DialogResult::ok).map(|result| result.picked.color.to_hex());
|
||||
|
||||
@@ -114,6 +114,7 @@ craft-material-graph = { workspace = true, optional = true }
|
||||
craft-materialx = { workspace = true, optional = true }
|
||||
craft-math = { workspace = true, optional = true }
|
||||
craft-mesh = { workspace = true, optional = true }
|
||||
craft-mesh-ops = { workspace = true, optional = true }
|
||||
craft-metadata = { workspace = true, optional = true }
|
||||
craft-metafile = { workspace = true, optional = true }
|
||||
craft-midi = { workspace = true, optional = true }
|
||||
@@ -675,6 +676,8 @@ mesh-ply = ["mesh", "craft-mesh/ply"]
|
||||
mesh-stl = ["mesh", "craft-mesh/stl"]
|
||||
mesh-threemf = ["mesh", "craft-mesh/threemf"]
|
||||
|
||||
mesh-ops = ["dep:craft-mesh-ops"]
|
||||
|
||||
metadata = ["dep:craft-metadata"]
|
||||
|
||||
metafile = ["dep:craft-metafile"]
|
||||
@@ -706,6 +709,8 @@ pages = ["dep:craft-pages", "keymap", "text"]
|
||||
palette = ["dep:craft-palette"]
|
||||
|
||||
pbr = ["dep:craft-pbr"]
|
||||
pbr-materialx = ["pbr", "craft-pbr/materialx"]
|
||||
pbr-mesh = ["pbr", "craft-pbr/mesh"]
|
||||
pbr-parallel = ["pbr", "craft-pbr/parallel"]
|
||||
|
||||
pcap = ["dep:craft-pcap"]
|
||||
@@ -945,7 +950,12 @@ text-ukrainian = ["text", "craft-text/ukrainian"]
|
||||
|
||||
texture = ["dep:craft-texture"]
|
||||
texture-dds = ["texture", "craft-texture/dds"]
|
||||
texture-decode = ["texture", "craft-texture/decode"]
|
||||
texture-exr = ["texture", "craft-texture/exr"]
|
||||
texture-hdr = ["texture", "craft-texture/hdr"]
|
||||
texture-parallel = ["texture", "craft-texture/parallel"]
|
||||
texture-png = ["texture", "craft-texture/png"]
|
||||
texture-tiff = ["texture", "craft-texture/tiff"]
|
||||
|
||||
tga = ["dep:craft-tga"]
|
||||
|
||||
|
||||
@@ -251,6 +251,8 @@ pub use craft_media_source as media_source;
|
||||
pub use craft_menu as menu;
|
||||
#[cfg(feature = "mesh")]
|
||||
pub use craft_mesh as mesh;
|
||||
#[cfg(feature = "mesh-ops")]
|
||||
pub use craft_mesh_ops as mesh_ops;
|
||||
#[cfg(feature = "metadata")]
|
||||
pub use craft_metadata as metadata;
|
||||
#[cfg(feature = "metafile")]
|
||||
|
||||
@@ -19,7 +19,7 @@ pub struct CornerStyle {
|
||||
pub(super) dot: f32,
|
||||
/// The pointer's reach.
|
||||
pub(super) reach: f32,
|
||||
/// The least distance inside a corner.
|
||||
/// The least distance inside a corner: [`CornerWidgets::INSET`](super::CornerWidgets::INSET).
|
||||
pub(super) inset: f32,
|
||||
/// The shortest side, on the screen, whose corners show widgets.
|
||||
pub(super) min_side: f32,
|
||||
@@ -38,7 +38,7 @@ impl CornerStyle {
|
||||
widget: tokens.size.handle.md,
|
||||
dot: tokens.size.handle.sm,
|
||||
reach: tokens.size.hit.target,
|
||||
inset: tokens.space.gap.stack,
|
||||
inset: super::CornerWidgets::INSET,
|
||||
min_side: MIN_SIDE,
|
||||
fill: cx.color(tokens.color.overlay.handle_fill),
|
||||
color: cx.color(tokens.color.overlay.line),
|
||||
|
||||
@@ -101,6 +101,10 @@ impl<'a> CornerWidgets<'a> {
|
||||
|
||||
/// The widest inner angle, in degrees, a widget shows at unless [`hide_above`](Self::hide_above) says otherwise.
|
||||
pub const HIDE_ABOVE: f64 = 180.0;
|
||||
|
||||
/// The least distance, in screen points along each side of a right angle, a widget sits inside its corner, at every
|
||||
/// density. A host that hit-tests the widgets itself reads it from here.
|
||||
pub const INSET: f32 = 10.0;
|
||||
}
|
||||
|
||||
/// What the widgets report: the edit of the targets and what the widgets ask the host to do.
|
||||
|
||||
@@ -118,3 +118,30 @@ fn a_triangle_apex_rounds_with_the_pointer_travel() {
|
||||
assert!(small > START_RADIUS, "a short pull rounds the apex: {small}");
|
||||
assert!(large > small, "a longer pull rounds it more: {small} then {large}");
|
||||
}
|
||||
|
||||
/// A slightly rounded right-angle corner's widget sits `CornerWidgets::INSET` points inside the corner along each side,
|
||||
/// at every density, so a host that hit-tests the widgets with that constant presses where the widget is drawn.
|
||||
#[trial]
|
||||
fn a_widget_sits_the_published_inset_inside_its_corner_at_every_density() {
|
||||
for density in [craft_theme::Size::Compact, craft_theme::Size::Comfortable] {
|
||||
let vertex = Rc::new(Cell::new(egui::Pos2::ZERO));
|
||||
let seen = Rc::clone(&vertex);
|
||||
let mut targets = vec![square()];
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let room = ui.available_rect_before_wrap();
|
||||
let view = CanvasView::new(room, Point::new(210.0, 200.0), 1.0);
|
||||
seen.set(view.to_screen(targets[0].corners[0].vertex));
|
||||
Canvas::new("Document")
|
||||
.view(view)
|
||||
.show(ui, |ui, body| CornerWidgets::new("Corner radius", Bind::bound(&mut targets)).show_at(ui, body.rect));
|
||||
});
|
||||
fixture.density(density).settle();
|
||||
let widget = fixture.by_label("Corner 1 of 4").expect("the first corner has a widget");
|
||||
let offset = widget.center() - vertex.get();
|
||||
let inset = CornerWidgets::INSET;
|
||||
assert!(
|
||||
(offset.x - inset).abs() < 0.5 && (offset.y - inset).abs() < 0.5,
|
||||
"{density:?}: the widget sits {offset:?} from its corner, not {inset} along each side"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1757,7 +1757,8 @@ fn deflate_rows(
|
||||
/// and completes the flush: when a sync flush fills the buffer, miniz_oxide (flate2's former Rust
|
||||
/// backend) can return before compressing the last lookahead bytes, and the next call only
|
||||
/// drains the pending output, so a resumed flush silently drops data. `None` (the caller then
|
||||
/// uses the serial encoder) if the single call did not finish.
|
||||
/// uses the serial encoder) if the single call did not finish. The returned bytes keep no
|
||||
/// spare capacity, because the caller holds every band until it joins them into one stream.
|
||||
fn deflate_band(filtered: &[u8], lvl: flate2::Compression, last: bool) -> Option<Vec<u8>> {
|
||||
let mut c = flate2::Compress::new(lvl, false);
|
||||
// Stored blocks cost 5 bytes per 64 KiB, the flush an empty stored block: 1/8 is ample.
|
||||
@@ -1766,7 +1767,10 @@ fn deflate_band(filtered: &[u8], lvl: flate2::Compression, last: bool) -> Option
|
||||
let flush = if last { flate2::FlushCompress::Finish } else { flate2::FlushCompress::Sync };
|
||||
let status = c.compress_vec(filtered, &mut z, flush).ok()?;
|
||||
let done = if last { status == flate2::Status::StreamEnd } else { c.total_in() as usize == filtered.len() && z.len() < z.capacity() };
|
||||
done.then_some(z)
|
||||
done.then(|| {
|
||||
z.shrink_to_fit();
|
||||
z
|
||||
})
|
||||
}
|
||||
|
||||
/// One scanline with the adaptive filter choice, appended to `out` (type byte + data).
|
||||
@@ -2256,6 +2260,19 @@ mod parallel_tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every band is held until the stream is joined, so a band keeps only the bytes it holds,
|
||||
/// not the worst-case buffer it was deflated into (about 1.125 times the image in all).
|
||||
#[test]
|
||||
fn deflated_bands_keep_no_spare_capacity() {
|
||||
let (w, h, bpp) = (1024usize, 600usize, 3usize);
|
||||
let px: Vec<u8> = (0..w * h * bpp).map(|i| (i % 7) as u8).collect();
|
||||
let parts = deflate_rows(&px, None, w * bpp, bpp, band_rows(w * bpp), flate2::Compression::default(), true, 2).unwrap();
|
||||
assert!(parts.len() > 2);
|
||||
for (i, p) in parts.iter().enumerate() {
|
||||
assert!(p.z.capacity() <= p.z.len() + 64, "band {i}: capacity {} for {} bytes of {}", p.z.capacity(), p.z.len(), p.len);
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes depend on the image, not on the machine: one, two and 32 worker threads
|
||||
/// (and the machine's own count, through `encode`) give the same stream.
|
||||
#[test]
|
||||
|
||||
@@ -747,8 +747,8 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result<Prep
|
||||
let tl = {
|
||||
let mut l = tiff::decoder::Limits::default();
|
||||
l.decoding_buffer_size = limits.alloc_usize();
|
||||
// No compressed chunk can be larger than the file.
|
||||
l.intermediate_buffer_size = f.b.len().max(1);
|
||||
// Each compressed chunk must fit both the file and the allocation budget.
|
||||
l.intermediate_buffer_size = f.b.len().max(1).min(limits.alloc_usize());
|
||||
l
|
||||
};
|
||||
let mut dec = Decoder::new(Patched { b: f.b, patches: &patches, pos: 0 }).map(|d| d.with_limits(tl.clone())).map_err(map_err)?;
|
||||
|
||||
@@ -27,7 +27,7 @@ mod binding;
|
||||
mod command;
|
||||
|
||||
pub use binding::{Binding, BindingError};
|
||||
pub use command::{CommandDef, CommandKind, DeleteKeys, ModalRule, TypingRule};
|
||||
pub use command::{CommandDef, CommandKind, DeleteKeys, Dispatch, ModalRule, TypingRule};
|
||||
|
||||
mod editing;
|
||||
pub use editing::text_editing_chords;
|
||||
@@ -400,7 +400,9 @@ impl Keymap {
|
||||
self.find(command).map(|i| &self.catalog[i])
|
||||
}
|
||||
|
||||
/// The effective bindings of a command; empty for an unknown one.
|
||||
/// The effective bindings of a command; empty for an unknown one. A command the app runs itself
|
||||
/// ([`Dispatch::App`]) lists its bindings too, as the shortcut editor shows and edits them, though nothing here
|
||||
/// matches them.
|
||||
pub fn bindings(&self, command: &CommandRef) -> Vec<Binding> {
|
||||
self.find(command).map(|i| self.current[i].iter().filter(|b| self.counts(b)).map(|b| self.public(i, b)).collect()).unwrap_or_default()
|
||||
}
|
||||
@@ -455,7 +457,8 @@ impl Keymap {
|
||||
}
|
||||
}
|
||||
|
||||
/// The command `chord` (pressed twice when `double`) runs with `active` focus.
|
||||
/// The command `chord` (pressed twice when `double`) runs with `active` focus. A command the app runs itself
|
||||
/// ([`Dispatch::App`]) is none of them: its chords belong to the app's own key handling.
|
||||
pub fn lookup(&self, chord: &Chord, double: bool, active: &Active) -> Lookup {
|
||||
self.lookup_nested(chord, double, active, &[])
|
||||
}
|
||||
@@ -522,6 +525,9 @@ impl Keymap {
|
||||
/// applies (an application binding with no panel focused, a panel binding with its panel focused, a context
|
||||
/// binding with its context active), gives the command or a cycle that holds it. `None` when every binding is
|
||||
/// shadowed or the command has none. Read from a table the keymap builds when its bindings change.
|
||||
///
|
||||
/// A command the app runs itself ([`Dispatch::App`]) shows its first single-press binding wherever it is, home
|
||||
/// scope first: nothing here matches its chords, so nothing here can shadow them.
|
||||
pub fn shown_chord(&self, command: &CommandRef) -> Option<Chord> {
|
||||
self.find(command).and_then(|i| self.shown[i])
|
||||
}
|
||||
@@ -537,6 +543,15 @@ impl Keymap {
|
||||
fn shown_of(&self, i: usize) -> Option<Chord> {
|
||||
let home = &self.catalog[i].scope;
|
||||
let single = || self.current[i].iter().filter(|(trigger, _)| trigger.press == PressKind::Single);
|
||||
// The app runs a command marked `Dispatch::App` on its own, so the keymap cannot tell whether a chord it also
|
||||
// binds takes the key first: it shows the command's first binding rather than dropping it as shadowed.
|
||||
if self.catalog[i].dispatch == Dispatch::App {
|
||||
return single()
|
||||
.filter(|(_, scope)| scope == home)
|
||||
.chain(single().filter(|(_, scope)| scope != home))
|
||||
.map(|(trigger, _)| trigger.chord)
|
||||
.next();
|
||||
}
|
||||
let runs = |(trigger, scope): &&Bound| {
|
||||
let name = [scope.as_str()];
|
||||
let active = match self.scopes.kind(scope) {
|
||||
@@ -1061,6 +1076,11 @@ impl Keymap {
|
||||
|
||||
fn index_command(&mut self, i: usize) {
|
||||
let Some(list) = self.current.get(i) else { return };
|
||||
// A command the app runs itself matches nothing here: its chords stay in the app's hands, as the raw input
|
||||
// holds them.
|
||||
if self.catalog[i].dispatch == Dispatch::App {
|
||||
return;
|
||||
}
|
||||
let holds = self.holds;
|
||||
for (k, (t, _)) in list.iter().enumerate().filter(|(_, (t, _))| holds || !t.is_hold()) {
|
||||
self.by_trigger.entry(t.effective(self.platform)).or_default().insert((i, k));
|
||||
|
||||
@@ -28,6 +28,27 @@ pub enum CommandKind {
|
||||
Momentary,
|
||||
}
|
||||
|
||||
/// Who runs a command's keys.
|
||||
///
|
||||
/// A command the app runs itself keeps its place in the catalog and its bindings: menus, tooltips, rails and buttons
|
||||
/// show its chords ([`Keymap::shown_chord`](crate::Keymap::shown_chord)) and the shortcut editor lists them, and the
|
||||
/// keymap matches none of them, so the press goes to the app as it would for a command with no binding here.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum Dispatch {
|
||||
/// This keymap runs the command on its chords ([`Keymap::lookup`](crate::Keymap::lookup)).
|
||||
#[default]
|
||||
Keymap,
|
||||
/// The app runs the command from its own key handling (a canvas editor with its own keymap).
|
||||
App,
|
||||
}
|
||||
|
||||
/// Whether a command's keys are the keymap's, which written catalogs leave out as the default.
|
||||
fn is_keymap(dispatch: &Dispatch) -> bool {
|
||||
*dispatch == Dispatch::Keymap
|
||||
}
|
||||
|
||||
/// Whether a command fires while a dialog is open.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -82,6 +103,10 @@ pub struct CommandDef {
|
||||
/// Whether the command fires while a dialog is open.
|
||||
#[serde(default)]
|
||||
pub modal: ModalRule,
|
||||
/// Who runs the command's keys: this keymap, or the app, which shows them and matches none of them
|
||||
/// ([`Dispatch`]).
|
||||
#[serde(default, skip_serializing_if = "is_keymap")]
|
||||
pub dispatch: Dispatch,
|
||||
}
|
||||
|
||||
impl CommandDef {
|
||||
@@ -99,6 +124,7 @@ impl CommandDef {
|
||||
defaults: Vec::new(),
|
||||
icon: None,
|
||||
modal: ModalRule::default(),
|
||||
dispatch: Dispatch::Keymap,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,6 +163,12 @@ impl CommandDef {
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the [`dispatch`](CommandDef::dispatch).
|
||||
pub fn with_dispatch(mut self, dispatch: Dispatch) -> CommandDef {
|
||||
self.dispatch = dispatch;
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds a default binding.
|
||||
pub fn with_default(mut self, binding: Binding) -> CommandDef {
|
||||
self.defaults.push(binding);
|
||||
|
||||
@@ -62,6 +62,10 @@
|
||||
//! assert_eq!(press("M", &editing), Lookup::None, "plain keys go to the text field");
|
||||
//! ```
|
||||
//!
|
||||
//! A command whose keys the app runs itself keeps its bindings and shows their chords, and the keymap matches none of
|
||||
//! them: `CommandDef::new(..).with_dispatch(Dispatch::App)` tells the surfaces what to show for a command whose keys
|
||||
//! the app's own key handling takes (a canvas's tool keys), so the menus and the shortcut editor still read the catalog.
|
||||
//!
|
||||
//! # Storing overrides
|
||||
//!
|
||||
//! [`Overrides`] is a field of the app's craft-settings type, marked
|
||||
@@ -158,8 +162,8 @@ pub use import::{
|
||||
ContextRule, DecodedCode, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, ImportPlan, ImportReport, NoneDefined, NotRead, Start, plan,
|
||||
};
|
||||
pub use keymap::{
|
||||
AssignError, Assigned, Binding, BindingError, CommandDef, CommandKind, Conflict, ConflictKind, DeleteKeys, DropReason, Holder, Keymap, Lookup,
|
||||
MAX_BINDING_TEXT, MAX_BINDINGS, MAX_COMMANDS, MAX_CONFLICTS, ModalRule, Overrides, Policy, Problem, TypingRule, text_editing_chords,
|
||||
AssignError, Assigned, Binding, BindingError, CommandDef, CommandKind, Conflict, ConflictKind, DeleteKeys, Dispatch, DropReason, Holder, Keymap,
|
||||
Lookup, MAX_BINDING_TEXT, MAX_BINDINGS, MAX_COMMANDS, MAX_CONFLICTS, ModalRule, Overrides, Policy, Problem, TypingRule, text_editing_chords,
|
||||
};
|
||||
pub use layout::{COMMON_SYMBOLS, KeyInput, Layout, SYMBOL_TABLE, SymbolLayout};
|
||||
pub use matcher::{Hit, Matcher, Press};
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! Integration tests of craft-keymap: keymap.
|
||||
|
||||
use craft_keymap::{
|
||||
Active, Binding, Chord, CommandDef, CommandRef, DeleteKeys, DropReason, Key, KeyInput, Keymap, Layout, Lookup, MAX_COMMANDS, Matcher, Mods,
|
||||
Overrides, Platform, Policy, Press, Problem, Scope, Scopes, Trigger,
|
||||
Active, Binding, Chord, CommandDef, CommandRef, DeleteKeys, Dispatch, DropReason, Key, KeyInput, Keymap, Layout, Lookup, MAX_COMMANDS, Matcher,
|
||||
Mods, Overrides, Platform, Policy, Press, Problem, Scope, Scopes, Trigger,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
@@ -152,6 +152,35 @@ fn a_command_shows_only_the_chords_the_lookup_runs_it_for() {
|
||||
assert_eq!(alone.shown_chord(&cmd("edit.settings")), None, "every key shadowed");
|
||||
}
|
||||
|
||||
/// A command the app runs itself keeps its bindings and the chord they show, and matching passes over it: the lookup
|
||||
/// finds nothing for its chords, the command holds none, another command on a chord it binds still shows it, and an
|
||||
/// assignment takes nothing from it.
|
||||
#[test]
|
||||
fn a_command_the_app_runs_itself_shows_its_chords_and_matches_none() {
|
||||
let own = |id: &str, keys: &[&str]| app(id, keys).with_dispatch(Dispatch::App);
|
||||
let km = Keymap::new(vec![own("tool.brush", &["J", "B"])], Scopes::new(), Platform::Mac);
|
||||
assert_eq!(km.shown_chord(&cmd("tool.brush")), Some(chord("J")), "its first binding shows");
|
||||
assert_eq!(km.bindings(&cmd("tool.brush")), [b("J"), b("B")], "and the shortcut editor lists them");
|
||||
assert_eq!(press(&km, "J", &Active::NONE), Lookup::None, "the lookup passes over its chords");
|
||||
assert_eq!(press(&km, "B", &Active::NONE), Lookup::None);
|
||||
assert_eq!(km.holder(&chord("J")), None, "it holds no chord");
|
||||
assert!(km.holders(&chord("J")).is_empty());
|
||||
|
||||
// Another command on a chord it binds runs, and it still shows its own chord: nothing here shadows it.
|
||||
let shared = Keymap::new(vec![own("tool.brush", &["J"]), app("view.grid", &["J"])], Scopes::new(), Platform::Mac);
|
||||
assert_eq!(press(&shared, "J", &Active::NONE), run("view.grid"), "the chord is the other command's");
|
||||
assert_eq!(shared.shown_chord(&cmd("tool.brush")), Some(chord("J")));
|
||||
assert_eq!(shared.shown_chord(&cmd("view.grid")), Some(chord("J")));
|
||||
assert!(shared.conflicts().is_empty(), "a chord the app runs clashes with nothing here");
|
||||
|
||||
// Assigning a chord it binds to another command takes nothing from it.
|
||||
let mut stealer = Keymap::new(vec![own("tool.brush", &["B"]), app("view.grid", &["J"])], Scopes::new(), Platform::Mac);
|
||||
let done = stealer.assign(&cmd("view.grid"), b("B"), Policy::Steal).expect("the assignment is taken");
|
||||
assert!(done.taken_from.is_empty(), "the command the app runs keeps its binding");
|
||||
assert_eq!(stealer.bindings(&cmd("tool.brush")), [b("B")]);
|
||||
assert_eq!(press(&stealer, "B", &Active::NONE), run("view.grid"));
|
||||
}
|
||||
|
||||
/// The shown chords are worked out when the bindings change, not per call, and follow every change: a key freed by one
|
||||
/// command shows on the command it no longer shadows, and a stolen key leaves the command it was taken from.
|
||||
#[test]
|
||||
|
||||
+1094
-44
File diff suppressed because it is too large.
Load diff
@@ -226,6 +226,8 @@ pub enum GalleryFace<'a> {
|
||||
thumbnails: &'a Thumbnails<u64>,
|
||||
/// What renders the thumbnail.
|
||||
source: &'a dyn ThumbSource<u64>,
|
||||
/// Whether the transparency grid shows behind transparent pixels.
|
||||
checker: bool,
|
||||
},
|
||||
/// A tile painted directly.
|
||||
Paint(&'a dyn Fn(&ContentPainterCx, Rect)),
|
||||
@@ -250,7 +252,17 @@ impl<'a> GalleryFace<'a> {
|
||||
|
||||
/// A thumbnail under `key`, rendered by `source` into `thumbnails`.
|
||||
pub fn rendered(key: u64, thumbnails: &'a Thumbnails<u64>, source: &'a dyn ThumbSource<u64>) -> Self {
|
||||
GalleryFace::Rendered { key, thumbnails, source }
|
||||
GalleryFace::Rendered { key, thumbnails, source, checker: true }
|
||||
}
|
||||
|
||||
/// Whether a rendered thumbnail shows the transparency grid behind its transparent pixels (default on). Off for a
|
||||
/// thumbnail that is a mask on the surface it sits on, such as an equation symbol. Other faces ignore it.
|
||||
#[must_use]
|
||||
pub fn checker(mut self, on: bool) -> Self {
|
||||
if let GalleryFace::Rendered { checker, .. } = &mut self {
|
||||
*checker = on;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// The picture this face shows, `size` high and `aspect` times as wide. It is decoration: the tile that holds it
|
||||
@@ -258,7 +270,9 @@ impl<'a> GalleryFace<'a> {
|
||||
fn picture(&self, aspect: ThumbAspect, size: ThumbSize) -> Picture<'a> {
|
||||
let picture = match self {
|
||||
GalleryFace::Image { key, revision, image } => Picture::new(Label::default(), *key, *image).revision(*revision),
|
||||
GalleryFace::Rendered { key, thumbnails, source } => Picture::rendered(Label::default(), *key, thumbnails, *source),
|
||||
GalleryFace::Rendered { key, thumbnails, source, checker } => {
|
||||
Picture::rendered(Label::default(), *key, thumbnails, *source).checker(*checker)
|
||||
}
|
||||
GalleryFace::Paint(paint) => {
|
||||
let paint = *paint;
|
||||
Picture::painter(Label::default(), aspect, move |cx: &ContentPainterCx<'_>, rect: Rect| paint(cx, rect))
|
||||
|
||||
@@ -172,8 +172,7 @@ fn gallery_rendered(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let options = ThumbnailOptions::new();
|
||||
let thumbnails = Thumbnails::<u64>::in_context(ui.ctx(), "craft_menu.gallery.story", options);
|
||||
let source = FakeThumbSource::<u64>::new().later(true);
|
||||
let items: Vec<GalleryItem<'_, usize>> = (0..COUNT)
|
||||
.map(|at| GalleryItem { key: at, label: name(at), face: GalleryFace::Rendered { key: at as u64, thumbnails: &thumbnails, source: &source } })
|
||||
.collect();
|
||||
let items: Vec<GalleryItem<'_, usize>> =
|
||||
(0..COUNT).map(|at| GalleryItem { key: at, label: name(at), face: GalleryFace::rendered(at as u64, &thumbnails, &source) }).collect();
|
||||
show(ui, &items)
|
||||
}
|
||||
@@ -24,6 +24,8 @@ use crate::shortcuts::state::{DialogState, Env};
|
||||
const LISTS_SHARE: f32 = 0.5;
|
||||
/// The detail column's share of the width beside the lists.
|
||||
const DETAIL_SHARE: f32 = 0.5;
|
||||
/// The most Categories rows shown before the list scrolls.
|
||||
const CATEGORY_ROWS: u16 = 6;
|
||||
const PANES: [ColumnWidth; 2] = [ColumnWidth::fill(LISTS_SHARE), ColumnWidth::fill(DETAIL_SHARE)];
|
||||
|
||||
/// One frame of the command-lists body: a search field, the Categories list beside the Commands
|
||||
@@ -62,6 +64,8 @@ fn categories(ui: &mut Ui, env: &Env<'_>, state: &mut DialogState) {
|
||||
let mut selection = Selection::new(at.into_iter().collect(), at, at);
|
||||
let out = List::<usize>::new(words.categories.clone())
|
||||
.id_salt("categories")
|
||||
// A short list, so the Commands list under it keeps room in a dialog of ordinary height.
|
||||
.max_rows(CATEGORY_ROWS)
|
||||
.select(SelectMode::Single)
|
||||
.selection(Bind::bound(&mut selection))
|
||||
.show_items(ui, &Titles(&labels), &mut |key, _| ListRow::new(labels[*key].clone()));
|
||||
|
||||
@@ -263,3 +263,26 @@ fn the_current_tile_paints_an_accent_fill_and_edge_even_when_focused() {
|
||||
assert!(shapes.iter().any(|p| p.fill == fill && near(p, current)), "{who}: the focused current tile keeps its fill");
|
||||
}
|
||||
}
|
||||
|
||||
/// How many shapes a gallery of one rendered tile of a transparent image paints, as built or with `checker(false)`.
|
||||
fn shapes_of_rendered(opt_out: bool) -> usize {
|
||||
use craft_ui::primitives::textures::{FakeThumbSource, ThumbnailOptions, Thumbnails};
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let options = ThumbnailOptions::new().jobs(std::sync::Arc::new(craft_host::InlineJobs));
|
||||
let thumbnails = Thumbnails::<u64>::in_context(ui.ctx(), "gallery_checker_test", options);
|
||||
let source = FakeThumbSource::<u64>::new();
|
||||
// The default case sets nothing, so a default that turned the grid off fails here.
|
||||
let face = GalleryFace::rendered(1, &thumbnails, &source);
|
||||
let face = if opt_out { face.checker(false) } else { face };
|
||||
let items = [GalleryItem { key: 0_usize, label: Label::from("Mask"), face }];
|
||||
Gallery::new("Symbols", &items, None).tiles(1, 1).show(ui);
|
||||
});
|
||||
fixture.settle();
|
||||
fixture.frame_shapes().len()
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_rendered_gallery_tile_paints_a_checker_unless_it_opts_out() {
|
||||
let (with, without) = (shapes_of_rendered(false), shapes_of_rendered(true));
|
||||
assert!(with > without, "the default paints {with} shapes, the opt-out {without}: the grid is the difference");
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
//! The Customize Keyboard layout: each change is applied at once and Escape closes without rolling back.
|
||||
|
||||
use craft_keymap::{Binding, CommandDef, CommandRef, Keymap, Platform, Scope, Scopes, Trigger};
|
||||
use craft_menu::shortcuts::{Layout, Outcome};
|
||||
use craft_menu::shortcuts::{Area, Layout, Outcome};
|
||||
use craft_ui::contract::Role;
|
||||
use craft_ui::testing::trial;
|
||||
use egui::{Key, Modifiers};
|
||||
@@ -79,3 +79,29 @@ fn command_lists_assign_remove_and_close_apply_each_change_at_once() {
|
||||
assert_eq!(keys(&rig), left, "the keymap keeps the edits");
|
||||
assert!(rig.bindings("file.export").is_empty(), "the taken chord is not given back");
|
||||
}
|
||||
|
||||
/// A long Categories list must not take the room the Commands list needs: in a dialog of ordinary height a command row
|
||||
/// still shows above the footer.
|
||||
#[trial]
|
||||
fn commands_keep_room_beside_a_long_categories_list() {
|
||||
let rig = Rig::tuned(Platform::Mac, |options| {
|
||||
options.layout = Layout::CommandLists;
|
||||
options.own_areas = true;
|
||||
options.size = Some(egui::vec2(640.0, 460.0));
|
||||
options.areas = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"].map(|name| Area::new(name, name, |_| true)).to_vec();
|
||||
});
|
||||
let row = rig.find("Bring to Front").center();
|
||||
let footer = rig.find("Reset All…").center();
|
||||
assert!(row.y < footer.y, "the command row ({row:?}) sits above the footer ({footer:?})");
|
||||
// The capped list scrolls: the arrow keys still reach its last entry.
|
||||
let mut rig = rig;
|
||||
rig.click("A");
|
||||
for _ in 0..11 {
|
||||
rig.press(Modifiers::NONE, Key::ArrowDown);
|
||||
}
|
||||
let area = {
|
||||
let shared = rig.shared.borrow();
|
||||
shared.state.snapshot(&shared.km).expect("the dialog has shown").area
|
||||
};
|
||||
assert_eq!(area, "L", "the last Categories entry is reachable");
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
# Attribution
|
||||
|
||||
`craft-mesh-ops` generates tangents with the `mikktspace` crate.
|
||||
|
||||
| Package | Authors | Source | License |
|
||||
|---|---|---|---|
|
||||
| `mikktspace` 0.3.0 | Benjamin Wasty, David Harvey-Macaulay, Layl Bongers | [crates.io](https://crates.io/crates/mikktspace/0.3.0), [gltf-rs/mikktspace](https://github.com/gltf-rs/mikktspace) | MIT OR Apache-2.0 (the package's `license` field) |
|
||||
|
||||
The package's `src/generated.rs` is a translation of Morten S. Mikkelsen's C implementation of
|
||||
the MikkTSpace algorithm and carries that implementation's notice, reproduced here unchanged:
|
||||
|
||||
```text
|
||||
Copyright (C) 2011 by Morten S. Mikkelsen
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source distribution.
|
||||
```
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "craft-mesh-ops"
|
||||
description = "Triangle mesh operations: smooth normals, MikkTSpace tangents, welding, UV unwrapping, a UV-space G-buffer, primitives with UVs, a BVH and an orbit camera"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
glam = { version = "0.30", features = ["serde"] }
|
||||
# MIT OR Apache-2.0; its src/generated.rs also carries the zlib-style notice of the C original,
|
||||
# reproduced in ATTRIBUTION.md.
|
||||
mikktspace = { version = "0.3", default-features = false, features = ["glam"] }
|
||||
rayon = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
@@ -0,0 +1,47 @@
|
||||
# craft-mesh-ops
|
||||
|
||||
Operations on triangle meshes, for apps that paint, bake or preview materials on 3D models. The
|
||||
crate has no UI, does no file or network I/O and has no `unsafe` code. File formats stay in
|
||||
[`craft-mesh`](../mesh/README.md).
|
||||
|
||||
- **`Mesh`.** Positions, normals, tangents, UVs, vertex colors, indices, per-material submeshes
|
||||
and polygon-diagonal flags, with `validate`, `append`, `subdivided`, `normalize_to`, wireframe
|
||||
and UV-seam edges, and UV-tile helpers.
|
||||
- **Normals and tangents.** Smooth normals are area weighted. Tangents come from MikkTSpace, which
|
||||
glTF 2.0 recommends for meshes without tangents
|
||||
(<https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html>): `w` holds the bitangent sign.
|
||||
- **UV unwrapping.** `unwrap::auto_unwrap` makes a non-overlapping layout per material, splitting
|
||||
vertices where charts meet.
|
||||
- **UV G-buffer.** `UvGBuffer` records, for each texel of one material's UV space, the triangle
|
||||
and barycentrics under the texel center; `surface_at` turns them into a position, normal and
|
||||
tangent frame. `UvGBuffer::new` returns an error for a side of 0 or above `MAX_SIDE` (16,384),
|
||||
for more than `MAX_TEXELS` texels (8,192 × 8,192), when the triangles touch more than
|
||||
`MAX_BAND_ENTRIES` bands of 32 rows in all, and when the memory cannot be reserved.
|
||||
- **Primitives.** Sphere, rounded box, cube, cylinder, torus and plane with UVs and tangents, and
|
||||
the built-in scenes in `primitives::BUILTINS`. `primitives::cube` and `primitives::rounded_box`
|
||||
return `Result<Mesh>`. They reject non-finite or nonpositive dimensions and dimensions whose
|
||||
doubled half extents overflow. A box bevel must be finite and between zero and 95% of its
|
||||
smallest half extent; an invalid bevel returns `GeomError::Invalid`.
|
||||
- **BVH.** `Bvh` is a binned SAH tree on all three axes with a median split when no split beats a
|
||||
leaf. It answers closest-hit, any-hit and filtered ray casts, nearest-point queries and box
|
||||
queries.
|
||||
- **Camera.** `OrbitCamera` and `Ray` give an orbit view and picking rays.
|
||||
|
||||
`GeomError::Invalid` is the one error type. `rayon` parallelizes the UV G-buffer, and `serde`
|
||||
serializes `OrbitCamera`; both are always on.
|
||||
|
||||
## Origin
|
||||
|
||||
| Part | Source |
|
||||
|---|---|
|
||||
| `mesh.rs`, `bvh.rs`, `primitives.rs`, `gbuffer.rs`, `unwrap.rs`, `camera.rs` and their tests | TextureCraft `crates/geom` at [386630e](https://github.com/storytold/texturecraft/commit/386630ee85cb22679295b24013575d1aecb39ad2) |
|
||||
| `Mesh::subdivided` and `subdivision_shares_edge_midpoints` | MaterialCraft `crates/geom/src/mesh.rs` at [3133062](https://github.com/storytold/materialcraft/commit/3133062968b8a1566eda12a357cb06062db16687) |
|
||||
|
||||
MikkTSpace comes from the `mikktspace` crate; its notice is in [ATTRIBUTION.md](ATTRIBUTION.md).
|
||||
|
||||
## Migration
|
||||
|
||||
| App | Status |
|
||||
|---|---|
|
||||
| TextureCraft | `texturecraft-geom` is the source. The app switches to this crate in its own pull request. |
|
||||
| MaterialCraft | `materialcraft-geom` is the source of `subdivided`. The app switches in its own pull request. |
|
||||
@@ -0,0 +1,678 @@
|
||||
//! Bounding volume hierarchy over a mesh's triangles: closest-hit and any-hit ray casts, and
|
||||
//! box queries (used by picking, baking and brush stamps).
|
||||
|
||||
use glam::{Vec3, Vec3A};
|
||||
|
||||
use crate::Mesh;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Node {
|
||||
lo: Vec3A,
|
||||
hi: Vec3A,
|
||||
/// Leaf: first triangle in `order`; inner: index of the left child (right = left + 1).
|
||||
first: u32,
|
||||
/// Triangles in a leaf; 0 for inner nodes.
|
||||
count: u32,
|
||||
}
|
||||
|
||||
/// A ray hit: distance, triangle and barycentrics (weights of vertices 1 and 2).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Hit {
|
||||
pub t: f32,
|
||||
pub tri: u32,
|
||||
pub u: f32,
|
||||
pub v: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Bvh {
|
||||
nodes: Vec<Node>,
|
||||
/// Triangle vertices in BVH order.
|
||||
tris: Vec<[Vec3; 3]>,
|
||||
/// Original triangle index of each entry in `tris`.
|
||||
order: Vec<u32>,
|
||||
}
|
||||
|
||||
const LEAF: usize = 4;
|
||||
|
||||
/// Traversal stack of (node, entry distance): inline for typical depths (no allocation per
|
||||
/// ray), spilling to the heap for degenerate trees.
|
||||
struct Stack {
|
||||
inline: [(u32, f32); 64],
|
||||
len: usize,
|
||||
spill: Vec<(u32, f32)>,
|
||||
}
|
||||
|
||||
impl Default for Stack {
|
||||
fn default() -> Self {
|
||||
Stack { inline: [(0, 0.0); 64], len: 0, spill: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Stack {
|
||||
fn push(&mut self, v: (u32, f32)) {
|
||||
match self.inline.get_mut(self.len) {
|
||||
Some(slot) if self.spill.is_empty() => {
|
||||
*slot = v;
|
||||
self.len += 1;
|
||||
}
|
||||
_ => self.spill.push(v),
|
||||
}
|
||||
}
|
||||
|
||||
fn pop(&mut self) -> Option<(u32, f32)> {
|
||||
self.spill.pop().or_else(|| {
|
||||
self.len = self.len.checked_sub(1)?;
|
||||
self.inline.get(self.len).copied()
|
||||
})
|
||||
}
|
||||
}
|
||||
const BINS: usize = 12;
|
||||
|
||||
fn grow(lo: &mut Vec3, hi: &mut Vec3, p: Vec3) {
|
||||
*lo = lo.min(p);
|
||||
*hi = hi.max(p);
|
||||
}
|
||||
|
||||
fn area(lo: Vec3, hi: Vec3) -> f32 {
|
||||
let d = (hi - lo).max(Vec3::ZERO);
|
||||
d.x * d.y + d.y * d.z + d.z * d.x
|
||||
}
|
||||
|
||||
impl Bvh {
|
||||
pub fn new(mesh: &Mesh) -> Bvh {
|
||||
let triangle_count = mesh.triangle_count();
|
||||
let mut tris = Vec::with_capacity(triangle_count);
|
||||
|
||||
for triangle in 0..triangle_count {
|
||||
let Some([a, b, c]) = mesh.tri(triangle) else { continue };
|
||||
let position = |i: usize| mesh.positions.get(i).copied().unwrap_or(Vec3::ZERO);
|
||||
tris.push([position(a), position(b), position(c)]);
|
||||
}
|
||||
|
||||
let mut order: Vec<u32> = (0..tris.len() as u32).collect();
|
||||
let centroids: Vec<Vec3> = tris.iter().map(|t| (t[0] + t[1] + t[2]) / 3.0).collect();
|
||||
|
||||
let mut nodes = vec![Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first: 0, count: tris.len() as u32 }];
|
||||
let mut stack = vec![0usize];
|
||||
|
||||
while let Some(node_index) = stack.pop() {
|
||||
let Node { first, count, .. } = nodes[node_index];
|
||||
let (start, count) = (first as usize, count as usize);
|
||||
let (mut bounds_min, mut bounds_max) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
|
||||
let (mut centroid_min, mut centroid_max) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
|
||||
|
||||
for &triangle in &order[start..start + count] {
|
||||
for position in tris[triangle as usize] {
|
||||
grow(&mut bounds_min, &mut bounds_max, position);
|
||||
}
|
||||
grow(&mut centroid_min, &mut centroid_max, centroids[triangle as usize]);
|
||||
}
|
||||
|
||||
nodes[node_index].lo = bounds_min.into();
|
||||
nodes[node_index].hi = bounds_max.into();
|
||||
|
||||
if count <= LEAF {
|
||||
continue;
|
||||
}
|
||||
|
||||
let centroid_extent = centroid_max - centroid_min;
|
||||
let bin_of = |triangle: u32, axis: usize| {
|
||||
let offset = centroids[triangle as usize][axis] - centroid_min[axis];
|
||||
((offset / centroid_extent[axis] * BINS as f32) as usize).min(BINS - 1)
|
||||
};
|
||||
|
||||
// Reuse each triangle's bounds across all three axes
|
||||
let mut axis_bins = [[(0u32, Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)); BINS]; 3];
|
||||
|
||||
for &triangle in &order[start..start + count] {
|
||||
let [a, b, c] = tris[triangle as usize];
|
||||
let (triangle_min, triangle_max) = (a.min(b).min(c), a.max(b).max(c));
|
||||
|
||||
for axis in 0..3 {
|
||||
if centroid_extent[axis] <= 1e-12 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let bin = &mut axis_bins[axis][bin_of(triangle, axis)];
|
||||
bin.0 += 1;
|
||||
bin.1 = bin.1.min(triangle_min);
|
||||
bin.2 = bin.2.max(triangle_max);
|
||||
}
|
||||
}
|
||||
|
||||
let mut best_axis = 0;
|
||||
let mut best_split = 0;
|
||||
let mut best_cost = f32::MAX;
|
||||
|
||||
for axis in 0..3 {
|
||||
if centroid_extent[axis] <= 1e-12 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let bins = axis_bins[axis];
|
||||
|
||||
// Cache right bounds once and advance the left bounds per split
|
||||
let mut suffix = bins;
|
||||
for i in (0..BINS - 1).rev() {
|
||||
suffix[i] = (suffix[i].0 + suffix[i + 1].0, suffix[i].1.min(suffix[i + 1].1), suffix[i].2.max(suffix[i + 1].2));
|
||||
}
|
||||
|
||||
let (mut left_count, mut left_min, mut left_max) = (0u32, Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
|
||||
|
||||
for split in 1..BINS {
|
||||
let bin = bins[split - 1];
|
||||
left_count += bin.0;
|
||||
left_min = left_min.min(bin.1);
|
||||
left_max = left_max.max(bin.2);
|
||||
|
||||
let (right_count, right_min, right_max) = suffix[split];
|
||||
if left_count == 0 || right_count == 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let cost = left_count as f32 * area(left_min, left_max) + right_count as f32 * area(right_min, right_max);
|
||||
if cost < best_cost {
|
||||
best_cost = cost;
|
||||
best_axis = axis;
|
||||
best_split = split;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let node_order = &mut order[start..start + count];
|
||||
let left_count = if best_split == 0 || best_cost >= count as f32 * area(bounds_min, bounds_max) {
|
||||
// Split by count when SAH cannot help, including tied centroids
|
||||
let axis = if centroid_extent.x >= centroid_extent.y && centroid_extent.x >= centroid_extent.z {
|
||||
0
|
||||
} else if centroid_extent.y >= centroid_extent.z {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
};
|
||||
|
||||
let mid = count / 2;
|
||||
node_order.select_nth_unstable_by(mid, |&a, &b| centroids[a as usize][axis].total_cmp(¢roids[b as usize][axis]));
|
||||
mid
|
||||
} else {
|
||||
let mut left_count = 0;
|
||||
|
||||
for i in 0..node_order.len() {
|
||||
if bin_of(node_order[i], best_axis) < best_split {
|
||||
node_order.swap(left_count, i);
|
||||
left_count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
left_count
|
||||
};
|
||||
|
||||
if left_count == 0 || left_count == count {
|
||||
continue;
|
||||
}
|
||||
|
||||
let left_child = nodes.len();
|
||||
nodes.push(Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first, count: left_count as u32 });
|
||||
nodes.push(Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first: first + left_count as u32, count: (count - left_count) as u32 });
|
||||
|
||||
nodes[node_index].first = left_child as u32;
|
||||
nodes[node_index].count = 0;
|
||||
|
||||
stack.push(left_child);
|
||||
stack.push(left_child + 1);
|
||||
}
|
||||
|
||||
let tris = order.iter().map(|t| tris[*t as usize]).collect();
|
||||
Bvh { nodes, tris, order }
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.tris.is_empty()
|
||||
}
|
||||
|
||||
/// The flattened tree (for GPU traversal), root first: bounds, then for a leaf the range
|
||||
/// `first..first + count` of [`Bvh::triangles`], for an inner node (`count` 0) the children
|
||||
/// `first` and `first + 1`.
|
||||
pub fn nodes(&self) -> impl ExactSizeIterator<Item = (Vec3, Vec3, u32, u32)> + '_ {
|
||||
self.nodes.iter().map(|n| (n.lo.into(), n.hi.into(), n.first, n.count))
|
||||
}
|
||||
|
||||
/// Triangle vertices in BVH order, and the original triangle index of each.
|
||||
pub fn triangles(&self) -> (&[[Vec3; 3]], &[u32]) {
|
||||
(&self.tris, &self.order)
|
||||
}
|
||||
|
||||
fn slab(lo: Vec3A, hi: Vec3A, o: Vec3A, inv: Vec3A, tmax: f32) -> Option<f32> {
|
||||
let t0 = (lo - o) * inv;
|
||||
let t1 = (hi - o) * inv;
|
||||
// A ray lying in a slab plane gives 0·∞ = NaN: it is inside that slab, so the axis does
|
||||
// not bound the hit.
|
||||
let open = t0.is_nan_mask() | t1.is_nan_mask();
|
||||
let tn = Vec3A::select(open, Vec3A::NEG_INFINITY, t0.min(t1)).max_element().max(0.0);
|
||||
let tf = Vec3A::select(open, Vec3A::INFINITY, t0.max(t1)).min_element().min(tmax);
|
||||
(tn <= tf).then_some(tn)
|
||||
}
|
||||
|
||||
/// Möller–Trumbore, double sided.
|
||||
fn hit_tri(t: &[Vec3; 3], o: Vec3, d: Vec3) -> Option<(f32, f32, f32)> {
|
||||
let e1 = t[1] - t[0];
|
||||
let e2 = t[2] - t[0];
|
||||
let p = d.cross(e2);
|
||||
let det = e1.dot(p);
|
||||
if det.abs() < 1e-12 {
|
||||
return None;
|
||||
}
|
||||
let inv = 1.0 / det;
|
||||
let s = o - t[0];
|
||||
// A little slack on the edges: rays through a shared edge must not slip between its
|
||||
// two triangles to a surface behind.
|
||||
const EDGE: f32 = 1e-5;
|
||||
let u = s.dot(p) * inv;
|
||||
if !(-EDGE..=1.0 + EDGE).contains(&u) {
|
||||
return None;
|
||||
}
|
||||
let q = s.cross(e1);
|
||||
let v = d.dot(q) * inv;
|
||||
if v < -EDGE || u + v > 1.0 + EDGE {
|
||||
return None;
|
||||
}
|
||||
let tt = e2.dot(q) * inv;
|
||||
(tt > 0.0).then_some((tt, u, v))
|
||||
}
|
||||
|
||||
fn traverse(&self, o: Vec3, d: Vec3, mut tmax: f32, any: bool, filter: &dyn Fn(u32) -> bool) -> Option<Hit> {
|
||||
let root = self.nodes.first().filter(|_| !self.tris.is_empty())?;
|
||||
let (oa, inv) = (Vec3A::from(o), Vec3A::ONE / Vec3A::from(d));
|
||||
let mut best = None;
|
||||
let mut stack = Stack::default();
|
||||
stack.push((0, Self::slab(root.lo, root.hi, oa, inv, tmax)?));
|
||||
// Entries carry their entry distance: nodes behind a closer hit are skipped unopened.
|
||||
while let Some((ni, tn)) = stack.pop() {
|
||||
let Some(n) = self.nodes.get(ni as usize).filter(|_| tn <= tmax) else { continue };
|
||||
if n.count > 0 {
|
||||
let (f, c) = (n.first as usize, n.count as usize);
|
||||
for i in f..(f + c).min(self.tris.len()) {
|
||||
let (Some(tri), Some(&orig)) = (self.tris.get(i), self.order.get(i)) else { continue };
|
||||
if let Some((t, u, v)) = Self::hit_tri(tri, o, d)
|
||||
&& t < tmax
|
||||
&& filter(orig)
|
||||
{
|
||||
tmax = t;
|
||||
best = Some(Hit { t, tri: orig, u, v });
|
||||
if any {
|
||||
return best;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Visit the nearer child first.
|
||||
let (l, r) = (n.first, n.first + 1);
|
||||
let dl = self.nodes.get(l as usize).and_then(|c| Self::slab(c.lo, c.hi, oa, inv, tmax));
|
||||
let dr = self.nodes.get(r as usize).and_then(|c| Self::slab(c.lo, c.hi, oa, inv, tmax));
|
||||
match (dl, dr) {
|
||||
(Some(a), Some(b)) if a <= b => {
|
||||
stack.push((r, b));
|
||||
stack.push((l, a));
|
||||
}
|
||||
(Some(a), Some(b)) => {
|
||||
stack.push((l, a));
|
||||
stack.push((r, b));
|
||||
}
|
||||
(Some(a), None) => stack.push((l, a)),
|
||||
(None, Some(b)) => stack.push((r, b)),
|
||||
(None, None) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// Closest hit along `o + t·d` for `t` in (0, tmax).
|
||||
pub fn closest(&self, o: Vec3, d: Vec3, tmax: f32) -> Option<Hit> {
|
||||
self.traverse(o, d, tmax, false, &|_| true)
|
||||
}
|
||||
|
||||
/// Closest hit on triangles accepted by `filter` (original triangle index).
|
||||
pub fn closest_filtered(&self, o: Vec3, d: Vec3, tmax: f32, filter: &dyn Fn(u32) -> bool) -> Option<Hit> {
|
||||
self.traverse(o, d, tmax, false, filter)
|
||||
}
|
||||
|
||||
/// Whether anything is hit before `tmax` (occlusion rays).
|
||||
pub fn occluded(&self, o: Vec3, d: Vec3, tmax: f32) -> bool {
|
||||
self.traverse(o, d, tmax, true, &|_| true).is_some()
|
||||
}
|
||||
|
||||
/// The point nearest to `p` within `max_dist` on a triangle accepted by `filter` (original
|
||||
/// index): a [`Hit`] with the distance in `t` and the barycentrics of vertices 1 and 2.
|
||||
pub fn nearest(&self, p: Vec3, max_dist: f32, filter: &dyn Fn(u32) -> bool) -> Option<Hit> {
|
||||
let root = self.nodes.first().filter(|_| !self.tris.is_empty() && p.is_finite())?;
|
||||
let pa = Vec3A::from(p);
|
||||
let box_d2 = |n: &Node| (n.lo - pa).max(pa - n.hi).max(Vec3A::ZERO).length_squared();
|
||||
let (mut best_d2, mut best) = (max_dist * max_dist, None);
|
||||
let mut stack = Stack::default();
|
||||
stack.push((0, box_d2(root)));
|
||||
while let Some((ni, d2)) = stack.pop() {
|
||||
let Some(n) = self.nodes.get(ni as usize).filter(|_| d2 <= best_d2) else { continue };
|
||||
if n.count > 0 {
|
||||
for i in n.first as usize..(n.first as usize + n.count as usize).min(self.tris.len()) {
|
||||
let (Some(tri), Some(&orig)) = (self.tris.get(i), self.order.get(i)) else { continue };
|
||||
if !filter(orig) {
|
||||
continue;
|
||||
}
|
||||
let (q, u, v) = closest_on_triangle(p, tri);
|
||||
let dd = (q - p).length_squared();
|
||||
if dd < best_d2 {
|
||||
best_d2 = dd;
|
||||
best = Some(Hit { t: dd.sqrt(), tri: orig, u, v });
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Push the farther child first so the nearer one is searched first.
|
||||
let child = |c: u32| self.nodes.get(c as usize).map(|n| (c, box_d2(n)));
|
||||
let (Some(l), Some(r)) = (child(n.first), child(n.first + 1)) else { continue };
|
||||
let (near, far) = if l.1 <= r.1 { (l, r) } else { (r, l) };
|
||||
stack.push(far);
|
||||
stack.push(near);
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// Call `f` with every triangle (original index) whose bounds overlap the box.
|
||||
pub fn query_box(&self, lo: Vec3, hi: Vec3, mut f: impl FnMut(u32)) {
|
||||
let mut stack = vec![0u32];
|
||||
while let Some(i) = stack.pop() {
|
||||
let Some(n) = self.nodes.get(i as usize) else { continue };
|
||||
if self.tris.is_empty() || n.hi.cmplt(lo.into()).any() || n.lo.cmpgt(hi.into()).any() {
|
||||
continue;
|
||||
}
|
||||
if n.count > 0 {
|
||||
for k in n.first as usize..(n.first + n.count) as usize {
|
||||
let (Some(t), Some(o)) = (self.tris.get(k), self.order.get(k)) else { continue };
|
||||
let tlo = t[0].min(t[1]).min(t[2]);
|
||||
let thi = t[0].max(t[1]).max(t[2]);
|
||||
if !(thi.cmplt(lo).any() || tlo.cmpgt(hi).any()) {
|
||||
f(*o);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
stack.push(n.first);
|
||||
stack.push(n.first + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The point of triangle `t` nearest to `p` and its barycentrics (weights of vertices 1 and 2),
|
||||
/// by Voronoi region (Ericson, Real-Time Collision Detection, 5.1.5). Degenerate triangles give
|
||||
/// a non-finite distance and are never nearest.
|
||||
fn closest_on_triangle(p: Vec3, t: &[Vec3; 3]) -> (Vec3, f32, f32) {
|
||||
let [a, b, c] = *t;
|
||||
let (ab, ac, ap) = (b - a, c - a, p - a);
|
||||
let (d1, d2) = (ab.dot(ap), ac.dot(ap));
|
||||
if d1 <= 0.0 && d2 <= 0.0 {
|
||||
return (a, 0.0, 0.0);
|
||||
}
|
||||
let bp = p - b;
|
||||
let (d3, d4) = (ab.dot(bp), ac.dot(bp));
|
||||
if d3 >= 0.0 && d4 <= d3 {
|
||||
return (b, 1.0, 0.0);
|
||||
}
|
||||
let vc = d1 * d4 - d3 * d2;
|
||||
if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 {
|
||||
let v = d1 / (d1 - d3);
|
||||
return (a + ab * v, v, 0.0);
|
||||
}
|
||||
let cp = p - c;
|
||||
let (d5, d6) = (ab.dot(cp), ac.dot(cp));
|
||||
if d6 >= 0.0 && d5 <= d6 {
|
||||
return (c, 0.0, 1.0);
|
||||
}
|
||||
let vb = d5 * d2 - d1 * d6;
|
||||
if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 {
|
||||
let w = d2 / (d2 - d6);
|
||||
return (a + ac * w, 0.0, w);
|
||||
}
|
||||
let va = d3 * d6 - d5 * d4;
|
||||
if va <= 0.0 && d4 - d3 >= 0.0 && d5 - d6 >= 0.0 {
|
||||
let w = (d4 - d3) / ((d4 - d3) + (d5 - d6));
|
||||
return (b + (c - b) * w, 1.0 - w, w);
|
||||
}
|
||||
let denom = 1.0 / (va + vb + vc);
|
||||
let (v, w) = (vb * denom, vc * denom);
|
||||
(a + ab * v + ac * w, v, w)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::primitives;
|
||||
|
||||
#[test]
|
||||
fn nearest_point_matches_brute_force() {
|
||||
let m = primitives::builtin("torus").unwrap();
|
||||
let bvh = Bvh::new(&m);
|
||||
let mut seed = 7u32;
|
||||
let mut rnd = move || {
|
||||
seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
|
||||
(seed >> 8) as f32 / (1u32 << 24) as f32 * 4.0 - 2.0
|
||||
};
|
||||
for _ in 0..200 {
|
||||
let p = Vec3::new(rnd(), rnd(), rnd());
|
||||
let hit = bvh.nearest(p, f32::MAX, &|_| true).unwrap();
|
||||
let brute = (0..m.triangle_count())
|
||||
.map(|t| {
|
||||
let [a, b, c] = m.tri(t).unwrap().map(|i| m.positions[i]);
|
||||
(closest_on_triangle(p, &[a, b, c]).0 - p).length()
|
||||
})
|
||||
.fold(f32::MAX, f32::min);
|
||||
assert!((hit.t - brute).abs() < 1e-5, "{} vs {brute}", hit.t);
|
||||
let [a, b, c] = m.tri(hit.tri as usize).unwrap().map(|i| m.positions[i]);
|
||||
let q = a * (1.0 - hit.u - hit.v) + b * hit.u + c * hit.v;
|
||||
assert!(((q - p).length() - hit.t).abs() < 1e-4);
|
||||
}
|
||||
assert!(bvh.nearest(Vec3::splat(100.0), 1.0, &|_| true).is_none(), "out of range");
|
||||
assert!(bvh.nearest(Vec3::ZERO, f32::MAX, &|_| false).is_none(), "filtered out");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn traversal_stack_spills_in_lifo_order() {
|
||||
let mut st = Stack::default();
|
||||
for v in 0..200 {
|
||||
st.push((v, v as f32));
|
||||
}
|
||||
assert!((0..200).rev().all(|v| st.pop() == Some((v, v as f32))));
|
||||
assert_eq!(st.pop(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ray_hits_sphere_at_expected_distance() {
|
||||
let m = primitives::sphere(1.0, 64, 32);
|
||||
let bvh = Bvh::new(&m);
|
||||
let h = bvh.closest(Vec3::new(0.0, 0.0, 5.0), Vec3::NEG_Z, 100.0).unwrap();
|
||||
assert!((h.t - 4.0).abs() < 0.01, "{}", h.t);
|
||||
assert!(bvh.closest(Vec3::new(0.0, 3.0, 5.0), Vec3::NEG_Z, 100.0).is_none());
|
||||
// Rays lying exactly in a node's bounding plane (y = 0 is the equator) hit the front.
|
||||
// Axis-aligned rays lying in a node's bounding plane (y = 0) still find the front.
|
||||
for x in [-0.5f32, -0.4, 0.3] {
|
||||
let h = bvh.closest(Vec3::new(x, 0.0, 5.0), Vec3::NEG_Z, 100.0).unwrap();
|
||||
assert!(h.t < 5.0, "x {x}: hit the back at t {}", h.t);
|
||||
}
|
||||
// Rays through shared edges (the equator) hit the front, never slip through to the back.
|
||||
let m = primitives::sphere(1.0, 48, 24);
|
||||
let bvh = Bvh::new(&m);
|
||||
for i in 0..200 {
|
||||
let x = i as f32 / 100.0 - 1.0;
|
||||
let o = Vec3::new(0.0, 0.0, 5.0);
|
||||
let d = (Vec3::new(x * 0.9, 0.0, 0.0) - o).normalize();
|
||||
let h = bvh.closest(o, d, 100.0).unwrap();
|
||||
assert!(h.t < 5.0, "x {x}: hit the back at t {}", h.t);
|
||||
}
|
||||
assert!(bvh.occluded(Vec3::new(0.0, 0.0, 5.0), Vec3::NEG_Z, 10.0));
|
||||
assert!(!bvh.occluded(Vec3::new(0.0, 0.0, 5.0), Vec3::NEG_Z, 3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_brute_force() {
|
||||
let m = primitives::material_ball();
|
||||
let bvh = Bvh::new(&m);
|
||||
for i in 0..200 {
|
||||
let a = i as f32 * 0.731;
|
||||
let o = Vec3::new(a.cos() * 6.0, (i as f32 * 0.37).sin() * 3.0 + 1.0, a.sin() * 6.0);
|
||||
let d = (Vec3::new(0.0, 1.0, 0.0) + Vec3::new((a * 3.1).sin(), (a * 1.7).cos(), (a * 2.3).sin()) * 0.6 - o).normalize();
|
||||
let fast = bvh.closest(o, d, 1e9).map(|h| h.t);
|
||||
let mut slow: Option<f32> = None;
|
||||
for t in 0..m.triangle_count() {
|
||||
let [x, y, z] = m.tri(t).unwrap();
|
||||
if let Some((tt, _, _)) = Bvh::hit_tri(&[m.positions[x], m.positions[y], m.positions[z]], o, d) {
|
||||
slow = Some(slow.map_or(tt, |s: f32| s.min(tt)));
|
||||
}
|
||||
}
|
||||
match (fast, slow) {
|
||||
(Some(a), Some(b)) => assert!((a - b).abs() < 1e-4, "{a} {b}"),
|
||||
(None, None) => {}
|
||||
other => panic!("mismatch {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn box_query_finds_overlapping_triangles() {
|
||||
let m = primitives::plane(2.0, 4);
|
||||
let bvh = Bvh::new(&m);
|
||||
let mut found = Vec::new();
|
||||
bvh.query_box(Vec3::new(-0.1, -0.1, -0.1), Vec3::new(0.1, 0.1, 0.1), |t| found.push(t));
|
||||
assert!(!found.is_empty() && found.len() <= 8, "{found:?}");
|
||||
let empty = Bvh::new(&Mesh::default());
|
||||
assert!(empty.closest(Vec3::ZERO, Vec3::X, 1.0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_coplanar_plate_does_not_degrade_leaf_sizes() {
|
||||
let mut positions = Vec::new();
|
||||
let mut indices = Vec::new();
|
||||
let w = 200.0f32;
|
||||
let h = 100.0f32;
|
||||
|
||||
// Large plate at z = 0
|
||||
let b = positions.len() as u32;
|
||||
positions.extend_from_slice(&[Vec3::new(0.0, 0.0, 0.0), Vec3::new(w, 0.0, 0.0), Vec3::new(w, h, 0.0), Vec3::new(0.0, h, 0.0)]);
|
||||
indices.extend_from_slice(&[b, b + 1, b + 2, b, b + 2, b + 3]);
|
||||
|
||||
// 500 small triangles sitting at z = 0.5
|
||||
for i in 0..500 {
|
||||
let x = 20.0 + (i % 160) as f32;
|
||||
let y = 10.0 + ((i / 160) % 80) as f32;
|
||||
let idx = positions.len() as u32;
|
||||
positions.push(Vec3::new(x, y, 0.5));
|
||||
positions.push(Vec3::new(x + 0.5, y, 0.5));
|
||||
positions.push(Vec3::new(x, y + 0.5, 0.6));
|
||||
indices.extend_from_slice(&[idx, idx + 1, idx + 2]);
|
||||
}
|
||||
|
||||
let mesh = Mesh {
|
||||
positions,
|
||||
normals: Vec::new(),
|
||||
uvs: Vec::new(),
|
||||
indices,
|
||||
tangents: Vec::new(),
|
||||
colors: Vec::new(),
|
||||
submeshes: Vec::new(),
|
||||
materials: Vec::new(),
|
||||
diagonals: Vec::new(),
|
||||
};
|
||||
|
||||
let bvh = Bvh::new(&mesh);
|
||||
|
||||
for (_, _, _, count) in bvh.nodes() {
|
||||
if count > 0 {
|
||||
assert!(count <= LEAF as u32, "leaf has too many triangles: {count}");
|
||||
}
|
||||
}
|
||||
|
||||
// The foreground triangle is the closest hit
|
||||
let hit = bvh.closest(Vec3::new(20.1, 10.1, 10.0), Vec3::NEG_Z, 100.0).unwrap();
|
||||
assert!((hit.t - 9.5).abs() < 0.1, "hit t: {}", hit.t);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clustered_coplanar_fallback_partitions_nodes() {
|
||||
let mut positions = Vec::new();
|
||||
let mut indices = Vec::new();
|
||||
let w = 200.0f32;
|
||||
let h = 100.0f32;
|
||||
|
||||
let b = positions.len() as u32;
|
||||
positions.extend_from_slice(&[Vec3::new(0.0, 0.0, 0.0), Vec3::new(w, 0.0, 0.0), Vec3::new(w, h, 0.0), Vec3::new(0.0, h, 0.0)]);
|
||||
indices.extend_from_slice(&[b, b + 1, b + 2, b, b + 2, b + 3]);
|
||||
|
||||
// Shared bins keep every SAH split as costly as an unsplit leaf
|
||||
for i in 0..500 {
|
||||
let x = 130.0 + (i % 10) as f32 * 0.1;
|
||||
let y = 64.0 + (i / 10) as f32 * 0.02;
|
||||
let idx = positions.len() as u32;
|
||||
positions.push(Vec3::new(x, y, 0.0));
|
||||
positions.push(Vec3::new(x + 0.01, y, 0.0));
|
||||
positions.push(Vec3::new(x, y + 0.01, 0.0));
|
||||
indices.extend_from_slice(&[idx, idx + 1, idx + 2]);
|
||||
}
|
||||
|
||||
let mesh = Mesh {
|
||||
positions,
|
||||
normals: Vec::new(),
|
||||
uvs: Vec::new(),
|
||||
indices,
|
||||
tangents: Vec::new(),
|
||||
colors: Vec::new(),
|
||||
submeshes: Vec::new(),
|
||||
materials: Vec::new(),
|
||||
diagonals: Vec::new(),
|
||||
};
|
||||
|
||||
let bvh = Bvh::new(&mesh);
|
||||
|
||||
for (_, _, _, count) in bvh.nodes() {
|
||||
if count > 0 {
|
||||
assert!(count <= LEAF as u32, "leaf has too many triangles: {count}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coincident_centroids_still_partition_large_and_small_triangles() {
|
||||
let mut mesh = Mesh::default();
|
||||
|
||||
// Different triangle sizes share an exact centroid
|
||||
for i in 0..=500 {
|
||||
let size = if i == 0 { 100.0 } else { 0.01 + i as f32 * 0.0001 };
|
||||
let first = mesh.positions.len() as u32;
|
||||
mesh.positions.extend([Vec3::new(-size, -size, 0.0), Vec3::new(size, -size, 0.0), Vec3::new(0.0, 2.0 * size, 0.0)]);
|
||||
mesh.indices.extend([first, first + 1, first + 2]);
|
||||
}
|
||||
|
||||
mesh.normals.resize(mesh.positions.len(), Vec3::Z);
|
||||
mesh.uvs.resize(mesh.positions.len(), glam::Vec2::ZERO);
|
||||
mesh.tangents.resize(mesh.positions.len(), glam::Vec4::new(1.0, 0.0, 0.0, 1.0));
|
||||
mesh.validate().unwrap();
|
||||
|
||||
let bvh = Bvh::new(&mesh);
|
||||
|
||||
for (_, _, _, count) in bvh.nodes() {
|
||||
assert!(count <= LEAF as u32, "leaf has too many triangles: {count}");
|
||||
}
|
||||
|
||||
// The outer ray only hits the large triangle
|
||||
let origin = Vec3::new(50.0, 0.0, 10.0);
|
||||
let hit = bvh.closest(origin, Vec3::NEG_Z, 100.0).unwrap();
|
||||
assert_eq!(hit.tri, 0);
|
||||
assert_eq!(hit.t, 10.0);
|
||||
|
||||
assert!(bvh.occluded(origin, Vec3::NEG_Z, 100.0));
|
||||
assert!(!bvh.occluded(origin, Vec3::NEG_Z, 5.0));
|
||||
|
||||
// Median partitions preserve original triangle IDs
|
||||
let hit = bvh.closest_filtered(Vec3::new(0.0, 0.0, 10.0), Vec3::NEG_Z, 100.0, &|t| t == 500).unwrap();
|
||||
assert_eq!(hit.tri, 500);
|
||||
assert_eq!(hit.t, 10.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
//! Orbit camera (texture painting navigation) and picking rays.
|
||||
|
||||
use glam::{Mat4, Vec2, Vec3, Vec4};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct OrbitCamera {
|
||||
pub target: Vec3,
|
||||
/// Radians around Y.
|
||||
pub yaw: f32,
|
||||
/// Radians above the horizon, clamped to ±89°.
|
||||
pub pitch: f32,
|
||||
pub distance: f32,
|
||||
/// Vertical field of view, degrees.
|
||||
pub fov: f32,
|
||||
/// Scene radius (sets the clip planes).
|
||||
pub scene_radius: f32,
|
||||
/// Orthographic projection instead of perspective.
|
||||
#[serde(default)]
|
||||
pub ortho: bool,
|
||||
}
|
||||
|
||||
impl Default for OrbitCamera {
|
||||
fn default() -> Self {
|
||||
OrbitCamera { target: Vec3::ZERO, yaw: 0.0, pitch: 0.12, distance: 5.0, fov: 40.0, scene_radius: 1.0, ortho: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// A ray in world space.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Ray {
|
||||
pub origin: Vec3,
|
||||
pub dir: Vec3,
|
||||
}
|
||||
|
||||
impl OrbitCamera {
|
||||
pub fn eye(&self) -> Vec3 {
|
||||
let (sy, cy) = self.yaw.sin_cos();
|
||||
let (sp, cp) = self.pitch.sin_cos();
|
||||
self.target + Vec3::new(cp * sy, sp, cp * cy) * self.distance
|
||||
}
|
||||
|
||||
pub fn forward(&self) -> Vec3 {
|
||||
(self.target - self.eye()).try_normalize().unwrap_or(Vec3::NEG_Z)
|
||||
}
|
||||
|
||||
pub fn view(&self) -> Mat4 {
|
||||
Mat4::look_at_rh(self.eye(), self.target, Vec3::Y)
|
||||
}
|
||||
|
||||
pub fn proj(&self, aspect: f32) -> Mat4 {
|
||||
let r = self.scene_radius.max(1e-3);
|
||||
let near = (self.distance - r * 4.0).max(r * 0.01).max(1e-4);
|
||||
let far = self.distance + r * 50.0;
|
||||
let aspect = if aspect.is_finite() && aspect > 1e-4 { aspect } else { 1.0 };
|
||||
if self.ortho {
|
||||
let h = self.distance * (self.fov.to_radians() * 0.5).tan();
|
||||
Mat4::orthographic_rh(-h * aspect, h * aspect, -h, h, near.min(0.01), far)
|
||||
} else {
|
||||
Mat4::perspective_rh(self.fov.clamp(5.0, 150.0).to_radians(), aspect, near, far)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn view_proj(&self, aspect: f32) -> Mat4 {
|
||||
self.proj(aspect) * self.view()
|
||||
}
|
||||
|
||||
/// Frame a bounding box, keeping the current angles.
|
||||
pub fn frame(&mut self, lo: Vec3, hi: Vec3) {
|
||||
self.target = (lo + hi) * 0.5;
|
||||
let r = ((hi - lo).length() * 0.5).max(1e-3);
|
||||
self.scene_radius = r;
|
||||
self.distance = r / (self.fov.clamp(5.0, 150.0).to_radians() * 0.5).sin() * 1.1;
|
||||
}
|
||||
|
||||
pub fn orbit(&mut self, dx: f32, dy: f32) {
|
||||
self.yaw -= dx;
|
||||
self.pitch = (self.pitch + dy).clamp(-89f32.to_radians(), 89f32.to_radians());
|
||||
}
|
||||
|
||||
/// Pan by a screen fraction (dx, dy in viewport heights).
|
||||
pub fn pan(&mut self, dx: f32, dy: f32) {
|
||||
let f = self.forward();
|
||||
let right = f.cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X);
|
||||
let up = right.cross(f);
|
||||
let scale = self.distance * (self.fov.to_radians() * 0.5).tan() * 2.0;
|
||||
self.target += (-right * dx + up * dy) * scale;
|
||||
}
|
||||
|
||||
/// Dolly by a factor exponent (positive zooms in).
|
||||
pub fn zoom(&mut self, amount: f32) {
|
||||
let r = self.scene_radius.max(1e-3);
|
||||
self.distance = (self.distance * (-amount).exp()).clamp(r * 0.05, r * 200.0);
|
||||
}
|
||||
|
||||
/// Ray through a viewport point given in normalized device coordinates (-1..1, y up).
|
||||
pub fn ray(&self, ndc: Vec2, aspect: f32) -> Ray {
|
||||
let inv = self.view_proj(aspect).inverse();
|
||||
let a = inv * Vec4::new(ndc.x, ndc.y, 0.0, 1.0);
|
||||
let b = inv * Vec4::new(ndc.x, ndc.y, 1.0, 1.0);
|
||||
let (a, b) = (a.truncate() / a.w, b.truncate() / b.w);
|
||||
Ray { origin: a, dir: (b - a).try_normalize().unwrap_or(self.forward()) }
|
||||
}
|
||||
|
||||
/// Project a world point to NDC (x, y in -1..1, y up; z depth). None behind the camera.
|
||||
pub fn project(&self, p: Vec3, aspect: f32) -> Option<Vec3> {
|
||||
let c = self.view_proj(aspect) * p.extend(1.0);
|
||||
(c.w > 1e-6).then(|| c.truncate() / c.w)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn center_ray_points_at_target_and_projection_inverts() {
|
||||
let mut c = OrbitCamera::default();
|
||||
c.frame(Vec3::splat(-1.0), Vec3::splat(1.0));
|
||||
let r = c.ray(Vec2::ZERO, 1.5);
|
||||
assert!((r.dir - c.forward()).length() < 1e-4);
|
||||
let p = Vec3::new(0.3, -0.2, 0.1);
|
||||
let ndc = c.project(p, 1.5).unwrap();
|
||||
let r = c.ray(ndc.truncate(), 1.5);
|
||||
let to_p = (p - r.origin).normalize();
|
||||
assert!(to_p.dot(r.dir) > 0.9999);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pitch_is_clamped_and_zoom_bounded() {
|
||||
let mut c = OrbitCamera::default();
|
||||
c.orbit(0.0, 10.0);
|
||||
assert!(c.pitch <= 89f32.to_radians() + 1e-6);
|
||||
for _ in 0..1000 {
|
||||
c.zoom(1.0);
|
||||
}
|
||||
assert!(c.distance > 0.0 && c.distance.is_finite());
|
||||
let _ = c.proj(f32::NAN);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
//! The UV-space G-buffer: which triangle (and where on it) each texel of a texture set maps
|
||||
//! to. Painting, compositing, baking and padding all work from this one buffer, so they agree
|
||||
//! on which texel is which surface point.
|
||||
|
||||
use glam::{Vec2, Vec3, Vec4};
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::{GeomError, Mesh, Result};
|
||||
|
||||
/// Texel not covered by any triangle.
|
||||
pub const NO_TRI: u32 = u32::MAX;
|
||||
|
||||
const BAND: u32 = 32;
|
||||
|
||||
/// Largest width or height of a G-buffer, in texels.
|
||||
pub const MAX_SIDE: u32 = 16_384;
|
||||
|
||||
/// Largest texel count of a G-buffer (8,192 × 8,192). Each texel takes 12 bytes, so a full
|
||||
/// buffer takes 768 MiB and its largest vector (`bary`) 512 MiB, which fits a 32-bit address
|
||||
/// space.
|
||||
pub const MAX_TEXELS: usize = 1 << 26;
|
||||
|
||||
/// Largest number of (triangle, band of 32 rows) pairs a G-buffer bins before rasterizing: a
|
||||
/// triangle counts once for every band it touches. The bins take 4 bytes per entry, 512 MiB at
|
||||
/// most.
|
||||
pub const MAX_BAND_ENTRIES: usize = 1 << 27;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct UvGBuffer {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// Triangle under each texel center, [`NO_TRI`] when uncovered.
|
||||
pub tri: Vec<u32>,
|
||||
/// Barycentric weights of the triangle's second and third vertices.
|
||||
pub bary: Vec<[f32; 2]>,
|
||||
/// Texels written by more than one triangle (overlapping UVs).
|
||||
pub overlaps: u32,
|
||||
}
|
||||
|
||||
/// Interpolated surface attributes at a texel.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Surface {
|
||||
pub pos: Vec3,
|
||||
/// Interpolated shading normal (normalized).
|
||||
pub nrm: Vec3,
|
||||
/// Flat triangle normal (for ray offsets).
|
||||
pub geo_nrm: Vec3,
|
||||
pub tangent: Vec4,
|
||||
pub uv: Vec2,
|
||||
pub tri: u32,
|
||||
}
|
||||
|
||||
/// Checks a requested G-buffer size against [`MAX_SIDE`] and [`MAX_TEXELS`] and returns its
|
||||
/// texel count.
|
||||
fn checked_texels(width: u32, height: u32) -> Result<usize> {
|
||||
for (name, side) in [("width", width), ("height", height)] {
|
||||
if side == 0 || side > MAX_SIDE {
|
||||
return Err(GeomError::Invalid(format!("G-buffer {name} {side} is outside 1..={MAX_SIDE}")));
|
||||
}
|
||||
}
|
||||
// Both sides are at most MAX_SIDE, so the product fits in usize on 32-bit targets too.
|
||||
let n = width as usize * height as usize;
|
||||
if n > MAX_TEXELS {
|
||||
return Err(GeomError::Invalid(format!("G-buffer {width}×{height} has more than {MAX_TEXELS} texels")));
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// A vector of `n` copies of `value`, or an error when the memory cannot be reserved.
|
||||
fn filled<T: Clone>(n: usize, value: T) -> Result<Vec<T>> {
|
||||
let mut v = Vec::new();
|
||||
v.try_reserve_exact(n).map_err(|e| GeomError::Invalid(format!("G-buffer of {n} texels: {e}")))?;
|
||||
v.resize(n, value);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn edge(a: Vec2, b: Vec2, p: Vec2) -> f32 {
|
||||
(b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x)
|
||||
}
|
||||
|
||||
impl UvGBuffer {
|
||||
/// Rasterize the triangles of material `material` at `width × height`.
|
||||
///
|
||||
/// Returns an error when `width` or `height` is 0 or above [`MAX_SIDE`], when
|
||||
/// `width × height` is above [`MAX_TEXELS`], when the triangles touch more than
|
||||
/// [`MAX_BAND_ENTRIES`] bands of 32 rows in all, or when the memory cannot be reserved.
|
||||
pub fn new(mesh: &Mesh, material: usize, width: u32, height: u32) -> Result<UvGBuffer> {
|
||||
let n = checked_texels(width, height)?;
|
||||
let (w, h) = (width, height);
|
||||
let size = Vec2::new(w as f32, h as f32);
|
||||
let bands = h.div_ceil(BAND) as usize;
|
||||
let span = |t: usize| -> Option<(usize, usize)> {
|
||||
let [a, b, c] = mesh.tri(t)?;
|
||||
let (ua, ub, uc) = (mesh.uvs.get(a)?, mesh.uvs.get(b)?, mesh.uvs.get(c)?);
|
||||
let y0 = (ua.y.min(ub.y).min(uc.y) * size.y).floor().max(0.0) as i64;
|
||||
let y1 = (ua.y.max(ub.y).max(uc.y) * size.y).ceil().min(size.y) as i64;
|
||||
if y1 <= y0 || !ua.is_finite() || !ub.is_finite() || !uc.is_finite() {
|
||||
return None;
|
||||
}
|
||||
Some(((y0 / BAND as i64) as usize, ((y1 - 1).max(0) / BAND as i64) as usize))
|
||||
};
|
||||
// The triangles of each band, in mesh order, as one list: band `i` holds
|
||||
// `bins[start[i]..start[i + 1]]`. A counting pass sizes the list before it is reserved.
|
||||
let mut start = vec![0usize; bands + 1];
|
||||
for t in mesh.triangles_of(material) {
|
||||
let Some((b0, b1)) = span(t) else { continue };
|
||||
for s in start.iter_mut().skip(b0 + 1).take(b1 + 1 - b0) {
|
||||
*s += 1;
|
||||
}
|
||||
}
|
||||
for i in 1..start.len() {
|
||||
start[i] = start[i].saturating_add(start[i - 1]);
|
||||
}
|
||||
let entries = start.last().copied().unwrap_or(0);
|
||||
if entries > MAX_BAND_ENTRIES {
|
||||
return Err(GeomError::Invalid(format!("G-buffer triangles touch {entries} bands in all, more than {MAX_BAND_ENTRIES}")));
|
||||
}
|
||||
let mut bins = filled(entries, 0u32)?;
|
||||
let mut next = start.clone();
|
||||
for t in mesh.triangles_of(material) {
|
||||
let Some((b0, b1)) = span(t) else { continue };
|
||||
for k in next.iter_mut().take(b1 + 1).skip(b0) {
|
||||
if let Some(slot) = bins.get_mut(*k) {
|
||||
*slot = t as u32;
|
||||
}
|
||||
*k += 1;
|
||||
}
|
||||
}
|
||||
let mut tri = filled(n, NO_TRI)?;
|
||||
let mut bary = filled(n, [0.0f32; 2])?;
|
||||
let band_len = BAND as usize * w as usize;
|
||||
let overlaps: u32 = tri
|
||||
.par_chunks_mut(band_len)
|
||||
.zip(bary.par_chunks_mut(band_len))
|
||||
.enumerate()
|
||||
.map(|(bi, (tri, bary))| {
|
||||
let mut overlaps = 0u32;
|
||||
let row0 = bi as u32 * BAND;
|
||||
let rows = (tri.len() as u32) / w;
|
||||
let band = match (start.get(bi), start.get(bi + 1)) {
|
||||
(Some(&s), Some(&e)) => bins.get(s..e).unwrap_or(&[]),
|
||||
_ => &[],
|
||||
};
|
||||
for &t in band {
|
||||
let Some([a, b, c]) = mesh.tri(t as usize) else { continue };
|
||||
let (Some(&ua), Some(&ub), Some(&uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue };
|
||||
let (pa, pb, pc) = (ua * size, ub * size, uc * size);
|
||||
let area = edge(pa, pb, pc);
|
||||
if area.abs() < 1e-12 {
|
||||
continue;
|
||||
}
|
||||
let eps = -1e-6 * area.abs();
|
||||
let x0 = pa.x.min(pb.x).min(pc.x).floor().max(0.0) as u32;
|
||||
let x1 = (pa.x.max(pb.x).max(pc.x).ceil().min(w as f32) as u32).min(w);
|
||||
let y0 = (pa.y.min(pb.y).min(pc.y).floor().max(row0 as f32) as u32).max(row0);
|
||||
let y1 = (pa.y.max(pb.y).max(pc.y).ceil() as u32).min(row0 + rows);
|
||||
for y in y0..y1 {
|
||||
for x in x0..x1 {
|
||||
let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5);
|
||||
let (w0, w1, w2) = (edge(pb, pc, p) * area.signum(), edge(pc, pa, p) * area.signum(), edge(pa, pb, p) * area.signum());
|
||||
if w0 < eps || w1 < eps || w2 < eps {
|
||||
continue;
|
||||
}
|
||||
let i = (y - row0) as usize * w as usize + x as usize;
|
||||
if let (Some(slot), Some(bw)) = (tri.get_mut(i), bary.get_mut(i)) {
|
||||
if *slot != NO_TRI {
|
||||
overlaps += 1;
|
||||
}
|
||||
*slot = t;
|
||||
let inv = 1.0 / area.abs();
|
||||
*bw = [w1 * inv, w2 * inv];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
overlaps
|
||||
})
|
||||
.sum();
|
||||
Ok(UvGBuffer { width: w, height: h, tri, bary, overlaps })
|
||||
}
|
||||
|
||||
pub fn covered(&self, i: usize) -> bool {
|
||||
self.tri.get(i).is_some_and(|t| *t != NO_TRI)
|
||||
}
|
||||
|
||||
pub fn coverage_mask(&self) -> Vec<bool> {
|
||||
self.tri.iter().map(|t| *t != NO_TRI).collect()
|
||||
}
|
||||
|
||||
pub fn covered_count(&self) -> usize {
|
||||
self.tri.iter().filter(|t| **t != NO_TRI).count()
|
||||
}
|
||||
|
||||
/// Surface attributes at texel index `i` (None when uncovered).
|
||||
pub fn surface(&self, mesh: &Mesh, i: usize) -> Option<Surface> {
|
||||
let t = *self.tri.get(i)?;
|
||||
if t == NO_TRI {
|
||||
return None;
|
||||
}
|
||||
let [b1, b2] = *self.bary.get(i)?;
|
||||
surface_at(mesh, t, b1, b2)
|
||||
}
|
||||
}
|
||||
|
||||
/// Interpolate triangle `t` at barycentrics (weights of vertices 1 and 2).
|
||||
pub fn surface_at(mesh: &Mesh, t: u32, b1: f32, b2: f32) -> Option<Surface> {
|
||||
let [a, b, c] = mesh.tri(t as usize)?;
|
||||
let b0 = 1.0 - b1 - b2;
|
||||
let p = |v: &[Vec3]| -> Option<Vec3> { Some(*v.get(a)? * b0 + *v.get(b)? * b1 + *v.get(c)? * b2) };
|
||||
let pos = p(&mesh.positions)?;
|
||||
let nrm = p(&mesh.normals)?.try_normalize().unwrap_or(Vec3::Y);
|
||||
let (pa, pb, pc) = (*mesh.positions.get(a)?, *mesh.positions.get(b)?, *mesh.positions.get(c)?);
|
||||
let geo_nrm = (pb - pa).cross(pc - pa).try_normalize().unwrap_or(nrm);
|
||||
let tan = *mesh.tangents.get(a)? * b0 + *mesh.tangents.get(b)? * b1 + *mesh.tangents.get(c)? * b2;
|
||||
let uv = *mesh.uvs.get(a)? * b0 + *mesh.uvs.get(b)? * b1 + *mesh.uvs.get(c)? * b2;
|
||||
let tdir = tan.truncate().try_normalize().unwrap_or_else(|| nrm.any_orthonormal_vector());
|
||||
let w = mesh.tangents.get(a).map(|t| if t.w < 0.0 { -1.0 } else { 1.0 }).unwrap_or(1.0);
|
||||
Some(Surface { pos, nrm, geo_nrm, tangent: tdir.extend(w), uv, tri: t })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::primitives;
|
||||
|
||||
#[test]
|
||||
fn half_triangle_covers_texels_with_centers_inside() {
|
||||
// One triangle covering the lower-left half of UV space (v down: y = v·H).
|
||||
let m = Mesh::from_parts(
|
||||
vec![Vec3::ZERO, Vec3::X, Vec3::Y],
|
||||
None,
|
||||
vec![Vec2::new(0.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0)],
|
||||
vec![0, 1, 2],
|
||||
"m",
|
||||
)
|
||||
.unwrap();
|
||||
let g = UvGBuffer::new(&m, 0, 8, 8).unwrap();
|
||||
for y in 0..8u32 {
|
||||
for x in 0..8u32 {
|
||||
let inside = (x as f32 + 0.5) <= (y as f32 + 0.5);
|
||||
assert_eq!(g.covered((y * 8 + x) as usize), inside, "({x},{y})");
|
||||
}
|
||||
}
|
||||
assert_eq!(g.overlaps, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_and_degenerate_triangles() {
|
||||
let uv = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(0.5, 0.5)];
|
||||
let m = Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z], None, uv, vec![0, 1, 2, 0, 1, 2, 0, 3, 3], "m").unwrap();
|
||||
let g = UvGBuffer::new(&m, 0, 16, 16).unwrap();
|
||||
assert!(g.overlaps > 0);
|
||||
assert!(g.covered_count() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sizes_outside_the_limits_are_rejected() {
|
||||
// 2^27 + 1 texels wide: 32 rows of it overflow u32.
|
||||
assert!(checked_texels((1 << 27) + 1, 1).is_err());
|
||||
assert!(checked_texels(u32::MAX, u32::MAX).is_err());
|
||||
assert!(checked_texels(0, 8).is_err());
|
||||
assert!(checked_texels(8, 0).is_err());
|
||||
assert!(checked_texels(MAX_SIDE + 1, 1).is_err());
|
||||
assert!(checked_texels(1, MAX_SIDE + 1).is_err());
|
||||
// Both sides in range, but more than MAX_TEXELS texels.
|
||||
assert!(checked_texels(MAX_SIDE, MAX_SIDE).is_err());
|
||||
assert!(checked_texels(MAX_SIDE, 4_097).is_err());
|
||||
assert_eq!(checked_texels(MAX_SIDE, 4_096), Ok(MAX_TEXELS));
|
||||
assert_eq!(checked_texels(MAX_SIDE, 1), Ok(MAX_SIDE as usize));
|
||||
|
||||
let m = primitives::sphere(1.0, 8, 4);
|
||||
assert!(UvGBuffer::new(&m, 0, MAX_SIDE + 1, 1).is_err());
|
||||
assert!(UvGBuffer::new(&m, 0, 0, 1).is_err());
|
||||
let g = UvGBuffer::new(&m, 0, 64, 32).unwrap();
|
||||
assert_eq!((g.width, g.height, g.tri.len(), g.bary.len()), (64, 32, 2_048, 2_048));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_band_entries_are_rejected() {
|
||||
// 2^27 / 512 + 1 triangles, each spanning all 512 bands of a 1 × 16,384 buffer.
|
||||
let tall = (MAX_BAND_ENTRIES / 512 + 1) as u32;
|
||||
let mut m = Mesh {
|
||||
positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y],
|
||||
uvs: vec![Vec2::ZERO, Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0)],
|
||||
..Mesh::default()
|
||||
};
|
||||
m.indices = (0..tall).flat_map(|_| [0, 1, 2]).collect();
|
||||
m.submeshes = vec![crate::SubMesh { name: "m".into(), material: 0, start: 0, count: tall * 3 }];
|
||||
assert!(UvGBuffer::new(&m, 0, 1, MAX_SIDE).is_err());
|
||||
m.indices.truncate(3);
|
||||
m.submeshes[0].count = 3;
|
||||
let g = UvGBuffer::new(&m, 0, 1, MAX_SIDE).unwrap();
|
||||
// The texel centers at u = 0.5 lie inside the triangle down to v = 0.5.
|
||||
assert_eq!(g.covered_count(), MAX_SIDE as usize / 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sphere_surface_lies_on_the_sphere() {
|
||||
let m = primitives::sphere(2.0, 64, 32);
|
||||
let g = UvGBuffer::new(&m, 0, 128, 128).unwrap();
|
||||
assert!(g.covered_count() > 128 * 128 * 9 / 10, "{}", g.covered_count());
|
||||
for i in (0..g.tri.len()).step_by(97) {
|
||||
if let Some(s) = g.surface(&m, i) {
|
||||
assert!((s.pos.length() - 2.0).abs() < 0.02);
|
||||
assert!(s.nrm.dot(s.pos.normalize()) > 0.99);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
//! # craft-mesh-ops
|
||||
//!
|
||||
//! Triangle mesh operations: the [`Mesh`] type with normals and MikkTSpace tangents, built-in
|
||||
//! [`primitives`] (material ball, sphere, cube, …), a [`Bvh`] for ray casts and box queries,
|
||||
//! the UV-space [`UvGBuffer`] that maps texels to surface points, and the [`OrbitCamera`].
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod bvh;
|
||||
pub mod camera;
|
||||
pub mod gbuffer;
|
||||
pub mod mesh;
|
||||
pub mod primitives;
|
||||
pub mod unwrap;
|
||||
|
||||
pub use bvh::{Bvh, Hit};
|
||||
pub use camera::{OrbitCamera, Ray};
|
||||
pub use gbuffer::{MAX_BAND_ENTRIES, MAX_SIDE, MAX_TEXELS, NO_TRI, Surface, UvGBuffer, surface_at};
|
||||
pub use glam;
|
||||
pub use mesh::{BaseColor, MAX_TRIANGLES, Mesh, SubMesh};
|
||||
|
||||
#[derive(Debug, thiserror::Error, Clone, PartialEq)]
|
||||
pub enum GeomError {
|
||||
#[error("invalid mesh: {0}")]
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, GeomError>;
|
||||
@@ -0,0 +1,647 @@
|
||||
//! The internal triangle mesh.
|
||||
|
||||
use glam::{Vec2, Vec3, Vec4};
|
||||
|
||||
use crate::{GeomError, Result};
|
||||
|
||||
/// An edge by the bits of its two end positions, the lower one first
|
||||
type EdgePositions = ([u32; 3], [u32; 3]);
|
||||
|
||||
/// A contiguous index range drawn with one material.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SubMesh {
|
||||
pub name: String,
|
||||
pub material: usize,
|
||||
/// First index (into [`Mesh::indices`]) and index count.
|
||||
pub start: u32,
|
||||
pub count: u32,
|
||||
}
|
||||
|
||||
/// A material's base color (what a color-map bake transfers): `factor` (linear RGBA) times an
|
||||
/// optional texture sampled at the mesh UVs.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct BaseColor {
|
||||
pub factor: Vec4,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// `width × height` RGBA8 texels (color sRGB-encoded, alpha linear), rows top → bottom like
|
||||
/// the UVs' v; empty without a texture.
|
||||
pub texels: Vec<[u8; 4]>,
|
||||
}
|
||||
|
||||
/// Triangle mesh in world space. UVs use the glTF convention (origin top-left, v down).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Mesh {
|
||||
pub positions: Vec<Vec3>,
|
||||
pub normals: Vec<Vec3>,
|
||||
/// xyz tangent, w bitangent sign.
|
||||
pub tangents: Vec<Vec4>,
|
||||
pub uvs: Vec<Vec2>,
|
||||
/// RGBA vertex colors in 0..1 (glTF: linear; OBJ, PLY: as stored): one per vertex, or empty.
|
||||
pub colors: Vec<Vec4>,
|
||||
pub indices: Vec<u32>,
|
||||
/// Index ranges per material and part (node / object); `name` is the part name.
|
||||
pub submeshes: Vec<SubMesh>,
|
||||
pub materials: Vec<String>,
|
||||
/// Per triangle, bit `i` set when edge `i` (corner `i` to corner `i + 1`) is a diagonal the
|
||||
/// importer added to split a polygon, which wireframes leave out. Empty: every edge is real.
|
||||
pub diagonals: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Hard cap on mesh size accepted from files (triangles).
|
||||
pub const MAX_TRIANGLES: usize = 20_000_000;
|
||||
|
||||
impl Mesh {
|
||||
pub fn triangle_count(&self) -> usize {
|
||||
self.indices.len() / 3
|
||||
}
|
||||
|
||||
pub fn vertex_count(&self) -> usize {
|
||||
self.positions.len()
|
||||
}
|
||||
|
||||
/// Axis-aligned bounds (zero box for an empty mesh).
|
||||
pub fn bounds(&self) -> (Vec3, Vec3) {
|
||||
if self.positions.is_empty() {
|
||||
return (Vec3::ZERO, Vec3::ZERO);
|
||||
}
|
||||
self.positions.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p)))
|
||||
}
|
||||
|
||||
/// Bounding-sphere radius around the bounds center (at least a small epsilon).
|
||||
pub fn radius(&self) -> f32 {
|
||||
let (lo, hi) = self.bounds();
|
||||
((hi - lo).length() * 0.5).max(1e-4)
|
||||
}
|
||||
|
||||
/// Vertex indices of triangle `t`.
|
||||
pub fn tri(&self, t: usize) -> Option<[usize; 3]> {
|
||||
let i = self.indices.get(t * 3..t * 3 + 3)?;
|
||||
Some([i[0] as usize, i[1] as usize, i[2] as usize])
|
||||
}
|
||||
|
||||
/// The edges wireframes draw: each vertex pair once (smaller index first), leaving out
|
||||
/// polygon diagonals ([`Mesh::diagonals`]) unless only one triangle has the edge (a UV seam
|
||||
/// split it from its twin), per material in `0..materials.len().max(1)`.
|
||||
pub fn wire_edges(&self) -> Vec<Vec<(u32, u32)>> {
|
||||
(0..self.materials.len().max(1))
|
||||
.map(|m| {
|
||||
// Edge → (real in some triangle, triangles using it), in first-seen order.
|
||||
let mut edges: Vec<((u32, u32), bool, u8)> = Vec::new();
|
||||
let mut at: std::collections::HashMap<(u32, u32), usize> = std::collections::HashMap::new();
|
||||
for t in self.triangles_of(m) {
|
||||
let Some(v) = self.indices.get(t * 3..t * 3 + 3) else { continue };
|
||||
let hidden = self.diagonals.get(t).copied().unwrap_or(0);
|
||||
for (i, (a, b)) in [(v[0], v[1]), (v[1], v[2]), (v[2], v[0])].into_iter().enumerate() {
|
||||
let key = (a.min(b), a.max(b));
|
||||
let real = hidden >> i & 1 == 0;
|
||||
let e = *at.entry(key).or_insert_with(|| {
|
||||
edges.push((key, false, 0));
|
||||
edges.len() - 1
|
||||
});
|
||||
if let Some((_, r, n)) = edges.get_mut(e) {
|
||||
*r |= real;
|
||||
*n = n.saturating_add(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
edges.into_iter().filter(|(_, real, n)| *real || *n == 1).map(|(k, ..)| k).collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)`
|
||||
pub fn uv_seam_edges(&self) -> Vec<Vec<(u32, u32)>> {
|
||||
// Signed zero denotes the same position on either side of an imported seam
|
||||
let bits = |position: Vec3| position.to_array().map(|coordinate| if coordinate == 0.0 { 0 } else { coordinate.to_bits() });
|
||||
let mut seams = vec![Vec::new(); self.materials.len().max(1)];
|
||||
// Match across materials before grouping the lines for texture-set visibility
|
||||
let mut sides: std::collections::HashMap<EdgePositions, Vec<(u32, u32, usize)>> = std::collections::HashMap::new();
|
||||
for material in 0..seams.len() {
|
||||
for triangle in self.triangles_of(material) {
|
||||
let Some(corners) = self.indices.get(triangle * 3..triangle * 3 + 3) else { continue };
|
||||
|
||||
for (from, to) in [(corners[0], corners[1]), (corners[1], corners[2]), (corners[2], corners[0])] {
|
||||
let (Some(from_position), Some(to_position)) = (self.positions.get(from as usize), self.positions.get(to as usize)) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let (from_bits, to_bits) = (bits(*from_position), bits(*to_position));
|
||||
let (edge, pair) = if from_bits <= to_bits { ((from_bits, to_bits), (from, to)) } else { ((to_bits, from_bits), (to, from)) };
|
||||
sides.entry(edge).or_default().push((pair.0, pair.1, material));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let uv = |index: u32| self.uvs.get(index as usize).copied();
|
||||
for pairs in sides.into_values() {
|
||||
let Some(&(first_from, first_to, _)) = pairs.first() else { continue };
|
||||
|
||||
if pairs.iter().any(|&(from, to, _)| (uv(from), uv(to)) != (uv(first_from), uv(first_to))) {
|
||||
for (from, to, material) in pairs {
|
||||
if let Some(edges) = seams.get_mut(material) {
|
||||
edges.push((from.min(to), from.max(to)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for edges in &mut seams {
|
||||
edges.sort_unstable();
|
||||
edges.dedup();
|
||||
}
|
||||
|
||||
seams
|
||||
}
|
||||
|
||||
/// Material of triangle `t`.
|
||||
pub fn material_of(&self, t: usize) -> Option<usize> {
|
||||
let idx = (t * 3) as u32;
|
||||
self.submeshes.iter().find(|s| idx >= s.start && idx < s.start.saturating_add(s.count)).map(|s| s.material)
|
||||
}
|
||||
|
||||
/// Triangle index range belonging to material `m` (all submeshes of that material).
|
||||
pub fn triangles_of(&self, m: usize) -> impl Iterator<Item = usize> + '_ {
|
||||
self.submeshes.iter().filter(move |s| s.material == m).flat_map(|s| (s.start / 3) as usize..((s.start + s.count) / 3) as usize)
|
||||
}
|
||||
|
||||
/// Check that attribute arrays agree and every index is in range.
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
let n = self.positions.len();
|
||||
if self.normals.len() != n || self.uvs.len() != n || self.tangents.len() != n {
|
||||
return Err(GeomError::Invalid(format!(
|
||||
"attribute counts differ: {} positions, {} normals, {} uvs, {} tangents",
|
||||
n,
|
||||
self.normals.len(),
|
||||
self.uvs.len(),
|
||||
self.tangents.len()
|
||||
)));
|
||||
}
|
||||
if !self.colors.is_empty() && self.colors.len() != n {
|
||||
return Err(GeomError::Invalid(format!("{} vertex colors for {n} vertices", self.colors.len())));
|
||||
}
|
||||
if !self.indices.len().is_multiple_of(3) {
|
||||
return Err(GeomError::Invalid("index count is not a multiple of 3".into()));
|
||||
}
|
||||
if self.triangle_count() > MAX_TRIANGLES {
|
||||
return Err(GeomError::Invalid(format!("mesh has more than {MAX_TRIANGLES} triangles")));
|
||||
}
|
||||
if let Some(bad) = self.indices.iter().find(|i| **i as usize >= n) {
|
||||
return Err(GeomError::Invalid(format!("index {bad} out of range ({n} vertices)")));
|
||||
}
|
||||
if self.positions.iter().any(|p| !p.is_finite()) {
|
||||
return Err(GeomError::Invalid("mesh has non-finite positions".into()));
|
||||
}
|
||||
for s in &self.submeshes {
|
||||
if s.start as usize + s.count as usize > self.indices.len() || s.material >= self.materials.len().max(1) {
|
||||
return Err(GeomError::Invalid(format!("submesh {} is out of range", s.name)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Area-weighted smooth normals over the index buffer.
|
||||
pub fn compute_normals(&mut self) {
|
||||
let mut normals = vec![Vec3::ZERO; self.positions.len()];
|
||||
for &[a, b, c] in self.indices.as_chunks::<3>().0 {
|
||||
let (a, b, c) = (a as usize, b as usize, c as usize);
|
||||
let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue };
|
||||
let face = (*pb - *pa).cross(*pc - *pa);
|
||||
for v in [a, b, c] {
|
||||
if let Some(x) = normals.get_mut(v) {
|
||||
*x += face;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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).
|
||||
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() {
|
||||
self.compute_normals();
|
||||
}
|
||||
if self.uvs.len() != self.positions.len() {
|
||||
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) {
|
||||
self.simple_tangents();
|
||||
}
|
||||
for (t, n) in self.tangents.iter_mut().zip(&self.normals) {
|
||||
// Orthonormalize against the normal; repair degenerate results.
|
||||
let v = t.truncate();
|
||||
let o = (v - *n * n.dot(v)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector());
|
||||
*t = o.extend(if t.w < 0.0 { -1.0 } else { 1.0 });
|
||||
}
|
||||
}
|
||||
|
||||
fn simple_tangents(&mut self) {
|
||||
let mut tangents = vec![Vec3::ZERO; self.positions.len()];
|
||||
for &[a, b, c] in self.indices.as_chunks::<3>().0 {
|
||||
let (a, b, c) = (a as usize, b as usize, c as usize);
|
||||
let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue };
|
||||
let (Some(ua), Some(ub), Some(uc)) = (self.uvs.get(a), self.uvs.get(b), self.uvs.get(c)) else { continue };
|
||||
let (e1, e2) = (*pb - *pa, *pc - *pa);
|
||||
let (d1, d2) = (*ub - *ua, *uc - *ua);
|
||||
let determinant = d1.x * d2.y - d2.x * d1.y;
|
||||
if determinant.abs() < 1e-12 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let tangent = (e1 * d2.y - e2 * d1.y) / determinant;
|
||||
for v in [a, b, c] {
|
||||
if let Some(x) = tangents.get_mut(v) {
|
||||
*x += tangent;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.tangents = tangents.into_iter().map(|t| t.try_normalize().unwrap_or(Vec3::X).extend(1.0)).collect();
|
||||
}
|
||||
|
||||
/// The UV tiles material `m` covers: integer parts of its triangles' UV centroids (v down),
|
||||
/// ascending. Non-finite UVs are skipped.
|
||||
pub fn uv_tiles(&self, m: usize) -> std::collections::BTreeSet<(i32, i32)> {
|
||||
self.triangles_of(m)
|
||||
.filter_map(|t| {
|
||||
let [a, b, c] = self.tri(t)?;
|
||||
let uv = (*self.uvs.get(a)? + *self.uvs.get(b)? + *self.uvs.get(c)?) / 3.0;
|
||||
uv.is_finite().then(|| (uv.x.floor() as i32, uv.y.floor() as i32))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Remap the UVs of material `m`'s triangles with `f`. Vertices they share with other
|
||||
/// materials are duplicated first, so the other triangles keep their UVs.
|
||||
pub fn map_material_uvs(&mut self, m: usize, f: impl Fn(Vec2) -> Vec2) {
|
||||
self.map_material_uvs_with(m, |_, uv| f(uv));
|
||||
}
|
||||
|
||||
/// [`Mesh::map_material_uvs`] where `f` also gets the UV centroid of the first of the
|
||||
/// material's triangles using the vertex: piecewise maps (UV tiles of different sizes) then
|
||||
/// place a vertex on a tile border with its own triangle's tile.
|
||||
pub fn map_material_uvs_with(&mut self, m: usize, f: impl Fn(Vec2, Vec2) -> Vec2) {
|
||||
let material_triangles: Vec<usize> = self.triangles_of(m).collect();
|
||||
let mut in_material = vec![false; self.triangle_count()];
|
||||
for t in &material_triangles {
|
||||
if let Some(x) = in_material.get_mut(*t) {
|
||||
*x = true;
|
||||
}
|
||||
}
|
||||
|
||||
let mut shared = vec![false; self.positions.len()];
|
||||
for (_, tri) in self.indices.as_chunks::<3>().0.iter().enumerate().filter(|(t, _)| !in_material.get(*t).copied().unwrap_or(false)) {
|
||||
for v in tri {
|
||||
if let Some(s) = shared.get_mut(*v as usize) {
|
||||
*s = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut duplicates = std::collections::HashMap::new();
|
||||
for k in material_triangles.iter().flat_map(|t| t * 3..t * 3 + 3) {
|
||||
let Some(&v) = self.indices.get(k) else { continue };
|
||||
let v = if shared.get(v as usize).copied().unwrap_or(false) {
|
||||
*duplicates.entry(v).or_insert_with(|| self.duplicate_vertex(v as usize))
|
||||
} else {
|
||||
v
|
||||
};
|
||||
if let Some(i) = self.indices.get_mut(k) {
|
||||
*i = v;
|
||||
}
|
||||
}
|
||||
|
||||
// (vertex, centroid of its first triangle), each vertex once
|
||||
let mut vertices = Vec::with_capacity(material_triangles.len() * 3);
|
||||
for t in &material_triangles {
|
||||
let Some(tri) = self.tri(*t) else { continue };
|
||||
let centroid = tri.iter().map(|v| self.uvs.get(*v).copied().unwrap_or_default()).sum::<Vec2>() / 3.0;
|
||||
vertices.extend(tri.map(|v| (v, centroid)));
|
||||
}
|
||||
|
||||
vertices.sort_by_key(|(v, _)| *v);
|
||||
vertices.dedup_by_key(|(v, _)| *v);
|
||||
for (v, centroid) in vertices {
|
||||
if let Some(uv) = self.uvs.get_mut(v) {
|
||||
*uv = f(centroid, *uv);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Append a copy of vertex `v`; returns its index.
|
||||
fn duplicate_vertex(&mut self, v: usize) -> u32 {
|
||||
let i = self.positions.len() as u32;
|
||||
self.positions.push(self.positions.get(v).copied().unwrap_or_default());
|
||||
self.normals.push(self.normals.get(v).copied().unwrap_or(Vec3::Y));
|
||||
self.tangents.push(self.tangents.get(v).copied().unwrap_or(Vec4::new(1.0, 0.0, 0.0, 1.0)));
|
||||
self.uvs.push(self.uvs.get(v).copied().unwrap_or_default());
|
||||
if !self.colors.is_empty() {
|
||||
self.colors.push(self.colors.get(v).copied().unwrap_or(Vec4::ONE));
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
/// Append `other`, offsetting indices; its submeshes keep their material indices shifted by
|
||||
/// this mesh's material count.
|
||||
pub fn append(&mut self, other: &Mesh) {
|
||||
let base = self.positions.len() as u32;
|
||||
let ibase = self.indices.len() as u32;
|
||||
let mbase = self.materials.len();
|
||||
self.positions.extend_from_slice(&other.positions);
|
||||
self.normals.extend_from_slice(&other.normals);
|
||||
self.tangents.extend_from_slice(&other.tangents);
|
||||
self.uvs.extend_from_slice(&other.uvs);
|
||||
if !(self.colors.is_empty() && other.colors.is_empty()) {
|
||||
// Vertices of the side without colors become white.
|
||||
self.colors.resize(base as usize, Vec4::ONE);
|
||||
self.colors.extend(other.colors.iter().copied().chain(std::iter::repeat(Vec4::ONE)).take(other.positions.len()));
|
||||
}
|
||||
if !(self.diagonals.is_empty() && other.diagonals.is_empty()) {
|
||||
self.diagonals.resize(ibase as usize / 3, 0);
|
||||
self.diagonals.extend(other.diagonals.iter().copied().chain(std::iter::repeat(0)).take(other.triangle_count()));
|
||||
}
|
||||
self.indices.extend(other.indices.iter().map(|i| i + base));
|
||||
self.materials.extend(other.materials.iter().cloned());
|
||||
self.submeshes.extend(other.submeshes.iter().map(|s| SubMesh {
|
||||
name: s.name.clone(),
|
||||
material: s.material + mbase,
|
||||
start: s.start + ibase,
|
||||
count: s.count,
|
||||
}));
|
||||
}
|
||||
|
||||
/// Each triangle split into four at its edge midpoints (shared edges share their midpoint);
|
||||
/// attributes are interpolated and submesh ranges keep their triangles.
|
||||
pub fn subdivided(&self) -> Mesh {
|
||||
let mut m = Mesh { indices: Vec::with_capacity(self.indices.len() * 4), ..self.clone() };
|
||||
let has = |len: usize| len == self.positions.len();
|
||||
let (has_n, has_t, has_uv, has_c) = (has(self.normals.len()), has(self.tangents.len()), has(self.uvs.len()), has(self.colors.len()));
|
||||
let mut mids = std::collections::HashMap::new();
|
||||
let mut mid = |m: &mut Mesh, a: u32, b: u32| -> u32 {
|
||||
*mids.entry((a.min(b), a.max(b))).or_insert_with(|| {
|
||||
let (i, j) = (a as usize, b as usize);
|
||||
m.positions.push((self.positions[i] + self.positions[j]) * 0.5);
|
||||
if has_n {
|
||||
m.normals.push((self.normals[i] + self.normals[j]).normalize_or_zero());
|
||||
}
|
||||
if has_t {
|
||||
let (ti, tj) = (self.tangents[i], self.tangents[j]);
|
||||
m.tangents.push((ti.truncate() + tj.truncate()).normalize_or_zero().extend(ti.w));
|
||||
}
|
||||
if has_uv {
|
||||
m.uvs.push((self.uvs[i] + self.uvs[j]) * 0.5);
|
||||
}
|
||||
if has_c {
|
||||
m.colors.push((self.colors[i] + self.colors[j]) * 0.5);
|
||||
}
|
||||
(m.positions.len() - 1) as u32
|
||||
})
|
||||
};
|
||||
for t in self.indices.as_chunks::<3>().0 {
|
||||
if t.iter().any(|&i| i as usize >= self.positions.len()) {
|
||||
continue;
|
||||
}
|
||||
let (a, b, c) = (t[0], t[1], t[2]);
|
||||
let (ab, bc, ca) = (mid(&mut m, a, b), mid(&mut m, b, c), mid(&mut m, c, a));
|
||||
m.indices.extend_from_slice(&[a, ab, ca, ab, b, bc, ca, bc, c, ab, bc, ca]);
|
||||
}
|
||||
for s in &mut m.submeshes {
|
||||
s.start *= 4;
|
||||
s.count *= 4;
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// Uniformly scale and translate so the mesh is centered with the given bounding radius.
|
||||
pub fn normalize_to(&mut self, radius: f32) {
|
||||
let (lo, hi) = self.bounds();
|
||||
let c = (lo + hi) * 0.5;
|
||||
let s = radius / self.radius();
|
||||
for p in &mut self.positions {
|
||||
*p = (*p - c) * s;
|
||||
}
|
||||
}
|
||||
|
||||
/// A single-material mesh from raw attributes; computes missing normals and tangents.
|
||||
pub fn from_parts(positions: Vec<Vec3>, normals: Option<Vec<Vec3>>, uvs: Vec<Vec2>, indices: Vec<u32>, material: &str) -> Result<Mesh> {
|
||||
let count = indices.len() as u32;
|
||||
let mut m = Mesh {
|
||||
normals: normals.unwrap_or_default(),
|
||||
uvs,
|
||||
positions,
|
||||
indices,
|
||||
tangents: Vec::new(),
|
||||
colors: Vec::new(),
|
||||
submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }],
|
||||
materials: vec![material.into()],
|
||||
diagonals: Vec::new(),
|
||||
};
|
||||
if m.normals.len() != m.positions.len() {
|
||||
m.compute_normals();
|
||||
}
|
||||
m.compute_tangents();
|
||||
m.validate()?;
|
||||
Ok(m)
|
||||
}
|
||||
}
|
||||
|
||||
struct Mikk<'a> {
|
||||
mesh: &'a mut Mesh,
|
||||
}
|
||||
|
||||
impl Mikk<'_> {
|
||||
fn vi(&self, face: usize, vert: usize) -> usize {
|
||||
self.mesh.indices.get(face * 3 + vert).copied().unwrap_or(0) as usize
|
||||
}
|
||||
}
|
||||
|
||||
impl mikktspace::Geometry for Mikk<'_> {
|
||||
fn num_faces(&self) -> usize {
|
||||
self.mesh.indices.len() / 3
|
||||
}
|
||||
fn num_vertices_of_face(&self, _face: usize) -> usize {
|
||||
3
|
||||
}
|
||||
fn position(&self, face: usize, vert: usize) -> [f32; 3] {
|
||||
self.mesh.positions.get(self.vi(face, vert)).copied().unwrap_or_default().to_array()
|
||||
}
|
||||
fn normal(&self, face: usize, vert: usize) -> [f32; 3] {
|
||||
self.mesh.normals.get(self.vi(face, vert)).copied().unwrap_or(Vec3::Y).to_array()
|
||||
}
|
||||
fn tex_coord(&self, face: usize, vert: usize) -> [f32; 2] {
|
||||
// MikkTSpace expects OpenGL texture coordinates (v up); our UVs are glTF (v down). With
|
||||
// v flipped, the bitangent `cross(N, T) * w` points up the image, as glTF requires.
|
||||
let uv = self.mesh.uvs.get(self.vi(face, vert)).copied().unwrap_or_default();
|
||||
[uv.x, 1.0 - uv.y]
|
||||
}
|
||||
fn set_tangent_encoded(&mut self, tangent: [f32; 4], face: usize, vert: usize) {
|
||||
let i = self.vi(face, vert);
|
||||
if let Some(t) = self.mesh.tangents.get_mut(i) {
|
||||
*t = Vec4::from_array(tangent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
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)],
|
||||
None,
|
||||
vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 0.0)],
|
||||
vec![0, 1, 2, 0, 2, 3],
|
||||
"Default",
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normals_and_tangents_of_a_quad() {
|
||||
let m = quad();
|
||||
for n in &m.normals {
|
||||
assert!((*n - Vec3::Z).length() < 1e-5);
|
||||
}
|
||||
for t in &m.tangents {
|
||||
assert!((t.truncate() - Vec3::X).length() < 1e-4, "{t:?}");
|
||||
}
|
||||
assert_eq!(m.material_of(1), Some(0));
|
||||
assert_eq!(m.triangles_of(0).collect::<Vec<_>>(), vec![0, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wire_edges_leave_out_polygon_diagonals() {
|
||||
let mut m = quad();
|
||||
assert_eq!(m.wire_edges(), vec![vec![(0, 1), (1, 2), (0, 2), (2, 3), (0, 3)]], "triangles show every edge");
|
||||
// Edge 2 of (0, 1, 2) and edge 0 of (0, 2, 3) split the quad.
|
||||
m.diagonals = vec![0b100, 0b001];
|
||||
assert_eq!(m.wire_edges(), vec![vec![(0, 1), (1, 2), (2, 3), (0, 3)]]);
|
||||
// A diagonal whose twin a seam split off (vertex 4 copies vertex 0) stays.
|
||||
let mut seam = m.clone();
|
||||
seam.indices[3] = 4;
|
||||
assert_eq!(seam.wire_edges()[0].len(), 6);
|
||||
// Appending keeps each side's diagonals on its own triangles.
|
||||
let mut a = Mesh::from_parts(m.positions.clone(), None, m.uvs.clone(), vec![0, 1, 2], "A").unwrap();
|
||||
a.append(&m);
|
||||
assert_eq!(a.diagonals, vec![0, 0b100, 0b001]);
|
||||
assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_seams_are_where_the_uv_layout_splits() {
|
||||
let mesh = quad();
|
||||
assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()], "one UV island has no seam");
|
||||
|
||||
// Vertex 4 copies vertex 0's position with another UV: the diagonal (0, 2) / (4, 2) is cut
|
||||
let mut seam = mesh.clone();
|
||||
seam.positions.push(seam.positions[0]);
|
||||
seam.normals.push(seam.normals[0]);
|
||||
seam.tangents.push(seam.tangents[0]);
|
||||
seam.uvs.push(Vec2::new(0.9, 0.9));
|
||||
seam.indices[3] = 4;
|
||||
assert_eq!(seam.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]);
|
||||
|
||||
// The same split with the same UV is a hard edge, not a seam
|
||||
let mut hard = seam.clone();
|
||||
hard.uvs[4] = hard.uvs[0];
|
||||
assert_eq!(hard.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_seams_join_positions_with_opposite_signed_zero() {
|
||||
let mut mesh = quad();
|
||||
mesh.positions.push(Vec3::new(-0.0, 0.0, 0.0));
|
||||
mesh.normals.push(mesh.normals[0]);
|
||||
mesh.tangents.push(mesh.tangents[0]);
|
||||
mesh.uvs.push(Vec2::new(0.9, 0.9));
|
||||
mesh.indices[3] = 4;
|
||||
assert_eq!(mesh.positions[0], mesh.positions[4]);
|
||||
assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_seams_between_materials_belong_to_both_materials() {
|
||||
let mut mesh = quad();
|
||||
mesh.positions.push(mesh.positions[0]);
|
||||
mesh.normals.push(mesh.normals[0]);
|
||||
mesh.tangents.push(mesh.tangents[0]);
|
||||
mesh.uvs.push(Vec2::new(0.9, 0.9));
|
||||
mesh.indices[3] = 4;
|
||||
mesh.materials.push("second".into());
|
||||
mesh.submeshes[0].count = 3;
|
||||
mesh.submeshes.push(SubMesh { name: "second".into(), material: 1, start: 3, count: 3 });
|
||||
|
||||
assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2)], vec![(2, 4)]]);
|
||||
mesh.uvs[4] = mesh.uvs[0];
|
||||
assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new(); 2], "a material boundary alone is not a UV seam");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subdivision_shares_edge_midpoints() {
|
||||
let m = quad().subdivided();
|
||||
// 4 corners + 5 edge midpoints (the diagonal is shared), 8 triangles.
|
||||
assert_eq!((m.positions.len(), m.triangle_count()), (9, 8));
|
||||
assert_eq!(m.uvs.len(), 9);
|
||||
assert_eq!((m.submeshes[0].start, m.submeshes[0].count), (0, 24));
|
||||
m.validate().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_catches_bad_indices() {
|
||||
let mut m = quad();
|
||||
m.indices[0] = 99;
|
||||
assert!(m.validate().is_err());
|
||||
let mut m = quad();
|
||||
m.uvs.pop();
|
||||
assert!(m.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn append_offsets_indices_and_materials() {
|
||||
let mut a = quad();
|
||||
let b = quad();
|
||||
a.append(&b);
|
||||
assert_eq!(a.indices[6], 4);
|
||||
assert_eq!(a.submeshes[1].material, 1);
|
||||
assert_eq!(a.submeshes[1].start, 6);
|
||||
a.validate().unwrap();
|
||||
// Colors on one side only: the other side's vertices become white.
|
||||
let mut red = quad();
|
||||
red.colors = vec![Vec4::new(1.0, 0.0, 0.0, 1.0); 4];
|
||||
a.append(&red);
|
||||
assert_eq!(a.colors.len(), 12);
|
||||
assert_eq!((a.colors[0], a.colors[8]), (Vec4::ONE, Vec4::new(1.0, 0.0, 0.0, 1.0)));
|
||||
a.append(&quad());
|
||||
assert_eq!(a.colors[15], Vec4::ONE);
|
||||
a.validate().unwrap();
|
||||
a.colors.pop();
|
||||
assert!(a.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn material_uvs_remap_and_split_shared_vertices() {
|
||||
// quad(): two triangles sharing an edge; put the second in its own material.
|
||||
let mut m = quad();
|
||||
m.materials = vec!["a".into(), "b".into()];
|
||||
m.submeshes =
|
||||
vec![SubMesh { name: "a".into(), material: 0, start: 0, count: 3 }, SubMesh { name: "b".into(), material: 1, start: 3, count: 3 }];
|
||||
let before = m.clone();
|
||||
m.map_material_uvs(1, |uv| uv + Vec2::X);
|
||||
m.validate().unwrap();
|
||||
assert_eq!(m.vertex_count(), 6, "the two shared vertices are split");
|
||||
assert_eq!(&m.indices[..3], &before.indices[..3]);
|
||||
for k in 0..3 {
|
||||
let (old, new) = (before.indices[k] as usize, m.indices[k] as usize);
|
||||
assert_eq!(m.uvs[new], before.uvs[old], "material a keeps its UVs");
|
||||
let (old, new) = (before.indices[3 + k] as usize, m.indices[3 + k] as usize);
|
||||
assert_eq!((m.uvs[new], m.positions[new]), (before.uvs[old] + Vec2::X, before.positions[old]));
|
||||
}
|
||||
assert_eq!(m.uv_tiles(1).into_iter().collect::<Vec<_>>(), vec![(1, 0)]);
|
||||
assert_eq!(m.uv_tiles(0).into_iter().collect::<Vec<_>>(), vec![(0, 0)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,604 @@
|
||||
//! Built-in meshes with clean, non-overlapping UVs: material ball, sphere, (rounded) cube,
|
||||
//! cylinder, torus and plane. Y is up; triangles are counter-clockwise seen from outside.
|
||||
|
||||
use std::f32::consts::{PI, TAU};
|
||||
|
||||
use glam::{Vec2, Vec3};
|
||||
|
||||
use crate::mesh::{Mesh, SubMesh};
|
||||
use crate::{GeomError, Result};
|
||||
|
||||
/// A UV-space rectangle: origin and size.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct UvRect {
|
||||
o: Vec2,
|
||||
s: Vec2,
|
||||
}
|
||||
|
||||
impl UvRect {
|
||||
const FULL: UvRect = UvRect { o: Vec2::ZERO, s: Vec2::ONE };
|
||||
fn map(&self, u: f32, v: f32) -> Vec2 {
|
||||
self.o + self.s * Vec2::new(u, v)
|
||||
}
|
||||
fn inset(&self, m: f32) -> UvRect {
|
||||
UvRect { o: self.o + Vec2::splat(m), s: self.s - Vec2::splat(2.0 * m) }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Builder {
|
||||
p: Vec<Vec3>,
|
||||
n: Vec<Vec3>,
|
||||
uv: Vec<Vec2>,
|
||||
idx: Vec<u32>,
|
||||
/// Per triangle: its [`Mesh::diagonals`] bits.
|
||||
diag: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Builder {
|
||||
fn vert(&mut self, p: Vec3, n: Vec3, uv: Vec2) -> u32 {
|
||||
self.p.push(p);
|
||||
self.n.push(n.try_normalize().unwrap_or(Vec3::Y));
|
||||
self.uv.push(uv);
|
||||
(self.p.len() - 1) as u32
|
||||
}
|
||||
|
||||
/// A grid of (rows+1)×(cols+1) vertices from `f(row, col)`, rows going "down" the texture.
|
||||
fn grid(&mut self, rows: usize, cols: usize, mut f: impl FnMut(usize, usize) -> (Vec3, Vec3, Vec2)) {
|
||||
let base = self.p.len() as u32;
|
||||
for i in 0..=rows {
|
||||
for j in 0..=cols {
|
||||
let (p, n, uv) = f(i, j);
|
||||
self.vert(p, n, uv);
|
||||
}
|
||||
}
|
||||
let w = (cols + 1) as u32;
|
||||
for i in 0..rows as u32 {
|
||||
for j in 0..cols as u32 {
|
||||
let a = base + i * w + j;
|
||||
let (b, c, d) = (a + 1, a + w, a + w + 1);
|
||||
self.idx.extend_from_slice(&[a, c, d, a, d, b]);
|
||||
// Edge d-a of the first triangle and a-d of the second split the quad.
|
||||
self.diag.extend_from_slice(&[0b100, 0b001]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The mesh of one material, with tangents.
|
||||
fn finish(self, material: &str) -> Mesh {
|
||||
let mut m = self.into_mesh(material);
|
||||
m.compute_tangents();
|
||||
m
|
||||
}
|
||||
|
||||
/// The mesh of one material, without tangents.
|
||||
fn into_mesh(self, material: &str) -> Mesh {
|
||||
let count = self.idx.len() as u32;
|
||||
Mesh {
|
||||
positions: self.p,
|
||||
normals: self.n,
|
||||
uvs: self.uv,
|
||||
indices: self.idx,
|
||||
tangents: Vec::new(),
|
||||
colors: Vec::new(),
|
||||
submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }],
|
||||
materials: vec![material.into()],
|
||||
diagonals: self.diag,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// UV sphere of `radius` centred at `center`.
|
||||
pub fn sphere(radius: f32, segments: usize, rings: usize) -> Mesh {
|
||||
let mut b = Builder::default();
|
||||
sphere_into(&mut b, Vec3::ZERO, radius, segments.max(3), rings.max(2), UvRect::FULL);
|
||||
b.finish("Sphere")
|
||||
}
|
||||
|
||||
fn sphere_into(b: &mut Builder, center: Vec3, radius: f32, segs: usize, rings: usize, r: UvRect) {
|
||||
b.grid(rings, segs, |i, j| {
|
||||
let (u, v) = (j as f32 / segs as f32, i as f32 / rings as f32);
|
||||
let (theta, phi) = (v * PI, u * TAU + PI * 1.5);
|
||||
let n = Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin());
|
||||
(center + n * radius, n, r.map(u, v))
|
||||
});
|
||||
}
|
||||
|
||||
/// A box with rounded edges (`bevel` = edge radius; 0 gives a plain cube). Faces are laid out
|
||||
/// in a 3×2 UV atlas.
|
||||
/// Each half extent must be finite and positive, and its doubled value must be finite.
|
||||
/// `bevel` must be finite and between zero and 95% of the smallest half extent.
|
||||
pub fn rounded_box(half: Vec3, bevel: f32) -> Result<Mesh> {
|
||||
if !half.is_finite() || !half.cmpgt(Vec3::ZERO).all() || !(half * 2.0).is_finite() {
|
||||
return Err(GeomError::Invalid("box half extents must be positive and finite, with finite doubled extents".into()));
|
||||
}
|
||||
if !bevel.is_finite() || bevel < 0.0 || bevel > half.min_element() * 0.95 {
|
||||
return Err(GeomError::Invalid("box bevel must be finite and between zero and 95% of the smallest half extent".into()));
|
||||
}
|
||||
let mut b = Builder::default();
|
||||
rounded_box_into(&mut b, Vec3::ZERO, half, bevel, UvRect::FULL);
|
||||
Ok(b.finish("Box"))
|
||||
}
|
||||
|
||||
/// The cube primitive (sharp edges). `size` must be finite and have a finite positive half extent.
|
||||
pub fn cube(size: f32) -> Result<Mesh> {
|
||||
let mut m = rounded_box(Vec3::splat(size * 0.5), 0.0)?;
|
||||
m.materials = vec!["Cube".into()];
|
||||
if let Some(s) = m.submeshes.first_mut() {
|
||||
s.name = "Cube".into();
|
||||
}
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
fn rounded_box_into(b: &mut Builder, center: Vec3, half: Vec3, bevel: f32, r: UvRect) {
|
||||
let bevel = bevel.clamp(0.0, half.min_element() * 0.95);
|
||||
// (normal, U = right, V = down) per face, seen from outside.
|
||||
let faces = [
|
||||
(Vec3::Z, Vec3::X, -Vec3::Y),
|
||||
(Vec3::X, -Vec3::Z, -Vec3::Y),
|
||||
(-Vec3::Z, -Vec3::X, -Vec3::Y),
|
||||
(-Vec3::X, Vec3::Z, -Vec3::Y),
|
||||
(Vec3::Y, Vec3::X, Vec3::Z),
|
||||
(-Vec3::Y, Vec3::X, -Vec3::Z),
|
||||
];
|
||||
let (kb, kc) = if bevel > 0.0 { (6usize, 10usize) } else { (0, 12) };
|
||||
// Coordinates along one face axis from -h to h, dense in the bevels.
|
||||
let coords = |h: f32| -> Vec<f32> {
|
||||
let inner = h - bevel;
|
||||
let mut v = Vec::new();
|
||||
for i in 0..kb {
|
||||
v.push(-h + bevel * (i as f32 / kb as f32));
|
||||
}
|
||||
for i in 0..=kc {
|
||||
v.push(inner * (2.0 * (i as f32 / kc as f32) - 1.0));
|
||||
}
|
||||
for i in 1..=kb {
|
||||
v.push(inner + bevel * (i as f32 / kb as f32));
|
||||
}
|
||||
v
|
||||
};
|
||||
let inner = half - Vec3::splat(bevel);
|
||||
for (f, (n, u, v)) in faces.iter().enumerate() {
|
||||
let cell = UvRect { o: r.map((f % 3) as f32 / 3.0, (f / 3) as f32 / 2.0), s: r.s * Vec2::new(1.0 / 3.0, 0.5) }.inset(0.01 * r.s.x);
|
||||
let (hu, hv, hn) = ((*u * half).abs().max_element(), (*v * half).abs().max_element(), (*n * half).abs().max_element());
|
||||
let (cu, cv) = (coords(hu), coords(hv));
|
||||
let (cols, rows) = (cu.len() - 1, cv.len() - 1);
|
||||
b.grid(rows, cols, |i, j| {
|
||||
let (a, c) = (cu[j], cv[i]);
|
||||
let q = *n * hn + *u * a + *v * c;
|
||||
let clamped = q.clamp(-inner, inner);
|
||||
let dir = (q - clamped).try_normalize().unwrap_or(*n);
|
||||
let p = if bevel > 0.0 { clamped + dir * bevel } else { q };
|
||||
let nn = if bevel > 0.0 { dir } else { *n };
|
||||
(center + p, nn, cell.map((a + hu) / (2.0 * hu), (c + hv) / (2.0 * hv)))
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Surface of revolution of a profile `(radius, y)` listed top → bottom, mapped into `r`
|
||||
/// (u around, v down the profile by arc length).
|
||||
fn lathe_into(b: &mut Builder, center: Vec3, profile: &[(f32, f32)], segs: usize, r: UvRect) {
|
||||
if profile.len() < 2 {
|
||||
return;
|
||||
}
|
||||
let mut len = vec![0.0f32];
|
||||
for w in profile.windows(2) {
|
||||
let d = Vec2::new(w[1].0 - w[0].0, w[1].1 - w[0].1).length();
|
||||
len.push(len.last().copied().unwrap_or(0.0) + d);
|
||||
}
|
||||
let total = len.last().copied().unwrap_or(1.0).max(1e-6);
|
||||
let rows = profile.len() - 1;
|
||||
b.grid(rows, segs, |i, j| {
|
||||
let (rad, y) = profile[i];
|
||||
// Profile tangent (downwards) → outward normal in the (r, y) plane.
|
||||
let prev = profile[i.saturating_sub(1)];
|
||||
let next = profile[(i + 1).min(rows)];
|
||||
let t = Vec2::new(next.0 - prev.0, next.1 - prev.1).try_normalize().unwrap_or(Vec2::NEG_Y);
|
||||
let n2 = Vec2::new(-t.y, t.x);
|
||||
let u = j as f32 / segs as f32;
|
||||
let phi = u * TAU + PI * 1.5;
|
||||
let dir = Vec3::new(phi.cos(), 0.0, -phi.sin());
|
||||
let p = center + dir * rad + Vec3::Y * y;
|
||||
let n = dir * n2.x + Vec3::Y * n2.y;
|
||||
(p, n, r.map(u, len[i] / total))
|
||||
});
|
||||
}
|
||||
|
||||
/// [`preview_orb`]: half-size of the cube that cuts the unit sphere flat (each face rim is the
|
||||
/// circle where they meet).
|
||||
const ORB_CUT: f32 = 0.8;
|
||||
/// [`preview_orb`] domed panels: where the valley sits, as a fraction of the face rim radius.
|
||||
const ORB_PANEL_VALLEY: f32 = 0.88;
|
||||
|
||||
/// The preview orb of the smart mask and smart material previews: a sphere cut flat by a cube on six sides, on a thin round base
|
||||
/// Each feature gives one kind of mask something to show: sharp face rims (edges), a softly
|
||||
/// blended left face (soft edges), domed panels inside the front, left and top faces whose valleys
|
||||
/// hold dirt (cavities), a slot around the middle (cavity), the base (thin part, the seam where it
|
||||
/// meets the body) and plain rounded corners (gradients). Faces +Z (front), -X (left) and +Y (top)
|
||||
/// carry the panels, so the shape is made to be seen from the front left, slightly from above.
|
||||
/// The body takes the top 79 % of the UV square, the base the bottom 19 %.
|
||||
pub fn preview_orb() -> Mesh {
|
||||
// Grid rows (columns: twice as many); fewer blur the panel walls, more cost bake time
|
||||
const ROWS: usize = 300;
|
||||
const BODY_UV_HEIGHT: f32 = 0.79;
|
||||
const BASE_UV: UvRect = UvRect { o: Vec2::new(0.0, 0.81), s: Vec2::new(1.0, 0.19) };
|
||||
const BASE_RADIUS: f32 = 0.95;
|
||||
const BASE_HALF_HEIGHT: f32 = 0.025;
|
||||
const BASE_Y: f32 = -0.6;
|
||||
const BASE_RIM_STEPS: usize = 12;
|
||||
const BASE_SEGMENTS: usize = 256;
|
||||
|
||||
let mut b = Builder::default();
|
||||
b.grid(ROWS, ROWS * 2, |i, j| {
|
||||
let (u, v) = (j as f32 / (ROWS * 2) as f32, i as f32 / ROWS as f32);
|
||||
let (theta, phi) = (v * PI, u * TAU + PI * 1.5);
|
||||
let dir = Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin());
|
||||
(dir * preview_orb_radius(dir), dir, Vec2::new(u, v * BODY_UV_HEIGHT))
|
||||
});
|
||||
|
||||
// Base: a thin disc with a rounded rim (a half circle from its top face to its bottom face)
|
||||
let mut profile = vec![(0.0, BASE_HALF_HEIGHT)];
|
||||
for k in 0..=BASE_RIM_STEPS {
|
||||
let a = k as f32 / BASE_RIM_STEPS as f32 * PI;
|
||||
profile.push((BASE_RADIUS - BASE_HALF_HEIGHT + BASE_HALF_HEIGHT * a.sin(), BASE_HALF_HEIGHT * a.cos()));
|
||||
}
|
||||
profile.push((0.0, -BASE_HALF_HEIGHT));
|
||||
lathe_into(&mut b, Vec3::Y * BASE_Y, &profile, BASE_SEGMENTS, BASE_UV);
|
||||
|
||||
let mut m = b.into_mesh("Preview");
|
||||
// Normals from the triangles: the panel walls are too steep for the sphere's directions
|
||||
m.compute_normals();
|
||||
// Body and base both run U around the vertical axis, so the tangent is that direction (a
|
||||
// fraction of the cost of the general tangent pass on this many triangles)
|
||||
m.tangents = m
|
||||
.positions
|
||||
.iter()
|
||||
.zip(&m.normals)
|
||||
.map(|(p, n)| {
|
||||
let around = Vec3::new(p.z, 0.0, -p.x).try_normalize().unwrap_or(Vec3::X);
|
||||
(around - *n * n.dot(around)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()).extend(1.0)
|
||||
})
|
||||
.collect();
|
||||
m
|
||||
}
|
||||
|
||||
/// Distance from the centre of the [`preview_orb`] body along unit direction `d`.
|
||||
fn preview_orb_radius(d: Vec3) -> f32 {
|
||||
// Rim blends: the sharp faces, and the softly blended left face
|
||||
const SHARP_BLEND: f32 = 0.035;
|
||||
const SOFT_BLEND: f32 = 0.18;
|
||||
// Domed panels: valley depth below the face, dome rise past it; the left panel is smaller
|
||||
const PANEL_DEPTH: f32 = 0.11;
|
||||
const PANEL_BULGE: f32 = 0.04;
|
||||
const LEFT_PANEL_SCALE: f32 = 0.9;
|
||||
// Slot around the middle: centre height, half-width, edge rounding, depth; it fades out over
|
||||
// this fraction of the left panel's rim
|
||||
const SLOT_Y: f32 = -0.03;
|
||||
const SLOT_HALF_WIDTH: f32 = 0.05;
|
||||
const SLOT_ROUNDING: f32 = 0.015;
|
||||
const SLOT_DEPTH: f32 = 0.12;
|
||||
const SLOT_FADE: f32 = 0.04;
|
||||
|
||||
let rim = (1.0 - ORB_CUT * ORB_CUT).sqrt() / ORB_CUT;
|
||||
let smooth = |a: f32, b: f32, x: f32| {
|
||||
let t = ((x - a) / (b - a)).clamp(0.0, 1.0);
|
||||
t * t * (3.0 - 2.0 * t)
|
||||
};
|
||||
// Polynomial smooth minimum with blend radius k
|
||||
let smin = |a: f32, b: f32, k: f32| {
|
||||
let h = (0.5 + 0.5 * (b - a) / k).clamp(0.0, 1.0);
|
||||
b + (a - b) * h - k * h * (1.0 - h)
|
||||
};
|
||||
// Domed panel at `rho` (radius in face units) inside a face of rim `rim`: a steep wall from
|
||||
// the rim into a valley, then a dome rising slightly past the face over the middle
|
||||
let panel = |rho: f32, rim: f32| {
|
||||
let valley = rim * ORB_PANEL_VALLEY;
|
||||
if rho < valley {
|
||||
PANEL_BULGE - (PANEL_BULGE + PANEL_DEPTH) * (rho / valley).powi(3)
|
||||
} else {
|
||||
-PANEL_DEPTH * (1.0 - ((rho - valley) / (rim - valley)).min(1.0))
|
||||
}
|
||||
};
|
||||
let face_rho = |along: f32, u: f32, v: f32| (u * u + v * v).sqrt() / along.max(1e-3);
|
||||
|
||||
// The cut: sharp rims except the softly blended left face
|
||||
let mut radius = 1.0f32;
|
||||
for (along, blend) in [(d.x, SHARP_BLEND), (-d.x, SOFT_BLEND), (d.y, SHARP_BLEND), (-d.y, SHARP_BLEND), (d.z, SHARP_BLEND), (-d.z, SHARP_BLEND)] {
|
||||
// Directions facing away from a face stay on the sphere (9 = far past it)
|
||||
let to_face = if along > 1e-3 { ORB_CUT / along } else { 9.0 };
|
||||
radius = smin(radius, to_face, blend);
|
||||
}
|
||||
|
||||
let a = d.abs();
|
||||
let left_rim = rim * LEFT_PANEL_SCALE;
|
||||
let mut relief = 0.0;
|
||||
if d.z > 0.0 && a.z >= a.x && a.z >= a.y {
|
||||
relief += panel(face_rho(d.z, d.x, d.y), rim);
|
||||
}
|
||||
if d.x < 0.0 && a.x >= a.y && a.x >= a.z {
|
||||
relief += panel(face_rho(-d.x, d.y, d.z), left_rim);
|
||||
}
|
||||
if d.y > 0.0 && a.y >= a.x && a.y >= a.z {
|
||||
relief += panel(face_rho(d.y, d.x, d.z), rim);
|
||||
}
|
||||
|
||||
// Slot around the middle, stopping at the left panel
|
||||
let in_left_panel =
|
||||
if d.x < 0.0 { 1.0 - smooth(left_rim * (1.0 - SLOT_FADE), left_rim * (1.0 + SLOT_FADE), face_rho(-d.x, d.y, d.z)) } else { 0.0 };
|
||||
let slot_band = 1.0 - smooth(SLOT_HALF_WIDTH - SLOT_ROUNDING, SLOT_HALF_WIDTH + SLOT_ROUNDING, (d.y - SLOT_Y).abs());
|
||||
relief -= SLOT_DEPTH * slot_band * (1.0 - in_left_panel);
|
||||
|
||||
radius + relief
|
||||
}
|
||||
|
||||
/// A flat disk facing up (+Y) or down, with planar UVs inside `r`.
|
||||
fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize, r: UvRect) {
|
||||
let n = if up { Vec3::Y } else { Vec3::NEG_Y };
|
||||
let c = b.vert(center, n, r.map(0.5, 0.5));
|
||||
let first = b.p.len() as u32;
|
||||
for j in 0..segs {
|
||||
let a = j as f32 / segs as f32 * TAU;
|
||||
let (x, z) = (a.cos(), a.sin());
|
||||
// Top view: +X right, +Z down the texture; bottom view mirrors X.
|
||||
let uv = if up { r.map(0.5 + x * 0.5, 0.5 + z * 0.5) } else { r.map(0.5 + x * 0.5, 0.5 - z * 0.5) };
|
||||
b.vert(center + Vec3::new(x, 0.0, z) * radius, n, uv);
|
||||
}
|
||||
for j in 0..segs as u32 {
|
||||
let (a, bb) = (first + j, first + (j + 1) % segs as u32);
|
||||
if up {
|
||||
b.idx.extend_from_slice(&[c, bb, a]);
|
||||
} else {
|
||||
b.idx.extend_from_slice(&[c, a, bb]);
|
||||
}
|
||||
b.diag.push(0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A capped cylinder along Y.
|
||||
pub fn cylinder(radius: f32, height: f32, segs: usize) -> Mesh {
|
||||
let mut b = Builder::default();
|
||||
let h = height * 0.5;
|
||||
lathe_into(&mut b, Vec3::ZERO, &[(radius, h), (radius, -h)], segs.max(3), UvRect { o: Vec2::ZERO, s: Vec2::new(1.0, 0.5) }.inset(0.01));
|
||||
disk_into(&mut b, Vec3::Y * h, radius, true, segs.max(3), UvRect { o: Vec2::new(0.0, 0.5), s: Vec2::splat(0.5) }.inset(0.01));
|
||||
disk_into(&mut b, -Vec3::Y * h, radius, false, segs.max(3), UvRect { o: Vec2::new(0.5, 0.5), s: Vec2::splat(0.5) }.inset(0.01));
|
||||
b.finish("Cylinder")
|
||||
}
|
||||
|
||||
/// A torus around Y.
|
||||
pub fn torus(major: f32, minor: f32, segs: usize, sides: usize) -> Mesh {
|
||||
let mut b = Builder::default();
|
||||
let (segs, sides) = (segs.max(3), sides.max(3));
|
||||
b.grid(sides, segs, |i, j| {
|
||||
let (u, v) = (j as f32 / segs as f32, i as f32 / sides as f32);
|
||||
let phi = u * TAU + PI * 1.5;
|
||||
let theta = v * TAU;
|
||||
let dir = Vec3::new(phi.cos(), 0.0, -phi.sin());
|
||||
let n = dir * theta.cos() - Vec3::Y * theta.sin();
|
||||
(dir * major + n * minor, n, Vec2::new(u, v))
|
||||
});
|
||||
b.finish("Torus")
|
||||
}
|
||||
|
||||
/// A subdivided plane facing +Y.
|
||||
pub fn plane(size: f32, subdivisions: usize) -> Mesh {
|
||||
let mut b = Builder::default();
|
||||
let s = subdivisions.max(1);
|
||||
b.grid(s, s, |i, j| {
|
||||
let (u, v) = (j as f32 / s as f32, i as f32 / s as f32);
|
||||
(Vec3::new((u - 0.5) * size, 0.0, (v - 0.5) * size), Vec3::Y, Vec2::new(u, v))
|
||||
});
|
||||
b.finish("Plane")
|
||||
}
|
||||
|
||||
/// Two planes side by side on UV tiles 1001 and 1002 (UDIM): one material, 4 × 2 units.
|
||||
pub fn udim_plane() -> Mesh {
|
||||
let mut m = plane(2.0, 16);
|
||||
let mut right = m.clone();
|
||||
for p in &mut m.positions {
|
||||
p.x -= 1.0;
|
||||
}
|
||||
for p in &mut right.positions {
|
||||
p.x += 1.0;
|
||||
}
|
||||
for uv in &mut right.uvs {
|
||||
uv.x += 1.0;
|
||||
}
|
||||
right.materials.clear();
|
||||
right.submeshes.clear();
|
||||
m.append(&right);
|
||||
let count = m.indices.len() as u32;
|
||||
if let Some(s) = m.submeshes.first_mut() {
|
||||
s.count = count;
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// The default project mesh: a ball on a beveled pedestal, two materials ("Ball", "Base").
|
||||
pub fn material_ball() -> Mesh {
|
||||
let mut ball = Builder::default();
|
||||
sphere_into(&mut ball, Vec3::new(0.0, 1.32, 0.0), 1.0, 128, 64, UvRect::FULL);
|
||||
let mut ball = ball.finish("Ball");
|
||||
|
||||
let mut base = Builder::default();
|
||||
let (r, top, bot, bev) = (1.05f32, 0.32f32, 0.0f32, 0.07f32);
|
||||
let mut profile = vec![(0.42, top + 0.06), (0.62, top + 0.06)];
|
||||
// Collar bevel and the ring the ball sits on, then the beveled drum.
|
||||
for k in 1..=6 {
|
||||
let a = k as f32 / 6.0 * PI * 0.5;
|
||||
profile.push((0.62 + 0.06 * a.sin(), top + 0.06 * a.cos()));
|
||||
}
|
||||
profile.push((r - bev, top));
|
||||
for k in 1..=6 {
|
||||
let a = k as f32 / 6.0 * PI * 0.5;
|
||||
profile.push((r - bev + bev * a.sin(), top - bev + bev * a.cos()));
|
||||
}
|
||||
profile.push((r, bot + bev));
|
||||
for k in 1..=6 {
|
||||
let a = k as f32 / 6.0 * PI * 0.5;
|
||||
profile.push((r - bev + bev * a.cos(), bot + bev - bev * a.sin()));
|
||||
}
|
||||
lathe_into(&mut base, Vec3::ZERO, &profile, 128, UvRect { o: Vec2::ZERO, s: Vec2::new(1.0, 0.5) }.inset(0.01));
|
||||
disk_into(&mut base, Vec3::new(0.0, top + 0.06, 0.0), 0.42, true, 128, UvRect { o: Vec2::new(0.0, 0.5), s: Vec2::splat(0.5) }.inset(0.01));
|
||||
disk_into(&mut base, Vec3::new(0.0, bot, 0.0), r - bev, false, 128, UvRect { o: Vec2::new(0.5, 0.5), s: Vec2::splat(0.5) }.inset(0.01));
|
||||
let base = base.finish("Base");
|
||||
ball.append(&base);
|
||||
ball
|
||||
}
|
||||
|
||||
/// A small showcase scene: a beveled crate with a rounded lid and a cylinder handle, in three
|
||||
/// materials (used for demo projects and tests of multiple texture sets).
|
||||
pub fn crate_scene() -> Mesh {
|
||||
let mut body = Builder::default();
|
||||
rounded_box_into(&mut body, Vec3::new(0.0, 0.8, 0.0), Vec3::new(1.2, 0.8, 0.8), 0.12, UvRect::FULL);
|
||||
let mut m = body.finish("Crate");
|
||||
let mut lid = Builder::default();
|
||||
rounded_box_into(&mut lid, Vec3::new(0.0, 1.72, 0.0), Vec3::new(1.28, 0.12, 0.88), 0.08, UvRect::FULL);
|
||||
m.append(&lid.finish("Lid"));
|
||||
let mut handle = torus(0.32, 0.07, 64, 24);
|
||||
for p in &mut handle.positions {
|
||||
*p = Vec3::new(p.x, p.z, -p.y) + Vec3::new(0.0, 1.84, 0.0);
|
||||
}
|
||||
for n in &mut handle.normals {
|
||||
*n = Vec3::new(n.x, n.z, -n.y);
|
||||
}
|
||||
handle.materials = vec!["Handle".into()];
|
||||
if let Some(s) = handle.submeshes.first_mut() {
|
||||
s.name = "Handle".into();
|
||||
}
|
||||
handle.compute_tangents();
|
||||
m.append(&handle);
|
||||
m
|
||||
}
|
||||
|
||||
/// Built-in mesh by id (`builtin:<id>` in project files).
|
||||
pub fn builtin(id: &str) -> Option<Mesh> {
|
||||
Some(match id {
|
||||
"material_ball" | "materialball" | "ball" => material_ball(),
|
||||
"sphere" => sphere(1.0, 128, 64),
|
||||
"cube" => cube(2.0).ok()?,
|
||||
"rounded_cube" | "roundedcube" | "box" => rounded_box(Vec3::ONE, 0.15).ok()?,
|
||||
"cylinder" => cylinder(1.0, 2.0, 96),
|
||||
"torus" => torus(1.0, 0.35, 128, 48),
|
||||
"plane" => plane(2.0, 16),
|
||||
"crate" => crate_scene(),
|
||||
"udim_plane" | "udimplane" => udim_plane(),
|
||||
// Not offered for new projects (not in BUILTINS): the smart mask preview session's mesh
|
||||
"preview_orb" => preview_orb(),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Ids accepted by [`builtin`], in menu order.
|
||||
pub const BUILTINS: [(&str, &str); 9] = [
|
||||
("material_ball", "Material ball"),
|
||||
("sphere", "Sphere"),
|
||||
("cube", "Cube"),
|
||||
("rounded_cube", "Rounded cube"),
|
||||
("cylinder", "Cylinder"),
|
||||
("torus", "Torus"),
|
||||
("plane", "Plane"),
|
||||
("crate", "Crate"),
|
||||
("udim_plane", "UDIM plane"),
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn invalid_cube_dimensions_do_not_panic() {
|
||||
for size in [-1.0, 0.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
|
||||
let result = std::panic::catch_unwind(|| cube(size));
|
||||
assert!(result.is_ok(), "cube({size}) panicked");
|
||||
assert!(result.unwrap().is_err(), "cube({size}) must reject invalid dimensions");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_rounded_box_dimensions_do_not_panic() {
|
||||
for axis in 0..3 {
|
||||
for value in [-1.0, 0.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX] {
|
||||
let mut half = Vec3::ONE;
|
||||
half[axis] = value;
|
||||
let result = std::panic::catch_unwind(|| rounded_box(half, 0.0));
|
||||
assert!(result.is_ok(), "rounded_box({half:?}) panicked");
|
||||
assert!(result.unwrap().is_err(), "rounded_box({half:?}) must reject invalid dimensions");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_box_bevels_are_rejected_instead_of_clamped() {
|
||||
for bevel in [-1.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.950001] {
|
||||
assert!(rounded_box(Vec3::ONE, bevel).is_err(), "{bevel}");
|
||||
}
|
||||
for bevel in [0.0, 0.95] {
|
||||
assert!(rounded_box(Vec3::ONE, bevel).is_ok(), "{bevel}");
|
||||
}
|
||||
assert!(cube(2.0).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_finite_box_extents_keep_generated_positions_finite() {
|
||||
let mesh = rounded_box(Vec3::new(1e38, 1.0, 1.0), 0.0).unwrap();
|
||||
assert!(mesh.positions.iter().all(|p| p.is_finite()));
|
||||
}
|
||||
|
||||
/// Every triangle's winding agrees with its vertex normals, UVs stay in 0..1 (u in 0..max_u),
|
||||
/// and the UV mapping is not mirrored (tangent handedness +1).
|
||||
fn check(m: &Mesh, max_u: f32) {
|
||||
m.validate().unwrap();
|
||||
let mut bad = 0;
|
||||
for t in 0..m.triangle_count() {
|
||||
let [a, b, c] = m.tri(t).unwrap();
|
||||
let face = (m.positions[b] - m.positions[a]).cross(m.positions[c] - m.positions[a]);
|
||||
if face.length() < 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let n = m.normals[a] + m.normals[b] + m.normals[c];
|
||||
if face.dot(n) <= 0.0 {
|
||||
bad += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(bad, 0, "{} triangles wound against their normals", bad);
|
||||
for uv in &m.uvs {
|
||||
assert!((0.0..=max_u).contains(&uv.x) && (0.0..=1.0).contains(&uv.y), "{uv:?}");
|
||||
}
|
||||
let mirrored = m.tangents.iter().filter(|t| t.w < 0.0).count();
|
||||
assert!(mirrored * 50 < m.tangents.len().max(1), "{mirrored} mirrored tangents");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn primitives_are_well_formed() {
|
||||
for (id, _) in BUILTINS {
|
||||
let m = builtin(id).unwrap();
|
||||
assert!(m.triangle_count() > 0, "{id}");
|
||||
check(&m, if id == "udim_plane" { 2.0 } else { 1.0 });
|
||||
}
|
||||
assert!(builtin("nope").is_none());
|
||||
assert_eq!(udim_plane().uv_tiles(0).into_iter().collect::<Vec<_>>(), vec![(0, 0), (1, 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_orb_is_well_formed_with_domed_panels() {
|
||||
let m = preview_orb();
|
||||
check(&m, 1.0);
|
||||
|
||||
// Above the middle slot, the front panel's dome rises past the cut face and its valley
|
||||
// sits below it
|
||||
let front_depth = |rho: f32| {
|
||||
let d = Vec3::new(0.0, rho, 1.0).normalize();
|
||||
preview_orb_radius(d) * d.z
|
||||
};
|
||||
let rim = (1.0 - ORB_CUT * ORB_CUT).sqrt() / ORB_CUT;
|
||||
let (dome, valley) = (front_depth(0.2), front_depth(rim * ORB_PANEL_VALLEY));
|
||||
assert!(dome > ORB_CUT && valley < ORB_CUT - 0.05, "dome {dome}, valley {valley}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn material_ball_has_two_materials() {
|
||||
let m = material_ball();
|
||||
assert_eq!(m.materials, vec!["Ball".to_string(), "Base".to_string()]);
|
||||
assert!(m.triangles_of(0).count() > 0 && m.triangles_of(1).count() > 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
//! Automatic UV unwrapping for meshes imported without texture coordinates.
|
||||
//!
|
||||
//! Triangles are grouped into charts by flood fill across shared (welded) edges while each face
|
||||
//! normal stays within 60° of the chart's seed face, so every chart is a height field over its
|
||||
//! seed plane and projects onto it without flipping. Charts are rotated to their principal axes
|
||||
//! and shelf-packed per material into 0..1 with one uniform scale, so texel density is the same
|
||||
//! everywhere within a material.
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
use glam::{Vec2, Vec3};
|
||||
|
||||
use crate::{GeomError, Mesh, Result};
|
||||
|
||||
/// Faces of a chart stay within this angle of the seed face normal (cos 60°).
|
||||
const CHART_COS: f32 = 0.5;
|
||||
/// Packing never goes beyond this virtual resolution (texels per side).
|
||||
const MAX_PACK_RES: f32 = 65_536.0;
|
||||
|
||||
/// Welded vertex id per vertex: vertices at the same position (snapped to a grid of 1e-6 of
|
||||
/// the bounding diagonal) share an id. Ids are dense, in order of first appearance.
|
||||
pub fn weld_ids(positions: &[Vec3]) -> Vec<u32> {
|
||||
let (lo, hi) = positions.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p)));
|
||||
let cell = ((hi - lo).length() * 1e-6).max(1e-12);
|
||||
let mut map: HashMap<[i64; 3], u32> = HashMap::with_capacity(positions.len());
|
||||
positions
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let q = ((*p - lo) / cell).round();
|
||||
let next = map.len() as u32;
|
||||
*map.entry([q.x as i64, q.y as i64, q.z as i64]).or_insert(next)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// True when the mesh has triangles and every one of them has two corners at the same position.
|
||||
/// MikkTSpace (and so [`Mesh::compute_tangents`]) crashes on such meshes, so callers reject them.
|
||||
pub fn all_triangles_degenerate(mesh: &Mesh) -> bool {
|
||||
let p = |i: &u32| mesh.positions.get(*i as usize);
|
||||
!mesh.indices.is_empty()
|
||||
&& mesh.indices.chunks(3).all(|t| match t {
|
||||
[a, b, c] => p(a) == p(b) || p(a) == p(c) || p(b) == p(c),
|
||||
_ => true,
|
||||
})
|
||||
}
|
||||
|
||||
struct Chart {
|
||||
material: usize,
|
||||
/// Projection basis (right-handed with the seed normal).
|
||||
t: Vec3,
|
||||
b: Vec3,
|
||||
/// Rotation to the chart's principal axes (cos, sin).
|
||||
rot: Vec2,
|
||||
lo: Vec2,
|
||||
hi: Vec2,
|
||||
/// Texel offset of the chart's packed rectangle and the material's scale and resolution.
|
||||
offset: Vec2,
|
||||
}
|
||||
|
||||
impl Chart {
|
||||
fn local(&self, p: Vec3) -> Vec2 {
|
||||
let q = Vec2::new(p.dot(self.t), p.dot(self.b));
|
||||
Vec2::new(q.x * self.rot.x - q.y * self.rot.y, q.x * self.rot.y + q.y * self.rot.x)
|
||||
}
|
||||
fn size(&self) -> Vec2 {
|
||||
(self.hi - self.lo).max(Vec2::ZERO)
|
||||
}
|
||||
}
|
||||
|
||||
/// The material each triangle is unwrapped for; triangles in no submesh count as material 0. Returns an error when submeshes of two
|
||||
/// materials share a triangle.
|
||||
fn triangle_materials(mesh: &Mesh) -> Result<Vec<usize>> {
|
||||
let mut material = vec![None; mesh.triangle_count()];
|
||||
for s in &mesh.submeshes {
|
||||
for t in (s.start / 3) as usize..((s.start as usize + s.count as usize) / 3) {
|
||||
if let Some(m) = material.get_mut(t) {
|
||||
if let Some(other) = *m
|
||||
&& other != s.material
|
||||
{
|
||||
return Err(GeomError::Invalid(format!("triangle {t} is in submeshes of materials {other} and {}", s.material)));
|
||||
}
|
||||
*m = Some(s.material);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(material.into_iter().map(|m| m.unwrap_or(0)).collect())
|
||||
}
|
||||
|
||||
/// Replace the UVs of `mesh` with an automatic non-overlapping layout: each material gets its
|
||||
/// own 0..1 space with charts at least `padding_texels` (minimum 1) away from each other and
|
||||
/// the borders at `resolution`. Vertices are split at chart borders; tangents are recomputed.
|
||||
/// Returns the number of charts, or an error, before any change to the mesh, when submeshes of
|
||||
/// two materials share a triangle.
|
||||
pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Result<usize> {
|
||||
mesh.validate_indices()?;
|
||||
if all_triangles_degenerate(mesh) {
|
||||
return Err(GeomError::Invalid("every triangle of the mesh is degenerate".into()));
|
||||
}
|
||||
let material = triangle_materials(mesh)?;
|
||||
if mesh.normals.len() != mesh.positions.len() {
|
||||
mesh.compute_normals();
|
||||
}
|
||||
let n = mesh.triangle_count();
|
||||
let weld = weld_ids(&mesh.positions);
|
||||
let pos = |v: usize| mesh.positions.get(v).copied().unwrap_or_default();
|
||||
let wid = |v: usize| weld.get(v).copied().unwrap_or(u32::MAX);
|
||||
|
||||
// Face normals (None for degenerate faces) and materials.
|
||||
let mut normal: Vec<Option<Vec3>> = Vec::with_capacity(n);
|
||||
let mut area = Vec::with_capacity(n);
|
||||
for t in 0..n {
|
||||
let [a, b, c] = mesh.tri(t).unwrap_or([0; 3]);
|
||||
let cr = (pos(b) - pos(a)).cross(pos(c) - pos(a));
|
||||
area.push(cr.length() * 0.5);
|
||||
normal.push(cr.try_normalize());
|
||||
}
|
||||
|
||||
// Manifold edge adjacency over welded vertices: edge → (face, face, count).
|
||||
let mut edges: HashMap<(u32, u32), (u32, u32, u8)> = HashMap::with_capacity(n * 2);
|
||||
let tri_edges = |t: usize| -> [(u32, u32); 3] {
|
||||
let [a, b, c] = mesh.tri(t).unwrap_or([0; 3]);
|
||||
let key = |x: usize, y: usize| {
|
||||
let (p, q) = (wid(x), wid(y));
|
||||
(p.min(q), p.max(q))
|
||||
};
|
||||
[key(a, b), key(b, c), key(c, a)]
|
||||
};
|
||||
for t in 0..n {
|
||||
for e in tri_edges(t) {
|
||||
if e.0 == e.1 {
|
||||
continue;
|
||||
}
|
||||
let slot = edges.entry(e).or_insert((t as u32, u32::MAX, 0));
|
||||
if slot.2 == 1 {
|
||||
slot.1 = t as u32;
|
||||
}
|
||||
slot.2 = slot.2.saturating_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Grow charts from the largest unassigned faces.
|
||||
let mut order: Vec<usize> = (0..n).collect();
|
||||
order.sort_by(|a, b| area[*b].total_cmp(&area[*a]));
|
||||
let mut chart_of = vec![u32::MAX; n];
|
||||
let mut charts: Vec<Chart> = Vec::new();
|
||||
let mut queue = VecDeque::new();
|
||||
for &seed in &order {
|
||||
if chart_of[seed] != u32::MAX {
|
||||
continue;
|
||||
}
|
||||
let id = charts.len() as u32;
|
||||
let sn = normal[seed].unwrap_or(Vec3::Z);
|
||||
let t = sn.any_orthonormal_vector();
|
||||
charts.push(Chart { material: material[seed], t, b: sn.cross(t), rot: Vec2::X, lo: Vec2::ZERO, hi: Vec2::ZERO, offset: Vec2::ZERO });
|
||||
chart_of[seed] = id;
|
||||
queue.push_back(seed);
|
||||
while let Some(f) = queue.pop_front() {
|
||||
for e in tri_edges(f) {
|
||||
let Some(&(f0, f1, 2)) = edges.get(&e) else { continue };
|
||||
let g = if f0 as usize == f { f1 } else { f0 } as usize;
|
||||
let ok = normal.get(g).is_some_and(|nn| nn.is_none_or(|nn| nn.dot(sn) >= CHART_COS));
|
||||
if ok && chart_of.get(g) == Some(&u32::MAX) && material.get(g) == Some(&material[seed]) {
|
||||
chart_of[g] = id;
|
||||
queue.push_back(g);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Principal axes and bounds of every chart.
|
||||
let mut cov = vec![(Vec2::ZERO, [0.0f64; 3], 0usize); charts.len()];
|
||||
for (t, &c) in chart_of.iter().enumerate() {
|
||||
let c = c as usize;
|
||||
for v in mesh.tri(t).unwrap_or([0; 3]) {
|
||||
if let (Some(ch), Some(acc)) = (charts.get(c), cov.get_mut(c)) {
|
||||
let q = ch.local(pos(v));
|
||||
acc.0 += q;
|
||||
acc.1[0] += (q.x * q.x) as f64;
|
||||
acc.1[1] += (q.y * q.y) as f64;
|
||||
acc.1[2] += (q.x * q.y) as f64;
|
||||
acc.2 += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (ch, (sum, m, k)) in charts.iter_mut().zip(&cov) {
|
||||
let k = (*k).max(1) as f64;
|
||||
let (mx, my) = (sum.x as f64 / k, sum.y as f64 / k);
|
||||
let (cxx, cyy, cxy) = (m[0] / k - mx * mx, m[1] / k - my * my, m[2] / k - mx * my);
|
||||
let angle = 0.5 * (2.0 * cxy).atan2(cxx - cyy);
|
||||
// Rotate so the principal axis lies along x.
|
||||
ch.rot = Vec2::new((-angle).cos() as f32, (-angle).sin() as f32);
|
||||
ch.lo = Vec2::splat(f32::MAX);
|
||||
ch.hi = Vec2::splat(f32::MIN);
|
||||
}
|
||||
for (t, &c) in chart_of.iter().enumerate() {
|
||||
let c = c as usize;
|
||||
for v in mesh.tri(t).unwrap_or([0; 3]) {
|
||||
if let Some(ch) = charts.get_mut(c) {
|
||||
let q = ch.local(pos(v));
|
||||
ch.lo = ch.lo.min(q);
|
||||
ch.hi = ch.hi.max(q);
|
||||
}
|
||||
}
|
||||
}
|
||||
for ch in &mut charts {
|
||||
if ch.size().y > ch.size().x {
|
||||
// Quarter turn (x, y) → (y, −x) so shelves stay low.
|
||||
ch.rot = Vec2::new(ch.rot.y, -ch.rot.x);
|
||||
let (lo, hi) = (ch.lo, ch.hi);
|
||||
ch.lo = Vec2::new(lo.y, -hi.x);
|
||||
ch.hi = Vec2::new(hi.y, -lo.x);
|
||||
}
|
||||
}
|
||||
|
||||
// Pack each material's charts into its own 0..1 square.
|
||||
let pad = padding_texels.max(1.0);
|
||||
let mut scale = HashMap::new();
|
||||
let mats: std::collections::BTreeSet<usize> = charts.iter().map(|c| c.material).collect();
|
||||
for m in mats {
|
||||
let ids: Vec<usize> = (0..charts.len()).filter(|i| charts[*i].material == m).collect();
|
||||
let sizes: Vec<Vec2> = ids.iter().map(|i| charts[*i].size()).collect();
|
||||
let (s, res, offsets) = pack(&sizes, resolution.max(16) as f32, pad)?;
|
||||
for (i, o) in ids.iter().zip(offsets) {
|
||||
charts[*i].offset = o;
|
||||
}
|
||||
scale.insert(m, (s, res));
|
||||
}
|
||||
|
||||
// Rebuild vertices: one per (vertex, chart).
|
||||
let mut remap: HashMap<(u32, u32), u32> = HashMap::with_capacity(mesh.positions.len() * 2);
|
||||
let (mut positions, mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
|
||||
let mut indices = Vec::with_capacity(mesh.indices.len());
|
||||
for (t, &c) in chart_of.iter().enumerate() {
|
||||
let Some(ch) = charts.get(c as usize) else { continue };
|
||||
let (s, res) = scale.get(&ch.material).copied().unwrap_or((0.0, 1.0));
|
||||
for v in mesh.tri(t).unwrap_or([0; 3]) {
|
||||
let idx = *remap.entry((v as u32, c)).or_insert_with(|| {
|
||||
let q = ch.local(pos(v));
|
||||
// Chart y points up; UV v points down the image.
|
||||
let texel = ch.offset + Vec2::splat(pad) + Vec2::new(q.x - ch.lo.x, ch.hi.y - q.y) * s;
|
||||
positions.push(pos(v));
|
||||
normals.push(mesh.normals.get(v).copied().unwrap_or(Vec3::Y));
|
||||
if let Some(c) = mesh.colors.get(v) {
|
||||
colors.push(*c);
|
||||
}
|
||||
uvs.push((texel / res).clamp(Vec2::ZERO, Vec2::ONE));
|
||||
(positions.len() - 1) as u32
|
||||
});
|
||||
indices.push(idx);
|
||||
}
|
||||
}
|
||||
mesh.positions = positions;
|
||||
mesh.normals = normals;
|
||||
mesh.uvs = uvs;
|
||||
mesh.colors = colors;
|
||||
mesh.indices = indices;
|
||||
mesh.compute_tangents();
|
||||
mesh.validate()?;
|
||||
Ok(charts.len())
|
||||
}
|
||||
|
||||
/// Shelf-pack rectangles of world `sizes` (each grown by `pad` texels per side) into a square of
|
||||
/// `res` texels with the largest uniform scale that fits. Returns (texels per world unit,
|
||||
/// resolution used, texel offset per rectangle). The resolution doubles when the padding alone
|
||||
/// cannot fit (very many charts), so the result always fits in 0..1.
|
||||
fn pack(sizes: &[Vec2], mut res: f32, pad: f32) -> Result<(f32, f32, Vec<Vec2>)> {
|
||||
let mut order: Vec<usize> = (0..sizes.len()).collect();
|
||||
order.sort_by(|a, b| sizes[*b].y.total_cmp(&sizes[*a].y));
|
||||
let place = |s: f32, res: f32| -> Option<Vec<Vec2>> {
|
||||
let mut out = vec![Vec2::ZERO; sizes.len()];
|
||||
let (mut x, mut y, mut shelf) = (0.0f32, 0.0f32, 0.0f32);
|
||||
for &i in &order {
|
||||
let r = sizes[i] * s + Vec2::splat(2.0 * pad);
|
||||
if r.x > res {
|
||||
return None;
|
||||
}
|
||||
if x + r.x > res {
|
||||
y += shelf;
|
||||
x = 0.0;
|
||||
shelf = 0.0;
|
||||
}
|
||||
if y + r.y > res {
|
||||
return None;
|
||||
}
|
||||
out[i] = Vec2::new(x, y);
|
||||
x += r.x;
|
||||
shelf = shelf.max(r.y);
|
||||
}
|
||||
Some(out)
|
||||
};
|
||||
while place(0.0, res).is_none() {
|
||||
res *= 2.0;
|
||||
if res > MAX_PACK_RES {
|
||||
return Err(GeomError::Invalid("too many UV charts to pack".into()));
|
||||
}
|
||||
}
|
||||
let largest = sizes.iter().map(|s| s.max_element()).fold(0.0f32, f32::max);
|
||||
if largest <= 0.0 {
|
||||
return Ok((0.0, res, place(0.0, res).unwrap_or_default()));
|
||||
}
|
||||
let (mut lo, mut hi) = (0.0f32, (res - 2.0 * pad).max(0.0) / largest);
|
||||
if place(hi, res).is_some() {
|
||||
lo = hi;
|
||||
}
|
||||
for _ in 0..40 {
|
||||
if hi - lo <= lo * 1e-4 {
|
||||
break;
|
||||
}
|
||||
let mid = 0.5 * (lo + hi);
|
||||
if place(mid, res).is_some() { lo = mid } else { hi = mid }
|
||||
}
|
||||
Ok((lo, res, place(lo, res).unwrap_or_default()))
|
||||
}
|
||||
|
||||
impl Mesh {
|
||||
/// Index-range checks only (attribute arrays may be incomplete before unwrapping).
|
||||
fn validate_indices(&self) -> Result<()> {
|
||||
let n = self.positions.len();
|
||||
if !self.indices.len().is_multiple_of(3) || self.indices.iter().any(|i| *i as usize >= n) {
|
||||
return Err(GeomError::Invalid("mesh indices are out of range".into()));
|
||||
}
|
||||
if self.triangle_count() > crate::MAX_TRIANGLES {
|
||||
return Err(GeomError::Invalid(format!("mesh has more than {} triangles", crate::MAX_TRIANGLES)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{UvGBuffer, primitives};
|
||||
|
||||
fn check(mut m: Mesh, min_coverage: f32) {
|
||||
m.uvs.clear();
|
||||
let charts = auto_unwrap(&mut m, 4.0, 512).unwrap();
|
||||
assert!(charts >= 1);
|
||||
m.validate().unwrap();
|
||||
assert!(m.uvs.iter().all(|uv| (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y)));
|
||||
let g = UvGBuffer::new(&m, 0, 512, 512).unwrap();
|
||||
let covered = g.covered_count() as f32;
|
||||
let coverage = covered / (512.0 * 512.0);
|
||||
assert!(coverage > min_coverage, "coverage {coverage} with {charts} charts");
|
||||
assert!((g.overlaps as f32) < covered * 0.005, "overlaps {} of {covered}", g.overlaps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sphere_unwraps_without_overlaps() {
|
||||
check(primitives::sphere(1.0, 48, 24), 0.3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cube_unwraps_without_overlaps() {
|
||||
check(primitives::cube(2.0).unwrap(), 0.3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn torus_and_material_ball_unwrap() {
|
||||
check(primitives::torus(1.0, 0.3, 48, 24), 0.2);
|
||||
let mut ball = primitives::material_ball();
|
||||
ball.uvs.clear();
|
||||
auto_unwrap(&mut ball, 2.0, 1024).unwrap();
|
||||
for m in 0..ball.materials.len() {
|
||||
let g = UvGBuffer::new(&ball, m, 512, 512).unwrap();
|
||||
assert!((g.overlaps as f32) < g.covered_count() as f32 * 0.005 + 1.0, "material {m}: {} overlaps", g.overlaps);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn triangles_in_two_materials_are_rejected_unchanged() {
|
||||
// Two congruent triangles in material 0; material 1 also lists the first.
|
||||
let p = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z * 5.0, Vec3::Z * 5.0 + Vec3::X, Vec3::Z * 5.0 + Vec3::Y];
|
||||
let mut m = Mesh::from_parts(p, None, Vec::new(), vec![0, 1, 2, 3, 4, 5], "a").unwrap();
|
||||
m.materials.push("b".into());
|
||||
m.submeshes.push(crate::SubMesh { name: "b".into(), material: 1, start: 0, count: 3 });
|
||||
let before = m.clone();
|
||||
assert!(auto_unwrap(&mut m, 2.0, 64).is_err());
|
||||
assert_eq!(m, before);
|
||||
// The same material listed twice is not a conflict.
|
||||
m.submeshes[1].material = 0;
|
||||
assert_eq!(auto_unwrap(&mut m, 2.0, 64).unwrap(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_tiny_charts_still_fit() {
|
||||
// 2000 disconnected triangles: the packer grows its virtual resolution.
|
||||
let mut p = Vec::new();
|
||||
let mut idx = Vec::new();
|
||||
for i in 0..2000u32 {
|
||||
let o = Vec3::new(i as f32 * 3.0, 0.0, 0.0);
|
||||
p.extend([o, o + Vec3::X, o + Vec3::Y]);
|
||||
idx.extend([i * 3, i * 3 + 1, i * 3 + 2]);
|
||||
}
|
||||
let mut m = Mesh::from_parts(p, None, Vec::new(), idx, "m").unwrap();
|
||||
auto_unwrap(&mut m, 4.0, 128).unwrap();
|
||||
assert!(m.uvs.iter().all(|uv| (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn degenerate_and_empty_meshes_do_not_fail() {
|
||||
let mut empty = Mesh::default();
|
||||
assert_eq!(auto_unwrap(&mut empty, 4.0, 256).unwrap(), 0);
|
||||
// A sliver (zero-area) triangle next to a real one.
|
||||
let p = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::X * 2.0];
|
||||
let mut m = Mesh::from_parts(p, None, Vec::new(), vec![0, 1, 2, 0, 1, 3], "m").unwrap();
|
||||
auto_unwrap(&mut m, 4.0, 256).unwrap();
|
||||
m.validate().unwrap();
|
||||
let mut point = Mesh { positions: vec![Vec3::ONE; 3], indices: vec![0, 1, 2], ..Mesh::default() };
|
||||
assert!(all_triangles_degenerate(&point));
|
||||
assert!(auto_unwrap(&mut point, 4.0, 256).is_err());
|
||||
}
|
||||
}
|
||||
@@ -52,8 +52,8 @@ pub use reading::{ReadingNav, ReadingNavOutput, ReadingState, ReadingView, Readi
|
||||
pub use setup::{PageLayoutChoice, PageLayoutMenus, PageSetupDialog};
|
||||
pub use sync_views::{Lead, SyncedViews, SyncedViewsOutput, SyncedViewsState};
|
||||
pub use table::{
|
||||
BorderEdges, BorderPreset, CellAlign, CellSelectionOverlay, EdgeKey, EdgeLook, EdgePicker, RowHeight, SampleArea, TableChange, TableGeometry,
|
||||
TableProperties, TablePropertiesOutput, TableSizePicker, TableSizePickerOutput, TableValues, TextDirection,
|
||||
BorderEdges, BorderPreset, CellAlign, CellSelectionOverlay, EdgeKey, EdgeLook, EdgePicker, EdgeSize, RowHeight, SampleArea, TableChange,
|
||||
TableGeometry, TableProperties, TablePropertiesOutput, TableSizePicker, TableSizePickerOutput, TableValues, TextDirection,
|
||||
};
|
||||
pub use text_selection::{
|
||||
MarkArea, MarkKind, PageTextSource, PageTexts, TextMark, TextMarks, TextSelectState, TextSelectTool, TextSelection, TextSpan,
|
||||
|
||||
@@ -163,6 +163,8 @@ pub struct EdgePickerStyle {
|
||||
focus: FocusLook,
|
||||
/// The side of the square.
|
||||
side: f32,
|
||||
/// The side of the square at [`EdgeSize::Sample`].
|
||||
sample_side: f32,
|
||||
/// How far the outer lines sit inside the square, and how near a line the pointer picks it.
|
||||
inset: f32,
|
||||
/// The area inside the lines.
|
||||
@@ -198,6 +200,20 @@ pub struct EdgePicker<'a> {
|
||||
/// How the picture is drawn: the proxy diagram, or a sample of the borders on text, a paragraph or a page.
|
||||
#[prop]
|
||||
look: EdgeLook,
|
||||
/// The extent of the square: a thumbnail, or a sample-sized preview.
|
||||
#[prop]
|
||||
preview: EdgeSize,
|
||||
}
|
||||
|
||||
/// How large the picker's square is.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum EdgeSize {
|
||||
/// A thumbnail (`size.thumb.lg`).
|
||||
#[default]
|
||||
Thumb,
|
||||
/// A preview at sample size (`size.thumb.sample.lg`), for a Borders or Shading dialog's page-like preview.
|
||||
Sample,
|
||||
}
|
||||
|
||||
/// How the borders preview is drawn.
|
||||
@@ -246,7 +262,7 @@ struct ClickRun {
|
||||
impl<'a> EdgePicker<'a> {
|
||||
/// A picker named `label` editing `edges`.
|
||||
pub fn new(label: impl Into<Label>, edges: Bind<'a, BorderEdges>) -> Self {
|
||||
EdgePicker { common: Common::new(), edges, paragraph: false, look: EdgeLook::default() }.label(label).ltr_axis()
|
||||
EdgePicker { common: Common::new(), edges, paragraph: false, look: EdgeLook::default(), preview: EdgeSize::default() }.label(label).ltr_axis()
|
||||
}
|
||||
|
||||
/// The name of `edge`.
|
||||
@@ -353,6 +369,7 @@ impl Component for EdgePicker<'_> {
|
||||
.border(edge, cx.tokens.stroke.thin),
|
||||
focus: cx.focus_look(),
|
||||
side: cx.tokens.size.thumb.lg,
|
||||
sample_side: cx.tokens.size.thumb.sample.lg,
|
||||
inset: cx.tokens.space.pad.regular,
|
||||
fill: cx.color(colors.surface.sunken),
|
||||
on: Stateful::new(cx.color(colors.accent.solid)),
|
||||
@@ -361,7 +378,10 @@ impl Component for EdgePicker<'_> {
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::splat(cx.style.side)
|
||||
Vec2::splat(match self.preview {
|
||||
EdgeSize::Thumb => cx.style.side,
|
||||
EdgeSize::Sample => cx.style.sample_side,
|
||||
})
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
|
||||
@@ -9,7 +9,7 @@ pub mod size_picker;
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) mod stories;
|
||||
|
||||
pub use edges::{BorderEdges, BorderPreset, EdgeKey, EdgeLook, EdgePicker, EdgePickerStyle, EdgePickerWords, SampleArea};
|
||||
pub use edges::{BorderEdges, BorderPreset, EdgeKey, EdgeLook, EdgePicker, EdgePickerStyle, EdgePickerWords, EdgeSize, SampleArea};
|
||||
pub use properties::{CellAlign, RowHeight, TableChange, TableProperties, TablePropertiesOutput, TablePropertiesWords, TableValues, TextDirection};
|
||||
pub use selection::{CellSelectionOverlay, CellSelectionStyle, TableGeometry};
|
||||
pub use size_picker::{TableSizePicker, TableSizePickerOutput, TableSizePickerStyle, TableSizePickerWords};
|
||||
@@ -25,3 +25,22 @@ fn right_at_a_row_end_goes_on_to_the_next_row() {
|
||||
fixture.key(Key::ArrowRight, Modifiers::NONE).idle(2);
|
||||
assert_eq!(hovered.get(), Some((2, 1)), "Right wraps to the next row");
|
||||
}
|
||||
|
||||
/// A picker asked for sample size draws a larger square than the default thumbnail.
|
||||
#[trial]
|
||||
fn edge_picker_sample_size_is_larger_than_the_thumbnail() {
|
||||
use craft_pages::ui::table::{BorderEdges, EdgePicker, EdgeSize};
|
||||
use craft_ui::contract::Bind;
|
||||
let sides = Rc::new(Cell::new((0.0, 0.0)));
|
||||
let seen = sides.clone();
|
||||
let mut edges = BorderEdges::default();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let thumb = EdgePicker::new("Thumb", Bind::bound(&mut edges)).show(ui).response.rect.width();
|
||||
let mut other = BorderEdges::default();
|
||||
let sample = EdgePicker::new("Sample", Bind::bound(&mut other)).preview(EdgeSize::Sample).show(ui).response.rect.width();
|
||||
seen.set((thumb, sample));
|
||||
});
|
||||
fixture.settle();
|
||||
let (thumb, sample) = sides.get();
|
||||
assert!(thumb > 0.0 && sample > thumb, "thumb {thumb}, sample {sample}");
|
||||
}
|
||||
@@ -10,16 +10,25 @@ repository.workspace = true
|
||||
[features]
|
||||
default = []
|
||||
parallel = ["dep:rayon"]
|
||||
# The conversion from craft-mesh's glTF metallic-roughness material.
|
||||
mesh = ["dep:craft-mesh"]
|
||||
# The conversion from craft-materialx's resolved shader inputs.
|
||||
materialx = ["dep:craft-materialx"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-materialx = { workspace = true, optional = true }
|
||||
craft-mesh = { path = "../mesh", default-features = false, optional = true }
|
||||
craft-texture = { workspace = true }
|
||||
rayon = { workspace = true, optional = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
craft-materialx = { workspace = true }
|
||||
craft-mesh = { path = "../mesh", default-features = false }
|
||||
craft-pbr = { path = ".", features = ["parallel", "mesh", "materialx"] }
|
||||
# The differential tests run verbatim copies of the apps' previous code, which uses glam and rayon.
|
||||
glam = "0.30"
|
||||
# Parses and validates the WGSL text of `SHADE_WGSL`.
|
||||
|
||||
+41
-2
@@ -109,8 +109,47 @@ It has no UI, does no file or network I/O and has no `unsafe` code.
|
||||
`PbrError::BadDirection`.
|
||||
After size and byte checks pass, a filtering work count above `u64::MAX` returns
|
||||
`PbrError::BadOption`, including when `max_work` is `u64::MAX`. `hammersley` returns coordinates in `0..1`.
|
||||
- **Features.** `parallel` computes rows on several threads with rayon. The default build is
|
||||
serial and builds for `wasm32-unknown-unknown`. Results are the same either way.
|
||||
- **Surfaces.** A `Surface` holds a `Material` and the state a renderer applies around it: alpha
|
||||
and `AlphaMode`, linear emission, the double-sided and unlit flags, optional `Clearcoat` and
|
||||
`Sheen` layers, `TextureBinding`s (the image or file, UV set, wrap modes, UV transform, encoding
|
||||
and a scale) and `other_inputs`. Textures are not loaded. `try_direct` shades only the
|
||||
`Material`; the layers, textures and other inputs are kept for a renderer that shades them, and
|
||||
an unlit surface shows its base color without lighting.
|
||||
- **Conversions.** `try_from_mesh` (feature `mesh`) converts a `craft_mesh::Material` and
|
||||
`try_from_materialx` (feature `materialx`) converts the `craft_materialx::StrictMaterial` that
|
||||
`Document::read_material_strict` reads. Each returns
|
||||
a `Conversion`: the `Surface` and a `ConversionReport` that lists what was kept without being
|
||||
shaded, what was approximated and how, what was dropped and why, and the MaterialX reader's
|
||||
warnings. No value is clamped: one that is not finite, is out of its range or has the wrong
|
||||
number of components gives a `ConvertError` naming the source field.
|
||||
- From craft-mesh, the glTF 2.0 metallic-roughness material
|
||||
(<https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#materials>): base color, alpha,
|
||||
metallic, roughness, emissive, alpha mode and cutoff, double-sided and unlit map as they are.
|
||||
Every texture is kept with its UV state; base color, emissive and sheen color textures are
|
||||
sRGB and the others linear. Clearcoat (`KHR_materials_clearcoat`) and sheen
|
||||
(`KHR_materials_sheen`) are kept when on; a clearcoat factor of 0 or a black sheen color turns
|
||||
the layer off, and its textures are dropped.
|
||||
- From MaterialX, OpenPBR Surface, Standard Surface and glTF PBR inputs take the defaults of
|
||||
their node definitions when absent
|
||||
(<https://github.com/AcademySoftwareFoundation/MaterialX/tree/main/libraries/bxdf>). The base
|
||||
color is multiplied by the base weight, the specular weight becomes the weight times
|
||||
`((ior − 1) / (ior + 1))² / 0.04` (at most `MAX_SPECULAR`), emission is the color times its
|
||||
strength, and the coat, fuzz or sheen become the layers. Color constants are decoded to linear
|
||||
Rec.709 from the color space in effect (`srgb_texture`, `srgb_rec709_scene`, the Rec.709
|
||||
gamma spaces, `lin_rec709`, `lin_rec709_scene`, `data`); another color space is an error. An
|
||||
image becomes a texture binding and the core holds 1 times any weight in its place. A coat or
|
||||
sheen roughness image binds as `ClearcoatRoughnessFirst` or `SheenRoughnessFirst`, which read
|
||||
the first channel; the glTF bindings `ClearcoatRoughness` and `SheenRoughness` read G and A.
|
||||
Tangent-space normal textures require an image connected through a `normalmap` node.
|
||||
Direct world-space normal images are dropped with a report entry. Literal normal-map
|
||||
inputs and authored normal-map frames are unsupported and reported. Authored `constant`,
|
||||
`clamp`, and `mirror` image addressing modes are also reported. Other inputs of the shader's
|
||||
table are kept in `other_inputs`.
|
||||
- **Features.** `parallel` computes rows on several threads with rayon. `mesh` and `materialx`
|
||||
add the conversions and depend on craft-mesh and craft-materialx. The default build has none of
|
||||
them, is serial and builds for `wasm32-unknown-unknown`, as do `mesh` and `materialx`. Results
|
||||
are the same either way.
|
||||
The `craft` facade forwards the conversion features as `pbr-mesh` and `pbr-materialx`.
|
||||
|
||||
On a 256 × 128 source, the default `try_prefilter` evaluates 1,396,736 samples (10,912 output
|
||||
pixels in levels 1 to 5, 128 samples each).
|
||||
|
||||
@@ -0,0 +1,600 @@
|
||||
//! The conversion from a `craft_materialx::StrictMaterial`: an OpenPBR Surface, Standard Surface
|
||||
//! or glTF PBR shader with its resolved inputs.
|
||||
|
||||
use craft_materialx::{Resolved, Shader, StrictMaterial};
|
||||
use craft_texture::srgb_to_linear;
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::surface::{
|
||||
AlphaMode, Clearcoat, Conversion, ConversionReport, ConvertError, FINITE, NON_NEGATIVE, ReportItem, Sheen, Surface, TextureBinding,
|
||||
TextureEncoding, TextureInput, TextureSource, UNIT, UvTransform, Wrap,
|
||||
};
|
||||
use crate::{MAX_SPECULAR, Material};
|
||||
|
||||
/// What a shader input holds and the range its values must be in.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Kind {
|
||||
/// One number from `lo` to `hi`.
|
||||
Scalar(f32, f32),
|
||||
/// Three color components from 0 to the bound, in the color space in effect.
|
||||
Color(f32),
|
||||
/// Three finite numbers, such as a normal.
|
||||
Vector,
|
||||
/// glTF PBR's alpha mode: 0, 1 or 2.
|
||||
Mode,
|
||||
}
|
||||
|
||||
const UNIT_KIND: Kind = Kind::Scalar(0.0, 1.0);
|
||||
const NON_NEGATIVE_KIND: Kind = Kind::Scalar(0.0, f32::MAX);
|
||||
const COLOR: Kind = Kind::Color(1.0);
|
||||
|
||||
const COAT_OFF: &str = "the coat weight is 0, which turns the layer off";
|
||||
const SHEEN_OFF: &str = "the sheen color is black or its weight is 0, which turns the layer off";
|
||||
|
||||
/// What an input maps to on the [`Surface`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Role {
|
||||
BaseColor,
|
||||
BaseWeight,
|
||||
Metallic,
|
||||
Roughness,
|
||||
SpecularWeight,
|
||||
Ior,
|
||||
CoatWeight,
|
||||
CoatRoughness,
|
||||
SheenWeight,
|
||||
SheenColor,
|
||||
SheenRoughness,
|
||||
EmissionStrength,
|
||||
EmissionColor,
|
||||
Opacity,
|
||||
AlphaMode,
|
||||
AlphaCutoff,
|
||||
Normal,
|
||||
Occlusion,
|
||||
/// Kept as an other input or a texture, and not shaded.
|
||||
Kept,
|
||||
/// Kept like [`Role::Kept`] while the coat is on, and dropped when it is off.
|
||||
CoatKept,
|
||||
}
|
||||
|
||||
/// A shader input the conversion reads, with its default from the shader's node definition.
|
||||
struct Field {
|
||||
name: &'static str,
|
||||
kind: Kind,
|
||||
role: Role,
|
||||
default: [f32; 3],
|
||||
}
|
||||
|
||||
const fn field(name: &'static str, kind: Kind, role: Role, default: f32) -> Field {
|
||||
Field { name, kind, role, default: [default; 3] }
|
||||
}
|
||||
|
||||
/// OpenPBR Surface inputs and defaults, from its node definition
|
||||
/// (<https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/bxdf/open_pbr_surface.mtlx>).
|
||||
const OPEN_PBR: &[Field] = &[
|
||||
field("base_color", COLOR, Role::BaseColor, 0.8),
|
||||
field("base_weight", UNIT_KIND, Role::BaseWeight, 1.0),
|
||||
field("base_metalness", UNIT_KIND, Role::Metallic, 0.0),
|
||||
field("specular_roughness", UNIT_KIND, Role::Roughness, 0.3),
|
||||
field("specular_weight", NON_NEGATIVE_KIND, Role::SpecularWeight, 1.0),
|
||||
field("specular_ior", NON_NEGATIVE_KIND, Role::Ior, 1.5),
|
||||
field("coat_weight", UNIT_KIND, Role::CoatWeight, 0.0),
|
||||
field("coat_roughness", UNIT_KIND, Role::CoatRoughness, 0.0),
|
||||
field("fuzz_weight", UNIT_KIND, Role::SheenWeight, 0.0),
|
||||
field("fuzz_color", COLOR, Role::SheenColor, 1.0),
|
||||
field("fuzz_roughness", UNIT_KIND, Role::SheenRoughness, 0.5),
|
||||
field("emission_luminance", NON_NEGATIVE_KIND, Role::EmissionStrength, 0.0),
|
||||
field("emission_color", COLOR, Role::EmissionColor, 1.0),
|
||||
field("geometry_opacity", UNIT_KIND, Role::Opacity, 1.0),
|
||||
field("geometry_normal", Kind::Vector, Role::Normal, 0.0),
|
||||
field("geometry_coat_normal", Kind::Vector, Role::CoatKept, 0.0),
|
||||
field("specular_color", COLOR, Role::Kept, 1.0),
|
||||
field("specular_roughness_anisotropy", UNIT_KIND, Role::Kept, 0.0),
|
||||
field("transmission_weight", UNIT_KIND, Role::Kept, 0.0),
|
||||
field("subsurface_weight", UNIT_KIND, Role::Kept, 0.0),
|
||||
field("coat_color", COLOR, Role::CoatKept, 1.0),
|
||||
field("coat_ior", NON_NEGATIVE_KIND, Role::CoatKept, 1.6),
|
||||
];
|
||||
|
||||
/// Standard Surface 1.0.1 inputs and defaults, from its node definition
|
||||
/// (<https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/bxdf/standard_surface.mtlx>).
|
||||
const STANDARD_SURFACE: &[Field] = &[
|
||||
field("base_color", COLOR, Role::BaseColor, 0.8),
|
||||
field("base", UNIT_KIND, Role::BaseWeight, 1.0),
|
||||
field("metalness", UNIT_KIND, Role::Metallic, 0.0),
|
||||
field("specular_roughness", UNIT_KIND, Role::Roughness, 0.2),
|
||||
field("specular", UNIT_KIND, Role::SpecularWeight, 1.0),
|
||||
field("specular_IOR", NON_NEGATIVE_KIND, Role::Ior, 1.5),
|
||||
field("coat", UNIT_KIND, Role::CoatWeight, 0.0),
|
||||
field("coat_roughness", UNIT_KIND, Role::CoatRoughness, 0.1),
|
||||
field("sheen", UNIT_KIND, Role::SheenWeight, 0.0),
|
||||
field("sheen_color", COLOR, Role::SheenColor, 1.0),
|
||||
field("sheen_roughness", UNIT_KIND, Role::SheenRoughness, 0.3),
|
||||
field("emission", NON_NEGATIVE_KIND, Role::EmissionStrength, 0.0),
|
||||
field("emission_color", COLOR, Role::EmissionColor, 1.0),
|
||||
field("opacity", COLOR, Role::Opacity, 1.0),
|
||||
field("normal", Kind::Vector, Role::Normal, 0.0),
|
||||
field("coat_normal", Kind::Vector, Role::CoatKept, 0.0),
|
||||
field("specular_color", COLOR, Role::Kept, 1.0),
|
||||
field("specular_anisotropy", UNIT_KIND, Role::Kept, 0.0),
|
||||
field("transmission", UNIT_KIND, Role::Kept, 0.0),
|
||||
field("subsurface", UNIT_KIND, Role::Kept, 0.0),
|
||||
field("coat_color", COLOR, Role::CoatKept, 1.0),
|
||||
field("coat_IOR", NON_NEGATIVE_KIND, Role::CoatKept, 1.5),
|
||||
];
|
||||
|
||||
/// glTF PBR inputs and defaults, from its node definition
|
||||
/// (<https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/bxdf/gltf_pbr.mtlx>).
|
||||
const GLTF_PBR: &[Field] = &[
|
||||
field("base_color", COLOR, Role::BaseColor, 1.0),
|
||||
field("metallic", UNIT_KIND, Role::Metallic, 1.0),
|
||||
field("roughness", UNIT_KIND, Role::Roughness, 1.0),
|
||||
field("specular", UNIT_KIND, Role::SpecularWeight, 1.0),
|
||||
field("ior", Kind::Scalar(1.0, f32::MAX), Role::Ior, 1.5),
|
||||
field("clearcoat", UNIT_KIND, Role::CoatWeight, 0.0),
|
||||
field("clearcoat_roughness", UNIT_KIND, Role::CoatRoughness, 0.0),
|
||||
field("sheen_color", COLOR, Role::SheenColor, 0.0),
|
||||
field("sheen_roughness", UNIT_KIND, Role::SheenRoughness, 0.0),
|
||||
field("emissive_strength", NON_NEGATIVE_KIND, Role::EmissionStrength, 1.0),
|
||||
field("emissive", COLOR, Role::EmissionColor, 0.0),
|
||||
field("alpha", UNIT_KIND, Role::Opacity, 1.0),
|
||||
field("alpha_mode", Kind::Mode, Role::AlphaMode, 0.0),
|
||||
field("alpha_cutoff", UNIT_KIND, Role::AlphaCutoff, 0.5),
|
||||
field("normal", Kind::Vector, Role::Normal, 0.0),
|
||||
field("occlusion", UNIT_KIND, Role::Occlusion, 1.0),
|
||||
field("clearcoat_normal", Kind::Vector, Role::CoatKept, 0.0),
|
||||
field("transmission", UNIT_KIND, Role::Kept, 0.0),
|
||||
field("specular_color", Kind::Color(f32::MAX), Role::Kept, 1.0),
|
||||
];
|
||||
|
||||
/// What a conversion found for one field of the table.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Got {
|
||||
Missing,
|
||||
/// Checked values, linear for a color.
|
||||
Constant(Vec<f32>),
|
||||
Texture,
|
||||
}
|
||||
|
||||
/// The table of the material's shader and what each field holds.
|
||||
struct Inputs {
|
||||
table: &'static [Field],
|
||||
got: Vec<Got>,
|
||||
}
|
||||
|
||||
impl Inputs {
|
||||
fn find(&self, role: Role) -> Option<(&Field, &Got)> {
|
||||
self.table.iter().zip(&self.got).find(|(f, _)| f.role == role)
|
||||
}
|
||||
|
||||
/// The field's value: the authored one, 1 for a texture (the factor its samples multiply),
|
||||
/// or the default when the input is absent. `None` when the shader has no such field.
|
||||
fn value(&self, role: Role) -> Option<[f32; 3]> {
|
||||
let (f, got) = self.find(role)?;
|
||||
Some(match got {
|
||||
Got::Missing => f.default,
|
||||
Got::Texture => [1.0; 3],
|
||||
Got::Constant(v) if v.len() == 1 => [v[0]; 3],
|
||||
Got::Constant(v) => [v.first().copied().unwrap_or(0.0), v.get(1).copied().unwrap_or(0.0), v.get(2).copied().unwrap_or(0.0)],
|
||||
})
|
||||
}
|
||||
|
||||
fn scalar(&self, role: Role, absent: f32) -> f32 {
|
||||
self.value(role).map_or(absent, |v| v[0])
|
||||
}
|
||||
|
||||
fn textured(&self, role: Role) -> bool {
|
||||
self.find(role).is_some_and(|(_, g)| *g == Got::Texture)
|
||||
}
|
||||
|
||||
fn name(&self, role: Role) -> &'static str {
|
||||
self.table.iter().find(|f| f.role == role).map_or("", |f| f.name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a `craft_materialx::StrictMaterial`, as `Document::read_material_strict` reads it, by
|
||||
/// the input tables of its shader's node definition
|
||||
/// (<https://github.com/AcademySoftwareFoundation/MaterialX/tree/main/libraries/bxdf>). An input
|
||||
/// that is absent takes the definition's default, so an empty input list gives the shader's
|
||||
/// default material.
|
||||
///
|
||||
/// - The core's base color is the base color times the base weight (`base_weight`, or `base` in
|
||||
/// Standard Surface), which both shaders apply to the diffuse and the metal color. Metallic
|
||||
/// and roughness map as they are. The core's specular weight is the specular weight times
|
||||
/// Schlick's reflectance at normal incidence for the index of refraction,
|
||||
/// `((ior − 1) / (ior + 1))²`, divided by 0.04; it is reported as approximated when it is not 1,
|
||||
/// and a value over [`MAX_SPECULAR`] is an error.
|
||||
/// - The coat (`coat_*`, or `clearcoat*` in glTF PBR) becomes [`Surface::clearcoat`] when its
|
||||
/// weight is above 0 or a texture sets it. The fuzz of OpenPBR and the sheen of Standard
|
||||
/// Surface become [`Surface::sheen`] with the weight times the color as its color, reported as
|
||||
/// approximated; glTF PBR's sheen maps as it is. A layer is kept only when it is on.
|
||||
/// - Emission is the emission color times its strength: `emission_luminance` (reported as
|
||||
/// approximated, since it is in nits), `emission`, or `emissive_strength`. A color whose
|
||||
/// strength is 0 gives no emission.
|
||||
/// An authored color at strength 0 is validated and reported as dropped.
|
||||
/// - Alpha is the opacity. Standard Surface's opacity is a color: equal channels give that value,
|
||||
/// and different channels give their luminance by the Rec.709 luma coefficients, reported as
|
||||
/// approximated, as the shader's own node graph reduces it with a `luminance` node. OpenPBR's
|
||||
/// `geometry_opacity` and glTF PBR's `alpha` are floats in their node definitions, so a color
|
||||
/// there is [`ConvertError::Components`]. glTF PBR's `alpha_mode` 0, 1 and 2 give opaque,
|
||||
/// masked at `alpha_cutoff`, and blended; the other shaders blend when the opacity is below 1
|
||||
/// or a texture sets it.
|
||||
/// - Every other input of the table (normals, specular color, anisotropy, transmission,
|
||||
/// subsurface, coat color and IOR, occlusion) is kept in [`Surface::other_inputs`], or as a
|
||||
/// texture, and reported as unshaded. The displacement is kept the same way.
|
||||
/// - An image becomes a [`TextureBinding`] with the file path, the UV tiling as its transform's
|
||||
/// scale, and an encoding from its color space for a color input (linear for data); the core
|
||||
/// holds 1 times any weight in its place; Standard Surface's color `opacity` binds as
|
||||
/// [`TextureInput::OpacityRgb`] and the float opacities as [`TextureInput::Opacity`]; an IOR
|
||||
/// texture leaves the default IOR, reported
|
||||
/// as approximated. The inputs and textures of a layer that is off (the coat's roughness,
|
||||
/// color, IOR and normal among them) are dropped and reported.
|
||||
/// - Color constants are decoded to linear Rec.709 from the color space in effect, as the
|
||||
/// MaterialX specification asks
|
||||
/// (<https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/documents/Specification/MaterialX.Specification.md#color-spaces-and-color-management-systems>):
|
||||
/// `srgb_texture` and `srgb_rec709_scene` by the sRGB transfer function, the Rec.709 gamma
|
||||
/// spaces by their power, and `lin_rec709`, `lin_rec709_scene`, `data`, `none` or no color
|
||||
/// space as they are. Another color space is [`ConvertError::ColorSpace`].
|
||||
/// - The reader's warnings are carried into the report. Inputs outside the table are dropped and
|
||||
/// reported.
|
||||
///
|
||||
/// Every value is checked and none is clamped: a value that is not finite (a color also after it
|
||||
/// is decoded to linear), is outside the definition's range (`0..=1` for weights, colors and
|
||||
/// roughness, at least 0 for strengths and IOR, at least 1 for glTF PBR's `ior`), has the wrong
|
||||
/// number of components, or is an
|
||||
/// `alpha_mode` other than 0, 1 or 2 is an error, and so is a texture on `alpha_mode` or
|
||||
/// `alpha_cutoff`, a UV tiling that is not two positive numbers, or an input named twice.
|
||||
pub fn try_from_materialx(m: &StrictMaterial) -> Result<Conversion, ConvertError> {
|
||||
let table = match m.shader {
|
||||
Shader::OpenPbr => OPEN_PBR,
|
||||
Shader::StandardSurface => STANDARD_SURFACE,
|
||||
Shader::GltfPbr => GLTF_PBR,
|
||||
};
|
||||
let mut report = ConversionReport::default();
|
||||
let mut inputs = Inputs { table, got: table.iter().map(|_| Got::Missing).collect() };
|
||||
let mut textures: Vec<(Role, TextureBinding)> = Vec::new();
|
||||
let mut others: Vec<(Role, String, Vec<f32>)> = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
for (name, value) in &m.inputs {
|
||||
if !seen.insert(name.as_str()) {
|
||||
return Err(ConvertError::Duplicate(name.clone()));
|
||||
}
|
||||
let Some(idx) = table.iter().position(|f| f.name == name) else {
|
||||
report.items.push(ReportItem::Dropped { input: name.clone(), why: "is not an input of the shader that the conversion reads" });
|
||||
continue;
|
||||
};
|
||||
let f = &table[idx];
|
||||
match value {
|
||||
Resolved::Constant { values, colorspace } => {
|
||||
let v = checked_values(f, values, colorspace.as_deref())?;
|
||||
if matches!(f.role, Role::Kept | Role::CoatKept | Role::Normal | Role::Occlusion) {
|
||||
others.push((f.role, name.clone(), v));
|
||||
} else {
|
||||
inputs.got[idx] = Got::Constant(v);
|
||||
}
|
||||
}
|
||||
Resolved::Image { file, colorspace, uv_tiling } | Resolved::NormalMap { file, colorspace, uv_tiling } => {
|
||||
if matches!(f.role, Role::AlphaMode | Role::AlphaCutoff) {
|
||||
return Err(ConvertError::BadValue { input: name.clone(), reason: "cannot be a texture" });
|
||||
}
|
||||
let binding = image_binding(f, file, colorspace.as_deref(), *uv_tiling)?;
|
||||
let tangent = matches!(value, Resolved::NormalMap { .. });
|
||||
let normal = matches!(f.role, Role::Normal) || (matches!(f.role, Role::CoatKept) && matches!(f.kind, Kind::Vector));
|
||||
if normal && !tangent {
|
||||
report.items.push(ReportItem::Dropped { input: name.clone(), why: "world-space normal images are not supported" });
|
||||
continue;
|
||||
}
|
||||
if tangent && !normal {
|
||||
report.items.push(ReportItem::Dropped { input: name.clone(), why: "a normalmap image is not supported on this input" });
|
||||
continue;
|
||||
}
|
||||
textures.push((f.role, binding));
|
||||
inputs.got[idx] = Got::Texture;
|
||||
}
|
||||
}
|
||||
}
|
||||
let material = core(&inputs, &mut report)?;
|
||||
let clearcoat = clearcoat(&inputs);
|
||||
let sheen = sheen(&inputs, m.shader, &mut report);
|
||||
let emissive = emission(&inputs, m.shader, &mut report);
|
||||
let (alpha, alpha_mode) = alpha(&inputs, m.shader, &mut report)?;
|
||||
let off = |role: Role| match role {
|
||||
Role::CoatWeight | Role::CoatRoughness | Role::CoatKept if clearcoat.is_none() => Some(COAT_OFF),
|
||||
Role::SheenWeight | Role::SheenColor | Role::SheenRoughness if sheen.is_none() => Some(SHEEN_OFF),
|
||||
Role::EmissionColor if inputs.scalar(Role::EmissionStrength, 1.0) == 0.0 => Some("the emission strength is 0"),
|
||||
_ => None,
|
||||
};
|
||||
// Authored constants of a layer that is off, except the weight or color that turns it off.
|
||||
for (f, got) in table.iter().zip(&inputs.got) {
|
||||
let Got::Constant(v) = got else { continue };
|
||||
let turns_it_off = match f.role {
|
||||
Role::CoatWeight => true,
|
||||
Role::SheenWeight | Role::SheenColor => v.iter().all(|c| *c == 0.0),
|
||||
_ => false,
|
||||
};
|
||||
if let Some(why) = off(f.role).filter(|_| !turns_it_off) {
|
||||
report.items.push(ReportItem::Dropped { input: f.name.to_owned(), why });
|
||||
}
|
||||
}
|
||||
let mut other_inputs = Vec::new();
|
||||
for (role, input, values) in others {
|
||||
match off(role) {
|
||||
Some(why) => report.items.push(ReportItem::Dropped { input, why }),
|
||||
None => {
|
||||
report.items.push(ReportItem::Unshaded { input: input.clone() });
|
||||
other_inputs.push((input, values));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut kept = Vec::new();
|
||||
for (role, binding) in textures {
|
||||
let off = off(role);
|
||||
let input = texture_name(&inputs, role, &binding);
|
||||
match off {
|
||||
Some(why) => report.items.push(ReportItem::Dropped { input, why }),
|
||||
None => {
|
||||
report.items.push(ReportItem::Unshaded { input });
|
||||
kept.push(binding);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (layer, on) in [("clearcoat", clearcoat.is_some()), ("sheen", sheen.is_some())] {
|
||||
if on {
|
||||
report.items.push(ReportItem::Unshaded { input: layer.into() });
|
||||
}
|
||||
}
|
||||
displacement(m.displacement.as_ref(), &mut kept, &mut other_inputs, &mut report)?;
|
||||
report.items.extend(m.warnings.iter().cloned().map(ReportItem::Warning));
|
||||
let surface = Surface {
|
||||
name: m.name.clone(),
|
||||
material,
|
||||
alpha,
|
||||
alpha_mode,
|
||||
emissive,
|
||||
double_sided: false,
|
||||
unlit: false,
|
||||
clearcoat,
|
||||
sheen,
|
||||
textures: kept,
|
||||
other_inputs,
|
||||
};
|
||||
Ok(Conversion { surface, report })
|
||||
}
|
||||
|
||||
/// The source name of a texture for the report.
|
||||
fn texture_name(inputs: &Inputs, role: Role, binding: &TextureBinding) -> String {
|
||||
match &binding.input {
|
||||
TextureInput::Other(name) => name.clone(),
|
||||
_ => inputs.name(role).to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The reason text for a value outside `lo..=hi`.
|
||||
fn reason(lo: f32, hi: f32) -> &'static str {
|
||||
match (lo, hi) {
|
||||
(0.0, 1.0) => UNIT,
|
||||
(0.0, _) => NON_NEGATIVE,
|
||||
(1.0, _) => "is not a finite number of at least 1",
|
||||
_ => FINITE,
|
||||
}
|
||||
}
|
||||
|
||||
/// The values of a constant for field `f`, checked against its kind and, for a color, decoded
|
||||
/// to linear from `space`.
|
||||
fn checked_values(f: &Field, values: &[f32], space: Option<&str>) -> Result<Vec<f32>, ConvertError> {
|
||||
let expected = match f.kind {
|
||||
Kind::Scalar(..) | Kind::Mode => 1,
|
||||
Kind::Color(_) | Kind::Vector => 3,
|
||||
};
|
||||
if values.len() != expected {
|
||||
return Err(ConvertError::Components { input: f.name.to_owned(), expected, found: values.len() });
|
||||
}
|
||||
let bad = |reason| ConvertError::BadValue { input: f.name.to_owned(), reason };
|
||||
let (lo, hi) = match f.kind {
|
||||
Kind::Scalar(lo, hi) => (lo, hi),
|
||||
Kind::Color(hi) => (0.0, hi),
|
||||
Kind::Vector => (f32::MIN, f32::MAX),
|
||||
Kind::Mode => (0.0, 2.0),
|
||||
};
|
||||
let in_range = |v: f32| v.is_finite() && (lo..=hi).contains(&v);
|
||||
for &v in values {
|
||||
if !in_range(v) {
|
||||
return Err(bad(reason(lo, hi)));
|
||||
}
|
||||
if f.kind == Kind::Mode && v.fract() != 0.0 {
|
||||
return Err(bad("is not 0, 1 or 2"));
|
||||
}
|
||||
}
|
||||
match f.kind {
|
||||
Kind::Color(_) => {
|
||||
let linear = decode(values, space, f.name)?;
|
||||
if linear.iter().all(|&v| in_range(v)) { Ok(linear) } else { Err(bad("is not a finite color once decoded to linear")) }
|
||||
}
|
||||
_ => Ok(values.to_vec()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `values` decoded to linear Rec.709 from the color space `space`.
|
||||
fn decode(values: &[f32], space: Option<&str>, input: &str) -> Result<Vec<f32>, ConvertError> {
|
||||
let power = |p: f32| values.iter().map(|v| v.powf(p)).collect();
|
||||
Ok(match space {
|
||||
None | Some("data" | "none" | "lin_rec709" | "lin_rec709_scene") => values.to_vec(),
|
||||
Some("srgb_texture" | "srgb_rec709_scene") => values.iter().map(|v| srgb_to_linear(*v)).collect(),
|
||||
Some("g22_rec709" | "g22_rec709_scene") => power(2.2),
|
||||
Some("g18_rec709" | "g18_rec709_scene") => power(1.8),
|
||||
Some("g24_rec709_scene") => power(2.4),
|
||||
Some(other) => return Err(ConvertError::ColorSpace { input: input.to_owned(), colorspace: other.to_owned() }),
|
||||
})
|
||||
}
|
||||
|
||||
/// The binding of an image on field `f`.
|
||||
fn image_binding(f: &Field, file: &str, space: Option<&str>, tiling: Option<[f32; 2]>) -> Result<TextureBinding, ConvertError> {
|
||||
let input = match f.role {
|
||||
Role::BaseColor => TextureInput::BaseColor,
|
||||
Role::Metallic => TextureInput::Metallic,
|
||||
Role::Roughness => TextureInput::Roughness,
|
||||
Role::Normal => TextureInput::Normal,
|
||||
Role::Occlusion => TextureInput::Occlusion,
|
||||
Role::EmissionColor => TextureInput::Emissive,
|
||||
Role::Opacity if matches!(f.kind, Kind::Color(_)) => TextureInput::OpacityRgb,
|
||||
Role::Opacity => TextureInput::Opacity,
|
||||
Role::CoatWeight => TextureInput::Clearcoat,
|
||||
Role::CoatRoughness => TextureInput::ClearcoatRoughnessFirst,
|
||||
Role::SheenColor => TextureInput::SheenColor,
|
||||
Role::SheenRoughness => TextureInput::SheenRoughnessFirst,
|
||||
_ => TextureInput::Other(f.name.to_owned()),
|
||||
};
|
||||
let encoding = if matches!(f.kind, Kind::Color(_)) { encoding(space) } else { TextureEncoding::Linear };
|
||||
let transform = match tiling {
|
||||
Some(scale) if scale.iter().all(|v| v.is_finite() && *v > 0.0) => Some(UvTransform { offset: [0.0; 2], rotation: 0.0, scale }),
|
||||
Some(_) => return Err(ConvertError::BadValue { input: f.name.to_owned(), reason: "has a UV tiling that is not two positive numbers" }),
|
||||
None => None,
|
||||
};
|
||||
Ok(TextureBinding { input, source: TextureSource::File(file.to_owned()), encoding, uv_set: 0, wrap: [Wrap::Repeat; 2], transform, scale: 1.0 })
|
||||
}
|
||||
|
||||
/// The encoding of a color image in the color space `space`.
|
||||
fn encoding(space: Option<&str>) -> TextureEncoding {
|
||||
match space {
|
||||
None | Some("data" | "none" | "lin_rec709" | "lin_rec709_scene") => TextureEncoding::Linear,
|
||||
Some("srgb_texture" | "srgb_rec709_scene") => TextureEncoding::Srgb,
|
||||
Some(other) => TextureEncoding::Named(other.to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The BRDF core.
|
||||
fn core(inputs: &Inputs, report: &mut ConversionReport) -> Result<Material, ConvertError> {
|
||||
let color = inputs.value(Role::BaseColor).unwrap_or([1.0; 3]);
|
||||
let weight = inputs.scalar(Role::BaseWeight, 1.0);
|
||||
let base = color.map(|c| c * weight);
|
||||
let metallic = inputs.scalar(Role::Metallic, 0.0);
|
||||
let roughness = inputs.scalar(Role::Roughness, 0.0);
|
||||
if inputs.textured(Role::Ior) {
|
||||
report
|
||||
.items
|
||||
.push(ReportItem::Approximated { input: inputs.name(Role::Ior).into(), how: "is a texture; the default index of refraction was used" });
|
||||
}
|
||||
let ior = match inputs.find(Role::Ior) {
|
||||
Some((f, Got::Texture)) => f64::from(f.default[0]),
|
||||
_ => f64::from(inputs.scalar(Role::Ior, 1.5)),
|
||||
};
|
||||
// The reflectance relative to 0.04, which is 1 within rounding at the default IOR of 1.5.
|
||||
let mut ratio = ((ior - 1.0) / (ior + 1.0)).powi(2) / 0.04;
|
||||
if (ratio - 1.0).abs() < 1e-9 {
|
||||
ratio = 1.0;
|
||||
}
|
||||
let specular = f64::from(inputs.scalar(Role::SpecularWeight, 1.0)) * ratio;
|
||||
let name = inputs.name(Role::SpecularWeight);
|
||||
if specular > f64::from(MAX_SPECULAR) {
|
||||
return Err(ConvertError::BadValue {
|
||||
input: name.into(),
|
||||
reason: "times the reflectance of the index of refraction is over the 25 the BRDF supports",
|
||||
});
|
||||
}
|
||||
if specular != 1.0 {
|
||||
report.items.push(ReportItem::Approximated {
|
||||
input: name.into(),
|
||||
how: "times Schlick's reflectance at normal incidence for the index of refraction, over 0.04, is the core's specular weight",
|
||||
});
|
||||
}
|
||||
Ok(Material::try_new(base, metallic, roughness)?.try_with_weights(specular as f32, 1.0)?)
|
||||
}
|
||||
|
||||
/// The coat, when its weight is above 0 or a texture sets it.
|
||||
fn clearcoat(inputs: &Inputs) -> Option<Clearcoat> {
|
||||
let weight = inputs.scalar(Role::CoatWeight, 0.0);
|
||||
(weight > 0.0).then(|| Clearcoat { weight, roughness: inputs.scalar(Role::CoatRoughness, 0.0) })
|
||||
}
|
||||
|
||||
/// The sheen, when its color times its weight is not black.
|
||||
fn sheen(inputs: &Inputs, shader: Shader, report: &mut ConversionReport) -> Option<Sheen> {
|
||||
let weight = inputs.scalar(Role::SheenWeight, 1.0);
|
||||
let color = inputs.value(Role::SheenColor)?.map(|c| c * weight);
|
||||
if color == [0.0; 3] {
|
||||
return None;
|
||||
}
|
||||
if shader != Shader::GltfPbr {
|
||||
report.items.push(ReportItem::Approximated { input: inputs.name(Role::SheenWeight).into(), how: "times the color is the sheen color" });
|
||||
}
|
||||
Some(Sheen { color, roughness: inputs.scalar(Role::SheenRoughness, 0.0) })
|
||||
}
|
||||
|
||||
/// The emission color times its strength.
|
||||
fn emission(inputs: &Inputs, shader: Shader, report: &mut ConversionReport) -> [f32; 3] {
|
||||
let strength = inputs.scalar(Role::EmissionStrength, 1.0);
|
||||
let color = inputs.value(Role::EmissionColor).unwrap_or([0.0; 3]);
|
||||
let emissive = color.map(|c| c * strength);
|
||||
if shader == Shader::OpenPbr && emissive != [0.0; 3] {
|
||||
report.items.push(ReportItem::Approximated {
|
||||
input: inputs.name(Role::EmissionStrength).into(),
|
||||
how: "is in nits and multiplies the emission color",
|
||||
});
|
||||
}
|
||||
emissive
|
||||
}
|
||||
|
||||
/// Alpha and its mode.
|
||||
fn alpha(inputs: &Inputs, shader: Shader, report: &mut ConversionReport) -> Result<(f32, AlphaMode), ConvertError> {
|
||||
let opacity = inputs.value(Role::Opacity).unwrap_or([1.0; 3]);
|
||||
let alpha = if shader == Shader::StandardSurface && (opacity[0] != opacity[1] || opacity[1] != opacity[2]) {
|
||||
report
|
||||
.items
|
||||
.push(ReportItem::Approximated { input: inputs.name(Role::Opacity).into(), how: "is a color; its Rec.709 luminance is the alpha" });
|
||||
luminance(opacity)
|
||||
} else {
|
||||
opacity[0]
|
||||
};
|
||||
let mode = if shader == Shader::GltfPbr {
|
||||
match inputs.scalar(Role::AlphaMode, 0.0) {
|
||||
0.0 => AlphaMode::Opaque,
|
||||
1.0 => AlphaMode::Mask(inputs.scalar(Role::AlphaCutoff, 0.5)),
|
||||
2.0 => AlphaMode::Blend,
|
||||
_ => return Err(ConvertError::BadValue { input: "alpha_mode".into(), reason: "is not 0, 1 or 2" }),
|
||||
}
|
||||
} else if alpha < 1.0 || inputs.textured(Role::Opacity) {
|
||||
AlphaMode::Blend
|
||||
} else {
|
||||
AlphaMode::Opaque
|
||||
};
|
||||
if shader == Shader::GltfPbr
|
||||
&& !matches!(mode, AlphaMode::Mask(_))
|
||||
&& inputs.find(Role::AlphaCutoff).is_some_and(|(_, value)| matches!(value, Got::Constant(_)))
|
||||
{
|
||||
report.items.push(ReportItem::Dropped { input: inputs.name(Role::AlphaCutoff).into(), why: "the alpha mode does not use a cutoff" });
|
||||
}
|
||||
Ok((alpha, mode))
|
||||
}
|
||||
|
||||
/// The luminance of a linear Rec.709 color, by the `rec709` luma coefficients of the MaterialX
|
||||
/// `luminance` node
|
||||
/// (<https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/stdlib_defs.mtlx>),
|
||||
/// kept between the smallest and largest channel so that rounding cannot leave `0..=1`.
|
||||
fn luminance(c: [f32; 3]) -> f32 {
|
||||
let y = 0.2126 * f64::from(c[0]) + 0.7152 * f64::from(c[1]) + 0.0722 * f64::from(c[2]);
|
||||
(y as f32).clamp(c[0].min(c[1]).min(c[2]), c[0].max(c[1]).max(c[2]))
|
||||
}
|
||||
|
||||
/// Keeps the displacement as a texture or an other input.
|
||||
fn displacement(
|
||||
value: Option<&Resolved>,
|
||||
textures: &mut Vec<TextureBinding>,
|
||||
other_inputs: &mut Vec<(String, Vec<f32>)>,
|
||||
report: &mut ConversionReport,
|
||||
) -> Result<(), ConvertError> {
|
||||
const DISPLACEMENT: Field = field("displacement", Kind::Scalar(f32::MIN, f32::MAX), Role::Kept, 0.0);
|
||||
match value {
|
||||
None => return Ok(()),
|
||||
Some(Resolved::Constant { values, .. }) => other_inputs.push(("displacement".into(), checked_values(&DISPLACEMENT, values, None)?)),
|
||||
Some(Resolved::Image { file, colorspace, uv_tiling }) => {
|
||||
let mut binding = image_binding(&DISPLACEMENT, file, colorspace.as_deref(), *uv_tiling)?;
|
||||
binding.input = TextureInput::Displacement;
|
||||
textures.push(binding);
|
||||
}
|
||||
Some(Resolved::NormalMap { .. }) => {
|
||||
return Err(ConvertError::BadValue { input: "displacement".into(), reason: "cannot be a normalmap image" });
|
||||
}
|
||||
}
|
||||
report.items.push(ReportItem::Unshaded { input: "displacement".into() });
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
//! The conversion from a `craft_mesh::Material`, which holds a glTF 2.0 metallic-roughness
|
||||
//! material.
|
||||
|
||||
use craft_mesh::{AlphaMode as MeshAlpha, Material as MeshMaterial, TextureRef, Wrap as MeshWrap};
|
||||
|
||||
use crate::Material;
|
||||
use crate::surface::{
|
||||
AlphaMode, Clearcoat, Conversion, ConversionReport, ConvertError, FINITE, NON_NEGATIVE, ReportItem, Sheen, Surface, TextureBinding,
|
||||
TextureEncoding, TextureInput, TextureSource, UNIT, UvTransform, Wrap, checked,
|
||||
};
|
||||
|
||||
/// The material extensions whose values `craft_mesh` reads into `craft_mesh::Material`'s fields.
|
||||
/// It reads only part of `KHR_materials_pbrSpecularGlossiness` and of `KHR_materials_clearcoat`.
|
||||
const CONVERTED_EXTENSIONS: &[&str] = &[
|
||||
"KHR_materials_unlit",
|
||||
"KHR_materials_emissive_strength",
|
||||
"KHR_materials_pbrSpecularGlossiness",
|
||||
"KHR_materials_clearcoat",
|
||||
"KHR_materials_sheen",
|
||||
];
|
||||
const SPECULAR_GLOSSINESS: &str = "KHR_materials_pbrSpecularGlossiness";
|
||||
|
||||
/// Converts a `craft_mesh::Material` as glTF 2.0 defines its metallic-roughness material
|
||||
/// (<https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#materials>).
|
||||
///
|
||||
/// - Mapped as they are: the linear base color RGB, metallic and roughness into the core with
|
||||
/// specular and diffuse weights of 1, base color alpha into [`Surface::alpha`], the alpha mode
|
||||
/// and cutoff, the linear emissive color, the double-sided flag, the unlit flag of
|
||||
/// `KHR_materials_unlit` and the name. Nothing is converted between color spaces: the source
|
||||
/// values are linear.
|
||||
/// - Kept and reported as [`ReportItem::Unshaded`]: every texture, with its image index, UV set,
|
||||
/// wrap modes and `KHR_texture_transform`, and the normal scale and occlusion strength as the
|
||||
/// binding's scale; the clearcoat layer of `KHR_materials_clearcoat`; the sheen layer of
|
||||
/// `KHR_materials_sheen`; and the unlit flag. Base color, emissive and sheen color textures
|
||||
/// are sRGB-encoded and the others are linear, as glTF and its extensions define them.
|
||||
/// - Dropped and reported: the clearcoat textures when the clearcoat factor is 0, and the sheen
|
||||
/// textures when the sheen color factor is black. Each extension turns its layer off then.
|
||||
/// Every other material extension in `craft_mesh::Material::extensions`, such as
|
||||
/// `KHR_materials_transmission`, is dropped and reported by its name, and so is the
|
||||
/// `clearcoatNormalTexture` of `KHR_materials_clearcoat`, which `craft_mesh` does not read.
|
||||
/// - Reported as [`ReportItem::Approximated`]: `KHR_materials_pbrSpecularGlossiness`, which
|
||||
/// `craft_mesh` reads as its diffuse color and texture with roughness from the glossiness,
|
||||
/// without its specular color or specular-glossiness texture.
|
||||
///
|
||||
/// Every value is checked and none is clamped. Base color channels, alpha, metallic,
|
||||
/// roughness, occlusion strength and the clearcoat and sheen values must be numbers from 0 to 1;
|
||||
/// emissive channels and the alpha cutoff must be finite and at least 0; the normal scale and
|
||||
/// every UV transform value must be finite. Otherwise the result is
|
||||
/// [`ConvertError::BadValue`] naming the `craft_mesh::Material` field.
|
||||
pub fn try_from_mesh(m: &MeshMaterial) -> Result<Conversion, ConvertError> {
|
||||
let [r, g, b, a] = m.base_color;
|
||||
let base = [checked(r, 0.0, 1.0, "base_color", UNIT)?, checked(g, 0.0, 1.0, "base_color", UNIT)?, checked(b, 0.0, 1.0, "base_color", UNIT)?];
|
||||
let alpha = checked(a, 0.0, 1.0, "base_color alpha", UNIT)?;
|
||||
let metallic = checked(m.metallic, 0.0, 1.0, "metallic", UNIT)?;
|
||||
let roughness = checked(m.roughness, 0.0, 1.0, "roughness", UNIT)?;
|
||||
let material = Material::try_new(base, metallic, roughness)?;
|
||||
let mut emissive = [0.0; 3];
|
||||
for (out, v) in emissive.iter_mut().zip(m.emissive) {
|
||||
*out = checked(v, 0.0, f32::MAX, "emissive", NON_NEGATIVE)?;
|
||||
}
|
||||
let alpha_mode = match m.alpha_mode {
|
||||
MeshAlpha::Opaque => AlphaMode::Opaque,
|
||||
MeshAlpha::Mask(cutoff) => AlphaMode::Mask(checked(cutoff, 0.0, f32::MAX, "alpha cutoff", NON_NEGATIVE)?),
|
||||
MeshAlpha::Blend => AlphaMode::Blend,
|
||||
};
|
||||
let normal_scale = checked(m.normal_scale, f32::MIN, f32::MAX, "normal_scale", FINITE)?;
|
||||
let occlusion_strength = checked(m.occlusion_strength, 0.0, 1.0, "occlusion_strength", UNIT)?;
|
||||
let clearcoat_weight = checked(m.clearcoat, 0.0, 1.0, "clearcoat", UNIT)?;
|
||||
let clearcoat_roughness = checked(m.clearcoat_roughness, 0.0, 1.0, "clearcoat_roughness", UNIT)?;
|
||||
let mut sheen_color = [0.0; 3];
|
||||
for (out, v) in sheen_color.iter_mut().zip(m.sheen_color) {
|
||||
*out = checked(v, 0.0, 1.0, "sheen_color", UNIT)?;
|
||||
}
|
||||
let sheen_roughness = checked(m.sheen_roughness, 0.0, 1.0, "sheen_roughness", UNIT)?;
|
||||
|
||||
let mut report = ConversionReport::default();
|
||||
let mut textures = Vec::new();
|
||||
let mut bind =
|
||||
|name: &str, slot: &Option<TextureRef>, input: TextureInput, encoding: TextureEncoding, scale: f32, dropped: Option<&'static str>| {
|
||||
let Some(t) = slot else {
|
||||
if scale != 1.0 {
|
||||
let factor = match input {
|
||||
TextureInput::Normal => "normal_scale",
|
||||
TextureInput::Occlusion => "occlusion_strength",
|
||||
_ => name,
|
||||
};
|
||||
report.items.push(ReportItem::Dropped { input: factor.to_owned(), why: "the corresponding texture is absent" });
|
||||
}
|
||||
return Ok(());
|
||||
};
|
||||
// The texture is checked before a layer that is off drops it.
|
||||
let b = binding(name, t, input, encoding, scale)?;
|
||||
if let Some(why) = dropped {
|
||||
report.items.push(ReportItem::Dropped { input: name.to_owned(), why });
|
||||
return Ok(());
|
||||
}
|
||||
textures.push(b);
|
||||
report.items.push(ReportItem::Unshaded { input: name.to_owned() });
|
||||
Ok::<(), ConvertError>(())
|
||||
};
|
||||
use TextureEncoding::{Linear, Srgb};
|
||||
bind("base_color_texture", &m.base_color_texture, TextureInput::BaseColor, Srgb, 1.0, None)?;
|
||||
bind("metallic_roughness_texture", &m.metallic_roughness_texture, TextureInput::MetallicRoughness, Linear, 1.0, None)?;
|
||||
bind("normal_texture", &m.normal_texture, TextureInput::Normal, Linear, normal_scale, None)?;
|
||||
bind("occlusion_texture", &m.occlusion_texture, TextureInput::Occlusion, Linear, occlusion_strength, None)?;
|
||||
bind("emissive_texture", &m.emissive_texture, TextureInput::Emissive, Srgb, 1.0, None)?;
|
||||
let coat_off = (clearcoat_weight == 0.0).then_some("the clearcoat factor is 0, which turns the layer off");
|
||||
bind("clearcoat_texture", &m.clearcoat_texture, TextureInput::Clearcoat, Linear, 1.0, coat_off)?;
|
||||
bind("clearcoat_roughness_texture", &m.clearcoat_roughness_texture, TextureInput::ClearcoatRoughness, Linear, 1.0, coat_off)?;
|
||||
let sheen_off = (sheen_color == [0.0; 3]).then_some("the sheen color factor is black, which turns the layer off");
|
||||
bind("sheen_color_texture", &m.sheen_color_texture, TextureInput::SheenColor, Srgb, 1.0, sheen_off)?;
|
||||
bind("sheen_roughness_texture", &m.sheen_roughness_texture, TextureInput::SheenRoughness, Linear, 1.0, sheen_off)?;
|
||||
|
||||
let clearcoat = coat_off.is_none().then_some(Clearcoat { weight: clearcoat_weight, roughness: clearcoat_roughness });
|
||||
if clearcoat.is_some() {
|
||||
report.items.push(ReportItem::Unshaded { input: "clearcoat".into() });
|
||||
}
|
||||
let sheen = sheen_off.is_none().then_some(Sheen { color: sheen_color, roughness: sheen_roughness });
|
||||
if sheen.is_some() {
|
||||
report.items.push(ReportItem::Unshaded { input: "sheen".into() });
|
||||
}
|
||||
for (inactive, roughness, input) in
|
||||
[(clearcoat.is_none(), clearcoat_roughness, "clearcoat_roughness"), (sheen.is_none(), sheen_roughness, "sheen_roughness")]
|
||||
{
|
||||
if inactive && roughness != 0.0 {
|
||||
report.items.push(ReportItem::Dropped { input: input.into(), why: "the layer is off" });
|
||||
}
|
||||
}
|
||||
if m.unlit {
|
||||
report.items.push(ReportItem::Unshaded { input: "unlit".into() });
|
||||
}
|
||||
for name in m.extensions.keys().filter(|k| !CONVERTED_EXTENSIONS.contains(&k.as_str())) {
|
||||
report.items.push(ReportItem::Dropped { input: name.clone(), why: "the extension is not converted" });
|
||||
}
|
||||
if m.extensions.get("KHR_materials_clearcoat").is_some_and(|c| c.get("clearcoatNormalTexture").is_some()) {
|
||||
report.items.push(ReportItem::Dropped { input: "clearcoatNormalTexture".into(), why: "craft-mesh does not read it" });
|
||||
}
|
||||
if m.extensions.contains_key(SPECULAR_GLOSSINESS) {
|
||||
report.items.push(ReportItem::Approximated {
|
||||
input: SPECULAR_GLOSSINESS.into(),
|
||||
how: "read as its diffuse color and texture with roughness from the glossiness; its specular color and texture are not converted",
|
||||
});
|
||||
}
|
||||
let surface = Surface {
|
||||
name: m.name.clone(),
|
||||
material,
|
||||
alpha,
|
||||
alpha_mode,
|
||||
emissive,
|
||||
double_sided: m.double_sided,
|
||||
unlit: m.unlit,
|
||||
clearcoat,
|
||||
sheen,
|
||||
textures,
|
||||
other_inputs: Vec::new(),
|
||||
};
|
||||
Ok(Conversion { surface, report })
|
||||
}
|
||||
|
||||
/// The binding of the texture `t` in the field `name`.
|
||||
fn binding(name: &str, t: &TextureRef, input: TextureInput, encoding: TextureEncoding, scale: f32) -> Result<TextureBinding, ConvertError> {
|
||||
let transform = match t.transform {
|
||||
Some(x) => {
|
||||
for v in [x.offset[0], x.offset[1], x.rotation, x.scale[0], x.scale[1]] {
|
||||
checked(v, f32::MIN, f32::MAX, &format!("{name} transform"), FINITE)?;
|
||||
}
|
||||
Some(UvTransform { offset: x.offset, rotation: x.rotation, scale: x.scale })
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let wrap = t.wrap.map(|w| match w {
|
||||
MeshWrap::Repeat => Wrap::Repeat,
|
||||
MeshWrap::Clamp => Wrap::Clamp,
|
||||
MeshWrap::Mirror => Wrap::Mirror,
|
||||
});
|
||||
Ok(TextureBinding { input, source: TextureSource::Image(t.image), encoding, uv_set: t.uv_set, wrap, transform, scale })
|
||||
}
|
||||
@@ -36,6 +36,14 @@
|
||||
//! [`SHADE_WGSL`] is the WGSL text of the same shading functions for an app's own shaders, and
|
||||
//! [`GpuMaterial`] and [`GpuSh9`] lay out the values it reads.
|
||||
//!
|
||||
//! A [`Surface`] is a [`Material`] with the state a renderer applies around it: alpha and its
|
||||
//! mode, emission, sidedness, the unlit flag, clearcoat and sheen layers, and texture bindings
|
||||
//! that are kept but not loaded. With the `mesh` feature, `try_from_mesh` converts a
|
||||
//! `craft_mesh::Material`, and with the `materialx` feature, `try_from_materialx` converts a
|
||||
//! `craft_materialx::StrictMaterial`. Each returns the surface and a [`ConversionReport`] of what it
|
||||
//! kept without shading, approximated or dropped, and a [`ConvertError`] for a value that is not
|
||||
//! finite or is out of its range. Neither feature is on by default.
|
||||
//!
|
||||
//! The diffuse coefficients are the nine real SH coefficients of the radiance, convolved with the
|
||||
//! clamped cosine lobe (band factors `π`, `2π/3` and `π/4`, Ramamoorthi and Hanrahan 2001,
|
||||
//! <https://graphics.stanford.edu/papers/envmap/envmap.pdf>) and divided by `π`. [`irradiance`]
|
||||
@@ -51,9 +59,14 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod brdf;
|
||||
#[cfg(feature = "materialx")]
|
||||
mod convert_materialx;
|
||||
#[cfg(feature = "mesh")]
|
||||
mod convert_mesh;
|
||||
mod environment;
|
||||
mod prefilter;
|
||||
mod sh;
|
||||
mod surface;
|
||||
mod vec3;
|
||||
mod wgsl;
|
||||
|
||||
@@ -61,9 +74,17 @@ mod wgsl;
|
||||
use rayon::prelude::*;
|
||||
|
||||
pub use brdf::{MAX_SPECULAR, MIN_DIRECT_ROUGHNESS, Material, Visibility, try_environment_brdf};
|
||||
#[cfg(feature = "materialx")]
|
||||
pub use convert_materialx::try_from_materialx;
|
||||
#[cfg(feature = "mesh")]
|
||||
pub use convert_mesh::try_from_mesh;
|
||||
pub use environment::{ColorEncoding, ENVIRONMENTS, EnvImage, Environment, MAX_RADIANCE, default_environment, dir_of, uv_of};
|
||||
pub use prefilter::{PrefilterOptions, ggx_distribution, ggx_distribution_between, hammersley, try_prefilter};
|
||||
pub use sh::{irradiance, sh_basis, try_sh9};
|
||||
pub use surface::{
|
||||
AlphaMode, Clearcoat, Conversion, ConversionReport, ConvertError, ReportItem, Sheen, Surface, TextureBinding, TextureEncoding, TextureInput,
|
||||
TextureSource, UvTransform, Wrap,
|
||||
};
|
||||
pub use wgsl::{GpuMaterial, GpuSh9, SHADE_WGSL};
|
||||
|
||||
/// Why an environment could not be made, filtered or read, or a material could not be shaded.
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
//! A surface material: the BRDF core with the surface state around it, and the report and errors
|
||||
//! of the conversions into it.
|
||||
|
||||
use crate::{Material, PbrError};
|
||||
|
||||
/// A material as a renderer needs it: the metallic-roughness [`Material`] that
|
||||
/// [`Material::try_direct`] shades, and the state a renderer applies around it. Alpha, emission
|
||||
/// and sidedness are applied by the renderer, not by the BRDF. The clearcoat and sheen layers,
|
||||
/// the textures and [`Surface::other_inputs`] are kept but not shaded by
|
||||
/// [`Material::try_direct`]. When [`Surface::unlit`] is set, the surface shows its base color
|
||||
/// without lighting, and [`Material::try_direct`] does not give its appearance.
|
||||
///
|
||||
/// Made by `try_from_mesh` (the `mesh` feature) and `try_from_materialx` (the `materialx`
|
||||
/// feature), which check every value.
|
||||
/// `#[non_exhaustive]`: read and change the fields, but get a value from a conversion.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct Surface {
|
||||
/// The source material's name.
|
||||
pub name: String,
|
||||
/// The BRDF core. Where a texture is bound to one of its values, the core holds the factor the
|
||||
/// texture's samples are multiplied by.
|
||||
pub material: Material,
|
||||
/// Coverage from 0 (transparent) to 1 (opaque).
|
||||
pub alpha: f32,
|
||||
/// How [`Surface::alpha`] is used.
|
||||
pub alpha_mode: AlphaMode,
|
||||
/// Linear RGB emission, each channel at least 0.
|
||||
pub emissive: [f32; 3],
|
||||
/// Both faces are drawn and lit.
|
||||
pub double_sided: bool,
|
||||
/// The surface is shown as its base color and alpha, without lighting.
|
||||
pub unlit: bool,
|
||||
/// A clear layer over the base, when its weight is above 0 or a texture sets it.
|
||||
pub clearcoat: Option<Clearcoat>,
|
||||
/// A sheen layer, when its color is not black or a texture sets it.
|
||||
pub sheen: Option<Sheen>,
|
||||
/// Textures bound to the material's values, not loaded or sampled.
|
||||
pub textures: Vec<TextureBinding>,
|
||||
/// Source inputs with no field here, by their source name, as authored. Color values are
|
||||
/// linear.
|
||||
pub other_inputs: Vec<(String, Vec<f32>)>,
|
||||
}
|
||||
|
||||
/// How a surface's alpha is used.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub enum AlphaMode {
|
||||
/// Alpha is ignored and the surface is opaque.
|
||||
#[default]
|
||||
Opaque,
|
||||
/// The surface is drawn where alpha is at least the cutoff, which is at least 0.
|
||||
Mask(f32),
|
||||
/// The surface is blended by alpha.
|
||||
Blend,
|
||||
}
|
||||
|
||||
/// A clear layer over the base: weight and perceptual roughness, each from 0 to 1.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Clearcoat {
|
||||
pub weight: f32,
|
||||
pub roughness: f32,
|
||||
}
|
||||
|
||||
/// A sheen layer: linear RGB color and perceptual roughness, each from 0 to 1.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Sheen {
|
||||
pub color: [f32; 3],
|
||||
pub roughness: f32,
|
||||
}
|
||||
|
||||
/// The value a texture sets, and which of its channels it reads.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum TextureInput {
|
||||
/// Base color in RGB; from glTF, alpha in A.
|
||||
BaseColor,
|
||||
/// glTF's packed texture: roughness in G and metallic in B.
|
||||
MetallicRoughness,
|
||||
/// Metallic in the first channel.
|
||||
Metallic,
|
||||
/// Roughness in the first channel.
|
||||
Roughness,
|
||||
/// A tangent-space normal map; [`TextureBinding::scale`] scales its X and Y.
|
||||
Normal,
|
||||
/// Ambient occlusion in R; [`TextureBinding::scale`] is its strength.
|
||||
Occlusion,
|
||||
/// Emission color in RGB.
|
||||
Emissive,
|
||||
/// Opacity: alpha in the first channel.
|
||||
Opacity,
|
||||
/// A colored opacity in RGB, such as Standard Surface's `opacity`; the alpha is its Rec.709
|
||||
/// luminance.
|
||||
OpacityRgb,
|
||||
/// Clearcoat weight in R.
|
||||
Clearcoat,
|
||||
/// glTF's clearcoat roughness texture: roughness in G.
|
||||
ClearcoatRoughness,
|
||||
/// Clearcoat roughness in the first channel.
|
||||
ClearcoatRoughnessFirst,
|
||||
/// Sheen color in RGB.
|
||||
SheenColor,
|
||||
/// glTF's sheen roughness texture: roughness in A.
|
||||
SheenRoughness,
|
||||
/// Sheen roughness in the first channel.
|
||||
SheenRoughnessFirst,
|
||||
/// Displacement height in the first channel.
|
||||
Displacement,
|
||||
/// A source input with no slot above, by its source name.
|
||||
Other(String),
|
||||
}
|
||||
|
||||
/// Where a texture's image is.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum TextureSource {
|
||||
/// An index into the source scene's images (`craft_mesh::Scene::images`).
|
||||
Image(usize),
|
||||
/// A file path, as the source document wrote it with any file prefix applied.
|
||||
File(String),
|
||||
}
|
||||
|
||||
/// How a texture's samples are encoded.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum TextureEncoding {
|
||||
/// Linear values, or data that is not a color.
|
||||
Linear,
|
||||
/// sRGB-encoded color.
|
||||
Srgb,
|
||||
/// A color space by the name the source gives it, which the caller converts.
|
||||
Named(String),
|
||||
}
|
||||
|
||||
/// How a texture continues outside 0..1.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum Wrap {
|
||||
#[default]
|
||||
Repeat,
|
||||
Clamp,
|
||||
Mirror,
|
||||
}
|
||||
|
||||
/// A UV transform: scale, then rotate by `rotation` radians, then add `offset`, in the order and
|
||||
/// with the signs of glTF's `KHR_texture_transform`. Every value is finite.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct UvTransform {
|
||||
pub offset: [f32; 2],
|
||||
pub rotation: f32,
|
||||
pub scale: [f32; 2],
|
||||
}
|
||||
|
||||
/// A texture bound to a value of a [`Surface`].
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TextureBinding {
|
||||
pub input: TextureInput,
|
||||
pub source: TextureSource,
|
||||
pub encoding: TextureEncoding,
|
||||
/// The UV set the texture reads.
|
||||
pub uv_set: u32,
|
||||
/// How the texture continues outside 0..1 along u and v.
|
||||
pub wrap: [Wrap; 2],
|
||||
pub transform: Option<UvTransform>,
|
||||
/// A finite scale on the samples: the normal scale of a normal map, the strength of an
|
||||
/// occlusion map, and 1 otherwise.
|
||||
pub scale: f32,
|
||||
}
|
||||
|
||||
/// A converted surface and what the conversion did not carry over exactly.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Conversion {
|
||||
pub surface: Surface,
|
||||
pub report: ConversionReport,
|
||||
}
|
||||
|
||||
/// What a conversion kept without shading, approximated or dropped, in the order it found them.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ConversionReport {
|
||||
pub items: Vec<ReportItem>,
|
||||
}
|
||||
|
||||
impl ConversionReport {
|
||||
/// Whether every source value went into a field that [`Material::try_direct`] shades or that
|
||||
/// a renderer applies (alpha, emission, sidedness), with nothing approximated or dropped.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.items.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// One entry of a [`ConversionReport`]. `input` is the source's name for the value.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub enum ReportItem {
|
||||
/// Kept on the [`Surface`] (a layer, a texture, an unlit flag or an other input), and not
|
||||
/// shaded by [`Material::try_direct`].
|
||||
Unshaded { input: String },
|
||||
/// Mapped with a change of meaning; `how` says what was done.
|
||||
Approximated { input: String, how: &'static str },
|
||||
/// Not kept; `why` says why.
|
||||
Dropped { input: String, why: &'static str },
|
||||
/// A warning the source reader gave.
|
||||
Warning(String),
|
||||
}
|
||||
|
||||
/// Why a material could not be converted. Nothing is clamped or replaced: a value out of its
|
||||
/// range is an error.
|
||||
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum ConvertError {
|
||||
/// A value is not a finite number, or is out of its range; `reason` says which.
|
||||
#[error("{input} {reason}")]
|
||||
BadValue { input: String, reason: &'static str },
|
||||
/// A value has the wrong number of components.
|
||||
#[error("{input} has {found} values where {expected} are needed")]
|
||||
Components { input: String, expected: usize, found: usize },
|
||||
/// A color value is in a color space the conversion does not decode.
|
||||
#[error("{input} is in the color space {colorspace}, which is not converted")]
|
||||
ColorSpace { input: String, colorspace: String },
|
||||
/// The source names an input more than once.
|
||||
#[error("the material has more than one {0} input")]
|
||||
Duplicate(String),
|
||||
/// The BRDF core rejected the converted values.
|
||||
#[error(transparent)]
|
||||
Material(#[from] PbrError),
|
||||
}
|
||||
|
||||
/// `v` when it is finite and in `lo..=hi`, else [`ConvertError::BadValue`] naming `input`.
|
||||
#[cfg(feature = "mesh")]
|
||||
pub(crate) fn checked(v: f32, lo: f32, hi: f32, input: &str, reason: &'static str) -> Result<f32, ConvertError> {
|
||||
if v.is_finite() && (lo..=hi).contains(&v) { Ok(v) } else { Err(ConvertError::BadValue { input: input.to_owned(), reason }) }
|
||||
}
|
||||
|
||||
/// The reason text for a value that must be from 0 to 1.
|
||||
#[cfg(any(feature = "mesh", feature = "materialx"))]
|
||||
pub(crate) const UNIT: &str = "is not a number from 0 to 1";
|
||||
/// The reason text for a value that must be finite and at least 0.
|
||||
#[cfg(any(feature = "mesh", feature = "materialx"))]
|
||||
pub(crate) const NON_NEGATIVE: &str = "is not a finite number of at least 0";
|
||||
/// The reason text for a value that must be finite.
|
||||
#[cfg(any(feature = "mesh", feature = "materialx"))]
|
||||
pub(crate) const FINITE: &str = "is not a finite number";
|
||||
@@ -0,0 +1,252 @@
|
||||
use craft_materialx::{Document, Resolved};
|
||||
use craft_mesh::Material as Mesh;
|
||||
use craft_pbr::{ConvertError, ReportItem, TextureInput, TextureSource, try_from_materialx, try_from_mesh};
|
||||
|
||||
fn document(shader: &str, inputs: &str, nodes: &str, material_inputs: &str) -> Document {
|
||||
let text = format!(
|
||||
r#"<materialx><{shader} name="S">{inputs}</{shader}>{nodes}<surfacematerial name="M"><input name="surfaceshader" nodename="S"/>{material_inputs}</surfacematerial></materialx>"#
|
||||
);
|
||||
Document::parse(text.as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inactive_emission_still_validates_the_color_field() {
|
||||
let doc = document("standard_surface", r#"<input name="emission" value="0"/><input name="emission_color" value="2,0,0"/>"#, "", "");
|
||||
let material = doc.read_material_strict(None).unwrap();
|
||||
assert!(matches!(try_from_materialx(&material), Err(ConvertError::BadValue { input, .. }) if input == "emission_color"));
|
||||
let legacy = doc.read_material(None).unwrap();
|
||||
assert!(!legacy.inputs.iter().any(|(name, _)| name == "emission_color"));
|
||||
let valid = document("standard_surface", r#"<input name="emission" value="0"/><input name="emission_color" value="0.2,0.3,0.4"/>"#, "", "");
|
||||
let converted = try_from_materialx(&valid.read_material_strict(None).unwrap()).unwrap();
|
||||
assert_eq!(converted.surface.emissive, [0.0; 3]);
|
||||
assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == "emission_color")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn displacement_scale_is_reported_when_it_is_not_applied() {
|
||||
for scale in ["", r#"<input name="scale" value="1"/>"#, r#"<input name="scale" value="2"/>"#] {
|
||||
let node = format!(r#"<displacement name="D"><input name="displacement" type="float" value="0.25"/>{scale}</displacement>"#);
|
||||
let doc = document("standard_surface", "", &node, r#"<input name="displacementshader" nodename="D"/>"#);
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert_eq!(converted.surface.other_inputs, vec![("displacement".into(), vec![0.25])]);
|
||||
assert_eq!(
|
||||
converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains("scale"))),
|
||||
scale.contains('2')
|
||||
);
|
||||
}
|
||||
for scale in ["1,2", "NaN", ""] {
|
||||
let node = format!(r#"<displacement name="D"><input name="displacement" value="0.25"/><input name="scale" value="{scale}"/></displacement>"#);
|
||||
assert!(document("standard_surface", "", &node, r#"<input name="displacementshader" nodename="D"/>"#).read_material_strict(None).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graph_surface_connections_preserve_the_shader_scope() {
|
||||
let doc = Document::parse(
|
||||
br#"<materialx><image name="T" type="color3"><input name="file" value="root.png"/></image>
|
||||
<nodegraph name="g"><image name="T" type="color3"><input name="file" value="graph.png"/></image>
|
||||
<standard_surface name="S"><input name="base_color" nodename="T"/></standard_surface>
|
||||
<output name="out" nodename="S"/></nodegraph>
|
||||
<surfacematerial name="M"><input name="surfaceshader" nodegraph="g" output="out"/></surfacematerial></materialx>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert_eq!(converted.surface.textures[0].source, TextureSource::File("graph.png".into()));
|
||||
assert!(doc.read_material(None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_authored_connections_do_not_become_shader_defaults() {
|
||||
for reference in [r#"nodename="missing""#, r#"nodegraph="missing" output="out""#] {
|
||||
let doc = document("open_pbr_surface", &format!(r#"<input name="base_color" {reference}/>"#), "", "");
|
||||
assert!(doc.read_material_strict(None).is_err(), "{reference}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nonzero_tiled_image_offset_is_reported() {
|
||||
for offset in ["0,0", "0.25,0"] {
|
||||
let nodes = format!(
|
||||
r#"<tiledimage name="T" type="color3"><input name="file" value="tile.png"/><input name="uvtiling" value="2,2"/><input name="uvoffset" value="{offset}"/></tiledimage>"#
|
||||
);
|
||||
let doc = document("open_pbr_surface", r#"<input name="base_color" nodename="T"/>"#, &nodes, "");
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert_eq!(converted.surface.textures[0].transform.unwrap().scale, [2.0, 2.0]);
|
||||
assert_eq!(
|
||||
converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains("uvoffset"))),
|
||||
offset != "0,0"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_omitted_color_constant_value_is_black() {
|
||||
let doc = document("open_pbr_surface", r#"<input name="base_color" nodename="K"/>"#, r#"<constant name="K" type="color3"/>"#, "");
|
||||
let material = doc.read_material_strict(None).unwrap();
|
||||
assert!(
|
||||
matches!(material.inputs.iter().find(|(name, _)| name == "base_color"), Some((_, Resolved::Constant { values, .. })) if values == &[0.0; 3])
|
||||
);
|
||||
assert_eq!(try_from_materialx(&material).unwrap().surface.material.base_color(), [0.0; 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_authored_cutoff_is_reported_when_the_alpha_mode_does_not_use_it() {
|
||||
for mode in [0, 1, 2] {
|
||||
let doc = document("gltf_pbr", &format!(r#"<input name="alpha_mode" value="{mode}"/><input name="alpha_cutoff" value="0.25"/>"#), "", "");
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert_eq!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == "alpha_cutoff")), mode != 1);
|
||||
if mode == 1 {
|
||||
assert_eq!(converted.surface.alpha_mode, craft_pbr::AlphaMode::Mask(0.25));
|
||||
}
|
||||
let absent = document("gltf_pbr", &format!(r#"<input name="alpha_mode" value="{mode}"/>"#), "", "");
|
||||
let converted = try_from_materialx(&absent.read_material_strict(None).unwrap()).unwrap();
|
||||
assert!(!converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == "alpha_cutoff")));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_displacement_is_reported_without_a_scalar_height_binding() {
|
||||
for source in [r#"type="vector3" value="0.1,0.2,0.3""#, r#"type="vector3" nodename="T""#, r#"value="0.1,0.2,0.3""#] {
|
||||
let nodes = format!(
|
||||
r#"<image name="T" type="vector3"><input name="file" value="vector.png"/></image><displacement name="D"><input name="displacement" {source}/></displacement>"#
|
||||
);
|
||||
let doc = document("standard_surface", "", &nodes, r#"<input name="displacementshader" nodename="D"/>"#);
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert!(!converted.surface.textures.iter().any(|texture| texture.input == TextureInput::Displacement));
|
||||
assert!(!converted.surface.other_inputs.iter().any(|(name, _)| name == "displacement"));
|
||||
assert!(
|
||||
converted
|
||||
.report
|
||||
.items
|
||||
.iter()
|
||||
.any(|item| matches!(item, ReportItem::Warning(message) if message.contains("vector") && message.contains("displacement")))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inactive_mesh_layers_report_nondefault_roughness() {
|
||||
assert!(try_from_mesh(&Mesh::default()).unwrap().report.is_empty());
|
||||
let converted = try_from_mesh(&Mesh { clearcoat_roughness: 0.5, sheen_roughness: 0.5, ..Mesh::default() }).unwrap();
|
||||
for field in ["clearcoat_roughness", "sheen_roughness"] {
|
||||
assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == field)), "{field}");
|
||||
}
|
||||
let active =
|
||||
try_from_mesh(&Mesh { clearcoat: 1.0, clearcoat_roughness: 0.5, sheen_color: [0.2; 3], sheen_roughness: 0.5, ..Mesh::default() }).unwrap();
|
||||
assert_eq!(active.surface.clearcoat.unwrap().roughness, 0.5);
|
||||
assert_eq!(active.surface.sheen.unwrap().roughness, 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn omitted_numeric_constants_use_their_typed_zero_values() {
|
||||
for (kind, count) in [("float", 1), ("integer", 1), ("boolean", 1), ("vector2", 2), ("vector3", 3), ("vector4", 4), ("color3", 3), ("color4", 4)]
|
||||
{
|
||||
let doc = document("open_pbr_surface", r#"<input name="base_color" nodename="K"/>"#, &format!(r#"<constant name="K" type="{kind}"/>"#), "");
|
||||
let material = doc.read_material_strict(None).unwrap();
|
||||
assert!(
|
||||
matches!(material.inputs.iter().find(|(name, _)| name == "base_color"), Some((_, Resolved::Constant { values, .. })) if values == &vec![0.0; count]),
|
||||
"{kind}"
|
||||
);
|
||||
}
|
||||
let unsupported = document("open_pbr_surface", r#"<input name="base_color" nodename="K"/>"#, r#"<constant name="K" type="matrix33"/>"#, "");
|
||||
let material = unsupported.read_material_strict(None).unwrap();
|
||||
assert!(material.inputs.is_empty() && !material.warnings.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_graph_output_selection_rejects_ambiguity() {
|
||||
let read = |outputs: &str, selection: &str| {
|
||||
Document::parse(
|
||||
format!(
|
||||
r#"<materialx><nodegraph name="g">
|
||||
<standard_surface name="A"><input name="base_color" value="0.2,0.2,0.2"/></standard_surface>
|
||||
<standard_surface name="B"><input name="base_color" value="0.8,0.8,0.8"/></standard_surface>{outputs}</nodegraph>
|
||||
<surfacematerial name="M"><input name="surfaceshader" nodegraph="g" {selection}/></surfacematerial></materialx>"#
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.unwrap()
|
||||
.read_material_strict(None)
|
||||
};
|
||||
let both = r#"<output name="a" nodename="A"/><output name="b" nodename="B"/>"#;
|
||||
assert!(read(both, "").is_err());
|
||||
assert!(read(both, r#"output="missing""#).is_err());
|
||||
assert_eq!(try_from_materialx(&read(both, r#"output="b""#).unwrap()).unwrap().surface.material.base_color(), [0.8; 3]);
|
||||
let sole = read(r#"<output name="a" nodename="A"/>"#, r#"output="unused""#).unwrap();
|
||||
assert_eq!(try_from_materialx(&sole).unwrap().surface.material.base_color(), [0.2; 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn omitted_node_parameters_keep_their_identity_defaults() {
|
||||
let displaced = document(
|
||||
"standard_surface",
|
||||
"",
|
||||
r#"<displacement name="D"><input name="displacement" value="0.25"/><input name="scale" type="float"/></displacement>"#,
|
||||
r#"<input name="displacementshader" nodename="D"/>"#,
|
||||
);
|
||||
assert!(displaced.read_material_strict(None).unwrap().warnings.is_empty());
|
||||
let image = document(
|
||||
"open_pbr_surface",
|
||||
r#"<input name="base_color" nodename="T"/>"#,
|
||||
r#"<tiledimage name="T" type="color3"><input name="file" value="tile.png"/><input name="uvoffset" type="vector2"/></tiledimage>"#,
|
||||
"",
|
||||
);
|
||||
assert!(image.read_material_strict(None).unwrap().warnings.is_empty());
|
||||
let normal = document(
|
||||
"open_pbr_surface",
|
||||
r#"<input name="geometry_normal" nodename="N"/>"#,
|
||||
r#"<normalmap name="N"><input name="in" nodename="T"/><input name="scale" type="float"/></normalmap><image name="T" type="vector3"><input name="file" value="n.png"/></image>"#,
|
||||
"",
|
||||
);
|
||||
assert!(normal.read_material_strict(None).unwrap().warnings.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interface_connections_report_the_unsupported_value() {
|
||||
let doc = Document::parse(
|
||||
br#"<materialx><nodegraph name="g"><input name="tint" type="color3" value="0.2,0.3,0.4"/>
|
||||
<standard_surface name="S"><input name="base_color" interfacename="tint" value="0.8,0.8,0.8"/></standard_surface>
|
||||
<output name="out" nodename="S"/></nodegraph><surfacematerial name="M">
|
||||
<input name="surfaceshader" nodegraph="g"/></surfacematerial></materialx>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert!(
|
||||
converted
|
||||
.report
|
||||
.items
|
||||
.iter()
|
||||
.any(|item| matches!(item, ReportItem::Warning(message) if message.contains("interface") && message.contains("tint")))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connected_image_tiling_keeps_the_resolved_scale() {
|
||||
for connection in [r#"nodename="K""#, r#"nodegraph="g""#] {
|
||||
let nodes = format!(
|
||||
r#"<tiledimage name="T" type="color3"><input name="file" value="tile.png"/><input name="uvtiling" {connection}/></tiledimage>
|
||||
<constant name="K" type="vector2"><input name="value" value="2,3"/></constant>
|
||||
<nodegraph name="g"><constant name="K" type="vector2"><input name="value" value="2,3"/></constant><output name="out" nodename="K"/></nodegraph>"#
|
||||
);
|
||||
let doc = document("standard_surface", r#"<input name="base_color" nodename="T"/>"#, &nodes, "");
|
||||
let material = doc.read_material_strict(None).unwrap();
|
||||
assert!(material.warnings.is_empty(), "{:?}", material.warnings);
|
||||
assert_eq!(material.uv_tiling, [2.0, 3.0]);
|
||||
let converted = try_from_materialx(&material).unwrap();
|
||||
let binding = converted.surface.textures.iter().find(|binding| binding.input == TextureInput::BaseColor).unwrap();
|
||||
assert_eq!(binding.transform.as_ref().map(|transform| transform.scale), Some([2.0, 3.0]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn images_without_literal_file_values_report_the_skipped_texture() {
|
||||
for kind in ["image", "tiledimage"] {
|
||||
for file in ["", r#"<input name="file"/>"#, r#"<input name="file" value=""/>"#, r#"<input name="file" interfacename="filename"/>"#] {
|
||||
let nodes = format!(r#"<{kind} name="T" type="color3">{file}</{kind}>"#);
|
||||
let doc = document("standard_surface", r#"<input name="base_color" nodename="T"/>"#, &nodes, "");
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert!(converted.surface.textures.is_empty());
|
||||
assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains("file"))));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
use craft_materialx::Document;
|
||||
use craft_mesh::Material;
|
||||
use craft_pbr::{ReportItem, TextureInput, try_from_materialx, try_from_mesh};
|
||||
|
||||
fn document(input: &str, nodes: &str) -> Document {
|
||||
Document::parse(
|
||||
format!(
|
||||
r#"<materialx><open_pbr_surface name="S">{input}</open_pbr_surface>{nodes}<surfacematerial name="M"><input name="surfaceshader" nodename="S"/></surfacematerial></materialx>"#
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_output_without_a_target_does_not_select_another_output() {
|
||||
let doc = Document::parse(
|
||||
br#"<materialx><nodegraph name="g"><open_pbr_surface name="S"/>
|
||||
<output name="a" nodename="S"/><output name="b"/></nodegraph>
|
||||
<surfacematerial name="M"><input name="surfaceshader" nodegraph="g" output="b"/></surfacematerial></materialx>"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(doc.read_material_strict(None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nondefault_image_addressing_modes_are_reported() {
|
||||
for name in ["uaddressmode", "vaddressmode"] {
|
||||
for mode in ["constant", "clamp", "mirror"] {
|
||||
let node =
|
||||
format!(r#"<image name="T" type="color3"><input name="file" value="color.png"/><input name="{name}" value="{mode}"/></image>"#);
|
||||
let doc = document(r#"<input name="base_color" nodename="T"/>"#, &node);
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains(name))));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_identified_convert_node_uses_its_omitted_input_default() {
|
||||
let doc = document(r#"<input name="base_color" nodename="C"/>"#, r#"<convert name="C" type="color3" nodedef="ND_convert_float_color3"/>"#);
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert_eq!(converted.surface.material.base_color(), [0.0; 3]);
|
||||
assert!(converted.report.is_empty(), "{:?}", converted.report);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_literals_use_the_nodes_type_when_the_input_omits_it() {
|
||||
for (ty, value) in [("integer", "0.5"), ("float", "1,2"), ("color3", "1,2")] {
|
||||
let node = format!(r#"<constant name="C" type="{ty}"><input name="value" value="{value}"/></constant>"#);
|
||||
let doc = document(r#"<input name="base_color" nodename="C"/>"#, &node);
|
||||
assert!(doc.read_material_strict(None).is_err(), "{ty} {value}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_graph_local_node_does_not_bind_a_root_node() {
|
||||
let doc = Document::parse(
|
||||
br#"<materialx><image name="T" type="color3"><input name="file" value="root.png"/></image>
|
||||
<nodegraph name="g"><open_pbr_surface name="S"><input name="base_color" nodename="T"/></open_pbr_surface>
|
||||
<output name="out" nodename="S"/></nodegraph><surfacematerial name="M">
|
||||
<input name="surfaceshader" nodegraph="g"/></surfacematerial></materialx>"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(doc.read_material_strict(None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_normal_vectors_are_not_bound_as_tangent_space_maps() {
|
||||
let image = r#"<image name="T" type="vector3"><input name="file" value="normal.png"/></image>"#;
|
||||
let direct = document(r#"<input name="geometry_normal" nodename="T"/>"#, image);
|
||||
let converted = try_from_materialx(&direct.read_material_strict(None).unwrap()).unwrap();
|
||||
assert!(!converted.surface.textures.iter().any(|binding| binding.input == TextureInput::Normal));
|
||||
assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == "geometry_normal")));
|
||||
let nodes = format!(r#"{image}<normalmap name="N" type="vector3"><input name="in" nodename="T"/></normalmap>"#);
|
||||
let wrapped = document(r#"<input name="geometry_normal" nodename="N"/>"#, &nodes);
|
||||
let converted = try_from_materialx(&wrapped.read_material_strict(None).unwrap()).unwrap();
|
||||
assert!(converted.surface.textures.iter().any(|binding| binding.input == TextureInput::Normal));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nondefault_factors_without_textures_are_reported() {
|
||||
let material = Material { normal_scale: 0.5, occlusion_strength: 0.25, ..Material::default() };
|
||||
let converted = try_from_mesh(&material).unwrap();
|
||||
for name in ["normal_scale", "occlusion_strength"] {
|
||||
assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == name)));
|
||||
}
|
||||
assert!(try_from_mesh(&Material::default()).unwrap().report.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_normalmaps_are_reported_and_skipped() {
|
||||
let nodes = r#"<image name="T" type="vector3"><input name="file" value="normal.png"/></image>
|
||||
<normalmap name="Inner" type="vector3"><input name="in" nodename="T"/></normalmap>
|
||||
<normalmap name="Outer" type="vector3"><input name="in" nodename="Inner"/></normalmap>"#;
|
||||
let doc = document(r#"<input name="geometry_normal" nodename="Outer"/>"#, nodes);
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert!(!converted.surface.textures.iter().any(|binding| binding.input == TextureInput::Normal));
|
||||
assert!(
|
||||
converted
|
||||
.report
|
||||
.items
|
||||
.iter()
|
||||
.any(|item| matches!(item, ReportItem::Warning(message) if message.contains("nested") && message.contains("Outer")))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalmap_literals_do_not_become_untransformed_world_normals() {
|
||||
for value in ["1,0.5,1", "0.5,0.5,1"] {
|
||||
let doc = document(
|
||||
r#"<input name="geometry_normal" nodename="N"/>"#,
|
||||
&format!(r#"<normalmap name="N" type="vector3"><input name="in" value="{value}"/></normalmap>"#),
|
||||
);
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert!(!converted.surface.other_inputs.iter().any(|(name, _)| name == "geometry_normal"));
|
||||
assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains("normalmap"))));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authored_normalmap_frames_are_reported() {
|
||||
for name in ["normal", "tangent", "bitangent"] {
|
||||
let nodes = format!(
|
||||
r#"<image name="T" type="vector3"><input name="file" value="normal.png"/></image>
|
||||
<normalmap name="N" type="vector3"><input name="in" nodename="T"/><input name="{name}" type="vector3" value="1,0,0"/></normalmap>"#
|
||||
);
|
||||
let doc = document(r#"<input name="geometry_normal" nodename="N"/>"#, &nodes);
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert!(converted.report.items.iter().any(|item| matches!(item, ReportItem::Warning(message) if message.contains(name))));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coat_normals_keep_tangent_maps_and_report_direct_world_images() {
|
||||
for (shader, weight, normal) in [
|
||||
("open_pbr_surface", "coat_weight", "geometry_coat_normal"),
|
||||
("standard_surface", "coat", "coat_normal"),
|
||||
("gltf_pbr", "clearcoat", "clearcoat_normal"),
|
||||
] {
|
||||
for (node, wrapped) in [("T", false), ("N", true)] {
|
||||
let xml = format!(
|
||||
r#"<materialx><{shader} name="S"><input name="{weight}" value="1"/><input name="{normal}" nodename="{node}"/></{shader}>
|
||||
<image name="T" type="vector3"><input name="file" value="normal.png"/></image>
|
||||
<normalmap name="N" type="vector3"><input name="in" nodename="T"/></normalmap>
|
||||
<surfacematerial name="M"><input name="surfaceshader" nodename="S"/></surfacematerial></materialx>"#
|
||||
);
|
||||
let doc = Document::parse(xml.as_bytes()).unwrap();
|
||||
let converted = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
converted.surface.textures.iter().any(|binding| matches!(&binding.input, TextureInput::Other(name) if name == normal)),
|
||||
wrapped,
|
||||
"{shader} {node}"
|
||||
);
|
||||
assert_eq!(
|
||||
converted.report.items.iter().any(|item| matches!(item, ReportItem::Dropped { input, .. } if input == normal)),
|
||||
!wrapped,
|
||||
"{shader} {node}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,724 @@
|
||||
//! Conversions into a `Surface`: glTF 2.0 materials from craft-mesh and MaterialX shaders from
|
||||
//! craft-materialx, checked against the defaults and ranges the public definitions give.
|
||||
|
||||
use craft_materialx::{Document, Resolved as Value, Shader, StrictMaterial as Mx, Texture, write_open_pbr};
|
||||
use craft_mesh::{AlphaMode as MeshAlpha, Material as Mesh, TextureRef, UvTransform as MeshUv, Wrap as MeshWrap};
|
||||
use craft_pbr::{
|
||||
AlphaMode, Clearcoat, Conversion, ConvertError, ReportItem, Sheen, TextureEncoding, TextureInput, TextureSource, UvTransform, Wrap,
|
||||
try_from_materialx, try_from_mesh,
|
||||
};
|
||||
|
||||
fn close(a: f32, b: f32) -> bool {
|
||||
a.is_finite() && b.is_finite() && (a - b).abs() <= 1e-6 * a.abs().max(b.abs()).max(1.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_is_false_for_values_that_are_not_finite() {
|
||||
assert!(close(1.0, 1.0 + 1e-7));
|
||||
assert!(!close(f32::INFINITY, 1.0) && !close(f32::INFINITY, f32::INFINITY) && !close(f32::NAN, 1.0));
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn assert_close3(a: [f32; 3], b: [f32; 3]) {
|
||||
assert!(a.iter().zip(b).all(|(x, y)| close(*x, y)), "{a:?} against {b:?}");
|
||||
}
|
||||
|
||||
fn unshaded(c: &Conversion, input: &str) -> bool {
|
||||
c.report.items.iter().any(|i| matches!(i, ReportItem::Unshaded { input: n } if n == input))
|
||||
}
|
||||
|
||||
fn approximated(c: &Conversion, input: &str) -> bool {
|
||||
c.report.items.iter().any(|i| matches!(i, ReportItem::Approximated { input: n, .. } if n == input))
|
||||
}
|
||||
|
||||
fn dropped(c: &Conversion, input: &str) -> bool {
|
||||
c.report.items.iter().any(|i| matches!(i, ReportItem::Dropped { input: n, .. } if n == input))
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn bad_value(r: Result<Conversion, ConvertError>, input: &str) {
|
||||
match r {
|
||||
Err(ConvertError::BadValue { input: n, .. }) => assert!(n.contains(input), "{n} is not {input}"),
|
||||
other => panic!("{input}: expected a bad value, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn tex(image: usize) -> Option<TextureRef> {
|
||||
Some(TextureRef { image, ..TextureRef::default() })
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ craft-mesh (glTF 2.0)
|
||||
|
||||
#[test]
|
||||
fn mesh_factors_map_as_they_are() {
|
||||
let m = Mesh {
|
||||
name: "Paint".into(),
|
||||
base_color: [0.25, 0.5, 0.75, 0.6],
|
||||
metallic: 0.3,
|
||||
roughness: 0.7,
|
||||
emissive: [2.0, 0.5, 0.0],
|
||||
alpha_mode: MeshAlpha::Mask(0.4),
|
||||
double_sided: true,
|
||||
..Mesh::default()
|
||||
};
|
||||
let c = try_from_mesh(&m).unwrap();
|
||||
let s = &c.surface;
|
||||
assert_eq!(s.name, "Paint");
|
||||
assert_eq!(s.material.base_color(), [0.25, 0.5, 0.75]);
|
||||
assert_eq!((s.material.metallic(), s.material.roughness()), (0.3, 0.7));
|
||||
assert_eq!((s.material.specular(), s.material.diffuse()), (1.0, 1.0));
|
||||
assert_eq!(s.alpha, 0.6);
|
||||
assert_eq!(s.alpha_mode, AlphaMode::Mask(0.4));
|
||||
assert_eq!(s.emissive, [2.0, 0.5, 0.0]);
|
||||
assert!(s.double_sided && !s.unlit);
|
||||
assert_eq!((s.clearcoat, s.sheen), (None, None));
|
||||
assert!(s.textures.is_empty() && s.other_inputs.is_empty());
|
||||
assert!(c.report.is_empty(), "{:?}", c.report);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_defaults_are_the_gltf_defaults() {
|
||||
// glTF 2.0 gives baseColorFactor [1, 1, 1, 1], metallicFactor 1, roughnessFactor 1,
|
||||
// emissiveFactor [0, 0, 0] and alphaMode OPAQUE
|
||||
// (https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#reference-material).
|
||||
let c = try_from_mesh(&Mesh::default()).unwrap();
|
||||
let s = &c.surface;
|
||||
assert_eq!(s.material.base_color(), [1.0; 3]);
|
||||
assert_eq!((s.material.metallic(), s.material.roughness(), s.alpha), (1.0, 1.0, 1.0));
|
||||
assert_eq!((s.emissive, s.alpha_mode), ([0.0; 3], AlphaMode::Opaque));
|
||||
assert!(!s.double_sided);
|
||||
assert!(c.report.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_extensions_that_are_not_converted_are_reported_as_dropped() {
|
||||
let mut m = Mesh::default();
|
||||
for name in ["KHR_materials_transmission", "KHR_materials_clearcoat", "KHR_materials_unlit", "KHR_materials_emissive_strength"] {
|
||||
m.extensions.insert(name.into(), craft_mesh::serde_json::json!({}));
|
||||
}
|
||||
let c = try_from_mesh(&m).unwrap();
|
||||
assert!(dropped(&c, "KHR_materials_transmission"), "{:?}", c.report);
|
||||
assert_eq!(c.report.items.len(), 1, "{:?}", c.report);
|
||||
// craft-mesh reads part of these two.
|
||||
m.extensions.insert("KHR_materials_clearcoat".into(), craft_mesh::serde_json::json!({ "clearcoatNormalTexture": { "index": 0 } }));
|
||||
m.extensions.insert("KHR_materials_pbrSpecularGlossiness".into(), craft_mesh::serde_json::json!({ "specularFactor": [1, 0, 0] }));
|
||||
let c = try_from_mesh(&m).unwrap();
|
||||
assert!(dropped(&c, "clearcoatNormalTexture"), "{:?}", c.report);
|
||||
assert!(approximated(&c, "KHR_materials_pbrSpecularGlossiness"), "{:?}", c.report);
|
||||
assert_eq!(c.report.items.len(), 3, "{:?}", c.report);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_textures_keep_their_uv_state_scale_and_encoding() {
|
||||
let mr = TextureRef {
|
||||
image: 2,
|
||||
uv_set: 1,
|
||||
wrap: [MeshWrap::Clamp, MeshWrap::Mirror],
|
||||
transform: Some(MeshUv { offset: [0.25, 0.5], rotation: 0.5, scale: [2.0, 3.0] }),
|
||||
};
|
||||
let m = Mesh {
|
||||
base_color_texture: tex(1),
|
||||
metallic_roughness_texture: Some(mr),
|
||||
normal_texture: tex(3),
|
||||
normal_scale: 0.5,
|
||||
occlusion_texture: tex(4),
|
||||
occlusion_strength: 0.25,
|
||||
emissive_texture: tex(5),
|
||||
clearcoat: 0.5,
|
||||
clearcoat_texture: tex(6),
|
||||
clearcoat_roughness_texture: tex(7),
|
||||
sheen_color: [0.1, 0.0, 0.0],
|
||||
sheen_color_texture: tex(8),
|
||||
sheen_roughness_texture: tex(9),
|
||||
..Mesh::default()
|
||||
};
|
||||
let c = try_from_mesh(&m).unwrap();
|
||||
// Base color, emissive and sheen color textures are sRGB, the rest linear (glTF 2.0 and
|
||||
// KHR_materials_sheen); the packed texture holds roughness in G and metallic in B.
|
||||
let expected = [
|
||||
("base_color_texture", TextureInput::BaseColor, TextureEncoding::Srgb),
|
||||
("metallic_roughness_texture", TextureInput::MetallicRoughness, TextureEncoding::Linear),
|
||||
("normal_texture", TextureInput::Normal, TextureEncoding::Linear),
|
||||
("occlusion_texture", TextureInput::Occlusion, TextureEncoding::Linear),
|
||||
("emissive_texture", TextureInput::Emissive, TextureEncoding::Srgb),
|
||||
("clearcoat_texture", TextureInput::Clearcoat, TextureEncoding::Linear),
|
||||
("clearcoat_roughness_texture", TextureInput::ClearcoatRoughness, TextureEncoding::Linear),
|
||||
("sheen_color_texture", TextureInput::SheenColor, TextureEncoding::Srgb),
|
||||
("sheen_roughness_texture", TextureInput::SheenRoughness, TextureEncoding::Linear),
|
||||
];
|
||||
assert_eq!(c.surface.textures.len(), expected.len());
|
||||
for (i, ((name, input, encoding), b)) in expected.into_iter().zip(&c.surface.textures).enumerate() {
|
||||
assert_eq!((&b.input, &b.encoding, &b.source), (&input, &encoding, &TextureSource::Image(i + 1)), "{name}");
|
||||
assert!(unshaded(&c, name), "{name}");
|
||||
}
|
||||
let mr = &c.surface.textures[1];
|
||||
assert_eq!((mr.uv_set, mr.wrap), (1, [Wrap::Clamp, Wrap::Mirror]));
|
||||
assert_eq!(mr.transform, Some(UvTransform { offset: [0.25, 0.5], rotation: 0.5, scale: [2.0, 3.0] }));
|
||||
assert_eq!((c.surface.textures[2].scale, c.surface.textures[3].scale, c.surface.textures[0].scale), (0.5, 0.25, 1.0));
|
||||
assert_eq!(c.surface.textures[0].transform, None);
|
||||
// The core holds the factors the textures multiply: glTF's defaults here.
|
||||
assert_eq!((c.surface.material.metallic(), c.surface.material.roughness()), (1.0, 1.0));
|
||||
assert!(unshaded(&c, "clearcoat") && unshaded(&c, "sheen"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_clearcoat_and_sheen_are_kept_and_layers_that_are_off_drop_their_textures() {
|
||||
let on = Mesh { clearcoat: 0.75, clearcoat_roughness: 0.25, sheen_color: [0.5, 0.25, 0.0], sheen_roughness: 0.6, ..Mesh::default() };
|
||||
let c = try_from_mesh(&on).unwrap();
|
||||
assert_eq!(c.surface.clearcoat, Some(Clearcoat { weight: 0.75, roughness: 0.25 }));
|
||||
assert_eq!(c.surface.sheen, Some(Sheen { color: [0.5, 0.25, 0.0], roughness: 0.6 }));
|
||||
// A clearcoat factor of 0 and a black sheen color each turn their layer off
|
||||
// (KHR_materials_clearcoat, KHR_materials_sheen).
|
||||
let off = Mesh {
|
||||
clearcoat_roughness: 0.5,
|
||||
clearcoat_texture: tex(1),
|
||||
clearcoat_roughness_texture: tex(2),
|
||||
sheen_roughness: 0.5,
|
||||
sheen_color_texture: tex(3),
|
||||
sheen_roughness_texture: tex(4),
|
||||
..Mesh::default()
|
||||
};
|
||||
let c = try_from_mesh(&off).unwrap();
|
||||
assert_eq!((c.surface.clearcoat, c.surface.sheen), (None, None));
|
||||
assert!(c.surface.textures.is_empty());
|
||||
for name in ["clearcoat_texture", "clearcoat_roughness_texture", "sheen_color_texture", "sheen_roughness_texture"] {
|
||||
assert!(dropped(&c, name), "{name}");
|
||||
}
|
||||
assert!(!unshaded(&c, "clearcoat") && !unshaded(&c, "sheen"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_textures_of_a_layer_that_is_off_are_checked_before_they_are_dropped() {
|
||||
let t = TextureRef { transform: Some(MeshUv { rotation: f32::NAN, ..MeshUv::default() }), ..TextureRef::default() };
|
||||
bad_value(try_from_mesh(&Mesh { clearcoat_roughness_texture: Some(t), ..Mesh::default() }), "clearcoat_roughness_texture transform");
|
||||
bad_value(try_from_mesh(&Mesh { sheen_color_texture: Some(t), ..Mesh::default() }), "sheen_color_texture transform");
|
||||
let fine = TextureRef { transform: Some(MeshUv { rotation: 0.5, ..MeshUv::default() }), ..TextureRef::default() };
|
||||
let c = try_from_mesh(&Mesh { clearcoat_texture: Some(fine), ..Mesh::default() }).unwrap();
|
||||
assert!(c.surface.textures.is_empty() && dropped(&c, "clearcoat_texture"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_unlit_is_kept_and_reported() {
|
||||
let c = try_from_mesh(&Mesh { unlit: true, base_color: [0.2, 0.4, 0.6, 1.0], ..Mesh::default() }).unwrap();
|
||||
assert!(c.surface.unlit);
|
||||
assert_eq!(c.surface.material.base_color(), [0.2, 0.4, 0.6]);
|
||||
assert!(unshaded(&c, "unlit"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_values_that_are_not_finite_or_out_of_range_are_errors() {
|
||||
type Set = fn(&mut Mesh, f32);
|
||||
let unit: [(&str, Set); 8] = [
|
||||
("base_color", |m, v| m.base_color[1] = v),
|
||||
("base_color alpha", |m, v| m.base_color[3] = v),
|
||||
("metallic", |m, v| m.metallic = v),
|
||||
("roughness", |m, v| m.roughness = v),
|
||||
("occlusion_strength", |m, v| m.occlusion_strength = v),
|
||||
("clearcoat", |m, v| m.clearcoat = v),
|
||||
("clearcoat_roughness", |m, v| m.clearcoat_roughness = v),
|
||||
("sheen_color", |m, v| m.sheen_color[2] = v),
|
||||
];
|
||||
for (name, set) in unit.iter().chain([("sheen_roughness", (|m: &mut Mesh, v| m.sheen_roughness = v) as Set)].iter()) {
|
||||
for v in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.01, 1.01] {
|
||||
let mut m = Mesh::default();
|
||||
set(&mut m, v);
|
||||
bad_value(try_from_mesh(&m), name);
|
||||
}
|
||||
for v in [0.0, 1.0] {
|
||||
let mut m = Mesh::default();
|
||||
set(&mut m, v);
|
||||
assert!(try_from_mesh(&m).is_ok(), "{name} {v}");
|
||||
}
|
||||
}
|
||||
for v in [f32::NAN, f32::INFINITY, -1.0] {
|
||||
bad_value(try_from_mesh(&Mesh { emissive: [0.0, v, 0.0], ..Mesh::default() }), "emissive");
|
||||
bad_value(try_from_mesh(&Mesh { alpha_mode: MeshAlpha::Mask(v), ..Mesh::default() }), "alpha cutoff");
|
||||
}
|
||||
for v in [f32::NAN, f32::INFINITY] {
|
||||
bad_value(try_from_mesh(&Mesh { normal_scale: v, ..Mesh::default() }), "normal_scale");
|
||||
let t = TextureRef { transform: Some(MeshUv { rotation: v, ..MeshUv::default() }), ..TextureRef::default() };
|
||||
bad_value(try_from_mesh(&Mesh { emissive_texture: Some(t), ..Mesh::default() }), "emissive_texture transform");
|
||||
}
|
||||
// Emission above 1, a cutoff above 1 and a negative normal scale are in range.
|
||||
let wide = Mesh { emissive: [40.0; 3], alpha_mode: MeshAlpha::Mask(2.0), normal_scale: -1.0, ..Mesh::default() };
|
||||
let c = try_from_mesh(&wide).unwrap();
|
||||
assert_eq!((c.surface.emissive, c.surface.alpha_mode), ([40.0; 3], AlphaMode::Mask(2.0)));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ craft-materialx
|
||||
|
||||
fn mx(shader: Shader, inputs: &[(&str, Value)]) -> Mx {
|
||||
Mx {
|
||||
name: "M".into(),
|
||||
shader,
|
||||
inputs: inputs.iter().map(|(n, v)| ((*n).to_owned(), v.clone())).collect(),
|
||||
displacement: None,
|
||||
uv_tiling: [1.0, 1.0],
|
||||
warnings: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn k(values: &[f32]) -> Value {
|
||||
Value::Constant { values: values.to_vec(), colorspace: None }
|
||||
}
|
||||
|
||||
fn ks(values: &[f32], space: &str) -> Value {
|
||||
Value::Constant { values: values.to_vec(), colorspace: Some(space.into()) }
|
||||
}
|
||||
|
||||
fn img(file: &str, space: Option<&str>, tiling: Option<[f32; 2]>) -> Value {
|
||||
Value::Image { file: file.into(), colorspace: space.map(str::to_owned), uv_tiling: tiling }
|
||||
}
|
||||
|
||||
/// Schlick's reflectance at normal incidence for an index of refraction, as the specular weight
|
||||
/// of the core: `((n − 1) / (n + 1))² / 0.04`.
|
||||
fn specular_for_ior(n: f64) -> f32 {
|
||||
(((n - 1.0) / (n + 1.0)).powi(2) / 0.04) as f32
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_empty_inputs_give_each_shaders_defaults() {
|
||||
// The defaults of the node definitions in MaterialX's libraries/bxdf: open_pbr_surface.mtlx,
|
||||
// standard_surface.mtlx (version 1.0.1) and gltf_pbr.mtlx
|
||||
// (https://github.com/AcademySoftwareFoundation/MaterialX/tree/main/libraries/bxdf).
|
||||
let open = try_from_materialx(&mx(Shader::OpenPbr, &[])).unwrap();
|
||||
let s = &open.surface;
|
||||
assert_close3(s.material.base_color(), [0.8; 3]);
|
||||
assert_eq!((s.material.metallic(), s.material.roughness(), s.material.specular()), (0.0, 0.3, 1.0));
|
||||
assert_eq!((s.alpha, s.alpha_mode, s.emissive), (1.0, AlphaMode::Opaque, [0.0; 3]));
|
||||
assert_eq!((s.clearcoat, s.sheen), (None, None));
|
||||
assert!(open.report.is_empty(), "{:?}", open.report);
|
||||
|
||||
let standard = try_from_materialx(&mx(Shader::StandardSurface, &[])).unwrap();
|
||||
let s = &standard.surface;
|
||||
assert_close3(s.material.base_color(), [0.8; 3]);
|
||||
assert_eq!((s.material.metallic(), s.material.roughness(), s.material.specular()), (0.0, 0.2, 1.0));
|
||||
assert_eq!((s.alpha, s.alpha_mode, s.emissive), (1.0, AlphaMode::Opaque, [0.0; 3]));
|
||||
assert_eq!((s.clearcoat, s.sheen), (None, None));
|
||||
assert!(standard.report.is_empty(), "{:?}", standard.report);
|
||||
|
||||
let gltf = try_from_materialx(&mx(Shader::GltfPbr, &[])).unwrap();
|
||||
let s = &gltf.surface;
|
||||
assert_eq!(s.material.base_color(), [1.0; 3]);
|
||||
assert_eq!((s.material.metallic(), s.material.roughness(), s.material.specular()), (1.0, 1.0, 1.0));
|
||||
assert_eq!((s.alpha, s.alpha_mode, s.emissive), (1.0, AlphaMode::Opaque, [0.0; 3]));
|
||||
assert_eq!((s.clearcoat, s.sheen), (None, None));
|
||||
assert!(gltf.report.is_empty(), "{:?}", gltf.report);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_base_weight_scales_the_base_color_and_specular_follows_weight_and_ior() {
|
||||
let c =
|
||||
try_from_materialx(&mx(Shader::OpenPbr, &[("base_color", k(&[0.5, 0.4, 0.2])), ("base_weight", k(&[0.5])), ("base_metalness", k(&[0.25]))]))
|
||||
.unwrap();
|
||||
assert_close3(c.surface.material.base_color(), [0.25, 0.2, 0.1]);
|
||||
assert_eq!(c.surface.material.metallic(), 0.25);
|
||||
assert!(c.report.is_empty(), "{:?}", c.report);
|
||||
let standard = try_from_materialx(&mx(Shader::StandardSurface, &[("base", k(&[0.5])), ("specular", k(&[0.5]))])).unwrap();
|
||||
assert_close3(standard.surface.material.base_color(), [0.4; 3]);
|
||||
assert!(close(standard.surface.material.specular(), 0.5));
|
||||
assert!(approximated(&standard, "specular"));
|
||||
|
||||
let weight = try_from_materialx(&mx(Shader::OpenPbr, &[("specular_weight", k(&[2.0]))])).unwrap();
|
||||
assert!(close(weight.surface.material.specular(), 2.0));
|
||||
assert!(approximated(&weight, "specular_weight"));
|
||||
let water = try_from_materialx(&mx(Shader::OpenPbr, &[("specular_ior", k(&[1.33]))])).unwrap();
|
||||
assert!(close(water.surface.material.specular(), specular_for_ior(1.33)), "{}", water.surface.material.specular());
|
||||
let gltf = try_from_materialx(&mx(Shader::GltfPbr, &[("ior", k(&[2.0])), ("specular", k(&[0.5]))])).unwrap();
|
||||
assert!(close(gltf.surface.material.specular(), 0.5 * specular_for_ior(2.0)));
|
||||
// 25 is the largest weight the core takes: at IOR 1.5 a weight of 25 fits, 25.5 does not.
|
||||
let max = try_from_materialx(&mx(Shader::OpenPbr, &[("specular_weight", k(&[25.0]))])).unwrap();
|
||||
assert!(close(max.surface.material.specular(), 25.0));
|
||||
bad_value(try_from_materialx(&mx(Shader::OpenPbr, &[("specular_weight", k(&[25.5]))])), "specular_weight");
|
||||
bad_value(try_from_materialx(&mx(Shader::OpenPbr, &[("specular_weight", k(&[2.0])), ("specular_ior", k(&[30.0]))])), "specular_weight");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_color_constants_are_decoded_from_the_color_space_in_effect() {
|
||||
let base = |v: Value| try_from_materialx(&mx(Shader::GltfPbr, &[("base_color", v)])).map(|c| c.surface.material.base_color());
|
||||
let c = [0.5, 0.2, 0.02];
|
||||
// The sRGB transfer function of IEC 61966-2-1, written out here independently.
|
||||
let srgb = |v: f32| if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) };
|
||||
for space in ["srgb_texture", "srgb_rec709_scene"] {
|
||||
let got = base(ks(&c, space)).unwrap();
|
||||
assert_close3(got, c.map(srgb));
|
||||
assert_close3(got, c.map(craft_texture::srgb_to_linear));
|
||||
}
|
||||
for space in ["lin_rec709", "lin_rec709_scene", "data", "none"] {
|
||||
assert_eq!(base(ks(&c, space)).unwrap(), c, "{space}");
|
||||
}
|
||||
assert_eq!(base(k(&c)).unwrap(), c);
|
||||
assert_close3(base(ks(&c, "g22_rec709")).unwrap(), c.map(|v| v.powf(2.2)));
|
||||
assert_close3(base(ks(&c, "g18_rec709_scene")).unwrap(), c.map(|v| v.powf(1.8)));
|
||||
assert_close3(base(ks(&c, "g24_rec709_scene")).unwrap(), c.map(|v| v.powf(2.4)));
|
||||
for space in ["acescg", "lin_ap1_scene", "srgb_p3d65_scene", "bogus"] {
|
||||
match base(ks(&c, space)) {
|
||||
Err(ConvertError::ColorSpace { input, colorspace }) => assert_eq!((input.as_str(), colorspace.as_str()), ("base_color", space)),
|
||||
other => panic!("{space}: {other:?}"),
|
||||
}
|
||||
}
|
||||
// Scalars are never decoded, whatever the color space.
|
||||
let rough = try_from_materialx(&mx(Shader::GltfPbr, &[("roughness", ks(&[0.5], "srgb_texture"))])).unwrap();
|
||||
assert_eq!(rough.surface.material.roughness(), 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_images_become_bindings_and_the_core_holds_the_factor() {
|
||||
let m = mx(
|
||||
Shader::OpenPbr,
|
||||
&[
|
||||
("base_color", img("tex/albedo.png", Some("srgb_texture"), Some([2.0, 3.0]))),
|
||||
("base_weight", k(&[0.5])),
|
||||
("base_metalness", img("metal.png", Some("srgb_texture"), None)),
|
||||
("specular_roughness", img("rough.png", None, None)),
|
||||
("geometry_opacity", img("cut.png", None, None)),
|
||||
("geometry_normal", Value::NormalMap { file: "n.png".into(), colorspace: Some("lin_rec709".into()), uv_tiling: None }),
|
||||
("emission_color", img("glow.png", Some("acescg"), None)),
|
||||
("emission_luminance", k(&[4.0])),
|
||||
("specular_ior", img("ior.png", None, None)),
|
||||
],
|
||||
);
|
||||
let c = try_from_materialx(&m).unwrap();
|
||||
let s = &c.surface;
|
||||
assert_close3(s.material.base_color(), [0.5; 3]);
|
||||
assert_eq!((s.material.metallic(), s.material.roughness(), s.material.specular()), (1.0, 1.0, 1.0));
|
||||
assert_eq!((s.alpha, s.alpha_mode), (1.0, AlphaMode::Blend));
|
||||
assert_eq!(s.emissive, [4.0; 3]);
|
||||
let find = |input: TextureInput| s.textures.iter().find(|b| b.input == input).unwrap();
|
||||
let albedo = find(TextureInput::BaseColor);
|
||||
assert_eq!((&albedo.source, &albedo.encoding), (&TextureSource::File("tex/albedo.png".into()), &TextureEncoding::Srgb));
|
||||
assert_eq!(albedo.transform, Some(UvTransform { offset: [0.0; 2], rotation: 0.0, scale: [2.0, 3.0] }));
|
||||
assert_eq!((albedo.uv_set, albedo.wrap, albedo.scale), (0, [Wrap::Repeat; 2], 1.0));
|
||||
// Data inputs are linear whatever color space the file carries; color inputs keep theirs.
|
||||
assert_eq!(find(TextureInput::Metallic).encoding, TextureEncoding::Linear);
|
||||
assert_eq!(find(TextureInput::Roughness).encoding, TextureEncoding::Linear);
|
||||
assert_eq!(find(TextureInput::Normal).encoding, TextureEncoding::Linear);
|
||||
assert_eq!(find(TextureInput::Opacity).source, TextureSource::File("cut.png".into()));
|
||||
assert_eq!(find(TextureInput::Emissive).encoding, TextureEncoding::Named("acescg".into()));
|
||||
assert_eq!(find(TextureInput::Other("specular_ior".into())).source, TextureSource::File("ior.png".into()));
|
||||
for name in ["base_color", "base_metalness", "specular_roughness", "geometry_opacity", "geometry_normal", "emission_color", "specular_ior"] {
|
||||
assert!(unshaded(&c, name), "{name}");
|
||||
}
|
||||
assert!(approximated(&c, "specular_ior"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_coat_and_sheen_are_kept_only_when_they_are_on() {
|
||||
let c = try_from_materialx(&mx(
|
||||
Shader::OpenPbr,
|
||||
&[("coat_weight", k(&[0.5])), ("coat_roughness", k(&[0.2])), ("fuzz_weight", k(&[0.5])), ("fuzz_color", k(&[1.0, 0.5, 0.0]))],
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(c.surface.clearcoat, Some(Clearcoat { weight: 0.5, roughness: 0.2 }));
|
||||
// fuzz_roughness defaults to 0.5.
|
||||
assert_eq!(c.surface.sheen, Some(Sheen { color: [0.5, 0.25, 0.0], roughness: 0.5 }));
|
||||
assert!(approximated(&c, "fuzz_weight") && unshaded(&c, "clearcoat") && unshaded(&c, "sheen"));
|
||||
|
||||
let standard = try_from_materialx(&mx(Shader::StandardSurface, &[("coat", k(&[1.0])), ("sheen", k(&[0.5]))])).unwrap();
|
||||
// coat_roughness 0.1, sheen_color white and sheen_roughness 0.3 by default.
|
||||
assert_eq!(standard.surface.clearcoat, Some(Clearcoat { weight: 1.0, roughness: 0.1 }));
|
||||
assert_eq!(standard.surface.sheen, Some(Sheen { color: [0.5; 3], roughness: 0.3 }));
|
||||
|
||||
let gltf = try_from_materialx(&mx(Shader::GltfPbr, &[("sheen_color", k(&[0.2, 0.1, 0.0])), ("sheen_roughness", k(&[0.4]))])).unwrap();
|
||||
assert_eq!(gltf.surface.sheen, Some(Sheen { color: [0.2, 0.1, 0.0], roughness: 0.4 }));
|
||||
assert!(!approximated(&gltf, "sheen_color"));
|
||||
|
||||
let off = try_from_materialx(&mx(
|
||||
Shader::OpenPbr,
|
||||
&[("coat_roughness", img("coat_r.png", None, None)), ("fuzz_color", img("fuzz.png", None, None)), ("coat_weight", k(&[0.0]))],
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!((off.surface.clearcoat, off.surface.sheen), (None, None));
|
||||
assert!(off.surface.textures.is_empty());
|
||||
assert!(dropped(&off, "coat_roughness") && dropped(&off, "fuzz_color"));
|
||||
let textured = try_from_materialx(&mx(Shader::OpenPbr, &[("coat_weight", img("coat.png", None, None))])).unwrap();
|
||||
assert_eq!(textured.surface.clearcoat, Some(Clearcoat { weight: 1.0, roughness: 0.0 }));
|
||||
assert_eq!(textured.surface.textures[0].input, TextureInput::Clearcoat);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_coat_and_sheen_roughness_images_read_their_first_channel() {
|
||||
let cases = [
|
||||
(Shader::OpenPbr, [("coat_weight", k(&[1.0])), ("fuzz_weight", k(&[1.0]))], ["coat_roughness", "fuzz_roughness"]),
|
||||
(Shader::StandardSurface, [("coat", k(&[1.0])), ("sheen", k(&[1.0]))], ["coat_roughness", "sheen_roughness"]),
|
||||
(Shader::GltfPbr, [("clearcoat", k(&[1.0])), ("sheen_color", k(&[1.0, 1.0, 1.0]))], ["clearcoat_roughness", "sheen_roughness"]),
|
||||
];
|
||||
for (shader, [coat, sheen], [coat_roughness, sheen_roughness]) in cases {
|
||||
let c = try_from_materialx(&mx(
|
||||
shader,
|
||||
&[coat, sheen, (coat_roughness, img("coat_r.png", None, None)), (sheen_roughness, img("sheen_r.png", None, None))],
|
||||
))
|
||||
.unwrap();
|
||||
let inputs: Vec<_> = c.surface.textures.iter().map(|t| (t.input.clone(), t.source.clone())).collect();
|
||||
assert_eq!(
|
||||
inputs,
|
||||
[
|
||||
(TextureInput::ClearcoatRoughnessFirst, TextureSource::File("coat_r.png".into())),
|
||||
(TextureInput::SheenRoughnessFirst, TextureSource::File("sheen_r.png".into())),
|
||||
],
|
||||
"{shader:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_coat_only_inputs_are_dropped_while_the_coat_is_off() {
|
||||
let coat_only = [
|
||||
(Shader::OpenPbr, "coat_weight", ["geometry_coat_normal", "coat_color", "coat_ior"]),
|
||||
(Shader::StandardSurface, "coat", ["coat_normal", "coat_color", "coat_IOR"]),
|
||||
];
|
||||
for (shader, weight, [normal, color, ior]) in coat_only {
|
||||
let inputs = [
|
||||
(normal, Value::NormalMap { file: "coat_n.png".into(), colorspace: None, uv_tiling: None }),
|
||||
(color, img("coat_c.png", None, None)),
|
||||
(ior, k(&[1.4])),
|
||||
];
|
||||
// The coat weight is left at its default of 0.
|
||||
let off = try_from_materialx(&mx(shader, &inputs)).unwrap();
|
||||
assert_eq!(off.surface.clearcoat, None);
|
||||
assert!(off.surface.textures.is_empty(), "{:?}", off.surface.textures);
|
||||
assert!(off.surface.other_inputs.is_empty(), "{:?}", off.surface.other_inputs);
|
||||
for name in [normal, color, ior] {
|
||||
assert!(dropped(&off, name) && !unshaded(&off, name), "{name}: {:?}", off.report);
|
||||
}
|
||||
// With the coat on, the same inputs are kept and reported as unshaded.
|
||||
let mut with_coat = inputs.to_vec();
|
||||
with_coat.push((weight, k(&[0.5])));
|
||||
let on = try_from_materialx(&mx(shader, &with_coat)).unwrap();
|
||||
assert!(on.surface.clearcoat.is_some());
|
||||
assert_eq!(on.surface.textures.len(), 2);
|
||||
assert_eq!(on.surface.other_inputs, vec![(ior.to_owned(), vec![1.4])]);
|
||||
for name in [normal, color, ior] {
|
||||
assert!(unshaded(&on, name) && !dropped(&on, name), "{name}");
|
||||
}
|
||||
}
|
||||
let gltf = try_from_materialx(&mx(
|
||||
Shader::GltfPbr,
|
||||
&[("clearcoat_normal", Value::NormalMap { file: "cc_n.png".into(), colorspace: None, uv_tiling: None })],
|
||||
))
|
||||
.unwrap();
|
||||
assert!(gltf.surface.textures.is_empty() && dropped(&gltf, "clearcoat_normal"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_constants_of_a_layer_that_is_off_are_dropped() {
|
||||
// The coat weight defaults to 0, so the coat is off and its roughness is dropped.
|
||||
let coat = try_from_materialx(&mx(Shader::OpenPbr, &[("coat_roughness", k(&[0.4]))])).unwrap();
|
||||
assert_eq!(coat.surface.clearcoat, None);
|
||||
assert!(dropped(&coat, "coat_roughness"), "{:?}", coat.report);
|
||||
// The weight that turns the layer off is not reported as dropped.
|
||||
let zero = try_from_materialx(&mx(Shader::OpenPbr, &[("coat_weight", k(&[0.0])), ("coat_roughness", k(&[0.4]))])).unwrap();
|
||||
assert!(dropped(&zero, "coat_roughness") && !dropped(&zero, "coat_weight"), "{:?}", zero.report);
|
||||
let on = try_from_materialx(&mx(Shader::OpenPbr, &[("coat_weight", k(&[0.5])), ("coat_roughness", k(&[0.4]))])).unwrap();
|
||||
assert!(!dropped(&on, "coat_roughness"));
|
||||
// fuzz_weight defaults to 0: the fuzz color and roughness are dropped.
|
||||
let fuzz = try_from_materialx(&mx(Shader::OpenPbr, &[("fuzz_color", k(&[1.0, 0.5, 0.0])), ("fuzz_roughness", k(&[0.2]))])).unwrap();
|
||||
assert!(dropped(&fuzz, "fuzz_color") && dropped(&fuzz, "fuzz_roughness"), "{:?}", fuzz.report);
|
||||
// A black color turns the sheen off, so its weight is dropped and the color is not.
|
||||
let black = try_from_materialx(&mx(Shader::StandardSurface, &[("sheen", k(&[0.5])), ("sheen_color", k(&[0.0; 3]))])).unwrap();
|
||||
assert!(dropped(&black, "sheen") && !dropped(&black, "sheen_color"), "{:?}", black.report);
|
||||
let gltf = try_from_materialx(&mx(Shader::GltfPbr, &[("sheen_roughness", k(&[0.3]))])).unwrap();
|
||||
assert!(dropped(&gltf, "sheen_roughness"), "{:?}", gltf.report);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_emission_is_the_color_times_its_strength() {
|
||||
let dark = try_from_materialx(&mx(Shader::OpenPbr, &[("emission_color", k(&[1.0, 0.5, 0.0]))])).unwrap();
|
||||
assert_eq!(dark.surface.emissive, [0.0; 3]);
|
||||
assert!(dropped(&dark, "emission_color"), "{:?}", dark.report);
|
||||
let lit = try_from_materialx(&mx(Shader::OpenPbr, &[("emission_color", k(&[1.0, 0.5, 0.0])), ("emission_luminance", k(&[10.0]))])).unwrap();
|
||||
assert_eq!(lit.surface.emissive, [10.0, 5.0, 0.0]);
|
||||
assert!(approximated(&lit, "emission_luminance"));
|
||||
let standard = try_from_materialx(&mx(Shader::StandardSurface, &[("emission", k(&[2.0])), ("emission_color", k(&[0.5, 0.25, 1.0]))])).unwrap();
|
||||
assert_eq!(standard.surface.emissive, [1.0, 0.5, 2.0]);
|
||||
assert!(standard.report.is_empty());
|
||||
let gltf = try_from_materialx(&mx(Shader::GltfPbr, &[("emissive", k(&[0.5, 0.25, 0.0])), ("emissive_strength", k(&[2.0]))])).unwrap();
|
||||
assert_eq!(gltf.surface.emissive, [1.0, 0.5, 0.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_standard_surface_opacity_color_gives_its_luminance() {
|
||||
let standard = |opacity: &[f32]| try_from_materialx(&mx(Shader::StandardSurface, &[("opacity", k(opacity))]));
|
||||
let gray = standard(&[0.5; 3]).unwrap();
|
||||
assert_eq!(gray.surface.alpha, 0.5);
|
||||
assert!(gray.report.is_empty(), "{:?}", gray.report);
|
||||
// 0.2126 * 0.2 + 0.7152 * 0.4 + 0.0722 * 0.6, the Rec.709 luminance; the mean would be 0.4.
|
||||
let colored = standard(&[0.2, 0.4, 0.6]).unwrap();
|
||||
assert!(close(colored.surface.alpha, 0.37192), "{}", colored.surface.alpha);
|
||||
assert_eq!(colored.surface.alpha_mode, AlphaMode::Blend);
|
||||
assert!(approximated(&colored, "opacity"));
|
||||
let green = standard(&[0.0, 1.0, 0.0]).unwrap();
|
||||
assert!(close(green.surface.alpha, 0.7152), "{}", green.surface.alpha);
|
||||
let near_white = standard(&[1.0, 1.0, 0.999_999_9]).unwrap();
|
||||
assert!(near_white.surface.alpha <= 1.0 && near_white.surface.alpha >= 0.999_999_9);
|
||||
for v in [f32::NAN, f32::INFINITY, -0.01, 1.01] {
|
||||
bad_value(standard(&[0.5, v, 0.5]), "opacity");
|
||||
}
|
||||
// An image on the color opacity binds as RGB; the float opacities bind their first channel.
|
||||
let textured = try_from_materialx(&mx(Shader::StandardSurface, &[("opacity", img("o.png", None, None))])).unwrap();
|
||||
assert_eq!(textured.surface.textures[0].input, TextureInput::OpacityRgb);
|
||||
for (shader, name) in [(Shader::OpenPbr, "geometry_opacity"), (Shader::GltfPbr, "alpha")] {
|
||||
let c = try_from_materialx(&mx(shader, &[(name, img("o.png", None, None))])).unwrap();
|
||||
assert_eq!(c.surface.textures[0].input, TextureInput::Opacity, "{name}");
|
||||
}
|
||||
// OpenPBR's geometry_opacity is a float in its node definition.
|
||||
assert_eq!(
|
||||
try_from_materialx(&mx(Shader::OpenPbr, &[("geometry_opacity", k(&[0.5; 3]))])).unwrap_err(),
|
||||
ConvertError::Components { input: "geometry_opacity".into(), expected: 1, found: 3 }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_alpha_and_its_mode() {
|
||||
let open = try_from_materialx(&mx(Shader::OpenPbr, &[("geometry_opacity", k(&[0.5]))])).unwrap();
|
||||
assert_eq!((open.surface.alpha, open.surface.alpha_mode), (0.5, AlphaMode::Blend));
|
||||
|
||||
let gltf = |inputs: &[(&str, Value)]| try_from_materialx(&mx(Shader::GltfPbr, inputs));
|
||||
assert_eq!(gltf(&[("alpha_mode", k(&[1.0])), ("alpha_cutoff", k(&[0.25]))]).unwrap().surface.alpha_mode, AlphaMode::Mask(0.25));
|
||||
assert_eq!(gltf(&[("alpha_mode", k(&[1.0]))]).unwrap().surface.alpha_mode, AlphaMode::Mask(0.5));
|
||||
assert_eq!(gltf(&[("alpha_mode", k(&[2.0]))]).unwrap().surface.alpha_mode, AlphaMode::Blend);
|
||||
let opaque = gltf(&[("alpha", k(&[0.5]))]).unwrap();
|
||||
assert_eq!((opaque.surface.alpha, opaque.surface.alpha_mode), (0.5, AlphaMode::Opaque));
|
||||
for bad in [3.0, 1.5, -1.0] {
|
||||
bad_value(gltf(&[("alpha_mode", k(&[bad]))]), "alpha_mode");
|
||||
}
|
||||
bad_value(gltf(&[("alpha_mode", img("m.png", None, None))]), "alpha_mode");
|
||||
bad_value(gltf(&[("alpha_cutoff", img("c.png", None, None))]), "alpha_cutoff");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_bad_inputs_are_errors_and_unknown_ones_are_dropped() {
|
||||
let open = |inputs: &[(&str, Value)]| try_from_materialx(&mx(Shader::OpenPbr, inputs));
|
||||
assert_eq!(open(&[("base_metalness", k(&[0.0])), ("base_metalness", k(&[1.0]))]).unwrap_err(), ConvertError::Duplicate("base_metalness".into()));
|
||||
assert_eq!(open(&[("base_color", k(&[0.5]))]).unwrap_err(), ConvertError::Components { input: "base_color".into(), expected: 3, found: 1 });
|
||||
assert_eq!(
|
||||
open(&[("base_metalness", k(&[0.5; 3]))]).unwrap_err(),
|
||||
ConvertError::Components { input: "base_metalness".into(), expected: 1, found: 3 }
|
||||
);
|
||||
for v in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.01, 1.01] {
|
||||
for name in
|
||||
["base_weight", "base_metalness", "specular_roughness", "coat_weight", "fuzz_roughness", "geometry_opacity", "transmission_weight"]
|
||||
{
|
||||
bad_value(open(&[(name, k(&[v]))]), name);
|
||||
}
|
||||
bad_value(open(&[("base_color", k(&[0.5, v, 0.5]))]), "base_color");
|
||||
}
|
||||
for v in [f32::NAN, f32::INFINITY, -1.0] {
|
||||
bad_value(open(&[("emission_luminance", k(&[v]))]), "emission_luminance");
|
||||
bad_value(open(&[("specular_ior", k(&[v]))]), "specular_ior");
|
||||
bad_value(open(&[("geometry_normal", k(&[0.0, 0.0, if v < 0.0 { f32::NAN } else { v }]))]), "geometry_normal");
|
||||
}
|
||||
bad_value(try_from_materialx(&mx(Shader::GltfPbr, &[("ior", k(&[0.9]))])), "ior");
|
||||
// glTF PBR's specular_color has no upper bound, so a large encoded value overflows to
|
||||
// infinity when it is decoded to linear; that is an error, not an infinite input.
|
||||
for space in ["g22_rec709", "srgb_texture", "srgb_rec709_scene", "g24_rec709_scene"] {
|
||||
bad_value(try_from_materialx(&mx(Shader::GltfPbr, &[("specular_color", ks(&[1e20, 1.0, 1.0], space))])), "specular_color");
|
||||
}
|
||||
let wide = try_from_materialx(&mx(Shader::GltfPbr, &[("specular_color", ks(&[4.0, 1.0, 1.0], "g22_rec709"))])).unwrap();
|
||||
assert_eq!(wide.surface.other_inputs.len(), 1);
|
||||
assert!(close(wide.surface.other_inputs[0].1[0], 4f32.powf(2.2)));
|
||||
bad_value(open(&[("base_color", img("a.png", None, Some([0.0, 1.0])))]), "base_color");
|
||||
bad_value(open(&[("base_color", img("a.png", None, Some([f32::NAN, 1.0])))]), "base_color");
|
||||
let unknown = open(&[("thin_film_weight", k(&[0.5])), ("not_an_input", img("x.png", None, None))]).unwrap();
|
||||
assert!(dropped(&unknown, "thin_film_weight") && dropped(&unknown, "not_an_input"));
|
||||
assert!(unknown.surface.textures.is_empty() && unknown.surface.other_inputs.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_other_inputs_and_the_displacement_are_kept() {
|
||||
let mut m = mx(
|
||||
Shader::OpenPbr,
|
||||
&[
|
||||
("specular_color", ks(&[1.0, 0.5, 0.5], "srgb_texture")),
|
||||
("transmission_weight", k(&[0.5])),
|
||||
("subsurface_weight", img("sss.png", None, None)),
|
||||
],
|
||||
);
|
||||
m.displacement = Some(k(&[0.25]));
|
||||
let c = try_from_materialx(&m).unwrap();
|
||||
let srgb_half = craft_texture::srgb_to_linear(0.5);
|
||||
assert_eq!(
|
||||
c.surface.other_inputs,
|
||||
vec![
|
||||
("specular_color".into(), vec![1.0, srgb_half, srgb_half]),
|
||||
("transmission_weight".into(), vec![0.5]),
|
||||
("displacement".into(), vec![0.25])
|
||||
]
|
||||
);
|
||||
assert_eq!(c.surface.textures[0].input, TextureInput::Other("subsurface_weight".into()));
|
||||
for name in ["specular_color", "transmission_weight", "subsurface_weight", "displacement"] {
|
||||
assert!(unshaded(&c, name), "{name}");
|
||||
}
|
||||
m.displacement = Some(img("h.png", Some("srgb_texture"), Some([4.0, 4.0])));
|
||||
let c = try_from_materialx(&m).unwrap();
|
||||
let h = c.surface.textures.iter().find(|b| b.input == TextureInput::Displacement).unwrap();
|
||||
assert_eq!((&h.source, &h.encoding), (&TextureSource::File("h.png".into()), &TextureEncoding::Linear));
|
||||
assert_eq!(h.transform.map(|t| t.scale), Some([4.0, 4.0]));
|
||||
m.displacement = Some(k(&[f32::NAN]));
|
||||
bad_value(try_from_materialx(&m), "displacement");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_reader_warnings_reach_the_report() {
|
||||
let mut m = mx(Shader::OpenPbr, &[]);
|
||||
m.warnings = vec!["input thin_film_weight is not read".into()];
|
||||
let c = try_from_materialx(&m).unwrap();
|
||||
assert_eq!(c.report.items, vec![ReportItem::Warning("input thin_film_weight is not read".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_float_converted_to_a_color_is_not_decoded_from_the_nodes_color_space() {
|
||||
// The float is not a color value, so the node's srgb_texture does not apply to it.
|
||||
let doc = Document::parse(
|
||||
br#"<materialx colorspace="lin_rec709">
|
||||
<open_pbr_surface name="S"><input name="base_color" nodename="C"/></open_pbr_surface>
|
||||
<convert name="C" type="color3" colorspace="srgb_texture"><input name="in" type="float" value="0.5"/></convert>
|
||||
<surfacematerial name="M"><input name="surfaceshader" nodename="S"/></surfacematerial>
|
||||
</materialx>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let c = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert_close3(c.surface.material.base_color(), [0.5; 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_documents_convert_from_xml() {
|
||||
let doc = Document::parse(
|
||||
br#"<materialx colorspace="srgb_texture">
|
||||
<gltf_pbr name="S">
|
||||
<input name="base_color" type="color3" value="0.5, 0.5, 0.5"/>
|
||||
<input name="emissive" type="color3" value="1, 0, 0" colorspace="lin_rec709"/>
|
||||
<input name="emissive_strength" type="float" value="3"/>
|
||||
<input name="iridescence" type="float" value="0.5"/>
|
||||
</gltf_pbr>
|
||||
<surfacematerial name="Red"><input name="surfaceshader" nodename="S"/></surfacematerial>
|
||||
</materialx>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let c = try_from_materialx(&doc.read_material_strict(None).unwrap()).unwrap();
|
||||
assert_eq!(c.surface.name, "Red");
|
||||
assert_close3(c.surface.material.base_color(), [craft_texture::srgb_to_linear(0.5); 3]);
|
||||
assert_eq!(c.surface.emissive, [3.0, 0.0, 0.0]);
|
||||
assert_eq!(c.report.items, vec![ReportItem::Warning("input iridescence is not read".into())]);
|
||||
|
||||
// craft-materialx's OpenPBR writer and this conversion agree on every texture it writes.
|
||||
let textures = [
|
||||
Texture { input: "base_color".into(), file: "albedo.png".into(), colorspace: "srgb_texture".into() },
|
||||
Texture { input: "specular_roughness".into(), file: "rough.png".into(), colorspace: "srgb_texture".into() },
|
||||
Texture { input: "geometry_normal".into(), file: "normal.png".into(), colorspace: "lin_rec709".into() },
|
||||
Texture { input: "emission_color".into(), file: "glow.png".into(), colorspace: "lin_rec709".into() },
|
||||
Texture { input: "height".into(), file: "height.png".into(), colorspace: "lin_rec709".into() },
|
||||
];
|
||||
let written = Document::parse(write_open_pbr("Stone", &textures, None).as_bytes()).unwrap();
|
||||
let c = try_from_materialx(&written.read_material_strict(None).unwrap()).unwrap();
|
||||
let s = &c.surface;
|
||||
let by = |input: TextureInput| s.textures.iter().find(|b| b.input == input).map(|b| (b.source.clone(), b.encoding.clone()));
|
||||
assert_eq!(by(TextureInput::BaseColor), Some((TextureSource::File("albedo.png".into()), TextureEncoding::Srgb)));
|
||||
assert_eq!(by(TextureInput::Roughness), Some((TextureSource::File("rough.png".into()), TextureEncoding::Linear)));
|
||||
assert_eq!(by(TextureInput::Normal), Some((TextureSource::File("normal.png".into()), TextureEncoding::Linear)));
|
||||
assert_eq!(by(TextureInput::Emissive), Some((TextureSource::File("glow.png".into()), TextureEncoding::Linear)));
|
||||
assert_eq!(by(TextureInput::Displacement), Some((TextureSource::File("height.png".into()), TextureEncoding::Linear)));
|
||||
// The writer sets emission_luminance to 1 with an emission texture, so the texture shows.
|
||||
assert_eq!(s.emissive, [1.0; 3]);
|
||||
assert_eq!(s.name, "Stone");
|
||||
}
|
||||
@@ -5,6 +5,9 @@
|
||||
mod bench;
|
||||
mod bounds;
|
||||
mod brdf;
|
||||
mod conversion_edges;
|
||||
mod conversion_followups;
|
||||
mod convert;
|
||||
mod differential;
|
||||
mod moved;
|
||||
mod numeric;
|
||||
|
||||
Generated
-2
@@ -103,8 +103,6 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69374b3668dd45aeb3d3145cda68f2c7b4f223aaa2511e67d076f1c7d741388d"
|
||||
dependencies = [
|
||||
"hayro-ccitt",
|
||||
]
|
||||
|
||||
@@ -24,6 +24,8 @@ mod writer;
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub(crate) mod testkit;
|
||||
#[cfg(test)]
|
||||
pub(crate) use security::{ALL_FOLLOWED, ALL_FOLLOWED_LIMIT, MAX_FOLLOWED};
|
||||
|
||||
pub use crate::crypt::{
|
||||
Algorithm, Auth, Method as CryptMethod, NewEncryption, Permissions, SecurityHandler, effective_password, pdfdoc_byte, pdfdoc_char,
|
||||
|
||||
@@ -611,7 +611,8 @@ fn renderer_operators(data: &[u8]) -> Vec<Vec<u8>> {
|
||||
let mut iter = hayro_syntax::content::UntypedIter::new(data);
|
||||
let mut out = Vec::new();
|
||||
while let Some(instruction) = iter.next() {
|
||||
out.push(instruction.operator.as_ref().to_vec());
|
||||
let operator: &[u8] = instruction.operator.as_ref();
|
||||
out.push(operator.to_vec());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -767,9 +767,22 @@ impl Document {
|
||||
Some(XrefEntry::InFile { offset, .. }) => {
|
||||
let resolve = |r: ObjRef| self.stream_length(r);
|
||||
let off = offset as usize;
|
||||
let at = |off: usize| match parse_indirect_shared(&self.data, off, &resolve, &self.endstreams) {
|
||||
Ok((id, o)) if id.num == num => Some(self.decrypted(id, o)),
|
||||
_ => None,
|
||||
let at = |off: usize| {
|
||||
#[cfg(test)]
|
||||
{
|
||||
let parses = super::tests::OFFSET_PARSES.with(|parses| {
|
||||
let mut parses = parses.borrow_mut();
|
||||
let count = parses.entry(num).or_default();
|
||||
*count += 1;
|
||||
*count
|
||||
});
|
||||
let limit = super::tests::OFFSET_PARSE_LIMIT.with(std::cell::Cell::get);
|
||||
assert!(parses <= limit, "object {num} parsed {parses} times at an offset, more than the {limit} allowed");
|
||||
}
|
||||
match parse_indirect_shared(&self.data, off, &resolve, &self.endstreams) {
|
||||
Ok((id, o)) if id.num == num => Some(self.decrypted(id, o)),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
// Offsets relative to a shifted header, or simply wrong: try both fixes.
|
||||
at(off)
|
||||
|
||||
@@ -26,6 +26,11 @@ std::thread_local! {
|
||||
pub(super) static FILE_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// How many times `Document::objstm` decoded an object stream on this thread.
|
||||
pub(super) static OBJSTM_DECODES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// How many times `Document::load` parsed each file object at an offset on this thread, by
|
||||
/// object number.
|
||||
pub(super) static OFFSET_PARSES: std::cell::RefCell<HashMap<u32, usize>> = std::cell::RefCell::new(HashMap::new());
|
||||
/// The most offset parses of one object a test allows: one more fails the test at once.
|
||||
pub(super) static OFFSET_PARSE_LIMIT: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
|
||||
}
|
||||
|
||||
/// A scan that doesn't find an object isn't made again: each reads the whole file, and a file can
|
||||
@@ -2465,8 +2470,6 @@ fn the_chain_row_limit_counts_rows_an_xref_stream_index_repeats() {
|
||||
assert!(detail.contains("more than 7 entries"), "{detail}");
|
||||
}
|
||||
|
||||
// Not on the web: it times the load on a thread, and wasm32-unknown-unknown has none.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_stream_whose_length_is_itself_and_never_ends_loads_quickly() {
|
||||
// From the nightly fuzz job: `6 0 obj << /Length 6 0 R >> stream` with no `endstream`
|
||||
@@ -2476,14 +2479,16 @@ fn a_stream_whose_length_is_itself_and_never_ends_loads_quickly() {
|
||||
// only runs when the header is shifted.
|
||||
let mut bytes = b"%PDF-1.7\n1 0 obj\n<< /Type /Catalog >>\nendobj\n".to_vec();
|
||||
bytes.extend_from_slice(b"6 0 obj\n<< /Length 6 0 R >>\nstream\nno end marker follows\n");
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
if let Ok(doc) = Document::open(Arc::new(bytes)) {
|
||||
let _ = doc.try_get(6);
|
||||
}
|
||||
let _ = tx.send(());
|
||||
});
|
||||
rx.recv_timeout(std::time::Duration::from_secs(20)).expect("loading must not retry exponentially");
|
||||
// Each object is parsed at its offset at most twice; a retry of each attempt is past this
|
||||
// limit long before its end.
|
||||
OFFSET_PARSES.with(|parses| parses.borrow_mut().clear());
|
||||
OFFSET_PARSE_LIMIT.with(|limit| limit.set(2));
|
||||
if let Ok(doc) = Document::open(Arc::new(bytes)) {
|
||||
let _ = doc.try_get(6);
|
||||
}
|
||||
OFFSET_PARSE_LIMIT.with(|limit| limit.set(usize::MAX));
|
||||
let parses = OFFSET_PARSES.with(|parses| parses.borrow().clone());
|
||||
assert!(parses.get(&6).is_some_and(|&n| n <= 2) && parses.values().all(|&n| n <= 2), "{parses:?}");
|
||||
}
|
||||
|
||||
/// A file whose object 3 (its `/Info`) can't be parsed: the rest reads.
|
||||
|
||||
@@ -20,7 +20,7 @@ use crate::cos::{Dict, Document, Object, PdfString, Stream};
|
||||
/// file could make one read a tree of them, each object read again once the cache has let it go.
|
||||
/// An object takes a few of these, and two dozen if every part of it is given by reference; past
|
||||
/// this they read as absent. The parameters of an object stream, read together, count as one.
|
||||
const MAX_FOLLOWED: u32 = 32;
|
||||
pub(crate) const MAX_FOLLOWED: u32 = 32;
|
||||
|
||||
std::thread_local! {
|
||||
/// How many [`FollowScope`]s this thread is inside.
|
||||
@@ -58,9 +58,23 @@ pub(crate) fn following<T>(spent: T, f: impl FnOnce() -> T) -> T {
|
||||
return spent;
|
||||
}
|
||||
FOLLOWED.set(FOLLOWED.get() + 1);
|
||||
#[cfg(test)]
|
||||
{
|
||||
let all = ALL_FOLLOWED.replace(ALL_FOLLOWED.get().saturating_add(1)).saturating_add(1);
|
||||
let limit = ALL_FOLLOWED_LIMIT.get();
|
||||
assert!(all <= limit, "{all} references followed, more than the {limit} allowed");
|
||||
}
|
||||
f()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
/// The references followed on this thread, in every [`FollowScope`].
|
||||
pub(crate) static ALL_FOLLOWED: Cell<usize> = const { Cell::new(0) };
|
||||
/// The most references a test lets this thread follow: one more fails the test at once.
|
||||
pub(crate) static ALL_FOLLOWED_LIMIT: Cell<usize> = const { Cell::new(usize::MAX) };
|
||||
}
|
||||
|
||||
/// `o`, or the object it refers to, for what decides how a stream or dictionary is treated. Past
|
||||
/// [`MAX_FOLLOWED`] a reference reads as absent.
|
||||
fn followed<'o>(doc: &Document, o: &'o Object) -> Held<'o> {
|
||||
|
||||
@@ -1310,14 +1310,15 @@ fn selectors_that_lead_to_selectors_load_at_once() {
|
||||
top = stream_of(&mut doc, vec![Object::Ref(a), first.clone(), second.clone(), Object::Ref(b)]);
|
||||
}
|
||||
let saved = write_incremental(&doc, &SaveOptions::default()).unwrap();
|
||||
let (done, finished) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let doc = Document::open(Arc::new(saved)).unwrap();
|
||||
let _ = done.send(doc.get(top).as_dict().is_some());
|
||||
});
|
||||
// With the budget it takes milliseconds, and without it longer than anyone would wait, so a
|
||||
// margin this wide can't fail on a busy machine.
|
||||
assert_eq!(finished.recv_timeout(std::time::Duration::from_secs(120)), Ok(true), "loading must not fan out");
|
||||
let doc = Document::open(Arc::new(saved)).unwrap();
|
||||
// The one read follows no more references than its budget allows; one that fans out is past
|
||||
// this limit long before its end.
|
||||
let budget = crate::cos::MAX_FOLLOWED as usize;
|
||||
crate::cos::ALL_FOLLOWED.set(0);
|
||||
crate::cos::ALL_FOLLOWED_LIMIT.set(budget);
|
||||
assert!(doc.get(top).as_dict().is_some(), "loading must not fan out");
|
||||
crate::cos::ALL_FOLLOWED_LIMIT.set(usize::MAX);
|
||||
assert!(crate::cos::ALL_FOLLOWED.get() <= budget);
|
||||
}
|
||||
|
||||
/// An R6 file of the fixture's page, its `/Encrypt` given `cf` as `/CF` and `selectors` (`/StmF`,
|
||||
|
||||
@@ -30,6 +30,13 @@ use super::{BlendMode, DisplayList, FillItem, FillRule, GroupItem, Item, Paint};
|
||||
use crate::ink::{InkColor, InkId, InkSet, Overprint, Process};
|
||||
|
||||
/// How [`flatten`] cuts transparent art.
|
||||
///
|
||||
/// `FlattenOptions` can be initialized with its three fields:
|
||||
///
|
||||
/// ```
|
||||
/// use craft_prepress::flatten::FlattenOptions;
|
||||
/// let options = FlattenOptions { sliver: 0.01, max_regions: 5000, raster_dpi: 300.0 };
|
||||
/// ```
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct FlattenOptions {
|
||||
/// Regions narrower than this (in points) are dropped ([`geom::regions_with`]).
|
||||
@@ -48,6 +55,27 @@ impl Default for FlattenOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// These limits bound each region sweep used by [`flatten_with_limits`]. The PDF entry points
|
||||
/// with explicit limits also apply them to each even-odd path rebuild during page reading.
|
||||
/// A stopped rebuild retains the original path and fill rule.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct FlattenSweepLimits {
|
||||
/// The region sweep of one group stops after this many work units. The group then goes to
|
||||
/// [`Flattened::complex`] whole as [`ComplexReason::Degenerate`]. The default is
|
||||
/// [`geom::DEFAULT_MAX_SWEEP_WORK`].
|
||||
pub max_sweep_work: u64,
|
||||
/// The region sweep of one group stops before holding more than this many output units.
|
||||
/// The group then goes to [`Flattened::complex`] whole as [`ComplexReason::Degenerate`].
|
||||
/// The default is [`geom::DEFAULT_MAX_TOPOLOGY_UNITS`].
|
||||
pub max_sweep_units: usize,
|
||||
}
|
||||
|
||||
impl Default for FlattenSweepLimits {
|
||||
fn default() -> Self {
|
||||
Self { max_sweep_work: geom::DEFAULT_MAX_SWEEP_WORK, max_sweep_units: geom::DEFAULT_MAX_TOPOLOGY_UNITS }
|
||||
}
|
||||
}
|
||||
|
||||
/// A page with no transparency left.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Flattened {
|
||||
@@ -132,6 +160,11 @@ pub enum FlattenError {
|
||||
/// an item that does come back unchanged, and so do opaque items with no transparency painted
|
||||
/// above them where they paint.
|
||||
pub fn flatten(list: &DisplayList, opts: &FlattenOptions) -> Result<Flattened, FlattenError> {
|
||||
flatten_with_limits(list, opts, &FlattenSweepLimits::default())
|
||||
}
|
||||
|
||||
/// `flatten_with_limits` flattens `list` using `opts` and the region sweep `limits`.
|
||||
pub fn flatten_with_limits(list: &DisplayList, opts: &FlattenOptions, limits: &FlattenSweepLimits) -> Result<Flattened, FlattenError> {
|
||||
let nan = Rect::new(f64::NAN, f64::NAN, f64::NAN, f64::NAN);
|
||||
let bounds: Vec<Rect> = list.items.iter().map(|i| bounds(i).unwrap_or(nan)).collect();
|
||||
let transparent: Vec<bool> = list.items.iter().map(is_transparent).collect();
|
||||
@@ -165,7 +198,7 @@ pub fn flatten(list: &DisplayList, opts: &FlattenOptions) -> Result<Flattened, F
|
||||
out.report.kept += 1;
|
||||
}
|
||||
Plan::Drop => {}
|
||||
Plan::Emit(g) => flatten_group(list, &members[g], &bounds, &transparent, opts, &mut out)?,
|
||||
Plan::Emit(g) => flatten_group(list, &members[g], &bounds, &transparent, opts, limits, &mut out)?,
|
||||
}
|
||||
}
|
||||
out.report.complex_regions = out.complex.len();
|
||||
@@ -178,6 +211,7 @@ fn flatten_group(
|
||||
bounds: &[Rect],
|
||||
transparent: &[bool],
|
||||
opts: &FlattenOptions,
|
||||
limits: &FlattenSweepLimits,
|
||||
out: &mut Flattened,
|
||||
) -> Result<(), FlattenError> {
|
||||
let mut b = Builder::new(&list.inks);
|
||||
@@ -206,7 +240,7 @@ fn flatten_group(
|
||||
out.report.flattened += members.len();
|
||||
return Ok(());
|
||||
}
|
||||
let regions = match geom::regions_with(&b.shapes, &b.clips, opts.sliver) {
|
||||
let regions = match geom::regions_with_limits(&b.shapes, &b.clips, opts.sliver, limits.max_sweep_work, limits.max_sweep_units) {
|
||||
Ok(r) => r,
|
||||
Err(GeomError::Degenerate) => {
|
||||
// Each member's box is clear of every other group's items.
|
||||
@@ -1046,4 +1080,24 @@ mod tests {
|
||||
let l = list(InkSet::new(), vec![Item::Group(group(0.5, BlendMode::Normal, vec![crowded]))]);
|
||||
assert!(flatten(&l, &FlattenOptions::default()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sweep_limits_send_the_group_to_complex() {
|
||||
let l = list(
|
||||
InkSet::new(),
|
||||
vec![
|
||||
solid(Rect::new(0.0, 0.0, 100.0, 100.0), &[(M, 1.0)]),
|
||||
Item::Group(group(0.5, BlendMode::Normal, vec![solid(Rect::new(50.0, 0.0, 150.0, 100.0), &[(C, 1.0)])])),
|
||||
],
|
||||
);
|
||||
assert!(flat(&l).report.complex_groups.is_empty());
|
||||
|
||||
for limits in [
|
||||
FlattenSweepLimits { max_sweep_work: 1, ..FlattenSweepLimits::default() },
|
||||
FlattenSweepLimits { max_sweep_units: 1, ..FlattenSweepLimits::default() },
|
||||
] {
|
||||
let f = flatten_with_limits(&l, &FlattenOptions::default(), &limits).unwrap();
|
||||
assert_eq!(f.report.complex_groups, [ComplexGroup { items: vec![0, 1], reason: ComplexReason::Degenerate }], "{limits:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,7 @@ use kurbo::Rect;
|
||||
use super::pdf::{ReadColor, ReadError, ReadOptions, read_color, read_page_in};
|
||||
use super::raster::{FlattenPageReport, Rasterizer};
|
||||
use super::write::{FontMap, WriteError, write_flattened_with_fonts};
|
||||
use super::{DisplayList, FlattenError, FlattenOptions, flatten};
|
||||
use super::{DisplayList, FlattenError, FlattenOptions, FlattenSweepLimits, flatten_with_limits};
|
||||
use crate::cms::CmsConversion;
|
||||
use crate::plates::{self, Fallback, pdf_text};
|
||||
|
||||
@@ -175,7 +175,16 @@ pub enum FlattenDocumentError {
|
||||
/// `pdf` with the transparency of every page in [`FlattenDocumentOptions::pages`] flattened, as
|
||||
/// one PDF. See the module docs for what carries over.
|
||||
pub fn flatten_document(pdf: &[u8], opts: &FlattenDocumentOptions) -> Result<(Vec<u8>, FlattenDocumentReport), FlattenDocumentError> {
|
||||
flatten_document_with_progress(pdf, opts, &mut |_, _| {})
|
||||
flatten_document_with_limits(pdf, opts, &FlattenSweepLimits::default())
|
||||
}
|
||||
|
||||
/// [`flatten_document`] with explicit sweep work and output limits.
|
||||
pub fn flatten_document_with_limits(
|
||||
pdf: &[u8],
|
||||
opts: &FlattenDocumentOptions,
|
||||
limits: &FlattenSweepLimits,
|
||||
) -> Result<(Vec<u8>, FlattenDocumentReport), FlattenDocumentError> {
|
||||
flatten_document_with_limits_and_progress(pdf, opts, limits, &mut |_, _| {})
|
||||
}
|
||||
|
||||
/// [`flatten_document`], calling `progress(done, total)` after each page.
|
||||
@@ -183,6 +192,16 @@ pub fn flatten_document_with_progress(
|
||||
pdf: &[u8],
|
||||
opts: &FlattenDocumentOptions,
|
||||
progress: &mut dyn FnMut(usize, usize),
|
||||
) -> Result<(Vec<u8>, FlattenDocumentReport), FlattenDocumentError> {
|
||||
flatten_document_with_limits_and_progress(pdf, opts, &FlattenSweepLimits::default(), progress)
|
||||
}
|
||||
|
||||
/// [`flatten_document_with_limits`], calling `progress(done, total)` after each page.
|
||||
pub fn flatten_document_with_limits_and_progress(
|
||||
pdf: &[u8],
|
||||
opts: &FlattenDocumentOptions,
|
||||
limits: &FlattenSweepLimits,
|
||||
progress: &mut dyn FnMut(usize, usize),
|
||||
) -> Result<(Vec<u8>, FlattenDocumentReport), FlattenDocumentError> {
|
||||
let doc = Arc::new(open_slice(pdf, None)?);
|
||||
let count = doc.pages().len();
|
||||
@@ -213,9 +232,9 @@ pub fn flatten_document_with_progress(
|
||||
report.other_intents.push(page);
|
||||
}
|
||||
let p = doc.pages().get(page).ok_or(FlattenDocumentError::Read { page, source: ReadError::NoPage(page) })?;
|
||||
match read_page_in(&doc, page, &opts.read, color.read.clone()) {
|
||||
match read_page_in(&doc, page, &opts.read, color.read.clone(), limits) {
|
||||
Ok((list, read)) => {
|
||||
let flat = flatten(&list, &opts.flatten).map_err(|source| FlattenDocumentError::Flatten { page, source })?;
|
||||
let flat = flatten_with_limits(&list, &opts.flatten, limits).map_err(|source| FlattenDocumentError::Flatten { page, source })?;
|
||||
let mut raster = Rasterizer::new(&list, color.settings.clone(), color.condition.clone(), &color.cms, opts.flatten.raster_dpi);
|
||||
let at = |source| FlattenDocumentError::Write { page, source };
|
||||
let settings = page_settings(p, list.page).ok_or(at(WriteError::Page))?;
|
||||
|
||||
@@ -21,6 +21,19 @@ use linesweeper::topology::{ContourIdx, Contours, Topology, WindingNumber};
|
||||
/// numerical debris, such as the lens between two nearly coincident curves.
|
||||
pub const DEFAULT_SLIVER: f64 = 0.01;
|
||||
|
||||
/// The default for the most work the sweep may do, counted as segment comparisons plus segment
|
||||
/// position checks plus one unit for every 16 segments a search of the sweep line passes or probes
|
||||
/// plus the horizontal segments each step of a sweep line visits,
|
||||
/// before the shapes count as too degenerate to sweep. Stacked copies of a shape can need billions
|
||||
/// of comparisons; a release build makes about 17 million a second.
|
||||
pub const DEFAULT_MAX_SWEEP_WORK: u64 = 100_000_000;
|
||||
|
||||
/// The default for the most output the sweep's topology may hold before the shapes count as too
|
||||
/// degenerate to sweep, in units: each output segment takes one unit plus one for each entry of its
|
||||
/// two winding numbers (at least one each), so 2,000,000 segments with single-entry windings fill
|
||||
/// it. Each segment's windings can hold an entry for every shape that covers it.
|
||||
pub const DEFAULT_MAX_TOPOLOGY_UNITS: usize = 6_000_000;
|
||||
|
||||
/// How a path's winding number decides what is inside it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum FillRule {
|
||||
@@ -125,10 +138,17 @@ pub fn regions(shapes: &[Shape], clips: &[ClipPath]) -> Result<Vec<Region>, Geom
|
||||
|
||||
/// [`regions`] with contours narrower than `sliver` dropped.
|
||||
pub fn regions_with(shapes: &[Shape], clips: &[ClipPath], sliver: f64) -> Result<Vec<Region>, GeomError> {
|
||||
regions_with_limits(shapes, clips, sliver, DEFAULT_MAX_SWEEP_WORK, DEFAULT_MAX_TOPOLOGY_UNITS)
|
||||
}
|
||||
|
||||
/// [`regions_with`] with the sweep stopped, as [`GeomError::Degenerate`], once it passes
|
||||
/// `max_work` units of work or its topology passes `max_units` units of output (see
|
||||
/// [`DEFAULT_MAX_SWEEP_WORK`] and [`DEFAULT_MAX_TOPOLOGY_UNITS`] for the units).
|
||||
pub fn regions_with_limits(shapes: &[Shape], clips: &[ClipPath], sliver: f64, max_work: u64, max_units: usize) -> Result<Vec<Region>, GeomError> {
|
||||
if shapes.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
Ok(Arrangement::new(shapes, clips, sliver)?.regions())
|
||||
Arrangement::new(shapes, clips, sliver, max_work, max_units)?.regions()
|
||||
}
|
||||
|
||||
/// The finiteness check [`regions_with`] makes: every point of every shape path and of every clip
|
||||
@@ -268,6 +288,9 @@ impl WindingNumber for Multi {
|
||||
let w = self.get(tag);
|
||||
Multi(Arc::new(if w == 0 { vec![] } else { vec![(tag, w)] }))
|
||||
}
|
||||
fn storage_units(&self) -> usize {
|
||||
self.0.len().max(1)
|
||||
}
|
||||
}
|
||||
|
||||
/// The sweep of shapes and clips. Tags `0..n` are shapes, `n + c` is clip `c`.
|
||||
@@ -281,7 +304,7 @@ struct Arrangement {
|
||||
}
|
||||
|
||||
impl Arrangement {
|
||||
fn new(shapes: &[Shape], clips: &[ClipPath], sliver: f64) -> Result<Self, GeomError> {
|
||||
fn new(shapes: &[Shape], clips: &[ClipPath], sliver: f64, work_limit: u64, output_limit: usize) -> Result<Self, GeomError> {
|
||||
let n = shapes.len();
|
||||
let mut used = vec![false; clips.len()];
|
||||
let mut shape_clips = Vec::with_capacity(n);
|
||||
@@ -304,8 +327,11 @@ impl Arrangement {
|
||||
let eps = eps_for(paths.iter().map(|p| &p.0))?;
|
||||
snap_horizontals(&mut paths.iter_mut().map(|p| &mut p.0).collect::<Vec<_>>(), eps);
|
||||
// The sweep can panic on rare near-degenerate input; the flattener then rasterizes.
|
||||
let sweep = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| Topology::<Multi>::from_paths(paths.iter().map(|(p, t)| (p, *t)), eps)));
|
||||
// Every subpath is closed, so a path error is a degenerate input too.
|
||||
let sweep = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
Topology::<Multi>::from_paths_with_limits(paths.iter().map(|(p, t)| (p, *t)), eps, work_limit, output_limit)
|
||||
}));
|
||||
// Every subpath is closed, so a path error or a sweep past its work or output limit is a
|
||||
// degenerate input too.
|
||||
let top = sweep.map_err(|_| GeomError::Degenerate)?.map_err(|_| GeomError::Degenerate)?;
|
||||
let rules = shapes.iter().map(|s| s.rule).chain(clips.iter().map(|c| c.rule)).collect();
|
||||
let tidy = Tidy::keeping(sliver, paths.iter().map(|p| &p.0));
|
||||
@@ -324,7 +350,7 @@ impl Arrangement {
|
||||
/// sets × edges. Instead the sets go into batches whose faces share no vertex (so no edge
|
||||
/// either): one pass per batch walks each face's contours as its own set's pass would, and the
|
||||
/// set a contour bounds is the one of its batch at its first point.
|
||||
fn regions(&self) -> Vec<Region> {
|
||||
fn regions(&self) -> Result<Vec<Region>, GeomError> {
|
||||
let top = &self.top;
|
||||
// The distinct non-empty coverage sets, numbered in the order met, and the set of each
|
||||
// side of each segment. Faces have many sides, so a set is worked out once per winding.
|
||||
@@ -391,7 +417,7 @@ impl Arrangement {
|
||||
}
|
||||
let mut faces: Vec<Vec<BezPath>> = vec![Vec::new(); sets.len()];
|
||||
for b in 0..batches {
|
||||
let c = top.contours(|w| id(w).is_some_and(|m| batch[m] == b));
|
||||
let c = contours(top, |w| id(w).is_some_and(|m| batch[m] == b))?;
|
||||
let owner: Option<Vec<usize>> = c
|
||||
.contours()
|
||||
.map(|ct| {
|
||||
@@ -403,7 +429,7 @@ impl Arrangement {
|
||||
// Not expected: every contour starts at a vertex of the arrangement. Fall back to
|
||||
// a pass per set for this batch.
|
||||
for m in (0..sets.len()).filter(|&m| batch[m] == b) {
|
||||
let c = top.contours(|w| id(w) == Some(m));
|
||||
let c = contours(top, |w| id(w) == Some(m))?;
|
||||
faces[m].extend(c.grouped().into_iter().map(|g| self.outline(&c, g)));
|
||||
}
|
||||
continue;
|
||||
@@ -439,7 +465,7 @@ impl Arrangement {
|
||||
out.push(Region { path, area, sources: sources.clone() });
|
||||
}
|
||||
}
|
||||
out
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The contours `idx` of `c` as one path, repaired, without slivers, and with the pieces the
|
||||
@@ -467,6 +493,18 @@ impl Arrangement {
|
||||
}
|
||||
}
|
||||
|
||||
/// The contours of `top`'s faces for which `inside` holds. The contour walk returns an error when the
|
||||
/// sweep left winding numbers that disagree around a point, and can still panic on other degenerate
|
||||
/// input; either way that input is degenerate.
|
||||
fn contours(top: &Topology<Multi>, inside: impl Fn(&Multi) -> bool) -> Result<Contours, GeomError> {
|
||||
walk_result(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| top.try_contours(inside))))
|
||||
}
|
||||
|
||||
/// Maps a contour walk that panicked or returned an error to [`GeomError::Degenerate`].
|
||||
fn walk_result<T>(walk: std::thread::Result<Result<T, linesweeper::Error>>) -> Result<T, GeomError> {
|
||||
walk.map_err(|_| GeomError::Degenerate)?.map_err(|_| GeomError::Degenerate)
|
||||
}
|
||||
|
||||
/// A point as a map key (the arrangement's vertices are exact).
|
||||
fn vertex_key(p: Point) -> (u64, u64) {
|
||||
(p.x.to_bits(), p.y.to_bits())
|
||||
@@ -963,6 +1001,20 @@ mod tests {
|
||||
Shape::new(path, FillRule::NonZero)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inconsistent_windings_are_degenerate() {
|
||||
// A walk that returns an error or panics gives `Degenerate`; one that finishes gives its contours.
|
||||
assert_eq!(walk_result::<u8>(Ok(Err(linesweeper::Error::InconsistentWindingNumbers))), Err(GeomError::Degenerate));
|
||||
assert_eq!(walk_result::<u8>(Err(Box::new("walk panicked"))), Err(GeomError::Degenerate));
|
||||
assert_eq!(walk_result(Ok(Ok(7_u8))), Ok(7));
|
||||
let shapes = [fill(rect(0.0, 0.0, 10.0, 10.0))];
|
||||
let arrangement = Arrangement::new(&shapes, &[], DEFAULT_SLIVER, DEFAULT_MAX_SWEEP_WORK, DEFAULT_MAX_TOPOLOGY_UNITS).unwrap();
|
||||
assert_eq!(contours(&arrangement.top, |w: &Multi| w.get(0) != 0).map(|c| c.contours().count()), Ok(1));
|
||||
// A walk that panics, in debug and release builds alike, gives `Degenerate`.
|
||||
let panicking = |_: &Multi| -> bool { panic!("degenerate walk") };
|
||||
assert_eq!(contours(&arrangement.top, panicking).err(), Some(GeomError::Degenerate));
|
||||
}
|
||||
|
||||
/// The regions with their sources and areas rounded to 1e-6, sorted.
|
||||
fn summary(regions: &[Region]) -> Vec<(Vec<usize>, f64)> {
|
||||
let mut v: Vec<(Vec<usize>, f64)> = regions.iter().map(|r| (r.sources.clone(), (r.area * 1e6).round() / 1e6)).collect();
|
||||
@@ -1035,6 +1087,58 @@ mod tests {
|
||||
top.contours(|w| *w != 0).contours().map(|c| c.path.area()).sum::<f64>().abs()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sweep_past_its_work_limit_is_degenerate() {
|
||||
let shapes = vec![fill(Circle::new((50.0, 50.0), 40.0).to_path(0.01)); 20];
|
||||
assert_eq!(Arrangement::new(&shapes, &[], DEFAULT_SLIVER, 1_000, DEFAULT_MAX_TOPOLOGY_UNITS).err(), Some(GeomError::Degenerate));
|
||||
assert_eq!(regions(&shapes, &[]).unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regions_with_limits_takes_the_callers_limits() {
|
||||
let shapes = vec![fill(Circle::new((50.0, 50.0), 40.0).to_path(0.01)); 20];
|
||||
let limited = |work, units| regions_with_limits(&shapes, &[], DEFAULT_SLIVER, work, units);
|
||||
assert_eq!(limited(1_000, DEFAULT_MAX_TOPOLOGY_UNITS).err(), Some(GeomError::Degenerate));
|
||||
assert_eq!(limited(DEFAULT_MAX_SWEEP_WORK, 10).err(), Some(GeomError::Degenerate));
|
||||
assert_eq!(limited(DEFAULT_MAX_SWEEP_WORK, DEFAULT_MAX_TOPOLOGY_UNITS).unwrap().len(), 1);
|
||||
}
|
||||
|
||||
// 1,100 overlapping shapes made only of horizontal edges at one height. The sweep makes one
|
||||
// output segment for each run of coincident horizontal pieces and none for a run whose winding
|
||||
// numbers cancel, as every run does here, so the topology stays under
|
||||
// DEFAULT_MAX_TOPOLOGY_UNITS.
|
||||
#[test]
|
||||
fn coincident_horizontal_edges_stay_under_the_output_limit() {
|
||||
let n = 1_100;
|
||||
let shapes: Vec<Shape> = (0..n)
|
||||
.map(|i| {
|
||||
let i = f64::from(i);
|
||||
let mut path = BezPath::new();
|
||||
path.move_to((i, 0.0));
|
||||
path.line_to((2.0 * f64::from(n) + i, 0.0));
|
||||
path.close_path();
|
||||
fill(path)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(regions(&shapes, &[]), Ok(vec![]));
|
||||
}
|
||||
|
||||
// 200 squares, each one unit down and right of the one before, cross each other's edges and
|
||||
// make fewer than 2,000,000 output segments, but the winding numbers of those segments hold an
|
||||
// entry for each square that covers them, which passes DEFAULT_MAX_TOPOLOGY_UNITS. The sweep
|
||||
// has no work limit here, so the output limit stops it.
|
||||
#[test]
|
||||
fn winding_entries_count_toward_the_output_limit() {
|
||||
let k = 200;
|
||||
let shapes: Vec<Shape> = (0..k)
|
||||
.map(|i| {
|
||||
let i = f64::from(i);
|
||||
fill(rect(i, i, f64::from(k) + i, f64::from(k) + i))
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(Arrangement::new(&shapes, &[], DEFAULT_SLIVER, u64::MAX, DEFAULT_MAX_TOPOLOGY_UNITS).err(), Some(GeomError::Degenerate));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stacked_boxes_fold_into_one_group_past_the_comparison_budget() {
|
||||
// Boxes one above the other, all sharing x 0–10: each stays open for every later one.
|
||||
@@ -1054,7 +1158,7 @@ mod tests {
|
||||
fill(rect(i, i + 0.25, i + 8.0, i + 8.25))
|
||||
})
|
||||
.collect();
|
||||
let a = Arrangement::new(&shapes, &[], DEFAULT_SLIVER).unwrap();
|
||||
let a = Arrangement::new(&shapes, &[], DEFAULT_SLIVER, DEFAULT_MAX_SWEEP_WORK, DEFAULT_MAX_TOPOLOGY_UNITS).unwrap();
|
||||
let mut sides = 0;
|
||||
let mut lists = std::collections::HashSet::new();
|
||||
for s in a.top.segment_indices() {
|
||||
|
||||
@@ -14,12 +14,16 @@ use kurbo::{Affine, BezPath, Point, Rect};
|
||||
|
||||
use crate::ink::{InkColor, InkId, InkSet, Overprint};
|
||||
|
||||
pub use compose::{ComplexGroup, ComplexReason, ComplexRegion, FlattenError, FlattenOptions, FlattenReport, Flattened, flatten};
|
||||
pub use compose::{
|
||||
ComplexGroup, ComplexReason, ComplexRegion, FlattenError, FlattenOptions, FlattenReport, FlattenSweepLimits, Flattened, flatten,
|
||||
flatten_with_limits,
|
||||
};
|
||||
pub use document::{
|
||||
FlattenDocumentError, FlattenDocumentOptions, FlattenDocumentReport, FlattenTotals, Unreadable, flatten_document, flatten_document_with_progress,
|
||||
FlattenDocumentError, FlattenDocumentOptions, FlattenDocumentReport, FlattenTotals, Unreadable, flatten_document, flatten_document_with_limits,
|
||||
flatten_document_with_limits_and_progress, flatten_document_with_progress,
|
||||
};
|
||||
pub use geom::FillRule;
|
||||
pub use raster::{FlattenPageError, FlattenPageOptions, FlattenPageReport, flatten_page};
|
||||
pub use raster::{FlattenPageError, FlattenPageOptions, FlattenPageReport, flatten_page, flatten_page_with_limits};
|
||||
|
||||
mod compose;
|
||||
mod document;
|
||||
|
||||
@@ -43,6 +43,8 @@ use craft_pdf::{OpenError, open_slice};
|
||||
use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape, Stroke, StrokeOpts};
|
||||
|
||||
use super::font::FontCache;
|
||||
#[cfg(test)]
|
||||
use super::geom;
|
||||
use super::shade::{self, Canvas, StopInks};
|
||||
use super::{
|
||||
BlendMode, DisplayList, FillItem, FillRule, GradientGeometry, GroupItem, ImageItem, ImageSpace, Item, Mask, MaskKind, Paint, PlacedGlyph,
|
||||
@@ -170,7 +172,7 @@ pub enum ReadError {
|
||||
pub fn read_page(pdf: &[u8], page: usize, opts: &ReadOptions) -> Result<(DisplayList, ReadReport), ReadError> {
|
||||
let doc = open_slice(pdf, None)?;
|
||||
let color = read_color(&doc, page, &opts.fallback)?;
|
||||
read_page_in(&doc, page, opts, color)
|
||||
read_page_in(&doc, page, opts, color, &super::FlattenSweepLimits::default())
|
||||
}
|
||||
|
||||
/// How a page's process color converts: its output intent's simulation, else `fallback`'s.
|
||||
@@ -189,7 +191,13 @@ pub(crate) fn read_color(doc: &Pdf, page: usize, fallback: &Fallback) -> Result<
|
||||
}
|
||||
|
||||
/// [`read_page`] of an open document, with the page's color already read.
|
||||
pub(crate) fn read_page_in(doc: &Pdf, page: usize, opts: &ReadOptions, color: ReadColor) -> Result<(DisplayList, ReadReport), ReadError> {
|
||||
pub(crate) fn read_page_in(
|
||||
doc: &Pdf,
|
||||
page: usize,
|
||||
opts: &ReadOptions,
|
||||
color: ReadColor,
|
||||
limits: &super::FlattenSweepLimits,
|
||||
) -> Result<(DisplayList, ReadReport), ReadError> {
|
||||
let (simulation, conversion) = color;
|
||||
let pages = doc.pages();
|
||||
let p = pages.get(page).ok_or(ReadError::NoPage(page))?;
|
||||
@@ -220,6 +228,7 @@ pub(crate) fn read_page_in(doc: &Pdf, page: usize, opts: &ReadOptions, color: Re
|
||||
masks: HashMap::new(),
|
||||
fonts: FontCache::new(),
|
||||
scale: f64::from(dpi) / 72.0,
|
||||
sweep_limits: *limits,
|
||||
};
|
||||
|
||||
let items = catch_unwind(AssertUnwindSafe(|| {
|
||||
@@ -260,6 +269,7 @@ struct Shared {
|
||||
fonts: FontCache,
|
||||
/// Raster pixels per point.
|
||||
scale: f64,
|
||||
sweep_limits: super::FlattenSweepLimits,
|
||||
}
|
||||
|
||||
/// How a paint composites: what wraps it in a group of its own.
|
||||
@@ -344,6 +354,11 @@ fn clip_group((clip, rule): (BezPath, FillRule)) -> GroupItem {
|
||||
}
|
||||
|
||||
impl<'s, 'a> Reader<'s, 'a> {
|
||||
fn nonzero(&self, path: &BezPath, rule: FillRule) -> (BezPath, FillRule) {
|
||||
let limits = self.shared.sweep_limits;
|
||||
nonzero_within(path, rule, limits.max_sweep_work, limits.max_sweep_units)
|
||||
}
|
||||
|
||||
fn new(shared: &'s mut Shared, glyph: bool, bounds: Rect) -> Self {
|
||||
Self {
|
||||
shared,
|
||||
@@ -621,7 +636,7 @@ impl<'s, 'a> Reader<'s, 'a> {
|
||||
fn area_fill(&mut self, path: BezPath, rule: FillRule, paint: &PdfPaint<'a>, stroke: bool) {
|
||||
let PdfPaint::Pattern(pattern) = paint else { return };
|
||||
self.flush();
|
||||
let (clip, rule) = nonzero(&path, rule);
|
||||
let (clip, rule) = self.nonzero(&path, rule);
|
||||
let (op, big_op, _) = self.overprint;
|
||||
let flag = if stroke { big_op } else { op };
|
||||
match pattern.as_ref() {
|
||||
@@ -975,7 +990,7 @@ impl<'s, 'a> Reader<'s, 'a> {
|
||||
let mut outline = BezPath::new();
|
||||
for item in &items {
|
||||
if let Item::Fill(f) = item {
|
||||
let (path, rule) = nonzero(&f.path, f.rule);
|
||||
let (path, rule) = self.nonzero(&f.path, f.rule);
|
||||
if rule != FillRule::NonZero {
|
||||
return None;
|
||||
}
|
||||
@@ -1016,7 +1031,7 @@ impl<'a> Device<'a> for Reader<'_, 'a> {
|
||||
|
||||
fn push_clip_path(&mut self, clip_path: &ClipPath) {
|
||||
self.flush();
|
||||
let clip = nonzero(&clip_path.path, fill_rule(clip_path.fill));
|
||||
let clip = self.nonzero(&clip_path.path, fill_rule(clip_path.fill));
|
||||
self.frames.push(Frame { kind: FrameKind::Clip, group: clip_group(clip) });
|
||||
}
|
||||
|
||||
@@ -1317,22 +1332,35 @@ fn dash_pattern(path: &BezPath, dashes: &[f32]) -> Option<Vec<f64>> {
|
||||
}
|
||||
|
||||
/// `path` filled by `rule`, as a path and the rule it is filled by. An even-odd path is
|
||||
/// rebuilt from its boundary as a path filled nonzero; if that fails it is kept closed and
|
||||
/// filled even-odd.
|
||||
/// rebuilt from its boundary as a path filled nonzero; if that fails, panics, or passes the
|
||||
/// flattener's default sweep work or output limit ([`geom::DEFAULT_MAX_SWEEP_WORK`],
|
||||
/// [`geom::DEFAULT_MAX_TOPOLOGY_UNITS`]), it is kept closed and filled even-odd. The same fallback
|
||||
/// applies when an input subpath fails [`linesweeper::binary_op`]'s automatic-accuracy check.
|
||||
#[cfg(test)]
|
||||
fn nonzero(path: &BezPath, rule: FillRule) -> (BezPath, FillRule) {
|
||||
nonzero_within(path, rule, geom::DEFAULT_MAX_SWEEP_WORK, geom::DEFAULT_MAX_TOPOLOGY_UNITS)
|
||||
}
|
||||
|
||||
/// Rebuilds an even-odd path with the sweep stopped after `work_limit` units of work or before
|
||||
/// its topology holds more than `output_limit` units. A stopped rebuild keeps the original rule.
|
||||
fn nonzero_within(path: &BezPath, rule: FillRule, work_limit: u64, output_limit: usize) -> (BezPath, FillRule) {
|
||||
if rule == FillRule::NonZero {
|
||||
return (path.clone(), FillRule::NonZero);
|
||||
}
|
||||
let closed = closed(path);
|
||||
match linesweeper::binary_op(&closed, &BezPath::new(), linesweeper::FillRule::EvenOdd, linesweeper::BinaryOp::Union) {
|
||||
Ok(contours) => {
|
||||
let op = catch_unwind(AssertUnwindSafe(|| {
|
||||
let top = linesweeper::topology::Topology::<i32>::from_paths_with_automatic_limits([(&closed, ())], work_limit, output_limit)?;
|
||||
top.try_contours(|winding| winding % 2 != 0)
|
||||
}));
|
||||
match op {
|
||||
Ok(Ok(contours)) => {
|
||||
let mut out = BezPath::new();
|
||||
for contour in contours.contours() {
|
||||
out.extend(contour.path.iter());
|
||||
}
|
||||
(out, FillRule::NonZero)
|
||||
}
|
||||
Err(_) => (closed, FillRule::EvenOdd),
|
||||
Ok(Err(_)) | Err(_) => (closed, FillRule::EvenOdd),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1363,6 +1391,119 @@ fn closed(path: &BezPath) -> BezPath {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn page_reader_uses_explicit_sweep_limits_for_even_odd_clips() {
|
||||
use craft_pdf::write::backend::geom::{PathBuilder, Rect as KRect};
|
||||
use craft_pdf::write::backend::page::PageSettings;
|
||||
use craft_pdf::write::backend::paint::{Fill, FillRule as KFillRule};
|
||||
use craft_pdf::write::{Metadata, Writer};
|
||||
let mut writer = Writer::new(Default::default(), Metadata::default());
|
||||
let mut page = writer.document_mut().start_page_with(PageSettings::from_wh(100.0, 100.0).unwrap());
|
||||
let mut surface = page.surface();
|
||||
let mut clip = PathBuilder::new();
|
||||
clip.push_rect(KRect::from_ltrb(0.0, 0.0, 90.0, 90.0).unwrap());
|
||||
clip.push_rect(KRect::from_ltrb(20.0, 20.0, 70.0, 70.0).unwrap());
|
||||
surface.push_clip_path(&clip.finish().unwrap(), &KFillRule::EvenOdd);
|
||||
let mut paint = PathBuilder::new();
|
||||
paint.push_rect(KRect::from_ltrb(0.0, 0.0, 100.0, 100.0).unwrap());
|
||||
surface.set_fill(Some(Fill::default()));
|
||||
surface.draw_path(&paint.finish().unwrap());
|
||||
surface.pop();
|
||||
surface.finish();
|
||||
page.finish();
|
||||
let bytes = writer.finish().unwrap();
|
||||
let doc = open_slice(&bytes, None).unwrap();
|
||||
let opts = ReadOptions::default();
|
||||
for limits in [
|
||||
super::super::FlattenSweepLimits::default(),
|
||||
super::super::FlattenSweepLimits { max_sweep_work: 1, ..Default::default() },
|
||||
super::super::FlattenSweepLimits { max_sweep_units: 1, ..Default::default() },
|
||||
] {
|
||||
let color = read_color(&doc, 0, &opts.fallback).unwrap();
|
||||
let (list, _) = read_page_in(&doc, 0, &opts, color, &limits).unwrap();
|
||||
let group = list
|
||||
.items
|
||||
.iter()
|
||||
.find_map(|item| match item {
|
||||
Item::Group(group) if group.clip.is_some() => Some(group),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let expected = if limits == super::super::FlattenSweepLimits::default() { FillRule::NonZero } else { FillRule::EvenOdd };
|
||||
assert_eq!(group.clip_rule, expected, "{limits:?}");
|
||||
let path = group.clip.as_ref().unwrap();
|
||||
let filled = |point| match group.clip_rule {
|
||||
FillRule::NonZero => path.winding(point) != 0,
|
||||
FillRule::EvenOdd => path.winding(point) % 2 != 0,
|
||||
};
|
||||
assert!(filled((10.0, 10.0).into()));
|
||||
assert!(!filled((50.0, 50.0).into()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn even_odd_path_with_inconsistent_windings_is_kept() {
|
||||
// `nonzero` returns a path for this input whether the sweep succeeds or reports
|
||||
// winding numbers that disagree around a point.
|
||||
let path = BezPath::from_svg("M4,-1 C8,1 -7,-2 5,8 L-4,-8 L2,1 L1,1 Z").unwrap();
|
||||
assert!(!nonzero(&path, FillRule::EvenOdd).0.elements().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn even_odd_holes_stay_open_beside_a_far_point() {
|
||||
// A square with a hole drawn in the same direction, a 0.3 wide sliver and a triangle at
|
||||
// 3e13, which makes the sweep tolerance about 0.43.
|
||||
let mut path = Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.0);
|
||||
path.extend(Rect::new(25.0, 25.0, 75.0, 75.0).to_path(0.0).iter());
|
||||
path.extend(Rect::new(200.0, 0.0, 200.3, 10.0).to_path(0.0).iter());
|
||||
path.move_to((3.0e13, 3.0e13));
|
||||
path.line_to((3.0e13 + 1.0e3, 3.0e13));
|
||||
path.line_to((3.0e13, 3.0e13 + 1.0e3));
|
||||
path.close_path();
|
||||
// The automatic-accuracy check rejects rebuilding the narrow subpath.
|
||||
let swept = linesweeper::binary_op(&path, &BezPath::new(), linesweeper::FillRule::EvenOdd, linesweeper::BinaryOp::Union);
|
||||
assert!(matches!(swept, Err(linesweeper::Error::FeatureBelowTolerance { .. })));
|
||||
let (out, rule) = nonzero(&path, FillRule::EvenOdd);
|
||||
let contains = |point| {
|
||||
let winding = out.winding(point);
|
||||
match rule {
|
||||
FillRule::EvenOdd => winding % 2 != 0,
|
||||
FillRule::NonZero => winding != 0,
|
||||
}
|
||||
};
|
||||
assert!(contains((200.15, 5.0).into()), "the narrow subpath remains filled");
|
||||
assert!(contains((10.0, 10.0).into()));
|
||||
assert!(!contains((50.0, 50.0).into()));
|
||||
assert_eq!(rule, FillRule::EvenOdd);
|
||||
assert_eq!(out, path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn even_odd_path_past_the_sweep_work_limit_is_kept() {
|
||||
// 21 stacked copies of one circle: the sweep compares their segments many times over.
|
||||
let circle = kurbo::Circle::new((50.0, 50.0), 40.0).to_path(0.01);
|
||||
let mut path = BezPath::new();
|
||||
for _ in 0..21 {
|
||||
path.extend(circle.iter());
|
||||
}
|
||||
let (kept, rule) = nonzero_within(&path, FillRule::EvenOdd, 1_000, geom::DEFAULT_MAX_TOPOLOGY_UNITS);
|
||||
assert_eq!(kept.elements(), closed(&path).elements());
|
||||
assert_eq!(rule, FillRule::EvenOdd);
|
||||
assert_ne!(nonzero(&path, FillRule::EvenOdd).0.elements(), closed(&path).elements());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn even_odd_path_past_the_sweep_output_limit_is_kept() {
|
||||
// A square with a hole drawn in the same direction makes 8 output segments.
|
||||
let mut path = Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.0);
|
||||
path.extend(Rect::new(25.0, 25.0, 75.0, 75.0).to_path(0.0).iter());
|
||||
let (kept, rule) = nonzero_within(&path, FillRule::EvenOdd, geom::DEFAULT_MAX_SWEEP_WORK, 4);
|
||||
assert_eq!(kept.elements(), closed(&path).elements());
|
||||
assert_eq!(rule, FillRule::EvenOdd);
|
||||
assert_ne!(kept.winding((50.0, 50.0).into()), 0);
|
||||
assert_eq!(nonzero(&path, FillRule::EvenOdd).0.winding((50.0, 50.0).into()), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn even_odd_paths_keep_their_rule_when_the_rebuild_fails() {
|
||||
// Two nested squares drawn in the same direction: even-odd leaves a hole, nonzero fills it.
|
||||
|
||||
@@ -41,7 +41,7 @@ use craft_pdf::interpret::color::CmykConversion;
|
||||
use craft_pdf::write::backend::SerializeSettings;
|
||||
use kurbo::{Affine, Rect, Shape as _};
|
||||
|
||||
use super::document::{FlattenDocumentError, FlattenDocumentOptions, flatten_document};
|
||||
use super::document::{FlattenDocumentError, FlattenDocumentOptions, flatten_document_with_limits};
|
||||
use super::pdf::{ReadError, ReadOptions, ReadReport};
|
||||
use super::write::{WriteError, page_pdf};
|
||||
use super::{
|
||||
@@ -409,11 +409,21 @@ pub enum FlattenPageError {
|
||||
}
|
||||
|
||||
/// Page `page` (from 0) of `pdf` with its transparency flattened, as a one-page PDF: the
|
||||
/// one-page case of [`flatten_document`].
|
||||
/// one-page case of [`super::flatten_document`].
|
||||
pub fn flatten_page(pdf: &[u8], page: usize, opts: &FlattenPageOptions) -> Result<(Vec<u8>, FlattenPageReport), FlattenPageError> {
|
||||
flatten_page_with_limits(pdf, page, opts, &super::FlattenSweepLimits::default())
|
||||
}
|
||||
|
||||
/// [`flatten_page`] with explicit sweep work and output limits.
|
||||
pub fn flatten_page_with_limits(
|
||||
pdf: &[u8],
|
||||
page: usize,
|
||||
opts: &FlattenPageOptions,
|
||||
limits: &super::FlattenSweepLimits,
|
||||
) -> Result<(Vec<u8>, FlattenPageReport), FlattenPageError> {
|
||||
let doc =
|
||||
FlattenDocumentOptions { read: opts.read.clone(), flatten: opts.flatten, pages: Some(page..page.saturating_add(1)), ..Default::default() };
|
||||
let (bytes, mut report) = flatten_document(pdf, &doc).map_err(|e| match e {
|
||||
let (bytes, mut report) = flatten_document_with_limits(pdf, &doc, limits).map_err(|e| match e {
|
||||
FlattenDocumentError::Open(e) => FlattenPageError::Open(e),
|
||||
FlattenDocumentError::PageRange { .. } => FlattenPageError::Read(ReadError::NoPage(page)),
|
||||
FlattenDocumentError::Read { source, .. } => FlattenPageError::Read(source),
|
||||
|
||||
@@ -117,6 +117,41 @@ fn opts() -> FlattenDocumentOptions {
|
||||
FlattenDocumentOptions { flatten: FlattenOptions { raster_dpi: 72.0, ..FlattenOptions::default() }, ..FlattenDocumentOptions::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_entry_points_keep_explicit_sweep_limits() {
|
||||
use craft_prepress::flatten::{
|
||||
FlattenSweepLimits, flatten_document_with_limits, flatten_document_with_limits_and_progress, flatten_page_with_limits,
|
||||
};
|
||||
let settings = SerializeSettings { no_device_cs: false, group_color_space: GroupColorSpace::Cmyk, ..Default::default() };
|
||||
let mut writer = Writer::new(settings, Metadata::default());
|
||||
let mut page = writer.document_mut().start_page_with(PageSettings::from_wh(200.0, 160.0).unwrap());
|
||||
let mut surface = page.surface();
|
||||
rect(&mut surface, 20.0, 20.0, 120.0, 100.0, fill(255, 0, 0, 0));
|
||||
surface.push_opacity(NormalizedF32::new(0.5).unwrap());
|
||||
rect(&mut surface, 70.0, 60.0, 170.0, 130.0, fill(0, 255, 0, 0));
|
||||
surface.pop();
|
||||
surface.finish();
|
||||
page.finish();
|
||||
let source = writer.finish().unwrap();
|
||||
let options = opts();
|
||||
let (_, ordinary) = flatten_document(&source, &options).unwrap();
|
||||
assert_eq!(ordinary.totals.complex_groups, 0);
|
||||
for limits in [FlattenSweepLimits { max_sweep_work: 1, ..Default::default() }, FlattenSweepLimits { max_sweep_units: 1, ..Default::default() }] {
|
||||
let (_, document) = flatten_document_with_limits(&source, &options, &limits).unwrap();
|
||||
assert_eq!(document.totals.complex_groups, 1);
|
||||
let mut progress = Vec::new();
|
||||
let (_, observed) = flatten_document_with_limits_and_progress(&source, &options, &limits, &mut |done, total| {
|
||||
progress.push((done, total));
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(observed, document);
|
||||
assert_eq!(progress, [(1, 1)]);
|
||||
let page_options = FlattenPageOptions { flatten: options.flatten, ..Default::default() };
|
||||
let (_, page) = flatten_page_with_limits(&source, 0, &page_options, &limits).unwrap();
|
||||
assert_eq!(page.flatten.complex_groups.len(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
fn separate(pdf: &[u8], page: usize) -> Plates {
|
||||
plates(pdf, page, DPI, &Options::default()).unwrap()
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "<commit>
|
||||
| German | — | — | TeX patterns (embedded, or a Language pack) |
|
||||
| Bulgarian | — | — | syllable rules |
|
||||
| Gujarati, Hindi | the installed Hunspell dictionary (Hindi: nukta letters spelled either way) | generic checks | akshara rules (or a Language pack) |
|
||||
| Marathi (mr) | its Language pack or Hunspell dictionary, as any pack language | — | akshara rules (or a Language pack) |
|
||||
|
||||
Grammar rules, suggestion tuning and the rule-based hyphenation are code: they work in every
|
||||
build.
|
||||
|
||||
@@ -300,6 +300,7 @@ impl<'a> MapLookup<'a> {
|
||||
|
||||
/// Lowercase the query only; the first group's representative keeps its authored case.
|
||||
pub(crate) fn fold(&self, c: char) -> char {
|
||||
count_map_steps(1);
|
||||
let l = c.to_lowercase().next().unwrap_or(c);
|
||||
self.first.get(&l).copied().unwrap_or(l)
|
||||
}
|
||||
@@ -308,10 +309,34 @@ impl<'a> MapLookup<'a> {
|
||||
fn alternatives(&self, c: char) -> Vec<char> {
|
||||
let mut seen = HashSet::new();
|
||||
seen.insert(c);
|
||||
self.groups_of.get(&c).into_iter().flatten().filter_map(|&i| self.groups.get(i)).flatten().copied().filter(|&x| seen.insert(x)).collect()
|
||||
self.groups_of
|
||||
.get(&c)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|&i| self.groups.get(i))
|
||||
.inspect(|group| count_map_steps(1 + group.len()))
|
||||
.flatten()
|
||||
.copied()
|
||||
.filter(|&x| seen.insert(x))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
// The MAP lookups on this thread: one per letter folded, and one per group a letter's
|
||||
// alternatives come from and per member read from it.
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
static MAP_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn count_map_steps(count: usize) {
|
||||
#[cfg(test)]
|
||||
MAP_STEPS.with(|steps| steps.set(steps.get().saturating_add(count)));
|
||||
#[cfg(not(test))]
|
||||
let _ = count;
|
||||
}
|
||||
|
||||
/// Every way of changing up to `t.max_map_changes` letters of `chars` to a MAP relative (`alts`,
|
||||
/// letter by letter), with its cost: all one-change variants first, then two, and so on, so the
|
||||
/// [`MAX_MAP_VARIANTS`] cap drops the variants with the most changes.
|
||||
@@ -738,36 +763,27 @@ mod tests {
|
||||
let dic = format!("{}\n{}\n", words.len(), words.join("\n"));
|
||||
AffixDict::from_hunspell(&aff, &dic, &[]).unwrap()
|
||||
}
|
||||
fn cpu_cost(f: &mut impl FnMut()) -> f64 {
|
||||
let ran = || {
|
||||
let s = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
|
||||
s.split_whitespace().next()?.parse::<u64>().ok()
|
||||
};
|
||||
let (start, before) = (std::time::Instant::now(), ran());
|
||||
f();
|
||||
match (before, ran()) {
|
||||
(Some(a), Some(b)) if b > a => (b - a) as f64 * 1e-9,
|
||||
_ => start.elapsed().as_secs_f64(),
|
||||
}
|
||||
}
|
||||
let small = dictionary(1);
|
||||
let big = dictionary(8);
|
||||
let run = |d: &AffixDict| {
|
||||
MAP_STEPS.with(|steps| steps.set(0));
|
||||
let out = suggest_in(d, "abcdef", 8, &Tuning::DEFAULT);
|
||||
let expected: Vec<String> = (0..8).map(|i| format!("abcde{}", char::from_u32(0xe000 + i).unwrap())).collect();
|
||||
assert_eq!(out, expected);
|
||||
std::hint::black_box(out);
|
||||
MAP_STEPS.with(std::cell::Cell::get)
|
||||
};
|
||||
run(&small);
|
||||
run(&big);
|
||||
let (mut t1, mut t8) = (f64::INFINITY, f64::INFINITY);
|
||||
for _ in 0..5 {
|
||||
t1 = t1.min(cpu_cost(&mut || (0..8).for_each(|_| run(&small))) / 8.0);
|
||||
t8 = t8.min(cpu_cost(&mut || run(&big)));
|
||||
let (s1, s8) = (run(&small), run(&big));
|
||||
// 8x the groups and the stems: about 8x the lookups, where a scan of the groups for each
|
||||
// letter of each stem is 64x.
|
||||
assert!(s8 <= 10 * s1, "8x MAP and stems cost {s8} MAP lookups against {s1}");
|
||||
// A letter folds through the index alone, one lookup: with the groups taken away, each
|
||||
// letter still folds the same.
|
||||
let groups: Vec<Vec<char>> = vec!["aąá".chars().collect(), "óu".chars().collect()];
|
||||
let lookup = MapLookup::new(&groups);
|
||||
let index_only = MapLookup { groups: &[], first: lookup.first.clone(), groups_of: lookup.groups_of.clone() };
|
||||
for &c in groups.iter().flatten() {
|
||||
assert_eq!(index_only.fold(c), lookup.fold(c), "{c}");
|
||||
}
|
||||
let ratio = t8 / t1.max(1e-9);
|
||||
eprintln!("MAP/stem scan: small={t1:.6}s big={t8:.6}s ratio={ratio:.2}");
|
||||
assert!(ratio < 24.0, "8x MAP and stems cost {ratio:.2}x: {t1:.6}s / {t8:.6}s");
|
||||
}
|
||||
|
||||
/// craft-libs#487 review: MAP variants are made by number of changes, so when a long word has
|
||||
|
||||
@@ -130,6 +130,34 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A zero-width joiner or non-joiner in a conjunct (`પુસ્` U+200D `તક`) keeps the word whole,
|
||||
/// and the word is found under the dictionary's spelling, which has no joiner.
|
||||
#[test]
|
||||
fn words_with_joiners_are_one_word_and_spelled() {
|
||||
test_dict::install();
|
||||
for word in ["પુસ્\u{200D}તક", "પુસ્\u{200C}તકોમાં"] {
|
||||
let text = format!("ઘર {word} ગામ");
|
||||
let at = text.find(word).unwrap();
|
||||
assert!(crate::words(&text).contains(&(at, at + word.len())), "{word:?}");
|
||||
assert!(is_correct(word), "{word:?}");
|
||||
let issues = crate::check_text(&text, &[(0..text.len(), crate::ProofLang::Gu)]);
|
||||
assert!(issues.is_empty(), "{word:?}: {issues:?}");
|
||||
}
|
||||
// Still a misspelling with a joiner, and a joiner at a word's edge is not in the word.
|
||||
assert!(!is_correct("પુસ્\u{200D}તકક"));
|
||||
let text = "ઘર\u{200D} ગામ";
|
||||
assert!(crate::words(text).contains(&(0, "ઘર".len())));
|
||||
// A word with a joiner written twice is a repeated word.
|
||||
let text = "પુસ્\u{200D}તક પુસ્\u{200D}તક";
|
||||
let issues = crate::check_grammar_in(text, crate::ProofLang::Gu);
|
||||
assert!(issues.iter().any(|i| i.start == 0 && i.end == text.len()), "{issues:?}");
|
||||
// A word Gujarati repeats on purpose (`જલ્દી જલ્દી`) still is one when typed with a joiner.
|
||||
for text in ["જલ્\u{200D}દી જલ્\u{200D}દી", "જલ્\u{200C}દી જલ્\u{200C}દી"] {
|
||||
let issues = crate::check_grammar_in(text, crate::ProofLang::Gu);
|
||||
assert!(issues.is_empty(), "{text:?}: {issues:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forbidden_words_are_rejected() {
|
||||
test_dict::install();
|
||||
|
||||
@@ -143,6 +143,22 @@ mod tests {
|
||||
test_dict::install();
|
||||
}
|
||||
|
||||
/// A zero-width joiner or non-joiner after a virama (`क्` U+200D `ष`) keeps the word whole, and
|
||||
/// the word is found under the dictionary's spelling, which has no joiner.
|
||||
#[test]
|
||||
fn words_with_joiners_are_one_word_and_spelled() {
|
||||
test_dict::install();
|
||||
for word in ["परीक्\u{200D}षण", "परीक्\u{200C}षण", "मित्\u{200D}रों"] {
|
||||
let text = format!("घर {word} पानी।");
|
||||
let at = text.find(word).unwrap();
|
||||
assert!(crate::words(&text).contains(&(at, at + word.len())), "{word:?}");
|
||||
assert!(is_correct(word), "{word:?}");
|
||||
let issues = crate::check_text(&text, &[(0..text.len(), crate::ProofLang::Hi)]);
|
||||
assert!(issues.is_empty(), "{word:?}: {issues:?}");
|
||||
}
|
||||
assert!(!is_correct("परीक्\u{200D}षणण"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_dictionary_applies() {
|
||||
test_dict::install();
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
//!
|
||||
//! **Bulgarian**: the Bulgarian syllable rules ([`crate::bg`]); no pattern file or word list.
|
||||
//!
|
||||
//! **Gujarati and Hindi**: breaks between aksharas, never inside a conjunct or between a
|
||||
//! **Gujarati, Hindi and Marathi**: breaks between aksharas, never inside a conjunct or between a
|
||||
//! consonant and its vowel sign ([`crate::indic`], rules from the script's Unicode encoding); no
|
||||
//! pattern file.
|
||||
//!
|
||||
@@ -120,7 +120,7 @@ pub enum Source {
|
||||
Patterns,
|
||||
/// A heuristic for a language without a dictionary or patterns.
|
||||
Heuristic,
|
||||
/// A language's syllable rules (Bulgarian [`crate::bg`], Turkish, Gujarati and Hindi [`crate::indic`]).
|
||||
/// A language's syllable rules (Bulgarian [`crate::bg`], Turkish, Gujarati, Hindi and Marathi [`crate::indic`]).
|
||||
Rules,
|
||||
/// No break points: the word is too short or no source applies.
|
||||
None,
|
||||
@@ -167,7 +167,7 @@ fn core_breaks(core: &[char], lang: ProofLang) -> (Vec<usize>, Source) {
|
||||
if lang == ProofLang::Bg && core.iter().all(|&c| crate::bg::is_letter(c)) {
|
||||
return (crate::bg::points(core), Source::Rules);
|
||||
}
|
||||
// Gujarati and Hindi words break between aksharas ([`crate::indic`]); other words in their runs
|
||||
// Gujarati, Hindi and Marathi words break between aksharas ([`crate::indic`]); other words in their runs
|
||||
// (`WordCraft`) are hyphenated as English.
|
||||
if let Some(script) = crate::indic::Script::of(lang)
|
||||
&& core.iter().all(|&c| script.is_letter(c))
|
||||
@@ -242,8 +242,8 @@ fn composed_chars(core: &[char]) -> (Vec<char>, Vec<Option<usize>>) {
|
||||
(nfc, starts)
|
||||
}
|
||||
|
||||
/// Does a pack's `pats` hyphenate `core` in `lang`? Russian, Bulgarian, Turkish, Gujarati and
|
||||
/// Hindi: a word in their script (the guard their rules use; for Gujarati and Hindi, the script's
|
||||
/// Does a pack's `pats` hyphenate `core` in `lang`? Russian, Bulgarian, Turkish, Gujarati, Hindi
|
||||
/// and Marathi: a word in their script (the guard their rules use; for the Indic ones, the script's
|
||||
/// letters and marks and the joiners inside a conjunct, [`crate::indic`]) whose letters the
|
||||
/// patterns know, so a word with a letter the pack never mentions goes on to the fallback rules. Polish, Portuguese, Italian
|
||||
/// and German: every word, as their embedded patterns do. Any other language: a word whose letters
|
||||
@@ -254,7 +254,7 @@ fn pack_patterns_fit(lang: ProofLang, pats: &Patterns, core: &[char]) -> bool {
|
||||
ProofLang::Bg => core.iter().all(|&c| crate::bg::is_letter(c)) && pack_knows(pats, core),
|
||||
ProofLang::Tr => core.iter().all(|&c| crate::tr::hyphen::is_letter(c)) && pack_knows(pats, core),
|
||||
ProofLang::Pl | ProofLang::Pt | ProofLang::It | ProofLang::De => true,
|
||||
ProofLang::Gu | ProofLang::Hi => {
|
||||
_ if crate::indic::Script::of(lang).is_some() => {
|
||||
crate::indic::Script::of(lang).is_some_and(|s| core.iter().all(|&c| s.is_letter(c))) && pack_knows(pats, core)
|
||||
}
|
||||
_ => pats.values(core).is_some(),
|
||||
|
||||
@@ -235,3 +235,12 @@ fn hindi_breaks_between_aksharas_within_the_limits() {
|
||||
assert_eq!(hi("«विद्यार्थी»"), "«वि-द्या-र्थी»", "punctuation around the word");
|
||||
assert_eq!(hi("Typography"), hyphenate_word_in("Typography", &lim, ProofLang::En));
|
||||
}
|
||||
|
||||
/// storytold/vectorcraft#4947: Marathi, a pack language (`mr`), breaks between aksharas as Hindi
|
||||
/// does, within the paragraph's limits.
|
||||
#[test]
|
||||
fn marathi_breaks_between_aksharas() {
|
||||
let mr = ProofLang::from_tag(Some("mr-IN"));
|
||||
assert_eq!(hyphenate_word_in("महाराष्ट्र", &Limits::default(), mr), "महा-रा-ष्ट्र");
|
||||
assert_eq!(word_breaks_in("महाराष्ट्र", mr).1, Source::Rules);
|
||||
}
|
||||
@@ -14,7 +14,8 @@
|
||||
//! The rules come from the scripts' Unicode encoding alone; no pattern file or word list is
|
||||
//! read (and none is borrowed). The Brahmic blocks share one layout (the ISCII order), so a
|
||||
//! script is its block's start and a few script-specific code points (`Script::kind`).
|
||||
//! Gujarati ([`ProofLang::Gu`]) and Hindi ([`ProofLang::Hi`], [`Script::Devanagari`]) use them;
|
||||
//! Gujarati ([`ProofLang::Gu`]), Hindi ([`ProofLang::Hi`]) and Marathi (the pack language `mr`)
|
||||
//! use them, Hindi and Marathi with [`Script::Devanagari`];
|
||||
//! another language written in one of these scripts is one more line in [`Script::of`].
|
||||
//!
|
||||
//! A single akshara left at the end or start of a line is ruled out by the paragraph's
|
||||
@@ -61,6 +62,9 @@ impl Script {
|
||||
match lang {
|
||||
ProofLang::Gu => Some(Script::Gujarati),
|
||||
ProofLang::Hi => Some(Script::Devanagari),
|
||||
// Marathi has no proofing language of its own: `mr`, `mr-IN` and `mar` are pack
|
||||
// languages, spelled from their pack or Hunspell dictionary.
|
||||
ProofLang::Pack(l) if matches!(l.primary(), "mr" | "mar") => Some(Script::Devanagari),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -243,11 +247,16 @@ mod tests {
|
||||
assert_eq!(hi("क्\u{200D}षमा"), "क्\u{200D}ष-मा");
|
||||
}
|
||||
|
||||
/// Gujarati and Hindi are mapped to their scripts, other languages to none.
|
||||
/// Gujarati, Hindi and Marathi (a pack language, by any of its tags) are mapped to their
|
||||
/// scripts, other languages (another pack language among them) to none.
|
||||
#[test]
|
||||
fn languages_map_to_their_script() {
|
||||
assert_eq!(Script::of(ProofLang::Gu), Some(Script::Gujarati));
|
||||
assert_eq!(Script::of(ProofLang::Hi), Some(Script::Devanagari));
|
||||
for tag in ["mr", "mr-IN", "mar"] {
|
||||
assert_eq!(Script::of(ProofLang::from_tag(Some(tag))), Some(Script::Devanagari), "{tag}");
|
||||
}
|
||||
assert_eq!(Script::of(ProofLang::from_tag(Some("ne"))), None);
|
||||
assert_eq!(Script::of(ProofLang::En), None);
|
||||
assert_eq!(Script::of(ProofLang::Bg), None);
|
||||
}
|
||||
|
||||
+22
-3
@@ -489,13 +489,32 @@ fn in_dialect(s: &str, word: &str, lang: ProofLang) -> String {
|
||||
}
|
||||
|
||||
/// Words in `text`: (byte start, byte end). Combining marks belong to the word they follow, so a
|
||||
/// word typed decomposed (`tambie\u{301}n`, NFD) is one word, as its precomposed form is.
|
||||
/// word typed decomposed (`tambie\u{301}n`, NFD) is one word, as its precomposed form is. A
|
||||
/// zero-width joiner or non-joiner between two letters, digits or marks is inside the word, as in
|
||||
/// Unicode's word boundaries (UAX #29): Indic text uses one to choose how a conjunct is drawn
|
||||
/// (`क्` U+200D `ष`, `પુસ્` U+200D `તક`). A joiner at a word's edge is not part of it.
|
||||
pub fn words(text: &str) -> Vec<(usize, usize)> {
|
||||
use indic::is_joiner;
|
||||
let mut out = Vec::new();
|
||||
let mut start: Option<usize> = None;
|
||||
let is_w = |c: char| c.is_alphanumeric() || c == '\'' || c == '’' || c == '-' || unicode_normalization::char::is_combining_mark(c);
|
||||
let is_core = |c: char| c.is_alphanumeric() || unicode_normalization::char::is_combining_mark(c);
|
||||
let is_w = |c: char| is_core(c) || c == '\'' || c == '’' || c == '-';
|
||||
// The char before was a letter, digit or mark, or a joiner kept after one.
|
||||
let mut after_core = false;
|
||||
// Is the first char after the current run of joiners a letter, digit or mark? Looked up once
|
||||
// per run, so a long run of joiners costs linear time, not quadratic.
|
||||
let mut run_ends_core: Option<bool> = None;
|
||||
for (i, c) in text.char_indices() {
|
||||
match (start, is_w(c)) {
|
||||
let w = if is_joiner(c) {
|
||||
after_core
|
||||
&& *run_ends_core
|
||||
.get_or_insert_with(|| text.get(i + c.len_utf8()..).and_then(|rest| rest.chars().find(|&n| !is_joiner(n))).is_some_and(is_core))
|
||||
} else {
|
||||
run_ends_core = None;
|
||||
is_w(c)
|
||||
};
|
||||
after_core = if is_joiner(c) { w } else { is_core(c) };
|
||||
match (start, w) {
|
||||
(None, true) => start = Some(i),
|
||||
(Some(s), false) => {
|
||||
out.push((s, i));
|
||||
|
||||
@@ -46,10 +46,13 @@ pub(crate) fn is_correct(script: &Script, d: &AffixDict, word: &str, opts: &crat
|
||||
}
|
||||
|
||||
/// Is one word (no hyphens) in the dictionary or the user dictionary, spelled as it is or as the
|
||||
/// script's [`Script::variant`]?
|
||||
/// script's [`Script::variant`]? A word with a zero-width joiner or non-joiner (`પુસ્` U+200D
|
||||
/// `તક`) is tried as typed, then without its joiners, as a dictionary that ignores them
|
||||
/// (Hunspell's `IGNORE`) would: they choose how a conjunct is drawn, not how the word is spelled.
|
||||
fn known(script: &Script, d: &AffixDict, w: &str) -> bool {
|
||||
let listed = |w: &str| d.check(w) || crate::in_user_dictionary(&w.to_lowercase());
|
||||
listed(w) || script.variant.and_then(|v| v(w)).is_some_and(|v| listed(&v))
|
||||
let spelled = |w: &str| listed(w) || script.variant.and_then(|v| v(w)).is_some_and(|v| listed(&v));
|
||||
spelled(w) || (w.contains(crate::indic::is_joiner) && spelled(&w.replace(crate::indic::is_joiner, "")))
|
||||
}
|
||||
|
||||
/// A language's script, messages and choices for [`check`].
|
||||
@@ -91,9 +94,11 @@ fn repeated_words(text: &str, ws: &[(usize, usize)], rules: &Rules, v: &mut Vec<
|
||||
let (Some(w0), Some(w1), Some(gap)) = (text.get(*a0..*b0), text.get(*a1..*b1), text.get(*b0..*a1)) else { continue };
|
||||
if !gap.is_empty()
|
||||
&& gap.chars().all(char::is_whitespace)
|
||||
&& w0.chars().all(|c| c.is_alphabetic() || (rules.script.is_letter)(c))
|
||||
&& w0.chars().all(|c| c.is_alphabetic() || (rules.script.is_letter)(c) || crate::indic::is_joiner(c))
|
||||
&& w0 == w1
|
||||
&& (rules.flag_repeat)(w0)
|
||||
// The words a language repeats on purpose are listed without joiners (`જલ્દી`), so
|
||||
// `જલ્` U+200D `દી` twice is the same intentional repeat.
|
||||
&& (rules.flag_repeat)(&w0.replace(crate::indic::is_joiner, ""))
|
||||
{
|
||||
v.push(issue(rules, *a0, *b1, format!("{}: “{w1}”", rules.repeated_word), vec![w0.to_string()]));
|
||||
}
|
||||
|
||||
@@ -317,19 +317,25 @@ impl Name {
|
||||
let mut letters_from = vec![0usize; n + 1];
|
||||
let mut run = 0usize;
|
||||
for (slot, c) in letters_from.iter_mut().zip(&chars).rev() {
|
||||
count_name_read();
|
||||
run = if c.is_alphabetic() { run.saturating_add(1) } else { 0 };
|
||||
*slot = run;
|
||||
}
|
||||
let last_bang = chars.iter().rposition(|c| *c == '!');
|
||||
let last_bang = chars.iter().rposition(|c| {
|
||||
count_name_read();
|
||||
*c == '!'
|
||||
});
|
||||
let mut cyrillic_runs: Vec<(usize, usize)> = (0..n).map(|i| (i, i + 1)).collect();
|
||||
let mut start = 0;
|
||||
while start < n {
|
||||
count_name_read();
|
||||
if !chars.get(start).is_some_and(|c| is_cyrillic(*c)) {
|
||||
start += 1;
|
||||
continue;
|
||||
}
|
||||
let mut end = start + 1;
|
||||
while chars.get(end).is_some_and(|c| is_cyrillic(*c)) {
|
||||
count_name_read();
|
||||
end += 1;
|
||||
}
|
||||
for slot in cyrillic_runs.get_mut(start..end).into_iter().flatten() {
|
||||
@@ -341,6 +347,19 @@ impl Name {
|
||||
}
|
||||
}
|
||||
|
||||
// Each character of a decoded name that `Name::new` and the position checks of `score` read on
|
||||
// this thread.
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
static NAME_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn count_name_read() {
|
||||
#[cfg(test)]
|
||||
NAME_READS.with(|reads| reads.set(reads.get().saturating_add(1)));
|
||||
}
|
||||
|
||||
/// Whether the character at `i` of `chars` is common in Western names, for weighing windows-1252
|
||||
/// against Mac Roman: letters (but not those windows-1252 has only at 0x80–0x9F, where Mac Roman
|
||||
/// keeps its accented lowercase: Mac "Größe" is 1252 "Grš§e"), typographic punctuation,
|
||||
@@ -356,6 +375,7 @@ fn is_latin_common(name: &Name, i: usize) -> bool {
|
||||
/// Where the character at `i` of `name` sits: right after an ASCII letter or digit (inside a word
|
||||
/// or a number), and how many letters (accented ones too: "¡Ánimo!") follow it directly.
|
||||
fn position(name: &Name, i: usize) -> (bool, usize) {
|
||||
count_name_read();
|
||||
let after_ascii = i.checked_sub(1).and_then(|k| name.chars.get(k)).is_some_and(|c| c.is_ascii_alphanumeric());
|
||||
let letters_after = name.letters_from.get(i.saturating_add(1)).copied().unwrap_or(0);
|
||||
(after_ascii, letters_after)
|
||||
@@ -394,6 +414,7 @@ fn cyrillic_word(name: &Name, i: usize) -> bool {
|
||||
|
||||
/// The run of Cyrillic letters around the Cyrillic letter at `i` (`start..end`).
|
||||
fn cyrillic_run(name: &Name, i: usize) -> (usize, usize) {
|
||||
count_name_read();
|
||||
name.cyrillic_runs.get(i).copied().unwrap_or((i, i.saturating_add(1)))
|
||||
}
|
||||
|
||||
@@ -870,11 +891,16 @@ mod tests {
|
||||
// 64 KiB of one letter (é in windows-1252, й in windows-1251, Mac Roman's È), of
|
||||
// alternating Cyrillic letters, and of "¡ab" with no "!": every character used to rescan
|
||||
// the rest of the name, which took minutes.
|
||||
for unit in [&[0xe9u8][..], &[0xe9, 0xea][..], &[0xa1, b'a', b'b'][..]] {
|
||||
let name = unit.repeat(GUESS_SAMPLE / unit.len());
|
||||
let started = std::time::Instant::now();
|
||||
// A name four times as long must take about four times the reads, not sixteen.
|
||||
let reads = |unit: &[u8], len: usize| {
|
||||
let name = unit.repeat(len / unit.len());
|
||||
NAME_READS.with(|reads| reads.set(0));
|
||||
let _ = guess(&[&name], "");
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?} took {:?}", unit, started.elapsed());
|
||||
NAME_READS.with(std::cell::Cell::get)
|
||||
};
|
||||
for unit in [&[0xe9u8][..], &[0xe9, 0xea][..], &[0xa1, b'a', b'b'][..]] {
|
||||
let (quarter, full) = (reads(unit, GUESS_SAMPLE / 4), reads(unit, GUESS_SAMPLE));
|
||||
assert!(full <= 5 * quarter, "{unit:?}: {quarter} reads for a quarter of the name, {full} for all of it");
|
||||
}
|
||||
}
|
||||
}
|
||||
+36
-6
@@ -185,12 +185,41 @@ fn references(text: &str) -> impl Iterator<Item = &str> {
|
||||
text.match_indices('&').filter_map(|(at, _)| {
|
||||
let rest = text.get(at + 1..)?;
|
||||
// Look no further than the longest name: a file of `&`s without `;` would be read quadratically.
|
||||
let end = rest.bytes().take(MAX_NAME + 1).position(|b| b == b';')?;
|
||||
let name = rest.get(..end)?;
|
||||
let mut read = 0usize;
|
||||
let end = rest.bytes().take(MAX_NAME + 1).position(|b| {
|
||||
read += 1;
|
||||
b == b';'
|
||||
});
|
||||
count_name_bytes(read);
|
||||
let name = rest.get(..end?)?;
|
||||
(!name.is_empty() && name.len() <= MAX_NAME && !name.starts_with('#') && !name.contains(char::is_whitespace)).then_some(name)
|
||||
})
|
||||
}
|
||||
|
||||
// The bytes `references` reads after each `&` while looking for the `;`, on this thread, and the
|
||||
// most a test lets it read: past that the count fails the test at once rather than after the rest
|
||||
// of the work.
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
static NAME_BYTES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
static NAME_BYTE_LIMIT: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn count_name_bytes(count: usize) {
|
||||
#[cfg(test)]
|
||||
{
|
||||
let read = NAME_BYTES.with(|read| {
|
||||
read.set(read.get().saturating_add(count));
|
||||
read.get()
|
||||
});
|
||||
let limit = NAME_BYTE_LIMIT.with(std::cell::Cell::get);
|
||||
assert!(read <= limit, "{read} bytes read for reference names, more than the {limit} allowed");
|
||||
}
|
||||
#[cfg(not(test))]
|
||||
let _ = count;
|
||||
}
|
||||
|
||||
/// What entity `name` expands to (bytes), references in its value followed.
|
||||
fn expanded<'a>(name: &'a str, entities: &HashMap<&'a str, Vec<&'a str>>, memo: &mut HashMap<&'a str, usize>, depth: u32) -> usize {
|
||||
if let Some(n) = memo.get(name) {
|
||||
@@ -501,11 +530,12 @@ mod tests {
|
||||
assert!(!expansion_too_large("<svg a=\"& \"/>"));
|
||||
// Many `&`s with no `;` after them are read in linear time.
|
||||
let ampersands = format!("<!DOCTYPE svg [<!ENTITY a \"x\">]><svg id=\"{}\"/>", "&".repeat(1 << 20));
|
||||
let start = std::time::Instant::now();
|
||||
// At most the longest name and its `;` after each `&`; a quadratic read is past this limit
|
||||
// long before its end.
|
||||
NAME_BYTES.with(|read| read.set(0));
|
||||
NAME_BYTE_LIMIT.with(|limit| limit.set(ampersands.matches('&').count() * (MAX_NAME + 1)));
|
||||
assert!(!expansion_too_large(&ersands));
|
||||
eprintln!("DIAG svg ampersand run read in {:?}", start.elapsed());
|
||||
// A quadratic read would take hours; the bound is loose for a loaded machine.
|
||||
assert!(start.elapsed() < std::time::Duration::from_secs(120), "{:?}", start.elapsed());
|
||||
NAME_BYTE_LIMIT.with(|limit| limit.set(usize::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -9,6 +9,9 @@ description = "Source-level platform regression guards, test deadlines, hostile-
|
||||
publish = false
|
||||
|
||||
[features]
|
||||
default = []
|
||||
# Image comparison, PNG reading and writing, and golden reference checks.
|
||||
image = ["dep:png"]
|
||||
# `mcp::McpChild`: an MCP stdio test client.
|
||||
mcp = ["dep:serde_json"]
|
||||
# Pinned-corpus manifests and the `corpus::pinned` test gate (native only).
|
||||
@@ -17,16 +20,21 @@ corpus = ["dep:sha2", "dep:libc"]
|
||||
font-coverage = ["dep:skrifa"]
|
||||
|
||||
[dependencies]
|
||||
png = { version = "0.18", optional = true }
|
||||
sha2 = { version = "0.10", default-features = false, features = ["std"], optional = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
skrifa = { workspace = true, optional = true }
|
||||
toml = { version = "1", default-features = false, features = ["parse", "serde", "std"] }
|
||||
serde_json = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = { version = "0.2", optional = true }
|
||||
rustix = { version = "1.1", default-features = false, features = ["std", "fs"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
||||
[[test]]
|
||||
name = "mcp"
|
||||
required-features = ["mcp"]
|
||||
|
||||
@@ -258,6 +258,49 @@ Changes from `craft-media-testkit`'s `hammer`:
|
||||
- `parse` is owned and runs on a worker thread. A closure that borrows from the test needs its data
|
||||
moved or shared with an `Arc`.
|
||||
|
||||
## `image` feature
|
||||
|
||||
`craft-testkit = { ..., features = ["image"] }` adds `craft_testkit::image` and `assert_similar!`. It depends on `png` 0.18.
|
||||
|
||||
| Item | What it does |
|
||||
|---|---|
|
||||
| `Rgba8`, `Gray8` | Borrowed 8-bit views. `new` returns an error when a side is 0 or the buffer is not exactly `width × height × channels` bytes. |
|
||||
| `diff_rgba`, `diff_gray` | `DiffStats`: differing pixels, maximum and mean absolute sample difference, nearest-rank p99 of each pixel's largest difference, and PSNR with a peak of 255. RGBA counts alpha as a fourth sample. |
|
||||
| `psnr(a, b, peak)` | PSNR of two `u8` or `u16` planes. The caller passes the peak (255, 1023, 4095, 65535). Equal planes give `f64::INFINITY`; empty or unequal planes and a peak that is not finite and positive are errors. |
|
||||
| `Tolerance`, `compare_rgba`, `compare_gray` | Gates for maximum difference, p99, minimum PSNR and the share of bad pixels, each inclusive. With `neighborhood`, a pixel is bad only when nothing in the other image's 3×3 window is within `channel`, checked in both directions. |
|
||||
| `diff_image` | An opaque RGBA image of each absolute sample difference times 8, with alpha differences shown in every color channel. |
|
||||
| `decode_png`, `encode_png`, `encode_gray_png`, `read_png`, `write_png`, `write_gray_png` | 8-bit PNG reading and writing under `PngLimits` (default 16,384 × 16,384 pixels, 64 MiB encoded, 256 MiB decoded). Palette, low bit depths, 16-bit samples, `tRNS` and interlacing are converted to 8-bit gray or RGBA. Gamma, ICC and sRGB chunks are not applied. |
|
||||
| `check_golden`, `assert_similar!` | Compare an image with a reference PNG. The reference is written only when the variable named in `GoldenOptions::bless_var` (default `CRAFT_BLESS`) is exactly `1`; otherwise a missing reference is an error. A failed check writes `<name>.actual.png` and `<name>.diff.png` into `GoldenOptions::failures_dir`, using `<name>-1`, `<name>-2` and so on rather than replacing a file. `assert_similar!` fails the calling test. |
|
||||
|
||||
The views, statistics, PSNR, tolerances, the difference image and the in-memory PNG functions build for `wasm32`. The file functions, the bless variable and the golden check are native only.
|
||||
|
||||
```rust
|
||||
use craft_testkit::image::{GoldenOptions, Rgba8, Tolerance};
|
||||
|
||||
let options = GoldenOptions { bless_var: "FILMCRAFT_BLESS", ..GoldenOptions::new(&failures, "title_card") };
|
||||
let tolerance = Tolerance { min_psnr: Some(45.0), max_abs: Some(12), max_p99: Some(2), ..Tolerance::EXACT };
|
||||
craft_testkit::assert_similar!(&reference, Rgba8::new(width, height, &pixels)?, tolerance, options);
|
||||
```
|
||||
|
||||
## fixtures
|
||||
|
||||
The `fixtures` module (native targets only) generates missing test fixtures and shares them between test runs and processes:
|
||||
|
||||
- `fixtures_root(var)` is the nonempty value of `var` (default `CRAFT_FIXTURES_DIR`) or `<workspace>/target/fixtures`. The workspace is the one that holds the package under test, found from the `CARGO_MANIFEST_DIR` that Cargo and nextest set when they run tests: the folder named by the package's `package.workspace` key, or else the nearest folder whose `Cargo.toml` has a `[workspace]` table. A test binary run without `CARGO_MANIFEST_DIR` needs the root variable. `CARGO_TARGET_DIR` does not move the root. `fixtures_dir(sub, var)` creates a folder below the root and rejects an absolute `sub`, one containing `..`, and on Windows one with a drive inside it (`group\C:outside`). It creates the folder one level at a time and returns an error, without creating the rest, when a level resolves outside the root or is not a folder, for example a symbolic link or junction under the root that points elsewhere. The check uses paths, so it does not detect a folder that another process replaces with a link while the call runs or after it returns.
|
||||
- `temp_path(out)` creates a new, empty sibling of `out` with `create_new`, keeping the extension. A name that already exists is never reused.
|
||||
- `publish(tmp, out)` moves a nonempty regular file into place while holding a lock on `<out>.fixture-lock`. When `out` is already a nonempty regular file, it is kept and `tmp` is removed; the check reads only the type and length of `out`, so a nonempty `out` that cannot be read is kept too. A directory at `out` is an error, and so are an `out` whose name ends with `.fixture-lock` and a file system that does not support the lock.
|
||||
- `generate(out, required_var, make)` and `generate_with(out, required, make)` return a cached fixture without calling `make`, or run `make` on a claimed temporary file and publish it. The temporary file is removed when `make` fails, panics, writes nothing or makes `out` name the temporary file, and such an `out` is not returned. When `make` fails after another process published `out`, the published file is returned. A fixture that cannot be made follows the [skip](#skip) rule with the required variable `generate` is given (default `CRAFT_TEST_REQUIRED`): unset or empty prints `SKIPPED: <reason>` on standard error and returns `None`, `1` fails the test, and any other value, `0` included, fails the test as a configuration error. Only `generate` reads the required variable. `generate_with` uses the caller's `required` value instead: `true` fails the test, and `false` prints the skip line and returns `None`.
|
||||
- `run_generator(cmd, env, max_output)` runs a generator with `env` added to the child's environment only, and keeps at most `max_output` bytes of each output stream (`DEFAULT_MAX_OUTPUT` is 64 KiB). The variables and stream settings stay on `cmd`, so use a new `Command` for each call that needs a clean environment.
|
||||
- `report(name, status)` and `generate_and_report(name, outputs, generate)` print one of these lines on standard output, which FilmCraft's `cargo xtask fixtures` counts:
|
||||
|
||||
```text
|
||||
FIXTURE made <name>
|
||||
FIXTURE cached <name>
|
||||
FIXTURE skipped <name>
|
||||
```
|
||||
|
||||
A complete fixture is a nonempty regular file. A consumer that needs a valid media file checks its format after generation.
|
||||
|
||||
## mcp
|
||||
|
||||
The `mcp` feature adds `craft_testkit::mcp` and the `serde_json` dependency. The module is built on every target except `wasm32`, and it opens no network connection.
|
||||
@@ -451,6 +494,21 @@ PhotoCraft and DeckCraft. `holders_take_turns` waits on channels where the copie
|
||||
|---|---|---|---|
|
||||
| `Rng`, the edits of `mutations` and `hammer` | storytold/craft-libs | `crates/media-testkit/src/hostile.rs` | `75a654f4` |
|
||||
|
||||
### image
|
||||
|
||||
| Code | Source |
|
||||
|---|---|
|
||||
| Statistics, PNG reading and writing, golden check | FilmCraft `crates/testkit/src/golden.rs` at `e4ab3c6a99` |
|
||||
| Per-pixel channel tolerance and bad-pixel share | AniCraft `crates/engine/tests/golden/mod.rs` at `3435e98681` |
|
||||
| Gray view and 3×3 neighborhood comparison | PdfCraft `crates/oracle/src/pixels.rs` at `eead454105` |
|
||||
|
||||
### fixtures
|
||||
|
||||
| Part | Repository | Path | Commit |
|
||||
|---|---|---|---|
|
||||
| Locations, publication with winner reuse, reporting, and the moved tests | storytold/filmcraft | `crates/testkit/src/fixtures.rs` | `e4ab3c6a99` |
|
||||
| `generate_with` and the required rule, with `failed_generator_skips_when_optional` and `failed_generator_fails_when_required` | storytold/craft-libs | `crates/media-testkit/src/lib.rs` | `75a654f4f8` |
|
||||
|
||||
### mcp
|
||||
|
||||
| Code | Repository | Path | SHA |
|
||||
@@ -533,6 +591,25 @@ An adoption keeps the variable name the app uses today.
|
||||
CADCraft's and TextureCraft's loops make other edits than `mutations`. Their adoptions say which
|
||||
cases change, and keep the test names.
|
||||
|
||||
### image
|
||||
|
||||
| Consumer | Today | State |
|
||||
|---|---|---|
|
||||
| FilmCraft | `golden.rs`, `FILMCRAFT_BLESS` | Not started |
|
||||
| AniCraft | `crates/engine/tests/golden/mod.rs`, `UPDATE_GOLDENS` | Not started |
|
||||
| PdfCraft | `pdfcraft-oracle` `pixels.rs` | Not started |
|
||||
| VectorCraft | `crates/testkit/src/raster.rs` (comparison only) | Not started |
|
||||
| DesignCraft | `crates/render/tests/it/effects.rs`, `DESIGNCRAFT_BLESS` | Not started |
|
||||
|
||||
### fixtures
|
||||
|
||||
| Consumer | Copy it replaces | State |
|
||||
|---|---|---|
|
||||
| FilmCraft | `crates/testkit/src/fixtures.rs` (passes `FILMCRAFT_FIXTURES_DIR` and `FILMCRAFT_REQUIRE_ORACLES`) | Not switched |
|
||||
| EffectCraft | `crates/media/tests/it/footage.rs` | Not switched |
|
||||
| craft-libs `audio` and `video` tests | `crates/audio/tests/codecs/testkit.rs`, `crates/video/tests/vp8/common/mod.rs` | Not switched |
|
||||
| `craft-media-testkit` | its `fixtures` module and `temp_path` (keeps its public names) | Not switched |
|
||||
|
||||
### mcp
|
||||
|
||||
| Consumer | Code it replaces | State |
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,997 @@
|
||||
//! Image comparison for tests: checked RGBA8 and gray views, difference statistics, PSNR, a
|
||||
//! tolerance with an optional 3×3 neighborhood, a difference image, PNG reading and writing with
|
||||
//! size limits, and golden reference checks.
|
||||
//!
|
||||
//! Every function returns a [`Result`]. `assert_similar!` is the one form that fails a test, and it
|
||||
//! panics in the calling test.
|
||||
//!
|
||||
//! Statistics compare raw 8-bit sample values. PNG decoding does not apply gamma, ICC or sRGB
|
||||
//! chunks, so a reference compares as the bytes it stores.
|
||||
//!
|
||||
//! The views, statistics, PSNR, tolerance, difference image and in-memory PNG functions build for
|
||||
//! `wasm32`. The file functions, the bless variable and the golden check are native only.
|
||||
|
||||
use std::fmt;
|
||||
use std::io::Cursor;
|
||||
use std::path::PathBuf;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::{
|
||||
ffi::OsStr,
|
||||
fs,
|
||||
io::{Read, Write},
|
||||
path::Path,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
};
|
||||
|
||||
/// The bless variable `GoldenOptions::new` uses.
|
||||
pub const DEFAULT_BLESS_VAR: &str = "CRAFT_BLESS";
|
||||
|
||||
/// The most failure image pairs [`check_golden`] writes for one name in one folder.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_FAILURE_PAIRS: usize = 1000;
|
||||
|
||||
/// Why an image could not be compared, read or written.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub enum ImageError {
|
||||
/// A side is 0, or the stated size does not fit in memory.
|
||||
InvalidDimensions { width: u32, height: u32 },
|
||||
/// The pixel buffer is not exactly `width × height × channels` bytes.
|
||||
InvalidBufferLength { expected: usize, actual: usize },
|
||||
/// The two images have different sizes.
|
||||
SizeMismatch { a: (u32, u32), b: (u32, u32) },
|
||||
/// The two PSNR planes have different sample counts.
|
||||
PlaneLengthMismatch { a: usize, b: usize },
|
||||
/// A PSNR plane has no samples.
|
||||
EmptyPlane,
|
||||
/// A tolerance value is NaN or out of range.
|
||||
InvalidTolerance(&'static str),
|
||||
/// The PSNR peak is not finite or not greater than 0.
|
||||
InvalidPeak(f64),
|
||||
/// An input or output is larger than its [`PngLimits`] value.
|
||||
LimitExceeded(String),
|
||||
/// A failure image name or bless variable name is not allowed.
|
||||
InvalidName(String),
|
||||
/// The reference file does not exist and the bless variable is not `1`.
|
||||
MissingReference { path: PathBuf, bless_var: String },
|
||||
/// The image is outside the tolerance; the actual and difference images were written.
|
||||
GoldenMismatch(Box<GoldenMismatch>),
|
||||
/// The image is outside the tolerance, and the actual and difference images could not be
|
||||
/// encoded or written.
|
||||
GoldenMismatchUnsaved(Box<UnsavedMismatch>),
|
||||
/// The PNG stream is malformed, truncated or uses an unsupported form.
|
||||
Decode(String),
|
||||
/// The PNG encoder failed.
|
||||
Encode(String),
|
||||
/// A file could not be read or written.
|
||||
Io { path: PathBuf, source: std::io::Error },
|
||||
}
|
||||
|
||||
/// The details of a failed golden check.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct GoldenMismatch {
|
||||
/// The reference image.
|
||||
pub reference: PathBuf,
|
||||
/// The comparison that failed.
|
||||
pub verdict: Verdict,
|
||||
/// The actual image, written inside the failure folder.
|
||||
pub actual: PathBuf,
|
||||
/// The difference image, written inside the failure folder.
|
||||
pub diff: PathBuf,
|
||||
}
|
||||
|
||||
/// The details of a failed golden check whose failure images could not be saved.
|
||||
#[derive(Debug)]
|
||||
pub struct UnsavedMismatch {
|
||||
/// The reference image.
|
||||
pub reference: PathBuf,
|
||||
/// The comparison that failed.
|
||||
pub verdict: Verdict,
|
||||
/// Why the actual or difference image could not be encoded or written.
|
||||
pub error: ImageError,
|
||||
}
|
||||
|
||||
impl fmt::Display for ImageError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::InvalidDimensions { width, height } => {
|
||||
write!(f, "a {width}x{height} image is not valid: each side must be at least 1 and the buffer size must fit in memory")
|
||||
}
|
||||
Self::InvalidBufferLength { expected, actual } => {
|
||||
write!(f, "the pixel buffer holds {actual} bytes, but the stated size needs {expected}")
|
||||
}
|
||||
Self::SizeMismatch { a, b } => write!(f, "cannot compare a {}x{} image with a {}x{} one", a.0, a.1, b.0, b.1),
|
||||
Self::PlaneLengthMismatch { a, b } => write!(f, "cannot compare a plane of {a} samples with one of {b}"),
|
||||
Self::EmptyPlane => write!(f, "PSNR needs at least one sample"),
|
||||
Self::InvalidTolerance(why) => write!(f, "invalid tolerance: {why}"),
|
||||
Self::InvalidPeak(peak) => write!(f, "invalid PSNR peak {peak}: it must be finite and greater than 0"),
|
||||
Self::LimitExceeded(what) | Self::InvalidName(what) => f.write_str(what),
|
||||
Self::MissingReference { path, bless_var } => {
|
||||
write!(f, "{}: no reference image; run with {bless_var}=1 to write it, and look at it before committing", path.display())
|
||||
}
|
||||
Self::GoldenMismatch(m) => {
|
||||
write!(
|
||||
f,
|
||||
"{}: {}; actual image written to {}, difference image to {}",
|
||||
m.reference.display(),
|
||||
m.verdict,
|
||||
m.actual.display(),
|
||||
m.diff.display()
|
||||
)
|
||||
}
|
||||
Self::GoldenMismatchUnsaved(m) => {
|
||||
write!(f, "{}: {}; the actual and difference images could not be written: {}", m.reference.display(), m.verdict, m.error)
|
||||
}
|
||||
Self::Decode(e) => write!(f, "PNG decoding failed: {e}"),
|
||||
Self::Encode(e) => write!(f, "PNG encoding failed: {e}"),
|
||||
Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ImageError {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
match self {
|
||||
Self::Io { source, .. } => Some(source),
|
||||
Self::GoldenMismatchUnsaved(m) => Some(&m.error),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks a view's size and returns its pixel count.
|
||||
fn checked_len(width: u32, height: u32, channels: usize, actual: usize) -> Result<usize, ImageError> {
|
||||
if width == 0 || height == 0 {
|
||||
return Err(ImageError::InvalidDimensions { width, height });
|
||||
}
|
||||
let pixels = usize::try_from(width).ok().zip(usize::try_from(height).ok()).and_then(|(w, h)| w.checked_mul(h));
|
||||
let expected = pixels.and_then(|n| n.checked_mul(channels)).ok_or(ImageError::InvalidDimensions { width, height })?;
|
||||
if expected != actual {
|
||||
return Err(ImageError::InvalidBufferLength { expected, actual });
|
||||
}
|
||||
Ok(expected / channels)
|
||||
}
|
||||
|
||||
/// A borrowed 8-bit RGBA image, row-major, straight alpha, no row padding.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Rgba8<'a> {
|
||||
width: u32,
|
||||
height: u32,
|
||||
pixels: &'a [u8],
|
||||
}
|
||||
|
||||
impl<'a> Rgba8<'a> {
|
||||
/// Borrows `pixels` as a `width` × `height` image. Returns an error when a side is 0 or the
|
||||
/// buffer is not exactly `width × height × 4` bytes.
|
||||
pub fn new(width: u32, height: u32, pixels: &'a [u8]) -> Result<Self, ImageError> {
|
||||
checked_len(width, height, 4, pixels.len())?;
|
||||
Ok(Self { width, height, pixels })
|
||||
}
|
||||
|
||||
pub fn width(&self) -> u32 {
|
||||
self.width
|
||||
}
|
||||
|
||||
pub fn height(&self) -> u32 {
|
||||
self.height
|
||||
}
|
||||
|
||||
/// The pixel bytes, four per pixel.
|
||||
pub fn pixels(&self) -> &'a [u8] {
|
||||
self.pixels
|
||||
}
|
||||
|
||||
fn plane(self) -> Plane<'a> {
|
||||
Plane { width: self.width, height: self.height, channels: 4, pixels: self.pixels }
|
||||
}
|
||||
}
|
||||
|
||||
/// A borrowed 8-bit grayscale image, row-major, no row padding.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Gray8<'a> {
|
||||
width: u32,
|
||||
height: u32,
|
||||
pixels: &'a [u8],
|
||||
}
|
||||
|
||||
impl<'a> Gray8<'a> {
|
||||
/// Borrows `pixels` as a `width` × `height` image. Returns an error when a side is 0 or the
|
||||
/// buffer is not exactly `width × height` bytes.
|
||||
pub fn new(width: u32, height: u32, pixels: &'a [u8]) -> Result<Self, ImageError> {
|
||||
checked_len(width, height, 1, pixels.len())?;
|
||||
Ok(Self { width, height, pixels })
|
||||
}
|
||||
|
||||
pub fn width(&self) -> u32 {
|
||||
self.width
|
||||
}
|
||||
|
||||
pub fn height(&self) -> u32 {
|
||||
self.height
|
||||
}
|
||||
|
||||
/// The pixel bytes, one per pixel.
|
||||
pub fn pixels(&self) -> &'a [u8] {
|
||||
self.pixels
|
||||
}
|
||||
|
||||
fn plane(self) -> Plane<'a> {
|
||||
Plane { width: self.width, height: self.height, channels: 1, pixels: self.pixels }
|
||||
}
|
||||
}
|
||||
|
||||
/// A checked view with its channel count.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Plane<'a> {
|
||||
width: u32,
|
||||
height: u32,
|
||||
channels: usize,
|
||||
pixels: &'a [u8],
|
||||
}
|
||||
|
||||
fn same_size(a: Plane<'_>, b: Plane<'_>) -> Result<(), ImageError> {
|
||||
if (a.width, a.height) != (b.width, b.height) {
|
||||
return Err(ImageError::SizeMismatch { a: (a.width, a.height), b: (b.width, b.height) });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Difference statistics over raw 8-bit samples. RGBA counts alpha as a fourth sample.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct DiffStats {
|
||||
/// Pixels with any sample different.
|
||||
pub differing_pixels: usize,
|
||||
/// Largest absolute sample difference.
|
||||
pub max_abs: u8,
|
||||
/// Mean absolute sample difference over every sample.
|
||||
pub mean_abs: f64,
|
||||
/// The nearest-rank 99th percentile of each pixel's largest sample difference: the value at
|
||||
/// one-based position `ceil(0.99 × pixels)` in ascending order.
|
||||
pub p99: u8,
|
||||
/// PSNR in dB with a peak of 255 over every sample; `f64::INFINITY` when the images are equal.
|
||||
pub psnr: f64,
|
||||
/// Pixels in each image.
|
||||
pub total_pixels: usize,
|
||||
}
|
||||
|
||||
impl fmt::Display for DiffStats {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"PSNR {:.2} dB, max {}, p99 {}, mean {:.3}, {} of {} pixels differ",
|
||||
self.psnr, self.max_abs, self.p99, self.mean_abs, self.differing_pixels, self.total_pixels
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn max_delta(p: &[u8], q: &[u8]) -> u8 {
|
||||
p.iter().zip(q).map(|(x, y)| x.abs_diff(*y)).max().unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The value at one-based position `ceil(count × percent / 100)` of the histogram's samples.
|
||||
fn nearest_rank(histogram: &[usize; 256], count: usize, percent: u128) -> u8 {
|
||||
let rank = (count as u128 * percent).div_ceil(100).max(1);
|
||||
let mut seen = 0u128;
|
||||
for (value, &n) in histogram.iter().enumerate() {
|
||||
seen += n as u128;
|
||||
if seen >= rank {
|
||||
return u8::try_from(value).unwrap_or(u8::MAX);
|
||||
}
|
||||
}
|
||||
u8::MAX
|
||||
}
|
||||
|
||||
fn psnr_from(squares: u128, samples: usize, peak: f64) -> f64 {
|
||||
if squares == 0 {
|
||||
return f64::INFINITY;
|
||||
}
|
||||
let mse = squares as f64 / samples as f64;
|
||||
20.0 * peak.log10() - 10.0 * mse.log10()
|
||||
}
|
||||
|
||||
fn stats(a: Plane<'_>, b: Plane<'_>) -> Result<DiffStats, ImageError> {
|
||||
same_size(a, b)?;
|
||||
let mut histogram = [0usize; 256];
|
||||
let (mut sum, mut squares) = (0u128, 0u128);
|
||||
let (mut max_abs, mut differing_pixels, mut total_pixels) = (0u8, 0usize, 0usize);
|
||||
for (p, q) in a.pixels.chunks_exact(a.channels).zip(b.pixels.chunks_exact(b.channels)) {
|
||||
let mut largest = 0u8;
|
||||
for (x, y) in p.iter().zip(q) {
|
||||
let d = x.abs_diff(*y);
|
||||
sum += u128::from(d);
|
||||
squares += u128::from(d) * u128::from(d);
|
||||
largest = largest.max(d);
|
||||
}
|
||||
if let Some(n) = histogram.get_mut(usize::from(largest)) {
|
||||
*n += 1;
|
||||
}
|
||||
max_abs = max_abs.max(largest);
|
||||
differing_pixels += usize::from(largest > 0);
|
||||
total_pixels += 1;
|
||||
}
|
||||
let samples = a.pixels.len();
|
||||
Ok(DiffStats {
|
||||
differing_pixels,
|
||||
max_abs,
|
||||
mean_abs: sum as f64 / samples as f64,
|
||||
p99: nearest_rank(&histogram, total_pixels, 99),
|
||||
psnr: psnr_from(squares, samples, 255.0),
|
||||
total_pixels,
|
||||
})
|
||||
}
|
||||
|
||||
/// Statistics for two RGBA images of the same size.
|
||||
pub fn diff_rgba(a: Rgba8<'_>, b: Rgba8<'_>) -> Result<DiffStats, ImageError> {
|
||||
stats(a.plane(), b.plane())
|
||||
}
|
||||
|
||||
/// Statistics for two gray images of the same size.
|
||||
pub fn diff_gray(a: Gray8<'_>, b: Gray8<'_>) -> Result<DiffStats, ImageError> {
|
||||
stats(a.plane(), b.plane())
|
||||
}
|
||||
|
||||
mod sealed {
|
||||
pub trait Sealed {}
|
||||
impl Sealed for u8 {}
|
||||
impl Sealed for u16 {}
|
||||
}
|
||||
|
||||
/// A sample type [`psnr`] accepts: `u8` or `u16`.
|
||||
pub trait Sample: Copy + sealed::Sealed {
|
||||
/// The sample as an unsigned value.
|
||||
fn value(self) -> u32;
|
||||
}
|
||||
|
||||
impl Sample for u8 {
|
||||
fn value(self) -> u32 {
|
||||
u32::from(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl Sample for u16 {
|
||||
fn value(self) -> u32 {
|
||||
u32::from(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// PSNR in dB of two planes: `10 log10(peak² / MSE)`, with `MSE = Σ(a − b)² / samples`.
|
||||
///
|
||||
/// The caller supplies `peak`, for example 255 for 8-bit samples, 1023 for 10-bit, 4095 for
|
||||
/// 12-bit or 65535 for 16-bit. Equal planes return `f64::INFINITY`. Returns an error for planes
|
||||
/// of different lengths, empty planes, and a peak that is not finite or not greater than 0.
|
||||
pub fn psnr<T: Sample>(a: &[T], b: &[T], peak: f64) -> Result<f64, ImageError> {
|
||||
if !(peak.is_finite() && peak > 0.0) {
|
||||
return Err(ImageError::InvalidPeak(peak));
|
||||
}
|
||||
if a.len() != b.len() {
|
||||
return Err(ImageError::PlaneLengthMismatch { a: a.len(), b: b.len() });
|
||||
}
|
||||
if a.is_empty() {
|
||||
return Err(ImageError::EmptyPlane);
|
||||
}
|
||||
let squares: u128 = a
|
||||
.iter()
|
||||
.zip(b)
|
||||
.map(|(x, y)| {
|
||||
let d = u128::from(x.value().abs_diff(y.value()));
|
||||
d * d
|
||||
})
|
||||
.sum();
|
||||
Ok(psnr_from(squares, a.len(), peak))
|
||||
}
|
||||
|
||||
/// Acceptance gates for a comparison. Each gate that is set must hold, and every bound is
|
||||
/// inclusive.
|
||||
///
|
||||
/// A pixel is bad when its largest sample difference is greater than `channel`. With
|
||||
/// `neighborhood`, a pixel is bad only when no pixel in the other image's 3×3 window around it
|
||||
/// (clipped at the edges) is within `channel`; the check runs in both directions and the larger
|
||||
/// count is used. `max_abs`, `max_p99` and `min_psnr` always read the aligned statistics.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Tolerance {
|
||||
/// Largest allowed sample difference.
|
||||
pub max_abs: Option<u8>,
|
||||
/// Largest allowed [`DiffStats::p99`].
|
||||
pub max_p99: Option<u8>,
|
||||
/// Smallest allowed PSNR in dB.
|
||||
pub min_psnr: Option<f64>,
|
||||
/// The sample difference a pixel may have and still not count as bad.
|
||||
pub channel: u8,
|
||||
/// Largest allowed share of bad pixels, in `0.0..=1.0`; the allowed count is the largest
|
||||
/// count whose share of the pixels is at most this value.
|
||||
pub max_bad_fraction: Option<f64>,
|
||||
/// Match each pixel against the other image's 3×3 window instead of the aligned pixel.
|
||||
pub neighborhood: bool,
|
||||
}
|
||||
|
||||
impl Tolerance {
|
||||
/// Every sample must be equal.
|
||||
pub const EXACT: Tolerance =
|
||||
Tolerance { max_abs: Some(0), max_p99: None, min_psnr: None, channel: 0, max_bad_fraction: None, neighborhood: false };
|
||||
|
||||
/// Returns an error when `min_psnr` is NaN or `max_bad_fraction` is NaN or outside
|
||||
/// `0.0..=1.0`.
|
||||
pub fn validate(&self) -> Result<(), ImageError> {
|
||||
if self.min_psnr.is_some_and(f64::is_nan) {
|
||||
return Err(ImageError::InvalidTolerance("min_psnr is NaN"));
|
||||
}
|
||||
if self.max_bad_fraction.is_some_and(|f| !(0.0..=1.0).contains(&f)) {
|
||||
return Err(ImageError::InvalidTolerance("max_bad_fraction must be in 0.0..=1.0"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The result of comparing two images under a [`Tolerance`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Verdict {
|
||||
/// Aligned statistics.
|
||||
pub stats: DiffStats,
|
||||
/// Bad pixels under the tolerance's `channel` and `neighborhood` rules.
|
||||
pub bad_pixels: usize,
|
||||
/// The bad pixels allowed, when the tolerance sets `max_bad_fraction`.
|
||||
pub allowed_bad_pixels: Option<usize>,
|
||||
/// The tolerance the comparison used.
|
||||
pub tolerance: Tolerance,
|
||||
}
|
||||
|
||||
impl Verdict {
|
||||
/// Whether every gate of the tolerance holds.
|
||||
pub fn passed(&self) -> bool {
|
||||
let t = &self.tolerance;
|
||||
t.max_abs.is_none_or(|m| self.stats.max_abs <= m)
|
||||
&& t.max_p99.is_none_or(|m| self.stats.p99 <= m)
|
||||
&& t.min_psnr.is_none_or(|m| self.stats.psnr >= m)
|
||||
&& self.allowed_bad_pixels.is_none_or(|n| self.bad_pixels <= n)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Verdict {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let t = &self.tolerance;
|
||||
write!(f, "{}, {} pixels differ by more than {}", self.stats, self.bad_pixels, t.channel)?;
|
||||
if t.neighborhood {
|
||||
f.write_str(" within a 3x3 neighborhood")?;
|
||||
}
|
||||
let mut gates = Vec::new();
|
||||
if let Some(m) = t.min_psnr {
|
||||
gates.push(format!("PSNR >= {m} dB"));
|
||||
}
|
||||
if let Some(m) = t.max_abs {
|
||||
gates.push(format!("max <= {m}"));
|
||||
}
|
||||
if let Some(m) = t.max_p99 {
|
||||
gates.push(format!("p99 <= {m}"));
|
||||
}
|
||||
if let Some(n) = self.allowed_bad_pixels {
|
||||
gates.push(format!("at most {n} such pixels"));
|
||||
}
|
||||
if !gates.is_empty() {
|
||||
write!(f, " (tolerance: {})", gates.join(", "))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Pixels of `a` with no pixel within `channel` in `b`'s 3×3 window around the same position.
|
||||
fn unmatched(a: Plane<'_>, b: Plane<'_>, channel: u8) -> usize {
|
||||
let (Ok(w), Ok(h)) = (usize::try_from(a.width), usize::try_from(a.height)) else { return 0 };
|
||||
let ch = a.channels;
|
||||
a.pixels
|
||||
.chunks_exact(ch)
|
||||
.enumerate()
|
||||
.filter(|&(i, p)| {
|
||||
let (x, y) = (i % w, i / w);
|
||||
let mut rows = y.saturating_sub(1)..=(y + 1).min(h.saturating_sub(1));
|
||||
!rows.any(|ny| {
|
||||
(x.saturating_sub(1)..=(x + 1).min(w.saturating_sub(1))).any(|nx| {
|
||||
let j = (ny * w + nx) * ch;
|
||||
b.pixels.get(j..j + ch).is_some_and(|q| max_delta(p, q) <= channel)
|
||||
})
|
||||
})
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
/// The largest bad pixel count `n` with `n / total <= fraction`, computed as `f64` division so a
|
||||
/// share that equals `fraction` is allowed.
|
||||
fn allowed_bad(fraction: f64, total: usize) -> usize {
|
||||
let n = total as f64;
|
||||
let mut allowed = ((fraction * n).floor() as usize).min(total);
|
||||
while allowed > 0 && allowed as f64 / n > fraction {
|
||||
allowed -= 1;
|
||||
}
|
||||
while allowed < total && (allowed + 1) as f64 / n <= fraction {
|
||||
allowed += 1;
|
||||
}
|
||||
allowed
|
||||
}
|
||||
|
||||
fn compare(a: Plane<'_>, b: Plane<'_>, tolerance: Tolerance) -> Result<Verdict, ImageError> {
|
||||
tolerance.validate()?;
|
||||
let stats = stats(a, b)?;
|
||||
let bad_pixels = if tolerance.neighborhood {
|
||||
unmatched(a, b, tolerance.channel).max(unmatched(b, a, tolerance.channel))
|
||||
} else {
|
||||
a.pixels.chunks_exact(a.channels).zip(b.pixels.chunks_exact(b.channels)).filter(|(p, q)| max_delta(p, q) > tolerance.channel).count()
|
||||
};
|
||||
let allowed_bad_pixels = tolerance.max_bad_fraction.map(|f| allowed_bad(f, stats.total_pixels));
|
||||
Ok(Verdict { stats, bad_pixels, allowed_bad_pixels, tolerance })
|
||||
}
|
||||
|
||||
/// Compares two RGBA images of the same size under `tolerance`.
|
||||
pub fn compare_rgba(a: Rgba8<'_>, b: Rgba8<'_>, tolerance: Tolerance) -> Result<Verdict, ImageError> {
|
||||
compare(a.plane(), b.plane(), tolerance)
|
||||
}
|
||||
|
||||
/// Compares two gray images of the same size under `tolerance`.
|
||||
pub fn compare_gray(a: Gray8<'_>, b: Gray8<'_>, tolerance: Tolerance) -> Result<Verdict, ImageError> {
|
||||
compare(a.plane(), b.plane(), tolerance)
|
||||
}
|
||||
|
||||
/// An opaque RGBA image of the same size showing `|a − b|` × 8 per color channel (at most 255),
|
||||
/// with each pixel's alpha difference raised into all three color channels.
|
||||
pub fn diff_image(a: Rgba8<'_>, b: Rgba8<'_>) -> Result<Vec<u8>, ImageError> {
|
||||
same_size(a.plane(), b.plane())?;
|
||||
let scaled = |x: u8, y: u8| u8::try_from((u16::from(x.abs_diff(y)) * 8).min(255)).unwrap_or(u8::MAX);
|
||||
Ok(a.pixels
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.zip(b.pixels.as_chunks::<4>().0)
|
||||
.flat_map(|(p, q)| {
|
||||
let alpha = scaled(p[3], q[3]);
|
||||
[scaled(p[0], q[0]).max(alpha), scaled(p[1], q[1]).max(alpha), scaled(p[2], q[2]).max(alpha), 255]
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Size limits for PNG reading and writing.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct PngLimits {
|
||||
/// Largest width in pixels.
|
||||
pub max_width: u32,
|
||||
/// Largest height in pixels.
|
||||
pub max_height: u32,
|
||||
/// Largest encoded PNG, read or written, in bytes.
|
||||
pub max_input_bytes: usize,
|
||||
/// Largest decoded output in bytes, after conversion to 8-bit gray or RGBA. The returned pixels
|
||||
/// never exceed it. The decoder also takes it as a budget for its own working memory, but
|
||||
/// applies that budget on a best-effort basis: it allocates small fixed buffers, such as one for
|
||||
/// chunk data, before it checks the budget.
|
||||
pub max_decoded_bytes: usize,
|
||||
}
|
||||
|
||||
impl PngLimits {
|
||||
/// 16,384 × 16,384 pixels, 64 MiB encoded and 256 MiB decoded.
|
||||
pub const DEFAULT: PngLimits = PngLimits { max_width: 16_384, max_height: 16_384, max_input_bytes: 64 << 20, max_decoded_bytes: 256 << 20 };
|
||||
}
|
||||
|
||||
impl Default for PngLimits {
|
||||
fn default() -> Self {
|
||||
Self::DEFAULT
|
||||
}
|
||||
}
|
||||
|
||||
/// A decoded PNG with 8-bit samples.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum DecodedPng {
|
||||
/// Color, gray with alpha, palette, or gray with a `tRNS` chunk, as straight RGBA.
|
||||
Rgba { width: u32, height: u32, pixels: Vec<u8> },
|
||||
/// Gray without transparency.
|
||||
Gray { width: u32, height: u32, pixels: Vec<u8> },
|
||||
}
|
||||
|
||||
impl DecodedPng {
|
||||
pub fn width(&self) -> u32 {
|
||||
match self {
|
||||
Self::Rgba { width, .. } | Self::Gray { width, .. } => *width,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn height(&self) -> u32 {
|
||||
match self {
|
||||
Self::Rgba { height, .. } | Self::Gray { height, .. } => *height,
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixels as RGBA; gray becomes opaque RGBA with equal color channels.
|
||||
pub fn into_rgba(self) -> Vec<u8> {
|
||||
match self {
|
||||
Self::Rgba { pixels, .. } => pixels,
|
||||
Self::Gray { pixels, .. } => pixels.iter().flat_map(|&g| [g, g, g, 255]).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn limit(what: &str, value: impl Into<u128>, max: impl Into<u128>) -> Result<(), ImageError> {
|
||||
let (value, max) = (value.into(), max.into());
|
||||
if value > max {
|
||||
return Err(ImageError::LimitExceeded(format!("{what} {value} exceeds the limit of {max}")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn decoding_error(e: png::DecodingError) -> ImageError {
|
||||
match e {
|
||||
png::DecodingError::LimitsExceeded => ImageError::LimitExceeded("the PNG decoder's working memory exceeds max_decoded_bytes".into()),
|
||||
e => ImageError::Decode(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn to_usize(n: u32) -> Result<usize, ImageError> {
|
||||
usize::try_from(n).map_err(|_| ImageError::LimitExceeded(format!("{n} does not fit in memory")))
|
||||
}
|
||||
|
||||
/// Decodes a PNG to 8-bit gray or RGBA.
|
||||
///
|
||||
/// Palette images and `tRNS` chunks are expanded, samples under 8 bits are scaled to 8 bits, and
|
||||
/// 16-bit samples keep their high byte. Interlaced images are returned whole. An animated PNG
|
||||
/// returns its default image. The chunks after the image, through `IEND`, are read, and the CRC of
|
||||
/// every chunk, ancillary chunks included, is checked. The input size, the header's width and
|
||||
/// height, and the decoded size, both as the decoder returns it and after conversion to gray or
|
||||
/// RGBA, are each checked against `limits` and against the largest buffer the platform can
|
||||
/// allocate before the buffer for them is allocated.
|
||||
pub fn decode_png(bytes: &[u8], limits: PngLimits) -> Result<DecodedPng, ImageError> {
|
||||
limit("PNG input bytes", bytes.len() as u64, limits.max_input_bytes as u64)?;
|
||||
let mut options = png::DecodeOptions::default();
|
||||
options.set_skip_ancillary_crc_failures(false);
|
||||
let mut decoder = png::Decoder::new_with_options(Cursor::new(bytes), options);
|
||||
decoder.set_limits(png::Limits { bytes: limits.max_decoded_bytes });
|
||||
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
|
||||
let (width, height) = {
|
||||
let info = decoder.read_header_info().map_err(decoding_error)?;
|
||||
(info.width, info.height)
|
||||
};
|
||||
limit("PNG width", width, limits.max_width)?;
|
||||
limit("PNG height", height, limits.max_height)?;
|
||||
let mut reader = decoder.read_info().map_err(decoding_error)?;
|
||||
let pixels = to_usize(width)?.checked_mul(to_usize(height)?).ok_or(ImageError::InvalidDimensions { width, height })?;
|
||||
let channels = match reader.output_color_type().0 {
|
||||
png::ColorType::Grayscale => 1,
|
||||
png::ColorType::GrayscaleAlpha => 2,
|
||||
png::ColorType::Rgb => 3,
|
||||
png::ColorType::Rgba => 4,
|
||||
png::ColorType::Indexed => return Err(ImageError::Decode("the palette was not expanded".into())),
|
||||
};
|
||||
let size = reader.output_buffer_size().ok_or_else(|| ImageError::LimitExceeded("the decoded PNG does not fit in memory".into()))?;
|
||||
limit("decoded PNG bytes", size as u64, limits.max_decoded_bytes as u64)?;
|
||||
limit("decoded PNG buffer bytes", size as u64, isize::MAX as u64)?;
|
||||
let output = if channels == 1 { pixels as u128 } else { pixels as u128 * 4 };
|
||||
limit("decoded PNG bytes", output, limits.max_decoded_bytes as u64)?;
|
||||
limit("decoded PNG buffer bytes", output, isize::MAX as u64)?;
|
||||
let mut buf = vec![0u8; size];
|
||||
let info = reader.next_frame(&mut buf).map_err(decoding_error)?;
|
||||
reader.finish().map_err(decoding_error)?;
|
||||
if info.bit_depth != png::BitDepth::Eight || (info.width, info.height) != (width, height) {
|
||||
return Err(ImageError::Decode(format!("unexpected {:?}-bit {}x{} output", info.bit_depth, info.width, info.height)));
|
||||
}
|
||||
if info.color_type != reader.output_color_type().0 {
|
||||
return Err(ImageError::Decode(format!("unexpected {:?} output", info.color_type)));
|
||||
}
|
||||
let samples = pixels.checked_mul(channels).filter(|&n| n <= buf.len());
|
||||
let Some(samples) = samples else {
|
||||
return Err(ImageError::Decode("the decoded frame is shorter than its size".into()));
|
||||
};
|
||||
if channels == 1 || channels == 4 {
|
||||
// The frame is already in its final form: keep the buffer and drop any row padding.
|
||||
buf.truncate(samples);
|
||||
return Ok(if channels == 1 { DecodedPng::Gray { width, height, pixels: buf } } else { DecodedPng::Rgba { width, height, pixels: buf } });
|
||||
}
|
||||
let data = buf.get(..samples).unwrap_or_default();
|
||||
Ok(match channels {
|
||||
2 => DecodedPng::Rgba { width, height, pixels: data.as_chunks::<2>().0.iter().flat_map(|p| [p[0], p[0], p[0], p[1]]).collect() },
|
||||
_ => DecodedPng::Rgba { width, height, pixels: data.as_chunks::<3>().0.iter().flat_map(|p| [p[0], p[1], p[2], 255]).collect() },
|
||||
})
|
||||
}
|
||||
|
||||
/// An output buffer that refuses to grow past `max` bytes.
|
||||
struct BoundedSink {
|
||||
out: Vec<u8>,
|
||||
max: usize,
|
||||
exceeded: bool,
|
||||
}
|
||||
|
||||
impl std::io::Write for BoundedSink {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
if self.out.len().saturating_add(buf.len()) > self.max {
|
||||
self.exceeded = true;
|
||||
return Err(std::io::Error::other("the encoded PNG exceeds max_input_bytes"));
|
||||
}
|
||||
self.out.extend_from_slice(buf);
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks the size of an image to be encoded: its sides, and its pixel bytes as the decoder
|
||||
/// would return them, so that a written file can be read back under the same limits.
|
||||
fn check_encode_limits(width: u32, height: u32, decoded_bytes: usize, limits: PngLimits) -> Result<(), ImageError> {
|
||||
limit("PNG width", width, limits.max_width)?;
|
||||
limit("PNG height", height, limits.max_height)?;
|
||||
limit("decoded PNG bytes", decoded_bytes as u64, limits.max_decoded_bytes as u64)
|
||||
}
|
||||
|
||||
fn write_stream(sink: &mut BoundedSink, width: u32, height: u32, color: png::ColorType, data: &[u8]) -> Result<(), png::EncodingError> {
|
||||
let mut encoder = png::Encoder::new(sink, width, height);
|
||||
encoder.set_color(color);
|
||||
encoder.set_depth(png::BitDepth::Eight);
|
||||
encoder.set_compression(png::Compression::High);
|
||||
let mut writer = encoder.write_header()?;
|
||||
// The stream writer hands each compressed block to the sink as it fills, so a sink that refuses
|
||||
// more bytes stops compression early.
|
||||
let mut stream = writer.stream_writer()?;
|
||||
std::io::Write::write_all(&mut stream, data)?;
|
||||
stream.finish()?;
|
||||
writer.finish()
|
||||
}
|
||||
|
||||
/// Encodes `data`, stopping as soon as the output would pass `limits.max_input_bytes`.
|
||||
fn encode(width: u32, height: u32, color: png::ColorType, data: &[u8], limits: PngLimits) -> Result<Vec<u8>, ImageError> {
|
||||
let mut sink = BoundedSink { out: Vec::new(), max: limits.max_input_bytes, exceeded: false };
|
||||
match write_stream(&mut sink, width, height, color, data) {
|
||||
Ok(()) => Ok(sink.out),
|
||||
Err(_) if sink.exceeded => Err(ImageError::LimitExceeded(format!("the encoded PNG exceeds the limit of {} bytes", limits.max_input_bytes))),
|
||||
Err(e) => Err(ImageError::Encode(e.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes an RGBA image as an 8-bit PNG: RGB when every pixel is opaque, otherwise RGBA. Returns
|
||||
/// an error when the image's sides, its pixel bytes or the encoded file are over `limits`.
|
||||
pub fn encode_png(image: Rgba8<'_>, limits: PngLimits) -> Result<Vec<u8>, ImageError> {
|
||||
check_encode_limits(image.width, image.height, image.pixels.len(), limits)?;
|
||||
let px = image.pixels.as_chunks::<4>().0;
|
||||
if px.iter().all(|p| p[3] == 255) {
|
||||
let rgb: Vec<u8> = px.iter().flat_map(|p| [p[0], p[1], p[2]]).collect();
|
||||
encode(image.width, image.height, png::ColorType::Rgb, &rgb, limits)
|
||||
} else {
|
||||
encode(image.width, image.height, png::ColorType::Rgba, image.pixels, limits)
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes a gray image as an 8-bit grayscale PNG. Returns an error when the image's sides, its
|
||||
/// pixel bytes or the encoded file are over `limits`.
|
||||
pub fn encode_gray_png(image: Gray8<'_>, limits: PngLimits) -> Result<Vec<u8>, ImageError> {
|
||||
check_encode_limits(image.width, image.height, image.pixels.len(), limits)?;
|
||||
encode(image.width, image.height, png::ColorType::Grayscale, image.pixels, limits)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn io_error(path: &Path) -> impl FnOnce(std::io::Error) -> ImageError + '_ {
|
||||
move |source| ImageError::Io { path: path.to_path_buf(), source }
|
||||
}
|
||||
|
||||
/// Reads and decodes the PNG at `path`. The file size is checked against
|
||||
/// `limits.max_input_bytes` before it is read.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn read_png(path: &Path, limits: PngLimits) -> Result<DecodedPng, ImageError> {
|
||||
let file = fs::File::open(path).map_err(io_error(path))?;
|
||||
let len = file.metadata().map_err(io_error(path))?.len();
|
||||
limit("PNG file bytes", len, limits.max_input_bytes as u64)?;
|
||||
let mut bytes = Vec::new();
|
||||
file.take((limits.max_input_bytes as u64).saturating_add(1)).read_to_end(&mut bytes).map_err(io_error(path))?;
|
||||
decode_png(&bytes, limits)
|
||||
}
|
||||
|
||||
/// Writes `bytes` to a new file next to `path`, then renames it over `path`, so a failed write
|
||||
/// leaves an existing file as it was.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_file(path: &Path, bytes: &[u8]) -> Result<(), ImageError> {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
|
||||
fs::create_dir_all(dir).map_err(io_error(dir))?;
|
||||
let file_name = path.file_name().ok_or_else(|| ImageError::InvalidName(format!("{} does not name a file", path.display())))?;
|
||||
loop {
|
||||
let mut temp_name = std::ffi::OsString::from(".");
|
||||
temp_name.push(file_name);
|
||||
temp_name.push(format!(".{}-{}.tmp", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
let temp = dir.join(temp_name);
|
||||
match create_new(&temp, bytes) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(source) => return Err(ImageError::Io { path: temp, source }),
|
||||
}
|
||||
return fs::rename(&temp, path).map_err(|source| {
|
||||
let _ = fs::remove_file(&temp);
|
||||
ImageError::Io { path: path.to_path_buf(), source }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes `image` with [`encode_png`] and writes it to `path`, creating the parent folders.
|
||||
/// Nothing is written when encoding fails.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn write_png(path: &Path, image: Rgba8<'_>, limits: PngLimits) -> Result<(), ImageError> {
|
||||
write_file(path, &encode_png(image, limits)?)
|
||||
}
|
||||
|
||||
/// Encodes `image` with [`encode_gray_png`] and writes it to `path`, creating the parent folders.
|
||||
/// Nothing is written when encoding fails.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn write_gray_png(path: &Path, image: Gray8<'_>, limits: PngLimits) -> Result<(), ImageError> {
|
||||
write_file(path, &encode_gray_png(image, limits)?)
|
||||
}
|
||||
|
||||
/// Settings for [`check_golden`].
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct GoldenOptions<'a> {
|
||||
/// The variable that blesses references when its value is exactly `1`.
|
||||
pub bless_var: &'a str,
|
||||
/// The folder that receives the actual and difference images of a failed check.
|
||||
pub failures_dir: &'a Path,
|
||||
/// The file stem of the failure images: 1 to 100 ASCII letters, digits, `-`, `_` or `.`,
|
||||
/// starting with a letter, digit or `_`.
|
||||
pub name: &'a str,
|
||||
/// Limits for the reference and the written images.
|
||||
pub limits: PngLimits,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl<'a> GoldenOptions<'a> {
|
||||
/// Options with [`DEFAULT_BLESS_VAR`] and [`PngLimits::DEFAULT`].
|
||||
pub fn new(failures_dir: &'a Path, name: &'a str) -> Self {
|
||||
Self { bless_var: DEFAULT_BLESS_VAR, failures_dir, name, limits: PngLimits::DEFAULT }
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a bless variable's value asks to write references: only the exact value `1` does.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn is_bless_value(value: Option<&OsStr>) -> bool {
|
||||
value == Some(OsStr::new("1"))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn validate_names(options: &GoldenOptions<'_>) -> Result<(), ImageError> {
|
||||
let var = options.bless_var;
|
||||
if var.is_empty() || var.contains(['=', '\0']) {
|
||||
return Err(ImageError::InvalidName(format!("bless variable name {var:?} must not be empty or contain '=' or NUL")));
|
||||
}
|
||||
let name = options.name;
|
||||
let allowed = name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'));
|
||||
let first = name.bytes().next().is_some_and(|b| b.is_ascii_alphanumeric() || b == b'_');
|
||||
let stem = name.split('.').next().unwrap_or_default().to_ascii_uppercase();
|
||||
let numbered =
|
||||
stem.len() == 4 && (stem.starts_with("COM") || stem.starts_with("LPT")) && stem.as_bytes().get(3).is_some_and(|b| (b'1'..=b'9').contains(b));
|
||||
let reserved = numbered || matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL");
|
||||
if name.len() > 100 || !allowed || !first || reserved || name.ends_with('.') {
|
||||
return Err(ImageError::InvalidName(format!(
|
||||
"failure image name {name:?} must be 1 to 100 ASCII letters, digits, '-', '_' or '.', start with a letter, digit or '_', and not be a device name"
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn create_new(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||
let mut file = fs::OpenOptions::new().write(true).create_new(true).open(path)?;
|
||||
let written = file.write_all(bytes);
|
||||
if written.is_err() {
|
||||
drop(file);
|
||||
let _ = fs::remove_file(path);
|
||||
}
|
||||
written
|
||||
}
|
||||
|
||||
/// Writes the actual and difference images under new names in the failure folder. An existing
|
||||
/// file is never replaced: `<name>.actual.png`, then `<name>-1.actual.png` and so on.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_failure(options: &GoldenOptions<'_>, actual: &[u8], diff: &[u8]) -> Result<(PathBuf, PathBuf), ImageError> {
|
||||
let dir = options.failures_dir;
|
||||
fs::create_dir_all(dir).map_err(io_error(dir))?;
|
||||
for n in 0..MAX_FAILURE_PAIRS {
|
||||
let stem = if n == 0 { options.name.to_string() } else { format!("{}-{n}", options.name) };
|
||||
let actual_path = dir.join(format!("{stem}.actual.png"));
|
||||
match create_new(&actual_path, actual) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(source) => return Err(ImageError::Io { path: actual_path, source }),
|
||||
}
|
||||
let diff_path = dir.join(format!("{stem}.diff.png"));
|
||||
match create_new(&diff_path, diff) {
|
||||
Ok(()) => return Ok((actual_path, diff_path)),
|
||||
Err(e) => {
|
||||
let _ = fs::remove_file(&actual_path);
|
||||
if e.kind() != std::io::ErrorKind::AlreadyExists {
|
||||
return Err(ImageError::Io { path: diff_path, source: e });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(ImageError::LimitExceeded(format!("{} already holds {MAX_FAILURE_PAIRS} failure images named {}", dir.display(), options.name)))
|
||||
}
|
||||
|
||||
/// Compares `actual` with the reference PNG at `reference`, or writes the reference when the
|
||||
/// variable `options.bless_var` is exactly `1`.
|
||||
///
|
||||
/// A missing reference returns [`ImageError::MissingReference`] unless blessing. When the
|
||||
/// comparison fails, the actual and difference images are written as new files inside
|
||||
/// `options.failures_dir`, and [`ImageError::GoldenMismatch`] names them. When they cannot be
|
||||
/// encoded or written, [`ImageError::GoldenMismatchUnsaved`] carries the verdict together with
|
||||
/// that error. A reference that would
|
||||
/// be larger than `options.limits.max_input_bytes` is not written.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn check_golden(reference: &Path, actual: Rgba8<'_>, tolerance: Tolerance, options: GoldenOptions<'_>) -> Result<Verdict, ImageError> {
|
||||
validate_names(&options)?;
|
||||
let bless = is_bless_value(std::env::var_os(options.bless_var).as_deref());
|
||||
check_golden_with(reference, actual, tolerance, options, bless)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn check_golden_with(
|
||||
reference: &Path,
|
||||
actual: Rgba8<'_>,
|
||||
tolerance: Tolerance,
|
||||
options: GoldenOptions<'_>,
|
||||
bless: bool,
|
||||
) -> Result<Verdict, ImageError> {
|
||||
validate_names(&options)?;
|
||||
tolerance.validate()?;
|
||||
if bless {
|
||||
write_png(reference, actual, options.limits)?;
|
||||
return compare_rgba(actual, actual, tolerance);
|
||||
}
|
||||
let decoded = match read_png(reference, options.limits) {
|
||||
Ok(decoded) => decoded,
|
||||
Err(ImageError::Io { source, .. }) if source.kind() == std::io::ErrorKind::NotFound => {
|
||||
return Err(ImageError::MissingReference { path: reference.to_path_buf(), bless_var: options.bless_var.to_string() });
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let (width, height) = (decoded.width(), decoded.height());
|
||||
if (width, height) != (actual.width, actual.height) {
|
||||
return Err(ImageError::SizeMismatch { a: (width, height), b: (actual.width, actual.height) });
|
||||
}
|
||||
limit("decoded PNG bytes", actual.pixels.len() as u64, options.limits.max_decoded_bytes as u64)?;
|
||||
let pixels = decoded.into_rgba();
|
||||
let expected = Rgba8::new(width, height, &pixels)?;
|
||||
let verdict = compare_rgba(expected, actual, tolerance)?;
|
||||
if verdict.passed() {
|
||||
return Ok(verdict);
|
||||
}
|
||||
let saved = diff_image(expected, actual).and_then(|diff| {
|
||||
let actual_png = encode_png(actual, options.limits)?;
|
||||
let diff_png = encode_png(Rgba8::new(width, height, &diff)?, options.limits)?;
|
||||
write_failure(&options, &actual_png, &diff_png)
|
||||
});
|
||||
let reference = reference.to_path_buf();
|
||||
Err(match saved {
|
||||
Ok((actual, diff)) => ImageError::GoldenMismatch(Box::new(GoldenMismatch { reference, verdict, actual, diff })),
|
||||
Err(error) => ImageError::GoldenMismatchUnsaved(Box::new(UnsavedMismatch { reference, verdict, error })),
|
||||
})
|
||||
}
|
||||
|
||||
/// Fails the test that called [`assert_similar!`](crate::assert_similar); the panic names the
|
||||
/// caller's location.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[doc(hidden)]
|
||||
#[track_caller]
|
||||
#[allow(clippy::panic)]
|
||||
pub fn fail_similar(error: ImageError) -> ! {
|
||||
panic!("{error}")
|
||||
}
|
||||
|
||||
/// Runs [`check_golden`](crate::image::check_golden) and fails the calling test when it returns
|
||||
/// an error. Evaluates to the [`Verdict`](crate::image::Verdict).
|
||||
///
|
||||
/// ```ignore
|
||||
/// let options = craft_testkit::image::GoldenOptions::new(&failures, "title_card");
|
||||
/// craft_testkit::assert_similar!(&reference, actual, tolerance, options);
|
||||
/// ```
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[macro_export]
|
||||
macro_rules! assert_similar {
|
||||
($reference:expr, $actual:expr, $tolerance:expr, $options:expr $(,)?) => {
|
||||
match $crate::image::check_golden($reference, $actual, $tolerance, $options) {
|
||||
::core::result::Result::Ok(verdict) => verdict,
|
||||
::core::result::Result::Err(error) => $crate::image::fail_similar(error),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod tests;
|
||||
@@ -0,0 +1,927 @@
|
||||
use std::collections::HashSet;
|
||||
use std::ffi::OsStr;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::{
|
||||
BoundedSink, DecodedPng, GoldenOptions, Gray8, ImageError, PngLimits, Rgba8, Tolerance, check_golden_with, compare_gray, compare_rgba,
|
||||
decode_png, diff_gray, diff_image, diff_rgba, encode_gray_png, encode_png, is_bless_value, psnr, read_png, write_gray_png, write_png,
|
||||
write_stream,
|
||||
};
|
||||
|
||||
/// The bless variable of these tests. Comparison cases call `check_golden_with` with blessing off,
|
||||
/// and the `assert_similar!` cases run in a child process with the variable removed, so a value
|
||||
/// inherited from the environment cannot turn a comparison into a bless.
|
||||
const NO_BLESS: &str = "CRAFT_TESTKIT_SELF_TEST_BLESS";
|
||||
|
||||
/// Set in the child processes that `run_child` starts.
|
||||
const CHILD_MARKER: &str = "CRAFT_TESTKIT_IMAGE_CHILD";
|
||||
|
||||
/// A golden check that compares and never blesses.
|
||||
fn compare_golden(reference: &Path, actual: Rgba8<'_>, tolerance: Tolerance, options: GoldenOptions<'_>) -> Result<super::Verdict, ImageError> {
|
||||
check_golden_with(reference, actual, tolerance, options, false)
|
||||
}
|
||||
|
||||
fn ramp(w: u32, h: u32, alpha: u8) -> Vec<u8> {
|
||||
(0..w * h).flat_map(|i| [(i % w * 255 / w) as u8, (i / w * 255 / h) as u8, 77, alpha]).collect()
|
||||
}
|
||||
|
||||
fn rgba(w: u32, h: u32, px: &[u8]) -> Rgba8<'_> {
|
||||
Rgba8::new(w, h, px).expect("sized")
|
||||
}
|
||||
|
||||
fn gray(w: usize, h: usize, fill: u8) -> Vec<u8> {
|
||||
vec![fill; w * h]
|
||||
}
|
||||
|
||||
fn g(w: usize, h: usize, px: &[u8]) -> Gray8<'_> {
|
||||
Gray8::new(w as u32, h as u32, px).expect("sized")
|
||||
}
|
||||
|
||||
fn neighborhood(channel: u8) -> Tolerance {
|
||||
Tolerance { max_abs: None, channel, neighborhood: true, ..Tolerance::EXACT }
|
||||
}
|
||||
|
||||
/// FilmCraft's render tolerance.
|
||||
fn render() -> Tolerance {
|
||||
Tolerance { min_psnr: Some(45.0), max_abs: Some(12), max_p99: Some(2), ..Tolerance::EXACT }
|
||||
}
|
||||
|
||||
/// AniCraft's default tolerance.
|
||||
fn per_pixel() -> Tolerance {
|
||||
Tolerance { max_abs: None, channel: 3, max_bad_fraction: Some(0.002), ..Tolerance::EXACT }
|
||||
}
|
||||
|
||||
// PNG files written by hand from the W3C PNG specification, so the reader is checked against
|
||||
// the format rather than against the encoder it ships with.
|
||||
|
||||
fn crc32(bytes: &[u8]) -> u32 {
|
||||
let mut c = 0xFFFF_FFFFu32;
|
||||
for &b in bytes {
|
||||
c ^= u32::from(b);
|
||||
for _ in 0..8 {
|
||||
c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };
|
||||
}
|
||||
}
|
||||
!c
|
||||
}
|
||||
|
||||
fn adler32(bytes: &[u8]) -> u32 {
|
||||
let (mut a, mut b) = (1u32, 0u32);
|
||||
for &x in bytes {
|
||||
a = (a + u32::from(x)) % 65521;
|
||||
b = (b + a) % 65521;
|
||||
}
|
||||
(b << 16) | a
|
||||
}
|
||||
|
||||
/// A zlib stream of stored (uncompressed) deflate blocks.
|
||||
fn zlib_stored(data: &[u8]) -> Vec<u8> {
|
||||
let mut out = vec![0x78, 0x01];
|
||||
let blocks: Vec<&[u8]> = if data.is_empty() { vec![&[]] } else { data.chunks(65_535).collect() };
|
||||
for (i, block) in blocks.iter().enumerate() {
|
||||
out.push(u8::from(i + 1 == blocks.len()));
|
||||
let len = block.len() as u16;
|
||||
out.extend(len.to_le_bytes());
|
||||
out.extend((!len).to_le_bytes());
|
||||
out.extend_from_slice(block);
|
||||
}
|
||||
out.extend(adler32(data).to_be_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
fn chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
|
||||
out.extend((data.len() as u32).to_be_bytes());
|
||||
let mut body = kind.to_vec();
|
||||
body.extend_from_slice(data);
|
||||
out.extend_from_slice(&body);
|
||||
out.extend(crc32(&body).to_be_bytes());
|
||||
}
|
||||
|
||||
const SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
|
||||
|
||||
/// A PNG with the given header, extra chunks before the image data, and filtered scanlines.
|
||||
fn png_file(width: u32, height: u32, depth: u8, color: u8, interlace: u8, extra: &[(&[u8; 4], &[u8])], scanlines: &[u8]) -> Vec<u8> {
|
||||
let mut out = SIGNATURE.to_vec();
|
||||
let mut ihdr = Vec::new();
|
||||
ihdr.extend(width.to_be_bytes());
|
||||
ihdr.extend(height.to_be_bytes());
|
||||
ihdr.extend([depth, color, 0, 0, interlace]);
|
||||
chunk(&mut out, b"IHDR", &ihdr);
|
||||
for (kind, data) in extra {
|
||||
chunk(&mut out, kind, data);
|
||||
}
|
||||
chunk(&mut out, b"IDAT", &zlib_stored(scanlines));
|
||||
chunk(&mut out, b"IEND", &[]);
|
||||
out
|
||||
}
|
||||
|
||||
/// Adam7 pass origins and steps: (x0, y0, dx, dy).
|
||||
const ADAM7: [(usize, usize, usize, usize); 7] = [(0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)];
|
||||
|
||||
/// Scanlines of an 8-bit gray image in Adam7 order, each with filter type 0.
|
||||
fn adam7_gray(w: usize, h: usize, px: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
for (x0, y0, dx, dy) in ADAM7 {
|
||||
let cols: Vec<usize> = (x0..w).step_by(dx).collect();
|
||||
if cols.is_empty() {
|
||||
continue;
|
||||
}
|
||||
for y in (y0..h).step_by(dy) {
|
||||
out.push(0);
|
||||
out.extend(cols.iter().map(|&x| px[y * w + x]));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn decode(bytes: &[u8]) -> DecodedPng {
|
||||
decode_png(bytes, PngLimits::DEFAULT).expect("decodes")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixture_crc_matches_the_specification() {
|
||||
// Every PNG ends with this IEND chunk, whose CRC the specification's sample code yields.
|
||||
assert_eq!(crc32(b"IEND"), 0xAE42_6082);
|
||||
}
|
||||
|
||||
// Views.
|
||||
|
||||
#[test]
|
||||
fn invalid_view_length_is_error() {
|
||||
assert!(matches!(Rgba8::new(2, 2, &[0; 15]), Err(ImageError::InvalidBufferLength { expected: 16, actual: 15 })));
|
||||
assert!(matches!(Rgba8::new(2, 2, &[0; 17]), Err(ImageError::InvalidBufferLength { expected: 16, actual: 17 })));
|
||||
assert!(Rgba8::new(2, 2, &[0; 16]).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rgba_length_overflow_is_error() {
|
||||
for result in [Rgba8::new(u32::MAX, u32::MAX, &[]), Rgba8::new(u32::MAX, u32::MAX, &[0; 4])] {
|
||||
assert!(matches!(result, Err(ImageError::InvalidDimensions { .. } | ImageError::InvalidBufferLength { .. })), "{result:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_that_is_not_the_stated_size_is_rejected() {
|
||||
let buf = gray(4, 4, 0);
|
||||
assert!(Gray8::new(4, 4, &buf).is_ok());
|
||||
assert!(Gray8::new(5, 4, &buf).is_err());
|
||||
assert!(Gray8::new(4, 5, &buf).is_err());
|
||||
assert!(Gray8::new(u32::MAX, u32::MAX, &buf).is_err(), "the area must not overflow into a match");
|
||||
// A zero-sized image has no samples for p99 or PSNR, and PNG does not allow one: it is an error.
|
||||
assert!(matches!(Gray8::new(0, 0, &[]), Err(ImageError::InvalidDimensions { width: 0, height: 0 })));
|
||||
}
|
||||
|
||||
/// A zero-width image of enormous height is rejected at once, without walking its rows.
|
||||
#[test]
|
||||
fn an_image_without_pixels_compares_at_once() {
|
||||
assert!(matches!(Gray8::new(0, u32::MAX, &[]), Err(ImageError::InvalidDimensions { .. })));
|
||||
assert!(matches!(Rgba8::new(u32::MAX, 0, &[]), Err(ImageError::InvalidDimensions { .. })));
|
||||
}
|
||||
|
||||
// Statistics.
|
||||
|
||||
#[test]
|
||||
fn diff_metrics() {
|
||||
let a = ramp(10, 10, 255);
|
||||
assert_eq!(diff_rgba(rgba(10, 10, &a), rgba(10, 10, &a)).unwrap().psnr, f64::INFINITY);
|
||||
let mut b = a.clone();
|
||||
b[0] = b[0].wrapping_add(10); // one channel of one pixel
|
||||
let d = diff_rgba(rgba(10, 10, &a), rgba(10, 10, &b)).unwrap();
|
||||
assert_eq!((d.max_abs, d.p99, d.differing_pixels, d.total_pixels), (10, 0, 1, 100));
|
||||
assert!((d.mean_abs - 10.0 / 400.0).abs() < 1e-12);
|
||||
let mse: f64 = 100.0 / 400.0;
|
||||
assert!((d.psnr - 10.0 * (255.0f64 * 255.0 / mse).log10()).abs() < 1e-9);
|
||||
assert!(compare_rgba(rgba(10, 10, &a), rgba(10, 10, &b), render()).unwrap().passed());
|
||||
assert!(!compare_rgba(rgba(10, 10, &a), rgba(10, 10, &b), Tolerance::EXACT).unwrap().passed());
|
||||
let taller = ramp(10, 11, 255);
|
||||
assert!(diff_rgba(rgba(10, 10, &a), rgba(10, 11, &taller)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn p99_nearest_rank_small_samples() {
|
||||
// One pixel: rank ceil(0.99) = 1.
|
||||
let (a, b) = ([0u8], [7u8]);
|
||||
assert_eq!(diff_gray(g(1, 1, &a), g(1, 1, &b)).unwrap().p99, 7);
|
||||
// 100 pixels: rank 99. One changed pixel sits at position 100, two reach position 99.
|
||||
let base = gray(100, 1, 0);
|
||||
let mut one = base.clone();
|
||||
one[0] = 10;
|
||||
assert_eq!(diff_gray(g(100, 1, &base), g(100, 1, &one)).unwrap().p99, 0);
|
||||
let mut two = one.clone();
|
||||
two[1] = 10;
|
||||
assert_eq!(diff_gray(g(100, 1, &base), g(100, 1, &two)).unwrap().p99, 10);
|
||||
// 101 pixels: rank ceil(99.99) = 100.
|
||||
let base = gray(101, 1, 0);
|
||||
let mut one = base.clone();
|
||||
one[0] = 10;
|
||||
assert_eq!(diff_gray(g(101, 1, &base), g(101, 1, &one)).unwrap().p99, 0);
|
||||
let mut two = one.clone();
|
||||
two[1] = 10;
|
||||
assert_eq!(diff_gray(g(101, 1, &base), g(101, 1, &two)).unwrap().p99, 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psnr_published_two_sample_value() {
|
||||
// MSE = 255² / 2, so PSNR = 10 log10(2).
|
||||
let value = psnr(&[0u8, 0], &[255u8, 0], 255.0).unwrap();
|
||||
assert!((value - 3.010_299_956_6).abs() < 1e-9, "{value}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psnr_identical_is_infinite() {
|
||||
assert_eq!(psnr(&[1u8, 2, 3], &[1u8, 2, 3], 255.0).unwrap(), f64::INFINITY);
|
||||
assert_eq!(psnr(&[1000u16], &[1000u16], 1023.0).unwrap(), f64::INFINITY);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psnr_rejects_unequal_empty_and_bad_peak() {
|
||||
assert!(matches!(psnr(&[0u8, 1], &[0u8], 255.0), Err(ImageError::PlaneLengthMismatch { a: 2, b: 1 })));
|
||||
assert!(matches!(psnr::<u8>(&[], &[], 255.0), Err(ImageError::EmptyPlane)));
|
||||
for peak in [0.0, -1.0, f64::NAN, f64::INFINITY] {
|
||||
assert!(matches!(psnr(&[0u8], &[1u8], peak), Err(ImageError::InvalidPeak(_))), "{peak}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psnr_u16_peak() {
|
||||
let value = psnr(&[0u16, 0], &[1023u16, 0], 1023.0).unwrap();
|
||||
assert!((value - 10.0 * 2f64.log10()).abs() < 1e-9, "{value}");
|
||||
assert!(psnr(&[0u16], &[65535u16], 65535.0).unwrap().abs() < 1e-12);
|
||||
// peak² does not fit in f64 here, but the result does: 20 × 200 dB.
|
||||
let value = psnr(&[0u8], &[1u8], 1e200).unwrap();
|
||||
assert!((value - 4000.0).abs() < 1e-9, "{value}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diff_image_rejects_size_mismatch() {
|
||||
let a = [10u8, 20, 30, 255, 0, 0, 0, 255];
|
||||
let b = [11u8, 20, 30, 250, 0, 100, 0, 255];
|
||||
let d = diff_image(rgba(2, 1, &a), rgba(2, 1, &b)).unwrap();
|
||||
// Red differs by 1 (8 after scaling), alpha by 5 (40), which shows in every color channel.
|
||||
assert_eq!(d, vec![40, 40, 40, 255, 0, 255, 0, 255]);
|
||||
assert!(matches!(diff_image(rgba(2, 1, &a), rgba(1, 2, &b)), Err(ImageError::SizeMismatch { .. })));
|
||||
}
|
||||
|
||||
// Tolerances and the neighborhood.
|
||||
|
||||
#[test]
|
||||
fn identical_images_do_not_differ() {
|
||||
let buf = gray(16, 16, 128);
|
||||
let v = compare_gray(g(16, 16, &buf), g(16, 16, &buf), neighborhood(0)).expect("same size");
|
||||
assert_eq!(v.bad_pixels, 0);
|
||||
assert_eq!(v.stats.max_abs, 0);
|
||||
assert_eq!(v.stats.differing_pixels, 0);
|
||||
assert_eq!(v.stats.total_pixels, 256);
|
||||
}
|
||||
|
||||
/// A one-pixel shift of a stem is forgiven, because every moved pixel finds its match next door.
|
||||
#[test]
|
||||
fn a_one_pixel_shift_is_forgiven() {
|
||||
let (w, h) = (9usize, 9usize);
|
||||
let mut left = gray(w, h, 255);
|
||||
let mut right = gray(w, h, 255);
|
||||
for y in 0..h {
|
||||
left[y * w + 4] = 0;
|
||||
right[y * w + 5] = 0;
|
||||
}
|
||||
let v = compare_gray(g(w, h, &left), g(w, h, &right), neighborhood(8)).expect("same size");
|
||||
assert_eq!(v.bad_pixels, 0, "a one-pixel shift must not count as a difference");
|
||||
// The aligned difference still shows the shift.
|
||||
assert_eq!(v.stats.max_abs, 255);
|
||||
}
|
||||
|
||||
/// Content that is absent is not forgiven, however tolerant the neighborhood is.
|
||||
#[test]
|
||||
fn missing_content_is_not_forgiven() {
|
||||
let (w, h) = (16usize, 16usize);
|
||||
let blank = gray(w, h, 255);
|
||||
let mut drawn = blank.clone();
|
||||
for y in 5..11 {
|
||||
for x in 5..11 {
|
||||
drawn[y * w + x] = 0;
|
||||
}
|
||||
}
|
||||
let v = compare_gray(g(w, h, &blank), g(w, h, &drawn), neighborhood(8)).expect("same size");
|
||||
// Blank against drawn forgives the block's border and counts its 4x4 interior; drawn
|
||||
// against blank counts all 36 black pixels. The larger count is reported.
|
||||
assert_eq!(v.bad_pixels, 36, "every pixel of a missing block must be counted");
|
||||
}
|
||||
|
||||
/// A shift of more than one pixel is beyond the 3x3 window and is reported.
|
||||
#[test]
|
||||
fn a_shift_wider_than_the_window_is_reported() {
|
||||
let (w, h) = (16usize, 16usize);
|
||||
let mut left = gray(w, h, 255);
|
||||
let mut right = gray(w, h, 255);
|
||||
for y in 0..h {
|
||||
for x in 4..8 {
|
||||
left[y * w + x] = 0;
|
||||
}
|
||||
for x in 11..15 {
|
||||
right[y * w + x] = 0;
|
||||
}
|
||||
}
|
||||
assert!(compare_gray(g(w, h, &left), g(w, h, &right), neighborhood(8)).expect("same size").bad_pixels > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tolerance_absorbs_small_differences_only() {
|
||||
let flat = gray(8, 8, 100);
|
||||
let near = gray(8, 8, 105);
|
||||
let far = gray(8, 8, 200);
|
||||
let a = g(8, 8, &flat);
|
||||
assert_eq!(compare_gray(a, g(8, 8, &near), neighborhood(8)).expect("ok").bad_pixels, 0);
|
||||
assert_eq!(compare_gray(a, g(8, 8, &far), neighborhood(8)).expect("ok").bad_pixels, 64);
|
||||
// The tolerance is inclusive at the boundary.
|
||||
assert_eq!(compare_gray(a, g(8, 8, &near), neighborhood(5)).expect("ok").bad_pixels, 0);
|
||||
assert_eq!(compare_gray(a, g(8, 8, &near), neighborhood(4)).expect("ok").bad_pixels, 64);
|
||||
}
|
||||
|
||||
/// Comparison is symmetric: neither argument order flatters one image.
|
||||
#[test]
|
||||
fn comparison_is_symmetric() {
|
||||
let (w, h) = (12usize, 12usize);
|
||||
let mut thin = gray(w, h, 255);
|
||||
let mut thick = gray(w, h, 255);
|
||||
for y in 0..h {
|
||||
thin[y * w + 6] = 0;
|
||||
for x in 4..9 {
|
||||
thick[y * w + x] = 0;
|
||||
}
|
||||
}
|
||||
let forward = compare_gray(g(w, h, &thin), g(w, h, &thick), neighborhood(8)).expect("ok");
|
||||
let backward = compare_gray(g(w, h, &thick), g(w, h, &thin), neighborhood(8)).expect("ok");
|
||||
assert_eq!(forward, backward, "argument order must not change the verdict");
|
||||
assert!(forward.bad_pixels > 0, "a 1px stem against a 5px bar is a real difference");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neighborhood_clips_at_edges() {
|
||||
// Only the edge pixels differ, and their windows stop at the image border.
|
||||
let (a, b) = ([0u8, 255, 255], [255u8, 255, 0]);
|
||||
assert_eq!(compare_gray(g(3, 1, &a), g(3, 1, &b), neighborhood(0)).unwrap().bad_pixels, 1);
|
||||
let (a, b) = ([0u8], [1u8]);
|
||||
assert_eq!(compare_gray(g(1, 1, &a), g(1, 1, &b), neighborhood(0)).unwrap().bad_pixels, 1);
|
||||
assert_eq!(compare_gray(g(1, 1, &a), g(1, 1, &b), neighborhood(1)).unwrap().bad_pixels, 0);
|
||||
// RGBA pixels match only when every channel is within the tolerance.
|
||||
let a = [0u8, 0, 0, 255, 9, 9, 9, 255];
|
||||
let b = [0u8, 0, 0, 200, 9, 9, 9, 200];
|
||||
assert_eq!(compare_rgba(rgba(2, 1, &a), rgba(2, 1, &b), neighborhood(54)).unwrap().bad_pixels, 2);
|
||||
assert_eq!(compare_rgba(rgba(2, 1, &a), rgba(2, 1, &b), neighborhood(55)).unwrap().bad_pixels, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_pixel_fraction_is_inclusive() {
|
||||
let base = gray(1000, 1, 0);
|
||||
let mut off = base.clone();
|
||||
off[0] = 9;
|
||||
off[1] = 9;
|
||||
let t = Tolerance { max_abs: None, channel: 3, max_bad_fraction: Some(0.002), ..Tolerance::EXACT };
|
||||
let v = compare_gray(g(1000, 1, &base), g(1000, 1, &off), t).unwrap();
|
||||
assert_eq!((v.bad_pixels, v.allowed_bad_pixels), (2, Some(2)));
|
||||
assert!(v.passed());
|
||||
off[2] = 4;
|
||||
let v = compare_gray(g(1000, 1, &base), g(1000, 1, &off), t).unwrap();
|
||||
assert_eq!(v.bad_pixels, 3);
|
||||
assert!(!v.passed());
|
||||
// 0.29 × 100 is 28.999999999999996 in f64; 29 of 100 pixels is still 29%.
|
||||
let base = gray(100, 1, 0);
|
||||
let mut off = base.clone();
|
||||
off[..29].fill(9);
|
||||
let t = Tolerance { max_bad_fraction: Some(0.29), ..t };
|
||||
let v = compare_gray(g(100, 1, &base), g(100, 1, &off), t).unwrap();
|
||||
assert_eq!((v.bad_pixels, v.allowed_bad_pixels), (29, Some(29)));
|
||||
assert!(v.passed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_tolerance_is_error() {
|
||||
let a = [0u8];
|
||||
for t in [
|
||||
Tolerance { max_bad_fraction: Some(1.5), ..Tolerance::EXACT },
|
||||
Tolerance { max_bad_fraction: Some(-0.1), ..Tolerance::EXACT },
|
||||
Tolerance { max_bad_fraction: Some(f64::NAN), ..Tolerance::EXACT },
|
||||
Tolerance { min_psnr: Some(f64::NAN), ..Tolerance::EXACT },
|
||||
] {
|
||||
assert!(matches!(compare_gray(g(1, 1, &a), g(1, 1, &a), t), Err(ImageError::InvalidTolerance(_))), "{t:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_sizes_are_an_error_not_a_score() {
|
||||
let small = gray(4, 4, 0);
|
||||
let large = gray(8, 8, 0);
|
||||
let err = compare_gray(g(4, 4, &small), g(8, 8, &large), Tolerance::EXACT).expect_err("mismatch");
|
||||
assert!(matches!(err, ImageError::SizeMismatch { a: (4, 4), b: (8, 8) }), "{err:?}");
|
||||
assert!(err.to_string().contains("4x4"), "{err}");
|
||||
}
|
||||
|
||||
// PNG.
|
||||
|
||||
#[test]
|
||||
fn png_round_trip_rgb_and_rgba() {
|
||||
for alpha in [255, 128] {
|
||||
let px = ramp(37, 21, alpha);
|
||||
let png = encode_png(rgba(37, 21, &px), PngLimits::DEFAULT).unwrap();
|
||||
assert_eq!(decode(&png), DecodedPng::Rgba { width: 37, height: 21, pixels: px });
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gray_png_round_trip() {
|
||||
let px: Vec<u8> = (0..60).map(|i| (i * 4) as u8).collect();
|
||||
let png = encode_gray_png(g(10, 6, &px), PngLimits::DEFAULT).unwrap();
|
||||
assert_eq!(decode(&png), DecodedPng::Gray { width: 10, height: 6, pixels: px });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoded_header_matches_the_png_specification() {
|
||||
let opaque = ramp(3, 2, 255);
|
||||
let clear = ramp(3, 2, 7);
|
||||
let shades = [1u8, 2, 3, 4, 5, 6];
|
||||
for (png, color_type) in [
|
||||
(encode_png(rgba(3, 2, &opaque), PngLimits::DEFAULT).unwrap(), 2u8),
|
||||
(encode_png(rgba(3, 2, &clear), PngLimits::DEFAULT).unwrap(), 6),
|
||||
(encode_gray_png(g(3, 2, &shades), PngLimits::DEFAULT).unwrap(), 0),
|
||||
] {
|
||||
assert_eq!(png[..8], SIGNATURE);
|
||||
assert_eq!(png[8..16], [0, 0, 0, 13, b'I', b'H', b'D', b'R']);
|
||||
// Width, height, bit depth, color type, compression, filter and interlace methods.
|
||||
assert_eq!(png[16..29], [0, 0, 0, 3, 0, 0, 0, 2, 8, color_type, 0, 0, 0]);
|
||||
assert_eq!(png[29..33], crc32(&png[12..29]).to_be_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_normalizes_supported_color_types() {
|
||||
// Gray, 1 bit: 1 scales to 255.
|
||||
let png = png_file(8, 1, 1, 0, 0, &[], &[0, 0b1010_0000]);
|
||||
assert_eq!(decode(&png), DecodedPng::Gray { width: 8, height: 1, pixels: vec![255, 0, 255, 0, 0, 0, 0, 0] });
|
||||
// Gray, 2 bits: steps of 85.
|
||||
let png = png_file(4, 1, 2, 0, 0, &[], &[0, 0b00_01_10_11]);
|
||||
assert_eq!(decode(&png), DecodedPng::Gray { width: 4, height: 1, pixels: vec![0, 85, 170, 255] });
|
||||
// Gray with alpha.
|
||||
let png = png_file(2, 1, 8, 4, 0, &[], &[0, 10, 20, 30, 40]);
|
||||
assert_eq!(decode(&png), DecodedPng::Rgba { width: 2, height: 1, pixels: vec![10, 10, 10, 20, 30, 30, 30, 40] });
|
||||
// RGB.
|
||||
let png = png_file(1, 1, 8, 2, 0, &[], &[0, 1, 2, 3]);
|
||||
assert_eq!(decode(&png), DecodedPng::Rgba { width: 1, height: 1, pixels: vec![1, 2, 3, 255] });
|
||||
// RGBA.
|
||||
let png = png_file(1, 1, 8, 6, 0, &[], &[0, 1, 2, 3, 4]);
|
||||
assert_eq!(decode(&png), DecodedPng::Rgba { width: 1, height: 1, pixels: vec![1, 2, 3, 4] });
|
||||
// Palette with a tRNS entry for its first color.
|
||||
let png = png_file(2, 1, 8, 3, 0, &[(b"PLTE", &[255, 0, 0, 0, 0, 255]), (b"tRNS", &[128])], &[0, 0, 1]);
|
||||
assert_eq!(decode(&png), DecodedPng::Rgba { width: 2, height: 1, pixels: vec![255, 0, 0, 128, 0, 0, 255, 255] });
|
||||
// Gray with a tRNS value of 7.
|
||||
let png = png_file(2, 1, 8, 0, 0, &[(b"tRNS", &[0, 7])], &[0, 7, 9]);
|
||||
assert_eq!(decode(&png), DecodedPng::Rgba { width: 2, height: 1, pixels: vec![7, 7, 7, 0, 9, 9, 9, 255] });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_16bit_strips_to_8bit() {
|
||||
let png = png_file(1, 2, 16, 0, 0, &[], &[0, 0x12, 0x34, 0, 0xAB, 0xCD]);
|
||||
assert_eq!(decode(&png), DecodedPng::Gray { width: 1, height: 2, pixels: vec![0x12, 0xAB] });
|
||||
let png = png_file(1, 1, 16, 6, 0, &[], &[0, 1, 2, 3, 4, 5, 6, 0xFF, 0]);
|
||||
assert_eq!(decode(&png), DecodedPng::Rgba { width: 1, height: 1, pixels: vec![1, 3, 5, 255] });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interlaced_png_decodes_complete_frame() {
|
||||
let (w, h) = (5usize, 5usize);
|
||||
let px: Vec<u8> = (0..w * h).map(|i| (i * 10) as u8).collect();
|
||||
let png = png_file(5, 5, 8, 0, 1, &[], &adam7_gray(w, h, &px));
|
||||
assert_eq!(decode(&png), DecodedPng::Gray { width: 5, height: 5, pixels: px });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_signature_and_truncated_png_are_errors() {
|
||||
let px = ramp(4, 4, 255);
|
||||
let png = encode_png(rgba(4, 4, &px), PngLimits::DEFAULT).unwrap();
|
||||
let mut wrong = png.clone();
|
||||
wrong[1] = b'Q';
|
||||
assert!(matches!(decode_png(&wrong, PngLimits::DEFAULT), Err(ImageError::Decode(_))));
|
||||
assert!(matches!(decode_png(&[], PngLimits::DEFAULT), Err(ImageError::Decode(_))));
|
||||
// Cut inside the header, and just after the zlib header of the image data.
|
||||
let idat = png.windows(4).position(|w| w == b"IDAT").expect("an IDAT chunk");
|
||||
for len in [20, idat + 6] {
|
||||
assert!(matches!(decode_png(&png[..len], PngLimits::DEFAULT), Err(ImageError::Decode(_))), "{len}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_without_a_valid_end_is_an_error() {
|
||||
let png = png_file(2, 1, 8, 0, 0, &[], &[0, 1, 2]);
|
||||
assert!(decode_png(&png, PngLimits::DEFAULT).is_ok());
|
||||
// No IEND chunk.
|
||||
let cut = &png[..png.len() - 12];
|
||||
assert!(matches!(decode_png(cut, PngLimits::DEFAULT), Err(ImageError::Decode(_))));
|
||||
// An IEND chunk with a wrong CRC.
|
||||
let mut bad_crc = png.clone();
|
||||
if let Some(last) = bad_crc.last_mut() {
|
||||
*last ^= 0xFF;
|
||||
}
|
||||
assert!(matches!(decode_png(&bad_crc, PngLimits::DEFAULT), Err(ImageError::Decode(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_ancillary_crc_is_an_error() {
|
||||
let text: &[u8] = b"Comment\0x";
|
||||
// A tEXt chunk between the image data and IEND.
|
||||
let plain = png_file(2, 1, 8, 0, 0, &[], &[0, 1, 2]);
|
||||
let (body, iend) = plain.split_at(plain.len() - 12);
|
||||
let mut after = body.to_vec();
|
||||
chunk(&mut after, b"tEXt", text);
|
||||
after.extend_from_slice(iend);
|
||||
assert!(decode_png(&after, PngLimits::DEFAULT).is_ok(), "a valid tEXt chunk is accepted");
|
||||
let crc = after.len() - iend.len() - 1;
|
||||
after[crc] ^= 0xFF;
|
||||
assert!(matches!(decode_png(&after, PngLimits::DEFAULT), Err(ImageError::Decode(_))), "after the image");
|
||||
// A tEXt chunk between IHDR and the image data: signature, IHDR, then length, type and data.
|
||||
let mut before = png_file(2, 1, 8, 0, 0, &[(b"tEXt", text)], &[0, 1, 2]);
|
||||
assert!(decode_png(&before, PngLimits::DEFAULT).is_ok());
|
||||
let crc = 8 + 25 + 8 + text.len() + 3;
|
||||
before[crc] ^= 0xFF;
|
||||
assert!(matches!(decode_png(&before, PngLimits::DEFAULT), Err(ImageError::Decode(_))), "before the image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_limits_reject_header_before_allocation() {
|
||||
// The image data is a few bytes, so only the header can trigger the error.
|
||||
let wide = png_file(1_000_000, 1, 8, 0, 0, &[], &[0]);
|
||||
assert!(matches!(decode_png(&wide, PngLimits::DEFAULT), Err(ImageError::LimitExceeded(_))));
|
||||
let tall = png_file(1, 1_000_000, 8, 0, 0, &[], &[0]);
|
||||
assert!(matches!(decode_png(&tall, PngLimits::DEFAULT), Err(ImageError::LimitExceeded(_))));
|
||||
// 16,384 × 16,384 RGBA is 1 GiB decoded, over the 256 MiB default.
|
||||
let big = png_file(16_384, 16_384, 8, 6, 0, &[], &[0]);
|
||||
assert!(matches!(decode_png(&big, PngLimits::DEFAULT), Err(ImageError::LimitExceeded(_))));
|
||||
let narrow = PngLimits { max_width: 3, ..PngLimits::DEFAULT };
|
||||
let px = ramp(4, 1, 255);
|
||||
assert!(matches!(encode_png(rgba(4, 1, &px), narrow), Err(ImageError::LimitExceeded(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_input_byte_limit() {
|
||||
let px = ramp(4, 4, 255);
|
||||
let png = encode_png(rgba(4, 4, &px), PngLimits::DEFAULT).unwrap();
|
||||
let exact = PngLimits { max_input_bytes: png.len(), ..PngLimits::DEFAULT };
|
||||
assert!(decode_png(&png, exact).is_ok());
|
||||
let short = PngLimits { max_input_bytes: png.len() - 1, ..PngLimits::DEFAULT };
|
||||
assert!(matches!(decode_png(&png, short), Err(ImageError::LimitExceeded(_))));
|
||||
assert!(matches!(encode_png(rgba(4, 4, &px), short), Err(ImageError::LimitExceeded(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_decoded_byte_limit() {
|
||||
// 4x4 RGB: the decoder's output is 48 bytes, and 64 once converted to RGBA.
|
||||
let scanlines: Vec<u8> = (0..4).flat_map(|_| std::iter::once(0).chain(std::iter::repeat_n(9, 12))).collect();
|
||||
let png = png_file(4, 4, 8, 2, 0, &[], &scanlines);
|
||||
let with = |max_decoded_bytes| decode_png(&png, PngLimits { max_decoded_bytes, ..PngLimits::DEFAULT });
|
||||
assert!(with(64).is_ok());
|
||||
assert!(matches!(with(50), Err(ImageError::LimitExceeded(_))), "the converted size is checked");
|
||||
assert!(matches!(with(47), Err(ImageError::LimitExceeded(_))), "checked before allocation");
|
||||
}
|
||||
|
||||
/// The size after conversion to RGBA is checked from the header, before any image data is read,
|
||||
/// so a stream whose image data is a few bytes still fails on the limit.
|
||||
#[test]
|
||||
fn the_converted_size_is_checked_before_decoding() {
|
||||
// 4x4 RGB, 48 bytes as decoded and 64 as RGBA, with image data that would not decode.
|
||||
let png = png_file(4, 4, 8, 2, 0, &[], &[0]);
|
||||
let err = decode_png(&png, PngLimits { max_decoded_bytes: 50, ..PngLimits::DEFAULT }).unwrap_err();
|
||||
assert!(matches!(err, ImageError::LimitExceeded(_)), "{err:?}");
|
||||
assert!(matches!(decode_png(&png, PngLimits::DEFAULT), Err(ImageError::Decode(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_refuses_an_image_that_would_not_read_back() {
|
||||
// An image is only written when the same limits can decode it again.
|
||||
let px = ramp(4, 4, 255);
|
||||
let fits = PngLimits { max_decoded_bytes: 64, ..PngLimits::DEFAULT };
|
||||
let png = encode_png(rgba(4, 4, &px), fits).unwrap();
|
||||
assert!(decode_png(&png, fits).is_ok());
|
||||
let small = PngLimits { max_decoded_bytes: 63, ..PngLimits::DEFAULT };
|
||||
assert!(matches!(encode_png(rgba(4, 4, &px), small), Err(ImageError::LimitExceeded(_))));
|
||||
let shades = gray(4, 4, 9);
|
||||
assert!(encode_gray_png(g(4, 4, &shades), PngLimits { max_decoded_bytes: 16, ..PngLimits::DEFAULT }).is_ok());
|
||||
assert!(matches!(
|
||||
encode_gray_png(g(4, 4, &shades), PngLimits { max_decoded_bytes: 15, ..PngLimits::DEFAULT }),
|
||||
Err(ImageError::LimitExceeded(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_stops_at_the_byte_limit() {
|
||||
// Noise does not compress, so the encoder would write about 64 KiB without the bound.
|
||||
let mut state = 0x2545_F491_4F6C_DD1Du64;
|
||||
let px: Vec<u8> = (0..128 * 128 * 4)
|
||||
.map(|_| {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
(state >> 56) as u8
|
||||
})
|
||||
.collect();
|
||||
let tiny = PngLimits { max_input_bytes: 100, ..PngLimits::DEFAULT };
|
||||
let err = encode_png(rgba(128, 128, &px), tiny).unwrap_err();
|
||||
assert!(matches!(err, ImageError::LimitExceeded(_)), "{err:?}");
|
||||
assert!(encode_png(rgba(128, 128, &px), PngLimits::DEFAULT).unwrap().len() > 100);
|
||||
let mut sink = BoundedSink { out: Vec::new(), max: 100, exceeded: false };
|
||||
assert!(write_stream(&mut sink, 128, 128, png::ColorType::Rgba, &px).is_err());
|
||||
assert!(sink.exceeded && sink.out.len() <= 100, "{} bytes held", sink.out.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_error_is_result() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("file");
|
||||
std::fs::write(&file, b"x").unwrap();
|
||||
let px = ramp(2, 2, 255);
|
||||
assert!(matches!(write_png(&file.join("x.png"), rgba(2, 2, &px), PngLimits::DEFAULT), Err(ImageError::Io { .. })));
|
||||
assert!(matches!(read_png(&dir.path().join("none.png"), PngLimits::DEFAULT), Err(ImageError::Io { .. })));
|
||||
}
|
||||
|
||||
// Golden checks.
|
||||
|
||||
fn options<'a>(failures: &'a Path, name: &'a str) -> GoldenOptions<'a> {
|
||||
GoldenOptions { bless_var: NO_BLESS, ..GoldenOptions::new(failures, name) }
|
||||
}
|
||||
|
||||
fn mismatch(result: Result<super::Verdict, ImageError>) -> Box<super::GoldenMismatch> {
|
||||
match result {
|
||||
Err(ImageError::GoldenMismatch(m)) => m,
|
||||
other => panic!("expected a mismatch, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_golden_accepts_within_tolerance_and_reports_failures() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let failures = dir.path().join("failures");
|
||||
let path = dir.path().join("ramp.png");
|
||||
let img = ramp(32, 16, 255);
|
||||
write_png(&path, rgba(32, 16, &img), PngLimits::DEFAULT).unwrap();
|
||||
assert!(compare_golden(&path, rgba(32, 16, &img), Tolerance::EXACT, options(&failures, "ramp")).is_ok());
|
||||
let mut near = img.clone();
|
||||
near[5] += 1;
|
||||
assert!(compare_golden(&path, rgba(32, 16, &near), render(), options(&failures, "ramp")).is_ok());
|
||||
let mut far = img.clone();
|
||||
far.iter_mut().step_by(4).for_each(|v| *v = 255 - *v);
|
||||
let e = compare_golden(&path, rgba(32, 16, &far), render(), options(&failures, "ramp")).unwrap_err();
|
||||
assert!(e.to_string().contains("PSNR"), "{e}");
|
||||
let missing = compare_golden(&dir.path().join("missing.png"), rgba(32, 16, &img), render(), options(&failures, "ramp")).unwrap_err();
|
||||
assert!(matches!(missing, ImageError::MissingReference { .. }) && missing.to_string().contains(NO_BLESS), "{missing}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_check_passes_within_the_tolerance_and_fails_past_it() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let failures = dir.path().join("failures");
|
||||
let golden = dir.path().join("g.png");
|
||||
let (w, h) = (20u32, 10u32);
|
||||
let base: Vec<u8> = (0..w * h).flat_map(|i| [i as u8, 100, 200, 255]).collect();
|
||||
write_png(&golden, rgba(w, h, &base), PngLimits::DEFAULT).unwrap();
|
||||
assert!(compare_golden(&golden, rgba(w, h, &base), per_pixel(), options(&failures, "self-test-same")).is_ok());
|
||||
// Small differences everywhere are within the channel tolerance.
|
||||
let near: Vec<u8> = base.iter().map(|c| c.saturating_sub(2)).collect();
|
||||
assert!(compare_golden(&golden, rgba(w, h, &near), per_pixel(), options(&failures, "self-test-near")).is_ok());
|
||||
// A whole row changed is not.
|
||||
let mut off = base.clone();
|
||||
for px in off.as_chunks_mut::<4>().0.iter_mut().take(w as usize) {
|
||||
px[1] = 0;
|
||||
}
|
||||
let m = mismatch(compare_golden(&golden, rgba(w, h, &off), per_pixel(), options(&failures, "self-test-off")));
|
||||
assert_eq!(m.verdict.bad_pixels, 20);
|
||||
assert!(m.actual.exists() && m.diff.exists());
|
||||
assert!(m.diff.ends_with("self-test-off.diff.png"), "{}", m.diff.display());
|
||||
// A missing golden fails and says how to make one.
|
||||
let err = compare_golden(&dir.path().join("none.png"), rgba(w, h, &base), per_pixel(), options(&failures, "self-test-missing")).unwrap_err();
|
||||
assert!(err.to_string().contains(&format!("{NO_BLESS}=1")), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bless_requires_exact_one() {
|
||||
assert!(is_bless_value(Some(OsStr::new("1"))));
|
||||
for value in ["", "0", "true", "yes", "on", " 1", "1 ", "01", "11"] {
|
||||
assert!(!is_bless_value(Some(OsStr::new(value))), "{value:?}");
|
||||
}
|
||||
assert!(!is_bless_value(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_reference_fails_without_bless() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let reference = dir.path().join("refs").join("new.png");
|
||||
let px = ramp(4, 4, 255);
|
||||
let err = check_golden_with(&reference, rgba(4, 4, &px), Tolerance::EXACT, options(dir.path(), "new"), false).unwrap_err();
|
||||
assert!(matches!(err, ImageError::MissingReference { .. }), "{err:?}");
|
||||
assert!(!reference.exists(), "a normal run must not create a reference");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bless_creates_missing_reference() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let reference = dir.path().join("refs").join("new.png");
|
||||
let px = ramp(4, 4, 200);
|
||||
check_golden_with(&reference, rgba(4, 4, &px), Tolerance::EXACT, options(dir.path(), "new"), true).unwrap();
|
||||
assert_eq!(read_png(&reference, PngLimits::DEFAULT).unwrap(), DecodedPng::Rgba { width: 4, height: 4, pixels: px });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversize_bless_leaves_reference_unchanged() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let reference = dir.path().join("r.png");
|
||||
let old = ramp(8, 8, 255);
|
||||
write_png(&reference, rgba(8, 8, &old), PngLimits::DEFAULT).unwrap();
|
||||
let before = std::fs::read(&reference).unwrap();
|
||||
let new = ramp(8, 8, 9);
|
||||
let small = GoldenOptions { limits: PngLimits { max_input_bytes: 10, ..PngLimits::DEFAULT }, ..options(dir.path(), "r") };
|
||||
let err = check_golden_with(&reference, rgba(8, 8, &new), Tolerance::EXACT, small, true).unwrap_err();
|
||||
assert!(matches!(err, ImageError::LimitExceeded(_)), "{err:?}");
|
||||
assert_eq!(std::fs::read(&reference).unwrap(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gray_reference_expansion_respects_the_decoded_limit() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let reference = dir.path().join("g.png");
|
||||
let shades = gray(4, 4, 9);
|
||||
write_gray_png(&reference, g(4, 4, &shades), PngLimits::DEFAULT).unwrap();
|
||||
let px: Vec<u8> = shades.iter().flat_map(|&v| [v, v, v, 255]).collect();
|
||||
assert!(compare_golden(&reference, rgba(4, 4, &px), Tolerance::EXACT, options(dir.path(), "g")).is_ok());
|
||||
// The 16-byte gray reference fits, but its 64-byte RGBA form does not.
|
||||
let small = GoldenOptions { limits: PngLimits { max_decoded_bytes: 16, ..PngLimits::DEFAULT }, ..options(dir.path(), "g") };
|
||||
let err = compare_golden(&reference, rgba(4, 4, &px), Tolerance::EXACT, small).unwrap_err();
|
||||
assert!(matches!(err, ImageError::LimitExceeded(_)), "{err:?}");
|
||||
let wide = ramp(8, 2, 255);
|
||||
let err = compare_golden(&reference, rgba(8, 2, &wide), Tolerance::EXACT, options(dir.path(), "g")).unwrap_err();
|
||||
assert!(matches!(err, ImageError::SizeMismatch { a: (4, 4), b: (8, 2) }), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blessing_replaces_a_reference_whole() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let reference = dir.path().join("r.png");
|
||||
let old = ramp(4, 4, 255);
|
||||
write_png(&reference, rgba(4, 4, &old), PngLimits::DEFAULT).unwrap();
|
||||
let new = ramp(4, 4, 99);
|
||||
check_golden_with(&reference, rgba(4, 4, &new), Tolerance::EXACT, options(dir.path(), "r"), true).unwrap();
|
||||
assert_eq!(read_png(&reference, PngLimits::DEFAULT).unwrap(), DecodedPng::Rgba { width: 4, height: 4, pixels: new });
|
||||
let names: Vec<_> = std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name()).collect();
|
||||
assert_eq!(names, vec![std::ffi::OsString::from("r.png")], "no temporary file is left behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failure_name_rejects_path_components() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let failures = dir.path().join("failures");
|
||||
let reference = dir.path().join("r.png");
|
||||
let px = ramp(2, 2, 255);
|
||||
write_png(&reference, rgba(2, 2, &px), PngLimits::DEFAULT).unwrap();
|
||||
let other = ramp(2, 2, 0);
|
||||
let long = "a".repeat(101);
|
||||
for name in ["", "..", "../escape", "a/b", "a\\b", ".hidden", "C:x", "a b", "x\0", "trailing.", "CON", "nul.x", "com1", "LPT9.png", long.as_str()]
|
||||
{
|
||||
let err = compare_golden(&reference, rgba(2, 2, &other), Tolerance::EXACT, options(&failures, name)).unwrap_err();
|
||||
assert!(matches!(err, ImageError::InvalidName(_)), "{name:?}: {err:?}");
|
||||
}
|
||||
assert!(!failures.exists() && !dir.path().join("escape.actual.png").exists());
|
||||
for name in ["ok-name_1.v2", "_x", "com0", "console"] {
|
||||
assert!(
|
||||
matches!(compare_golden(&reference, rgba(2, 2, &other), Tolerance::EXACT, options(&failures, name)), Err(ImageError::GoldenMismatch(_))),
|
||||
"{name:?}"
|
||||
);
|
||||
}
|
||||
for var in ["", "A=B", "A\0B"] {
|
||||
let bad = GoldenOptions { bless_var: var, ..options(&failures, "ok") };
|
||||
assert!(matches!(compare_golden(&reference, rgba(2, 2, &px), Tolerance::EXACT, bad), Err(ImageError::InvalidName(_))), "{var:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failure_artifacts_stay_in_folder() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let failures = dir.path().join("deep").join("failures");
|
||||
let reference = dir.path().join("r.png");
|
||||
let px = ramp(3, 3, 255);
|
||||
write_png(&reference, rgba(3, 3, &px), PngLimits::DEFAULT).unwrap();
|
||||
let other = ramp(3, 3, 1);
|
||||
let m = mismatch(compare_golden(&reference, rgba(3, 3, &other), Tolerance::EXACT, options(&failures, "case")));
|
||||
assert_eq!(m.actual.parent(), Some(failures.as_path()));
|
||||
assert_eq!(m.diff.parent(), Some(failures.as_path()));
|
||||
assert_eq!(read_png(&m.actual, PngLimits::DEFAULT).unwrap(), DecodedPng::Rgba { width: 3, height: 3, pixels: other });
|
||||
let diff = read_png(&m.diff, PngLimits::DEFAULT).unwrap();
|
||||
assert_eq!((diff.width(), diff.height()), (3, 3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failure_artifacts_do_not_overwrite() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let reference = dir.path().join("r.png");
|
||||
let px = ramp(3, 3, 255);
|
||||
write_png(&reference, rgba(3, 3, &px), PngLimits::DEFAULT).unwrap();
|
||||
let first_img = ramp(3, 3, 1);
|
||||
let second_img = ramp(3, 3, 2);
|
||||
let first = mismatch(compare_golden(&reference, rgba(3, 3, &first_img), Tolerance::EXACT, options(dir.path(), "same")));
|
||||
let kept = std::fs::read(&first.actual).unwrap();
|
||||
let second = mismatch(compare_golden(&reference, rgba(3, 3, &second_img), Tolerance::EXACT, options(dir.path(), "same")));
|
||||
assert_ne!(first.actual, second.actual);
|
||||
assert_ne!(first.diff, second.diff);
|
||||
assert!(second.actual.ends_with("same-1.actual.png"), "{}", second.actual.display());
|
||||
assert_eq!(std::fs::read(&first.actual).unwrap(), kept);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parallel_failures_get_distinct_paths() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let reference = dir.path().join("r.png");
|
||||
let px = ramp(3, 3, 255);
|
||||
write_png(&reference, rgba(3, 3, &px), PngLimits::DEFAULT).unwrap();
|
||||
let other = ramp(3, 3, 1);
|
||||
let paths: Vec<PathBuf> = std::thread::scope(|s| {
|
||||
let handles: Vec<_> = (0..8)
|
||||
.map(|_| s.spawn(|| mismatch(compare_golden(&reference, rgba(3, 3, &other), Tolerance::EXACT, options(dir.path(), "race")))))
|
||||
.collect();
|
||||
handles
|
||||
.into_iter()
|
||||
.flat_map(|h| {
|
||||
let m = h.join().expect("thread");
|
||||
[m.actual, m.diff]
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
let distinct: HashSet<&PathBuf> = paths.iter().collect();
|
||||
assert_eq!(distinct.len(), 16);
|
||||
assert!(paths.iter().all(|p| p.exists()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mismatch_keeps_its_verdict_when_the_failure_images_cannot_be_written() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let reference = dir.path().join("r.png");
|
||||
let px = ramp(3, 3, 255);
|
||||
write_png(&reference, rgba(3, 3, &px), PngLimits::DEFAULT).unwrap();
|
||||
// The failure folder is a regular file, so the failure images cannot be written.
|
||||
let blocked = dir.path().join("file");
|
||||
std::fs::write(&blocked, b"x").unwrap();
|
||||
let other = ramp(3, 3, 1);
|
||||
let err = compare_golden(&reference, rgba(3, 3, &other), Tolerance::EXACT, options(&blocked, "case")).unwrap_err();
|
||||
let ImageError::GoldenMismatchUnsaved(m) = &err else { panic!("expected an unsaved mismatch, got {err:?}") };
|
||||
assert_eq!(m.verdict.bad_pixels, 9);
|
||||
assert!(!m.verdict.passed());
|
||||
assert!(matches!(m.error, ImageError::Io { .. }), "{:?}", m.error);
|
||||
assert!(err.to_string().contains("pixels differ") && err.to_string().contains("could not be written"), "{err}");
|
||||
assert!(std::error::Error::source(&err).is_some());
|
||||
}
|
||||
|
||||
/// Runs `name`, a test of this binary, in a child process with the bless variable removed and
|
||||
/// `CHILD_MARKER` set, and returns whether it passed and what it printed.
|
||||
fn run_child(name: &str) -> (bool, String) {
|
||||
let out = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", name, "--nocapture", "--test-threads=1"])
|
||||
.env_remove(NO_BLESS)
|
||||
.env(CHILD_MARKER, "1")
|
||||
.output()
|
||||
.unwrap();
|
||||
let printed = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
|
||||
assert!(printed.contains("running 1 test"), "the child did not run the test:\n{printed}");
|
||||
(out.status.success(), printed)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assert_similar_returns_the_verdict() {
|
||||
let (passed, printed) = run_child("image::tests::child_assert_similar_passes");
|
||||
assert!(passed, "the child failed:\n{printed}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assert_similar_fails_the_test() {
|
||||
let (passed, printed) = run_child("image::tests::child_assert_similar_fails");
|
||||
assert!(!passed, "the child passed:\n{printed}");
|
||||
assert!(printed.contains("no reference image"), "{printed}");
|
||||
}
|
||||
|
||||
/// Runs in the child process of `assert_similar_returns_the_verdict`, and passes at once elsewhere.
|
||||
#[test]
|
||||
fn child_assert_similar_passes() {
|
||||
if std::env::var_os(CHILD_MARKER).is_none() {
|
||||
return;
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let reference = dir.path().join("r.png");
|
||||
let px = ramp(3, 3, 255);
|
||||
write_png(&reference, rgba(3, 3, &px), PngLimits::DEFAULT).unwrap();
|
||||
let verdict = crate::assert_similar!(&reference, rgba(3, 3, &px), Tolerance::EXACT, options(dir.path(), "ok"));
|
||||
assert!(verdict.passed());
|
||||
}
|
||||
|
||||
/// Runs in the child process of `assert_similar_fails_the_test`, where it must fail, and passes at
|
||||
/// once elsewhere.
|
||||
#[test]
|
||||
fn child_assert_similar_fails() {
|
||||
if std::env::var_os(CHILD_MARKER).is_none() {
|
||||
return;
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let px = ramp(3, 3, 255);
|
||||
crate::assert_similar!(&dir.path().join("none.png"), rgba(3, 3, &px), Tolerance::EXACT, options(dir.path(), "none"));
|
||||
}
|
||||
@@ -13,6 +13,14 @@
|
||||
//! where `std::time::Instant::now()` panics on `wasm32`.
|
||||
//! * `guards::rust_sources`: directory crawler collecting `.rs` sources while excluding tests, with
|
||||
//! size limits (`guards::rust_sources_with_limits`). It is not built for `wasm32`.
|
||||
//! * `image` (feature `image`): RGBA8 and gray views, difference statistics, PSNR for `u8` and
|
||||
//! `u16` planes, tolerances with an optional 3×3 neighborhood, a difference image, PNG reading
|
||||
//! and writing with size limits, golden reference checks and `assert_similar!`.
|
||||
//!
|
||||
//! On native targets, the `fixtures` module locates generated test fixtures under `<workspace>/target/fixtures`,
|
||||
//! generates a missing one into a claimed temporary sibling, publishes it under a per-output lock that
|
||||
//! keeps a complete file another process published first, and prints the `FIXTURE made`, `cached` and
|
||||
//! `skipped` lines that FilmCraft's `cargo xtask fixtures` counts.
|
||||
//!
|
||||
//! [`rng`] holds two seeded generators for repeatable test input, [`rng::XorShift64`] and
|
||||
//! [`rng::XorShift64Star`], each with `next`, `below`, `byte` and `fill`.
|
||||
@@ -69,9 +77,13 @@
|
||||
pub mod corpus;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod deadline;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod fixtures;
|
||||
pub mod fonts;
|
||||
pub mod guards;
|
||||
pub mod hostile;
|
||||
#[cfg(feature = "image")]
|
||||
pub mod image;
|
||||
#[cfg(all(feature = "mcp", not(target_arch = "wasm32")))]
|
||||
pub mod mcp;
|
||||
pub mod rng;
|
||||
|
||||
@@ -111,7 +111,7 @@ pub fn skip(reason: &str, required_var: &str) -> bool {
|
||||
/// Fail the test when `required` is set, otherwise print the skip line and return `false`. It
|
||||
/// fails the test with a panic.
|
||||
#[allow(clippy::panic)]
|
||||
fn skip_with(required: bool, reason: &str, required_var: &str) -> bool {
|
||||
pub(crate) fn skip_with(required: bool, reason: &str, required_var: &str) -> bool {
|
||||
if required {
|
||||
panic!("{reason}, and {required_var}=1 forbids skipping this test");
|
||||
}
|
||||
|
||||
+162
-42
@@ -4,11 +4,10 @@
|
||||
|
||||
use super::length::{DocUnit, length_field, shown};
|
||||
use craft_behavior::{EditEvent, EditEvents, Metrics, Mixed, NumberCodec};
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::choice::Checkbox;
|
||||
use craft_ui::contract::{
|
||||
Bind, Common, Component, Cx, Entry, FieldLayout, MeasureCx, PaintUi, Props as _, Role, Show as _, ShowContainer as _, SideLabel, Sizing,
|
||||
Validity, clicked,
|
||||
Bind, Common, Component, Cx, Entry, FieldLayout, MeasureCx, PaintUi, Pointer as _, Props as _, Role, Show as _, ShowContainer as _, SideLabel,
|
||||
Sizing, Validity,
|
||||
};
|
||||
use craft_ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, HeldAnswer, HeldOk, StackDialog, dialog_id};
|
||||
use craft_ui::form::{Field, FieldGroup};
|
||||
@@ -18,7 +17,7 @@ use craft_ui::primitives::{PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::env::{Env, Label, Message, Units};
|
||||
use craft_ui::runtime::words::CommonWords;
|
||||
use craft_ui::sections::{DialogRole, FooterButton, GroupBox};
|
||||
use craft_ui::style::{ComponentStyle, StyleColor, StyleCx, SurfaceKind, TypeRole};
|
||||
use craft_ui::style::{ComponentStyle, FocusLook, StyleColor, StyleCx, SurfaceKind, TypeRole};
|
||||
use craft_ui::text::{NumberField, NumberOutput};
|
||||
use egui::{Pos2, Rect, Ui, Vec2, pos2, vec2};
|
||||
use std::cell::Cell;
|
||||
@@ -129,6 +128,19 @@ pub enum ColumnsPreset {
|
||||
Right,
|
||||
}
|
||||
|
||||
impl ColumnsPreset {
|
||||
/// The number of columns, and for Left and Right whether the narrow one is first.
|
||||
fn shape(self) -> (u32, Option<bool>) {
|
||||
match self {
|
||||
ColumnsPreset::One => (1, None),
|
||||
ColumnsPreset::Two => (2, None),
|
||||
ColumnsPreset::Three => (3, None),
|
||||
ColumnsPreset::Left => (2, Some(true)),
|
||||
ColumnsPreset::Right => (2, Some(false)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Columns dialog: only what changed comes back.
|
||||
///
|
||||
/// - [`word`](Self::word) off (PowerPoint): Number (1 to [`MAX_COLUMNS`]) and Spacing (0 to [`MAX_SPACING`] points);
|
||||
@@ -287,13 +299,7 @@ impl TextColumnsDialog {
|
||||
let Some(width) = self.word else { return };
|
||||
let spacing = DEFAULT_SPACING;
|
||||
self.edited.spacing = Some(spacing);
|
||||
let (count, narrow_first) = match preset {
|
||||
ColumnsPreset::One => (1, None),
|
||||
ColumnsPreset::Two => (2, None),
|
||||
ColumnsPreset::Three => (3, None),
|
||||
ColumnsPreset::Left => (2, Some(true)),
|
||||
ColumnsPreset::Right => (2, Some(false)),
|
||||
};
|
||||
let (count, narrow_first) = preset.shape();
|
||||
self.edited.count = Some(count);
|
||||
match narrow_first {
|
||||
None => {
|
||||
@@ -533,7 +539,11 @@ impl TextColumnsDialog {
|
||||
let mut chosen = None;
|
||||
Row::new().show(ui, |ui, _| {
|
||||
for (preset, label) in every {
|
||||
if clicked(&Button::new(label.clone()).show(ui)) {
|
||||
let tile = Field::new(label.clone())
|
||||
.layout(FieldLayout::Above)
|
||||
.sizing(Sizing::Content)
|
||||
.show(ui, |ui, _| ColumnsPresetTile::new(label.clone(), Self::preset_rows(preset)).show(ui).clicked);
|
||||
if tile.inner == Some(true) {
|
||||
chosen = Some(preset);
|
||||
}
|
||||
}
|
||||
@@ -543,6 +553,25 @@ impl TextColumnsDialog {
|
||||
}
|
||||
}
|
||||
|
||||
/// The columns a preset draws as, over a text width of 1 and a spacing of a twelfth.
|
||||
pub(crate) fn preset_rows(preset: ColumnsPreset) -> Vec<(f32, f32)> {
|
||||
let (count, narrow_first) = preset.shape();
|
||||
let spacing = 1.0 / 12.0;
|
||||
match narrow_first {
|
||||
// Not `even_rows`: its minimum column width is in points and would close the gaps over a width of 1.
|
||||
None => {
|
||||
let each = (1.0 - spacing * (count - 1) as f32) / count as f32;
|
||||
(0..count).map(|i| (each, if i + 1 < count { spacing } else { 0.0 })).collect()
|
||||
}
|
||||
Some(left) => {
|
||||
let narrow = (1.0 - spacing) * NARROW_SHARE;
|
||||
let wide = 1.0 - spacing - narrow;
|
||||
let (first, second) = if left { (narrow, wide) } else { (wide, narrow) };
|
||||
vec![(first, spacing), (second, 0.0)]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One row per column: its number, then its width and the spacing after it, each behind its caption.
|
||||
fn grid(&mut self, ui: &mut Ui, words: &TextColumnsWords, units: &Units) {
|
||||
let rows = self.rows();
|
||||
@@ -723,6 +752,25 @@ pub struct ColumnsPreviewStyle {
|
||||
pane: f32,
|
||||
/// The distance between text lines.
|
||||
pitch: f32,
|
||||
#[style(focus)]
|
||||
focus: FocusLook,
|
||||
}
|
||||
|
||||
impl ColumnsPreviewStyle {
|
||||
/// The preview's look; a preset thumbnail takes the same with a smaller pane.
|
||||
fn at(cx: &StyleCx<'_>) -> Self {
|
||||
let colors = &cx.tokens.color;
|
||||
ColumnsPreviewStyle {
|
||||
metrics: Metrics::new(),
|
||||
page: cx.color(colors.surface.raised),
|
||||
edge: cx.color(colors.line.border),
|
||||
line: cx.color(colors.text.faint),
|
||||
separator: cx.color(colors.text.normal),
|
||||
pane: cx.tokens.size.thumb.sample.lg,
|
||||
pitch: cx.tokens.typography.get(TypeRole::Body).line_height * LINE_PITCH,
|
||||
focus: cx.focus_look(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The page preview: the columns and the line between them on a page, as Word's dialog draws it.
|
||||
@@ -750,16 +798,7 @@ impl Component for ColumnsPreview {
|
||||
type Output = egui::Response;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: ColumnsPreviewStyleKey) -> ColumnsPreviewStyle {
|
||||
let colors = &cx.tokens.color;
|
||||
ColumnsPreviewStyle {
|
||||
metrics: Metrics::new(),
|
||||
page: cx.color(colors.surface.raised),
|
||||
edge: cx.color(colors.line.border),
|
||||
line: cx.color(colors.text.faint),
|
||||
separator: cx.color(colors.text.normal),
|
||||
pane: cx.tokens.size.thumb.md,
|
||||
pitch: cx.tokens.typography.get(TypeRole::Body).line_height * LINE_PITCH,
|
||||
}
|
||||
ColumnsPreviewStyle::at(cx)
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
@@ -767,26 +806,15 @@ impl Component for ColumnsPreview {
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let style = cx.style;
|
||||
let pane = cx.rect;
|
||||
let height = pane.height().min(pane.width() / PAGE_ASPECT);
|
||||
let page = Rect::from_center_size(pane.center(), vec2(height * PAGE_ASPECT, height));
|
||||
let draw = ui.draw();
|
||||
draw.surface(pane, SurfaceKind::Sunken, craft_ui::style::Corners::None);
|
||||
draw.fill(&PaintShape::Rect(page, egui::CornerRadius::ZERO), style.page);
|
||||
draw.stroke(&PaintShape::Rect(page, egui::CornerRadius::ZERO), StrokeWidth::Thin, style.edge);
|
||||
let plan = preview_plan(&self.rows, self.text_width, self.line_between, page);
|
||||
let line = |a: Pos2, b: Pos2, color: StyleColor| draw.stroke(&PaintShape::Path(vec![a, b]), StrokeWidth::Thin, color);
|
||||
for &(left, right) in &plan.columns {
|
||||
let mut y = plan.text.top();
|
||||
while y + style.pitch / 2.0 <= plan.text.bottom() {
|
||||
line(pos2(left, y), pos2(right, y), style.line);
|
||||
y += style.pitch;
|
||||
}
|
||||
}
|
||||
for &x in &plan.separators {
|
||||
line(pos2(x, plan.text.top()), pos2(x, plan.text.bottom()), style.separator);
|
||||
}
|
||||
paint_columns(
|
||||
ui,
|
||||
[cx.style.page, cx.style.edge, cx.style.line, cx.style.separator],
|
||||
cx.style.pitch,
|
||||
cx.rect,
|
||||
&self.rows,
|
||||
self.text_width,
|
||||
self.line_between,
|
||||
);
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> egui::Response {
|
||||
@@ -794,6 +822,98 @@ impl Component for ColumnsPreview {
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws the page of `rows` over `text_width` in `pane`.
|
||||
fn paint_columns(ui: &mut PaintUi<'_>, inks: [StyleColor; 4], pitch: f32, pane: Rect, rows: &[(f32, f32)], text_width: f32, line_between: bool) {
|
||||
let height = pane.height().min(pane.width() / PAGE_ASPECT);
|
||||
let page = Rect::from_center_size(pane.center(), vec2(height * PAGE_ASPECT, height));
|
||||
let draw = ui.draw();
|
||||
draw.surface(pane, SurfaceKind::Sunken, craft_ui::style::Corners::None);
|
||||
let [page_ink, edge, text, separator] = inks;
|
||||
draw.fill(&PaintShape::Rect(page, egui::CornerRadius::ZERO), page_ink);
|
||||
draw.stroke(&PaintShape::Rect(page, egui::CornerRadius::ZERO), StrokeWidth::Thin, edge);
|
||||
let plan = preview_plan(rows, text_width, line_between, page);
|
||||
let line = |a: Pos2, b: Pos2, color: StyleColor| draw.stroke(&PaintShape::Path(vec![a, b]), StrokeWidth::Thin, color);
|
||||
for &(left, right) in &plan.columns {
|
||||
let mut y = plan.text.top();
|
||||
while y + pitch / 2.0 <= plan.text.bottom() {
|
||||
line(pos2(left, y), pos2(right, y), text);
|
||||
y += pitch;
|
||||
}
|
||||
}
|
||||
for &x in &plan.separators {
|
||||
line(pos2(x, plan.text.top()), pos2(x, plan.text.bottom()), separator);
|
||||
}
|
||||
}
|
||||
|
||||
/// A preset's thumbnail: a small page with the preset's columns, a button named by the label.
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
pub struct ColumnsPresetTile {
|
||||
#[common]
|
||||
common: Common,
|
||||
rows: Vec<(f32, f32)>,
|
||||
clicked: bool,
|
||||
}
|
||||
|
||||
/// What a preset tile reports.
|
||||
#[derive(Clone, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct ColumnsPresetTileOutput {
|
||||
/// The tile's response.
|
||||
pub response: egui::Response,
|
||||
/// A click, Space or Enter reached the enabled tile.
|
||||
pub clicked: bool,
|
||||
}
|
||||
|
||||
impl craft_ui::contract::Outcome for ColumnsPresetTileOutput {
|
||||
type Value = craft_ui::contract::NoValue;
|
||||
|
||||
fn response(&self) -> &egui::Response {
|
||||
&self.response
|
||||
}
|
||||
}
|
||||
|
||||
impl ColumnsPresetTile {
|
||||
/// A tile named `label` drawing `rows` (each column's width and the spacing after it).
|
||||
pub fn new(label: impl Into<Label>, rows: Vec<(f32, f32)>) -> Self {
|
||||
ColumnsPresetTile { common: Common::new(), rows, clicked: false }.label(label)
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for ColumnsPresetTile {
|
||||
const ROLE: Role = Role::BUTTON;
|
||||
const PARTS: bool = false;
|
||||
const OVERLAYS: bool = false;
|
||||
type Style = ColumnsPreviewStyle;
|
||||
type Output = ColumnsPresetTileOutput;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: ColumnsPresetTileStyleKey) -> ColumnsPreviewStyle {
|
||||
let mut style = ColumnsPreviewStyle::at(cx);
|
||||
style.pane = cx.tokens.size.thumb.lg;
|
||||
style.pitch /= 2.0;
|
||||
style
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::splat(cx.style.pane)
|
||||
}
|
||||
|
||||
fn sense(&self) -> craft_behavior::Sense {
|
||||
craft_behavior::Sense::CLICK | craft_behavior::Sense::FOCUS
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
self.clicked = cx.activation().is_some() && cx.resolved.enabled;
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
paint_columns(ui, [cx.style.page, cx.style.edge, cx.style.line, cx.style.separator], cx.style.pitch, cx.rect, &self.rows, 1.0, false);
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> ColumnsPresetTileOutput {
|
||||
ColumnsPresetTileOutput { response: cx.response.clone(), clicked: self.clicked }
|
||||
}
|
||||
}
|
||||
|
||||
/// A choice from the Columns menu.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
|
||||
Loaded 100 of 422 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user