From 799e53c5936edd2e7d4d9450398bbce50bfd63ff Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:40:56 -0800 Subject: [PATCH 01/31] hayro-interpret: a soft mask set outside a form draws that form The self-draw check added with the PdfCraft port (patch 89) compared each form against every form being drawn on the page when it was drawn. A device interprets a soft mask, a tiling pattern or a Type 3 glyph when it applies it, which can be inside a form that the mask's content draws again: a soft mask set on the page whose group draws the same shared form as the page then draws. The mask's copy of the form was skipped, and the page reported ContentTruncated. Soft masks, tiling patterns and Type 3 glyphs now record the forms being drawn where the content set or showed them, and their content is checked against that record. A form that draws itself, directly, through another form, or through a soft mask, tiling pattern or Type 3 glyph set inside it, is still skipped and reported. --- vendor/README.craft-reader.md | 11 + vendor/hayro-interpret/SOURCE.json | 16 +- vendor/hayro-interpret/src/context.rs | 44 ++- vendor/hayro-interpret/src/font/mod.rs | 13 +- vendor/hayro-interpret/src/lib.rs | 2 + vendor/hayro-interpret/src/pattern.rs | 17 +- vendor/hayro-interpret/src/self_draw_tests.rs | 282 ++++++++++++++++++ vendor/hayro-interpret/src/soft_mask.rs | 16 +- 8 files changed, 388 insertions(+), 13 deletions(-) create mode 100644 vendor/hayro-interpret/src/self_draw_tests.rs diff --git a/vendor/README.craft-reader.md b/vendor/README.craft-reader.md index 405799ceb6..82e9c29302 100644 --- a/vendor/README.craft-reader.md +++ b/vendor/README.craft-reader.md @@ -88,6 +88,17 @@ colorants paint through their alternate space (`Plate::spots_as_process`) and no overprints. Masks in other color spaces are unchanged. A test in `crates/pdf/tests/plates.rs` checks process, spot, RGB and backdrop colors. +A craft-libs patch, labeled `Craft patch (self-draw scope)` in code comments, scopes the +self-draw check of hayro-interpret patch 89 for soft masks, tiling patterns and Type 3 glyphs. +Each of them records the forms being drawn where the content set or showed it +(`context::FormsDrawing`), and `SoftMask::interpret`, `SoftMask::interpret_plate`, +`TilingPattern::interpret` and `Type3Glyph::interpret` check the forms they draw against that +record instead of the forms the device is drawing when it calls them. A soft mask set on the page +and interpreted by a device while it draws a form now draws that form; before, the mask's copy of +the form was skipped and the page reported `ContentTruncated`. A form that draws itself, directly, +through another form, or through a soft mask, tiling pattern or Type 3 glyph set inside it, is +still skipped. Tests: `self_draw_tests.rs` in hayro-interpret. + The output-intent conversion of patch 36 goes through a `color::CmykConversion` trait, so that callers can convert with their own color management. `CmykSimulation::new` keeps #2770's moxcms conversion as the default, and `CmykSimulation::with_conversion` takes a diff --git a/vendor/hayro-interpret/SOURCE.json b/vendor/hayro-interpret/SOURCE.json index bffa37b555..71924358dd 100644 --- a/vendor/hayro-interpret/SOURCE.json +++ b/vendor/hayro-interpret/SOURCE.json @@ -188,7 +188,7 @@ "path": "src/context.rs", "source_sha256": "dc2be553958ee3f5e5e644a77a0301723bae9ca027a352c13b9caaf549cc0e56", "source_git_blob": "d6772baa15ebb95d3ba2d1f54ce5c250ad1e8137", - "sha256": "221174b2b65824e1489e8d0f61ac5c81b828caf7f5c7053e27c84a6657857f4c" + "sha256": "cf87f1889acca28e7d0e19b08e25ce9db3654de8f612b29f9a111bd06e01affd" }, { "path": "src/convert.rs", @@ -290,7 +290,7 @@ "path": "src/font/mod.rs", "source_sha256": "7e6411927d91205ca76c6b59f9d737cd1104d066f8cfcc0a87f481016ef30313", "source_git_blob": "7c8c8d086d59139df791cdb6952506473ec4b5a7", - "sha256": "c0c903cb8a33ab863412c407ad10181adec0d22b81c899fc5225de14d8878091" + "sha256": "903b2426fbbc1bc0ffbd3f1f2d1a3ce7fdd28aad424f38ba8592b866982de9f9" }, { "path": "src/font/outline.rs", @@ -386,7 +386,7 @@ "path": "src/lib.rs", "source_sha256": "ea3fa23b74f99b5382798f90b7e9f0e3edca354ee26ea92fe26a91ee5c0195c9", "source_git_blob": "24c3be295783d7a53ac6bc39d93e539883480cd4", - "sha256": "ea3fa23b74f99b5382798f90b7e9f0e3edca354ee26ea92fe26a91ee5c0195c9" + "sha256": "777f78daa1c2dbcb945bc2061bfd5748f3ee07a0efbe53de7fa7de29d2880f5f" }, { "path": "src/log.rs", @@ -404,7 +404,13 @@ "path": "src/pattern.rs", "source_sha256": "17b49a465275c20e6645dea9443f2cb3a64c594925fd860e74b80b44d5344e37", "source_git_blob": "9295f51709f8915951d7b9afca9411651d65a1f8", - "sha256": "e57d4de60126eafa0da2113af12bbbde1aabd15554f1ee26f6551b8219f4ede5" + "sha256": "7b89b41219c11eac781b64ec0584ccaebbd76aa9c570ba13a00e0cb06c59b4c5" + }, + { + "path": "src/self_draw_tests.rs", + "source_sha256": null, + "source_git_blob": null, + "sha256": "58930501e624b86fd45ddc82e464a959d989d6ef94eb7e62f8f8ad24c78ec8ec" }, { "path": "src/shading.rs", @@ -416,7 +422,7 @@ "path": "src/soft_mask.rs", "source_sha256": "6cd9c59c0cff580879c1f06ff40f3537c04b719bdb3ea59008fa1ab7559db5dd", "source_git_blob": "4d97d565b53c820fa927fbba8c3dda6acead7f34", - "sha256": "fe3da157602bf5b16a452ecbe1d8d554af992a5b9dfaa771dd23c2e2e66d730b" + "sha256": "54cb20d6ba5ab8e290e420833acfa9ce2e8e7274b74680e4b9481a093b5d1db9" }, { "path": "src/types.rs", diff --git a/vendor/hayro-interpret/src/context.rs b/vendor/hayro-interpret/src/context.rs index 7997e9c0de..66ae11e1cb 100644 --- a/vendor/hayro-interpret/src/context.rs +++ b/vendor/hayro-interpret/src/context.rs @@ -40,7 +40,9 @@ std::thread_local! { // PdfCraft patch (89): the form XObjects being drawn on this page, outermost first, across // the contexts of the tiling patterns, Type 3 glyphs, soft masks and groups painted while // they draw. A form already on it draws itself and is skipped. Its length is bounded by the - // nesting limits: every form on it is nested in the ones before it. + // nesting limits: every form on it is nested in the ones before it. While a device + // interprets a soft mask, tiling pattern or Type 3 glyph, it holds the forms that one was + // set in (`with_forms_drawing`). static FORMS_DRAWING: RefCell> = const { RefCell::new(Vec::new()) }; } @@ -159,6 +161,42 @@ pub(crate) fn take_nested_paint(depth: u32) -> bool { }) } +/// Craft patch (self-draw scope): the forms being drawn where a soft mask, a tiling pattern or a +/// Type 3 glyph was set in the content. A device may interpret any of them later, while it draws +/// another form: a soft mask set on the page is interpreted for each fill it applies to, inside +/// whatever form that fill is in. Its content is nested in the forms it was set in, so the +/// self-draw check of patch (89) runs against those (see [`with_forms_drawing`]). +#[derive(Clone, Default)] +pub(crate) struct FormsDrawing(Vec); + +impl FormsDrawing { + /// The forms being drawn now. + pub(crate) fn current() -> Self { + FORMS_DRAWING.with(|forms| Self(forms.try_borrow().map(|forms| forms.clone()).unwrap_or_default())) + } + + /// The forms, outermost first. + pub(crate) fn ids(&self) -> &[hayro_syntax::object::ObjectIdentifier] { + &self.0 + } +} + +/// Craft patch (self-draw scope): run `draw` with `forms` as the forms being drawn, and put +/// back the ones being drawn before. A form `draw` reaches is skipped only when it is among +/// `forms` or nested in itself within `draw`. +pub(crate) fn with_forms_drawing(forms: &FormsDrawing, draw: impl FnOnce() -> R) -> R { + let outer = FORMS_DRAWING.with(|stack| stack.try_borrow_mut().ok().map(|mut stack| core::mem::replace(&mut *stack, forms.0.clone()))); + let result = draw(); + if let Some(outer) = outer { + FORMS_DRAWING.with(|stack| { + if let Ok(mut stack) = stack.try_borrow_mut() { + *stack = outer; + } + }); + } + result +} + /// A cache used by the interpreter. /// /// Ideally, such a cache should be constructed once per PDF and then reused across @@ -363,7 +401,9 @@ impl<'a> Context<'a> { /// The forms being drawn are those of this page's context and of every context painting /// inside it (a tiling pattern, a Type 3 glyph, a soft mask or a group), so a form that /// reaches itself through one of those is skipped too, while a form drawn again after it - /// has finished draws as usual. + /// has finished draws as usual. A soft mask, tiling pattern or Type 3 glyph draws inside + /// the forms it was set in, wherever the device interprets it (Craft patch (self-draw + /// scope), [`FormsDrawing`]). pub(crate) fn enter_form( &mut self, id: Option, diff --git a/vendor/hayro-interpret/src/font/mod.rs b/vendor/hayro-interpret/src/font/mod.rs index e87382d976..a9ce0fe360 100644 --- a/vendor/hayro-interpret/src/font/mod.rs +++ b/vendor/hayro-interpret/src/font/mod.rs @@ -1,6 +1,7 @@ //! Interacting with the different kinds of PDF fonts. use crate::context::Context; +use crate::context::FormsDrawing; use crate::context::InterpreterCache; use crate::device::Device; use crate::font::cid::Type0Font; @@ -222,11 +223,16 @@ pub struct Type3Glyph<'a> { pub(crate) settings: InterpreterSettings, pub(crate) nesting_depth: u32, pub(crate) char_code: u32, + /// Craft patch (self-draw scope): the forms being drawn where the glyph was shown. + pub(crate) forms: FormsDrawing, } /// A glyph defined by PDF drawing instructions. impl<'a> Type3Glyph<'a> { /// Draw the type3 glyph to the given device. + /// + /// Craft patch (self-draw scope): the glyph procedure draws inside the forms the glyph was + /// shown in, wherever the device interprets it (see [`crate::SoftMask::interpret`]). pub fn interpret( &self, device: &mut impl Device<'a>, @@ -234,8 +240,10 @@ impl<'a> Type3Glyph<'a> { glyph_transform: Affine, paint: &Paint<'a>, ) { - self.font - .render_glyph(self, transform, glyph_transform, paint, device); + crate::context::with_forms_drawing(&self.forms, || { + self.font + .render_glyph(self, transform, glyph_transform, paint, device) + }); } /// Returns the Unicode code point for this glyph, if available: the `ToUnicode` cmap, then @@ -386,6 +394,7 @@ impl<'a> Font<'a> { settings: ctx.settings.clone(), nesting_depth, char_code, + forms: FormsDrawing::current(), }; Glyph::Type3(Box::new(shape_glyph)) diff --git a/vendor/hayro-interpret/src/lib.rs b/vendor/hayro-interpret/src/lib.rs index 03a0f44811..565fbc1c5d 100644 --- a/vendor/hayro-interpret/src/lib.rs +++ b/vendor/hayro-interpret/src/lib.rs @@ -40,6 +40,8 @@ mod device; mod function; mod interpret; mod ocg; +#[cfg(test)] +mod self_draw_tests; mod soft_mask; mod types; mod x_object; diff --git a/vendor/hayro-interpret/src/pattern.rs b/vendor/hayro-interpret/src/pattern.rs index bc3b99c943..288df7f54a 100644 --- a/vendor/hayro-interpret/src/pattern.rs +++ b/vendor/hayro-interpret/src/pattern.rs @@ -2,7 +2,7 @@ use crate::cache::Cache; use crate::color::{Color, ColorSpace, DefaultColorSpaces, Plate}; -use crate::context::{Context, InterpreterCache}; +use crate::context::{Context, FormsDrawing, InterpreterCache, with_forms_drawing}; use crate::device::Device; use crate::font::Glyph; use crate::interpret::state::{ActiveTransferFunction, State}; @@ -182,6 +182,8 @@ pub struct TilingPattern<'a> { pub(crate) settings: InterpreterSettings, pub(crate) xref: &'a XRef, nesting_depth: u32, + /// Craft patch (self-draw scope): the forms being drawn where the pattern was set. + forms: FormsDrawing, } impl TilingPattern<'_> { @@ -280,15 +282,28 @@ impl<'a> TilingPattern<'a> { cache: ctx.interpreter_cache.clone(), xref: ctx.xref, nesting_depth, + forms: FormsDrawing::current(), }) } /// Interpret the contents of the pattern into the given device. + /// + /// Craft patch (self-draw scope): the cell draws inside the forms the pattern was set in, + /// wherever the device interprets it (see [`SoftMask::interpret`]). pub fn interpret( &self, device: &mut impl Device<'a>, initial_transform: Affine, is_stroke: bool, + ) -> Option<()> { + with_forms_drawing(&self.forms, || self.interpret_cell(device, initial_transform, is_stroke)) + } + + fn interpret_cell( + &self, + device: &mut impl Device<'a>, + initial_transform: Affine, + is_stroke: bool, ) -> Option<()> { // PdfCraft patch: a tiling pattern can paint itself (directly, or through resources it // inherits when its own are missing), which recursed until the stack overflowed. Bound diff --git a/vendor/hayro-interpret/src/self_draw_tests.rs b/vendor/hayro-interpret/src/self_draw_tests.rs new file mode 100644 index 0000000000..e28b481f06 --- /dev/null +++ b/vendor/hayro-interpret/src/self_draw_tests.rs @@ -0,0 +1,282 @@ +//! Craft patch (self-draw scope) tests: a form that draws itself, directly or through another +//! form, a soft mask, a tiling pattern or a Type 3 glyph set inside it, is skipped and the page +//! reported truncated (patch (89)). A soft mask, tiling pattern or Type 3 glyph set outside a +//! form draws that form in full when the device interprets it while drawing the form. + +use crate::context::content_was_truncated; +use crate::font::{Glyph, Type3Glyph}; +use crate::pattern::Pattern; +use crate::{ + BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache, + InterpreterSettings, InterpreterWarning, Paint, PathDrawMode, SoftMask, interpret_page, +}; +use hayro_syntax::Pdf; +use kurbo::{Affine, BezPath, Rect}; +use std::sync::{Arc, Mutex}; + +/// A PDF with one 100 by 100 page whose resources are `resources` and whose content is +/// `content`, followed by `objects` as objects 5, 6 and so on. +fn pdf(resources: &str, content: &str, objects: &[String]) -> Pdf { + let mut bodies = vec![ + "<< /Type /Catalog /Pages 2 0 R >>".to_string(), + "<< /Type /Pages /Count 1 /Kids [3 0 R] >>".to_string(), + format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /Resources {resources} >>"), + stream("", content), + ]; + bodies.extend_from_slice(objects); + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, body) in bodies.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n{body}\nendobj\n", i + 1).as_bytes()); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", bodies.len() + 1).as_bytes()); + for offset in offsets { + out.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice( + format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", bodies.len() + 1).as_bytes(), + ); + Pdf::new(out).expect("synthetic pdf") +} + +fn stream(entries: &str, content: &str) -> String { + format!("<< /Length {} {entries} >>\nstream\n{content}\nendstream", content.len()) +} + +/// A form 10 by 10 that draws `content` with the resources of whatever draws it. +fn form(content: &str) -> String { + stream("/Type /XObject /Subtype /Form /BBox [0 0 10 10]", content) +} + +/// A soft mask group that draws `content` with `resources`. +fn mask_group(resources: &str, content: &str) -> String { + stream( + &format!("/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Group << /S /Transparency >> /Resources {resources}"), + content, + ) +} + +/// A coloured tiling pattern whose cell draws `content` with `resources`. +fn tiling(resources: &str, content: &str) -> String { + stream( + &format!( + "/Type /Pattern /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10 /Resources {resources}" + ), + content, + ) +} + +/// A Type 3 font whose glyph `a` is drawn by the procedure in object `proc`, with `resources`. +fn type3(resources: &str, proc: usize) -> String { + format!( + "<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] /CharProcs << /a {proc} 0 R >> /Encoding << /Type /Encoding /Differences [97 /a] >> /FirstChar 97 /LastChar 97 /Widths [1000] /Resources {resources} >>" + ) +} + +/// The paths a device was given, by where they were drawn. +#[derive(Default, Debug, PartialEq)] +struct Drawn { + paths: usize, + in_masks: usize, + in_patterns: usize, + in_glyphs: usize, +} + +/// A device that interprets every soft mask it is given, every tiling pattern it fills with and +/// every Type 3 glyph it draws, each into a device of its own, at the time it is given them. With +/// `defer_glyphs`, it keeps the first Type 3 glyph and interprets it at the next path instead. +#[derive(Default)] +struct Recorder<'a> { + drawn: Drawn, + defer_glyphs: bool, + deferred: Option>>, +} + +impl Recorder<'_> { + fn absorb(&mut self, inner: &Recorder<'_>) -> usize { + let d = &inner.drawn; + self.drawn.in_masks += d.in_masks; + self.drawn.in_patterns += d.in_patterns; + self.drawn.in_glyphs += d.in_glyphs; + d.paths + } +} + +impl<'a> Device<'a> for Recorder<'a> { + fn set_soft_mask(&mut self, mask: Option>) { + if let Some(mask) = mask { + let mut inner = Recorder::default(); + mask.interpret(&mut inner); + self.drawn.in_masks += self.absorb(&inner); + } + } + + fn set_blend_mode(&mut self, _: BlendMode) {} + + fn draw_path(&mut self, _: &BezPath, transform: Affine, paint: &Paint<'a>, _: &PathDrawMode) { + self.drawn.paths += 1; + if let Paint::Pattern(pattern) = paint + && let Pattern::Tiling(tiling) = &**pattern + { + let mut inner = Recorder::default(); + tiling.interpret(&mut inner, transform, false); + self.drawn.in_patterns += self.absorb(&inner); + } + if let Some(glyph) = self.deferred.take() { + let mut inner = Recorder::default(); + glyph.interpret(&mut inner, Affine::IDENTITY, Affine::IDENTITY, paint); + self.drawn.in_glyphs += self.absorb(&inner); + } + } + + fn push_clip_path(&mut self, _: &ClipPath) {} + + fn push_transparency_group(&mut self, _: f32, _: Option>, _: BlendMode) {} + + fn draw_glyph(&mut self, glyph: &Glyph<'a>, transform: Affine, glyph_transform: Affine, paint: &Paint<'a>, _: &GlyphDrawMode) { + let Glyph::Type3(glyph) = glyph else { + return; + }; + if self.defer_glyphs { + self.deferred = Some(glyph.clone()); + return; + } + let mut inner = Recorder::default(); + glyph.interpret(&mut inner, transform, glyph_transform, paint); + self.drawn.in_glyphs += self.absorb(&inner); + } + + fn draw_image(&mut self, _: Image<'a, '_>, _: Affine) {} + + fn pop_clip_path(&mut self) {} + + fn pop_transparency_group(&mut self) {} +} + +/// Draws the page of `pdf` and returns what was drawn and whether the page was reported +/// truncated. +fn draw(pdf: &Pdf, defer_glyphs: bool) -> (Drawn, bool) { + let cache = InterpreterCache::new(); + let warnings = Arc::new(Mutex::new(Vec::new())); + let sink = warnings.clone(); + let settings = InterpreterSettings { + warning_sink: Arc::new(move |warning| sink.lock().expect("warnings").push(warning)), + ..InterpreterSettings::default() + }; + let mut ctx = Context::new(Affine::IDENTITY, Rect::new(0.0, 0.0, 100.0, 100.0), &cache, pdf.xref(), settings); + let mut device = Recorder { defer_glyphs, ..Recorder::default() }; + let page = &pdf.pages()[0]; + interpret_page(page, &mut ctx, &mut device); + let warnings = warnings.lock().expect("warnings"); + let truncated = warnings.iter().any(|w| matches!(w, InterpreterWarning::ContentTruncated)); + assert_eq!(truncated, content_was_truncated()); + (device.drawn, truncated) +} + +const SQUARE: &str = "0 0 10 10 re f"; + +// A form that names itself in its own resources is a reference cycle, which hayro-syntax reads +// as a missing object. The forms below have no resources of their own and reach themselves +// through the page's. + +#[test] +fn a_form_that_draws_itself_is_skipped() { + let pdf = pdf("<< /XObject << /F 5 0 R >> >>", "/F Do", &[form("0 0 10 10 re f /F Do")]); + let (drawn, truncated) = draw(&pdf, false); + assert_eq!(drawn, Drawn { paths: 1, ..Drawn::default() }); + assert!(truncated); +} + +#[test] +fn a_form_that_draws_itself_through_another_form_is_skipped() { + let pdf = pdf( + "<< /XObject << /F 5 0 R /H 6 0 R >> >>", + "/F Do", + &[form("0 0 10 10 re f /H Do"), form("/F Do")], + ); + let (drawn, truncated) = draw(&pdf, false); + assert_eq!(drawn, Drawn { paths: 1, ..Drawn::default() }); + assert!(truncated); +} + +#[test] +fn a_soft_mask_set_outside_a_form_draws_that_form() { + // The mask is set on the page and draws the form the page then draws; the device interprets + // it while it draws that form. + let pdf = pdf( + "<< /XObject << /F 5 0 R >> /ExtGState << /GS << /SMask << /S /Alpha /G 6 0 R >> >> >> >>", + "/GS gs /F Do", + &[form(SQUARE), mask_group("<< /XObject << /F 5 0 R >> >>", "/F Do")], + ); + let (drawn, truncated) = draw(&pdf, false); + assert!(drawn.in_masks > 0, "{drawn:?}"); + assert_eq!(drawn.paths, 1); + assert!(!truncated); +} + +#[test] +fn a_soft_mask_set_inside_a_form_that_it_draws_skips_that_form() { + let pdf = pdf( + "<< /XObject << /F 5 0 R >> /ExtGState << /GS << /SMask << /S /Alpha /G 6 0 R >> >> >> >>", + "/F Do", + &[form("/GS gs 0 0 10 10 re f"), mask_group("<< /XObject << /F 5 0 R >> >>", "/F Do")], + ); + let (drawn, truncated) = draw(&pdf, false); + assert_eq!(drawn, Drawn { paths: 1, ..Drawn::default() }); + assert!(truncated); +} + +#[test] +fn a_tiling_pattern_set_outside_a_form_draws_that_form() { + let pdf = pdf( + "<< /XObject << /F 5 0 R >> /Pattern << /P 6 0 R >> >>", + "/Pattern cs /P scn /F Do", + &[form(SQUARE), tiling("<< /XObject << /F 5 0 R >> >>", "/F Do")], + ); + let (drawn, truncated) = draw(&pdf, false); + assert!(drawn.in_patterns > 0, "{drawn:?}"); + assert!(!truncated); +} + +#[test] +fn a_tiling_pattern_set_inside_a_form_that_it_draws_skips_that_form() { + let pdf = pdf( + "<< /XObject << /F 5 0 R >> /Pattern << /P 6 0 R >> >>", + "/F Do", + &[form("/Pattern cs /P scn 0 0 10 10 re f"), tiling("<< /XObject << /F 5 0 R >> >>", "/F Do")], + ); + let (drawn, truncated) = draw(&pdf, false); + assert_eq!(drawn, Drawn { paths: 1, ..Drawn::default() }); + assert!(truncated); +} + +#[test] +fn a_type3_glyph_shown_outside_a_form_draws_that_form() { + // The device keeps the glyph shown on the page and interprets it while it draws the form. + let pdf = pdf( + "<< /XObject << /F 5 0 R >> /Font << /T 6 0 R >> >>", + "BT /T 10 Tf (a) Tj ET /F Do", + &[form(SQUARE), type3("<< /XObject << /F 5 0 R >> >>", 7), stream("", "1000 0 d0 /F Do")], + ); + let (drawn, truncated) = draw(&pdf, true); + assert!(drawn.in_glyphs > 0, "{drawn:?}"); + assert!(!truncated); +} + +#[test] +fn a_type3_glyph_shown_inside_a_form_that_it_draws_skips_that_form() { + let pdf = pdf( + "<< /XObject << /F 5 0 R >> /Font << /T 6 0 R >> >>", + "/F Do", + &[ + form("BT /T 10 Tf (a) Tj ET 0 0 10 10 re f"), + type3("<< /XObject << /F 5 0 R >> >>", 7), + stream("", "1000 0 d0 /F Do"), + ], + ); + let (drawn, truncated) = draw(&pdf, false); + assert_eq!(drawn, Drawn { paths: 1, ..Drawn::default() }); + assert!(truncated); +} diff --git a/vendor/hayro-interpret/src/soft_mask.rs b/vendor/hayro-interpret/src/soft_mask.rs index 6ecd81dbfd..1ddee0c9e2 100644 --- a/vendor/hayro-interpret/src/soft_mask.rs +++ b/vendor/hayro-interpret/src/soft_mask.rs @@ -1,5 +1,5 @@ use crate::color::{CmykSimulation, Color, ColorComponents, ColorSpace, DeviceFamily, Ink, Plate, device_cmyk_to_gray}; -use crate::context::{Context, InterpreterCache}; +use crate::context::{Context, FormsDrawing, InterpreterCache, with_forms_drawing}; use crate::device::Device; use crate::function::Function; use crate::interpret::state::State; @@ -83,6 +83,8 @@ struct Repr<'a> { device_cmyk: bool, /// Craft patch (CMYK masks): the page plate's printing condition, for [`SoftMask::plate`]. simulation: Option, + /// Craft patch (self-draw scope): the forms being drawn where the mask was set. + forms: FormsDrawing, } impl Hash for Repr<'_> { @@ -184,6 +186,7 @@ impl<'a> SoftMask<'a> { .plate .as_ref() .and_then(|p| p.simulation.clone()); + let forms = FormsDrawing::current(); let cache_key = hash128(&( simulation.as_ref().map(|s| s.digest()), dict.cache_key(), @@ -191,6 +194,8 @@ impl<'a> SoftMask<'a> { [bbox.x0.to_bits(), bbox.y0.to_bits(), bbox.x1.to_bits(), bbox.y1.to_bits()], resources_key, nesting_depth, + // Craft patch (self-draw scope): the mask skips the forms it was set in. + forms.ids(), )); Some(Self(Rc::new(Repr { @@ -216,6 +221,7 @@ impl<'a> SoftMask<'a> { nesting_depth, device_cmyk, simulation, + forms, }))) } @@ -256,10 +262,14 @@ impl<'a> SoftMask<'a> { state, self.0.nesting_depth, ); - draw_form_xobject(&self.0.parent_resources, &self.0.group, &mut ctx, device); + with_forms_drawing(&self.0.forms, || draw_form_xobject(&self.0.parent_resources, &self.0.group, &mut ctx, device)); } /// Interpret the contents of the mask into the given device. + /// + /// Craft patch (self-draw scope): the contents draw inside the forms the mask was set in, + /// so a device may interpret the mask while it draws any form: a mask that draws that form + /// draws it, and one that draws a form it was set in skips that form. pub fn interpret(&self, device: &mut impl Device<'a>) { let state = State::new(self.0.root_transform); let mut ctx = Context::new_with( @@ -272,7 +282,7 @@ impl<'a> SoftMask<'a> { self.0.nesting_depth, ); ctx.luminosity_in_device_cmyk = self.0.luminosity_in_device_cmyk; - draw_form_xobject(&self.0.parent_resources, &self.0.group, &mut ctx, device); + with_forms_drawing(&self.0.forms, || draw_form_xobject(&self.0.parent_resources, &self.0.group, &mut ctx, device)); } /// Return the object identifier of the mask. From b7b02ef2cddfddb851b178fb02ca99cfb77e43f8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:52:30 -0800 Subject: [PATCH 02/31] hayro-interpret: American spelling in the self-draw test helper's comment --- vendor/hayro-interpret/SOURCE.json | 2 +- vendor/hayro-interpret/src/self_draw_tests.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/vendor/hayro-interpret/SOURCE.json b/vendor/hayro-interpret/SOURCE.json index 71924358dd..31ea9d136f 100644 --- a/vendor/hayro-interpret/SOURCE.json +++ b/vendor/hayro-interpret/SOURCE.json @@ -410,7 +410,7 @@ "path": "src/self_draw_tests.rs", "source_sha256": null, "source_git_blob": null, - "sha256": "58930501e624b86fd45ddc82e464a959d989d6ef94eb7e62f8f8ad24c78ec8ec" + "sha256": "84263a0741b19879104fa57fad43cc80c33ba902ba25fa2b9356fffed2e46202" }, { "path": "src/shading.rs", diff --git a/vendor/hayro-interpret/src/self_draw_tests.rs b/vendor/hayro-interpret/src/self_draw_tests.rs index e28b481f06..6cc6c2cb26 100644 --- a/vendor/hayro-interpret/src/self_draw_tests.rs +++ b/vendor/hayro-interpret/src/self_draw_tests.rs @@ -58,7 +58,7 @@ fn mask_group(resources: &str, content: &str) -> String { ) } -/// A coloured tiling pattern whose cell draws `content` with `resources`. +/// A colored tiling pattern whose cell draws `content` with `resources`. fn tiling(resources: &str, content: &str) -> String { stream( &format!( From e04db345243b7009f88bca88ad331e399b0f50aa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:02:45 -0800 Subject: [PATCH 03/31] craft-mesh-ops: tangents stay finite and split vertices with different frames compute_tangents now gives every triangle corner the frame MikkTSpace computed for it. A vertex whose corners get different frames (UVs mirrored across it) is split into one copy per frame, with positions, normals, UVs and colors copied. Tangents are always finite and unit length. A non-finite normal counts as +Y. Meshes with an index out of range, a non-finite or out-of-range (1e-6 to 1e6) position or UV, more than 2,048 triangles around one vertex, or corner welding past 2^27 comparisons skip MikkTSpace. The per-vertex fallback works in f64, sets the bitangent sign the way MikkTSpace does, and skips a triangle only when its UV edges are nearly parallel relative to their lengths, so small UV ranges still give a direction. --- crates/mesh-ops/README.md | 4 + crates/mesh-ops/src/mesh.rs | 376 +++++++++++++++++++++++++++++++----- 2 files changed, 335 insertions(+), 45 deletions(-) diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md index d7b1852d6a..71acaeb045 100644 --- a/crates/mesh-ops/README.md +++ b/crates/mesh-ops/README.md @@ -10,6 +10,10 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form - **Normals and tangents.** Smooth normals are area weighted. Tangents come from MikkTSpace, which glTF 2.0 recommends for meshes without tangents (): `w` holds the bitangent sign. + A vertex whose triangles have different tangent frames (mirrored UVs) is split into one copy + per frame. A mesh with more than 2,048 triangles around one vertex, or with non-finite + positions or UVs, or with positions or UVs above 1e6 or below 1e-6 in magnitude, gets per-vertex tangents from UV gradients instead of MikkTSpace. Tangents + are always finite; a non-finite normal counts as +Y. - **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 diff --git a/crates/mesh-ops/src/mesh.rs b/crates/mesh-ops/src/mesh.rs index 77c993d3c6..4abb157bd3 100644 --- a/crates/mesh-ops/src/mesh.rs +++ b/crates/mesh-ops/src/mesh.rs @@ -1,6 +1,6 @@ //! The internal triangle mesh. -use glam::{Vec2, Vec3, Vec4}; +use glam::{DVec3, Vec2, Vec3, Vec4}; use crate::{GeomError, Result}; @@ -51,6 +51,24 @@ pub struct Mesh { /// Hard cap on mesh size accepted from files (triangles). pub const MAX_TRIANGLES: usize = 20_000_000; +/// Positions and UVs go to MikkTSpace only when their largest magnitude lies between the +/// reciprocal of this and this, so edge lengths, cross products and their products with UVs +/// neither overflow nor underflow in `f32`. Other meshes get the `f64` per-vertex tangents. +const SAFE_MAGNITUDE: f32 = 1e6; + +/// Most triangles around one vertex (as MikkTSpace welds vertices) for which tangents come from +/// MikkTSpace. It visits the triangles around a vertex recursively, one call per triangle, so a +/// larger fan could exhaust the stack; such meshes get the per-vertex fallback. This crate's own +/// value. +pub const MAX_MIKKTSPACE_VALENCE: usize = 2_048; + +/// Most comparisons MikkTSpace may make welding corners, for which tangents come from it. It +/// compares each corner with the corners before it at the same position until one has the same +/// normal and UV, so `k` corners at one position can cost about `k²` comparisons; the sum of `k²` +/// over the positions stays within this. This crate's own value: the 6,144 corners at the pole of +/// a sphere with 2,048 segments take about 3.8e7. +pub const MAX_MIKKTSPACE_WELD_WORK: u64 = 1 << 27; + impl Mesh { pub fn triangle_count(&self) -> usize { self.indices.len() / 3 @@ -216,51 +234,91 @@ impl Mesh { self.normals = normals.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(); } - /// MikkTSpace tangents (falls back to per-triangle tangents if generation fails). + /// MikkTSpace tangents (falls back to per-vertex tangents if generation fails). A mesh with + /// an index out of range, a non-finite position or UV, a position or UV with a magnitude + /// outside 1e-6 to 1e6 (zero is fine), only degenerate triangles, more than + /// [`MAX_MIKKTSPACE_VALENCE`] triangles around one vertex or corners whose welding would take + /// more than [`MAX_MIKKTSPACE_WELD_WORK`] comparisons does not go to MikkTSpace. Missing + /// normals are computed and missing UVs are zero. A non-finite normal counts as +Y. + /// + /// MikkTSpace gives each triangle corner its own tangent frame. A vertex whose corners get + /// different frames (UVs mirrored across it) is split: every further frame gets a copy of + /// the vertex, and the corners with that frame use the copy. A copy whose index would not + /// fit in `u32` is not made, and those corners keep the first frame. 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() { + let n = self.positions.len(); + if self.normals.len() != n { self.compute_normals(); } - if self.uvs.len() != self.positions.len() { - self.uvs = vec![Vec2::ZERO; self.positions.len()]; + if self.uvs.len() != n { + self.uvs = vec![Vec2::ZERO; n]; } - // 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 }); - } - } + let normals: Vec = self.normals.iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(); + let mut corners = vec![Vec4::ZERO; self.indices.len()]; - 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; + // mikktspace crashes (out-of-bounds) when every triangle is degenerate; skip it then. Its + // callbacks read a missing vertex as the origin, which the degenerate check cannot see, + // so an index past the last vertex skips it too. + let usable = in_safe_range(self.positions.iter().flat_map(|p| p.to_array())) + && in_safe_range(self.uvs.iter().flat_map(|uv| uv.to_array())) + && self.indices.iter().all(|&i| (i as usize) < n); + let mut g = Mikk { positions: &self.positions, normals: &normals, uvs: &self.uvs, indices: &self.indices, corners: &mut corners }; + if !(usable && !g.all_triangles_degenerate() && g.affordable() && mikktspace::generate_tangents(&mut g)) { + let per_vertex = simple_tangents(&self.positions, &normals, &self.uvs, &self.indices); + for (corner, v) in corners.iter_mut().zip(&self.indices) { + *corner = per_vertex.get(*v as usize).copied().unwrap_or(Vec4::new(1.0, 0.0, 0.0, 1.0)); } + } - 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; + // Orthonormalize a tangent against the normal of vertex `v`; repair degenerate results. + let frame = |v: usize, t: Vec4| { + let n = normals.get(v).copied().unwrap_or(Vec3::Y); + let d = t.truncate(); + let o = (d - n * n.dot(d)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()); + o.extend(if t.w < 0.0 { -1.0 } else { 1.0 }) + }; + for (t, v) in corners.iter_mut().zip(&self.indices) { + *t = frame(*v as usize, *t); + } + + // One tangent per vertex: the first corner's frame, and a copy of the vertex for each + // other frame its corners have. Corners that share a frame get bit-identical tangents. + let bits = |t: Vec4| t.to_array().map(f32::to_bits); + let mut tangents = vec![None::; n]; + let mut copies: Vec<(u32, Vec4)> = Vec::new(); + let mut copy_of: std::collections::HashMap<(u32, [u32; 4]), u32> = std::collections::HashMap::new(); + for (index, &t) in self.indices.iter_mut().zip(&corners) { + let v = *index; + let Some(slot) = tangents.get_mut(v as usize) else { continue }; + match slot { + None => *slot = Some(t), + Some(first) if bits(*first) == bits(t) => {} + Some(_) => { + if let Some(©) = copy_of.get(&(v, bits(t))) { + *index = copy; + } else if let Ok(copy) = u32::try_from(n + copies.len()) { + copies.push((v, t)); + copy_of.insert((v, bits(t)), copy); + *index = copy; + } } } } - self.tangents = tangents.into_iter().map(|t| t.try_normalize().unwrap_or(Vec3::X).extend(1.0)).collect(); + // A vertex no triangle uses gets +X made perpendicular to its normal. + let mut out: Vec = tangents.iter().enumerate().map(|(v, t)| t.unwrap_or_else(|| frame(v, Vec4::new(1.0, 0.0, 0.0, 1.0)))).collect(); + out.extend(copies.iter().map(|(_, t)| *t)); + let has_colors = self.colors.len() == n; + for &(v, _) in &copies { + let v = v as usize; + self.positions.push(self.positions.get(v).copied().unwrap_or_default()); + self.normals.push(self.normals.get(v).copied().unwrap_or(Vec3::Y)); + self.uvs.push(self.uvs.get(v).copied().unwrap_or_default()); + if has_colors { + self.colors.push(self.colors.get(v).copied().unwrap_or(Vec4::ONE)); + } + } + self.tangents = out; } /// The UV tiles material `m` covers: integer parts of its triangles' UV centroids (v down), @@ -449,38 +507,145 @@ impl Mesh { } } +/// Per-vertex tangents from the UV gradients of the triangles around each vertex: the fallback +/// when MikkTSpace does not run or fails. `w` is -1 where the summed direction up the image +/// (toward smaller v) lies against `cross(normal, tangent)`, and +1 otherwise, as MikkTSpace +/// sets it. Edges, UV differences and sums are taken in `f64`, and a triangle is skipped when +/// its UV edges are nearly parallel relative to their lengths, so tiny UV differences still +/// set the direction. +fn simple_tangents(positions: &[Vec3], normals: &[Vec3], uvs: &[Vec2], indices: &[u32]) -> Vec { + let mut sums = vec![(DVec3::ZERO, DVec3::ZERO); positions.len()]; + for &[a, b, c] in 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)) = (positions.get(a), positions.get(b), positions.get(c)) else { continue }; + let (Some(ua), Some(ub), Some(uc)) = (uvs.get(a), uvs.get(b), uvs.get(c)) else { continue }; + let (e1, e2) = (pb.as_dvec3() - pa.as_dvec3(), pc.as_dvec3() - pa.as_dvec3()); + let (d1, d2) = (ub.as_dvec2() - ua.as_dvec2(), uc.as_dvec2() - ua.as_dvec2()); + let determinant = d1.x * d2.y - d2.x * d1.y; + if !determinant.is_finite() || determinant.abs() <= 1e-12 * d1.length() * d2.length() { + continue; + } + + let tangent = (e1 * d2.y - e2 * d1.y) / determinant; + // The direction in which v shrinks, which is up the image. + let up = (e1 * d2.x - e2 * d1.x) / determinant; + if !tangent.is_finite() || !up.is_finite() { + continue; + } + for v in [a, b, c] { + if let Some((t, u)) = sums.get_mut(v) { + *t += tangent; + *u += up; + } + } + } + + sums.into_iter() + .enumerate() + .map(|(v, (t, up))| { + let t = t.try_normalize().map(|t| t.as_vec3()).filter(|t| t.is_finite()).unwrap_or(Vec3::X); + let up = up.try_normalize().map(|up| up.as_vec3()).unwrap_or(Vec3::ZERO); + let n = normals.get(v).copied().unwrap_or(Vec3::Y); + let w = if n.cross(t).dot(up) < 0.0 { -1.0 } else { 1.0 }; + t.extend(w) + }) + .collect() +} + +/// Whether the values are finite and their largest magnitude is zero or lies between the +/// reciprocal of [`SAFE_MAGNITUDE`] and it. +fn in_safe_range(values: impl Iterator) -> bool { + let mut largest = 0.0_f32; + for c in values { + if !c.is_finite() { + return false; + } + largest = largest.max(c.abs()); + } + largest == 0.0 || (1.0 / SAFE_MAGNITUDE..=SAFE_MAGNITUDE).contains(&largest) +} + +/// The arrays MikkTSpace reads, and the tangent of every triangle corner it writes. struct Mikk<'a> { - mesh: &'a mut Mesh, + positions: &'a [Vec3], + normals: &'a [Vec3], + uvs: &'a [Vec2], + indices: &'a [u32], + corners: &'a mut [Vec4], } impl Mikk<'_> { fn vi(&self, face: usize, vert: usize) -> usize { - self.mesh.indices.get(face * 3 + vert).copied().unwrap_or(0) as usize + self.indices.get(face * 3 + vert).copied().unwrap_or(0) as usize + } + + /// True when the mesh has triangles and every one of them has two corners at the same + /// position as MikkTSpace gets it. + fn all_triangles_degenerate(&self) -> bool { + use mikktspace::Geometry; + self.num_faces() > 0 + && (0..self.num_faces()).all(|f| { + let p = |v| self.position(f, v); + p(0) == p(1) || p(0) == p(2) || p(1) == p(2) + }) + } + + /// Whether MikkTSpace's work on this input stays bounded: at most + /// [`MAX_MIKKTSPACE_VALENCE`] triangles around one vertex, which it visits recursively, one + /// call per triangle, and at most [`MAX_MIKKTSPACE_WELD_WORK`] for welding. + fn affordable(&self) -> bool { + let (valence, weld_work) = self.welding(); + valence <= MAX_MIKKTSPACE_VALENCE && weld_work <= MAX_MIKKTSPACE_WELD_WORK + } + + /// The most triangles that share one vertex as MikkTSpace sees it, and the sum of the squared + /// corner counts of its positions. It welds corners whose position, normal and UV, as this + /// type passes them, are equal (0 and -0 alike). + fn welding(&self) -> (usize, u64) { + use mikktspace::Geometry; + let bits = |x: f32| if x == 0.0 { 0 } else { x.to_bits() }; + let mut count: std::collections::HashMap<[u32; 8], usize> = std::collections::HashMap::new(); + let mut at_position: std::collections::HashMap<[u32; 3], u64> = std::collections::HashMap::new(); + let (mut most, mut work) = (0, 0u64); + for face in 0..self.num_faces() { + for vert in 0..3 { + let ([px, py, pz], [nx, ny, nz], [u, v]) = (self.position(face, vert), self.normal(face, vert), self.tex_coord(face, vert)); + let c = count.entry([px, py, pz, nx, ny, nz, u, v].map(bits)).or_insert(0); + *c += 1; + most = most.max(*c); + // k² grows by 2k + 1 with the (k + 1)th corner. + let k = at_position.entry([px, py, pz].map(bits)).or_insert(0); + work = work.saturating_add(k.saturating_mul(2).saturating_add(1)); + *k += 1; + } + } + (most, work) } } impl mikktspace::Geometry for Mikk<'_> { fn num_faces(&self) -> usize { - self.mesh.indices.len() / 3 + self.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() + (self.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() + self.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] + // v negated, the bitangent `cross(N, T) * w` points up the image, as glTF requires. + // Negating keeps differences in v that `1 - v` would round away. + let uv = self.uvs.get(self.vi(face, vert)).copied().unwrap_or_default(); + [uv.x, -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) { + // One tangent per corner: corners of a vertex can get different frames. + if let Some(t) = self.corners.get_mut(face * 3 + vert) { *t = Vec4::from_array(tangent); } } @@ -514,6 +679,127 @@ mod tests { assert_eq!(m.triangles_of(0).collect::>(), vec![0, 1]); } + #[test] + fn a_vertex_with_mirrored_frames_is_split() { + // Triangle (0, 1, 2) has u growing with x. Triangle (1, 3, 2) has the opposite UV + // orientation, so vertices 1 and 2 need one tangent frame for each triangle. + let corners = [Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(1.0, 1.0, 0.0)]; + let m = Mesh::from_parts( + corners.to_vec(), + None, + vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(0.0, 0.0), Vec2::new(1.0, 2.0)], + vec![0, 1, 2, 1, 3, 2], + "Default", + ) + .unwrap(); + assert_eq!(m.positions.len(), 6, "vertices 1 and 2 each get a copy"); + assert_eq!((m.normals.len(), m.uvs.len(), m.tangents.len()), (6, 6, 6)); + let signs = |t: usize| m.indices[t * 3..t * 3 + 3].iter().map(|&i| m.tangents[i as usize].w).collect::>(); + assert!(signs(0).iter().all(|w| *w == signs(0)[0]), "{:?}", signs(0)); + assert!(signs(1).iter().all(|w| *w == signs(1)[0]), "{:?}", signs(1)); + assert_ne!(signs(0)[0], signs(1)[0]); + let originals = [0, 1, 2, 3, 1, 2]; + for (i, p) in m.positions.iter().enumerate() { + assert_eq!(*p, corners[originals[i]], "vertex {i}"); + } + m.validate().unwrap(); + } + + #[test] + fn split_vertices_keep_their_colors() { + let mut m = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(1.0, 1.0, 0.0)], + uvs: vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(0.0, 0.0), Vec2::new(1.0, 2.0)], + colors: (0..4).map(|i| Vec4::splat(i as f32 / 4.0)).collect(), + indices: vec![0, 1, 2, 1, 3, 2], + materials: vec!["Default".into()], + submeshes: vec![SubMesh { name: "Default".into(), material: 0, start: 0, count: 6 }], + ..Mesh::default() + }; + m.compute_tangents(); + assert_eq!(m.positions.len(), 6); + assert_eq!(m.colors, [0, 1, 2, 3, 1, 2].map(|i| Vec4::splat(i as f32 / 4.0))); + m.validate().unwrap(); + } + + #[test] + fn tangents_stay_finite_for_non_finite_input() { + let mut m = quad(); + m.normals[0] = Vec3::NAN; + m.normals[1] = Vec3::splat(f32::INFINITY); + m.compute_tangents(); + assert!(m.tangents.iter().all(|t| t.is_finite() && (t.truncate().length() - 1.0).abs() < 1e-4), "{:?}", m.tangents); + + let mut m = quad(); + m.uvs[2] = Vec2::new(f32::NAN, 0.0); + m.positions[1].x = f32::INFINITY; + m.compute_tangents(); + assert!(m.tangents.iter().all(|t| t.is_finite()), "{:?}", m.tangents); + } + + #[test] + fn far_and_tiny_triangles_keep_their_tangent() { + for edge in [1e-20_f32, 1e20] { + let m = Mesh::from_parts( + vec![Vec3::ZERO, Vec3::new(edge, 0.0, 0.0), Vec3::new(0.0, edge, 0.0)], + Some(vec![Vec3::Z; 3]), + vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(0.0, 0.0)], + vec![0, 1, 2], + "Default", + ) + .unwrap(); + for t in &m.tangents { + assert!((t.truncate() - Vec3::X).length() < 1e-4 && t.w == 1.0, "edge {edge}: {t:?}"); + } + } + } + + #[test] + fn fallback_tangents_agree_with_mikktspace() { + // Each mesh is the quad with its UVs flipped one way; the fallback sets the same + // direction and bitangent sign MikkTSpace does. + for flip in [Vec2::new(1.0, 1.0), Vec2::new(-1.0, 1.0), Vec2::new(1.0, -1.0)] { + let mut m = quad(); + for uv in &mut m.uvs { + *uv = Vec2::new(uv.x * flip.x, uv.y * flip.y); + } + m.compute_tangents(); + let fallback = simple_tangents(&m.positions, &m.normals, &m.uvs, &m.indices); + assert_eq!(m.tangents.len(), 4); + for (mikk, simple) in m.tangents.iter().zip(&fallback) { + assert!((mikk.truncate() - simple.truncate()).length() < 1e-4, "flip {flip}: {mikk:?} {simple:?}"); + assert_eq!(mikk.w, simple.w, "flip {flip}"); + } + } + } + + #[test] + fn fallback_tangents_use_tiny_uv_differences() { + // u grows with y and v with x, over a range of 1e-7: the UV determinant is -1e-14. + let s = 1e-7_f32; + let positions = [Vec3::ZERO, Vec3::X, Vec3::Y]; + let uvs = [Vec2::ZERO, Vec2::new(0.0, s), Vec2::new(s, 0.0)]; + for t in simple_tangents(&positions, &[Vec3::Z; 3], &uvs, &[0, 1, 2]) { + assert!((t.truncate() - Vec3::Y).length() < 1e-4, "{t:?}"); + } + } + + #[test] + fn a_fan_around_one_vertex_skips_mikktspace() { + for (k, affordable) in [(MAX_MIKKTSPACE_VALENCE, true), (MAX_MIKKTSPACE_VALENCE + 1, false)] { + let mut positions = vec![Vec3::ZERO]; + for i in 0..=k { + let a = i as f32 / k as f32 * std::f32::consts::TAU; + positions.push(Vec3::new(a.cos(), a.sin(), 0.0)); + } + let indices: Vec = (0..k as u32).flat_map(|i| [0, i + 1, i + 2]).collect(); + let (normals, uvs) = (vec![Vec3::Z; positions.len()], vec![Vec2::ZERO; positions.len()]); + let mut corners = vec![Vec4::ZERO; indices.len()]; + let g = Mikk { positions: &positions, normals: &normals, uvs: &uvs, indices: &indices, corners: &mut corners }; + assert_eq!(g.affordable(), affordable, "{k} triangles"); + } + } + #[test] fn wire_edges_leave_out_polygon_diagonals() { let mut m = quad(); From 5bbddb458d9bca006689251fbab2ceebac8f969c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:20:42 -0800 Subject: [PATCH 04/31] Preserve tangent frames around collapsed mesh faces --- crates/mesh-ops/README.md | 3 +- crates/mesh-ops/src/mesh.rs | 225 ++++++++++++++++++++++++++++++++---- 2 files changed, 206 insertions(+), 22 deletions(-) diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md index 71acaeb045..c94ddb10f2 100644 --- a/crates/mesh-ops/README.md +++ b/crates/mesh-ops/README.md @@ -11,7 +11,8 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form glTF 2.0 recommends for meshes without tangents (): `w` holds the bitangent sign. A vertex whose triangles have different tangent frames (mirrored UVs) is split into one copy - per frame. A mesh with more than 2,048 triangles around one vertex, or with non-finite + per frame. Faces with coincident corners stay in the mesh and reuse shared vertex frames when + available. MikkTSpace omits those faces. A mesh with more than 2,048 noncollapsed triangles around one vertex, or with non-finite positions or UVs, or with positions or UVs above 1e6 or below 1e-6 in magnitude, gets per-vertex tangents from UV gradients instead of MikkTSpace. Tangents are always finite; a non-finite normal counts as +Y. - **UV unwrapping.** `unwrap::auto_unwrap` makes a non-overlapping layout per material, splitting diff --git a/crates/mesh-ops/src/mesh.rs b/crates/mesh-ops/src/mesh.rs index 4abb157bd3..1b7dbb7cf1 100644 --- a/crates/mesh-ops/src/mesh.rs +++ b/crates/mesh-ops/src/mesh.rs @@ -237,14 +237,16 @@ impl Mesh { /// MikkTSpace tangents (falls back to per-vertex tangents if generation fails). A mesh with /// an index out of range, a non-finite position or UV, a position or UV with a magnitude /// outside 1e-6 to 1e6 (zero is fine), only degenerate triangles, more than - /// [`MAX_MIKKTSPACE_VALENCE`] triangles around one vertex or corners whose welding would take - /// more than [`MAX_MIKKTSPACE_WELD_WORK`] comparisons does not go to MikkTSpace. Missing + /// [`MAX_MIKKTSPACE_VALENCE`] noncollapsed triangles around one vertex or noncollapsed corners + /// whose welding would take more than [`MAX_MIKKTSPACE_WELD_WORK`] comparisons does not go to MikkTSpace. Missing /// normals are computed and missing UVs are zero. A non-finite normal counts as +Y. /// /// MikkTSpace gives each triangle corner its own tangent frame. A vertex whose corners get /// different frames (UVs mirrored across it) is split: every further frame gets a copy of /// the vertex, and the corners with that frame use the copy. A copy whose index would not /// fit in `u32` is not made, and those corners keep the first frame. + /// Faces with coincident corners stay in the mesh but are omitted from MikkTSpace. Their + /// corners reuse a generated frame for the same vertex when one is available. pub fn compute_tangents(&mut self) { let n = self.positions.len(); if self.normals.len() != n { @@ -256,18 +258,25 @@ impl Mesh { let normals: Vec = self.normals.iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(); let mut corners = vec![Vec4::ZERO; self.indices.len()]; - // mikktspace crashes (out-of-bounds) when every triangle is degenerate; skip it then. Its - // callbacks read a missing vertex as the origin, which the degenerate check cannot see, - // so an index past the last vertex skips it too. + // MikkTSpace receives noncollapsed faces with valid indices and bounded attributes. let usable = in_safe_range(self.positions.iter().flat_map(|p| p.to_array())) && in_safe_range(self.uvs.iter().flat_map(|uv| uv.to_array())) && self.indices.iter().all(|&i| (i as usize) < n); - let mut g = Mikk { positions: &self.positions, normals: &normals, uvs: &self.uvs, indices: &self.indices, corners: &mut corners }; - if !(usable && !g.all_triangles_degenerate() && g.affordable() && mikktspace::generate_tangents(&mut g)) { + let mut g = Mikk { + positions: &self.positions, + normals: &normals, + uvs: &self.uvs, + indices: &self.indices, + corners: &mut corners, + faces: if usable { Mikk::noncollapsed_faces(&self.positions, &self.indices) } else { None }, + }; + if !(usable && g.face_count() != 0 && g.affordable() && mikktspace::generate_tangents(&mut g)) { let per_vertex = simple_tangents(&self.positions, &normals, &self.uvs, &self.indices); for (corner, v) in corners.iter_mut().zip(&self.indices) { *corner = per_vertex.get(*v as usize).copied().unwrap_or(Vec4::new(1.0, 0.0, 0.0, 1.0)); } + } else if g.faces.is_some() { + g.fill_collapsed_corners(); } // Orthonormalize a tangent against the normal of vertex `v`; repair degenerate results. @@ -572,22 +581,93 @@ struct Mikk<'a> { uvs: &'a [Vec2], indices: &'a [u32], corners: &'a mut [Vec4], + faces: Option>, } impl Mikk<'_> { - fn vi(&self, face: usize, vert: usize) -> usize { - self.indices.get(face * 3 + vert).copied().unwrap_or(0) as usize + fn face_count(&self) -> usize { + self.faces.as_ref().map_or(self.indices.len() / 3, Vec::len) } - /// True when the mesh has triangles and every one of them has two corners at the same - /// position as MikkTSpace gets it. - fn all_triangles_degenerate(&self) -> bool { - use mikktspace::Geometry; - self.num_faces() > 0 - && (0..self.num_faces()).all(|f| { - let p = |v| self.position(f, v); - p(0) == p(1) || p(0) == p(2) || p(1) == p(2) - }) + fn original_face(&self, face: usize) -> usize { + self.faces.as_ref().map_or(face, |faces| faces.get(face).copied().unwrap_or(0)) + } + + fn vi(&self, face: usize, vert: usize) -> usize { + let original = self.original_face(face); + self.indices.get(original * 3 + vert).copied().unwrap_or(0) as usize + } + + fn noncollapsed_faces(positions: &[Vec3], indices: &[u32]) -> Option> { + let mut remap: Option> = None; + for (face, vertices) in indices.as_chunks::<3>().0.iter().enumerate() { + let kept = match vertices.map(|vertex| positions.get(vertex as usize)) { + [Some(a), Some(b), Some(c)] => a != b && a != c && b != c, + _ => false, + }; + if kept { + if let Some(faces) = &mut remap { + faces.push(face); + } + } else if remap.is_none() { + remap = Some((0..face).collect()); + } + } + remap + } + + fn fill_collapsed_corners(&mut self) { + let bits = |value: f32| if value == 0.0 { 0 } else { value.to_bits() }; + let attributes = |index: usize| { + let (p, n, uv) = (self.positions[index], self.normals[index], self.uvs[index]); + [p.x, p.y, p.z, n.x, n.y, n.z, uv.x, uv.y].map(bits) + }; + let mut first = vec![None; self.positions.len()]; + for &face in self.faces.as_deref().unwrap_or(&[]) { + for vertex in 0..3 { + let corner = face * 3 + vertex; + let index = self.indices[corner] as usize; + first[index].get_or_insert(self.corners[corner]); + } + } + let generated_count = self.face_count() * 3; + let index_generated = generated_count <= self.indices.len() - generated_count; + let mut welded: std::collections::HashMap<[u32; 8], Option> = if index_generated { + std::collections::HashMap::new() + } else { + self.indices + .iter() + .zip(self.corners.iter()) + .filter(|&(index, tangent)| *tangent == Vec4::ZERO && first[*index as usize].is_none()) + .map(|(&index, _)| (attributes(index as usize), None)) + .collect() + }; + if index_generated || !welded.is_empty() { + for &face in self.faces.as_deref().unwrap_or(&[]) { + for vertex in 0..3 { + let corner = face * 3 + vertex; + let key = attributes(self.indices[corner] as usize); + if index_generated { + welded.entry(key).or_insert(Some(self.corners[corner])); + } else if let Some(frame) = welded.get_mut(&key) { + frame.get_or_insert(self.corners[corner]); + } + } + } + } + for (&index, tangent) in self.indices.iter().zip(self.corners.iter_mut()) { + if *tangent == Vec4::ZERO + && let Some(Some(frame)) = first.get(index as usize) + { + *tangent = *frame; + } else if *tangent == Vec4::ZERO + && let Some(Some(frame)) = welded.get(&attributes(index as usize)) + { + *tangent = *frame; + } else if *tangent == Vec4::ZERO { + *tangent = Vec4::new(1.0, 0.0, 0.0, -1.0); + } + } } /// Whether MikkTSpace's work on this input stays bounded: at most @@ -625,7 +705,7 @@ impl Mikk<'_> { impl mikktspace::Geometry for Mikk<'_> { fn num_faces(&self) -> usize { - self.indices.len() / 3 + self.face_count() } fn num_vertices_of_face(&self, _face: usize) -> usize { 3 @@ -645,7 +725,8 @@ impl mikktspace::Geometry for Mikk<'_> { } fn set_tangent_encoded(&mut self, tangent: [f32; 4], face: usize, vert: usize) { // One tangent per corner: corners of a vertex can get different frames. - if let Some(t) = self.corners.get_mut(face * 3 + vert) { + let original = self.original_face(face); + if let Some(t) = self.corners.get_mut(original * 3 + vert) { *t = Vec4::from_array(tangent); } } @@ -653,6 +734,101 @@ impl mikktspace::Geometry for Mikk<'_> { #[cfg(test)] mod tests { + #[test] + fn unmatched_collapsed_corners_keep_the_mikktspace_default_frame() { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z, Vec3::Z, Vec3::Z + Vec3::X], + normals: vec![Vec3::Z; 6], + uvs: vec![Vec2::ZERO, Vec2::X, Vec2::Y, Vec2::ZERO, Vec2::X, Vec2::Y], + indices: vec![0, 1, 2, 3, 4, 5], + ..Mesh::default() + }; + mesh.compute_tangents(); + for corner in 3..6 { + assert_eq!(mesh.tangents[mesh.indices[corner] as usize], Vec4::new(1.0, 0.0, 0.0, -1.0)); + } + } + + #[test] + fn collapsed_corners_reuse_frames_from_matching_vertex_attributes() { + for extra_valid_face in [false, true] { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::ZERO], + normals: vec![Vec3::Z; 4], + uvs: vec![Vec2::ZERO, Vec2::Y, Vec2::X, Vec2::ZERO], + indices: vec![0, 1, 2, 3, 3, 1], + ..Mesh::default() + }; + if extra_valid_face { + mesh.indices.extend_from_slice(&[0, 1, 2]); + } + mesh.compute_tangents(); + assert_eq!(mesh.tangents[mesh.indices[0] as usize], mesh.tangents[mesh.indices[3] as usize]); + } + } + + #[test] + fn collapsed_faces_do_not_force_valid_corner_frames_into_fallback() { + let angle = 0.1f32; + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(angle.cos(), angle.sin(), 0.0), Vec3::new(-angle.sin(), angle.cos(), 0.0)], + normals: vec![Vec3::Z; 5], + uvs: vec![Vec2::ZERO, Vec2::X, Vec2::Y, Vec2::X, Vec2::Y], + indices: vec![0, 1, 2, 0, 3, 4], + ..Mesh::default() + }; + for _ in 0..=MAX_MIKKTSPACE_VALENCE { + let duplicate = mesh.positions.len() as u32; + mesh.positions.push(Vec3::ZERO); + mesh.normals.push(Vec3::Z); + mesh.uvs.push(Vec2::ZERO); + mesh.indices.extend_from_slice(&[0, duplicate, 1]); + } + mesh.compute_tangents(); + assert_ne!(mesh.indices[0], mesh.indices[3]); + assert_eq!(mesh.tangents[mesh.indices[0] as usize].w, mesh.tangents[mesh.indices[3] as usize].w); + } + + #[test] + fn collapsed_corners_reuse_shared_generated_frames() { + let angle = 0.1f32; + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(angle.cos(), angle.sin(), 0.0), Vec3::new(-angle.sin(), angle.cos(), 0.0)], + normals: vec![Vec3::Z; 5], + uvs: vec![Vec2::ZERO, Vec2::Y, Vec2::X, Vec2::Y, Vec2::X], + indices: vec![0, 0, 1, 0, 1, 2, 0, 3, 4], + ..Mesh::default() + }; + mesh.compute_tangents(); + assert_eq!(mesh.positions.len(), 6); + assert_eq!(mesh.indices[0], mesh.indices[3]); + assert_eq!(mesh.indices[1], mesh.indices[3]); + assert_eq!(mesh.indices[2], mesh.indices[4]); + assert_ne!(mesh.indices[3], mesh.indices[6]); + assert!(mesh.tangents.iter().all(|tangent| tangent.is_finite())); + } + + #[test] + fn same_handed_corner_frames_keep_distinct_directions() { + let angle = 0.1f32; + let x = Vec3::new(angle.cos(), angle.sin(), 0.0); + let y = Vec3::new(-angle.sin(), angle.cos(), 0.0); + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, x, y], + normals: vec![Vec3::Z; 5], + uvs: vec![Vec2::ZERO, Vec2::X, Vec2::Y, Vec2::X, Vec2::Y], + indices: vec![0, 1, 2, 0, 3, 4], + ..Mesh::default() + }; + mesh.compute_tangents(); + let first = mesh.indices[0] as usize; + let second = mesh.indices[3] as usize; + assert_ne!(first, second); + assert_eq!(mesh.tangents[first].w, mesh.tangents[second].w); + assert!(mesh.tangents[first].truncate().dot(mesh.tangents[second].truncate()) > 0.99); + assert!((mesh.tangents[first].truncate() - mesh.tangents[second].truncate()).length() > 0.05); + } + use super::*; fn quad() -> Mesh { @@ -795,7 +971,14 @@ mod tests { let indices: Vec = (0..k as u32).flat_map(|i| [0, i + 1, i + 2]).collect(); let (normals, uvs) = (vec![Vec3::Z; positions.len()], vec![Vec2::ZERO; positions.len()]); let mut corners = vec![Vec4::ZERO; indices.len()]; - let g = Mikk { positions: &positions, normals: &normals, uvs: &uvs, indices: &indices, corners: &mut corners }; + let g = Mikk { + positions: &positions, + normals: &normals, + uvs: &uvs, + indices: &indices, + corners: &mut corners, + faces: Mikk::noncollapsed_faces(&positions, &indices), + }; assert_eq!(g.affordable(), affordable, "{k} triangles"); } } From 20a7c6d6084bf6063aa0f0ea62cedd8bb99273f9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 19:07:36 -0800 Subject: [PATCH 05/31] Preserve tangent frames across fallback regions --- crates/mesh-ops/README.md | 4 +- crates/mesh-ops/src/mesh.rs | 619 +++++++++++++++++++++++++++--- crates/mesh-ops/src/primitives.rs | 25 +- 3 files changed, 590 insertions(+), 58 deletions(-) diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md index c94ddb10f2..116923be9d 100644 --- a/crates/mesh-ops/README.md +++ b/crates/mesh-ops/README.md @@ -13,7 +13,9 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form A vertex whose triangles have different tangent frames (mirrored UVs) is split into one copy per frame. Faces with coincident corners stay in the mesh and reuse shared vertex frames when available. MikkTSpace omits those faces. A mesh with more than 2,048 noncollapsed triangles around one vertex, or with non-finite - positions or UVs, or with positions or UVs above 1e6 or below 1e-6 in magnitude, gets per-vertex tangents from UV gradients instead of MikkTSpace. Tangents + positions or UVs, or with positions or UVs above 1e6 or below 1e-6 in magnitude, gets per-corner tangents from f64 UV gradients instead of MikkTSpace. + An edge-connected region containing a face whose f32 UV gradients overflow or underflow uses that fallback. + Both paths use the stored UVs. Each triangle with usable UV gradients has one handedness sign. Tangents are always finite; a non-finite normal counts as +Y. - **UV unwrapping.** `unwrap::auto_unwrap` makes a non-overlapping layout per material, splitting vertices where charts meet. diff --git a/crates/mesh-ops/src/mesh.rs b/crates/mesh-ops/src/mesh.rs index 1b7dbb7cf1..0108d9ad99 100644 --- a/crates/mesh-ops/src/mesh.rs +++ b/crates/mesh-ops/src/mesh.rs @@ -234,7 +234,7 @@ impl Mesh { self.normals = normals.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(); } - /// MikkTSpace tangents (falls back to per-vertex tangents if generation fails). A mesh with + /// MikkTSpace tangents with per-corner f64 UV-gradient fallback. A mesh with /// an index out of range, a non-finite position or UV, a position or UV with a magnitude /// outside 1e-6 to 1e6 (zero is fine), only degenerate triangles, more than /// [`MAX_MIKKTSPACE_VALENCE`] noncollapsed triangles around one vertex or noncollapsed corners @@ -247,6 +247,8 @@ impl Mesh { /// fit in `u32` is not made, and those corners keep the first frame. /// Faces with coincident corners stay in the mesh but are omitted from MikkTSpace. Their /// corners reuse a generated frame for the same vertex when one is available. + /// Edge-connected regions containing a face whose f32 UV gradients overflow or underflow use the fallback. + /// Both paths use the stored UVs. Each triangle with usable UV gradients has one handedness sign. pub fn compute_tangents(&mut self) { let n = self.positions.len(); if self.normals.len() != n { @@ -270,13 +272,38 @@ impl Mesh { corners: &mut corners, faces: if usable { Mikk::noncollapsed_faces(&self.positions, &self.indices) } else { None }, }; - if !(usable && g.face_count() != 0 && g.affordable() && mikktspace::generate_tangents(&mut g)) { - let per_vertex = simple_tangents(&self.positions, &normals, &self.uvs, &self.indices); - for (corner, v) in corners.iter_mut().zip(&self.indices) { - *corner = per_vertex.get(*v as usize).copied().unwrap_or(Vec4::new(1.0, 0.0, 0.0, 1.0)); + let affordable = usable && g.face_count() != 0 && g.affordable(); + let mut fallback_faces: Vec = if affordable { + (0..g.face_count()) + .map(|face| g.original_face(face)) + .filter(|&face| !mikk_uvs_safe(&self.positions, &self.uvs, &self.indices[face * 3..face * 3 + 3])) + .collect() + } else { + Vec::new() + }; + if !fallback_faces.is_empty() { + let welded = tangent_vertex_ids(&self.positions, &normals, &self.uvs, self.indices.iter().copied()); + let eligible = g.faces.clone().unwrap_or_else(|| (0..self.indices.len() / 3).collect()); + fallback_faces = connected_fallback_faces(&welded, &eligible, &fallback_faces); + let mut faces = g.faces.take().unwrap_or_else(|| (0..self.indices.len() / 3).collect()); + faces.retain(|face| fallback_faces.binary_search(face).is_err()); + g.faces = Some(faces); + } + if !(affordable && g.face_count() != 0 && mikktspace::generate_tangents(&mut g)) { + fill_simple_tangents(&self.positions, &normals, &self.uvs, &self.indices, g.corners); + if self.indices.iter().all(|&index| (index as usize) < n) { + g.fill_collapsed_corners(); + } + } else { + let fallback_indices: Vec = fallback_faces.iter().flat_map(|&face| self.indices[face * 3..face * 3 + 3].iter().copied()).collect(); + let fallback = simple_tangents(&self.positions, &normals, &self.uvs, &fallback_indices); + for (slot, face) in fallback_faces.into_iter().enumerate() { + let start = face * 3; + g.corners[start..start + 3].copy_from_slice(&fallback[slot * 3..slot * 3 + 3]); + } + if g.faces.is_some() { + g.fill_collapsed_corners(); } - } else if g.faces.is_some() { - g.fill_collapsed_corners(); } // Orthonormalize a tangent against the normal of vertex `v`; repair degenerate results. @@ -516,49 +543,201 @@ impl Mesh { } } -/// Per-vertex tangents from the UV gradients of the triangles around each vertex: the fallback -/// when MikkTSpace does not run or fails. `w` is -1 where the summed direction up the image -/// (toward smaller v) lies against `cross(normal, tangent)`, and +1 otherwise, as MikkTSpace -/// sets it. Edges, UV differences and sums are taken in `f64`, and a triangle is skipped when -/// its UV edges are nearly parallel relative to their lengths, so tiny UV differences still -/// set the direction. -fn simple_tangents(positions: &[Vec3], normals: &[Vec3], uvs: &[Vec2], indices: &[u32]) -> Vec { - let mut sums = vec![(DVec3::ZERO, DVec3::ZERO); positions.len()]; - for &[a, b, c] in 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)) = (positions.get(a), positions.get(b), positions.get(c)) else { continue }; - let (Some(ua), Some(ub), Some(uc)) = (uvs.get(a), uvs.get(b), uvs.get(c)) else { continue }; - let (e1, e2) = (pb.as_dvec3() - pa.as_dvec3(), pc.as_dvec3() - pa.as_dvec3()); - let (d1, d2) = (ub.as_dvec2() - ua.as_dvec2(), uc.as_dvec2() - ua.as_dvec2()); - let determinant = d1.x * d2.y - d2.x * d1.y; - if !determinant.is_finite() || determinant.abs() <= 1e-12 * d1.length() * d2.length() { - continue; - } +fn tangent_vertex_ids(positions: &[Vec3], normals: &[Vec3], uvs: &[Vec2], indices: impl IntoIterator) -> Vec { + let bits = |value: f32| if value == 0.0 { 0 } else { value.to_bits() }; + let mut vertices = std::collections::HashMap::new(); + indices + .into_iter() + .map(|index| { + let index = index as usize; + let (Some(p), Some(n), Some(uv)) = (positions.get(index), normals.get(index), uvs.get(index)) else { return u32::MAX }; + let attributes = [p.x, p.y, p.z, n.x, n.y, n.z, uv.x, uv.y].map(bits); + let next = vertices.len() as u32; + *vertices.entry(attributes).or_insert(next) + }) + .collect() +} - let tangent = (e1 * d2.y - e2 * d1.y) / determinant; - // The direction in which v shrinks, which is up the image. - let up = (e1 * d2.x - e2 * d1.x) / determinant; - if !tangent.is_finite() || !up.is_finite() { - continue; +fn connected_fallback_faces(indices: &[u32], eligible: &[usize], seeds: &[usize]) -> Vec { + let vertex_count = indices.iter().copied().max().map_or(0, |index| index as usize + 1); + let mut offsets = vec![0usize; vertex_count + 1]; + for &face in eligible { + for &vertex in &indices[face * 3..face * 3 + 3] { + offsets[vertex as usize + 1] += 1; } - for v in [a, b, c] { - if let Some((t, u)) = sums.get_mut(v) { - *t += tangent; - *u += up; + } + for vertex in 1..offsets.len() { + offsets[vertex] += offsets[vertex - 1]; + } + let mut incidents = vec![0usize; eligible.len() * 3]; + let mut cursor = offsets.clone(); + for &face in eligible { + for &vertex in &indices[face * 3..face * 3 + 3] { + incidents[cursor[vertex as usize]] = face; + cursor[vertex as usize] += 1; + } + } + drop(cursor); + let mut selected = vec![false; indices.len() / 3]; + let mut faces = seeds.to_vec(); + for &face in seeds { + selected[face] = true; + } + let mut next = 0; + let mut visited_edges = std::collections::HashSet::new(); + while let Some(&face) = faces.get(next) { + next += 1; + let vertices = &indices[face * 3..face * 3 + 3]; + for edge in 0..3 { + let (a, b) = (vertices[edge] as usize, vertices[(edge + 1) % 3] as usize); + if !visited_edges.insert((a.min(b), a.max(b))) { + continue; + } + let vertex = if offsets[a + 1] - offsets[a] <= offsets[b + 1] - offsets[b] { a } else { b }; + for &other in &incidents[offsets[vertex]..offsets[vertex + 1]] { + #[cfg(test)] + FALLBACK_ADJACENCY_VISITS.with(|visits| visits.set(visits.get() + 1)); + if !selected[other] { + let triangle = &indices[other * 3..other * 3 + 3]; + if triangle.contains(&(a as u32)) && triangle.contains(&(b as u32)) { + selected[other] = true; + faces.push(other); + } + } } } } + faces.sort_unstable(); + faces +} - sums.into_iter() - .enumerate() - .map(|(v, (t, up))| { - let t = t.try_normalize().map(|t| t.as_vec3()).filter(|t| t.is_finite()).unwrap_or(Vec3::X); - let up = up.try_normalize().map(|up| up.as_vec3()).unwrap_or(Vec3::ZERO); - let n = normals.get(v).copied().unwrap_or(Vec3::Y); - let w = if n.cross(t).dot(up) < 0.0 { -1.0 } else { 1.0 }; - t.extend(w) - }) - .collect() +/// Per-corner tangents from f64 triangle UV gradients. +fn simple_tangents(positions: &[Vec3], normals: &[Vec3], uvs: &[Vec2], indices: &[u32]) -> Vec { + let mut corners = vec![Vec4::ZERO; indices.len()]; + fill_simple_tangents(positions, normals, uvs, indices, &mut corners); + corners +} + +fn fallback_gradients(positions: &[Vec3], uvs: &[Vec2], indices: &[u32]) -> Option<(DVec3, DVec3, DVec3, f64)> { + let &[a, b, c] = indices else { return None }; + let (a, b, c) = (a as usize, b as usize, c as usize); + let (pa, pb, pc) = (positions.get(a)?, positions.get(b)?, positions.get(c)?); + if pa == pb || pa == pc || pb == pc { + return None; + } + let (ua, ub, uc) = (uvs.get(a)?, uvs.get(b)?, uvs.get(c)?); + let (e1, e2) = (pb.as_dvec3() - pa.as_dvec3(), pc.as_dvec3() - pa.as_dvec3()); + let (d1, d2) = (ub.as_dvec2() - ua.as_dvec2(), uc.as_dvec2() - ua.as_dvec2()); + let determinant = d1.perp_dot(d2); + if !determinant.is_finite() || determinant == 0.0 { + return None; + } + let tangent = (e1 * d2.y - e2 * d1.y) / determinant; + let bitangent = (e2 * d1.x - e1 * d2.x) / determinant; + (tangent.is_finite() && bitangent.is_finite()).then_some((tangent, bitangent, e1.cross(e2), determinant)) +} + +fn fill_simple_tangents(positions: &[Vec3], normals: &[Vec3], uvs: &[Vec2], indices: &[u32], corners: &mut [Vec4]) { + corners.fill(Vec4::ZERO); + let mut valid_faces = Vec::new(); + for (face, vertices) in indices.as_chunks::<3>().0.iter().enumerate() { + #[cfg(test)] + FALLBACK_FACE_VISITS.with(|visits| visits.set(visits.get() + 1)); + let Some((tangent, _, _, determinant)) = fallback_gradients(positions, uvs, vertices) else { continue }; + valid_faces.push(face); + for corner in 0..3 { + let t = tangent.try_normalize().map(|t| t.as_vec3()).unwrap_or(Vec3::X); + let w = if determinant.is_sign_negative() { -1.0 } else { 1.0 }; + corners[face * 3 + corner] = t.extend(w); + } + } + fn root(parents: &mut [usize], mut at: usize) -> usize { + while parents[at] != at { + parents[at] = parents[parents[at]]; + at = parents[at]; + } + at + } + let mut parents: Vec = (0..valid_faces.len() * 3).collect(); + #[cfg(test)] + FALLBACK_CONNECTIVITY_CORNERS.with(|corners| corners.set(parents.len())); + let welded = tangent_vertex_ids(positions, normals, uvs, valid_faces.iter().flat_map(|&face| indices[face * 3..face * 3 + 3].iter().copied())); + let mut edges = std::collections::HashMap::new(); + for (slot, &face) in valid_faces.iter().enumerate() { + for edge in 0..3 { + let (mut a, mut b) = (slot * 3 + edge, slot * 3 + (edge + 1) % 3); + let reversed = usize::from(welded[a] > welded[b]); + if welded[a] > welded[b] { + std::mem::swap(&mut a, &mut b); + } + let key = (welded[a], welded[b], corners[face * 3 + a % 3].w < 0.0, corners[face * 3 + b % 3].w < 0.0); + let previous: &mut [Option<(usize, usize)>; 2] = edges.entry(key).or_insert([None, None]); + if let Some((previous_a, previous_b)) = previous[1 - reversed] { + for (current, previous) in [(a, previous_a), (b, previous_b)] { + let (a, b) = (root(&mut parents, current), root(&mut parents, previous)); + parents[a.max(b)] = a.min(b); + } + } + previous[reversed].get_or_insert((a, b)); + } + } + drop(edges); + drop(welded); + let mut sums = std::collections::HashMap::::new(); + for (slot, &face) in valid_faces.iter().enumerate() { + if let Some((tangent, ..)) = fallback_gradients(positions, uvs, &indices[face * 3..face * 3 + 3]) { + let direction = tangent.try_normalize().unwrap_or(DVec3::X); + let triangle = &indices[face * 3..face * 3 + 3]; + for corner in 0..3 { + let origin = positions[triangle[corner] as usize].as_dvec3(); + let a = (positions[triangle[(corner + 1) % 3] as usize].as_dvec3() - origin).try_normalize().unwrap_or(DVec3::ZERO); + let b = (positions[triangle[(corner + 2) % 3] as usize].as_dvec3() - origin).try_normalize().unwrap_or(DVec3::ZERO); + let weight = a.cross(b).length().atan2(a.dot(b)); + *sums.entry(root(&mut parents, slot * 3 + corner)).or_default() += direction * weight; + } + } + } + for (slot, &face) in valid_faces.iter().enumerate() { + let Some((gradient, bitangent, ..)) = fallback_gradients(positions, uvs, &indices[face * 3..face * 3 + 3]) else { continue }; + for local in 0..3 { + let index = face * 3 + local; + let corner = &mut corners[index]; + if let Some(tangent) = sums.get(&root(&mut parents, slot * 3 + local)).and_then(|sum| sum.try_normalize()) { + let normal = normals.get(indices[index] as usize).copied().unwrap_or(Vec3::Y).as_dvec3(); + if tangent.dot(gradient) > 0.0 && (normal.cross(tangent) * f64::from(corner.w)).dot(bitangent) > 0.0 { + *corner = tangent.as_vec3().extend(corner.w); + } + } + } + } +} + +#[cfg(test)] +std::thread_local! { + static FALLBACK_FACE_VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static FALLBACK_ADJACENCY_VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static FALLBACK_CONNECTIVITY_CORNERS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +fn mikk_uvs_safe(positions: &[Vec3], uvs: &[Vec2], indices: &[u32]) -> bool { + let [a, b, c] = indices else { return false }; + let (a, b, c) = (*a as usize, *b as usize, *c as usize); + let (d1, d2) = (uvs[b] - uvs[a], uvs[c] - uvs[a]); + let wide1 = uvs[b].as_dvec2() - uvs[a].as_dvec2(); + let wide2 = uvs[c].as_dvec2() - uvs[a].as_dvec2(); + if wide1.perp_dot(wide2) == 0.0 { + return true; + } + let determinant = d1.perp_dot(d2); + if determinant.abs() <= f32::MIN_POSITIVE || !determinant.is_finite() || !determinant.recip().is_finite() { + return false; + } + let (e1, e2) = (positions[b] - positions[a], positions[c] - positions[a]); + let tangent = e1 * d2.y - e2 * d1.y; + let bitangent = e2 * d1.x - e1 * d2.x; + [tangent, bitangent, tangent / determinant, bitangent / determinant] + .into_iter() + .all(|v| v.length_squared().is_finite() && v.length_squared() > 0.0) } /// Whether the values are finite and their largest magnitude is zero or lies between the @@ -617,20 +796,29 @@ impl Mikk<'_> { } fn fill_collapsed_corners(&mut self) { + let generated_faces: Vec = self + .corners + .as_chunks::<3>() + .0 + .iter() + .enumerate() + .filter(|(_, corners)| corners.iter().all(|corner| *corner != Vec4::ZERO)) + .map(|(face, _)| face) + .collect(); let bits = |value: f32| if value == 0.0 { 0 } else { value.to_bits() }; let attributes = |index: usize| { let (p, n, uv) = (self.positions[index], self.normals[index], self.uvs[index]); [p.x, p.y, p.z, n.x, n.y, n.z, uv.x, uv.y].map(bits) }; let mut first = vec![None; self.positions.len()]; - for &face in self.faces.as_deref().unwrap_or(&[]) { + for &face in &generated_faces { for vertex in 0..3 { let corner = face * 3 + vertex; let index = self.indices[corner] as usize; first[index].get_or_insert(self.corners[corner]); } } - let generated_count = self.face_count() * 3; + let generated_count = generated_faces.len() * 3; let index_generated = generated_count <= self.indices.len() - generated_count; let mut welded: std::collections::HashMap<[u32; 8], Option> = if index_generated { std::collections::HashMap::new() @@ -643,7 +831,7 @@ impl Mikk<'_> { .collect() }; if index_generated || !welded.is_empty() { - for &face in self.faces.as_deref().unwrap_or(&[]) { + for &face in &generated_faces { for vertex in 0..3 { let corner = face * 3 + vertex; let key = attributes(self.indices[corner] as usize); @@ -717,11 +905,8 @@ impl mikktspace::Geometry for Mikk<'_> { self.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 negated, the bitangent `cross(N, T) * w` points up the image, as glTF requires. - // Negating keeps differences in v that `1 - v` would round away. let uv = self.uvs.get(self.vi(face, vert)).copied().unwrap_or_default(); - [uv.x, -uv.y] + [uv.x, uv.y] } fn set_tangent_encoded(&mut self, tangent: [f32; 4], face: usize, vert: usize) { // One tangent per corner: corners of a vertex can get different frames. @@ -734,6 +919,333 @@ impl mikktspace::Geometry for Mikk<'_> { #[cfg(test)] mod tests { + #[test] + fn fallback_smoothing_is_invariant_to_gradient_magnitude() { + let mut reference = Mesh { + positions: vec![Vec3::ZERO, Vec3::Y, Vec3::X, Vec3::new(-1.0, -10.0, 0.0)], + normals: vec![-Vec3::Z; 4], + uvs: vec![Vec2::ZERO, Vec2::Y, Vec2::X, -Vec2::X], + indices: vec![0, 1, 2, 1, 0, 3], + ..Mesh::default() + }; + let mut tiny = reference.clone(); + tiny.uvs[3] = -Vec2::X * 1e-20; + reference.compute_tangents(); + tiny.compute_tangents(); + for corner in 0..6 { + let (expected, actual) = (reference.tangents[reference.indices[corner] as usize], tiny.tangents[tiny.indices[corner] as usize]); + assert!(expected.truncate().dot(actual.truncate()) > 0.999, "{corner}: {expected:?} {actual:?}"); + } + } + + #[test] + fn fallback_keeps_mikktspace_face_signs_with_opposed_vertex_normals() { + let mut reference = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y], + normals: vec![Vec3::Z, -Vec3::Z, Vec3::Z], + uvs: vec![Vec2::ZERO, Vec2::X, Vec2::Y], + indices: vec![0, 1, 2], + ..Mesh::default() + }; + let mut tiny = reference.clone(); + for uv in &mut tiny.uvs { + *uv *= 1e-30; + } + reference.compute_tangents(); + tiny.compute_tangents(); + assert!(reference.tangents.iter().all(|tangent| tangent.w == reference.tangents[0].w)); + for corner in 0..3 { + assert_eq!(tiny.tangents[tiny.indices[corner] as usize].w, reference.tangents[reference.indices[corner] as usize].w); + } + } + + #[test] + fn fallback_visits_a_nonmanifold_welded_edge_once() { + let count = 1000u32; + let mut mesh = Mesh { positions: vec![Vec3::ZERO, Vec3::X], normals: vec![Vec3::Z; 2], uvs: vec![Vec2::ZERO, Vec2::X], ..Mesh::default() }; + for face in 0..count { + mesh.positions.push(Vec3::Y * (1.0 + face as f32 / count as f32)); + mesh.normals.push(Vec3::Z); + mesh.uvs.push(Vec2::Y * if face == 0 { 1e-30 } else { 1.0 }); + mesh.indices.extend([0, 1, face + 2]); + } + FALLBACK_ADJACENCY_VISITS.with(|visits| visits.set(0)); + mesh.compute_tangents(); + let visits = FALLBACK_ADJACENCY_VISITS.with(|visits| visits.get()); + assert!(visits <= count as usize * 12, "nonmanifold traversal visited {visits} corners"); + } + + #[test] + fn ill_conditioned_uvs_keep_their_orientation_sign() { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::new(-1.0, 1.0, 0.0)], + normals: vec![Vec3::Z; 3], + uvs: vec![Vec2::ZERO, Vec2::ONE, Vec2::X * 1e-20], + indices: vec![0, 1, 2], + ..Mesh::default() + }; + let determinant = (mesh.uvs[1].as_dvec2() - mesh.uvs[0].as_dvec2()).perp_dot(mesh.uvs[2].as_dvec2() - mesh.uvs[0].as_dvec2()); + assert!(determinant < 0.0); + mesh.compute_tangents(); + assert!(mesh.tangents.iter().all(|tangent| tangent.w < 0.0)); + } + + #[test] + fn collapsed_faces_do_not_allocate_fallback_connectivity() { + let mut mesh = Mesh { + positions: vec![Vec3::X * 2_000_000.0, Vec3::X * 2_000_001.0, Vec3::new(2_000_000.0, 1.0, 0.0)], + normals: vec![Vec3::Z; 3], + uvs: vec![Vec2::ZERO, Vec2::X, Vec2::Y], + indices: vec![0, 1, 2], + ..Mesh::default() + }; + for _ in 0..1000 { + mesh.indices.extend([0, 0, 1]); + } + FALLBACK_CONNECTIVITY_CORNERS.with(|corners| corners.set(0)); + mesh.compute_tangents(); + let corners = FALLBACK_CONNECTIVITY_CORNERS.with(|corners| corners.get()); + assert_eq!(corners, 3, "fallback allocated connectivity for {corners} corners"); + } + + #[test] + fn regional_fallback_keeps_a_valid_nearly_parallel_uv_gradient() { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::Y, Vec3::new(-1.0, 1.0, 0.0), -Vec3::X], + normals: vec![Vec3::Z; 4], + uvs: vec![Vec2::ZERO, Vec2::X, Vec2::new(1.0, 1e-13), Vec2::Y * 1e-30], + indices: vec![0, 1, 2, 0, 2, 3], + ..Mesh::default() + }; + mesh.compute_tangents(); + assert!(mesh.tangents[mesh.indices[1] as usize].truncate().dot(Vec3::Y) > 0.99); + } + + #[test] + fn fallback_smoothing_does_not_reverse_an_adjacent_bitangent() { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(-1.0, -1.0, 0.0)], + normals: vec![Vec3::Z; 4], + uvs: vec![Vec2::ZERO, Vec2::ONE, Vec2::Y, Vec2::X * 1e-20], + indices: vec![0, 1, 2, 0, 1, 3], + ..Mesh::default() + }; + mesh.compute_tangents(); + for corner in 0..3 { + let tangent = mesh.tangents[mesh.indices[corner] as usize]; + assert!((Vec3::Z.cross(tangent.truncate()) * tangent.w).dot(Vec3::Y) > 0.0); + } + } + + #[test] + fn fallback_adjacency_ignores_incomplete_triangles() { + let positions = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::X * 10.0, Vec3::X * 11.0, Vec3::new(10.0, 1.0, 0.0)]; + let uvs = vec![Vec2::ZERO, Vec2::Y * 1e-30, Vec2::X * 1e-30, Vec2::ZERO, Vec2::X, Vec2::Y]; + let indices = vec![0, 1, 2, 3, 4, 5, 0, 1]; + let mut mesh = + Mesh { positions: positions.clone(), normals: vec![Vec3::Z; 6], uvs: uvs.clone(), indices: indices.clone(), ..Mesh::default() }; + mesh.compute_tangents(); + let result = Mesh::from_parts(positions, Some(vec![Vec3::Z; 6]), uvs, indices, "m"); + assert!(result.is_err()); + } + + #[test] + fn fallback_traversal_excludes_collapsed_face_fans() { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::X * 10.0, Vec3::X * 11.0, Vec3::new(10.0, 1.0, 0.0)], + normals: vec![Vec3::Z; 6], + uvs: vec![Vec2::ZERO, Vec2::Y * 1e-30, Vec2::X * 1e-30, Vec2::ZERO, Vec2::X, Vec2::Y], + indices: vec![0, 1, 2, 3, 4, 5], + ..Mesh::default() + }; + for _ in 0..1000 { + mesh.indices.extend([0, 1, 1]); + } + FALLBACK_ADJACENCY_VISITS.with(|visits| visits.set(0)); + mesh.compute_tangents(); + let visits = FALLBACK_ADJACENCY_VISITS.with(|visits| visits.get()); + assert!(visits <= mesh.indices.len() * 8, "fallback adjacency visited {visits} corners"); + } + + #[test] + fn fallback_boundaries_share_frames_across_equivalent_edge_vertices() { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::new(1.0, 1.0, 0.0), Vec3::ZERO, Vec3::new(1.0, 1.0, 0.0), Vec3::Y], + normals: vec![Vec3::Z; 6], + uvs: vec![Vec2::ZERO, Vec2::Y, Vec2::splat(1e-19), Vec2::ZERO, Vec2::splat(1e-19), Vec2::X * 1e-19], + indices: vec![0, 1, 2, 3, 4, 5], + ..Mesh::default() + }; + mesh.compute_tangents(); + assert_eq!(mesh.tangents[mesh.indices[0] as usize], mesh.tangents[mesh.indices[3] as usize]); + assert_eq!(mesh.tangents[mesh.indices[2] as usize], mesh.tangents[mesh.indices[4] as usize]); + } + + #[test] + fn a_numerical_fallback_boundary_preserves_continuous_edge_frames() { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::new(1.0, 1.0, 0.0), Vec3::Y], + normals: vec![Vec3::Z; 4], + uvs: vec![Vec2::ZERO, Vec2::Y, Vec2::splat(1e-19), Vec2::X * 1e-19], + indices: vec![0, 1, 2, 0, 2, 3], + ..Mesh::default() + }; + mesh.compute_tangents(); + assert_eq!(mesh.indices[0], mesh.indices[3]); + assert_eq!(mesh.indices[2], mesh.indices[4]); + } + + #[test] + fn an_isolated_uv_outlier_only_runs_fallback_for_its_island() { + let mut mesh = Mesh::default(); + for face in 0..1001 { + let x = face as f32 * 2.0; + mesh.positions.extend([Vec3::X * x, Vec3::X * (x + 1.0), Vec3::new(x, 1.0, 0.0)]); + mesh.normals.extend([Vec3::Z; 3]); + let scale = if face == 1000 { 1e-30 } else { 1.0 }; + mesh.uvs.extend([Vec2::ZERO, Vec2::X * scale, Vec2::Y * scale]); + mesh.indices.extend([face * 3, face * 3 + 1, face * 3 + 2]); + } + FALLBACK_FACE_VISITS.with(|visits| visits.set(0)); + mesh.compute_tangents(); + let visits = FALLBACK_FACE_VISITS.with(|visits| visits.get()); + assert_eq!(visits, 1, "fallback visited {visits} faces for one isolated UV outlier"); + } + + #[test] + fn subnormal_uv_determinants_use_the_wide_fallback() { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::X * 2.0, Vec3::X * 3.0, Vec3::new(2.0, 1.0, 0.0)], + normals: vec![Vec3::Z; 6], + uvs: vec![Vec2::ZERO, Vec2::X, Vec2::Y, Vec2::ZERO, Vec2::Y * 1e-19, Vec2::X * 1e-19], + indices: vec![0, 1, 2, 3, 4, 5], + ..Mesh::default() + }; + mesh.compute_tangents(); + assert!(mesh.tangents[mesh.indices[3] as usize].truncate().dot(Vec3::Y) > 0.99); + } + + #[test] + fn fallback_faces_touching_only_at_a_vertex_keep_their_directions() { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, -Vec3::X * 1e-40, -Vec3::Y * 1e-40], + normals: vec![Vec3::Z; 5], + uvs: vec![Vec2::ZERO, Vec2::X, Vec2::Y, Vec2::X * 1e-30, Vec2::Y * 1e-30], + indices: vec![0, 1, 2, 0, 3, 4], + ..Mesh::default() + }; + mesh.compute_tangents(); + assert!(mesh.tangents[mesh.indices[0] as usize].truncate().dot(Vec3::X) > 0.99); + assert!(mesh.tangents[mesh.indices[3] as usize].truncate().dot(-Vec3::X) > 0.99); + } + + #[test] + fn collapsed_fallback_faces_with_distinct_uvs_reuse_complete_frames() { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::ZERO], + normals: vec![Vec3::Z; 4], + uvs: vec![Vec2::ZERO, Vec2::Y * 1e-30, Vec2::X * 1e-30, Vec2::Y * 1e-30], + indices: vec![0, 1, 2, 0, 3, 2], + ..Mesh::default() + }; + mesh.compute_tangents(); + assert_eq!(mesh.indices[0], mesh.indices[3]); + assert_eq!(mesh.tangents[mesh.indices[3] as usize], mesh.tangents[mesh.indices[0] as usize]); + } + + #[test] + fn tiny_mikk_numerators_keep_their_uv_direction() { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::Y, Vec3::X * 1e-6], + normals: vec![Vec3::Z; 3], + uvs: vec![Vec2::ZERO, Vec2::X, Vec2::Y * 1e-25], + indices: vec![0, 1, 2], + ..Mesh::default() + }; + mesh.compute_tangents(); + assert!(mesh.tangents.iter().all(|t| t.truncate().dot(Vec3::Y) > 0.99)); + } + + #[test] + fn fallback_smooths_continuous_same_handed_edges() { + let mut mesh = quad(); + for p in &mut mesh.positions { + p.x += 2_000_000.0; + } + mesh.uvs = vec![Vec2::ZERO, Vec2::X, Vec2::ONE, Vec2::new(0.0, 2.0)]; + let count = mesh.positions.len(); + mesh.compute_tangents(); + assert_eq!(mesh.positions.len(), count); + assert_eq!(mesh.indices[0], mesh.indices[3]); + assert_eq!(mesh.indices[2], mesh.indices[4]); + } + + #[test] + fn collapsed_corners_reuse_tiny_uv_fallback_frames() { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::ZERO], + normals: vec![Vec3::Z; 4], + uvs: vec![Vec2::ZERO, Vec2::Y * 1e-30, Vec2::X * 1e-30, Vec2::ZERO], + indices: vec![0, 1, 2, 0, 3, 2], + ..Mesh::default() + }; + mesh.compute_tangents(); + assert_eq!(mesh.indices[0], mesh.indices[3]); + assert!(mesh.tangents[mesh.indices[4] as usize].truncate().dot(Vec3::Y) > 0.99); + } + + #[test] + fn tangent_frames_follow_stored_uv_gradients() { + for offset in [0.0, 2_000_000.0] { + for scale in [1.0, 1e-30] { + for orientation in [-1.0, 1.0] { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y].into_iter().map(|p| p + Vec3::X * offset).collect(), + normals: vec![Vec3::Z; 3], + uvs: vec![Vec2::ZERO, Vec2::X * scale, Vec2::Y * (scale * orientation)], + indices: vec![0, 1, 2], + ..Mesh::default() + }; + mesh.compute_tangents(); + for tangent in mesh.tangents { + assert!(tangent.truncate().dot(Vec3::X) > 0.99, "{offset} {scale} {orientation}: {tangent:?}"); + let bitangent = Vec3::Z.cross(tangent.truncate()) * tangent.w; + assert!(bitangent.dot(Vec3::Y * orientation) > 0.99, "{offset} {scale} {orientation}: {tangent:?}"); + } + } + } + } + } + + #[test] + fn translated_mirrored_faces_keep_separate_corner_frames() { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(1.0, 1.0, 0.0)].into_iter().map(|p| p + Vec3::X * 2_000_000.0).collect(), + normals: vec![Vec3::Z; 4], + uvs: vec![Vec2::new(0.0, 1.0), Vec2::ONE, Vec2::ZERO, Vec2::new(1.0, 2.0)], + indices: vec![0, 1, 2, 1, 3, 2], + ..Mesh::default() + }; + mesh.compute_tangents(); + assert_ne!(mesh.indices[1], mesh.indices[3]); + assert_ne!(mesh.indices[2], mesh.indices[5]); + assert!(mesh.tangents[mesh.indices[1] as usize].w * mesh.tangents[mesh.indices[3] as usize].w < 0.0); + } + + #[test] + fn tiny_uv_islands_do_not_receive_the_ordinary_islands_frame() { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::X * 2.0, Vec3::X * 3.0, Vec3::new(2.0, 1.0, 0.0)], + normals: vec![Vec3::Z; 6], + uvs: vec![Vec2::ZERO, Vec2::X, Vec2::Y, Vec2::ZERO, Vec2::Y * 1e-30, Vec2::X * 1e-30], + indices: vec![0, 1, 2, 3, 4, 5], + ..Mesh::default() + }; + mesh.compute_tangents(); + assert!(mesh.tangents[0].truncate().dot(Vec3::X) > 0.99); + assert!(mesh.tangents[3].truncate().dot(Vec3::Y) > 0.99); + } + #[test] fn unmatched_collapsed_corners_keep_the_mikktspace_default_frame() { let mut mesh = Mesh { @@ -925,7 +1437,7 @@ mod tests { ) .unwrap(); for t in &m.tangents { - assert!((t.truncate() - Vec3::X).length() < 1e-4 && t.w == 1.0, "edge {edge}: {t:?}"); + assert!((t.truncate() - Vec3::X).length() < 1e-4 && t.w == -1.0, "edge {edge}: {t:?}"); } } } @@ -942,7 +1454,8 @@ mod tests { m.compute_tangents(); let fallback = simple_tangents(&m.positions, &m.normals, &m.uvs, &m.indices); assert_eq!(m.tangents.len(), 4); - for (mikk, simple) in m.tangents.iter().zip(&fallback) { + for (&index, simple) in m.indices.iter().zip(&fallback) { + let mikk = m.tangents[index as usize]; assert!((mikk.truncate() - simple.truncate()).length() < 1e-4, "flip {flip}: {mikk:?} {simple:?}"); assert_eq!(mikk.w, simple.w, "flip {flip}"); } diff --git a/crates/mesh-ops/src/primitives.rs b/crates/mesh-ops/src/primitives.rs index 43a9f29684..8e544533f8 100644 --- a/crates/mesh-ops/src/primitives.rs +++ b/crates/mesh-ops/src/primitives.rs @@ -247,7 +247,7 @@ pub fn preview_orb() -> Mesh { .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) + (around - *n * n.dot(around)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()).extend(-1.0) }) .collect(); m @@ -497,7 +497,7 @@ mod tests { use super::*; /// 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). + /// and each reconstructed bitangent follows increasing v where the UV gradient is defined. fn check(m: &Mesh, max_u: f32) { m.validate().unwrap(); let mut bad = 0; @@ -516,8 +516,25 @@ mod tests { 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"); + let (mut opposed, mut tested) = (0, 0); + for &[a, b, c] in m.indices.as_chunks::<3>().0 { + let (a, b, c) = (a as usize, b as usize, c as usize); + let (d1, d2) = (m.uvs[b].as_dvec2() - m.uvs[a].as_dvec2(), m.uvs[c].as_dvec2() - m.uvs[a].as_dvec2()); + let determinant = d1.perp_dot(d2); + if determinant == 0.0 { + continue; + } + let (e1, e2) = (m.positions[b].as_dvec3() - m.positions[a].as_dvec3(), m.positions[c].as_dvec3() - m.positions[a].as_dvec3()); + let Some(bitangent) = ((e2 * d1.x - e1 * d2.x) / determinant).try_normalize() else { continue }; + for vertex in [a, b, c] { + let tangent = m.tangents[vertex]; + let reconstructed = m.normals[vertex].as_dvec3().cross(tangent.truncate().as_dvec3()) * tangent.w as f64; + tested += 1; + opposed += usize::from(reconstructed.dot(bitangent) < 0.0); + } + } + assert!(tested > 0); + assert!(opposed * 50 < tested, "{opposed} tangent frames oppose increasing v"); } #[test] From 192c7ebd0b38de2d7fe18924bcd1a6483ea54430 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 19:17:56 -0800 Subject: [PATCH 06/31] Clarify tangent fallback range limits --- crates/mesh-ops/README.md | 2 +- crates/mesh-ops/src/mesh.rs | 14 ++++++-------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md index 116923be9d..264ba07354 100644 --- a/crates/mesh-ops/README.md +++ b/crates/mesh-ops/README.md @@ -13,7 +13,7 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form A vertex whose triangles have different tangent frames (mirrored UVs) is split into one copy per frame. Faces with coincident corners stay in the mesh and reuse shared vertex frames when available. MikkTSpace omits those faces. A mesh with more than 2,048 noncollapsed triangles around one vertex, or with non-finite - positions or UVs, or with positions or UVs above 1e6 or below 1e-6 in magnitude, gets per-corner tangents from f64 UV gradients instead of MikkTSpace. + positions or UVs, or whose largest absolute position or UV component is nonzero and outside 1e-6 to 1e6, gets per-corner tangents from f64 UV gradients instead of MikkTSpace. An edge-connected region containing a face whose f32 UV gradients overflow or underflow uses that fallback. Both paths use the stored UVs. Each triangle with usable UV gradients has one handedness sign. Tangents are always finite; a non-finite normal counts as +Y. diff --git a/crates/mesh-ops/src/mesh.rs b/crates/mesh-ops/src/mesh.rs index 0108d9ad99..e6ce075824 100644 --- a/crates/mesh-ops/src/mesh.rs +++ b/crates/mesh-ops/src/mesh.rs @@ -51,15 +51,13 @@ pub struct Mesh { /// Hard cap on mesh size accepted from files (triangles). pub const MAX_TRIANGLES: usize = 20_000_000; -/// Positions and UVs go to MikkTSpace only when their largest magnitude lies between the -/// reciprocal of this and this, so edge lengths, cross products and their products with UVs -/// neither overflow nor underflow in `f32`. Other meshes get the `f64` per-vertex tangents. +/// The largest absolute position component and largest absolute UV component must each be +/// zero or between the reciprocal of this value and this value for MikkTSpace. +/// Other meshes get `f64` per-corner tangents. const SAFE_MAGNITUDE: f32 = 1e6; -/// Most triangles around one vertex (as MikkTSpace welds vertices) for which tangents come from -/// MikkTSpace. It visits the triangles around a vertex recursively, one call per triangle, so a -/// larger fan could exhaust the stack; such meshes get the per-vertex fallback. This crate's own -/// value. +/// MikkTSpace accepts at most this many triangles around one welded vertex. +/// Meshes above this crate's limit use the per-corner fallback. pub const MAX_MIKKTSPACE_VALENCE: usize = 2_048; /// Most comparisons MikkTSpace may make welding corners, for which tangents come from it. It @@ -235,7 +233,7 @@ impl Mesh { } /// MikkTSpace tangents with per-corner f64 UV-gradient fallback. A mesh with - /// an index out of range, a non-finite position or UV, a position or UV with a magnitude + /// an index out of range, a non-finite position or UV, a largest absolute position or UV component /// outside 1e-6 to 1e6 (zero is fine), only degenerate triangles, more than /// [`MAX_MIKKTSPACE_VALENCE`] noncollapsed triangles around one vertex or noncollapsed corners /// whose welding would take more than [`MAX_MIKKTSPACE_WELD_WORK`] comparisons does not go to MikkTSpace. Missing From 20de7662f732f004271a15a9ae7806eb1af97131 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 07:23:56 -0800 Subject: [PATCH 07/31] craft-mesh-ops: compute_tangents keeps the indices and vertex count compute_tangents no longer splits vertices at mirrored UV seams. Each vertex takes the frame of the first corner that uses it, so callers that hold per-vertex data keep a matching vertex count. The finite f64 fallback tangents are unchanged; the per-corner frames now come from a private corner_tangents helper. The test-only visit counters are removed from the fallback functions. The isolated-outlier test now checks the faces connected_fallback_faces selects. --- crates/mesh-ops/README.md | 4 +- crates/mesh-ops/src/mesh.rs | 300 ++++++++++-------------------------- 2 files changed, 86 insertions(+), 218 deletions(-) diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md index 029d01c97a..0b96711394 100644 --- a/crates/mesh-ops/README.md +++ b/crates/mesh-ops/README.md @@ -10,8 +10,8 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form - **Normals and tangents.** Smooth normals are area weighted. Tangents come from MikkTSpace, which glTF 2.0 recommends for meshes without tangents (): `w` holds the bitangent sign. - A vertex whose triangles have different tangent frames (mirrored UVs) is split into one copy - per frame. Faces with coincident corners stay in the mesh and reuse shared vertex frames when + `compute_tangents` keeps the indices and the vertex count; a vertex whose triangles have + different tangent frames (mirrored UVs) takes the frame of its first corner. Faces with coincident corners stay in the mesh and reuse shared vertex frames when available. MikkTSpace omits those faces. A mesh with more than 2,048 noncollapsed triangles around one vertex, or with non-finite positions or UVs, or whose largest absolute position or UV component is nonzero and outside 1e-6 to 1e6, gets per-corner tangents from f64 UV gradients instead of MikkTSpace. An edge-connected region containing a face whose f32 UV gradients overflow or underflow uses that fallback. diff --git a/crates/mesh-ops/src/mesh.rs b/crates/mesh-ops/src/mesh.rs index e6ce075824..dca7762175 100644 --- a/crates/mesh-ops/src/mesh.rs +++ b/crates/mesh-ops/src/mesh.rs @@ -239,15 +239,29 @@ impl Mesh { /// whose welding would take more than [`MAX_MIKKTSPACE_WELD_WORK`] comparisons does not go to MikkTSpace. Missing /// normals are computed and missing UVs are zero. A non-finite normal counts as +Y. /// - /// MikkTSpace gives each triangle corner its own tangent frame. A vertex whose corners get - /// different frames (UVs mirrored across it) is split: every further frame gets a copy of - /// the vertex, and the corners with that frame use the copy. A copy whose index would not - /// fit in `u32` is not made, and those corners keep the first frame. + /// The indices and the vertex count do not change. Each vertex gets the frame of the first + /// corner that uses it; a vertex no triangle uses gets +X made perpendicular to its normal. /// Faces with coincident corners stay in the mesh but are omitted from MikkTSpace. Their /// corners reuse a generated frame for the same vertex when one is available. /// Edge-connected regions containing a face whose f32 UV gradients overflow or underflow use the fallback. /// Both paths use the stored UVs. Each triangle with usable UV gradients has one handedness sign. pub fn compute_tangents(&mut self) { + let corners = self.corner_tangents(); + let normals: Vec = self.normals.iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(); + let mut tangents = vec![None::; self.positions.len()]; + for (&index, &t) in self.indices.iter().zip(&corners) { + if let Some(slot) = tangents.get_mut(index as usize) { + slot.get_or_insert(t); + } + } + self.tangents = + tangents.iter().enumerate().map(|(v, t)| t.unwrap_or_else(|| orthonormal(&normals, v, Vec4::new(1.0, 0.0, 0.0, 1.0)))).collect(); + } + + /// The tangent frame of every triangle corner, orthonormal to its vertex normal, as + /// [`Mesh::compute_tangents`] computes them. Missing normals are computed and missing UVs are + /// set to zero first. + fn corner_tangents(&mut self) -> Vec { let n = self.positions.len(); if self.normals.len() != n { self.compute_normals(); @@ -304,55 +318,10 @@ impl Mesh { } } - // Orthonormalize a tangent against the normal of vertex `v`; repair degenerate results. - let frame = |v: usize, t: Vec4| { - let n = normals.get(v).copied().unwrap_or(Vec3::Y); - let d = t.truncate(); - let o = (d - n * n.dot(d)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()); - o.extend(if t.w < 0.0 { -1.0 } else { 1.0 }) - }; for (t, v) in corners.iter_mut().zip(&self.indices) { - *t = frame(*v as usize, *t); + *t = orthonormal(&normals, *v as usize, *t); } - - // One tangent per vertex: the first corner's frame, and a copy of the vertex for each - // other frame its corners have. Corners that share a frame get bit-identical tangents. - let bits = |t: Vec4| t.to_array().map(f32::to_bits); - let mut tangents = vec![None::; n]; - let mut copies: Vec<(u32, Vec4)> = Vec::new(); - let mut copy_of: std::collections::HashMap<(u32, [u32; 4]), u32> = std::collections::HashMap::new(); - for (index, &t) in self.indices.iter_mut().zip(&corners) { - let v = *index; - let Some(slot) = tangents.get_mut(v as usize) else { continue }; - match slot { - None => *slot = Some(t), - Some(first) if bits(*first) == bits(t) => {} - Some(_) => { - if let Some(©) = copy_of.get(&(v, bits(t))) { - *index = copy; - } else if let Ok(copy) = u32::try_from(n + copies.len()) { - copies.push((v, t)); - copy_of.insert((v, bits(t)), copy); - *index = copy; - } - } - } - } - - // A vertex no triangle uses gets +X made perpendicular to its normal. - let mut out: Vec = tangents.iter().enumerate().map(|(v, t)| t.unwrap_or_else(|| frame(v, Vec4::new(1.0, 0.0, 0.0, 1.0)))).collect(); - out.extend(copies.iter().map(|(_, t)| *t)); - let has_colors = self.colors.len() == n; - for &(v, _) in &copies { - let v = v as usize; - self.positions.push(self.positions.get(v).copied().unwrap_or_default()); - self.normals.push(self.normals.get(v).copied().unwrap_or(Vec3::Y)); - self.uvs.push(self.uvs.get(v).copied().unwrap_or_default()); - if has_colors { - self.colors.push(self.colors.get(v).copied().unwrap_or(Vec4::ONE)); - } - } - self.tangents = out; + corners } /// The UV tiles material `m` covers: integer parts of its triangles' UV centroids (v down), @@ -541,6 +510,14 @@ impl Mesh { } } +/// Tangent `t` orthonormalized against the normal of vertex `v`, with degenerate results repaired. +fn orthonormal(normals: &[Vec3], v: usize, t: Vec4) -> Vec4 { + let n = normals.get(v).copied().unwrap_or(Vec3::Y); + let d = t.truncate(); + let o = (d - n * n.dot(d)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()); + o.extend(if t.w < 0.0 { -1.0 } else { 1.0 }) +} + fn tangent_vertex_ids(positions: &[Vec3], normals: &[Vec3], uvs: &[Vec2], indices: impl IntoIterator) -> Vec { let bits = |value: f32| if value == 0.0 { 0 } else { value.to_bits() }; let mut vertices = std::collections::HashMap::new(); @@ -593,8 +570,6 @@ fn connected_fallback_faces(indices: &[u32], eligible: &[usize], seeds: &[usize] } let vertex = if offsets[a + 1] - offsets[a] <= offsets[b + 1] - offsets[b] { a } else { b }; for &other in &incidents[offsets[vertex]..offsets[vertex + 1]] { - #[cfg(test)] - FALLBACK_ADJACENCY_VISITS.with(|visits| visits.set(visits.get() + 1)); if !selected[other] { let triangle = &indices[other * 3..other * 3 + 3]; if triangle.contains(&(a as u32)) && triangle.contains(&(b as u32)) { @@ -639,8 +614,6 @@ fn fill_simple_tangents(positions: &[Vec3], normals: &[Vec3], uvs: &[Vec2], indi corners.fill(Vec4::ZERO); let mut valid_faces = Vec::new(); for (face, vertices) in indices.as_chunks::<3>().0.iter().enumerate() { - #[cfg(test)] - FALLBACK_FACE_VISITS.with(|visits| visits.set(visits.get() + 1)); let Some((tangent, _, _, determinant)) = fallback_gradients(positions, uvs, vertices) else { continue }; valid_faces.push(face); for corner in 0..3 { @@ -657,8 +630,6 @@ fn fill_simple_tangents(positions: &[Vec3], normals: &[Vec3], uvs: &[Vec2], indi at } let mut parents: Vec = (0..valid_faces.len() * 3).collect(); - #[cfg(test)] - FALLBACK_CONNECTIVITY_CORNERS.with(|corners| corners.set(parents.len())); let welded = tangent_vertex_ids(positions, normals, uvs, valid_faces.iter().flat_map(|&face| indices[face * 3..face * 3 + 3].iter().copied())); let mut edges = std::collections::HashMap::new(); for (slot, &face) in valid_faces.iter().enumerate() { @@ -710,13 +681,6 @@ fn fill_simple_tangents(positions: &[Vec3], normals: &[Vec3], uvs: &[Vec2], indi } } -#[cfg(test)] -std::thread_local! { - static FALLBACK_FACE_VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - static FALLBACK_ADJACENCY_VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - static FALLBACK_CONNECTIVITY_CORNERS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - fn mikk_uvs_safe(positions: &[Vec3], uvs: &[Vec2], indices: &[u32]) -> bool { let [a, b, c] = indices else { return false }; let (a, b, c) = (*a as usize, *b as usize, *c as usize); @@ -928,10 +892,9 @@ mod tests { }; let mut tiny = reference.clone(); tiny.uvs[3] = -Vec2::X * 1e-20; - reference.compute_tangents(); - tiny.compute_tangents(); + let (reference, tiny) = (reference.corner_tangents(), tiny.corner_tangents()); for corner in 0..6 { - let (expected, actual) = (reference.tangents[reference.indices[corner] as usize], tiny.tangents[tiny.indices[corner] as usize]); + let (expected, actual) = (reference[corner], tiny[corner]); assert!(expected.truncate().dot(actual.truncate()) > 0.999, "{corner}: {expected:?} {actual:?}"); } } @@ -949,30 +912,13 @@ mod tests { for uv in &mut tiny.uvs { *uv *= 1e-30; } - reference.compute_tangents(); - tiny.compute_tangents(); - assert!(reference.tangents.iter().all(|tangent| tangent.w == reference.tangents[0].w)); + let (reference, tiny) = (reference.corner_tangents(), tiny.corner_tangents()); + assert!(reference.iter().all(|tangent| tangent.w == reference[0].w)); for corner in 0..3 { - assert_eq!(tiny.tangents[tiny.indices[corner] as usize].w, reference.tangents[reference.indices[corner] as usize].w); + assert_eq!(tiny[corner].w, reference[corner].w); } } - #[test] - fn fallback_visits_a_nonmanifold_welded_edge_once() { - let count = 1000u32; - let mut mesh = Mesh { positions: vec![Vec3::ZERO, Vec3::X], normals: vec![Vec3::Z; 2], uvs: vec![Vec2::ZERO, Vec2::X], ..Mesh::default() }; - for face in 0..count { - mesh.positions.push(Vec3::Y * (1.0 + face as f32 / count as f32)); - mesh.normals.push(Vec3::Z); - mesh.uvs.push(Vec2::Y * if face == 0 { 1e-30 } else { 1.0 }); - mesh.indices.extend([0, 1, face + 2]); - } - FALLBACK_ADJACENCY_VISITS.with(|visits| visits.set(0)); - mesh.compute_tangents(); - let visits = FALLBACK_ADJACENCY_VISITS.with(|visits| visits.get()); - assert!(visits <= count as usize * 12, "nonmanifold traversal visited {visits} corners"); - } - #[test] fn ill_conditioned_uvs_keep_their_orientation_sign() { let mut mesh = Mesh { @@ -988,24 +934,6 @@ mod tests { assert!(mesh.tangents.iter().all(|tangent| tangent.w < 0.0)); } - #[test] - fn collapsed_faces_do_not_allocate_fallback_connectivity() { - let mut mesh = Mesh { - positions: vec![Vec3::X * 2_000_000.0, Vec3::X * 2_000_001.0, Vec3::new(2_000_000.0, 1.0, 0.0)], - normals: vec![Vec3::Z; 3], - uvs: vec![Vec2::ZERO, Vec2::X, Vec2::Y], - indices: vec![0, 1, 2], - ..Mesh::default() - }; - for _ in 0..1000 { - mesh.indices.extend([0, 0, 1]); - } - FALLBACK_CONNECTIVITY_CORNERS.with(|corners| corners.set(0)); - mesh.compute_tangents(); - let corners = FALLBACK_CONNECTIVITY_CORNERS.with(|corners| corners.get()); - assert_eq!(corners, 3, "fallback allocated connectivity for {corners} corners"); - } - #[test] fn regional_fallback_keeps_a_valid_nearly_parallel_uv_gradient() { let mut mesh = Mesh { @@ -1015,8 +943,7 @@ mod tests { indices: vec![0, 1, 2, 0, 2, 3], ..Mesh::default() }; - mesh.compute_tangents(); - assert!(mesh.tangents[mesh.indices[1] as usize].truncate().dot(Vec3::Y) > 0.99); + assert!(mesh.corner_tangents()[1].truncate().dot(Vec3::Y) > 0.99); } #[test] @@ -1028,9 +955,8 @@ mod tests { indices: vec![0, 1, 2, 0, 1, 3], ..Mesh::default() }; - mesh.compute_tangents(); - for corner in 0..3 { - let tangent = mesh.tangents[mesh.indices[corner] as usize]; + let corners = mesh.corner_tangents(); + for &tangent in &corners[0..3] { assert!((Vec3::Z.cross(tangent.truncate()) * tangent.w).dot(Vec3::Y) > 0.0); } } @@ -1047,24 +973,6 @@ mod tests { assert!(result.is_err()); } - #[test] - fn fallback_traversal_excludes_collapsed_face_fans() { - let mut mesh = Mesh { - positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::X * 10.0, Vec3::X * 11.0, Vec3::new(10.0, 1.0, 0.0)], - normals: vec![Vec3::Z; 6], - uvs: vec![Vec2::ZERO, Vec2::Y * 1e-30, Vec2::X * 1e-30, Vec2::ZERO, Vec2::X, Vec2::Y], - indices: vec![0, 1, 2, 3, 4, 5], - ..Mesh::default() - }; - for _ in 0..1000 { - mesh.indices.extend([0, 1, 1]); - } - FALLBACK_ADJACENCY_VISITS.with(|visits| visits.set(0)); - mesh.compute_tangents(); - let visits = FALLBACK_ADJACENCY_VISITS.with(|visits| visits.get()); - assert!(visits <= mesh.indices.len() * 8, "fallback adjacency visited {visits} corners"); - } - #[test] fn fallback_boundaries_share_frames_across_equivalent_edge_vertices() { let mut mesh = Mesh { @@ -1074,9 +982,9 @@ mod tests { indices: vec![0, 1, 2, 3, 4, 5], ..Mesh::default() }; - mesh.compute_tangents(); - assert_eq!(mesh.tangents[mesh.indices[0] as usize], mesh.tangents[mesh.indices[3] as usize]); - assert_eq!(mesh.tangents[mesh.indices[2] as usize], mesh.tangents[mesh.indices[4] as usize]); + let corners = mesh.corner_tangents(); + assert_eq!(corners[0], corners[3]); + assert_eq!(corners[2], corners[4]); } #[test] @@ -1088,26 +996,19 @@ mod tests { indices: vec![0, 1, 2, 0, 2, 3], ..Mesh::default() }; - mesh.compute_tangents(); - assert_eq!(mesh.indices[0], mesh.indices[3]); - assert_eq!(mesh.indices[2], mesh.indices[4]); + let corners = mesh.corner_tangents(); + assert_eq!(corners[0], corners[3]); + assert_eq!(corners[2], corners[4]); } #[test] - fn an_isolated_uv_outlier_only_runs_fallback_for_its_island() { - let mut mesh = Mesh::default(); - for face in 0..1001 { - let x = face as f32 * 2.0; - mesh.positions.extend([Vec3::X * x, Vec3::X * (x + 1.0), Vec3::new(x, 1.0, 0.0)]); - mesh.normals.extend([Vec3::Z; 3]); - let scale = if face == 1000 { 1e-30 } else { 1.0 }; - mesh.uvs.extend([Vec2::ZERO, Vec2::X * scale, Vec2::Y * scale]); - mesh.indices.extend([face * 3, face * 3 + 1, face * 3 + 2]); + fn an_isolated_uv_outlier_only_selects_its_island_for_fallback() { + let mut indices = Vec::new(); + for face in 0..1001u32 { + indices.extend([face * 3, face * 3 + 1, face * 3 + 2]); } - FALLBACK_FACE_VISITS.with(|visits| visits.set(0)); - mesh.compute_tangents(); - let visits = FALLBACK_FACE_VISITS.with(|visits| visits.get()); - assert_eq!(visits, 1, "fallback visited {visits} faces for one isolated UV outlier"); + let eligible: Vec = (0..1001).collect(); + assert_eq!(connected_fallback_faces(&indices, &eligible, &[1000]), vec![1000]); } #[test] @@ -1119,8 +1020,7 @@ mod tests { indices: vec![0, 1, 2, 3, 4, 5], ..Mesh::default() }; - mesh.compute_tangents(); - assert!(mesh.tangents[mesh.indices[3] as usize].truncate().dot(Vec3::Y) > 0.99); + assert!(mesh.corner_tangents()[3].truncate().dot(Vec3::Y) > 0.99); } #[test] @@ -1132,9 +1032,9 @@ mod tests { indices: vec![0, 1, 2, 0, 3, 4], ..Mesh::default() }; - mesh.compute_tangents(); - assert!(mesh.tangents[mesh.indices[0] as usize].truncate().dot(Vec3::X) > 0.99); - assert!(mesh.tangents[mesh.indices[3] as usize].truncate().dot(-Vec3::X) > 0.99); + let corners = mesh.corner_tangents(); + assert!(corners[0].truncate().dot(Vec3::X) > 0.99); + assert!(corners[3].truncate().dot(-Vec3::X) > 0.99); } #[test] @@ -1146,9 +1046,8 @@ mod tests { indices: vec![0, 1, 2, 0, 3, 2], ..Mesh::default() }; - mesh.compute_tangents(); - assert_eq!(mesh.indices[0], mesh.indices[3]); - assert_eq!(mesh.tangents[mesh.indices[3] as usize], mesh.tangents[mesh.indices[0] as usize]); + let corners = mesh.corner_tangents(); + assert_eq!(corners[3], corners[0]); } #[test] @@ -1171,11 +1070,9 @@ mod tests { p.x += 2_000_000.0; } mesh.uvs = vec![Vec2::ZERO, Vec2::X, Vec2::ONE, Vec2::new(0.0, 2.0)]; - let count = mesh.positions.len(); - mesh.compute_tangents(); - assert_eq!(mesh.positions.len(), count); - assert_eq!(mesh.indices[0], mesh.indices[3]); - assert_eq!(mesh.indices[2], mesh.indices[4]); + let corners = mesh.corner_tangents(); + assert_eq!(corners[0], corners[3]); + assert_eq!(corners[2], corners[4]); } #[test] @@ -1187,9 +1084,9 @@ mod tests { indices: vec![0, 1, 2, 0, 3, 2], ..Mesh::default() }; - mesh.compute_tangents(); - assert_eq!(mesh.indices[0], mesh.indices[3]); - assert!(mesh.tangents[mesh.indices[4] as usize].truncate().dot(Vec3::Y) > 0.99); + let corners = mesh.corner_tangents(); + assert_eq!(corners[0], corners[3]); + assert!(corners[4].truncate().dot(Vec3::Y) > 0.99); } #[test] @@ -1224,10 +1121,9 @@ mod tests { indices: vec![0, 1, 2, 1, 3, 2], ..Mesh::default() }; - mesh.compute_tangents(); - assert_ne!(mesh.indices[1], mesh.indices[3]); - assert_ne!(mesh.indices[2], mesh.indices[5]); - assert!(mesh.tangents[mesh.indices[1] as usize].w * mesh.tangents[mesh.indices[3] as usize].w < 0.0); + let corners = mesh.corner_tangents(); + assert!(corners[1].w * corners[3].w < 0.0); + assert!(corners[2].w * corners[5].w < 0.0); } #[test] @@ -1294,9 +1190,9 @@ mod tests { mesh.uvs.push(Vec2::ZERO); mesh.indices.extend_from_slice(&[0, duplicate, 1]); } - mesh.compute_tangents(); - assert_ne!(mesh.indices[0], mesh.indices[3]); - assert_eq!(mesh.tangents[mesh.indices[0] as usize].w, mesh.tangents[mesh.indices[3] as usize].w); + let corners = mesh.corner_tangents(); + assert_ne!(corners[0], corners[3]); + assert_eq!(corners[0].w, corners[3].w); } #[test] @@ -1309,13 +1205,12 @@ mod tests { indices: vec![0, 0, 1, 0, 1, 2, 0, 3, 4], ..Mesh::default() }; - mesh.compute_tangents(); - assert_eq!(mesh.positions.len(), 6); - assert_eq!(mesh.indices[0], mesh.indices[3]); - assert_eq!(mesh.indices[1], mesh.indices[3]); - assert_eq!(mesh.indices[2], mesh.indices[4]); - assert_ne!(mesh.indices[3], mesh.indices[6]); - assert!(mesh.tangents.iter().all(|tangent| tangent.is_finite())); + let corners = mesh.corner_tangents(); + assert_eq!(corners[0], corners[3]); + assert_eq!(corners[1], corners[3]); + assert_eq!(corners[2], corners[4]); + assert_ne!(corners[3], corners[6]); + assert!(corners.iter().all(|tangent| tangent.is_finite())); } #[test] @@ -1330,13 +1225,11 @@ mod tests { indices: vec![0, 1, 2, 0, 3, 4], ..Mesh::default() }; - mesh.compute_tangents(); - let first = mesh.indices[0] as usize; - let second = mesh.indices[3] as usize; - assert_ne!(first, second); - assert_eq!(mesh.tangents[first].w, mesh.tangents[second].w); - assert!(mesh.tangents[first].truncate().dot(mesh.tangents[second].truncate()) > 0.99); - assert!((mesh.tangents[first].truncate() - mesh.tangents[second].truncate()).length() > 0.05); + let corners = mesh.corner_tangents(); + let (first, second) = (corners[0], corners[3]); + assert_eq!(first.w, second.w); + assert!(first.truncate().dot(second.truncate()) > 0.99); + assert!((first.truncate() - second.truncate()).length() > 0.05); } use super::*; @@ -1366,46 +1259,21 @@ mod tests { } #[test] - fn a_vertex_with_mirrored_frames_is_split() { + fn mirrored_frames_keep_the_indices_and_vertex_count() { // Triangle (0, 1, 2) has u growing with x. Triangle (1, 3, 2) has the opposite UV - // orientation, so vertices 1 and 2 need one tangent frame for each triangle. - let corners = [Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(1.0, 1.0, 0.0)]; - let m = Mesh::from_parts( - corners.to_vec(), - None, - vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(0.0, 0.0), Vec2::new(1.0, 2.0)], - vec![0, 1, 2, 1, 3, 2], - "Default", - ) - .unwrap(); - assert_eq!(m.positions.len(), 6, "vertices 1 and 2 each get a copy"); - assert_eq!((m.normals.len(), m.uvs.len(), m.tangents.len()), (6, 6, 6)); - let signs = |t: usize| m.indices[t * 3..t * 3 + 3].iter().map(|&i| m.tangents[i as usize].w).collect::>(); - assert!(signs(0).iter().all(|w| *w == signs(0)[0]), "{:?}", signs(0)); - assert!(signs(1).iter().all(|w| *w == signs(1)[0]), "{:?}", signs(1)); - assert_ne!(signs(0)[0], signs(1)[0]); - let originals = [0, 1, 2, 3, 1, 2]; - for (i, p) in m.positions.iter().enumerate() { - assert_eq!(*p, corners[originals[i]], "vertex {i}"); - } - m.validate().unwrap(); - } - - #[test] - fn split_vertices_keep_their_colors() { + // orientation, so vertices 1 and 2 have one corner frame for each triangle. let mut m = Mesh { positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(1.0, 1.0, 0.0)], uvs: vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(0.0, 0.0), Vec2::new(1.0, 2.0)], - colors: (0..4).map(|i| Vec4::splat(i as f32 / 4.0)).collect(), indices: vec![0, 1, 2, 1, 3, 2], - materials: vec!["Default".into()], - submeshes: vec![SubMesh { name: "Default".into(), material: 0, start: 0, count: 6 }], ..Mesh::default() }; + let corners = m.clone().corner_tangents(); + assert!(corners[1].w * corners[3].w < 0.0); m.compute_tangents(); - assert_eq!(m.positions.len(), 6); - assert_eq!(m.colors, [0, 1, 2, 3, 1, 2].map(|i| Vec4::splat(i as f32 / 4.0))); - m.validate().unwrap(); + assert_eq!(m.indices, [0, 1, 2, 1, 3, 2]); + assert_eq!((m.positions.len(), m.normals.len(), m.uvs.len(), m.tangents.len()), (4, 4, 4, 4)); + assert_eq!((m.tangents[1], m.tangents[2], m.tangents[3]), (corners[1], corners[2], corners[4])); } #[test] From 74cbf60c48be023401675b5ba63683fb3711bc41 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 07:35:51 -0800 Subject: [PATCH 08/31] craft-mesh-ops: f32 UV determinants that flip sign use the f64 fallback A face whose f32 UV determinant has the opposite sign of the f64 one now goes to the f64 fallback, so its handedness follows the stored UVs. compute_tangents builds the per-vertex frames without a second per-vertex buffer and frees the corner buffer before filling unused vertices. --- crates/mesh-ops/src/mesh.rs | 59 +++++++++++++++++++++++++++++-------- 1 file changed, 47 insertions(+), 12 deletions(-) diff --git a/crates/mesh-ops/src/mesh.rs b/crates/mesh-ops/src/mesh.rs index dca7762175..861fbe2686 100644 --- a/crates/mesh-ops/src/mesh.rs +++ b/crates/mesh-ops/src/mesh.rs @@ -243,19 +243,26 @@ impl Mesh { /// corner that uses it; a vertex no triangle uses gets +X made perpendicular to its normal. /// Faces with coincident corners stay in the mesh but are omitted from MikkTSpace. Their /// corners reuse a generated frame for the same vertex when one is available. - /// Edge-connected regions containing a face whose f32 UV gradients overflow or underflow use the fallback. + /// Edge-connected regions containing a face whose f32 UV gradients overflow, underflow or reverse the UV orientation use the fallback. /// Both paths use the stored UVs. Each triangle with usable UV gradients has one handedness sign. pub fn compute_tangents(&mut self) { let corners = self.corner_tangents(); - let normals: Vec = self.normals.iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(); - let mut tangents = vec![None::; self.positions.len()]; + let mut tangents = vec![Vec4::ZERO; self.positions.len()]; for (&index, &t) in self.indices.iter().zip(&corners) { - if let Some(slot) = tangents.get_mut(index as usize) { - slot.get_or_insert(t); + if let Some(slot) = tangents.get_mut(index as usize) + && *slot == Vec4::ZERO + { + *slot = t; } } - self.tangents = - tangents.iter().enumerate().map(|(v, t)| t.unwrap_or_else(|| orthonormal(&normals, v, Vec4::new(1.0, 0.0, 0.0, 1.0)))).collect(); + drop(corners); + for (vertex, tangent) in tangents.iter_mut().enumerate() { + if *tangent == Vec4::ZERO { + let normal = self.normals[vertex].try_normalize().unwrap_or(Vec3::Y); + *tangent = orthonormal(&[normal], 0, Vec4::new(1.0, 0.0, 0.0, 1.0)); + } + } + self.tangents = tangents; } /// The tangent frame of every triangle corner, orthonormal to its vertex normal, as @@ -687,11 +694,16 @@ fn mikk_uvs_safe(positions: &[Vec3], uvs: &[Vec2], indices: &[u32]) -> bool { let (d1, d2) = (uvs[b] - uvs[a], uvs[c] - uvs[a]); let wide1 = uvs[b].as_dvec2() - uvs[a].as_dvec2(); let wide2 = uvs[c].as_dvec2() - uvs[a].as_dvec2(); - if wide1.perp_dot(wide2) == 0.0 { + let wide_determinant = wide1.perp_dot(wide2); + if wide_determinant == 0.0 { return true; } let determinant = d1.perp_dot(d2); - if determinant.abs() <= f32::MIN_POSITIVE || !determinant.is_finite() || !determinant.recip().is_finite() { + if determinant.abs() <= f32::MIN_POSITIVE + || !determinant.is_finite() + || !determinant.recip().is_finite() + || determinant.is_sign_negative() != wide_determinant.is_sign_negative() + { return false; } let (e1, e2) = (positions[b] - positions[a], positions[c] - positions[a]); @@ -934,6 +946,25 @@ mod tests { assert!(mesh.tangents.iter().all(|tangent| tangent.w < 0.0)); } + #[test] + fn rounded_uv_determinant_does_not_reverse_handedness() { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y], + normals: vec![Vec3::Z; 3], + uvs: vec![Vec2::new(0.0, 0.1), Vec2::new(0.1, 0.6), Vec2::new(0.03, 0.25)], + indices: vec![0, 1, 2], + ..Mesh::default() + }; + let determinant = (mesh.uvs[1] - mesh.uvs[0]).perp_dot(mesh.uvs[2] - mesh.uvs[0]); + let wide_determinant = (mesh.uvs[1].as_dvec2() - mesh.uvs[0].as_dvec2()).perp_dot(mesh.uvs[2].as_dvec2() - mesh.uvs[0].as_dvec2()); + assert_ne!(determinant.is_sign_negative(), wide_determinant.is_sign_negative()); + assert!(!mikk_uvs_safe(&mesh.positions, &mesh.uvs, &mesh.indices)); + mesh.compute_tangents(); + for tangent in &mesh.tangents { + assert_eq!(tangent.w.is_sign_negative(), wide_determinant.is_sign_negative()); + } + } + #[test] fn regional_fallback_keeps_a_valid_nearly_parallel_uv_gradient() { let mut mesh = Mesh { @@ -1263,8 +1294,9 @@ mod tests { // Triangle (0, 1, 2) has u growing with x. Triangle (1, 3, 2) has the opposite UV // orientation, so vertices 1 and 2 have one corner frame for each triangle. let mut m = Mesh { - positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(1.0, 1.0, 0.0)], - uvs: vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(0.0, 0.0), Vec2::new(1.0, 2.0)], + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(1.0, 1.0, 0.0), Vec3::Z], + normals: vec![Vec3::Z, Vec3::Z, Vec3::Z, Vec3::Z, Vec3::X], + uvs: vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(0.0, 0.0), Vec2::new(1.0, 2.0), Vec2::ZERO], indices: vec![0, 1, 2, 1, 3, 2], ..Mesh::default() }; @@ -1272,7 +1304,10 @@ mod tests { assert!(corners[1].w * corners[3].w < 0.0); m.compute_tangents(); assert_eq!(m.indices, [0, 1, 2, 1, 3, 2]); - assert_eq!((m.positions.len(), m.normals.len(), m.uvs.len(), m.tangents.len()), (4, 4, 4, 4)); + assert_eq!((m.positions.len(), m.normals.len(), m.uvs.len(), m.tangents.len()), (5, 5, 5, 5)); + assert!(m.tangents[4].is_finite()); + assert!(m.tangents[4].truncate().dot(Vec3::X).abs() < 1e-6); + assert!((m.tangents[4].truncate().length() - 1.0).abs() < 1e-6); assert_eq!((m.tangents[1], m.tangents[2], m.tangents[3]), (corners[1], corners[2], corners[4])); } From 07f10fc3c0933d9653ab28775a3795f9ab524a01 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 07:42:14 -0800 Subject: [PATCH 09/31] craft-mesh-ops: fully collapsed meshes get tangents without a corner buffer When every triangle has coincident corners, compute_tangents writes the per-vertex frames directly instead of allocating one frame per index first. The frames are the same as before. --- crates/mesh-ops/src/mesh.rs | 53 +++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/crates/mesh-ops/src/mesh.rs b/crates/mesh-ops/src/mesh.rs index 861fbe2686..e942968ca2 100644 --- a/crates/mesh-ops/src/mesh.rs +++ b/crates/mesh-ops/src/mesh.rs @@ -246,6 +246,30 @@ impl Mesh { /// Edge-connected regions containing a face whose f32 UV gradients overflow, underflow or reverse the UV orientation use the fallback. /// Both paths use the stored UVs. Each triangle with usable UV gradients has one handedness sign. pub fn compute_tangents(&mut self) { + let n = self.positions.len(); + let (triangles, trailing_indices) = self.indices.as_chunks::<3>(); + if triangles.iter().all(|vertices| { + let [Some(a), Some(b), Some(c)] = vertices.map(|index| self.positions.get(index as usize)) else { return false }; + a == b || a == c || b == c + }) && trailing_indices.iter().all(|&index| (index as usize) < n) + { + if self.normals.len() != n { + self.compute_normals(); + } + if self.uvs.len() != n { + self.uvs = vec![Vec2::ZERO; n]; + } + let mut tangents = vec![Vec4::new(1.0, 0.0, 0.0, 1.0); n]; + for &index in &self.indices { + tangents[index as usize].w = -1.0; + } + for (tangent, normal) in tangents.iter_mut().zip(&self.normals) { + let normal = normal.try_normalize().unwrap_or(Vec3::Y); + *tangent = orthonormal(&[normal], 0, *tangent); + } + self.tangents = tangents; + return; + } let corners = self.corner_tangents(); let mut tangents = vec![Vec4::ZERO; self.positions.len()]; for (&index, &t) in self.indices.iter().zip(&corners) { @@ -1289,6 +1313,35 @@ mod tests { assert_eq!(m.triangles_of(0).collect::>(), vec![0, 1]); } + #[test] + fn collapsed_tangents_match_corner_frames_and_preserve_unused_vertices() { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::ZERO, Vec3::Y, Vec3::Z], + normals: vec![Vec3::new(2.0, 3.0, 4.0), Vec3::X, Vec3::NAN, Vec3::new(1.0, 2.0, 3.0)], + indices: vec![0, 1, 2, 2, 0, 1, 1, 1, 1], + ..Mesh::default() + }; + let mut reference = mesh.clone(); + let corners = reference.corner_tangents(); + mesh.compute_tangents(); + assert_eq!(mesh.indices, reference.indices); + assert_eq!(mesh.positions, reference.positions); + assert_eq!(mesh.uvs, reference.uvs); + assert_eq!(mesh.tangents.len(), mesh.positions.len()); + for vertex in 0..mesh.positions.len() { + let expected = reference.indices.iter().position(|&index| index as usize == vertex).map_or_else( + || { + let normal = reference.normals[vertex].try_normalize().unwrap_or(Vec3::Y); + orthonormal(&[normal], 0, Vec4::new(1.0, 0.0, 0.0, 1.0)) + }, + |corner| corners[corner], + ); + assert_eq!(mesh.tangents[vertex], expected, "vertex {vertex}"); + } + assert!(mesh.tangents[..3].iter().all(|tangent| tangent.w == -1.0)); + assert_eq!(mesh.tangents[3].w, 1.0); + } + #[test] fn mirrored_frames_keep_the_indices_and_vertex_count() { // Triangle (0, 1, 2) has u growing with x. Triangle (1, 3, 2) has the opposite UV From b3cd5e3d1343b28f775cfde8ee9cae84cd10c2d4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 08:09:02 -0800 Subject: [PATCH 10/31] craft-mesh-ops: compute_tangents_split splits vertices at mirrored seams compute_tangents_split computes the same corner frames as compute_tangents and gives a vertex one copy per further frame its corners have (UVs mirrored across it). It returns the original vertex of each copy in order, so callers can extend their own per-vertex data. Frames that differ only in the sign of a zero component share a vertex. Meshes with out-of-range indices, a partial trailing triangle or only collapsed faces keep their topology. --- crates/mesh-ops/README.md | 3 +- crates/mesh-ops/src/mesh.rs | 224 +++++++++++++++++++++++++++++++++++- 2 files changed, 220 insertions(+), 7 deletions(-) diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md index 0b96711394..56865b03e1 100644 --- a/crates/mesh-ops/README.md +++ b/crates/mesh-ops/README.md @@ -11,7 +11,8 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form glTF 2.0 recommends for meshes without tangents (): `w` holds the bitangent sign. `compute_tangents` keeps the indices and the vertex count; a vertex whose triangles have - different tangent frames (mirrored UVs) takes the frame of its first corner. Faces with coincident corners stay in the mesh and reuse shared vertex frames when + different tangent frames (mirrored UVs) takes the frame of its first corner. + `compute_tangents_split` instead splits such a vertex into one copy per frame. Faces with coincident corners stay in the mesh and reuse shared vertex frames when available. MikkTSpace omits those faces. A mesh with more than 2,048 noncollapsed triangles around one vertex, or with non-finite positions or UVs, or whose largest absolute position or UV component is nonzero and outside 1e-6 to 1e6, gets per-corner tangents from f64 UV gradients instead of MikkTSpace. An edge-connected region containing a face whose f32 UV gradients overflow or underflow uses that fallback. diff --git a/crates/mesh-ops/src/mesh.rs b/crates/mesh-ops/src/mesh.rs index e942968ca2..1934cd46db 100644 --- a/crates/mesh-ops/src/mesh.rs +++ b/crates/mesh-ops/src/mesh.rs @@ -247,12 +247,7 @@ impl Mesh { /// Both paths use the stored UVs. Each triangle with usable UV gradients has one handedness sign. pub fn compute_tangents(&mut self) { let n = self.positions.len(); - let (triangles, trailing_indices) = self.indices.as_chunks::<3>(); - if triangles.iter().all(|vertices| { - let [Some(a), Some(b), Some(c)] = vertices.map(|index| self.positions.get(index as usize)) else { return false }; - a == b || a == c || b == c - }) && trailing_indices.iter().all(|&index| (index as usize) < n) - { + if self.all_faces_collapsed() { if self.normals.len() != n { self.compute_normals(); } @@ -289,6 +284,88 @@ impl Mesh { self.tangents = tangents; } + /// Whether every index is in range and every triangle has coincident corners. + fn all_faces_collapsed(&self) -> bool { + let n = self.positions.len(); + let (triangles, trailing_indices) = self.indices.as_chunks::<3>(); + triangles.iter().all(|vertices| { + let [Some(a), Some(b), Some(c)] = vertices.map(|index| self.positions.get(index as usize)) else { return false }; + a == b || a == c || b == c + }) && trailing_indices.iter().all(|&index| (index as usize) < n) + } + + /// The tangents of [`Mesh::compute_tangents`], with a vertex split where its corners get + /// different frames (UVs mirrored across it). The first frame stays on the vertex; every + /// further frame gets a copy of the vertex (position, normal, UV and color), and the corners + /// with that frame use the copy. A copy whose index would not fit in `u32` is not made, and + /// those corners keep the first frame. Corners that share a frame get bit-identical tangents. + /// + /// This changes the indices and can add vertices. The result lists, in order, the original + /// vertex each copy was made from, so per-vertex data held outside the mesh can be extended + /// to match: copy `i` is vertex `old_count + i`. + /// + /// [`Mesh::wire_edges`] matches the two sides of a polygon diagonal by vertex index, so a + /// hidden diagonal whose endpoints were split on one side is drawn afterwards. + /// Out-of-range indices or an index buffer length that is not a multiple of 3 leave + /// the topology unchanged, compute tangents with + /// [`Mesh::compute_tangents`], and return an empty list. + pub fn compute_tangents_split(&mut self) -> Vec { + if !self.indices.len().is_multiple_of(3) + || self.indices.iter().any(|&index| index as usize >= self.positions.len()) + || self.all_faces_collapsed() + { + self.compute_tangents(); + return Vec::new(); + } + let corners = self.corner_tangents(); + let n = self.positions.len(); + let bits = |t: Vec4| t.to_array().map(|component| if component == 0.0 { 0 } else { component.to_bits() }); + let mut tangents = vec![None::; n]; + let mut copies: Vec<(u32, Vec4)> = Vec::new(); + let mut copy_of: std::collections::HashMap<(u32, [u32; 4]), u32> = std::collections::HashMap::new(); + for (index, &t) in self.indices.iter_mut().zip(&corners) { + let v = *index; + let Some(slot) = tangents.get_mut(v as usize) else { continue }; + match slot { + None => *slot = Some(t), + Some(first) if bits(*first) == bits(t) => {} + Some(_) => { + if let Some(©) = copy_of.get(&(v, bits(t))) { + *index = copy; + } else if let Ok(copy) = u32::try_from(n + copies.len()) { + copies.push((v, t)); + copy_of.insert((v, bits(t)), copy); + *index = copy; + } + } + } + } + drop(corners); + + // A vertex no triangle uses gets +X made perpendicular to its normal. + let mut out: Vec = (0..n) + .map(|v| { + tangents[v].unwrap_or_else(|| { + let normal = self.normals.get(v).copied().unwrap_or(Vec3::Y).try_normalize().unwrap_or(Vec3::Y); + orthonormal(&[normal], 0, Vec4::new(1.0, 0.0, 0.0, 1.0)) + }) + }) + .collect(); + out.extend(copies.iter().map(|(_, t)| *t)); + let has_colors = self.colors.len() == n; + for &(v, _) in &copies { + let v = v as usize; + self.positions.push(self.positions.get(v).copied().unwrap_or_default()); + self.normals.push(self.normals.get(v).copied().unwrap_or(Vec3::Y)); + self.uvs.push(self.uvs.get(v).copied().unwrap_or_default()); + if has_colors { + self.colors.push(self.colors.get(v).copied().unwrap_or(Vec4::ONE)); + } + } + self.tangents = out; + copies.into_iter().map(|(v, _)| v).collect() + } + /// The tangent frame of every triangle corner, orthonormal to its vertex normal, as /// [`Mesh::compute_tangents`] computes them. Missing normals are computed and missing UVs are /// set to zero first. @@ -1342,6 +1419,130 @@ mod tests { assert_eq!(mesh.tangents[3].w, 1.0); } + #[test] + fn a_vertex_with_mirrored_frames_is_split() { + // Triangle (0, 1, 2) has u growing with x. Triangle (1, 3, 2) has the opposite UV + // orientation, so vertices 1 and 2 need one tangent frame for each triangle. + let corners = [Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(1.0, 1.0, 0.0)]; + let mut m = Mesh::from_parts( + corners.to_vec(), + None, + vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(0.0, 0.0), Vec2::new(1.0, 2.0)], + vec![0, 1, 2, 1, 3, 2], + "Default", + ) + .unwrap(); + assert_eq!(m.positions.len(), 4, "compute_tangents does not split"); + assert_eq!(m.compute_tangents_split(), [1, 2]); + assert_eq!(m.positions.len(), 6, "vertices 1 and 2 each get a copy"); + assert_eq!((m.normals.len(), m.uvs.len(), m.tangents.len()), (6, 6, 6)); + let signs = |t: usize| m.indices[t * 3..t * 3 + 3].iter().map(|&i| m.tangents[i as usize].w).collect::>(); + assert!(signs(0).iter().all(|w| *w == signs(0)[0]), "{:?}", signs(0)); + assert!(signs(1).iter().all(|w| *w == signs(1)[0]), "{:?}", signs(1)); + assert_ne!(signs(0)[0], signs(1)[0]); + let originals = [0, 1, 2, 3, 1, 2]; + for (i, p) in m.positions.iter().enumerate() { + assert_eq!(*p, corners[originals[i]], "vertex {i}"); + } + m.validate().unwrap(); + } + + #[test] + fn signed_zero_frames_share_vertices_and_copies() { + for earlier_frame in [false, true] { + let scale = 1e-30; + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(1.0, 1.0, 0.0), Vec3::new(1.0, 1.0, 0.0), Vec3::new(2.0, 0.0, 0.0)], + normals: vec![Vec3::Z; 6], + uvs: vec![Vec2::ZERO, Vec2::X * scale, Vec2::Y * scale, Vec2::ONE * scale, Vec2::X * (2.0 * scale), Vec2::ONE * scale], + indices: vec![0, 2, 1, 2, 3, 1], + ..Mesh::default() + }; + if earlier_frame { + mesh.indices.splice(0..0, [1, 4, 5]); + } + let offset = if earlier_frame { 3 } else { 0 }; + let corners = mesh.clone().corner_tangents(); + assert_eq!(corners[offset + 2], corners[offset + 5]); + assert_ne!(corners[offset + 2].to_array().map(f32::to_bits), corners[offset + 5].to_array().map(f32::to_bits)); + let original = mesh.indices.clone(); + let copies = mesh.compute_tangents_split(); + if earlier_frame { + assert_eq!(copies, [1]); + } else { + assert!(copies.is_empty()); + assert_eq!(mesh.indices, original); + } + assert_eq!(mesh.indices[offset + 2], mesh.indices[offset + 5]); + assert_eq!(mesh.indices[offset + 1], mesh.indices[offset + 3]); + } + } + + #[test] + fn split_vertices_keep_their_colors() { + let mut m = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(1.0, 1.0, 0.0)], + uvs: vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(0.0, 0.0), Vec2::new(1.0, 2.0)], + colors: (0..4).map(|i| Vec4::splat(i as f32 / 4.0)).collect(), + indices: vec![0, 1, 2, 1, 3, 2], + materials: vec!["Default".into()], + submeshes: vec![SubMesh { name: "Default".into(), material: 0, start: 0, count: 6 }], + ..Mesh::default() + }; + m.compute_tangents_split(); + assert_eq!(m.positions.len(), 6); + assert_eq!(m.colors, [0, 1, 2, 3, 1, 2].map(|i| Vec4::splat(i as f32 / 4.0))); + m.validate().unwrap(); + } + + #[test] + fn collapsed_meshes_are_not_split() { + let mut m = Mesh { positions: vec![Vec3::ZERO, Vec3::X], indices: vec![0, 0, 1, 1, 1, 0], ..Mesh::default() }; + assert!(m.compute_tangents_split().is_empty()); + assert_eq!((m.positions.len(), m.tangents.len()), (2, 2)); + } + + #[test] + fn invalid_indices_do_not_become_tangent_copies() { + for suffix in [vec![0], vec![0, 1], vec![4], vec![4, 0, 1], vec![5, 0, 1]] { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(1.0, 1.0, 0.0)], + normals: vec![Vec3::Z; 4], + uvs: vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(0.0, 0.0), Vec2::new(1.0, 2.0)], + indices: vec![0, 1, 2, 1, 3, 2], + ..Mesh::default() + }; + let mut valid = mesh.clone(); + assert!(!valid.compute_tangents_split().is_empty()); + mesh.indices.extend(suffix); + let mut expected = mesh.clone(); + expected.compute_tangents(); + assert!(mesh.compute_tangents_split().is_empty()); + assert_eq!(mesh, expected); + assert!(mesh.validate().is_err()); + } + } + + #[test] + fn split_tangents_match_the_corner_frames() { + let angle = 0.1f32; + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(angle.cos(), angle.sin(), 0.0), Vec3::new(-angle.sin(), angle.cos(), 0.0)], + normals: vec![Vec3::Z; 5], + uvs: vec![Vec2::ZERO, Vec2::Y, Vec2::X, Vec2::Y, Vec2::X], + indices: vec![0, 0, 1, 0, 1, 2, 0, 3, 4], + ..Mesh::default() + }; + let corners = mesh.clone().corner_tangents(); + mesh.compute_tangents_split(); + assert_eq!(mesh.positions.len(), 6); + assert_eq!(mesh.indices[0], mesh.indices[3]); + assert_ne!(mesh.indices[3], mesh.indices[6]); + for (corner, &index) in mesh.indices.iter().enumerate() { + assert_eq!(mesh.tangents[index as usize], corners[corner], "corner {corner}"); + } + } + #[test] fn mirrored_frames_keep_the_indices_and_vertex_count() { // Triangle (0, 1, 2) has u growing with x. Triangle (1, 3, 2) has the opposite UV @@ -1468,6 +1669,17 @@ mod tests { assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges"); } + #[test] + fn unrelated_coincident_edges_do_not_hide_seam_exposed_diagonals() { + let mut mesh = quad(); + mesh.positions.extend([mesh.positions[0], mesh.positions[0], mesh.positions[2], Vec3::Z]); + mesh.uvs.extend([mesh.uvs[0], mesh.uvs[0], mesh.uvs[2], Vec2::ZERO]); + mesh.indices = vec![0, 1, 2, 4, 2, 3, 5, 6, 7]; + mesh.submeshes[0].count = mesh.indices.len() as u32; + mesh.diagonals = vec![0b100, 0b001, 0]; + assert_eq!(mesh.wire_edges(), vec![vec![(0, 1), (1, 2), (0, 2), (2, 4), (2, 3), (3, 4), (5, 6), (6, 7), (5, 7)]]); + } + #[test] fn uv_seams_are_where_the_uv_layout_splits() { let mesh = quad(); From 8592eb9101fa7deab1de31f26ffdbcae4aa27161 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 08:13:52 -0800 Subject: [PATCH 11/31] craft-mesh-ops: compute_tangents_split keeps topology for mismatched colors A nonempty color array whose length differs from the vertex count now keeps the topology unchanged, so the split cannot make the mismatch pass validate. The first frame of each vertex goes straight into the output buffer. --- crates/mesh-ops/src/mesh.rs | 101 +++++++++++++++++++++++++++--------- 1 file changed, 77 insertions(+), 24 deletions(-) diff --git a/crates/mesh-ops/src/mesh.rs b/crates/mesh-ops/src/mesh.rs index 1934cd46db..8dc9541432 100644 --- a/crates/mesh-ops/src/mesh.rs +++ b/crates/mesh-ops/src/mesh.rs @@ -306,12 +306,13 @@ impl Mesh { /// /// [`Mesh::wire_edges`] matches the two sides of a polygon diagonal by vertex index, so a /// hidden diagonal whose endpoints were split on one side is drawn afterwards. - /// Out-of-range indices or an index buffer length that is not a multiple of 3 leave - /// the topology unchanged, compute tangents with - /// [`Mesh::compute_tangents`], and return an empty list. + /// Out-of-range indices, an index buffer length that is not a multiple of 3, or a nonempty + /// colors array whose length differs from the vertex count leave the topology unchanged, compute + /// tangents with [`Mesh::compute_tangents`], and return an empty list. pub fn compute_tangents_split(&mut self) -> Vec { if !self.indices.len().is_multiple_of(3) || self.indices.iter().any(|&index| index as usize >= self.positions.len()) + || (!self.colors.is_empty() && self.colors.len() != self.positions.len()) || self.all_faces_collapsed() { self.compute_tangents(); @@ -320,37 +321,33 @@ impl Mesh { let corners = self.corner_tangents(); let n = self.positions.len(); let bits = |t: Vec4| t.to_array().map(|component| if component == 0.0 { 0 } else { component.to_bits() }); - let mut tangents = vec![None::; n]; + let mut out = vec![Vec4::ZERO; n]; let mut copies: Vec<(u32, Vec4)> = Vec::new(); let mut copy_of: std::collections::HashMap<(u32, [u32; 4]), u32> = std::collections::HashMap::new(); for (index, &t) in self.indices.iter_mut().zip(&corners) { let v = *index; - let Some(slot) = tangents.get_mut(v as usize) else { continue }; - match slot { - None => *slot = Some(t), - Some(first) if bits(*first) == bits(t) => {} - Some(_) => { - if let Some(©) = copy_of.get(&(v, bits(t))) { - *index = copy; - } else if let Ok(copy) = u32::try_from(n + copies.len()) { - copies.push((v, t)); - copy_of.insert((v, bits(t)), copy); - *index = copy; - } + let Some(slot) = out.get_mut(v as usize) else { continue }; + if *slot == Vec4::ZERO { + *slot = t; + } else if bits(*slot) != bits(t) { + if let Some(©) = copy_of.get(&(v, bits(t))) { + *index = copy; + } else if let Ok(copy) = u32::try_from(n + copies.len()) { + copies.push((v, t)); + copy_of.insert((v, bits(t)), copy); + *index = copy; } } } drop(corners); // A vertex no triangle uses gets +X made perpendicular to its normal. - let mut out: Vec = (0..n) - .map(|v| { - tangents[v].unwrap_or_else(|| { - let normal = self.normals.get(v).copied().unwrap_or(Vec3::Y).try_normalize().unwrap_or(Vec3::Y); - orthonormal(&[normal], 0, Vec4::new(1.0, 0.0, 0.0, 1.0)) - }) - }) - .collect(); + for (v, tangent) in out.iter_mut().enumerate() { + if *tangent == Vec4::ZERO { + let normal = self.normals.get(v).copied().unwrap_or(Vec3::Y).try_normalize().unwrap_or(Vec3::Y); + *tangent = orthonormal(&[normal], 0, Vec4::new(1.0, 0.0, 0.0, 1.0)); + } + } out.extend(copies.iter().map(|(_, t)| *t)); let has_colors = self.colors.len() == n; for &(v, _) in &copies { @@ -1447,6 +1444,37 @@ mod tests { m.validate().unwrap(); } + #[test] + fn split_tangents_preserve_first_frames_and_fill_unused_vertices() { + for mirrored in [false, true] { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(1.0, 1.0, 0.0), Vec3::Z], + normals: vec![Vec3::Z, Vec3::Z, Vec3::Z, Vec3::Z, Vec3::X], + uvs: vec![Vec2::ZERO, Vec2::X, Vec2::Y, if mirrored { Vec2::new(1.0, -1.0) } else { Vec2::ONE }, Vec2::ZERO], + indices: vec![0, 1, 2, 1, 3, 2, 1, 3, 2], + ..Mesh::default() + }; + let original_indices = mesh.indices.clone(); + let corners = mesh.clone().corner_tangents(); + let mut expected = mesh.clone(); + expected.compute_tangents(); + let copies = mesh.compute_tangents_split(); + assert_eq!(&mesh.tangents[..expected.positions.len()], expected.tangents.as_slice()); + assert_eq!(mesh.tangents.len(), mesh.positions.len()); + assert!(mesh.tangents.iter().all(|tangent| tangent.w.abs() == 1.0)); + for (corner, &index) in mesh.indices.iter().enumerate() { + assert_eq!(mesh.tangents[index as usize], corners[corner]); + } + if mirrored { + assert_eq!(copies, [1, 2]); + assert_eq!(&mesh.indices[3..6], &mesh.indices[6..9]); + } else { + assert!(copies.is_empty()); + assert_eq!(mesh.indices, original_indices); + } + } + } + #[test] fn signed_zero_frames_share_vertices_and_copies() { for earlier_frame in [false, true] { @@ -1495,6 +1523,31 @@ mod tests { m.validate().unwrap(); } + #[test] + fn mismatched_colors_do_not_become_valid_after_splitting() { + for color_count in [1, 3, 5, 6] { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(1.0, 1.0, 0.0)], + normals: vec![Vec3::Z; 4], + uvs: vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(0.0, 0.0), Vec2::new(1.0, 2.0)], + colors: (0..color_count).map(|i| Vec4::splat(i as f32 / 4.0)).collect(), + indices: vec![0, 1, 2, 1, 3, 2], + materials: vec!["Default".into()], + submeshes: vec![SubMesh { name: "Default".into(), material: 0, start: 0, count: 6 }], + ..Mesh::default() + }; + let mut valid = mesh.clone(); + valid.colors.clear(); + assert_eq!(valid.compute_tangents_split(), [1, 2]); + valid.validate().unwrap(); + let mut expected = mesh.clone(); + expected.compute_tangents(); + assert!(mesh.compute_tangents_split().is_empty()); + assert_eq!(mesh, expected); + assert!(mesh.validate().is_err()); + } + } + #[test] fn collapsed_meshes_are_not_split() { let mut m = Mesh { positions: vec![Vec3::ZERO, Vec3::X], indices: vec![0, 0, 1, 1, 1, 0], ..Mesh::default() }; From 33a08375d280596ec5f9b8fdc27c6e9dbb455b59 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 08:44:51 -0800 Subject: [PATCH 12/31] craft-mesh-ops: tangent docs limit the handedness guarantee to corner frames compute_tangents keeps the first frame of a vertex shared by mirrored triangles, so the stored signs of the other triangle can differ from its generated corner signs. The README and the compute_tangents rustdoc now say that only the generated corner frames of a triangle share one sign, and point callers who need both sides of a mirrored seam to compute_tangents_split, with the inputs it leaves unsplit. --- crates/mesh-ops/README.md | 8 +++++++- crates/mesh-ops/src/mesh.rs | 7 ++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md index 56865b03e1..1fbdb18701 100644 --- a/crates/mesh-ops/README.md +++ b/crates/mesh-ops/README.md @@ -16,7 +16,13 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form available. MikkTSpace omits those faces. A mesh with more than 2,048 noncollapsed triangles around one vertex, or with non-finite positions or UVs, or whose largest absolute position or UV component is nonzero and outside 1e-6 to 1e6, gets per-corner tangents from f64 UV gradients instead of MikkTSpace. An edge-connected region containing a face whose f32 UV gradients overflow or underflow uses that fallback. - Both paths use the stored UVs. Each triangle with usable UV gradients has one handedness sign. Tangents + Both paths use the stored UVs. The generated corner frames of a triangle with usable UV gradients + share one handedness sign. With `compute_tangents`, a vertex shared by mirrored triangles keeps + the first triangle's frame, so the stored signs of the other triangle can differ; use + `compute_tangents_split` when both sides of a mirrored seam need their own frames. It splits only + a mesh whose indices are in range, whose index count is a multiple of 3 and whose colors are + empty or one per vertex; any other mesh gets the `compute_tangents` result. Corners whose copy + would need an index above `u32::MAX` keep the first frame. Tangents are always finite; a non-finite normal counts as +Y. - **UV unwrapping.** `unwrap::auto_unwrap` makes a non-overlapping layout per material, splitting vertices where charts meet. diff --git a/crates/mesh-ops/src/mesh.rs b/crates/mesh-ops/src/mesh.rs index 8dc9541432..88368067ac 100644 --- a/crates/mesh-ops/src/mesh.rs +++ b/crates/mesh-ops/src/mesh.rs @@ -244,7 +244,12 @@ impl Mesh { /// Faces with coincident corners stay in the mesh but are omitted from MikkTSpace. Their /// corners reuse a generated frame for the same vertex when one is available. /// Edge-connected regions containing a face whose f32 UV gradients overflow, underflow or reverse the UV orientation use the fallback. - /// Both paths use the stored UVs. Each triangle with usable UV gradients has one handedness sign. + /// Both paths use the stored UVs. The generated corner frames of a triangle with usable UV + /// gradients share one handedness sign. The stored per-vertex frames need not: a vertex shared + /// by mirrored triangles keeps the first one's frame. [`Mesh::compute_tangents_split`] keeps + /// both sides of a mirrored seam when the mesh passes its input checks (indices in range, an + /// index count that is a multiple of 3, and no colors or one color per vertex) and each copy's + /// index fits in `u32`. pub fn compute_tangents(&mut self) { let n = self.positions.len(); if self.all_faces_collapsed() { From e1752a97278ddc5d359026ceb6b409bafb67042c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 08:46:13 -0800 Subject: [PATCH 13/31] craft-mesh-ops: tangent fallback and weld bound handle rounding cases - The weld work bound now counts every bucket that MikkTSpace's f32 midpoint cannot split, so a cluster of distinct positions one ULP apart in one grid cell no longer passes the bound. The bound is checked again after UV-unsafe regions are removed from the faces MikkTSpace sees. - The UV orientation is an exact determinant of the stored UVs, and the fallback takes its gradients from the best-conditioned corner, so a cyclic rotation of a triangle's indices keeps its frame and exactly collinear UVs stay degenerate. A zero exact determinant goes to MikkTSpace only when its f32 determinant is also zero. - The fallback projects each gradient and corner edge onto the vertex normal plane before weighting and before its direction checks, and an incident edge parallel to the normal gets a right-angle weight. - The README and compute_tangents docs say that one handedness sign holds for each triangle's per-corner frames, not for stored vertex tangents shared by mirrored triangles. --- crates/mesh-ops/README.md | 4 +- crates/mesh-ops/src/mesh.rs | 312 +++++++++++++++++++++++++++++++++--- 2 files changed, 292 insertions(+), 24 deletions(-) diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md index 0b96711394..9c5fb07507 100644 --- a/crates/mesh-ops/README.md +++ b/crates/mesh-ops/README.md @@ -15,7 +15,9 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form available. MikkTSpace omits those faces. A mesh with more than 2,048 noncollapsed triangles around one vertex, or with non-finite positions or UVs, or whose largest absolute position or UV component is nonzero and outside 1e-6 to 1e6, gets per-corner tangents from f64 UV gradients instead of MikkTSpace. An edge-connected region containing a face whose f32 UV gradients overflow or underflow uses that fallback. - Both paths use the stored UVs. Each triangle with usable UV gradients has one handedness sign. Tangents + Both paths use the stored UVs. The per-corner frames of each triangle with usable UV gradients + have one handedness sign. Stored vertex tangents can have mixed signs on a triangle when + mirrored triangles share vertices. Tangents are always finite; a non-finite normal counts as +Y. - **UV unwrapping.** `unwrap::auto_unwrap` makes a non-overlapping layout per material, splitting vertices where charts meet. diff --git a/crates/mesh-ops/src/mesh.rs b/crates/mesh-ops/src/mesh.rs index e942968ca2..a460970fbf 100644 --- a/crates/mesh-ops/src/mesh.rs +++ b/crates/mesh-ops/src/mesh.rs @@ -61,9 +61,9 @@ const SAFE_MAGNITUDE: f32 = 1e6; pub const MAX_MIKKTSPACE_VALENCE: usize = 2_048; /// Most comparisons MikkTSpace may make welding corners, for which tangents come from it. It -/// compares each corner with the corners before it at the same position until one has the same -/// normal and UV, so `k` corners at one position can cost about `k²` comparisons; the sum of `k²` -/// over the positions stays within this. This crate's own value: the 6,144 corners at the pole of +/// compares corners pairwise in buckets that its f32 midpoint cannot split, so `k` corners in +/// one bucket can cost about `k²` comparisons; the sum of `k²` over the buckets stays within +/// this. This crate's own value: the 6,144 corners at the pole of /// a sphere with 2,048 segments take about 3.8e7. pub const MAX_MIKKTSPACE_WELD_WORK: u64 = 1 << 27; @@ -244,7 +244,9 @@ impl Mesh { /// Faces with coincident corners stay in the mesh but are omitted from MikkTSpace. Their /// corners reuse a generated frame for the same vertex when one is available. /// Edge-connected regions containing a face whose f32 UV gradients overflow, underflow or reverse the UV orientation use the fallback. - /// Both paths use the stored UVs. Each triangle with usable UV gradients has one handedness sign. + /// Both paths use the stored UVs. The per-corner frames of each triangle with usable UV + /// gradients have one handedness sign. Stored vertex tangents can have mixed signs on a + /// triangle when mirrored triangles share vertices. pub fn compute_tangents(&mut self) { let n = self.positions.len(); let (triangles, trailing_indices) = self.indices.as_chunks::<3>(); @@ -316,6 +318,7 @@ impl Mesh { faces: if usable { Mikk::noncollapsed_faces(&self.positions, &self.indices) } else { None }, }; let affordable = usable && g.face_count() != 0 && g.affordable(); + let face_count = g.face_count(); let mut fallback_faces: Vec = if affordable { (0..g.face_count()) .map(|face| g.original_face(face)) @@ -332,7 +335,7 @@ impl Mesh { faces.retain(|face| fallback_faces.binary_search(face).is_err()); g.faces = Some(faces); } - if !(affordable && g.face_count() != 0 && mikktspace::generate_tangents(&mut g)) { + if !(affordable && g.face_count() != 0 && (g.face_count() == face_count || g.affordable()) && mikktspace::generate_tangents(&mut g)) { fill_simple_tangents(&self.positions, &normals, &self.uvs, &self.indices, g.corners); if self.indices.iter().all(|&index| (index as usize) < n) { g.fill_collapsed_corners(); @@ -622,9 +625,47 @@ fn simple_tangents(positions: &[Vec3], normals: &[Vec3], uvs: &[Vec2], indices: corners } +fn wide_uv_origin(uvs: [Vec2; 3]) -> (usize, f64) { + let [a, b, c] = uvs.map(|uv| uv.as_dvec2()); + let products = [a.x * b.y, -a.y * b.x, b.x * c.y, -b.y * c.x, c.x * a.y, -c.y * a.x]; + let mut expansion = [0.0; 6]; + let mut length = 0; + for mut product in products { + let mut next = 0; + for index in 0..length { + let term = expansion[index]; + let sum = product + term; + let rounded_term = sum - product; + let error = (product - (sum - rounded_term)) + (term - rounded_term); + if error != 0.0 { + expansion[next] = error; + next += 1; + } + product = sum; + } + expansion[next] = product; + length = next + 1; + } + let determinant: f64 = expansion[..length].iter().sum(); + let (mut origin, mut conditioning) = (0, -1.0); + for corner in 0..3 { + let a = uvs[(corner + 1) % 3].as_dvec2() - uvs[corner].as_dvec2(); + let b = uvs[(corner + 2) % 3].as_dvec2() - uvs[corner].as_dvec2(); + let scale = (a.x * b.y).abs() + (a.y * b.x).abs(); + let quality = if scale > 0.0 { determinant.abs() / scale } else { 0.0 }; + if quality > conditioning { + (origin, conditioning) = (corner, quality); + } + } + (origin, determinant) +} + fn fallback_gradients(positions: &[Vec3], uvs: &[Vec2], indices: &[u32]) -> Option<(DVec3, DVec3, DVec3, f64)> { let &[a, b, c] = indices else { return None }; let (a, b, c) = (a as usize, b as usize, c as usize); + let (origin, determinant) = wide_uv_origin([*uvs.get(a)?, *uvs.get(b)?, *uvs.get(c)?]); + let vertices = [a, b, c]; + let (a, b, c) = (vertices[origin], vertices[(origin + 1) % 3], vertices[(origin + 2) % 3]); let (pa, pb, pc) = (positions.get(a)?, positions.get(b)?, positions.get(c)?); if pa == pb || pa == pc || pb == pc { return None; @@ -632,7 +673,6 @@ fn fallback_gradients(positions: &[Vec3], uvs: &[Vec2], indices: &[u32]) -> Opti let (ua, ub, uc) = (uvs.get(a)?, uvs.get(b)?, uvs.get(c)?); let (e1, e2) = (pb.as_dvec3() - pa.as_dvec3(), pc.as_dvec3() - pa.as_dvec3()); let (d1, d2) = (ub.as_dvec2() - ua.as_dvec2(), uc.as_dvec2() - ua.as_dvec2()); - let determinant = d1.perp_dot(d2); if !determinant.is_finite() || determinant == 0.0 { return None; } @@ -686,13 +726,15 @@ fn fill_simple_tangents(positions: &[Vec3], normals: &[Vec3], uvs: &[Vec2], indi let mut sums = std::collections::HashMap::::new(); for (slot, &face) in valid_faces.iter().enumerate() { if let Some((tangent, ..)) = fallback_gradients(positions, uvs, &indices[face * 3..face * 3 + 3]) { - let direction = tangent.try_normalize().unwrap_or(DVec3::X); let triangle = &indices[face * 3..face * 3 + 3]; for corner in 0..3 { + let normal = normals.get(triangle[corner] as usize).copied().unwrap_or(Vec3::Y).as_dvec3(); + let project = |v: DVec3| v - normal * normal.dot(v); + let direction = project(tangent).try_normalize().unwrap_or(DVec3::ZERO); let origin = positions[triangle[corner] as usize].as_dvec3(); - let a = (positions[triangle[(corner + 1) % 3] as usize].as_dvec3() - origin).try_normalize().unwrap_or(DVec3::ZERO); - let b = (positions[triangle[(corner + 2) % 3] as usize].as_dvec3() - origin).try_normalize().unwrap_or(DVec3::ZERO); - let weight = a.cross(b).length().atan2(a.dot(b)); + let a = project(positions[triangle[(corner + 1) % 3] as usize].as_dvec3() - origin).try_normalize().unwrap_or(DVec3::ZERO); + let b = project(positions[triangle[(corner + 2) % 3] as usize].as_dvec3() - origin).try_normalize().unwrap_or(DVec3::ZERO); + let weight = if a == DVec3::ZERO || b == DVec3::ZERO { std::f64::consts::FRAC_PI_2 } else { a.cross(b).length().atan2(a.dot(b)) }; *sums.entry(root(&mut parents, slot * 3 + corner)).or_default() += direction * weight; } } @@ -704,6 +746,9 @@ fn fill_simple_tangents(positions: &[Vec3], normals: &[Vec3], uvs: &[Vec2], indi let corner = &mut corners[index]; if let Some(tangent) = sums.get(&root(&mut parents, slot * 3 + local)).and_then(|sum| sum.try_normalize()) { let normal = normals.get(indices[index] as usize).copied().unwrap_or(Vec3::Y).as_dvec3(); + let tangent = (tangent - normal * normal.dot(tangent)).normalize_or_zero(); + let gradient = gradient - normal * normal.dot(gradient); + let bitangent = bitangent - normal * normal.dot(bitangent); if tangent.dot(gradient) > 0.0 && (normal.cross(tangent) * f64::from(corner.w)).dot(bitangent) > 0.0 { *corner = tangent.as_vec3().extend(corner.w); } @@ -716,13 +761,11 @@ fn mikk_uvs_safe(positions: &[Vec3], uvs: &[Vec2], indices: &[u32]) -> bool { let [a, b, c] = indices else { return false }; let (a, b, c) = (*a as usize, *b as usize, *c as usize); let (d1, d2) = (uvs[b] - uvs[a], uvs[c] - uvs[a]); - let wide1 = uvs[b].as_dvec2() - uvs[a].as_dvec2(); - let wide2 = uvs[c].as_dvec2() - uvs[a].as_dvec2(); - let wide_determinant = wide1.perp_dot(wide2); - if wide_determinant == 0.0 { - return true; - } + let (_, wide_determinant) = wide_uv_origin([uvs[a], uvs[b], uvs[c]]); let determinant = d1.perp_dot(d2); + if wide_determinant == 0.0 { + return determinant == 0.0; + } if determinant.abs() <= f32::MIN_POSITIVE || !determinant.is_finite() || !determinant.recip().is_finite() @@ -865,26 +908,69 @@ impl Mikk<'_> { } /// The most triangles that share one vertex as MikkTSpace sees it, and the sum of the squared - /// corner counts of its positions. It welds corners whose position, normal and UV, as this + /// corner counts of its unsplit buckets. It welds corners whose position, normal and UV, as this /// type passes them, are equal (0 and -0 alike). fn welding(&self) -> (usize, u64) { use mikktspace::Geometry; let bits = |x: f32| if x == 0.0 { 0 } else { x.to_bits() }; let mut count: std::collections::HashMap<[u32; 8], usize> = std::collections::HashMap::new(); - let mut at_position: std::collections::HashMap<[u32; 3], u64> = std::collections::HashMap::new(); - let (mut most, mut work) = (0, 0u64); + let mut positions = Vec::with_capacity(self.num_faces() * 3); + let mut most = 0; for face in 0..self.num_faces() { for vert in 0..3 { let ([px, py, pz], [nx, ny, nz], [u, v]) = (self.position(face, vert), self.normal(face, vert), self.tex_coord(face, vert)); let c = count.entry([px, py, pz, nx, ny, nz, u, v].map(bits)).or_insert(0); *c += 1; most = most.max(*c); - // k² grows by 2k + 1 with the (k + 1)th corner. - let k = at_position.entry([px, py, pz].map(bits)).or_insert(0); - work = work.saturating_add(k.saturating_mul(2).saturating_add(1)); - *k += 1; + positions.push((0usize, Vec3::new(px, py, pz))); } } + fn bounds(positions: &[(usize, Vec3)]) -> (Vec3, Vec3, usize) { + let (lo, hi) = positions.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), &(_, p)| (lo.min(p), hi.max(p))); + let d = hi - lo; + let axis = if d.y > d.x && d.y > d.z { + 1 + } else if d.z > d.x { + 2 + } else { + 0 + }; + (lo, hi, axis) + } + fn bucket_work(positions: &mut [(usize, Vec3)], depth: usize) -> u64 { + if positions.len() < 2 { + return positions.len() as u64; + } + let (lo, hi, axis) = bounds(positions); + let midpoint = 0.5 * (hi[axis] + lo[axis]); + // Remaining buckets at the depth limit count every possible pair. + if depth == 64 || midpoint <= lo[axis] || midpoint >= hi[axis] { + let k = positions.len() as u64; + return k.saturating_mul(k); + } + let mut split = 0; + for next in 0..positions.len() { + if positions[next].1[axis] < midpoint { + positions.swap(split, next); + split += 1; + } + } + let (left, right) = positions.split_at_mut(split); + bucket_work(left, depth + 1).saturating_add(bucket_work(right, depth + 1)) + } + let (lo, hi, axis) = bounds(&positions); + for (cell, position) in &mut positions { + *cell = ((2048.0 * ((position[axis] - lo[axis]) / (hi[axis] - lo[axis]))) as usize).min(2047); + } + positions.sort_unstable_by_key(|&(cell, _)| cell); + let mut remaining = positions.as_mut_slice(); + let mut work = 0u64; + while let Some(&(cell, _)) = remaining.first() { + let end = remaining.partition_point(|&(next, _)| next == cell); + let (bucket, rest) = remaining.split_at_mut(end); + work = work.saturating_add(bucket_work(bucket, 0)); + remaining = rest; + } (most, work) } } @@ -917,6 +1003,186 @@ impl mikktspace::Geometry for Mikk<'_> { #[cfg(test)] mod tests { + #[test] + fn removing_unsafe_uv_faces_rechecks_weld_work() { + let next = f32::from_bits(1.0f32.to_bits() + 1); + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X * 2.0, Vec3::Y], + normals: vec![Vec3::Z; 3], + uvs: vec![Vec2::ZERO; 3], + indices: vec![0, 1, 2], + ..Mesh::default() + }; + for corner in 0..12_000 { + mesh.indices.push(mesh.positions.len() as u32); + mesh.positions.push(Vec3::new(if corner % 2 == 0 { 1.0 } else { next }, corner as f32 * 1e-12, 0.0)); + mesh.normals.push(Vec3::Z); + mesh.uvs.push(Vec2::ZERO); + } + let probe = mesh.vertex_count() as u32; + let probe_corner = mesh.indices.len(); + mesh.positions.extend([Vec3::new(0.5, 0.25, 0.0), Vec3::new(0.5, 0.25, 1.0), Vec3::new(0.75, 0.5, 0.0), Vec3::new(0.25, 0.25, 0.0)]); + mesh.normals.extend([Vec3::Z; 4]); + mesh.uvs.extend([Vec2::ZERO, Vec2::ONE, Vec2::X, -Vec2::X]); + mesh.indices.extend([probe, probe + 1, probe + 2, probe + 1, probe, probe + 3]); + let base = mesh.vertex_count() as u32; + mesh.positions.extend([Vec3::X * (2.0 * next), Vec3::new(2.0, 0.5, 0.0), Vec3::new(2.0, 1.0, 0.0)]); + mesh.normals.extend([Vec3::Z; 3]); + mesh.uvs.extend([Vec2::ZERO, Vec2::X, Vec2::Y * 1e-30]); + mesh.indices.extend([base, base + 1, base + 2]); + let mut corners = vec![Vec4::ZERO; mesh.indices.len()]; + let mut g = + Mikk { positions: &mesh.positions, normals: &mesh.normals, uvs: &mesh.uvs, indices: &mesh.indices, corners: &mut corners, faces: None }; + assert!(g.affordable()); + let unsafe_face = mesh.triangle_count() - 1; + assert!(!mikk_uvs_safe(&mesh.positions, &mesh.uvs, &mesh.indices[unsafe_face * 3..])); + g.faces = Some((0..unsafe_face).collect()); + assert!(!g.affordable()); + let indices = mesh.indices.clone(); + let vertex_count = mesh.vertex_count(); + let actual = mesh.corner_tangents(); + assert!(actual[probe_corner + 4].truncate().dot(Vec3::X) > 0.99999, "the final weld budget must select fallback for the whole mesh"); + assert_eq!(mesh.indices, indices); + assert_eq!(mesh.vertex_count(), vertex_count); + } + + #[test] + fn exactly_collinear_uvs_stay_degenerate_under_cyclic_permutations() { + let s = 5.0 * 2.0f32.powi(-56); + let uvs = [Vec2::ZERO, Vec2::new(1.0, 3.0), Vec2::new(s, 3.0 * s)]; + for indices in [[0, 1, 2], [1, 2, 0], [2, 0, 1]] { + let rotated = indices.map(|index| uvs[index as usize]); + assert_eq!(wide_uv_origin(rotated).1, 0.0, "exactly collinear stored UVs must have zero orientation"); + assert!(fallback_gradients(&[Vec3::ZERO, Vec3::X, Vec3::Y], &uvs, &indices).is_none()); + let mut perturbed = rotated; + let corner = indices.iter().position(|&index| index == 2).unwrap(); + perturbed[corner].y = f32::from_bits(perturbed[corner].y.to_bits() + 1); + assert!(wide_uv_origin(perturbed).1 > 0.0); + } + } + + #[test] + fn exactly_collinear_uvs_with_rounded_orientation_use_fallback() { + let scales = [5.0 * 2.0f32.powi(-23), 1.0, 2.0f32.powi(-73)]; + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y], + normals: vec![Vec3::Z; 3], + uvs: scales.map(|scale| Vec2::new(scale, 3.0 * scale)).to_vec(), + indices: vec![0, 1, 2], + ..Mesh::default() + }; + assert_eq!(wide_uv_origin([mesh.uvs[0], mesh.uvs[1], mesh.uvs[2]]).1, 0.0); + assert!((mesh.uvs[1] - mesh.uvs[0]).perp_dot(mesh.uvs[2] - mesh.uvs[0]) < 0.0); + assert!(!mikk_uvs_safe(&mesh.positions, &mesh.uvs, &mesh.indices), "rounded orientation must reject exactly collinear UVs"); + let indices = mesh.indices.clone(); + let vertex_count = mesh.vertex_count(); + mesh.compute_tangents(); + assert!( + mesh.tangents.iter().all(|&tangent| tangent == Vec4::new(1.0, 0.0, 0.0, -1.0)), + "degenerate UVs keep the default frame: {:?}", + mesh.tangents + ); + assert_eq!(mesh.indices, indices); + assert_eq!(mesh.vertex_count(), vertex_count); + } + + #[test] + fn zero_projected_incident_edges_receive_right_angle_weight() { + let positions = [Vec3::ZERO, Vec3::Z, Vec3::new(1.0, 1.0, 0.0), -Vec3::X]; + let normals = [Vec3::Z; 4]; + let uvs = [Vec2::ZERO, Vec2::ONE, Vec2::X, -Vec2::X]; + let corners = simple_tangents(&positions, &normals, &uvs, &[0, 1, 2, 1, 0, 3]); + let expected = (Vec3::new(1.0, 1.0, 0.0).normalize() + Vec3::X).normalize(); + assert!(corners[0].truncate().dot(expected) > 0.99999, "a vanished projected edge must contribute a right-angle weight"); + } + + #[test] + fn fallback_smoothing_projects_gradients_and_corner_edges() { + let mut reference = Mesh { + positions: vec![Vec3::ZERO, Vec3::Y, Vec3::new(1.0, 0.0, 4.0), Vec3::new(-1.0, -2.0, -1.0)], + normals: vec![-Vec3::Z; 4], + uvs: vec![Vec2::ZERO, Vec2::Y, Vec2::X, -Vec2::X], + indices: vec![0, 1, 2, 1, 0, 3], + ..Mesh::default() + }; + let mut translated = reference.clone(); + for position in &mut translated.positions { + position.x += 2_000_000.0; + } + let (expected, actual) = (reference.corner_tangents(), translated.corner_tangents()); + for corner in 0..6 { + assert!(expected[corner].truncate().dot(actual[corner].truncate()) > 0.99999, "{corner}: {:?} {:?}", expected[corner], actual[corner]); + } + translated.compute_tangents(); + assert_eq!(translated.indices, reference.indices); + assert_eq!(translated.vertex_count(), reference.vertex_count()); + } + + #[test] + fn fallback_smoothing_does_not_reverse_a_projected_gradient() { + let positions = vec![Vec3::ZERO, Vec3::new(-10.0, 1.0, 0.0), Vec3::new(1.0, 0.0, 100.0), Vec3::new(1.0, -1.0, -10.0)]; + let normals = vec![Vec3::Z; 4]; + let uvs = vec![Vec2::ZERO, Vec2::Y, Vec2::X, -Vec2::X]; + let corners = simple_tangents(&positions, &normals, &uvs, &[0, 2, 1, 0, 1, 3]); + assert!(corners[0].truncate().dot(Vec3::X) > 0.0); + } + + #[test] + fn tiny_uv_edges_keep_their_frame_under_cyclic_permutations() { + for indices in [vec![0, 1, 2], vec![1, 2, 0], vec![2, 0, 1]] { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y], + normals: vec![Vec3::Z; 3], + uvs: vec![Vec2::ZERO, Vec2::ONE, Vec2::new(-1e-20, 0.0)], + indices, + ..Mesh::default() + }; + assert!(!mikk_uvs_safe(&mesh.positions, &mesh.uvs, &mesh.indices)); + let corners = simple_tangents(&mesh.positions, &mesh.normals, &mesh.uvs, &mesh.indices); + for tangent in corners { + assert!(tangent.truncate().dot(-Vec3::Y) > 0.999, "{:?}: {tangent:?}", mesh.indices); + assert!(tangent.w > 0.0); + } + let indices = mesh.indices.clone(); + mesh.compute_tangents(); + for tangent in &mesh.tangents { + assert!(tangent.truncate().dot(-Vec3::Y) > 0.999, "{indices:?}: {tangent:?}"); + } + assert_eq!(mesh.indices, indices); + assert_eq!(mesh.vertex_count(), 3); + } + } + + #[test] + fn unsplittable_distinct_positions_exceed_the_weld_work_bound() { + let mut cluster = Mesh { + positions: vec![Vec3::ZERO, Vec3::X * 2.0, Vec3::Y], + normals: vec![Vec3::Z; 3], + uvs: vec![Vec2::ZERO; 3], + indices: vec![0, 1, 2], + ..Mesh::default() + }; + let next = f32::from_bits(1.0f32.to_bits() + 1); + for corner in 0..12_000 { + cluster.indices.push(cluster.positions.len() as u32); + cluster.positions.push(Vec3::new(if corner % 2 == 0 { 1.0 } else { next }, corner as f32 * 1e-12, 0.0)); + cluster.normals.push(Vec3::Z); + cluster.uvs.push(Vec2::ZERO); + } + for (mesh, affordable) in [(quad(), true), (cluster, false)] { + let mut corners = vec![Vec4::ZERO; mesh.indices.len()]; + let g = Mikk { + positions: &mesh.positions, + normals: &mesh.normals, + uvs: &mesh.uvs, + indices: &mesh.indices, + corners: &mut corners, + faces: Mikk::noncollapsed_faces(&mesh.positions, &mesh.indices), + }; + assert_eq!(g.affordable(), affordable); + } + } + #[test] fn fallback_smoothing_is_invariant_to_gradient_magnitude() { let mut reference = Mesh { From 41b9cd58e0072513641ddbbf396fa13dcc0b6bf3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 09:17:14 -0800 Subject: [PATCH 14/31] craft-mesh-ops: tangent frames stay unit length for tiny normals and projections Normals used for tangents are normalized in f64, and the tangent is projected against the normal through its f64 cross product, so tiny finite normals and nearly parallel tangents no longer give frames of about 0.8 length or frames parallel to the normal. Collapsed corners are repaired even when another triangle has an out-of-range index; those corners are left as they are. The fallback smoothing test now crosses the shared edge in reverse, and the primitive checker rejects tangents that are not finite, not unit length, not perpendicular to the normal, or whose sign is not +1 or -1. --- crates/mesh-ops/src/mesh.rs | 152 +++++++++++++++++++++++++++--- crates/mesh-ops/src/primitives.rs | 36 ++++++- 2 files changed, 174 insertions(+), 14 deletions(-) diff --git a/crates/mesh-ops/src/mesh.rs b/crates/mesh-ops/src/mesh.rs index a460970fbf..24f258e524 100644 --- a/crates/mesh-ops/src/mesh.rs +++ b/crates/mesh-ops/src/mesh.rs @@ -266,7 +266,7 @@ impl Mesh { tangents[index as usize].w = -1.0; } for (tangent, normal) in tangents.iter_mut().zip(&self.normals) { - let normal = normal.try_normalize().unwrap_or(Vec3::Y); + let normal = tangent_normal(*normal); *tangent = orthonormal(&[normal], 0, *tangent); } self.tangents = tangents; @@ -284,7 +284,7 @@ impl Mesh { drop(corners); for (vertex, tangent) in tangents.iter_mut().enumerate() { if *tangent == Vec4::ZERO { - let normal = self.normals[vertex].try_normalize().unwrap_or(Vec3::Y); + let normal = tangent_normal(self.normals[vertex]); *tangent = orthonormal(&[normal], 0, Vec4::new(1.0, 0.0, 0.0, 1.0)); } } @@ -302,7 +302,7 @@ impl Mesh { if self.uvs.len() != n { self.uvs = vec![Vec2::ZERO; n]; } - let normals: Vec = self.normals.iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(); + let normals: Vec = self.normals.iter().copied().map(tangent_normal).collect(); let mut corners = vec![Vec4::ZERO; self.indices.len()]; // MikkTSpace receives noncollapsed faces with valid indices and bounded attributes. @@ -337,9 +337,7 @@ impl Mesh { } if !(affordable && g.face_count() != 0 && (g.face_count() == face_count || g.affordable()) && mikktspace::generate_tangents(&mut g)) { fill_simple_tangents(&self.positions, &normals, &self.uvs, &self.indices, g.corners); - if self.indices.iter().all(|&index| (index as usize) < n) { - g.fill_collapsed_corners(); - } + g.fill_collapsed_corners(); } else { let fallback_indices: Vec = fallback_faces.iter().flat_map(|&face| self.indices[face * 3..face * 3 + 3].iter().copied()).collect(); let fallback = simple_tangents(&self.positions, &normals, &self.uvs, &fallback_indices); @@ -544,11 +542,22 @@ impl Mesh { } } +fn tangent_normal(normal: Vec3) -> Vec3 { + normal.as_dvec3().try_normalize().map(|normal| normal.as_vec3()).unwrap_or(Vec3::Y) +} + /// Tangent `t` orthonormalized against the normal of vertex `v`, with degenerate results repaired. fn orthonormal(normals: &[Vec3], v: usize, t: Vec4) -> Vec4 { let n = normals.get(v).copied().unwrap_or(Vec3::Y); - let d = t.truncate(); - let o = (d - n * n.dot(d)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()); + let (d, normal) = (t.truncate().as_dvec3(), n.as_dvec3()); + let cross = normal.cross(d); + let o = if cross.is_finite() && cross != DVec3::ZERO { + let projected = cross.cross(normal); + projected.try_normalize().map(|o| o.as_vec3()) + } else { + None + } + .unwrap_or_else(|| n.any_orthonormal_vector()); o.extend(if t.w < 0.0 { -1.0 } else { 1.0 }) } @@ -837,6 +846,9 @@ impl Mikk<'_> { } fn fill_collapsed_corners(&mut self) { + if !self.indices.iter().zip(self.corners.iter()).any(|(&index, &tangent)| (index as usize) < self.positions.len() && tangent == Vec4::ZERO) { + return; + } let generated_faces: Vec = self .corners .as_chunks::<3>() @@ -856,6 +868,9 @@ impl Mikk<'_> { for vertex in 0..3 { let corner = face * 3 + vertex; let index = self.indices[corner] as usize; + if index >= self.positions.len() { + continue; + } first[index].get_or_insert(self.corners[corner]); } } @@ -867,7 +882,7 @@ impl Mikk<'_> { self.indices .iter() .zip(self.corners.iter()) - .filter(|&(index, tangent)| *tangent == Vec4::ZERO && first[*index as usize].is_none()) + .filter(|&(index, tangent)| (*index as usize) < self.positions.len() && *tangent == Vec4::ZERO && first[*index as usize].is_none()) .map(|(&index, _)| (attributes(index as usize), None)) .collect() }; @@ -875,7 +890,11 @@ impl Mikk<'_> { for &face in &generated_faces { for vertex in 0..3 { let corner = face * 3 + vertex; - let key = attributes(self.indices[corner] as usize); + let index = self.indices[corner] as usize; + if index >= self.positions.len() { + continue; + } + let key = attributes(index); if index_generated { welded.entry(key).or_insert(Some(self.corners[corner])); } else if let Some(frame) = welded.get_mut(&key) { @@ -885,6 +904,9 @@ impl Mikk<'_> { } } for (&index, tangent) in self.indices.iter().zip(self.corners.iter_mut()) { + if index as usize >= self.positions.len() { + continue; + } if *tangent == Vec4::ZERO && let Some(Some(frame)) = first.get(index as usize) { @@ -1267,16 +1289,81 @@ mod tests { assert!(mesh.corner_tangents()[1].truncate().dot(Vec3::Y) > 0.99); } + #[test] + fn tiny_projected_tangents_have_unit_length() { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::new(1.0, 3e-23, 0.0), Vec3::Y], + normals: vec![Vec3::X; 3], + uvs: vec![Vec2::ZERO, Vec2::X * 1e-30, Vec2::Y * 1e-30], + indices: vec![0, 1, 2], + ..Mesh::default() + }; + for tangent in mesh.corner_tangents() { + assert!((tangent.truncate().length() - 1.0).abs() < 1e-6, "{tangent:?}"); + assert!(tangent.truncate().dot(Vec3::Y) > 0.999); + } + mesh.compute_tangents(); + for tangent in mesh.tangents { + assert!((tangent.truncate().length() - 1.0).abs() < 1e-6, "{tangent:?}"); + assert!(tangent.truncate().dot(Vec3::Y) > 0.999); + } + } + + #[test] + fn tangents_parallel_to_a_rounded_normal_use_the_perpendicular_fallback() { + let normal = Vec3::new(3.0, 4.0, 0.0) / 5.0; + let tangent = orthonormal(&[tangent_normal(normal)], 0, normal.extend(1.0)); + assert!(tangent.truncate().dot(normal).abs() < 1e-6, "{tangent:?}"); + assert!((tangent.truncate().length() - 1.0).abs() < 1e-6); + for perpendicular in [1e-7, 1e-13] { + let small = orthonormal(&[Vec3::X], 0, Vec4::new(1.0, 0.0, perpendicular, 1.0)); + assert!(small.truncate().dot(Vec3::Z) > 0.999, "{small:?}"); + } + let normal = tangent_normal(Vec3::new(1.0, 32.0, 0.0)); + let tangent = orthonormal(&[normal], 0, Vec3::new(0.03123475, 0.999512, 1e-24).extend(1.0)); + assert!((tangent.truncate().length() - 1.0).abs() < 1e-6, "{tangent:?}"); + assert!(tangent.truncate().dot(Vec3::Z) > 0.999, "{tangent:?}"); + assert!(tangent.truncate().dot(normal).abs() < 1e-6, "{tangent:?}"); + } + + #[test] + fn tiny_normals_keep_tangents_perpendicular() { + for indices in [vec![0, 1, 2], vec![0, 0, 0], Vec::new()] { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::ONE], + normals: vec![Vec3::X * 3e-23; 4], + uvs: vec![Vec2::ZERO, Vec2::X * 1e-30, Vec2::Y * 1e-30, Vec2::ONE], + indices, + ..Mesh::default() + }; + for tangent in mesh.corner_tangents() { + assert!(tangent.truncate().dot(Vec3::X).abs() < 1e-6, "{tangent:?}"); + assert!((tangent.truncate().length() - 1.0).abs() < 1e-6); + } + mesh.compute_tangents(); + for tangent in mesh.tangents { + assert!(tangent.truncate().dot(Vec3::X).abs() < 1e-6, "{tangent:?}"); + assert!((tangent.truncate().length() - 1.0).abs() < 1e-6); + } + } + } + #[test] fn fallback_smoothing_does_not_reverse_an_adjacent_bitangent() { let mut mesh = Mesh { positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(-1.0, -1.0, 0.0)], normals: vec![Vec3::Z; 4], - uvs: vec![Vec2::ZERO, Vec2::ONE, Vec2::Y, Vec2::X * 1e-20], - indices: vec![0, 1, 2, 0, 1, 3], + uvs: vec![Vec2::ZERO, Vec2::ONE * 1e-20, Vec2::Y * 1e-20, Vec2::new(2e-20, 1e-20)], + indices: vec![0, 1, 2, 0, 3, 1], ..Mesh::default() }; + for face in mesh.indices.as_chunks::<3>().0 { + assert!(!mikk_uvs_safe(&mesh.positions, &mesh.uvs, face)); + let (_, _, _, determinant) = fallback_gradients(&mesh.positions, &mesh.uvs, face).expect("nondegenerate UV gradients"); + assert!(determinant > 0.0); + } let corners = mesh.corner_tangents(); + assert_eq!(corners[0].w, corners[3].w); for &tangent in &corners[0..3] { assert!((Vec3::Z.cross(tangent.truncate()) * tangent.w).dot(Vec3::Y) > 0.0); } @@ -1410,6 +1497,45 @@ mod tests { assert!(corners[4].truncate().dot(Vec3::Y) > 0.99); } + #[test] + fn collapsed_corners_reuse_frames_with_out_of_range_triangles() { + for copies in [1, 8] { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::ZERO], + normals: vec![Vec3::Z; 4], + uvs: vec![Vec2::ZERO, Vec2::Y * 1e-30, Vec2::X * 1e-30, Vec2::ZERO], + indices: [0, 1, 2].repeat(copies), + ..Mesh::default() + }; + mesh.indices.extend([0, 3, 2, 99, 99, 99]); + let corners = mesh.corner_tangents(); + for &tangent in &corners[copies * 3..copies * 3 + 3] { + assert_eq!(tangent, corners[0]); + assert_eq!(tangent.w, -1.0); + } + assert!(corners[copies * 3 + 3..].iter().all(|tangent| tangent.is_finite() && tangent.w == 1.0)); + } + } + + #[test] + fn collapsed_corner_repair_skips_invalid_donors_and_recipients() { + for copies in [1, 8] { + let positions = [Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::ZERO]; + let normals = [Vec3::Z; 4]; + let uvs = [Vec2::ZERO, Vec2::Y, Vec2::X, Vec2::ZERO]; + let mut indices = [0, 1, 2].repeat(copies); + indices.extend([99, 0, 1, 0, 3, 2, 99, 99, 99]); + let frame = Vec3::Y.extend(-1.0); + let mut corners = vec![frame; copies * 3 + 3]; + corners.extend([Vec4::ZERO; 6]); + let mut g = Mikk { positions: &positions, normals: &normals, uvs: &uvs, indices: &indices, corners: &mut corners, faces: None }; + g.fill_collapsed_corners(); + assert_eq!(corners[copies * 3], frame); + assert_eq!(&corners[copies * 3 + 3..copies * 3 + 6], &[frame; 3]); + assert_eq!(&corners[copies * 3 + 6..], &[Vec4::ZERO; 3]); + } + } + #[test] fn tangent_frames_follow_stored_uv_gradients() { for offset in [0.0, 2_000_000.0] { @@ -1597,7 +1723,7 @@ mod tests { for vertex in 0..mesh.positions.len() { let expected = reference.indices.iter().position(|&index| index as usize == vertex).map_or_else( || { - let normal = reference.normals[vertex].try_normalize().unwrap_or(Vec3::Y); + let normal = tangent_normal(reference.normals[vertex]); orthonormal(&[normal], 0, Vec4::new(1.0, 0.0, 0.0, 1.0)) }, |corner| corners[corner], diff --git a/crates/mesh-ops/src/primitives.rs b/crates/mesh-ops/src/primitives.rs index 66da961d5e..4c7298e025 100644 --- a/crates/mesh-ops/src/primitives.rs +++ b/crates/mesh-ops/src/primitives.rs @@ -564,6 +564,13 @@ mod tests { for uv in &m.uvs { assert!((0.0..=max_u).contains(&uv.x) && (0.0..=1.0).contains(&uv.y), "{uv:?}"); } + for (index, tangent) in m.tangents.iter().enumerate() { + let normal = m.normals[index]; + assert!(tangent.truncate().is_finite(), "{tangent:?}"); + assert!((tangent.truncate().length() - 1.0).abs() < 1e-3, "{tangent:?}"); + assert!(tangent.truncate().dot(normal).abs() < 1e-3, "{tangent:?}, {normal:?}"); + assert!(tangent.w == 1.0 || tangent.w == -1.0, "{tangent:?}"); + } let (mut opposed, mut tested) = (0, 0); for &[a, b, c] in m.indices.as_chunks::<3>().0 { let (a, b, c) = (a as usize, b as usize, c as usize); @@ -578,13 +585,40 @@ mod tests { let tangent = m.tangents[vertex]; let reconstructed = m.normals[vertex].as_dvec3().cross(tangent.truncate().as_dvec3()) * tangent.w as f64; tested += 1; - opposed += usize::from(reconstructed.dot(bitangent) < 0.0); + let alignment = reconstructed.dot(bitangent); + assert!(alignment.is_finite(), "vertex {vertex}: {alignment}"); + opposed += usize::from(alignment < 0.0); } } assert!(tested > 0); assert!(opposed * 50 < tested, "{opposed} tangent frames oppose increasing v"); } + #[test] + fn check_rejects_invalid_tangent_frames() { + let mesh = cube(2.0).unwrap(); + for tangent in [ + Vec3::ZERO.extend(1.0), + (mesh.tangents[0].truncate() * 0.5).extend(mesh.tangents[0].w), + mesh.normals[0].extend(mesh.tangents[0].w), + Vec3::splat(f32::NAN).extend(1.0), + Vec3::splat(f32::INFINITY).extend(1.0), + mesh.tangents[0].truncate().extend(0.0), + mesh.tangents[0].truncate().extend(f32::NAN), + ] { + let mut invalid = mesh.clone(); + invalid.tangents[0] = tangent; + assert!(std::panic::catch_unwind(|| check(&invalid, 1.0)).is_err(), "{tangent:?}"); + } + } + + #[test] + fn check_rejects_nan_bitangent_alignment() { + let mut mesh = cube(2.0).unwrap(); + mesh.normals.fill(Vec3::splat(f32::NAN)); + assert!(std::panic::catch_unwind(|| check(&mesh, 1.0)).is_err()); + } + #[test] fn primitives_are_well_formed() { for (id, _) in BUILTINS { From 78a4ebd1319e979ba724edf1b17dec9aeefae967 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 09:20:05 -0800 Subject: [PATCH 15/31] craft-mesh-ops: drop a primitive checker test the perpendicularity check already covers --- crates/mesh-ops/src/primitives.rs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/crates/mesh-ops/src/primitives.rs b/crates/mesh-ops/src/primitives.rs index 4c7298e025..d89ea04a68 100644 --- a/crates/mesh-ops/src/primitives.rs +++ b/crates/mesh-ops/src/primitives.rs @@ -612,13 +612,6 @@ mod tests { } } - #[test] - fn check_rejects_nan_bitangent_alignment() { - let mut mesh = cube(2.0).unwrap(); - mesh.normals.fill(Vec3::splat(f32::NAN)); - assert!(std::panic::catch_unwind(|| check(&mesh, 1.0)).is_err()); - } - #[test] fn primitives_are_well_formed() { for (id, _) in BUILTINS { From 14d3f01b9c85d4470e43298b988b70c5317dd80f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 09:44:45 -0800 Subject: [PATCH 16/31] craft-mesh-ops: split tangents normalize unused-vertex normals in f64 compute_tangents_split normalized the normal of a vertex no triangle uses in f32, so a normal whose squared length underflows became +Y and the vertex got a +X tangent parallel to its real normal. It now uses tangent_normal, as compute_tangents does. With the f64 tangent projection from fix/mesh-ops-tangents, the signed-zero fixture's two corner frames are now bit-identical. The frame comparison moves into frame_bits, and the test checks it directly with +0.0 and -0.0 components. --- crates/mesh-ops/src/mesh.rs | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/crates/mesh-ops/src/mesh.rs b/crates/mesh-ops/src/mesh.rs index 1c56b4e901..2f34101bfb 100644 --- a/crates/mesh-ops/src/mesh.rs +++ b/crates/mesh-ops/src/mesh.rs @@ -325,7 +325,7 @@ impl Mesh { } let corners = self.corner_tangents(); let n = self.positions.len(); - let bits = |t: Vec4| t.to_array().map(|component| if component == 0.0 { 0 } else { component.to_bits() }); + let bits = frame_bits; let mut out = vec![Vec4::ZERO; n]; let mut copies: Vec<(u32, Vec4)> = Vec::new(); let mut copy_of: std::collections::HashMap<(u32, [u32; 4]), u32> = std::collections::HashMap::new(); @@ -349,7 +349,7 @@ impl Mesh { // A vertex no triangle uses gets +X made perpendicular to its normal. for (v, tangent) in out.iter_mut().enumerate() { if *tangent == Vec4::ZERO { - let normal = self.normals.get(v).copied().unwrap_or(Vec3::Y).try_normalize().unwrap_or(Vec3::Y); + let normal = tangent_normal(self.normals.get(v).copied().unwrap_or(Vec3::Y)); *tangent = orthonormal(&[normal], 0, Vec4::new(1.0, 0.0, 0.0, 1.0)); } } @@ -619,6 +619,12 @@ impl Mesh { } } +/// The bit pattern of a tangent frame with `-0.0` read as `0.0`, so frames that compare equal +/// share a vertex. +fn frame_bits(t: Vec4) -> [u32; 4] { + t.to_array().map(|component| if component == 0.0 { 0 } else { component.to_bits() }) +} + fn tangent_normal(normal: Vec3) -> Vec3 { normal.as_dvec3().try_normalize().map(|normal| normal.as_vec3()).unwrap_or(Vec3::Y) } @@ -1870,6 +1876,25 @@ mod tests { } } + #[test] + fn split_tangents_preserve_tiny_unused_vertex_normals() { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z], + // The squared length underflows to zero in f32. + normals: vec![Vec3::Z, Vec3::Z, Vec3::Z, Vec3::X * 1e-23], + uvs: vec![Vec2::ZERO, Vec2::X, Vec2::Y, Vec2::ZERO], + indices: vec![0, 1, 2], + ..Mesh::default() + }; + let mut expected = mesh.clone(); + expected.compute_tangents(); + mesh.compute_tangents_split(); + let tangent = mesh.tangents[3].truncate(); + assert!((tangent.length() - 1.0).abs() < 1e-6); + assert!(tangent.dot(Vec3::X).abs() < 1e-6); + assert_eq!(mesh.tangents[3], expected.tangents[3]); + } + #[test] fn signed_zero_frames_share_vertices_and_copies() { for earlier_frame in [false, true] { @@ -1887,7 +1912,8 @@ mod tests { let offset = if earlier_frame { 3 } else { 0 }; let corners = mesh.clone().corner_tangents(); assert_eq!(corners[offset + 2], corners[offset + 5]); - assert_ne!(corners[offset + 2].to_array().map(f32::to_bits), corners[offset + 5].to_array().map(f32::to_bits)); + assert_eq!(frame_bits(Vec4::new(1.0, 0.0, -0.0, -1.0)), frame_bits(Vec4::new(1.0, -0.0, 0.0, -1.0))); + assert_ne!(frame_bits(Vec4::new(1.0, 0.0, 0.0, -1.0)), frame_bits(Vec4::new(1.0, f32::MIN_POSITIVE, 0.0, -1.0))); let original = mesh.indices.clone(); let copies = mesh.compute_tangents_split(); if earlier_frame { From 3bf9142f7ef3a198eaf053438c21af49f411a394 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 10:15:56 -0800 Subject: [PATCH 17/31] craft-mesh-ops: tangent fallback pairs nonmanifold edges once and keeps small gradient terms When more than two same-handed faces share a welded edge, the fallback reused one stored half-edge for every later match and merged face pairs that MikkTSpace keeps apart. Each stored half-edge now pairs once, and later occurrences wait in order, so grouped and interleaved face lists pair the same faces. The fallback numerators now use the same compensated sums of products as the UV determinant, so a gradient carried by a small coordinate term is no longer lost to f64 cancellation. Each face computes its gradients once and the later passes reuse them. --- crates/mesh-ops/src/mesh.rs | 113 ++++++++++++++++++++++++++++-------- 1 file changed, 89 insertions(+), 24 deletions(-) diff --git a/crates/mesh-ops/src/mesh.rs b/crates/mesh-ops/src/mesh.rs index 24f258e524..c1b78a8e16 100644 --- a/crates/mesh-ops/src/mesh.rs +++ b/crates/mesh-ops/src/mesh.rs @@ -634,9 +634,10 @@ fn simple_tangents(positions: &[Vec3], normals: &[Vec3], uvs: &[Vec2], indices: corners } -fn wide_uv_origin(uvs: [Vec2; 3]) -> (usize, f64) { - let [a, b, c] = uvs.map(|uv| uv.as_dvec2()); - let products = [a.x * b.y, -a.y * b.x, b.x * c.y, -b.y * c.x, c.x * a.y, -c.y * a.x]; +fn wide_cross_difference(x: [f32; 3], y: [f32; 3]) -> f64 { + let [ax, bx, cx] = x.map(f64::from); + let [ay, by, cy] = y.map(f64::from); + let products = [ax * by, -ay * bx, bx * cy, -by * cx, cx * ay, -cy * ax]; let mut expansion = [0.0; 6]; let mut length = 0; for mut product in products { @@ -655,7 +656,11 @@ fn wide_uv_origin(uvs: [Vec2; 3]) -> (usize, f64) { expansion[next] = product; length = next + 1; } - let determinant: f64 = expansion[..length].iter().sum(); + expansion[..length].iter().sum() +} + +fn wide_uv_origin(uvs: [Vec2; 3]) -> (usize, f64) { + let determinant = wide_cross_difference(uvs.map(|uv| uv.x), uvs.map(|uv| uv.y)); let (mut origin, mut conditioning) = (0, -1.0); for corner in 0..3 { let a = uvs[(corner + 1) % 3].as_dvec2() - uvs[corner].as_dvec2(); @@ -681,21 +686,25 @@ fn fallback_gradients(positions: &[Vec3], uvs: &[Vec2], indices: &[u32]) -> Opti } let (ua, ub, uc) = (uvs.get(a)?, uvs.get(b)?, uvs.get(c)?); let (e1, e2) = (pb.as_dvec3() - pa.as_dvec3(), pc.as_dvec3() - pa.as_dvec3()); - let (d1, d2) = (ub.as_dvec2() - ua.as_dvec2(), uc.as_dvec2() - ua.as_dvec2()); if !determinant.is_finite() || determinant == 0.0 { return None; } - let tangent = (e1 * d2.y - e2 * d1.y) / determinant; - let bitangent = (e2 * d1.x - e1 * d2.x) / determinant; + let u = [ua.x, ub.x, uc.x]; + let v = [ua.y, ub.y, uc.y]; + let components = [[pa.x, pb.x, pc.x], [pa.y, pb.y, pc.y], [pa.z, pb.z, pc.z]]; + let tangent = DVec3::from_array(components.map(|p| wide_cross_difference(p, v))) / determinant; + let bitangent = DVec3::from_array(components.map(|p| wide_cross_difference(u, p))) / determinant; (tangent.is_finite() && bitangent.is_finite()).then_some((tangent, bitangent, e1.cross(e2), determinant)) } fn fill_simple_tangents(positions: &[Vec3], normals: &[Vec3], uvs: &[Vec2], indices: &[u32], corners: &mut [Vec4]) { corners.fill(Vec4::ZERO); let mut valid_faces = Vec::new(); + let mut gradients = Vec::new(); for (face, vertices) in indices.as_chunks::<3>().0.iter().enumerate() { - let Some((tangent, _, _, determinant)) = fallback_gradients(positions, uvs, vertices) else { continue }; + let Some((tangent, bitangent, _, determinant)) = fallback_gradients(positions, uvs, vertices) else { continue }; valid_faces.push(face); + gradients.push((tangent, bitangent, determinant)); for corner in 0..3 { let t = tangent.try_normalize().map(|t| t.as_vec3()).unwrap_or(Vec3::X); let w = if determinant.is_sign_negative() { -1.0 } else { 1.0 }; @@ -712,6 +721,7 @@ fn fill_simple_tangents(positions: &[Vec3], normals: &[Vec3], uvs: &[Vec2], indi let mut parents: Vec = (0..valid_faces.len() * 3).collect(); let welded = tangent_vertex_ids(positions, normals, uvs, valid_faces.iter().flat_map(|&face| indices[face * 3..face * 3 + 3].iter().copied())); let mut edges = std::collections::HashMap::new(); + let mut overflow = std::collections::HashMap::new(); for (slot, &face) in valid_faces.iter().enumerate() { for edge in 0..3 { let (mut a, mut b) = (slot * 3 + edge, slot * 3 + (edge + 1) % 3); @@ -720,36 +730,47 @@ fn fill_simple_tangents(positions: &[Vec3], normals: &[Vec3], uvs: &[Vec2], indi std::mem::swap(&mut a, &mut b); } let key = (welded[a], welded[b], corners[face * 3 + a % 3].w < 0.0, corners[face * 3 + b % 3].w < 0.0); - let previous: &mut [Option<(usize, usize)>; 2] = edges.entry(key).or_insert([None, None]); - if let Some((previous_a, previous_b)) = previous[1 - reversed] { + // The first waiting occurrence of each direction stays inline; later ones queue in `overflow`. + let pending: &mut [Option<(usize, usize)>; 2] = edges.entry(key).or_insert([None, None]); + if let Some((previous_a, previous_b)) = pending[1 - reversed].take() { + if let std::collections::hash_map::Entry::Occupied(mut entry) = overflow.entry((key, 1 - reversed)) { + let queue: &mut std::collections::VecDeque<_> = entry.get_mut(); + pending[1 - reversed] = queue.pop_front(); + if queue.is_empty() { + entry.remove(); + } + } for (current, previous) in [(a, previous_a), (b, previous_b)] { let (a, b) = (root(&mut parents, current), root(&mut parents, previous)); parents[a.max(b)] = a.min(b); } + } else if pending[reversed].is_none() { + pending[reversed] = Some((a, b)); + } else { + overflow.entry((key, reversed)).or_insert_with(std::collections::VecDeque::new).push_back((a, b)); } - previous[reversed].get_or_insert((a, b)); } } drop(edges); + drop(overflow); drop(welded); let mut sums = std::collections::HashMap::::new(); for (slot, &face) in valid_faces.iter().enumerate() { - if let Some((tangent, ..)) = fallback_gradients(positions, uvs, &indices[face * 3..face * 3 + 3]) { - let triangle = &indices[face * 3..face * 3 + 3]; - for corner in 0..3 { - let normal = normals.get(triangle[corner] as usize).copied().unwrap_or(Vec3::Y).as_dvec3(); - let project = |v: DVec3| v - normal * normal.dot(v); - let direction = project(tangent).try_normalize().unwrap_or(DVec3::ZERO); - let origin = positions[triangle[corner] as usize].as_dvec3(); - let a = project(positions[triangle[(corner + 1) % 3] as usize].as_dvec3() - origin).try_normalize().unwrap_or(DVec3::ZERO); - let b = project(positions[triangle[(corner + 2) % 3] as usize].as_dvec3() - origin).try_normalize().unwrap_or(DVec3::ZERO); - let weight = if a == DVec3::ZERO || b == DVec3::ZERO { std::f64::consts::FRAC_PI_2 } else { a.cross(b).length().atan2(a.dot(b)) }; - *sums.entry(root(&mut parents, slot * 3 + corner)).or_default() += direction * weight; - } + let (tangent, ..) = gradients[slot]; + let triangle = &indices[face * 3..face * 3 + 3]; + for corner in 0..3 { + let normal = normals.get(triangle[corner] as usize).copied().unwrap_or(Vec3::Y).as_dvec3(); + let project = |v: DVec3| v - normal * normal.dot(v); + let direction = project(tangent).try_normalize().unwrap_or(DVec3::ZERO); + let origin = positions[triangle[corner] as usize].as_dvec3(); + let a = project(positions[triangle[(corner + 1) % 3] as usize].as_dvec3() - origin).try_normalize().unwrap_or(DVec3::ZERO); + let b = project(positions[triangle[(corner + 2) % 3] as usize].as_dvec3() - origin).try_normalize().unwrap_or(DVec3::ZERO); + let weight = if a == DVec3::ZERO || b == DVec3::ZERO { std::f64::consts::FRAC_PI_2 } else { a.cross(b).length().atan2(a.dot(b)) }; + *sums.entry(root(&mut parents, slot * 3 + corner)).or_default() += direction * weight; } } for (slot, &face) in valid_faces.iter().enumerate() { - let Some((gradient, bitangent, ..)) = fallback_gradients(positions, uvs, &indices[face * 3..face * 3 + 3]) else { continue }; + let (gradient, bitangent, _) = gradients[slot]; for local in 0..3 { let index = face * 3 + local; let corner = &mut corners[index]; @@ -1483,6 +1504,50 @@ mod tests { assert_eq!(corners[2], corners[4]); } + #[test] + fn fallback_nonmanifold_edge_pairs_keep_distinct_frames() { + // Interleaved and grouped face orders pair the same faces across the shared edge. + let orders = [ + (vec![0, 1, 2, 1, 0, 3, 0, 1, 4, 1, 0, 5], [[0, 4, 6, 10], [1, 3, 7, 9]]), + (vec![0, 1, 2, 0, 1, 4, 1, 0, 3, 1, 0, 5], [[0, 7, 3, 10], [1, 6, 4, 9]]), + ]; + for (indices, groups) in orders { + let mut mesh = Mesh { + positions: vec![Vec3::ZERO, Vec3::new(1.0, 1.0, 0.0), Vec3::Y, Vec3::X, Vec3::Y * 1.5, Vec3::new(1.4, -0.3, 0.0)], + normals: vec![Vec3::Z; 6], + uvs: vec![Vec2::ZERO, Vec2::ONE, Vec2::Y, Vec2::X, Vec2::Y, Vec2::X], + indices, + ..Mesh::default() + }; + for position in &mut mesh.positions { + position.x += 2_000_000.0; + } + assert!(!in_safe_range(mesh.positions.iter().flat_map(|p| p.to_array()))); + let corners = mesh.corner_tangents(); + for [first, partner, second, second_partner] in groups { + assert!(corners[first].w * corners[second].w > 0.0); + assert!(corners[first].truncate().dot(corners[partner].truncate()) > 0.99999); + assert!(corners[second].truncate().dot(corners[second_partner].truncate()) > 0.99999); + assert!(corners[first].truncate().dot(corners[second].truncate()) > 0.8); + assert!((corners[first].truncate() - corners[second].truncate()).length() > 0.2); + } + } + } + + #[test] + fn fallback_gradient_numerators_preserve_small_terms() { + let mut mesh = Mesh { + positions: vec![Vec3::new(-1.0, -1.0, 0.0), Vec3::new(1.0, 1.0, 0.0), Vec3::new(1e-20, 0.0, 0.0)], + normals: vec![Vec3::Z; 3], + uvs: vec![Vec2::new(-1.0, -1.0), Vec2::ONE, Vec2::new(0.0, 1e-20)], + indices: vec![0, 1, 2], + ..Mesh::default() + }; + assert!(!mikk_uvs_safe(&mesh.positions, &mesh.uvs, &mesh.indices)); + let corners = mesh.corner_tangents(); + assert!(corners.iter().all(|tangent| tangent.truncate().dot(Vec3::Y) > 0.0)); + } + #[test] fn collapsed_corners_reuse_tiny_uv_fallback_frames() { let mut mesh = Mesh { From ee60045f2761f5df321f3651b3c0ffe9d3d5dfd1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 10:30:15 -0800 Subject: [PATCH 18/31] craft-mesh-ops: MikkTSpace path checks gradient direction and fallback drops matched edges f32 cancellation can reverse a finite UV gradient without changing the determinant sign, so a face whose f32 tangent or bitangent points against the compensated gradient now takes the fallback. The fallback edge map drops a key once neither direction has a corner pair waiting. --- crates/mesh-ops/src/mesh.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/crates/mesh-ops/src/mesh.rs b/crates/mesh-ops/src/mesh.rs index c1b78a8e16..0cb19017cd 100644 --- a/crates/mesh-ops/src/mesh.rs +++ b/crates/mesh-ops/src/mesh.rs @@ -740,6 +740,9 @@ fn fill_simple_tangents(positions: &[Vec3], normals: &[Vec3], uvs: &[Vec2], indi entry.remove(); } } + if pending.iter().all(Option::is_none) { + edges.remove(&key); + } for (current, previous) in [(a, previous_a), (b, previous_b)] { let (a, b) = (root(&mut parents, current), root(&mut parents, previous)); parents[a.max(b)] = a.min(b); @@ -806,9 +809,12 @@ fn mikk_uvs_safe(positions: &[Vec3], uvs: &[Vec2], indices: &[u32]) -> bool { let (e1, e2) = (positions[b] - positions[a], positions[c] - positions[a]); let tangent = e1 * d2.y - e2 * d1.y; let bitangent = e2 * d1.x - e1 * d2.x; + let Some((wide_tangent, wide_bitangent, _, _)) = fallback_gradients(positions, uvs, indices) else { return false }; [tangent, bitangent, tangent / determinant, bitangent / determinant] .into_iter() .all(|v| v.length_squared().is_finite() && v.length_squared() > 0.0) + && (tangent / determinant).as_dvec3().dot(wide_tangent) > 0.0 + && (bitangent / determinant).as_dvec3().dot(wide_bitangent) > 0.0 } /// Whether the values are finite and their largest magnitude is zero or lies between the @@ -1492,6 +1498,20 @@ mod tests { assert!(mesh.tangents.iter().all(|t| t.truncate().dot(Vec3::Y) > 0.99)); } + #[test] + fn canceled_mikk_gradients_keep_their_uv_direction() { + let mut mesh = Mesh { + positions: vec![Vec3::new(-1.0, 0.0, 0.0), Vec3::new(-0.7, 0.0, 0.0), Vec3::new(-0.4, 1e-11, 0.0)], + normals: vec![Vec3::Z; 3], + uvs: vec![Vec2::new(0.0, 0.1), Vec2::new(1.0, 0.4), Vec2::new(0.0, 0.7)], + indices: vec![0, 1, 2], + ..Mesh::default() + }; + assert!(!mikk_uvs_safe(&mesh.positions, &mesh.uvs, &mesh.indices)); + let corners = mesh.corner_tangents(); + assert!(corners.iter().all(|tangent| tangent.x > 0.0)); + } + #[test] fn fallback_smooths_continuous_same_handed_edges() { let mut mesh = quad(); From 992edb605bfd0369ef4186a4f296e00878d794c4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 11:51:55 -0800 Subject: [PATCH 19/31] hayro-interpret: rustfmt the patch 89 tiling pattern call and self-draw tests Formats the new lines in pattern.rs and self_draw_tests.rs with rustfmt's default settings, which the vendored hayro files follow. Lines that came from main are left as they are. --- vendor/hayro-interpret/src/pattern.rs | 4 +- vendor/hayro-interpret/src/self_draw_tests.rs | 99 +++++++++++++++---- 2 files changed, 85 insertions(+), 18 deletions(-) diff --git a/vendor/hayro-interpret/src/pattern.rs b/vendor/hayro-interpret/src/pattern.rs index c6e0e70d4e..1dceae2dd3 100644 --- a/vendor/hayro-interpret/src/pattern.rs +++ b/vendor/hayro-interpret/src/pattern.rs @@ -298,7 +298,9 @@ impl<'a> TilingPattern<'a> { initial_transform: Affine, is_stroke: bool, ) -> Option<()> { - drawing_within(&self.forms_drawing, || self.interpret_cell(device, initial_transform, is_stroke)) + drawing_within(&self.forms_drawing, || { + self.interpret_cell(device, initial_transform, is_stroke) + }) } fn interpret_cell( diff --git a/vendor/hayro-interpret/src/self_draw_tests.rs b/vendor/hayro-interpret/src/self_draw_tests.rs index cf63ff7131..c3b2b5ce17 100644 --- a/vendor/hayro-interpret/src/self_draw_tests.rs +++ b/vendor/hayro-interpret/src/self_draw_tests.rs @@ -21,7 +21,9 @@ fn pdf(resources: &str, content: &str, objects: &[String]) -> Pdf { let mut bodies = vec![ "<< /Type /Catalog /Pages 2 0 R >>".to_string(), "<< /Type /Pages /Count 1 /Kids [3 0 R] >>".to_string(), - format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /Resources {resources} >>"), + format!( + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /Resources {resources} >>" + ), stream("", content), ]; bodies.extend_from_slice(objects); @@ -32,18 +34,27 @@ fn pdf(resources: &str, content: &str, objects: &[String]) -> Pdf { out.extend_from_slice(format!("{} 0 obj\n{body}\nendobj\n", i + 1).as_bytes()); } let xref = out.len(); - out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", bodies.len() + 1).as_bytes()); + out.extend_from_slice( + format!("xref\n0 {}\n0000000000 65535 f \n", bodies.len() + 1).as_bytes(), + ); for offset in offsets { out.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes()); } out.extend_from_slice( - format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", bodies.len() + 1).as_bytes(), + format!( + "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", + bodies.len() + 1 + ) + .as_bytes(), ); Pdf::new(out).expect("synthetic pdf") } fn stream(entries: &str, content: &str) -> String { - format!("<< /Length {} {entries} >>\nstream\n{content}\nendstream", content.len()) + format!( + "<< /Length {} {entries} >>\nstream\n{content}\nendstream", + content.len() + ) } /// A form 10 by 10 that draws `content` with the resources of whatever draws it. @@ -54,7 +65,9 @@ fn form(content: &str) -> String { /// A soft mask group that draws `content` with `resources`. fn mask_group(resources: &str, content: &str) -> String { stream( - &format!("/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Group << /S /Transparency >> /Resources {resources}"), + &format!( + "/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Group << /S /Transparency >> /Resources {resources}" + ), content, ) } @@ -136,7 +149,14 @@ impl<'a> Device<'a> for Recorder<'a> { fn push_transparency_group(&mut self, _: f32, _: Option>, _: BlendMode) {} - fn draw_glyph(&mut self, glyph: &Glyph<'a>, transform: Affine, glyph_transform: Affine, paint: &Paint<'a>, _: &GlyphDrawMode) { + fn draw_glyph( + &mut self, + glyph: &Glyph<'a>, + transform: Affine, + glyph_transform: Affine, + paint: &Paint<'a>, + _: &GlyphDrawMode, + ) { let Glyph::Type3(glyph) = glyph else { return; }; @@ -166,12 +186,23 @@ fn draw(pdf: &Pdf, defer_glyphs: bool) -> (Drawn, bool) { warning_sink: Arc::new(move |warning| sink.lock().expect("warnings").push(warning)), ..InterpreterSettings::default() }; - let mut ctx = Context::new(Affine::IDENTITY, Rect::new(0.0, 0.0, 100.0, 100.0), &cache, pdf.xref(), settings); - let mut device = Recorder { defer_glyphs, ..Recorder::default() }; + let mut ctx = Context::new( + Affine::IDENTITY, + Rect::new(0.0, 0.0, 100.0, 100.0), + &cache, + pdf.xref(), + settings, + ); + let mut device = Recorder { + defer_glyphs, + ..Recorder::default() + }; let page = &pdf.pages()[0]; interpret_page(page, &mut ctx, &mut device); let warnings = warnings.lock().expect("warnings"); - let truncated = warnings.iter().any(|w| matches!(w, InterpreterWarning::ContentTruncated)); + let truncated = warnings + .iter() + .any(|w| matches!(w, InterpreterWarning::ContentTruncated)); assert_eq!(truncated, content_was_truncated()); (device.drawn, truncated) } @@ -189,7 +220,10 @@ fn a_soft_mask_set_outside_a_form_draws_that_form() { let pdf = pdf( "<< /XObject << /F 5 0 R >> /ExtGState << /GS << /SMask << /S /Alpha /G 6 0 R >> >> >> >>", "/GS gs /F Do", - &[form(SQUARE), mask_group("<< /XObject << /F 5 0 R >> >>", "/F Do")], + &[ + form(SQUARE), + mask_group("<< /XObject << /F 5 0 R >> >>", "/F Do"), + ], ); let (drawn, truncated) = draw(&pdf, false); assert!(drawn.in_masks > 0, "{drawn:?}"); @@ -202,10 +236,19 @@ fn a_soft_mask_set_inside_a_form_that_it_draws_skips_that_form() { let pdf = pdf( "<< /XObject << /F 5 0 R >> /ExtGState << /GS << /SMask << /S /Alpha /G 6 0 R >> >> >> >>", "/F Do", - &[form("/GS gs 0 0 10 10 re f"), mask_group("<< /XObject << /F 5 0 R >> >>", "/F Do")], + &[ + form("/GS gs 0 0 10 10 re f"), + mask_group("<< /XObject << /F 5 0 R >> >>", "/F Do"), + ], ); let (drawn, truncated) = draw(&pdf, false); - assert_eq!(drawn, Drawn { paths: 1, ..Drawn::default() }); + assert_eq!( + drawn, + Drawn { + paths: 1, + ..Drawn::default() + } + ); assert!(!truncated); } @@ -214,7 +257,10 @@ fn a_tiling_pattern_set_outside_a_form_draws_that_form() { let pdf = pdf( "<< /XObject << /F 5 0 R >> /Pattern << /P 6 0 R >> >>", "/Pattern cs /P scn /F Do", - &[form(SQUARE), tiling("<< /XObject << /F 5 0 R >> >>", "/F Do")], + &[ + form(SQUARE), + tiling("<< /XObject << /F 5 0 R >> >>", "/F Do"), + ], ); let (drawn, truncated) = draw(&pdf, false); assert!(drawn.in_patterns > 0, "{drawn:?}"); @@ -226,10 +272,19 @@ fn a_tiling_pattern_set_inside_a_form_that_it_draws_skips_that_form() { let pdf = pdf( "<< /XObject << /F 5 0 R >> /Pattern << /P 6 0 R >> >>", "/F Do", - &[form("/Pattern cs /P scn 0 0 10 10 re f"), tiling("<< /XObject << /F 5 0 R >> >>", "/F Do")], + &[ + form("/Pattern cs /P scn 0 0 10 10 re f"), + tiling("<< /XObject << /F 5 0 R >> >>", "/F Do"), + ], ); let (drawn, truncated) = draw(&pdf, false); - assert_eq!(drawn, Drawn { paths: 1, ..Drawn::default() }); + assert_eq!( + drawn, + Drawn { + paths: 1, + ..Drawn::default() + } + ); assert!(!truncated); } @@ -239,7 +294,11 @@ fn a_type3_glyph_shown_outside_a_form_draws_that_form() { let pdf = pdf( "<< /XObject << /F 5 0 R >> /Font << /T 6 0 R >> >>", "BT /T 10 Tf (a) Tj ET /F Do", - &[form(SQUARE), type3("<< /XObject << /F 5 0 R >> >>", 7), stream("", "1000 0 d0 /F Do")], + &[ + form(SQUARE), + type3("<< /XObject << /F 5 0 R >> >>", 7), + stream("", "1000 0 d0 /F Do"), + ], ); let (drawn, truncated) = draw(&pdf, true); assert!(drawn.in_glyphs > 0, "{drawn:?}"); @@ -258,6 +317,12 @@ fn a_type3_glyph_shown_inside_a_form_that_it_draws_skips_that_form() { ], ); let (drawn, truncated) = draw(&pdf, false); - assert_eq!(drawn, Drawn { paths: 1, ..Drawn::default() }); + assert_eq!( + drawn, + Drawn { + paths: 1, + ..Drawn::default() + } + ); assert!(!truncated); } From 340da93ecea410e479959578edae51be805e686f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:30:50 -0800 Subject: [PATCH 20/31] craft-raster3d: keep inverse-square falloff at or below 1 A clamped inverse-square light with a radius between 0 and 1 lit fully up to its radius and then used (1 / distance)^2, so it was brighter than full intensity between the radius and 1 unit. The plateau and the falloff now use the same radius, at least 1, and the `Light::radius` docs say so. --- crates/raster3d/src/scene.rs | 3 +++ crates/raster3d/src/shade.rs | 9 ++++----- crates/raster3d/tests/it/bounds.rs | 26 ++++++++++++++++++++++++++ 3 files changed, 33 insertions(+), 5 deletions(-) diff --git a/crates/raster3d/src/scene.rs b/crates/raster3d/src/scene.rs index 9667561ac1..ba8efd56e9 100644 --- a/crates/raster3d/src/scene.rs +++ b/crates/raster3d/src/scene.rs @@ -123,6 +123,9 @@ pub struct Light { pub cos_outer: f32, /// 0 none, 1 smooth, 2 inverse square clamped. Other values return [`RenderError::BadLight`]. pub falloff: u32, + /// For point and spot lights with falloff 1 or 2, the distance factor stays at 1 within the radius. + /// With falloff 2, a radius below 1 counts as 1; beyond that radius, the distance factor is (radius / distance)². + /// Falloff 0 ignores the radius. pub radius: f32, pub falloff_distance: f32, /// First shadow map (point lights, and spot lights whose outer cone's half angle is over 1.40 diff --git a/crates/raster3d/src/shade.rs b/crates/raster3d/src/shade.rs index 1af5b737f8..364bf10edf 100644 --- a/crates/raster3d/src/shade.rs +++ b/crates/raster3d/src/shade.rs @@ -521,11 +521,10 @@ fn attenuation(l: &Light, p: [f32; 3], to_l: [f32; 3], dist: f32) -> f32 { } } 2 if l.kind != 0 => { - if dist <= l.radius || (l.radius <= 0.0 && dist <= 1.0) { - 1.0 - } else { - (l.radius.max(1.0) / dist).powi(2) - } + // The plateau and the inverse square use the same radius, at least 1, so the + // factor never exceeds 1. + let r = l.radius.max(1.0); + if dist <= r { 1.0 } else { (r / dist).powi(2) } } _ => 1.0, }; diff --git a/crates/raster3d/tests/it/bounds.rs b/crates/raster3d/tests/it/bounds.rs index b73dcc7f35..fcca73aea1 100644 --- a/crates/raster3d/tests/it/bounds.rs +++ b/crates/raster3d/tests/it/bounds.rs @@ -1390,6 +1390,32 @@ fn a_point_light_whose_squared_distance_overflows_f32_still_lights() { assert!((far.data[px][0] - near.data[px][0]).abs() < 1e-3 * near.data[px][0], "{:?} {:?}", far.data[px], near.data[px]); } +#[test] +fn inverse_square_falloff_with_a_radius_below_one_never_brightens_the_light() { + // A clamped inverse-square point light 0.75 units from the pixel center (4.5, 4.5) of a quad. + // With a radius of 0.5 it lights the pixel as fully as a radius of 1 does, and past 1 unit + // both fall off the same. + let mut s = quad_scene(8, 8, &[([0.0, 0.0, 8.0, 8.0], 500.0, WHITE)]); + s.materials[0].unlit = false; + let mut point = spot([4.5, 4.5, 499.25], [0.0, 0.0, 1.0], 1.0, 1.0); + (point.kind, point.falloff, point.shadow) = (2, 2, -1); + s.lights = vec![point]; + let px = 4 * 8 + 4; + let mut lit = Vec::new(); + for z in [499.25, 497.0] { + s.lights[0].pos[2] = z; + s.lights[0].radius = 1.0; + let (one, _) = try_render_cpu(&s, &Limits::default()).unwrap(); + s.lights[0].radius = 0.5; + let (half, _) = try_render_cpu(&s, &Limits::default()).unwrap(); + assert!(one.data[px][0] > 0.01, "{z}: {:?}", one.data[px]); + assert_eq!(bits4(&half.data), bits4(&one.data), "{z}"); + lit.push(one.data[px][0]); + } + // 3 units away the light falls off to (1 / 3)² of its full intensity. + assert!((lit[1] * 9.0 - lit[0]).abs() < 1e-3 * lit[0], "{lit:?}"); +} + #[test] fn coordinates_from_two_to_the_twenty_third_texels_keep_the_half_texel_shift() { let texels = [[0.0, 0.0, 0.0, 1.0], [1.0, 0.0, 0.0, 1.0]]; From 5a69244212b2e5283b82f41d65018ea44dedf938 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 15:07:07 -0800 Subject: [PATCH 21/31] raster3d: charge the search under discarded pixels before its tests Band::fallback ran every coverage test of a triangle and only then added them to the shared work total, so a render over Limits::max_work still ran the whole triangle's tests, and TooMuchWork reported a `needed` that depended on the order the bands ran in. The search now gathers a triangle's candidate pixels in batches of 256 and charges each batch before testing it. A band also stops after any triangle once the total of all bands is over the limit, and the error reports `needed` as `limit + 1`. Output and the counted work are unchanged. --- crates/raster3d/src/lib.rs | 7 ++- crates/raster3d/src/raster.rs | 91 +++++++++++++++++++++++++----- crates/raster3d/tests/it/bounds.rs | 2 +- crates/raster3d/tests/it/main.rs | 1 + crates/raster3d/tests/it/work.rs | 59 +++++++++++++++++++ 5 files changed, 141 insertions(+), 19 deletions(-) create mode 100644 crates/raster3d/tests/it/work.rs diff --git a/crates/raster3d/src/lib.rs b/crates/raster3d/src/lib.rs index a5d25d295a..59e0627577 100644 --- a/crates/raster3d/src/lib.rs +++ b/crates/raster3d/src/lib.rs @@ -137,9 +137,10 @@ pub enum RenderError { #[error("the shadow texels do not fit 32-bit offsets")] TooManyShadowTexels, /// Rasterizing or rendering shadow maps would take more coverage or depth tests than - /// [`Limits::max_work`]. Preparation stops at the first triangle past the limit. Fallback - /// and shadow-map work may be counted on several threads, within one triangle per thread, so `needed` is at least - /// `limit + 1` and may be below the scene's total. + /// [`Limits::max_work`]. Preparation stops at the first triangle past the limit. The search + /// under discarded pixels runs on several threads and reports `needed` as `limit + 1`; shadow-map + /// work may be counted within one triangle per thread. `needed` is at least `limit + 1` and may + /// be below the scene's total. #[error("the render needs at least {needed} tests, over the limit of {limit}")] TooMuchWork { needed: u64, limit: u64 }, /// A resolve factor is zero or does not divide both sides of the target. diff --git a/crates/raster3d/src/raster.rs b/crates/raster3d/src/raster.rs index b03cbf4987..e5955c1b93 100644 --- a/crates/raster3d/src/raster.rs +++ b/crates/raster3d/src/raster.rs @@ -508,21 +508,27 @@ impl Band<'_> { /// triangle other than the pixel's visible one, inside the depth range as in /// [`Band::visibility`]. Triangles are /// visited in index order over their bounding boxes, and among fragments at equal depth the - /// first triangle's is kept. Coverage tests count toward [`Limits::max_work`]. + /// first triangle's is kept. Each coverage test counts toward [`Limits::max_work`] next to the + /// work `setup` charged. A triangle's candidate pixels are gathered in batches of 256, and each + /// batch is charged before its tests run, so a band stops with [`RenderError::TooMuchWork`] + /// without testing a batch that passes the limit. A band also stops after any triangle once the + /// total of all bands is over the limit. The error reports `needed` as `limit + 1`, so it does + /// not depend on the order the bands run in. fn fallback(&self, opaque: Pass, vis: &Visibility, discarded: &[bool]) -> Result>, RenderError> { let (s, w, y0, rows) = (self.s, self.w, self.y0, self.rows); + let over = || RenderError::TooMuchWork { needed: self.limit.saturating_add(1), limit: self.limit }; let mut best: Vec> = vec![None; rows * w]; + let mut batch = [(0usize, 0i32, 0i32); 256]; for &tj in opaque.bins { let t2 = &opaque.tris[tj as usize]; - let mut tests = 0u64; - for y in t2.bbox[1].max(y0)..t2.bbox[3].min(y0 + rows as i32) { - let r = (y - y0) as usize * w; - for x in t2.bbox[0]..t2.bbox[2] { - let i = r + x as usize; - if !discarded[i] || vis[i].0 == tj { - continue; - } - tests += 1; + let mut test = |entries: &[(usize, i32, i32)]| -> Result<(), RenderError> { + let tests = entries.len() as u64; + if self.spent.fetch_add(tests, Ordering::Relaxed).saturating_add(tests) > self.limit { + return Err(over()); + } + #[cfg(test)] + tests::FALLBACK_TESTS.fetch_add(tests, Ordering::Relaxed); + for &(i, x, y) in entries { if let Some((z, l2)) = cover(t2, x as f64 + 0.5, y as f64 + 0.5) && nearer(z, best[i].map_or(EMPTY, |b| b.ndc_z)) { @@ -532,10 +538,29 @@ impl Band<'_> { } } } + Ok(()) + }; + let mut len = 0; + for y in t2.bbox[1].max(y0)..t2.bbox[3].min(y0 + rows as i32) { + let r = (y - y0) as usize * w; + for x in t2.bbox[0]..t2.bbox[2] { + let i = r + x as usize; + if !discarded[i] || vis[i].0 == tj { + continue; + } + batch[len] = (i, x, y); + len += 1; + if len == batch.len() { + test(&batch)?; + len = 0; + } + } } - let needed = self.spent.fetch_add(tests, Ordering::Relaxed).saturating_add(tests); - if needed > self.limit { - return Err(RenderError::TooMuchWork { needed, limit: self.limit }); + if len != 0 { + test(&batch[..len])?; + } + if self.spent.load(Ordering::Relaxed) > self.limit { + return Err(over()); } } Ok(best) @@ -606,8 +631,44 @@ pub fn try_render(s: &Scene, limits: &Limits) -> Result { #[cfg(test)] mod tests { - use super::{cover, f32_crossing, fan, project}; - use crate::scene::Scene; + use std::sync::atomic::{AtomicU64, Ordering}; + + use super::{cover, f32_crossing, fan, project, try_render}; + use crate::scene::{Material, Scene, Vertex}; + use crate::{Limits, RenderError}; + + /// The coverage tests the search under discarded pixels has run. + pub(super) static FALLBACK_TESTS: AtomicU64 = AtomicU64::new(0); + + #[test] + fn the_search_under_discarded_pixels_runs_no_batch_past_the_work_limit() { + // One band of 32 × 16 pixels covered by a far quad and, nearer, a masked quad whose every + // fragment is discarded. Setup charges 4 × (512 + 1); the search tests each pixel three + // times (once for each far triangle and once for the near triangle that does not hold it). + let (w, h) = (32u32, 16u32); + let mut s = Scene { width: w, height: h, ssaa: 1, linear_io: true, ortho: true, cam_fwd: [0.0, 0.0, 1.0], ..Scene::default() }; + s.clip = [[2.0 / w as f32, 0.0, 0.0, -1.0], [0.0, -2.0 / h as f32, 0.0, 1.0], [0.0, 0.0, -0.001, 1.0], [0.0, 0.0, 0.0, 1.0]]; + s.view = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]; + s.materials = vec![ + Material { unlit: true, double_sided: true, ..Material::default() }, + Material { base: [1.0, 1.0, 1.0, 0.0], alpha_mode: 1, unlit: true, double_sided: true, ..Material::default() }, + ]; + for (m, z) in [(0, 100.0), (1, 50.0)] { + let b = s.vertices.len() as u32; + for (x, y) in [(0.0, 0.0), (w as f32, 0.0), (w as f32, h as f32), (0.0, h as f32)] { + s.vertices.push(Vertex { pos: [x, y, z], normal: [0.0, 0.0, -1.0], uv: [0.0; 2], tangent: [1.0, 0.0, 0.0, 1.0], material: m }); + } + s.indices.extend([b, b + 2, b + 1, b, b + 3, b + 2]); + } + s.opaque_count = 12; + let full = 4 * (32 * 16 + 1) + 3 * 32 * 16; + let limit = |max_work| Limits { max_work, ..Limits::default() }; + assert!(try_render(&s, &limit(full)).is_ok()); + FALLBACK_TESTS.store(0, Ordering::Relaxed); + assert!(matches!(try_render(&s, &limit(full - 1)), Err(RenderError::TooMuchWork { .. }))); + let ran = FALLBACK_TESTS.load(Ordering::Relaxed); + assert!(ran < 3 * 32 * 16, "{ran}"); + } #[test] fn wide_projection_preserves_subnormal_weights_on_an_included_edge() { diff --git a/crates/raster3d/tests/it/bounds.rs b/crates/raster3d/tests/it/bounds.rs index b73dcc7f35..4be6f63f94 100644 --- a/crates/raster3d/tests/it/bounds.rs +++ b/crates/raster3d/tests/it/bounds.rs @@ -1141,7 +1141,7 @@ fn overflowing_coverage_work_in_the_fallback_is_refused() { let setup = 4 * (4 * u64::from(height) + 1); assert_eq!(try_render(&s, &limits(|l| l.max_work = u64::MAX)).unwrap().color[0], WHITE); assert!( - matches!(try_render(&s, &limits(|l| l.max_work = setup)), Err(RenderError::TooMuchWork { limit, needed }) if limit == setup && needed > setup) + matches!(try_render(&s, &limits(|l| l.max_work = setup)), Err(RenderError::TooMuchWork { limit, needed }) if limit == setup && needed == setup + 1) ); s.materials[1].base[3] = 1.0; assert!(try_render(&s, &limits(|l| l.max_work = setup)).is_ok()); diff --git a/crates/raster3d/tests/it/main.rs b/crates/raster3d/tests/it/main.rs index 98f3485e8c..a141d1a855 100644 --- a/crates/raster3d/tests/it/main.rs +++ b/crates/raster3d/tests/it/main.rs @@ -5,6 +5,7 @@ mod bounds; mod differential; mod moved; +mod work; /// A verbatim copy of the app's previous code, run by `differential`. mod reference { diff --git a/crates/raster3d/tests/it/work.rs b/crates/raster3d/tests/it/work.rs new file mode 100644 index 0000000000..e6ba3a3c65 --- /dev/null +++ b/crates/raster3d/tests/it/work.rs @@ -0,0 +1,59 @@ +//! The work limit of the search under discarded pixels. + +use craft_raster3d::{RenderError, Scene, try_render}; + +use crate::{limits, quad_scene}; + +const WHITE: [f32; 4] = [1.0; 4]; +const FAR: [f32; 4] = [0.25, 0.5, 0.75, 1.0]; + +/// Two screen-filling quads; the nearer one is a masked material whose alpha fails the cutoff, so +/// every pixel is discarded and the search for a surviving fragment visits the farther quad. +fn discarding_scene(w: u32, h: u32) -> Scene { + let (fw, fh) = (w as f32, h as f32); + let mut s = quad_scene(w, h, &[([0.0, 0.0, fw, fh], 100.0, FAR), ([0.0, 0.0, fw, fh], 50.0, WHITE)]); + s.materials[1].alpha_mode = 1; + s.materials[1].base[3] = 0.0; + s +} + +#[test] +fn the_work_count_of_the_search_under_discarded_pixels_does_not_depend_on_the_bands() { + // Two bands of 16 rows; each band's first farther triangle makes 64 tests, so band 0 alone + // passes the limit. + let s = discarding_scene(4, 32); + let setup = 4 * (4 * 32 + 1); + assert!(matches!( + try_render(&s, &limits(|l| l.max_work = setup)), + Err(RenderError::TooMuchWork { limit, needed }) if limit == setup && needed == setup + 1 + )); + // The search tests each pixel of a band three times: once for each farther triangle and once + // for the nearer triangle that does not hold it. A limit that holds one band's tests but not + // both is passed only by the bands together. + let per_band = 3 * 4 * 16; + let band = discarding_scene(4, 16); + let band_setup = 4 * (4 * 16 + 1); + assert!(try_render(&band, &limits(|l| l.max_work = band_setup + per_band)).is_ok()); + assert!(try_render(&band, &limits(|l| l.max_work = band_setup + per_band - 1)).is_err()); + let limit = setup + per_band; + assert!(matches!( + try_render(&s, &limits(|l| l.max_work = limit)), + Err(RenderError::TooMuchWork { limit: l, needed }) if l == limit && needed == limit + 1 + )); + assert!(try_render(&s, &limits(|l| l.max_work = setup + 2 * per_band)).is_ok()); +} + +#[test] +fn a_search_of_several_batches_counts_every_test_once() { + // One band of 32 × 16 pixels: each farther triangle's bounding box holds 512 discarded pixels, + // so its tests are charged in two full batches of 256. The search tests each pixel three times. + let s = discarding_scene(32, 16); + let setup = 4 * (32 * 16 + 1); + let search = 3 * 32 * 16; + let t = try_render(&s, &limits(|l| l.max_work = setup + search)).unwrap(); + assert!(t.color.iter().all(|&c| c == FAR)); + assert!(matches!( + try_render(&s, &limits(|l| l.max_work = setup + search - 1)), + Err(RenderError::TooMuchWork { limit, needed }) if limit == setup + search - 1 && needed == limit + 1 + )); +} From 229d24becf8d248d86736c3cb5c9b13df5e19aa5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 15:18:13 -0800 Subject: [PATCH 22/31] raster3d: clip far-off depth crossings again in f64 A crossing of the near or far plane computed in f32 can land further off the plane than the 4-epsilon tolerance that moves an ndc depth back to 0..=1, and the depth test then rejected the corner, so part of a visible triangle was not drawn. Such a crossing is now computed again in f64 from the corner nearer the plane instead of being snapped to the plane. - The f64 crossing does not depend on the direction of the edge, and the retry is taken when either direction misses, so triangles that share the edge get the same corner. An edge from a corner clipped in f64 is also clipped in f64 at the next plane. - When the corrected corner has a subnormal coordinate, the triangle is clipped and projected in f64 throughout, since narrowing it to f32 would move or drop the corner. - A triangle whose corners all lie within 0 <= z <= w skips clipping. Split from #2985. --- crates/raster3d/src/raster.rs | 150 +++++++++++++++++-------- crates/raster3d/tests/it/main.rs | 1 + crates/raster3d/tests/it/near_plane.rs | 99 ++++++++++++++++ 3 files changed, 206 insertions(+), 44 deletions(-) create mode 100644 crates/raster3d/tests/it/near_plane.rs diff --git a/crates/raster3d/src/raster.rs b/crates/raster3d/src/raster.rs index b03cbf4987..b606121d53 100644 --- a/crates/raster3d/src/raster.rs +++ b/crates/raster3d/src/raster.rs @@ -49,6 +49,9 @@ struct STri { /// A polygon corner: clip coordinates and weights over the original triangle's vertices. type Corner = ([f32; 4], [f32; 3]); +/// A [`Corner`] held in `f64`. +type WideCorner = ([f64; 4], [f64; 3]); + /// A screen-space corner: position, ndc z, 1/w and weights. type ScreenCorner = ([f64; 2], f32, f64, [f32; 3]); @@ -110,7 +113,12 @@ pub(crate) fn f32_crossing(da: f32, db: f32) -> (bool, f32) { /// Clip a polygon against `planes` (see [`plane_distance`]), interpolating in `f64` from the /// corner nearer the plane. fn clip_f64(poly: &[Corner], planes: &[usize]) -> Vec { - let mut p: Vec<([f64; 4], [f64; 3])> = poly.iter().map(|(c, w)| (c.map(f64::from), w.map(f64::from))).collect(); + clip_wide(poly, planes).iter().map(|(c, w)| (c.map(|v| v as f32), w.map(|v| v as f32))).collect() +} + +/// [`clip_f64`] without narrowing the result to `f32`. +fn clip_wide(poly: &[Corner], planes: &[usize]) -> Vec { + let mut p: Vec = poly.iter().map(|(c, w)| (c.map(f64::from), w.map(f64::from))).collect(); for &plane in planes { if p.is_empty() { break; @@ -124,44 +132,7 @@ fn clip_f64(poly: &[Corner], planes: &[usize]) -> Vec { out.push(a); } if (da >= 0.0) != (db >= 0.0) { - let (p, q, t) = if da.abs() <= db.abs() { (a, b, da / (da - db)) } else { (b, a, db / (db - da)) }; - let c: [f64; 4] = std::array::from_fn(|k| p.0[k] + (q.0[k] - p.0[k]) * t); - let w: [f64; 3] = std::array::from_fn(|k| p.1[k] + (q.1[k] - p.1[k]) * t); - out.push((c, w)); - } - } - p = out; - } - p.iter().map(|(c, w)| (c.map(|v| v as f32), w.map(|v| v as f32))).collect() -} - -/// Clip a polygon (clip coords + original weights) against `0 ≤ z ≤ w`. -fn clip_poly(poly: Vec) -> Vec { - let mut p = poly; - for plane in 0..2 { - if p.is_empty() { - break; - } - let d = |c: &[f32; 4]| if plane == 0 { c[2] } else { c[3] - c[2] }; - let mut out = Vec::with_capacity(p.len() + 2); - for i in 0..p.len() { - let (a, b) = (p[i], p[(i + 1) % p.len()]); - let (da, db) = (d(&a.0), d(&b.0)); - if da >= 0.0 { - out.push(a); - } - if (da >= 0.0) != (db >= 0.0) { - let (from_b, t) = f32_crossing(da, db); - let (p, q) = if from_b { (b, a) } else { (a, b) }; - let mut c = [0.0; 4]; - let mut w = [0.0; 3]; - for k in 0..4 { - c[k] = p.0[k] + (q.0[k] - p.0[k]) * t; - } - for k in 0..3 { - w[k] = p.1[k] + (q.1[k] - p.1[k]) * t; - } - out.push((c, w)); + out.push(crossing_f64(a, b, da, db)); } } p = out; @@ -169,12 +140,89 @@ fn clip_poly(poly: Vec) -> Vec { p } +/// Where the edge from `a` (plane distance `da`) to `b` (`db`) crosses the plane, interpolated in +/// `f64` from the corner nearer the plane, so both directions of an edge give the same corner. +fn crossing_f64(a: ([f64; 4], [f64; 3]), b: ([f64; 4], [f64; 3]), da: f64, db: f64) -> ([f64; 4], [f64; 3]) { + let (p, q, t) = if da.abs() <= db.abs() { (a, b, da / (da - db)) } else { (b, a, db / (db - da)) }; + let c: [f64; 4] = std::array::from_fn(|k| p.0[k] + (q.0[k] - p.0[k]) * t); + let w: [f64; 3] = std::array::from_fn(|k| p.1[k] + (q.1[k] - p.1[k]) * t); + (c, w) +} + +/// Where the edge from `a` (plane distance `da`) to `b` (`db`) crosses the plane, in `f32` (see +/// [`f32_crossing`]). +fn f32_corner(a: Corner, b: Corner, da: f32, db: f32) -> Corner { + let (from_b, t) = f32_crossing(da, db); + let (p, q) = if from_b { (b, a) } else { (a, b) }; + let mut c = [0.0; 4]; + let mut w = [0.0; 3]; + for k in 0..4 { + c[k] = p.0[k] + (q.0[k] - p.0[k]) * t; + } + for k in 0..3 { + w[k] = p.1[k] + (q.1[k] - p.1[k]) * t; + } + (c, w) +} + +/// Whether a finite clip corner's ndc depth lies further outside `0..=1` than [`ndc_z`] moves back. +fn off_plane(c: &[f32; 4]) -> bool { + c.iter().all(|v| v.is_finite()) && !(-NDC_ROUNDING..=1.0 + NDC_ROUNDING).contains(&(f64::from(c[2]) / f64::from(c[3]))) +} + +/// Clip a polygon (clip coords + original weights) against `0 ≤ z ≤ w`. +fn clip_poly(poly: Vec) -> Option> { + if poly.iter().all(|(c, _)| c[2] >= 0.0 && c[2] <= c[3]) { + return Some(poly); + } + // Each corner carries whether it was clipped in f64. + let mut p: Vec<(Corner, bool)> = poly.into_iter().map(|c| (c, false)).collect(); + for plane in 0..2 { + if p.is_empty() { + break; + } + let d = |c: &[f32; 4]| if plane == 0 { c[2] } else { c[3] - c[2] }; + let mut out = Vec::with_capacity(p.len() + 2); + for i in 0..p.len() { + let ((a, a_wide), (b, b_wide)) = (p[i], p[(i + 1) % p.len()]); + let (da, db) = (d(&a.0), d(&b.0)); + if da >= 0.0 { + out.push((a, a_wide)); + } + if (da >= 0.0) != (db >= 0.0) { + // A finite crossing whose depth lands further off the plane than `ndc_z` moves + // back, in either direction of the edge, is clipped again in f64, and so is an + // edge from a corner clipped in f64. The f64 crossing does not depend on the + // direction, so the triangles on both sides of the edge get the same corner. + let corner = f32_corner(a, b, da, db); + if a_wide || b_wide || off_plane(&corner.0) || off_plane(&f32_corner(b, a, db, da).0) { + let wide = |x: &Corner| (x.0.map(f64::from), x.1.map(f64::from)); + let (a, b) = (wide(&a), wide(&b)); + let dist = |c: &[f64; 4]| plane_distance(c, plane); + let (c, w) = crossing_f64(a, b, dist(&a.0), dist(&b.0)); + if c.iter().any(|v| *v != 0.0 && v.abs() < f64::from(f32::MIN_POSITIVE)) { + return None; + } + out.push(((c.map(|v| v as f32), w.map(|v| v as f32)), true)); + } else { + out.push((corner, false)); + } + } + } + p = out; + } + Some(p.into_iter().map(|(c, _)| c).collect()) +} + +/// How far past 0 or 1 [`ndc_z`] moves an ndc depth back to the end of the range. +const NDC_ROUNDING: f64 = 4.0 * f32::EPSILON as f64; + /// The ndc depth of a corner clipped to `0 ≤ z ≤ w`, moved back to the end of the range when the /// division by `w` rounds past it by a few ulps (a corner on the near plane can give 1 + 2^-23). A /// depth further out is kept, and the depth test rejects it. #[inline] fn ndc_z(z: f32) -> f32 { - const ROUNDING: f32 = 4.0 * f32::EPSILON; + const ROUNDING: f32 = NDC_ROUNDING as f32; if (1.0..=1.0 + ROUNDING).contains(&z) { 1.0 } else if (-ROUNDING..0.0).contains(&z) { @@ -192,7 +240,9 @@ fn project(s: &Scene, clip: &[[f32; 4]], t: usize) -> Option<(Vec, let tri = vec![(clip[ids[0]], [1.0, 0.0, 0.0]), (clip[ids[1]], [0.0, 1.0, 0.0]), (clip[ids[2]], [0.0, 0.0, 1.0])]; let finite = |p: &[Corner]| p.iter().all(|(c, wt)| c.iter().chain(wt).all(|v| v.is_finite())); // The depth range in f32; when that overflows between far-apart corners, every plane in f64. - let poly = clip_poly(tri.clone()); + let Some(poly) = clip_poly(tri.clone()) else { + return project_wide(s, &clip_wide(&tri, &ALL_PLANES)); + }; let poly = if finite(&poly) { clip_guard(poly) } else { clip_f64(&tri, &ALL_PLANES) }; if poly.len() < 3 || !finite(&poly) { return None; @@ -212,16 +262,28 @@ fn project(s: &Scene, clip: &[[f32; 4]], t: usize) -> Option<(Vec, // A tiny w overflows 1/w in f32: project in f64, with 1/w scaled by a common factor so the // largest is 1 (the interpolation weights use only their ratios). The scaled values stay in // f64, since a ratio below the f32 range would round to 0 and drop the corner's weight. - let iw: Vec = poly.iter().map(|(c, _)| 1.0 / f64::from(c[3])).collect(); + let poly: Vec = poly.iter().map(|(c, wt)| (c.map(f64::from), wt.map(f64::from))).collect(); + project_wide(s, &poly) +} + +/// The screen corners of a clipped polygon projected in `f64`, or `None` when fewer than three +/// corners are left or one is not finite. +fn project_wide(s: &Scene, poly: &[WideCorner]) -> Option<(Vec, bool)> { + if poly.len() < 3 || !poly.iter().all(|(c, wt)| c.iter().chain(wt).all(|v| v.is_finite())) { + return None; + } + let (w, h) = (s.width as f64, s.height as f64); + let iw: Vec = poly.iter().map(|(c, _)| 1.0 / c[3]).collect(); let top = iw.iter().fold(0.0f64, |a, &b| a.max(b)); let scr: Vec = poly .iter() .zip(&iw) .map(|((c, wt), &iw)| { - let (nx, ny) = (f64::from(c[0]) * iw, f64::from(c[1]) * iw); - ([(nx + 1.0) * 0.5 * w, (1.0 - ny) * 0.5 * h], ndc_z((f64::from(c[2]) * iw) as f32), iw / top, *wt) + let (nx, ny) = (c[0] * iw, c[1] * iw); + ([(nx + 1.0) * 0.5 * w, (1.0 - ny) * 0.5 * h], ndc_z((c[2] * iw) as f32), iw / top, wt.map(|v| v as f32)) }) .collect(); + let ok = |s: &ScreenCorner| s.0.iter().all(|v| v.is_finite()) && s.1.is_finite() && s.2.is_finite(); scr.iter().all(ok).then_some((scr, true)) } diff --git a/crates/raster3d/tests/it/main.rs b/crates/raster3d/tests/it/main.rs index 98f3485e8c..30adfcfc3f 100644 --- a/crates/raster3d/tests/it/main.rs +++ b/crates/raster3d/tests/it/main.rs @@ -5,6 +5,7 @@ mod bounds; mod differential; mod moved; +mod near_plane; /// A verbatim copy of the app's previous code, run by `differential`. mod reference { diff --git a/crates/raster3d/tests/it/near_plane.rs b/crates/raster3d/tests/it/near_plane.rs new file mode 100644 index 0000000000..afa4560ef9 --- /dev/null +++ b/crates/raster3d/tests/it/near_plane.rs @@ -0,0 +1,99 @@ +//! Triangles that cross the near plane (ndc depth 1), where clipping rounds. + +use craft_raster3d::{Limits, Material, Scene, Vertex, try_render}; + +use crate::quad_scene; + +const WHITE: [f32; 4] = [1.0; 4]; + +/// A `w` × `h` scene with an identity clip transform and an unlit, double-sided white material +/// whose triangles are those of `corners` (clip positions, three per triangle), all opaque. +fn identity_scene(w: u32, h: u32, corners: &[[f32; 3]]) -> Scene { + let mut s = quad_scene(w, h, &[]); + s.materials.push(Material { unlit: true, double_sided: true, ..Material::default() }); + s.clip = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]; + for &pos in corners { + s.vertices.push(Vertex { pos, normal: [0.0, 0.0, -1.0], uv: [0.0; 2], tangent: [1.0, 0.0, 0.0, 1.0], material: 0 }); + } + s.indices = (0..corners.len() as u32).collect(); + s.opaque_count = corners.len() as u32; + s +} + +#[test] +fn a_near_plane_crossing_that_rounds_far_off_the_plane_is_still_drawn() { + // The f32 crossings of the edges to the middle corner land more than 4 ulps past depth 1. + let s = identity_scene(5, 5, &[[-1.0, -0.5, 0.264_506_85], [0.0, 8.690_391, 13.783_444], [1.0, -0.5, 0.264_506_85]]); + let t = try_render(&s, &Limits::default()).unwrap(); + // Clipped at depth 1 the triangle spans ndc y -0.5 to 0, whose top edge runs through the + // centers of row 2, so rows 2 and 3 are covered. + for (i, c) in t.color.iter().enumerate().take(20).skip(10) { + assert_eq!(*c, WHITE, "pixel {i}"); + } +} + +#[test] +fn triangles_that_share_an_edge_crossing_the_near_plane_leave_no_gap() { + // Only the first triangle has a second crossing that lands far off the plane; the shared + // edge's crossing is the same in both, so the pixel center beside it stays covered. + let (a, b) = ([-0.3, -0.51, 0.0], [12.0, 20.4, 13.783_444]); + let s = identity_scene(5, 5, &[a, b, [1.0, -0.5, 0.264_506_85], b, a, [-0.5, 1.0, 1.0]]); + let t = try_render(&s, &Limits::default()).unwrap(); + assert_eq!(t.color[12][3], 1.0, "{:?}", t.color); +} + +#[test] +fn triangles_that_share_an_edge_crossing_both_depth_planes_leave_no_gap() { + let (a, b) = ([-1.0, -0.03, -8.44], [1.0, 0.03, 9.44]); + let s = identity_scene(1, 1, &[a, b, [0.0, 1.0, 0.5], b, a, [0.0, -1.0, 0.5]]); + let t = try_render(&s, &Limits::default()).unwrap(); + assert_eq!(t.color[0][3], 1.0); +} + +#[test] +fn a_clipped_near_plane_edge_with_rounded_depth_below_one_is_drawn() { + // Both generated corners have z = 1 - 2^-24 and lie along screen row 2. + let s = identity_scene(5, 5, &[[-1.0, -0.5, 0.0], [0.0, 2623.5002, 5248.0], [1.0, -0.5, 0.0]]); + let t = try_render(&s, &Limits::default()).unwrap(); + for x in 0..5 { + assert_eq!(t.color[2 * 5 + x], WHITE, "column {x}"); + } +} + +#[test] +fn a_depth_crossing_that_overflows_f32_is_still_clipped_in_f64() { + // The edges to the third corner cross the far plane with a depth difference that overflows + // f32, so the polygon is clipped again in f64, which keeps the left pixel center inside. + let mut s = identity_scene(2, 1, &[[-6.099998e37, 8e37, 5e37], [-6.099998e37, -8e37, 5e37], [2.4799903e37, 0.0, -3.4e38]]); + s.clip[3][3] = 1e38; + let t = try_render(&s, &Limits::default()).unwrap(); + assert_eq!(t.color[0][3], 1.0); +} + +#[test] +fn a_subnormal_depth_crossing_with_positive_w_is_still_drawn() { + let mut s = identity_scene(1, 1, &[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]); + let scale = f32::from_bits(1); + s.clip = [[-12.0, 10.0, 0.0, 0.0], [-8.0, -9.0, 10.0, 0.0], [8.0, -7.0, 1.0, 0.0], [-7.0, 8.0, 0.0, 0.0]]; + for row in &mut s.clip { + for v in row { + *v *= scale; + } + } + let t = try_render(&s, &Limits::default()).unwrap(); + assert_eq!(t.color[0], WHITE); +} + +#[test] +fn a_subnormal_depth_crossing_preserves_projected_edge_coverage() { + let mut s = identity_scene(5, 5, &[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]); + let scale = f32::from_bits(1); + s.clip = [[3.0, -2.0, -2.0, 0.0], [0.0, -6.0, 5.0, 0.0], [8.0, 5.0, 3.0, 0.0], [5.0, 8.0, 4.0, 0.0]]; + for row in &mut s.clip { + for v in row { + *v *= scale; + } + } + let t = try_render(&s, &Limits::default()).unwrap(); + assert_eq!(t.color[3 * 5 + 2], WHITE); +} From 988e77876f9f462654ceac8372203ee3b91ed6ae Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:22:43 -0800 Subject: [PATCH 23/31] ui: a canvas body can claim a wheel gesture and mark it modal Wheel gains claimed, claimed_gathered, claimed_zoom_gathered and claimed_spent. CanvasSpace::claim_wheel claims the pass's share of the gesture the canvas owns and records the motion the body used up; the gesture's later shares carry the claim and count only the shares the body claimed, so a body that turns a gesture into steps keeps no state of its own. A second claim in the same pass replaces the first, and a claim outside a running pass, of a gesture another taker owns, or with a non-finite spent value is refused. claim_wheel returns whether the claim was taken. The canvas does not move its view by a claimed gesture: it skips the navigation of claimed shares and drops the eased wheel, the eased wheel zoom, the touchpad glide and any partial zoom notch the gesture still owed, also in passes without a share and after a device end. CanvasSpace::mark_wheel_modal marks the running gesture as gone on under one of the app's own modal windows, so its later shares carry Wheel::modal until it ends. Synthesized end shares carry the claims of the gesture they end, and a gesture the split hands to another owner starts its claims again. --- crates/behavior/src/wheel.rs | 18 +- crates/ui-canvas/src/canvas/mod.rs | 10 +- crates/ui-canvas/src/canvas/space.rs | 22 ++ .../ui-canvas/tests/it/canvas/modal_wheel.rs | 264 +++++++++++++++++- crates/ui-contract/src/runtime/wheel.rs | 131 ++++++++- crates/ui-contract/tests/it/runtime/wheel.rs | 102 +++++++ docs/contract-api.md | 10 +- 7 files changed, 549 insertions(+), 8 deletions(-) diff --git a/crates/behavior/src/wheel.rs b/crates/behavior/src/wheel.rs index a5de8554a7..9d81b764ea 100644 --- a/crates/behavior/src/wheel.rs +++ b/crates/behavior/src/wheel.rs @@ -106,8 +106,20 @@ pub struct Wheel { /// taker that owns the gesture; another taker's share holds its own `mods`. pub held: Mods, /// A wheel event of the running gesture, or one less than [`GESTURE_GAP`] seconds before it began, arrived while a - /// modal layer held the wheel: the turn began or went on under the modal, and it stays marked until it ends. + /// modal layer held the wheel: the turn began or went on under the modal, and it stays marked until it ends. An + /// app's own modal window marks it too (`CanvasSpace::mark_wheel_modal`). pub modal: bool, + /// The owner claimed an earlier share of the running gesture (`CanvasSpace::claim_wheel`): it takes the gesture + /// for itself. For the taker that owns the gesture; another taker's share is never claimed. + pub claimed: bool, + /// The `scroll` of the running gesture's shares the owner claimed before this one. Motion the owner did not + /// claim is not counted. + pub claimed_gathered: Vec2, + /// The `zoom_lines` of the running gesture's shares the owner claimed before this one. + pub claimed_zoom_gathered: Vec2, + /// The motion the owner said it used up (`spent`) with its claims of the running gesture so far, in its own + /// unit: `claimed_gathered` or `claimed_zoom_gathered` less this is what the claimed shares left over. + pub claimed_spent: Vec2, } /// The eased motion of a canvas's line wheel: notches gather into owed motion that later passes pay out. @@ -256,6 +268,10 @@ impl Wheel { moved: false, held: mods, modal: false, + claimed: false, + claimed_gathered: Vec2::ZERO, + claimed_zoom_gathered: Vec2::ZERO, + claimed_spent: Vec2::ZERO, } } diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index 963fd75f92..158ac49524 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -480,7 +480,15 @@ impl<'a> Canvas<'a> { let mut zoom_anchor = None; let wheel = cx.take_wheel(); let wheeled = wheel.is_some(); - if let Some(wheel) = &wheel { + // A share of a gesture the body claimed (`CanvasSpace::claim_wheel`) goes to the body alone: the view stays, and + // the motion the eased wheel and the eased wheel zoom still owe is dropped. + if crate::runtime::wheel::claimed(&ctx, id) || wheel.as_ref().is_some_and(|wheel| wheel.claimed) { + motion.glide.stop(); + cx.stop_wheel_ease(); + motion.wheel_zoom.stop_if(true); + motion.wheel = WheelNavigation::default(); + } + if let Some(wheel) = wheel.as_ref().filter(|wheel| !wheel.claimed) { let read = self.read_wheel(cx, &mut motion, &mut view, wheel, now); line_pan = read.line_pan; jumped |= read.jumped; diff --git a/crates/ui-canvas/src/canvas/space.rs b/crates/ui-canvas/src/canvas/space.rs index c8c9dc8432..e0349c07c3 100644 --- a/crates/ui-canvas/src/canvas/space.rs +++ b/crates/ui-canvas/src/canvas/space.rs @@ -298,6 +298,28 @@ impl CanvasSpace { nudge } + /// Claims this pass's wheel share ([`wheel`](Self::wheel)) for the canvas's body, recording `spent`, the part of + /// the claimed motion the body used up, in its own unit, and returning whether the claim succeeded. The gesture's + /// later shares carry `Wheel::claimed` and count only the claimed shares in `claimed_gathered`, + /// `claimed_zoom_gathered` and `claimed_spent`, so a body that turns a gesture into steps keeps no state of its + /// own. A second claim in the same pass replaces the first. + /// The canvas must own the gesture and have a share in the running pass. A share returned by `wheel` can belong + /// to a gesture another scroller owns; that share cannot be claimed. The body should act only on an accepted claim. + pub fn claim_wheel(&self, ctx: &egui::Context, spent: Vec2) -> bool { + if let (Some(canvas), Some(_)) = (self.canvas, self.wheel) { + return crate::runtime::wheel::claim(ctx, canvas, spent); + } + false + } + + /// Marks the running wheel gesture as begun or gone on under a modal, for one of the app's own modal windows that + /// the wheel service does not see. The gesture's later shares carry `Wheel::modal` until it ends. + pub fn mark_wheel_modal(&self, ctx: &egui::Context) { + if let Some(canvas) = self.canvas { + crate::runtime::wheel::mark_modal(ctx, canvas); + } + } + /// Device pixels per document unit (1 is 100 %) of the view at this scale. pub fn zoom_device(&self) -> f64 { zoom::device(&self.view, self.pixels_per_point) diff --git a/crates/ui-canvas/tests/it/canvas/modal_wheel.rs b/crates/ui-canvas/tests/it/canvas/modal_wheel.rs index 314fe1eeb2..d063e3ae36 100644 --- a/crates/ui-canvas/tests/it/canvas/modal_wheel.rs +++ b/crates/ui-canvas/tests/it/canvas/modal_wheel.rs @@ -2,12 +2,12 @@ use craft_behavior::CanvasView; use craft_behavior::kurbo::{Point, Size}; -use craft_ui::canvas::{Canvas, NavigationOptions}; +use craft_ui::canvas::{Canvas, NavigationOptions, WheelScheme, canvas_space}; use craft_ui::contract::{Common, Component, Container, ContainerProps, Cx, Mount, Overlay, Props as _, Role, ShowContainer as _}; use craft_ui::style::StyleCx; use craft_ui::testing::{Fixture, pointer, trial}; use craft_ui_test_kit::contract::PlainStyle; -use egui::{Response, Vec2}; +use egui::{Response, TouchPhase, Vec2}; use std::cell::Cell; use std::rc::Rc; @@ -81,3 +81,263 @@ fn the_wheel_over_a_canvas_under_a_modal_moves_nothing() { } } } + +/// A body that claims a wheel gesture (`CanvasSpace::claim_wheel`) reads the rest of it alone: the later shares reach +/// the body, and the view does not move by them. +#[trial] +fn the_rest_of_a_wheel_gesture_the_body_claimed_does_not_move_the_view() { + for eased in [false, true] { + claimed_gesture_keeps_the_view(eased); + } +} + +/// The claimed rest of a gesture of point scroll, or with `eased` of eased wheel lines whose first notch still owes +/// motion when the body claims the gesture. +fn claimed_gesture_keeps_the_view(eased: bool) { + let mut options = NavigationOptions::default(); + options.eased_wheel = eased; + let event = move || if eased { pointer::wheel_lines(-1.0) } else { pointer::wheel(-30.0) }; + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let claims = Rc::new(Cell::new(false)); + let read = Rc::new(Cell::new(0_u32)); + let (shown, claiming, reads) = (Rc::clone(&view), Rc::clone(&claims), Rc::clone(&read)); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && space.wheel().is_some() + { + reads.set(reads.get() + 1); + if claiming.get() { + assert!(space.claim_wheel(ui.ctx(), Vec2::ZERO), "the canvas owns this gesture"); + } + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.settle(); + let at = view.get().rect.center() + Vec2::new(0.0, 150.0); + fixture.frame(vec![pointer::moved(at)]); + let start = view.get(); + fixture.frame(vec![event()]); + fixture.idle(40); + assert!(view.get().center.y > start.center.y + 1.0, "eased {eased}: precondition: an unclaimed share scrolls the canvas"); + + // The first share of the gesture moves the view before the body claims it; an eased notch still owes motion. + claims.set(true); + fixture.frame(vec![event()]); + let claimed = view.get(); + // The motion the claimed notch still owed is dropped, with no more wheel input too. + fixture.idle(5); + let still = view.get(); + assert!((still.center.y - claimed.center.y).abs() < 1e-3, "eased {eased}: owed motion moved the view: {claimed:?} -> {still:?}"); + read.set(0); + for _ in 0..3 { + fixture.frame(vec![event()]); + } + assert_eq!(read.get(), 3, "eased {eased}: the body reads every share of the claimed gesture"); + claims.set(false); + fixture.idle(40); + let after = view.get(); + assert!( + (after.center.y - claimed.center.y).abs() < 1e-3 && after.zoom == claimed.zoom, + "eased {eased}: the view moved: {claimed:?} -> {after:?}" + ); +} + +/// A canvas reports a rejected claim when a nested scroller owns the diagonal gesture. +#[trial] +fn a_canvas_cannot_claim_the_horizontal_share_of_a_nested_scrollers_gesture() { + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let read = Rc::new(Cell::new(0_u32)); + let (shown, reads) = (Rc::clone(&view), Rc::clone(&read)); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).view(given).show(ui, |ui, body| { + let scroller = egui::Id::unique("nested_wheel_scroller"); + let rect = egui::Rect::from_center_size(given.rect.center(), Vec2::splat(200.0)); + craft_ui::testing::wheel::register(ui.ctx(), craft_behavior::WheelTaker::new(scroller, rect).vertical(true).scrolls(true)); + if let Some(space) = canvas_space(&body.env) + && let Some(wheel) = space.wheel() + { + assert!(wheel.scroll.x != 0.0 && wheel.scroll.y == 0.0, "the canvas receives only horizontal motion"); + let vertical = craft_ui::testing::wheel::take_share(ui.ctx(), scroller).expect("the nested scroller receives vertical motion"); + assert!(vertical.scroll.y != 0.0 && vertical.scroll.x == 0.0); + assert!(!space.claim_wheel(ui.ctx(), Vec2::ZERO), "the nested scroller owns the gesture"); + reads.set(reads.get() + 1); + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + let diagonal = || egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: Vec2::new(-20.0, -30.0), + phase: TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Wheel, + }; + fixture.frame(vec![diagonal()]); + let first = view.get(); + fixture.frame(vec![diagonal()]); + assert_eq!(read.get(), 2, "the canvas receives both horizontal shares"); + assert!(view.get().center.x > first.center.x, "a rejected claim leaves later horizontal panning enabled"); +} + +/// A body that first claims the device End stops the canvas glide after the gesture closes. +#[trial] +fn claiming_the_device_end_stops_the_canvas_glide() { + for claim_end in [false, true] { + let mut options = NavigationOptions::default(); + options.touchpad_glide = true; + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let claimed = Rc::new(Cell::new(false)); + let (shown, claims) = (Rc::clone(&view), Rc::clone(&claimed)); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |ui, body| { + if claim_end + && let Some(space) = canvas_space(&body.env) + && space.wheel().is_some_and(|wheel| wheel.phase == craft_behavior::WheelPhase::End) + { + space.claim_wheel(ui.ctx(), Vec2::ZERO); + claims.set(true); + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + let event = |phase, dy| egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: Vec2::new(0.0, dy), + phase, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Trackpad, + }; + fixture.frame(vec![event(TouchPhase::Start, -30.0)]); + for _ in 0..4 { + fixture.frame(vec![event(TouchPhase::Move, -30.0)]); + } + fixture.frame(vec![event(TouchPhase::End, 0.0)]); + assert_eq!(claimed.get(), claim_end, "the body claims only the device End"); + let lifted = view.get(); + fixture.idle(5); + let after = view.get(); + if claim_end { + assert!((after.center.y - lifted.center.y).abs() < 1e-3, "the claimed End left a glide: {lifted:?} -> {after:?}"); + } else { + assert!(after.center.y > lifted.center.y + 1.0, "precondition: the unclaimed End starts a glide"); + } + } +} + +/// A fresh notch and its eased tail move the view after the body claims the previous device End. +#[trial] +fn a_fresh_notch_eases_after_a_claimed_device_end() { + for zoom in [false, true] { + let mut options = NavigationOptions::default(); + options.eased_wheel = true; + options.eased_wheel_zoom = true; + options.touchpad_glide = true; + options.wheel = WheelScheme::Acrobat; + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let shown = Rc::clone(&view); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && space.wheel().is_some_and(|wheel| wheel.phase == craft_behavior::WheelPhase::End) + { + space.claim_wheel(ui.ctx(), Vec2::ZERO); + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + let swipe = |phase, dy| egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: Vec2::new(0.0, dy), + phase, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Trackpad, + }; + fixture.frame(vec![swipe(TouchPhase::Start, -30.0)]); + fixture.frame(vec![swipe(TouchPhase::End, 0.0)]); + let before = view.get(); + fixture.frame(vec![egui::Event::MouseWheel { + unit: if zoom { egui::MouseWheelUnit::Point } else { egui::MouseWheelUnit::Line }, + delta: Vec2::new(0.0, if zoom { -60.0 } else { -1.0 }), + phase: TouchPhase::Move, + modifiers: if zoom { egui::Modifiers::COMMAND } else { egui::Modifiers::NONE }, + source: egui::MouseWheelSource::Wheel, + }]); + let first = view.get(); + fixture.idle(5); + let after = view.get(); + if zoom { + assert!( + first.zoom < before.zoom && after.zoom < first.zoom, + "the fresh zoom notch and its tail move the view: {before:?} -> {first:?} -> {after:?}" + ); + } else { + assert!( + first.center.y > before.center.y && after.center.y > first.center.y, + "the fresh scroll notch and its tail move the view: {before:?} -> {first:?} -> {after:?}" + ); + } + } +} + +/// A partial zoom notch from a claimed gesture does not combine with the next gesture's first half notch. +#[trial] +fn claiming_a_gesture_clears_its_partial_zoom_notch() { + let mut options = NavigationOptions::default(); + options.wheel = WheelScheme::Zoom; + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let claim = Rc::new(Cell::new(true)); + let (shown, claiming) = (Rc::clone(&view), Rc::clone(&claim)); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && space.wheel().is_some() + && claiming.replace(false) + { + space.claim_wheel(ui.ctx(), Vec2::ZERO); + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + let half = || egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: Vec2::new(0.0, 0.5), + phase: TouchPhase::Move, + modifiers: egui::Modifiers::SHIFT, + source: egui::MouseWheelSource::Wheel, + }; + let before = view.get().zoom; + fixture.frame(vec![half()]); + assert!(!claim.get(), "the body claimed the first half notch"); + assert_eq!(view.get().zoom, before, "a half notch does not zoom"); + fixture.frame(vec![egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: Vec2::ZERO, + phase: TouchPhase::End, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Trackpad, + }]); + fixture.frame(vec![half()]); + assert_eq!(view.get().zoom, before, "the new gesture has only half a notch"); + fixture.frame(vec![half()]); + assert!(view.get().zoom > before, "the new gesture's two half notches complete a rung"); +} diff --git a/crates/ui-contract/src/runtime/wheel.rs b/crates/ui-contract/src/runtime/wheel.rs index 97ecae6636..977b844f8d 100644 --- a/crates/ui-contract/src/runtime/wheel.rs +++ b/crates/ui-contract/src/runtime/wheel.rs @@ -37,6 +37,14 @@ pub(crate) struct State { modal: bool, /// The time of the last wheel event a modal held; −∞ before the first. modal_last: f64, + /// The owner's claims on the running gesture, reset when the gesture closes. + claim: Claim, + /// The owner and motion of the running gesture's last share, which a claim in the same pass takes. + last_share: Option<(Id, Vec2, Vec2)>, + /// This pass's claim of the last share, with the motion it spent; it joins `claim` when the next share gathers. + pending: Option<(Vec2, Vec2, Vec2)>, + /// Each registered owner remains here until it reads the cancellation of its claimed motion. + cancellations: IdMap<()>, /// The last gesture the device ended, which a momentum run of the same owner within `GESTURE_GAP` resumes. device_ended: Option, /// The wheel ease each owner holds. @@ -59,6 +67,10 @@ impl Default for State { held: Mods::NONE, modal: false, modal_last: f64::NEG_INFINITY, + claim: Claim::default(), + last_share: None, + pending: None, + cancellations: IdMap::default(), device_ended: None, eases: IdMap::default(), } @@ -75,6 +87,32 @@ struct Ended { moved: bool, held: Mods, modal: bool, + claim: Claim, +} + +/// What the owner of a gesture claimed of it: whether it claimed a share, the claimed shares' scroll and zoom lines, +/// and the motion it said it spent. +#[derive(Clone, Copy, Default)] +struct Claim { + claimed: bool, + gathered: Vec2, + zoom_gathered: Vec2, + spent: Vec2, +} + +impl Claim { + /// Gives `share` the claims made before it. + fn give(self, share: &mut Wheel) { + share.claimed = self.claimed; + share.claimed_gathered = self.gathered; + share.claimed_zoom_gathered = self.zoom_gathered; + share.claimed_spent = self.spent; + } + + /// These claims and one more, of a share of `scroll` and `zoom_lines` that spent `spent`. + fn with(self, scroll: Vec2, zoom_lines: Vec2, spent: Vec2) -> Self { + Claim { claimed: true, gathered: self.gathered + scroll, zoom_gathered: self.zoom_gathered + zoom_lines, spent: self.spent + spent } + } } /// The modifiers held in `a` or in `b`. @@ -95,6 +133,61 @@ pub(crate) fn mark_moved(ctx: &Context, id: Id) { }); } +/// Claims for `id` this pass's share of the wheel gesture it owns, and records `spent`, the part of the claimed motion +/// it used up, in its own unit, returning whether the claim succeeded. The shares that follow in the gesture carry +/// `claimed` and the claimed motion (`Wheel::claimed_gathered`, `claimed_zoom_gathered` and `claimed_spent`); a share +/// the owner does not claim is not counted in them. A second claim in the same pass replaces the first, so a body +/// that runs twice claims once. Without a share for `id` in the running pass, or if `id` does not own the gesture, +/// it returns `false` without changing the claims. +pub fn claim(ctx: &Context, id: Id, spent: Vec2) -> bool { + if !spent.is_finite() { + return false; + } + let Some(running) = crate::runtime::frame::running(ctx) else { return false }; + PerViewport::::with(ctx, running.viewport, |state| { + let Some((owner, scroll, zoom_lines)) = state.last_share else { return false }; + if owner != id { + return false; + } + if state.gesture.owner != Some(id) { + return false; + } + state.pending = Some((scroll, zoom_lines, spent)); + state.cancellations.insert(id, ()); + // The eased wheel's owed motion stops with the claim: the owner's view moves no further by the gesture. + state.eases.remove(&id); + let now = crate::runtime::frame::clock(ctx); + // The swipe the device ended in this pass goes on in its momentum run, which must see the claim too. + let claimed = state.claim.with(scroll, zoom_lines, spent); + if let Some(ended) = state.device_ended.as_mut().filter(|ended| ended.owner == id && ended.at == now) { + ended.claim = claimed; + } + true + }) +} + +/// Returns whether `id` claimed the running gesture or has an unread cancellation from a claim, and consumes that +/// cancellation. A cancellation persists after the gesture closes until the owner reads it or stops registering. +pub fn claimed(ctx: &Context, id: Id) -> bool { + PerViewport::::with(ctx, pass::current_viewport(ctx), |state| { + let canceled = state.cancellations.remove(&id).is_some(); + canceled || (state.gesture.owner == Some(id) && (state.claim.claimed || state.pending.is_some())) + }) +} + +/// Marks the wheel gesture `id` owns as begun or gone on under a modal: an app's own modal window that the wheel +/// service does not see as a modal layer. The gesture's later shares carry `Wheel::modal` until it ends. +pub fn mark_modal(ctx: &Context, id: Id) { + PerViewport::::with(ctx, pass::current_viewport(ctx), |state| { + if state.gesture.owner == Some(id) { + state.modal = true; + } + if let Some(ended) = state.device_ended.as_mut().filter(|ended| ended.owner == id) { + ended.modal = true; + } + }); +} + /// Feeds `pan` to the wheel ease of `id` and returns this pass's eased step. The step is paid by the clock, so a /// later pass of the same frame pays zero. pub(crate) fn ease(ctx: &Context, id: Id, pan: Vec2) -> Vec2 { @@ -142,6 +235,7 @@ impl State { } let last = &self.last; self.eases.retain(|id, _| last.iter().any(|taker| taker.owner == *id)); + self.cancellations.retain(|id, _| last.iter().any(|taker| taker.owner == *id)); let open = self.gesture.last.is_finite(); let ended = self.gesture.end(if pressed { f64::INFINITY } else { now }); if open && !self.gesture.last.is_finite() { @@ -150,6 +244,7 @@ impl State { self.moved = false; self.held = Mods::NONE; self.modal = false; + self.clear_claim(Claim::default()); } ended } @@ -166,9 +261,25 @@ impl State { swipe.map_or((Vec2::ZERO, Vec2::ZERO, false, Mods::NONE), |ended| (ended.gathered, ended.zoom_gathered, ended.moved, ended.held)); // A turn that went on under a modal until just now goes on under it after the modal closes. self.modal = swipe.is_some_and(|ended| ended.modal) || now - self.modal_last < GESTURE_GAP; + self.clear_claim(swipe.map_or(Claim::default(), |ended| ended.claim)); swipe.map(|ended| ended.owner) } + /// Starts the running gesture's claims at `claim`, with no claim pending. + fn clear_claim(&mut self, claim: Claim) { + self.claim = claim; + self.last_share = None; + self.pending = None; + } + + /// Adds this pass's claim, if any, to the running gesture's claims. + fn settle_claim(&mut self) { + if let Some((scroll, zoom_lines, spent)) = self.pending.take() { + self.claim = self.claim.with(scroll, zoom_lines, spent); + } + self.last_share = None; + } + /// Adds `share`, in its owner's points, to the gesture it belongs to and gives it the gesture's gathered scroll, /// mark and held modifiers; a share of another owner than the gesture's gathers only itself. Every share carries /// whether the gesture went on under a modal. A point share cancels its owner's @@ -181,6 +292,8 @@ impl State { } share.modal = self.modal; if self.gesture.owner == Some(owner) { + self.claim.give(share); + self.last_share.get_or_insert((owner, share.scroll, share.zoom_lines)); self.gathered += share.scroll; self.zoom_gathered += share.zoom_lines; share.gathered = self.gathered; @@ -290,6 +403,8 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { state.last = std::mem::take(&mut state.this); state.last_layers = std::mem::take(&mut state.this_layers); state.shares.clear(); + // Last pass's claim joins the gesture's; a claim in this pass takes only a share of this pass. + state.settle_claim(); if let Some(winner) = pressed_on { state.armed = winner.filter(|id| state.last.iter().any(|taker| taker.gated && taker.owner == *id)); } @@ -312,6 +427,7 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { let held_before = if closing_press { either(state.held, press_mods) } else { state.held }; // A wheel a modal held in the pass before that press arrived during the gesture too. let modal_before = state.modal || (closing_press && wheel_before_press && (blocked || modal_family.is_some())); + let claim_before = state.claim; let ended = state.close_gesture(pressed_on.is_some(), now); let ended = ended.filter(|owner| state.last.iter().any(|taker| taker.owner == *owner && taker.value)); // A key tapped between the running gesture's wheel events counts as held for the rest of it, and one tapped @@ -331,6 +447,7 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { // The end carries the metadata of the gesture it ends. let mut end = Wheel::new(Vec2::ZERO, mods, WheelUnit::Point, WheelPhase::End); (end.held, end.modal) = (held_before, modal_before); + claim_before.give(&mut end); state.shares.push((owner, end)); } if let (Some(frame), Some(at)) = (&frame, hover) @@ -384,12 +501,17 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { }) }) .collect(); - let (previous_owner, held, modal) = (state.gesture.owner, state.held, state.modal); + let (previous_owner, held, modal, claimed) = (state.gesture.owner, state.held, state.modal, state.claim); let shares = split(&eligible, at, share, focus, state.armed, &mut state.gesture, now); // A momentum run resumes its swipe only on the swipe's owner; any split drops the ended swipe. if swipe.is_some() && state.gesture.owner != swipe { (state.gathered, state.zoom_gathered, state.moved, state.held) = (Vec2::ZERO, Vec2::ZERO, false, Mods::NONE); state.modal = now - state.modal_last < GESTURE_GAP; + state.clear_claim(Claim::default()); + } + // A running gesture the split hands to another owner starts its claims again: the new owner claimed none. + if previous_owner.is_some() && state.gesture.owner != previous_owner { + state.clear_claim(Claim::default()); } state.held = either(state.held, either(mods, held_mods)); state.device_ended = None; @@ -405,12 +527,15 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { state.gather(owner, &mut share); if share.phase == WheelPhase::End && Some(owner) == previous_owner && state.gesture.owner != previous_owner { (share.held, share.modal) = (held, modal); + claimed.give(&mut share); } state.shares.push((owner, share)); } if device_end { - let (gathered, zoom_gathered, moved, held, modal) = (state.gathered, state.zoom_gathered, state.moved, state.held, state.modal); - state.device_ended = state.gesture.owner.map(|owner| Ended { owner, at: now, gathered, zoom_gathered, moved, held, modal }); + let (gathered, zoom_gathered, moved, held, modal, claim) = + (state.gathered, state.zoom_gathered, state.moved, state.held, state.modal, state.claim); + state.device_ended = + state.gesture.owner.map(|owner| Ended { owner, at: now, gathered, zoom_gathered, moved, held, modal, claim }); } } } diff --git a/crates/ui-contract/tests/it/runtime/wheel.rs b/crates/ui-contract/tests/it/runtime/wheel.rs index aa33841af6..e3d58cd778 100644 --- a/crates/ui-contract/tests/it/runtime/wheel.rs +++ b/crates/ui-contract/tests/it/runtime/wheel.rs @@ -558,6 +558,108 @@ fn a_wheel_gesture_carries_the_keys_held_during_it_and_whether_it_began_under_a_ assert!(!fresh.modal, "a turn begun after the gap: {fresh:?}"); } +#[trial] +fn a_wheel_gesture_counts_only_the_shares_its_owner_claimed_and_an_app_modal_marks_it() { + let canvas = Id::unique("claim_canvas"); + let rect = Rect::from_min_size(Pos2::ZERO, Vec2::splat(400.0)); + // What the body does with this pass's share: claim it with this much spent, and mark the turn modal. + let claim: Cell> = Cell::new(None); + let modal = Cell::new(false); + let last: Cell> = Cell::new(None); + let mut show_frame = |ui: &mut Ui| { + register(ui.ctx(), WheelTaker::new(canvas, rect).vertical(true).scrolls(true)); + if let Some(share) = take_share(ui.ctx(), canvas) { + last.set(Some(share)); + for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + for spent in [Vec2::new(invalid, 0.0), Vec2::new(0.0, invalid)] { + assert!(!craft_ui::runtime::wheel::claim(ui.ctx(), canvas, spent), "a claim of {spent:?} is refused"); + } + } + if let Some(spent) = claim.get() { + // A body that runs twice in a pass claims once. + assert!(craft_ui::runtime::wheel::claim(ui.ctx(), canvas, spent)); + assert!(craft_ui::runtime::wheel::claim(ui.ctx(), canvas, spent)); + } + if modal.get() { + craft_ui::runtime::wheel::mark_modal(ui.ctx(), canvas); + } + } + }; + let mut frames = Frames::new(); + frames.idle(2, &mut show_frame); + frames.frame(vec![pointer::moved(Pos2::new(200.0, 200.0))], &mut show_frame); + let turn = |frames: &mut Frames, show_frame: &mut dyn FnMut(&mut Ui), take: Option| { + claim.set(take); + last.set(None); + frames.frame(vec![pointer::wheel(-30.0)], &mut *show_frame); + last.take().expect("the canvas takes the wheel") + }; + + // The first share is not claimed: the claims count nothing of it. + let first = turn(&mut frames, &mut show_frame, None); + assert!(!first.claimed && first.claimed_gathered == Vec2::ZERO, "nothing claimed yet: {first:?}"); + assert!(!craft_ui::runtime::wheel::claim(&frames.ctx, canvas, Vec2::new(0.0, 10.0)), "a share cannot be claimed between passes"); + assert!(!craft_ui::runtime::wheel::claimed(&frames.ctx, canvas), "a rejected claim does not cancel navigation"); + let second = turn(&mut frames, &mut show_frame, Some(Vec2::new(0.0, 1.0))); + assert!(!second.claimed && second.claimed_gathered == Vec2::ZERO, "the first share was left unclaimed: {second:?}"); + assert!(!craft_ui::runtime::wheel::claim(&frames.ctx, canvas, Vec2::new(0.0, 10.0)), "a late claim cannot replace the body's spent motion"); + let third = turn(&mut frames, &mut show_frame, Some(Vec2::new(0.0, -1.0))); + assert!(third.claimed, "the second share was claimed: {third:?}"); + assert_eq!((third.claimed_gathered, third.claimed_spent), (second.scroll, Vec2::new(0.0, 1.0)), "one claim of the second share: {third:?}"); + assert_eq!(third.gathered, first.scroll + second.scroll + third.scroll, "the gesture still gathers every share: {third:?}"); + let fourth = turn(&mut frames, &mut show_frame, None); + assert_eq!((fourth.claimed_gathered, fourth.claimed_spent), (second.scroll + third.scroll, Vec2::ZERO), "{fourth:?}"); + + // An app's own modal marks the rest of the turn, and a new turn starts with no claims and no mark. + modal.set(true); + let marked = turn(&mut frames, &mut show_frame, None); + assert!(!marked.modal, "the mark comes after the share: {marked:?}"); + modal.set(false); + let after = turn(&mut frames, &mut show_frame, None); + assert!(after.modal && after.claimed, "the rest of the turn is marked: {after:?}"); + frames.advance(GESTURE_GAP); + frames.idle(2, &mut show_frame); + let fresh = turn(&mut frames, &mut show_frame, None); + assert!(!fresh.modal && !fresh.claimed && fresh.claimed_gathered == Vec2::ZERO && fresh.claimed_spent == Vec2::ZERO, "{fresh:?}"); +} + +/// An unread cancellation survives gesture close while its owner registers and is released when that owner leaves. +#[trial] +fn unread_claim_cancellations_follow_registered_owners() { + for discarded in [false, true] { + let canvas = Id::unique("discarded_claim_canvas"); + let rect = Rect::from_min_size(Pos2::ZERO, Vec2::splat(400.0)); + let registered = Cell::new(true); + let consume = Cell::new(false); + let claimed = Cell::new(false); + let canceled = Cell::new(None); + let mut show_frame = |ui: &mut Ui| { + if registered.get() { + register(ui.ctx(), WheelTaker::new(canvas, rect).vertical(true).scrolls(true)); + if take_share(ui.ctx(), canvas).is_some() { + craft_ui::runtime::wheel::claim(ui.ctx(), canvas, Vec2::ZERO); + claimed.set(true); + } + if consume.take() { + canceled.set(Some(craft_ui::runtime::wheel::claimed(ui.ctx(), canvas))); + } + } + }; + let mut frames = Frames::new(); + frames.idle(2, &mut show_frame); + frames.frame(vec![pointer::moved(rect.center())], &mut show_frame); + frames.frame(vec![pointer::wheel(-30.0)], &mut show_frame); + assert!(claimed.get(), "the owner claimed its share"); + frames.advance(GESTURE_GAP); + registered.set(!discarded); + frames.idle(2, &mut show_frame); + registered.set(true); + consume.set(true); + frames.frame(Vec::new(), &mut show_frame); + assert_eq!(canceled.get(), Some(!discarded), "discarded {discarded}: only a registered owner retains its cancellation"); + } +} + #[trial] fn the_end_share_of_a_pressed_wheel_gesture_carries_a_key_tapped_before_the_press_in_its_pass() { let slider = Id::unique("press_held_slider"); diff --git a/docs/contract-api.md b/docs/contract-api.md index 8d3f7b3c92..30cdc1d570 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -1842,7 +1842,7 @@ The value core of chapter 10: the bound every value type meets, `Mixed`, edit ev Wheel gesture values, as craft-behavior's copy of egui's types so the wheel split is egui-free. - `craft_behavior::wheel::GESTURE_GAP`: `pub const GESTURE_GAP: f64`. The seconds between wheel events that still belong to one gesture. -- `craft_behavior::wheel::Wheel`: `pub struct Wheel { pub scroll: Vec2, pub lines: Vec2, pub zoom: f32, pub zoom_lines: Vec2, pub zoom_gathered: Vec2, pub mods: Mods, pub unit: WheelUnit, pub phase: WheelPhase, pub source: WheelSource, pub at: Option, pub zooms: bool, pub touch_zoom: f32, pub rotation: f32, pub touch_rotation: f32, pub touch_pan: Vec2, pub gathered: Vec2, pub moved: bool, pub held: Mods, pub modal: bool }`. One wheel event, or the sum of one pass's, as a taker reads it with `take_wheel`. +- `craft_behavior::wheel::Wheel`: `pub struct Wheel { pub scroll: Vec2, pub lines: Vec2, pub zoom: f32, pub zoom_lines: Vec2, pub zoom_gathered: Vec2, pub mods: Mods, pub unit: WheelUnit, pub phase: WheelPhase, pub source: WheelSource, pub at: Option, pub zooms: bool, pub touch_zoom: f32, pub rotation: f32, pub touch_rotation: f32, pub touch_pan: Vec2, pub gathered: Vec2, pub moved: bool, pub held: Mods, pub modal: bool, pub claimed: bool, pub claimed_gathered: Vec2, pub claimed_zoom_gathered: Vec2, pub claimed_spent: Vec2 }`. One wheel event, or the sum of one pass's, as a taker reads it with `take_wheel`. - `pub const fn new(scroll: Vec2, mods: Mods, unit: WheelUnit, phase: WheelPhase) -> Self`. A scroll of `scroll` points with no zoom. - `pub const fn zoom(mut self, zoom: f32) -> Self`. The same gesture with zoom factor `zoom`. - `pub const fn zoom_lines(mut self, lines: Vec2) -> Self`. The same gesture with `lines` wheel lines of motion that zoom (`Wheel::zoom_lines`). @@ -4604,6 +4604,14 @@ The toast queues: one per window (`WindowKey`), filled from any code with a `Con - `craft_ui::runtime::toast::shown`: `pub fn shown(ctx: &Context, id: ToastId, text: &str, held: bool)`. The host shows `id` in this pass; `held` says the pointer or focus is on it. - `craft_ui::runtime::toast::snapshot`: `pub fn snapshot(ctx: &Context) -> Vec<(WindowKey, Card)>`. Every live viewport's cards with their windows, oldest first, for `ui.inspect`; `cards` is the running viewport's. +## `craft_ui::runtime::wheel` + +The wheel service (8.6): takers register their view rects, the begin hook splits the pass's wheel input among them from last pass's registrations, and each taker reads its share once. + +- `craft_ui::runtime::wheel::claim`: `pub fn claim(ctx: &Context, id: Id, spent: Vec2) -> bool`. Claims for `id` this pass's share of the wheel gesture it owns, and records `spent`, the part of the claimed motion it used up, in its own unit, returning whether the claim succeeded. +- `craft_ui::runtime::wheel::claimed`: `pub fn claimed(ctx: &Context, id: Id) -> bool`. Returns whether `id` claimed the running gesture or has an unread cancellation from a claim, and consumes that cancellation. +- `craft_ui::runtime::wheel::mark_modal`: `pub fn mark_modal(ctx: &Context, id: Id)`. Marks the wheel gesture `id` owns as begun or gone on under a modal: an app's own modal window that the wheel service does not see as a modal layer. + ## `craft_ui::runtime::windows` `WindowHost`: the one multi-window driver. From 3de017b999596464f6d98907b88bde7e5af287ef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 17:26:08 -0800 Subject: [PATCH 24/31] ui: a wheel claim names its share, and a claimed swipe leaves no glide samples CanvasSpace keeps a ClaimToken with its wheel share, and claim_wheel passes it to craft_ui::runtime::wheel::claim, which refuses a token other than that of the share it would claim. A CanvasSpace kept from an earlier pass, or from a viewport that was closed and opened again under the same id, can no longer claim a later share. Tokens never repeat in the process. TouchpadGlide::stop also clears the lift samples, so the next swipe cannot glide on the motion of a claimed swipe whose device end the canvas did not read. --- crates/ui-canvas/src/canvas/mod.rs | 6 +- crates/ui-canvas/src/canvas/navigate/mod.rs | 26 ++- crates/ui-canvas/src/canvas/space.rs | 17 +- .../ui-canvas/tests/it/canvas/modal_wheel.rs | 198 +++++++++++++++++- crates/ui-contract/src/runtime/wheel.rs | 31 ++- crates/ui-contract/tests/it/runtime/wheel.rs | 22 +- docs/contract-api.md | 5 +- 7 files changed, 278 insertions(+), 27 deletions(-) diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index 158ac49524..3ee72c7cf9 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -305,6 +305,7 @@ struct Settled { keys: BodyKeys, /// The wheel share the canvas took this pass, handed on to its body. wheel: Option, + wheel_token: Option, /// A middle-button autoscroll or a held middle pan runs. auto_scrolling: bool, /// The mark of a running middle-button autoscroll, in screen points. @@ -626,7 +627,8 @@ impl<'a> Canvas<'a> { let easing = motion.animation.running(); let mark = motion.autoscroll.mark(); motion.restore(&ctx, id); - Settled { target, shown, easing, keys, wheel, auto_scrolling, mark, swallowing, zoom_anchor } + let wheel_token = crate::runtime::wheel::claim_token(&ctx, id); + Settled { target, shown, easing, keys, wheel, wheel_token, auto_scrolling, mark, swallowing, zoom_anchor } } /// One pass's wheel on `view`: a pan the eased wheel pays out later, or a pan, zoom or turn applied now, and the @@ -785,7 +787,7 @@ impl<'a> Canvas<'a> { .with_background(background) .with_precise(self.precise_cursors != caps_lock) .with_zoom_scheme(scheme) - .with_wheel(wheel) + .with_wheel(wheel, self.settled.and_then(|settled| settled.wheel_token)) .with_canvas(id); Some(match self.picture { Some(slot) => space.with_picture(slot), diff --git a/crates/ui-canvas/src/canvas/navigate/mod.rs b/crates/ui-canvas/src/canvas/navigate/mod.rs index de5a82eec4..1cafcaa914 100644 --- a/crates/ui-canvas/src/canvas/navigate/mod.rs +++ b/crates/ui-canvas/src/canvas/navigate/mod.rs @@ -163,6 +163,7 @@ impl TouchpadGlide { /// Stops a glide (the view hit a limit, a press, a key move, a zoom, a view command). pub(crate) fn stop(&mut self) { + self.samples.clear(); self.velocity = Vec2::ZERO; } @@ -204,7 +205,7 @@ impl TouchpadGlide { /// Reads the pass's wheel share at `now`; any wheel input stops a glide, a touchpad gesture's end may start one. /// `glide` is false where the view must not glide this pass (Touchpad Glide off, a zoom, a dialog). pub(crate) fn read(&mut self, wheel: &Wheel, now: f64, glide: bool) { - self.stop(); + self.velocity = Vec2::ZERO; // Zooming, a mouse wheel and sideways Shift scrolling never glide. if wheel.unit != WheelUnit::Point || wheel.mods.cmd || wheel.mods.ctrl || wheel.mods.shift || wheel.zoom != 1.0 { self.samples.clear(); @@ -326,3 +327,26 @@ fn document_bounds(view: &CanvasView, size: Size) -> Option { let bounds = quad.iter().skip(1).fold(Rect::from_min_max(quad[0], quad[0]), |r, &p| r.union(Rect::from_min_max(p, p))); (bounds.is_finite() && view.rect.is_finite()).then_some(bounds) } + +#[cfg(feature = "suite")] +pub(crate) mod trials { + use super::TouchpadGlide; + use crate::testing::trial; + use egui::Vec2; + + #[trial] + fn stopping_a_touchpad_glide_clears_its_lift_samples() { + let mut glide = TouchpadGlide::default(); + glide.push(0.0, Vec2::new(0.0, -30.0)); + glide.push(0.01, Vec2::new(0.0, -30.0)); + assert_ne!(glide.lift_velocity(0.02), Vec2::ZERO); + glide.velocity = glide.lift_velocity(0.02); + + glide.stop(); + + assert!(!glide.gliding()); + assert!(glide.samples.is_empty()); + glide.push(0.03, Vec2::new(0.0, -1.0)); + assert_eq!(glide.lift_velocity(0.04), Vec2::ZERO); + } +} diff --git a/crates/ui-canvas/src/canvas/space.rs b/crates/ui-canvas/src/canvas/space.rs index e0349c07c3..9083d5ce35 100644 --- a/crates/ui-canvas/src/canvas/space.rs +++ b/crates/ui-canvas/src/canvas/space.rs @@ -42,7 +42,7 @@ pub struct CanvasSpace { /// The canvas's picture slot for this pass, which [`paint_picture`](Self::paint_picture) appends to; `None` in a /// measuring pass. picture: Option, - wheel: Option, + wheel: Option<(craft_behavior::Wheel, Option)>, zoom_anchor: Option, } @@ -73,13 +73,13 @@ impl CanvasSpace { /// The wheel share the canvas read this pass, for a body that pages by wheel to read once. pub fn wheel(&self) -> Option { - self.wheel + self.wheel.map(|(wheel, _)| wheel) } - /// This space with the wheel share the canvas read this pass. + /// This space with the wheel share the canvas read and its claim token. #[must_use] - pub fn with_wheel(mut self, wheel: Option) -> Self { - self.wheel = wheel; + pub fn with_wheel(mut self, wheel: Option, token: Option) -> Self { + self.wheel = wheel.map(|wheel| (wheel, token)); self } @@ -304,10 +304,11 @@ impl CanvasSpace { /// `claimed_zoom_gathered` and `claimed_spent`, so a body that turns a gesture into steps keeps no state of its /// own. A second claim in the same pass replaces the first. /// The canvas must own the gesture and have a share in the running pass. A share returned by `wheel` can belong - /// to a gesture another scroller owns; that share cannot be claimed. The body should act only on an accepted claim. + /// to a gesture another scroller owns; that share cannot be claimed. A snapshot from another share cannot claim the + /// running pass's share, including after a viewport is recreated. The body should act only on an accepted claim. pub fn claim_wheel(&self, ctx: &egui::Context, spent: Vec2) -> bool { - if let (Some(canvas), Some(_)) = (self.canvas, self.wheel) { - return crate::runtime::wheel::claim(ctx, canvas, spent); + if let (Some(canvas), Some((_, Some(token)))) = (self.canvas, self.wheel) { + return crate::runtime::wheel::claim(ctx, canvas, token, spent); } false } diff --git a/crates/ui-canvas/tests/it/canvas/modal_wheel.rs b/crates/ui-canvas/tests/it/canvas/modal_wheel.rs index d063e3ae36..e56bdf7ddb 100644 --- a/crates/ui-canvas/tests/it/canvas/modal_wheel.rs +++ b/crates/ui-canvas/tests/it/canvas/modal_wheel.rs @@ -2,10 +2,10 @@ use craft_behavior::CanvasView; use craft_behavior::kurbo::{Point, Size}; -use craft_ui::canvas::{Canvas, NavigationOptions, WheelScheme, canvas_space}; +use craft_ui::canvas::{Canvas, CanvasSpace, NavigationOptions, WheelScheme, canvas_space}; use craft_ui::contract::{Common, Component, Container, ContainerProps, Cx, Mount, Overlay, Props as _, Role, ShowContainer as _}; use craft_ui::style::StyleCx; -use craft_ui::testing::{Fixture, pointer, trial}; +use craft_ui::testing::{Fixture, Frames, pointer, trial}; use craft_ui_test_kit::contract::PlainStyle; use egui::{Response, TouchPhase, Vec2}; use std::cell::Cell; @@ -341,3 +341,197 @@ fn claiming_a_gesture_clears_its_partial_zoom_notch() { fixture.frame(vec![half()]); assert!(view.get().zoom > before, "the new gesture's two half notches complete a rung"); } + +#[trial] +fn a_claimed_swipes_samples_do_not_glide_after_a_coalesced_start() { + let mut options = NavigationOptions::default(); + options.touchpad_glide = true; + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let claim = Rc::new(Cell::new(false)); + let last = Rc::new(Cell::new(None)); + let (shown, claiming, shares) = (Rc::clone(&view), Rc::clone(&claim), Rc::clone(&last)); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && let Some(wheel) = space.wheel() + { + shares.set(Some(wheel)); + if claiming.get() { + assert!(space.claim_wheel(ui.ctx(), Vec2::ZERO)); + } + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + let event = |phase, dy| egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: Vec2::new(0.0, dy), + phase, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Trackpad, + }; + fixture.frame(vec![event(TouchPhase::Start, -30.0)]); + claim.set(true); + fixture.frame(vec![event(TouchPhase::Move, -30.0)]); + fixture.frame(vec![event(TouchPhase::End, 0.0)]); + assert!(last.get().expect("the claimed End").claimed); + + claim.set(false); + fixture.frame(vec![event(TouchPhase::Move, -1.0)]); + let fresh = last.get().expect("the next swipe's Move"); + assert_eq!(fresh.phase, craft_behavior::WheelPhase::Move); + assert!(!fresh.claimed); + fixture.frame(vec![event(TouchPhase::End, 0.0)]); + let lifted = view.get(); + fixture.idle(5); + assert_eq!(view.get().center, lifted.center, "one small sample cannot start a glide"); +} + +#[trial] +fn a_stale_canvas_space_cannot_claim_a_wheel_share_in_a_later_pass() { + claim_from_retained_space(false); +} + +#[trial] +fn a_fresh_canvas_space_can_claim_after_a_stale_claim_is_refused() { + claim_from_retained_space(true); +} + +#[trial] +fn a_retained_canvas_space_cannot_claim_a_recreated_viewports_share_with_the_same_pass_number() { + for claim_fresh in [false, true] { + let viewport = egui::ViewportId::from_hash_of("canvas window"); + let retained: Cell> = Cell::new(None); + let issued = Cell::new(None); + let owner = egui::Id::unique("moving canvas"); + let recreated = Cell::new(false); + let attempts = Cell::new(0); + let last = Cell::new(None); + let view = Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0)); + let mut show = |ui: &mut egui::Ui| { + let mut given = view.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").id(owner).document(Size::new(4000.0, 4000.0)).view(given).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && let Some(wheel) = space.wheel() + { + last.set(Some(wheel)); + let pass = craft_ui::runtime::frame::running(ui.ctx()).expect("a running pass"); + if !recreated.get() { + retained.set(Some(space)); + issued.set(Some(pass.pass_nr)); + } else if attempts.get() == 0 { + assert_eq!(pass.viewport, viewport, "the recreated viewport has the same ID"); + assert_eq!(Some(pass.pass_nr), issued.get(), "the recreated viewport has the same pass counter"); + assert!(!retained.get().expect("the earlier snapshot").claim_wheel(ui.ctx(), Vec2::new(0.0, -30.0))); + assert!(!craft_ui::runtime::wheel::claimed(ui.ctx(), owner), "the rejected claim leaves the new share unclaimed"); + if claim_fresh { + assert!(space.claim_wheel(ui.ctx(), Vec2::ZERO)); + } + attempts.set(attempts.get() + 1); + } + } + }); + view.set(canvas.output.view.unwrap_or(given)); + }; + let mut frames = Frames::new(); + for reopen in [false, true] { + if reopen { + frames.close_viewport(viewport); + frames.frame(Vec::new(), |_| {}); + recreated.set(true); + } + frames.frame_in_viewport(viewport, Vec::new(), &mut show); + frames.frame_in_viewport(viewport, Vec::new(), &mut show); + frames.frame_in_viewport(viewport, vec![pointer::moved(view.get().rect.center())], &mut show); + frames.frame_in_viewport(viewport, vec![pointer::wheel_lines(-1.0)], &mut show); + } + assert_eq!(attempts.get(), 1); + last.set(None); + frames.frame_in_viewport(viewport, vec![pointer::wheel(-30.0)], &mut show); + let next = last.get().expect("the share after the claim attempt"); + assert_eq!(next.claimed, claim_fresh); + if !claim_fresh { + assert_eq!(next.claimed_gathered, Vec2::ZERO, "the rejected claim records no claimed motion"); + } + assert_eq!(next.claimed_spent, Vec2::ZERO, "the rejected claim records no spent motion"); + } +} + +fn claim_from_retained_space(claim_fresh: bool) { + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let retained: Rc>> = Rc::new(Cell::new(None)); + let later = Rc::new(Cell::new(false)); + let read = Rc::new(Cell::new(None)); + let attempts = Rc::new(Cell::new(0)); + let (shown, saved, claiming, shares, claims) = + (Rc::clone(&view), Rc::clone(&retained), Rc::clone(&later), Rc::clone(&read), Rc::clone(&attempts)); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).view(given).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && let Some(wheel) = space.wheel() + { + shares.set(Some(wheel)); + if claiming.get() { + assert!(!saved.get().expect("the earlier snapshot").claim_wheel(ui.ctx(), Vec2::ZERO)); + if claim_fresh { + assert!(space.claim_wheel(ui.ctx(), Vec2::ZERO)); + } + claims.set(claims.get() + 1); + } + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + if !claiming.get() && canvas.output.space.is_some_and(|space| space.wheel().is_some()) { + saved.set(canvas.output.space); + } + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + fixture.frame(vec![pointer::wheel(-30.0)]); + assert!(retained.get().is_some()); + later.set(true); + fixture.frame(vec![pointer::wheel(-30.0)]); + assert_eq!(attempts.get(), 1); + later.set(false); + fixture.frame(vec![pointer::wheel(-30.0)]); + let next = read.get().expect("the share after the claim attempt"); + assert_eq!(next.claimed, claim_fresh); + if claim_fresh { + assert_eq!(next.claimed_gathered, next.scroll, "only the fresh snapshot's share was claimed"); + } else { + assert_eq!(next.claimed_gathered, Vec2::ZERO, "the stale snapshot left the new share unclaimed"); + } +} + +#[trial] +fn a_small_reversal_of_a_claimed_gesture_keeps_the_step_count() { + let steps = Rc::new(Cell::new(0.0)); + let count = Rc::clone(&steps); + let mut fixture = Fixture::new(move |ui| { + let view = CanvasView::new(ui.available_rect_before_wrap(), Point::new(2000.0, 2000.0), 1.0); + Canvas::new("Document").document(Size::new(4000.0, 4000.0)).view(view).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && let Some(wheel) = space.wheel() + { + let remaining = wheel.claimed_gathered.y + wheel.scroll.y - wheel.claimed_spent.y; + let steps = (remaining / 30.0).trunc(); + if space.claim_wheel(ui.ctx(), Vec2::new(0.0, steps * 30.0)) { + count.set(count.get() + steps); + } + } + }); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(egui::Pos2::new(200.0, 200.0))]); + fixture.frame(vec![pointer::wheel(-30.0)]); + assert_eq!(steps.get(), -1.0, "the first share takes one step"); + fixture.frame(vec![pointer::wheel(5.0)]); + assert_eq!(steps.get(), -1.0, "a reversal smaller than one step leaves the count unchanged"); +} diff --git a/crates/ui-contract/src/runtime/wheel.rs b/crates/ui-contract/src/runtime/wheel.rs index 977b844f8d..966a989138 100644 --- a/crates/ui-contract/src/runtime/wheel.rs +++ b/crates/ui-contract/src/runtime/wheel.rs @@ -13,6 +13,13 @@ use craft_behavior::{ }; use craft_keymap::Mods; use egui::{Context, Id, IdMap, Pos2, Vec2}; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// The process-unique identity of a wheel share that can be claimed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ClaimToken(u64); + +static NEXT_CLAIM_TOKEN: AtomicU64 = AtomicU64::new(0); pub(crate) struct State { this: Vec>, @@ -39,8 +46,8 @@ pub(crate) struct State { modal_last: f64, /// The owner's claims on the running gesture, reset when the gesture closes. claim: Claim, - /// The owner and motion of the running gesture's last share, which a claim in the same pass takes. - last_share: Option<(Id, Vec2, Vec2)>, + /// The owner, token and motion of the running gesture's last share, which a claim in the same pass takes. + last_share: Option<(Id, ClaimToken, Vec2, Vec2)>, /// This pass's claim of the last share, with the motion it spent; it joins `claim` when the next share gathers. pending: Option<(Vec2, Vec2, Vec2)>, /// Each registered owner remains here until it reads the cancellation of its claimed motion. @@ -133,20 +140,26 @@ pub(crate) fn mark_moved(ctx: &Context, id: Id) { }); } +/// The token for the share `id` can claim in the running pass, including after it reads the share. +pub fn claim_token(ctx: &Context, id: Id) -> Option { + let running = crate::runtime::frame::running(ctx)?; + PerViewport::::with(ctx, running.viewport, |state| state.last_share.filter(|(owner, _, _, _)| *owner == id).map(|share| share.1)) +} + /// Claims for `id` this pass's share of the wheel gesture it owns, and records `spent`, the part of the claimed motion /// it used up, in its own unit, returning whether the claim succeeded. The shares that follow in the gesture carry /// `claimed` and the claimed motion (`Wheel::claimed_gathered`, `claimed_zoom_gathered` and `claimed_spent`); a share /// the owner does not claim is not counted in them. A second claim in the same pass replaces the first, so a body /// that runs twice claims once. Without a share for `id` in the running pass, or if `id` does not own the gesture, -/// it returns `false` without changing the claims. -pub fn claim(ctx: &Context, id: Id, spent: Vec2) -> bool { +/// it returns `false` without changing the claims. `token` must identify the share being claimed. +pub fn claim(ctx: &Context, id: Id, token: ClaimToken, spent: Vec2) -> bool { if !spent.is_finite() { return false; } let Some(running) = crate::runtime::frame::running(ctx) else { return false }; PerViewport::::with(ctx, running.viewport, |state| { - let Some((owner, scroll, zoom_lines)) = state.last_share else { return false }; - if owner != id { + let Some((owner, shared_token, scroll, zoom_lines)) = state.last_share else { return false }; + if owner != id || shared_token != token { return false; } if state.gesture.owner != Some(id) { @@ -293,7 +306,11 @@ impl State { share.modal = self.modal; if self.gesture.owner == Some(owner) { self.claim.give(share); - self.last_share.get_or_insert((owner, share.scroll, share.zoom_lines)); + if self.last_share.is_none() + && let Ok(token) = NEXT_CLAIM_TOKEN.try_update(Ordering::Relaxed, Ordering::Relaxed, |next| next.checked_add(1)) + { + self.last_share = Some((owner, ClaimToken(token), share.scroll, share.zoom_lines)); + } self.gathered += share.scroll; self.zoom_gathered += share.zoom_lines; share.gathered = self.gathered; diff --git a/crates/ui-contract/tests/it/runtime/wheel.rs b/crates/ui-contract/tests/it/runtime/wheel.rs index e3d58cd778..c5de7bda0c 100644 --- a/crates/ui-contract/tests/it/runtime/wheel.rs +++ b/crates/ui-contract/tests/it/runtime/wheel.rs @@ -566,19 +566,22 @@ fn a_wheel_gesture_counts_only_the_shares_its_owner_claimed_and_an_app_modal_mar let claim: Cell> = Cell::new(None); let modal = Cell::new(false); let last: Cell> = Cell::new(None); + let last_token = Cell::new(None); let mut show_frame = |ui: &mut Ui| { register(ui.ctx(), WheelTaker::new(canvas, rect).vertical(true).scrolls(true)); if let Some(share) = take_share(ui.ctx(), canvas) { last.set(Some(share)); + let token = craft_ui::runtime::wheel::claim_token(ui.ctx(), canvas).expect("a claimable share"); + last_token.set(Some(token)); for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { for spent in [Vec2::new(invalid, 0.0), Vec2::new(0.0, invalid)] { - assert!(!craft_ui::runtime::wheel::claim(ui.ctx(), canvas, spent), "a claim of {spent:?} is refused"); + assert!(!craft_ui::runtime::wheel::claim(ui.ctx(), canvas, token, spent), "a claim of {spent:?} is refused"); } } if let Some(spent) = claim.get() { // A body that runs twice in a pass claims once. - assert!(craft_ui::runtime::wheel::claim(ui.ctx(), canvas, spent)); - assert!(craft_ui::runtime::wheel::claim(ui.ctx(), canvas, spent)); + assert!(craft_ui::runtime::wheel::claim(ui.ctx(), canvas, token, spent)); + assert!(craft_ui::runtime::wheel::claim(ui.ctx(), canvas, token, spent)); } if modal.get() { craft_ui::runtime::wheel::mark_modal(ui.ctx(), canvas); @@ -598,11 +601,17 @@ fn a_wheel_gesture_counts_only_the_shares_its_owner_claimed_and_an_app_modal_mar // The first share is not claimed: the claims count nothing of it. let first = turn(&mut frames, &mut show_frame, None); assert!(!first.claimed && first.claimed_gathered == Vec2::ZERO, "nothing claimed yet: {first:?}"); - assert!(!craft_ui::runtime::wheel::claim(&frames.ctx, canvas, Vec2::new(0.0, 10.0)), "a share cannot be claimed between passes"); + assert!( + !craft_ui::runtime::wheel::claim(&frames.ctx, canvas, last_token.get().expect("the last share's token"), Vec2::new(0.0, 10.0)), + "a share cannot be claimed between passes" + ); assert!(!craft_ui::runtime::wheel::claimed(&frames.ctx, canvas), "a rejected claim does not cancel navigation"); let second = turn(&mut frames, &mut show_frame, Some(Vec2::new(0.0, 1.0))); assert!(!second.claimed && second.claimed_gathered == Vec2::ZERO, "the first share was left unclaimed: {second:?}"); - assert!(!craft_ui::runtime::wheel::claim(&frames.ctx, canvas, Vec2::new(0.0, 10.0)), "a late claim cannot replace the body's spent motion"); + assert!( + !craft_ui::runtime::wheel::claim(&frames.ctx, canvas, last_token.get().expect("the last share's token"), Vec2::new(0.0, 10.0)), + "a late claim cannot replace the body's spent motion" + ); let third = turn(&mut frames, &mut show_frame, Some(Vec2::new(0.0, -1.0))); assert!(third.claimed, "the second share was claimed: {third:?}"); assert_eq!((third.claimed_gathered, third.claimed_spent), (second.scroll, Vec2::new(0.0, 1.0)), "one claim of the second share: {third:?}"); @@ -637,7 +646,8 @@ fn unread_claim_cancellations_follow_registered_owners() { if registered.get() { register(ui.ctx(), WheelTaker::new(canvas, rect).vertical(true).scrolls(true)); if take_share(ui.ctx(), canvas).is_some() { - craft_ui::runtime::wheel::claim(ui.ctx(), canvas, Vec2::ZERO); + let token = craft_ui::runtime::wheel::claim_token(ui.ctx(), canvas).expect("a claimable share"); + craft_ui::runtime::wheel::claim(ui.ctx(), canvas, token, Vec2::ZERO); claimed.set(true); } if consume.take() { diff --git a/docs/contract-api.md b/docs/contract-api.md index 30cdc1d570..a30297541f 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -4608,7 +4608,10 @@ The toast queues: one per window (`WindowKey`), filled from any code with a `Con The wheel service (8.6): takers register their view rects, the begin hook splits the pass's wheel input among them from last pass's registrations, and each taker reads its share once. -- `craft_ui::runtime::wheel::claim`: `pub fn claim(ctx: &Context, id: Id, spent: Vec2) -> bool`. Claims for `id` this pass's share of the wheel gesture it owns, and records `spent`, the part of the claimed motion it used up, in its own unit, returning whether the claim succeeded. +- `craft_ui::runtime::wheel::ClaimToken`: `pub struct ClaimToken(/* private fields */)`. A small `Copy` token that identifies a claimable wheel share and never repeats in the process. +- `craft_ui::runtime::wheel::claim_token`: `pub fn claim_token(ctx: &Context, id: Id) -> Option`. Returns the token for the share `id` can claim in the running pass, including after it reads the share. +- `craft_ui::runtime::wheel::claim`: `pub fn claim(ctx: &Context, id: Id, token: ClaimToken, spent: Vec2) -> bool`. Claims for `id` this pass's share of the wheel gesture it owns, and records `spent`, the part of the claimed motion it used up, in its own unit, returning whether the claim succeeded. The token must match the share being claimed, including when a viewport is recreated with the same ID and pass counter. +- `craft_ui::canvas::CanvasSpace::with_wheel`: `pub fn with_wheel(mut self, wheel: Option, token: Option) -> Self`. Sets the wheel share and its claim token. `CanvasSpace::claim_wheel` refuses a snapshot from another share. - `craft_ui::runtime::wheel::claimed`: `pub fn claimed(ctx: &Context, id: Id) -> bool`. Returns whether `id` claimed the running gesture or has an unread cancellation from a claim, and consumes that cancellation. - `craft_ui::runtime::wheel::mark_modal`: `pub fn mark_modal(ctx: &Context, id: Id)`. Marks the wheel gesture `id` owns as begun or gone on under a modal: an app's own modal window that the wheel service does not see as a modal layer. From 66923d268ae9de0880fef13f6456d8c4c85cd443 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 17:54:27 -0800 Subject: [PATCH 25/31] ui: CanvasSpace::with_wheel keeps one argument, and a share's receiver can mark it modal CanvasSpace::with_wheel takes only the share again, as before the claim token; the canvas attaches the token through a crate-private method, so a space built with with_wheel carries no token and cannot claim. craft_ui::runtime::wheel::mark_modal also marks a gesture that `id` received a share of in this pass, for example the horizontal share of a diagonal gesture that a nested scroller owns. Claims stay with the gesture's owner. --- crates/ui-canvas/src/canvas/mod.rs | 3 +- crates/ui-canvas/src/canvas/space.rs | 14 +++- .../ui-canvas/tests/it/canvas/modal_wheel.rs | 72 +++++++++++++++++++ crates/ui-contract/src/runtime/wheel.rs | 15 ++-- docs/contract-api.md | 4 +- 5 files changed, 98 insertions(+), 10 deletions(-) diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index 3ee72c7cf9..b74be1fb3e 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -787,7 +787,8 @@ impl<'a> Canvas<'a> { .with_background(background) .with_precise(self.precise_cursors != caps_lock) .with_zoom_scheme(scheme) - .with_wheel(wheel, self.settled.and_then(|settled| settled.wheel_token)) + .with_wheel(wheel) + .with_wheel_token(self.settled.and_then(|settled| settled.wheel_token)) .with_canvas(id); Some(match self.picture { Some(slot) => space.with_picture(slot), diff --git a/crates/ui-canvas/src/canvas/space.rs b/crates/ui-canvas/src/canvas/space.rs index 9083d5ce35..770ea60a92 100644 --- a/crates/ui-canvas/src/canvas/space.rs +++ b/crates/ui-canvas/src/canvas/space.rs @@ -76,10 +76,18 @@ impl CanvasSpace { self.wheel.map(|(wheel, _)| wheel) } - /// This space with the wheel share the canvas read and its claim token. + /// This space with the wheel share the canvas read. #[must_use] - pub fn with_wheel(mut self, wheel: Option, token: Option) -> Self { - self.wheel = wheel.map(|wheel| (wheel, token)); + pub fn with_wheel(mut self, wheel: Option) -> Self { + self.wheel = wheel.map(|wheel| (wheel, None)); + self + } + + #[must_use] + pub(crate) fn with_wheel_token(mut self, token: Option) -> Self { + if let Some((_, claim)) = self.wheel.as_mut() { + *claim = token; + } self } diff --git a/crates/ui-canvas/tests/it/canvas/modal_wheel.rs b/crates/ui-canvas/tests/it/canvas/modal_wheel.rs index e56bdf7ddb..a6e7b64038 100644 --- a/crates/ui-canvas/tests/it/canvas/modal_wheel.rs +++ b/crates/ui-canvas/tests/it/canvas/modal_wheel.rs @@ -146,6 +146,31 @@ fn claimed_gesture_keeps_the_view(eased: bool) { ); } +#[trial] +fn a_canvas_space_with_a_supplied_wheel_share_has_no_claim_token() { + let read = Rc::new(Cell::new(0_u32)); + let reads = Rc::clone(&read); + let mut fixture = Fixture::new(move |ui| { + let view = CanvasView::new(ui.available_rect_before_wrap(), Point::new(2000.0, 2000.0), 1.0); + Canvas::new("Document").document(Size::new(4000.0, 4000.0)).view(view).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && let Some(wheel) = space.wheel() + { + let supplied = space.with_wheel(Some(wheel)); + assert_eq!(supplied.wheel(), Some(wheel)); + assert!(!supplied.claim_wheel(ui.ctx(), Vec2::ZERO), "a supplied share has no claim token"); + assert!(supplied.with_wheel(None).wheel().is_none()); + assert!(space.claim_wheel(ui.ctx(), Vec2::ZERO), "the canvas's original share keeps its token"); + reads.set(reads.get() + 1); + } + }); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(egui::Pos2::new(200.0, 200.0))]); + fixture.frame(vec![pointer::wheel(-30.0)]); + assert_eq!(read.get(), 1); +} + /// A canvas reports a rejected claim when a nested scroller owns the diagonal gesture. #[trial] fn a_canvas_cannot_claim_the_horizontal_share_of_a_nested_scrollers_gesture() { @@ -187,6 +212,53 @@ fn a_canvas_cannot_claim_the_horizontal_share_of_a_nested_scrollers_gesture() { assert!(view.get().center.x > first.center.x, "a rejected claim leaves later horizontal panning enabled"); } +#[trial] +fn a_canvas_can_mark_the_horizontal_share_of_a_nested_scrollers_gesture_modal() { + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let read = Rc::new(Cell::new(0_u32)); + let (shown, reads) = (Rc::clone(&view), Rc::clone(&read)); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).view(given).show(ui, |ui, body| { + let scroller = egui::Id::unique("modal_nested_wheel_scroller"); + let rect = egui::Rect::from_center_size(given.rect.center(), Vec2::splat(200.0)); + craft_ui::testing::wheel::register(ui.ctx(), craft_behavior::WheelTaker::new(scroller, rect).vertical(true).scrolls(true)); + if let Some(space) = canvas_space(&body.env) + && let Some(wheel) = space.wheel() + { + let vertical = craft_ui::testing::wheel::take_share(ui.ctx(), scroller).expect("the nested scroller receives vertical motion"); + assert!(wheel.scroll.x != 0.0 && wheel.scroll.y == 0.0); + assert!(vertical.scroll.y != 0.0 && vertical.scroll.x == 0.0); + assert_eq!(wheel.modal, reads.get() == 1, "only the rest of the marked gesture is modal"); + assert_eq!(vertical.modal, wheel.modal, "both shares carry the gesture's modal mark"); + assert!(!space.claim_wheel(ui.ctx(), Vec2::ZERO), "marking does not let the canvas claim the gesture"); + assert!(craft_ui::runtime::wheel::claim_token(ui.ctx(), scroller).is_some(), "the nested scroller owns the gesture"); + if reads.get() == 0 { + space.mark_wheel_modal(ui.ctx()); + } + reads.set(reads.get() + 1); + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + let diagonal = || egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: Vec2::new(-20.0, -30.0), + phase: TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Wheel, + }; + fixture.frame(vec![diagonal()]); + fixture.frame(vec![diagonal()]); + assert_eq!(read.get(), 2, "the canvas receives both horizontal shares"); + fixture.advance(craft_behavior::GESTURE_GAP); + fixture.frame(vec![diagonal()]); + assert_eq!(read.get(), 3, "a new gesture starts without the modal mark"); +} + /// A body that first claims the device End stops the canvas glide after the gesture closes. #[trial] fn claiming_the_device_end_stops_the_canvas_glide() { diff --git a/crates/ui-contract/src/runtime/wheel.rs b/crates/ui-contract/src/runtime/wheel.rs index 966a989138..dc0720d782 100644 --- a/crates/ui-contract/src/runtime/wheel.rs +++ b/crates/ui-contract/src/runtime/wheel.rs @@ -30,6 +30,7 @@ pub(crate) struct State { /// The last-pressed gated control while the pointer has stayed inside it since. armed: Option, shares: Vec<(Id, Wheel)>, + recipients: Vec, /// The wheel gesture the split tracks across passes. gesture: WheelGesture, /// The running gesture's gathered scroll in its owner's points, reset when the gesture closes. @@ -67,6 +68,7 @@ impl Default for State { last_layers: IdMap::default(), armed: None, shares: Vec::new(), + recipients: Vec::new(), gesture: WheelGesture::default(), gathered: Vec2::ZERO, zoom_gathered: Vec2::ZERO, @@ -188,14 +190,17 @@ pub fn claimed(ctx: &Context, id: Id) -> bool { }) } -/// Marks the wheel gesture `id` owns as begun or gone on under a modal: an app's own modal window that the wheel -/// service does not see as a modal layer. The gesture's later shares carry `Wheel::modal` until it ends. +/// Marks the wheel gesture `id` owns or received a share of in this pass as begun or gone on under an app's own +/// modal window that the wheel service does not see as a modal layer. The gesture's later shares carry +/// `Wheel::modal` until it ends. pub fn mark_modal(ctx: &Context, id: Id) { PerViewport::::with(ctx, pass::current_viewport(ctx), |state| { - if state.gesture.owner == Some(id) { + let received = state.recipients.contains(&id); + if state.gesture.owner == Some(id) || received { state.modal = true; } - if let Some(ended) = state.device_ended.as_mut().filter(|ended| ended.owner == id) { + let now = crate::runtime::frame::clock(ctx); + if let Some(ended) = state.device_ended.as_mut().filter(|ended| ended.owner == id || (received && ended.at == now)) { ended.modal = true; } }); @@ -564,6 +569,8 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { state.shares.remove(0); state.shares[at].1.phase = WheelPhase::Start; } + state.recipients.clear(); + state.recipients.extend(state.shares.iter().map(|(owner, _)| *owner)); // A value control that owns the running gesture hears its end without a timer of its own: a pass at the gap. // An owed ease pays in the passes that follow. state.wake(now) diff --git a/docs/contract-api.md b/docs/contract-api.md index a30297541f..b4055910a0 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -4611,9 +4611,9 @@ The wheel service (8.6): takers register their view rects, the begin hook splits - `craft_ui::runtime::wheel::ClaimToken`: `pub struct ClaimToken(/* private fields */)`. A small `Copy` token that identifies a claimable wheel share and never repeats in the process. - `craft_ui::runtime::wheel::claim_token`: `pub fn claim_token(ctx: &Context, id: Id) -> Option`. Returns the token for the share `id` can claim in the running pass, including after it reads the share. - `craft_ui::runtime::wheel::claim`: `pub fn claim(ctx: &Context, id: Id, token: ClaimToken, spent: Vec2) -> bool`. Claims for `id` this pass's share of the wheel gesture it owns, and records `spent`, the part of the claimed motion it used up, in its own unit, returning whether the claim succeeded. The token must match the share being claimed, including when a viewport is recreated with the same ID and pass counter. -- `craft_ui::canvas::CanvasSpace::with_wheel`: `pub fn with_wheel(mut self, wheel: Option, token: Option) -> Self`. Sets the wheel share and its claim token. `CanvasSpace::claim_wheel` refuses a snapshot from another share. +- `craft_ui::canvas::CanvasSpace::with_wheel`: `pub fn with_wheel(mut self, wheel: Option) -> Self`. Sets the wheel share without a claim token. `CanvasSpace::claim_wheel` refuses a snapshot from another share. - `craft_ui::runtime::wheel::claimed`: `pub fn claimed(ctx: &Context, id: Id) -> bool`. Returns whether `id` claimed the running gesture or has an unread cancellation from a claim, and consumes that cancellation. -- `craft_ui::runtime::wheel::mark_modal`: `pub fn mark_modal(ctx: &Context, id: Id)`. Marks the wheel gesture `id` owns as begun or gone on under a modal: an app's own modal window that the wheel service does not see as a modal layer. +- `craft_ui::runtime::wheel::mark_modal`: `pub fn mark_modal(ctx: &Context, id: Id)`. Marks the wheel gesture `id` owns or received a share of in this pass as begun or gone on under a modal: an app's own modal window that the wheel service does not see as a modal layer. ## `craft_ui::runtime::windows` From d00725a7ad5f9aeecf32686d600ea4ba376b83ed Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 30 Nov 2026 03:27:34 +0100 Subject: [PATCH 26/31] Preserve native FigCraft image dimensions in header reads --- crates/figcraft-format/src/lib.rs | 34 ++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/crates/figcraft-format/src/lib.rs b/crates/figcraft-format/src/lib.rs index 7475c5e216..a06dc1b869 100644 --- a/crates/figcraft-format/src/lib.rs +++ b/crates/figcraft-format/src/lib.rs @@ -150,6 +150,9 @@ impl<'de> Deserialize<'de> for BranchIndex { pub struct Header { pub version: Option, pub images: Option>, + /// Stored dimensions, retained even when a consumer cannot decode an image's codec. + /// These are untrusted metadata, not permission to allocate a pixel buffer. + pub image_dimensions: std::collections::BTreeMap, } pub fn read_header(text: &str) -> Result { @@ -170,10 +173,20 @@ impl<'de> Deserialize<'de> for Header { match k.as_str() { "version" => h.version = m.next_value::()?.as_u64(), "imageIndex" => { - h.images = m - .next_value::()? + let value = m.next_value::()?; + h.images = + value.as_array().map(|a| a.iter().filter_map(|v| v.get("hash").and_then(Value::as_str).map(str::to_owned)).collect()); + h.image_dimensions = value .as_array() - .map(|a| a.iter().filter_map(|v| v.get("hash").and_then(Value::as_str).map(str::to_owned)).collect()) + .into_iter() + .flatten() + .filter_map(|v| { + let hash = v.get("hash")?.as_str()?.to_owned(); + let width = u32::try_from(v.get("width")?.as_u64()?).ok()?; + let height = u32::try_from(v.get("height")?.as_u64()?).ok()?; + Some((hash, (width, height))) + }) + .collect(); } _ => { m.next_value::()?; @@ -324,6 +337,17 @@ pub fn write_document_json(doc: &D, images: &[I #[cfg(test)] mod tests { + #[test] + fn image_dimensions_survive_the_native_envelope() { + let images = [super::ImageIndexEntry { hash: "original-image".into(), width: 731, height: 419 }]; + let mut json = Vec::new(); + super::write_document_json(&serde_json::json!({"name":"original fixture"}), &images, &mut json).unwrap(); + let header = super::read_header(std::str::from_utf8(&json).unwrap()).unwrap(); + assert_eq!(header.image_dimensions.get(&images[0].hash), Some(&(images[0].width, images[0].height))); + let legacy = super::read_header(r#"{"imageIndex":[{"hash":"legacy"},{"hash":"overflow","width":4294967296,"height":1}]}"#).unwrap(); + assert_eq!(legacy.images.unwrap().len(), 2); + assert!(legacy.image_dimensions.is_empty()); + } use super::*; #[test] @@ -437,8 +461,8 @@ mod tests { } #[test] fn newer_version_is_reported_before_document_decode() { - assert_eq!(check_version(&Header { version: Some(2), images: None }), Err(NewerVersion(2))); - assert_eq!(check_version(&Header { version: Some(u64::MAX), images: None }), Err(NewerVersion(u32::MAX))); + assert_eq!(check_version(&Header { version: Some(2), ..Header::default() }), Err(NewerVersion(2))); + assert_eq!(check_version(&Header { version: Some(u64::MAX), ..Header::default() }), Err(NewerVersion(u32::MAX))); #[derive(Deserialize)] struct Payload { From 091ebbd78a0dff6ac3cd784606314a8993cc5f56 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 30 Nov 2026 09:36:29 +0700 Subject: [PATCH 27/31] raster3d: list the inverse-square radius change in the README --- crates/raster3d/README.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/raster3d/README.md b/crates/raster3d/README.md index 4e0e9600ed..3e45b41e71 100644 --- a/crates/raster3d/README.md +++ b/crates/raster3d/README.md @@ -144,7 +144,8 @@ lights' outer cones are over 1.40 radians wide, where resolve blocks hold more t subsamples, where shadows-only materials do not receive shadows, where fragments under discarded opaque pixels leave the depth range, where blended casters have no base texture, where opaque-mode and masked casters have an opacity below 0.5, where casters reach within 1 unit of -light-space depth of a spot or point light, where an encoded color is negative, and where a +light-space depth of a spot or point light, where an inverse-square point or spot light's radius is +between 0 and 1, where an encoded color is negative, and where a texture is sampled between large finite texels of opposite signs. Halfway between red values of `3e38` and `−3e38`, for example, the sampler here returns red 0 and EffectCraft's interpolation overflows `f32`. @@ -198,6 +199,10 @@ Changes from those files: - A spot light whose outer cone's half angle plus 0.05 radians is over 1.45 radians gets six maps, as a point light does. EffectCraft gave it one map 1.45 radians wide, so receivers in the rest of the cone were not shadowed. +- An inverse-square point or spot light whose radius is between 0 and 1 takes a radius of 1 for both + its full-strength plateau and its falloff, so its distance factor never exceeds 1. EffectCraft kept + the plateau at the radius and divided 1 by the distance beyond it, so a fragment between the radius + and 1 unit from the light took more than the light's full strength. - A resolve block of more than 2^24 subsamples is averaged in `f64`. EffectCraft's `f32` count of covered subsamples stopped at 2^24, which raised the mean depth. - A clipped corner whose `1/w` overflows `f32` (a clip transform scaled near `f32`'s smallest From 7dd943f93abbef3d37b9f926064aa9a482fb1f42 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 30 Nov 2026 09:38:33 +0700 Subject: [PATCH 28/31] vendor/hayro-interpret: record the rustfmt'd hashes of pattern.rs and self_draw_tests.rs --- vendor/hayro-interpret/SOURCE.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vendor/hayro-interpret/SOURCE.json b/vendor/hayro-interpret/SOURCE.json index dd0936abb9..8ad75195aa 100644 --- a/vendor/hayro-interpret/SOURCE.json +++ b/vendor/hayro-interpret/SOURCE.json @@ -404,13 +404,13 @@ "path": "src/pattern.rs", "source_sha256": "17b49a465275c20e6645dea9443f2cb3a64c594925fd860e74b80b44d5344e37", "source_git_blob": "9295f51709f8915951d7b9afca9411651d65a1f8", - "sha256": "dccd845f4d6f72c43f78fdeca0ed12064fc1e49f8991c1682bc079e2d0e9e9e8" + "sha256": "4621fe8b85f472e731e2c01d0f92ec1662c7d9d0f0e20f520fd9c926201af8d5" }, { "path": "src/self_draw_tests.rs", "source_sha256": null, "source_git_blob": null, - "sha256": "9d7c7af03161eb4ad00aaa6db8a4df3c11fa340281b2fc27c22ca83b5aa11d23" + "sha256": "1f0a93fb387d3ba51c1348ed69fe567fdb2be88ee57506400cd66644dadadb85" }, { "path": "src/shading.rs", From 6c9315adb9503e6aeb4740593a626c932afd8622 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 30 Nov 2026 09:41:42 +0700 Subject: [PATCH 29/31] ui-canvas: name the glide trial's swipe sample as a documented const --- crates/ui-canvas/src/canvas/navigate/mod.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/ui-canvas/src/canvas/navigate/mod.rs b/crates/ui-canvas/src/canvas/navigate/mod.rs index 1cafcaa914..3e9e886733 100644 --- a/crates/ui-canvas/src/canvas/navigate/mod.rs +++ b/crates/ui-canvas/src/canvas/navigate/mod.rs @@ -334,11 +334,14 @@ pub(crate) mod trials { use crate::testing::trial; use egui::Vec2; + /// One sample of a touchpad swipe upward, in points: the glide's input, not a size of anything drawn. + const SWIPE: Vec2 = Vec2::new(0.0, -30.0); + #[trial] fn stopping_a_touchpad_glide_clears_its_lift_samples() { let mut glide = TouchpadGlide::default(); - glide.push(0.0, Vec2::new(0.0, -30.0)); - glide.push(0.01, Vec2::new(0.0, -30.0)); + glide.push(0.0, SWIPE); + glide.push(0.01, SWIPE); assert_ne!(glide.lift_velocity(0.02), Vec2::ZERO); glide.velocity = glide.lift_velocity(0.02); From 607aeb0b552f16b09ca8a9a5c213a42ca96ba5a9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 19:14:57 -0800 Subject: [PATCH 30/31] craft-mesh-ops: tangents read glTF UVs with v up again compute_tangents and compute_tangents_split pass the UVs to MikkTSpace and to the f64 fallback with v negated, as main did with 1 - v. glTF UVs run v down the image, so without the flip the bitangent followed increasing v and every unmirrored mesh got w = -1, which inverts the green channel of glTF normal maps. The tests expect w = +1 for unmirrored UVs again, preview_orb sets +1 again, and the primitive check counts mirrored tangents as before and also checks that each bitangent points up the image. A new test checks that a plain quad keeps w = +1 with both functions. --- crates/mesh-ops/README.md | 3 +- crates/mesh-ops/src/mesh.rs | 61 ++++++++++++++++++++++++------- crates/mesh-ops/src/primitives.rs | 14 ++++--- 3 files changed, 58 insertions(+), 20 deletions(-) diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md index 1fbdb18701..608f843045 100644 --- a/crates/mesh-ops/README.md +++ b/crates/mesh-ops/README.md @@ -16,7 +16,8 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form available. MikkTSpace omits those faces. A mesh with more than 2,048 noncollapsed triangles around one vertex, or with non-finite positions or UVs, or whose largest absolute position or UV component is nonzero and outside 1e-6 to 1e6, gets per-corner tangents from f64 UV gradients instead of MikkTSpace. An edge-connected region containing a face whose f32 UV gradients overflow or underflow uses that fallback. - Both paths use the stored UVs. The generated corner frames of a triangle with usable UV gradients + Both paths read the stored glTF UVs (v down) with v negated, so an unmirrored mapping gets + `w = +1`. The generated corner frames of a triangle with usable UV gradients share one handedness sign. With `compute_tangents`, a vertex shared by mirrored triangles keeps the first triangle's frame, so the stored signs of the other triangle can differ; use `compute_tangents_split` when both sides of a mirrored seam need their own frames. It splits only diff --git a/crates/mesh-ops/src/mesh.rs b/crates/mesh-ops/src/mesh.rs index d32c4f299d..6869402a69 100644 --- a/crates/mesh-ops/src/mesh.rs +++ b/crates/mesh-ops/src/mesh.rs @@ -244,7 +244,8 @@ impl Mesh { /// Faces with coincident corners stay in the mesh but are omitted from MikkTSpace. Their /// corners reuse a generated frame for the same vertex when one is available. /// Edge-connected regions containing a face whose f32 UV gradients overflow, underflow or reverse the UV orientation use the fallback. - /// Both paths use the stored UVs. The generated corner frames of a triangle with usable UV + /// Both paths read the stored UVs with v up, so an unmirrored glTF mapping (v down) gets + /// `w = +1`. The generated corner frames of a triangle with usable UV /// gradients share one handedness sign. The stored per-vertex frames need not: a vertex shared /// by mirrored triangles keeps the first one's frame. [`Mesh::compute_tangents_split`] keeps /// both sides of a mirrored seam when the mesh passes its input checks (indices in range, an @@ -380,16 +381,17 @@ impl Mesh { self.uvs = vec![Vec2::ZERO; n]; } let normals: Vec = self.normals.iter().copied().map(tangent_normal).collect(); + let uvs = tangent_uvs(&self.uvs); let mut corners = vec![Vec4::ZERO; self.indices.len()]; // MikkTSpace receives noncollapsed faces with valid indices and bounded attributes. let usable = in_safe_range(self.positions.iter().flat_map(|p| p.to_array())) - && in_safe_range(self.uvs.iter().flat_map(|uv| uv.to_array())) + && in_safe_range(uvs.iter().flat_map(|uv| uv.to_array())) && self.indices.iter().all(|&i| (i as usize) < n); let mut g = Mikk { positions: &self.positions, normals: &normals, - uvs: &self.uvs, + uvs: &uvs, indices: &self.indices, corners: &mut corners, faces: if usable { Mikk::noncollapsed_faces(&self.positions, &self.indices) } else { None }, @@ -399,13 +401,13 @@ impl Mesh { let mut fallback_faces: Vec = if affordable { (0..g.face_count()) .map(|face| g.original_face(face)) - .filter(|&face| !mikk_uvs_safe(&self.positions, &self.uvs, &self.indices[face * 3..face * 3 + 3])) + .filter(|&face| !mikk_uvs_safe(&self.positions, &uvs, &self.indices[face * 3..face * 3 + 3])) .collect() } else { Vec::new() }; if !fallback_faces.is_empty() { - let welded = tangent_vertex_ids(&self.positions, &normals, &self.uvs, self.indices.iter().copied()); + let welded = tangent_vertex_ids(&self.positions, &normals, &uvs, self.indices.iter().copied()); let eligible = g.faces.clone().unwrap_or_else(|| (0..self.indices.len() / 3).collect()); fallback_faces = connected_fallback_faces(&welded, &eligible, &fallback_faces); let mut faces = g.faces.take().unwrap_or_else(|| (0..self.indices.len() / 3).collect()); @@ -413,11 +415,11 @@ impl Mesh { g.faces = Some(faces); } if !(affordable && g.face_count() != 0 && (g.face_count() == face_count || g.affordable()) && mikktspace::generate_tangents(&mut g)) { - fill_simple_tangents(&self.positions, &normals, &self.uvs, &self.indices, g.corners); + fill_simple_tangents(&self.positions, &normals, &uvs, &self.indices, g.corners); g.fill_collapsed_corners(); } else { let fallback_indices: Vec = fallback_faces.iter().flat_map(|&face| self.indices[face * 3..face * 3 + 3].iter().copied()).collect(); - let fallback = simple_tangents(&self.positions, &normals, &self.uvs, &fallback_indices); + let fallback = simple_tangents(&self.positions, &normals, &uvs, &fallback_indices); for (slot, face) in fallback_faces.into_iter().enumerate() { let start = face * 3; g.corners[start..start + 3].copy_from_slice(&fallback[slot * 3..slot * 3 + 3]); @@ -711,6 +713,13 @@ fn connected_fallback_faces(indices: &[u32], eligible: &[usize], seeds: &[usize] } /// Per-corner tangents from f64 triangle UV gradients. +/// The UVs that MikkTSpace and the fallback receive. They expect OpenGL texture coordinates +/// (v up); our UVs are glTF (v down). With v negated, the bitangent `cross(N, T) * w` points up +/// the image, as glTF requires. Negating keeps differences in v that `1 - v` would round away. +fn tangent_uvs(uvs: &[Vec2]) -> Vec { + uvs.iter().map(|uv| Vec2::new(uv.x, -uv.y)).collect() +} + fn simple_tangents(positions: &[Vec3], normals: &[Vec3], uvs: &[Vec2], indices: &[u32]) -> Vec { let mut corners = vec![Vec4::ZERO; indices.len()]; fill_simple_tangents(positions, normals, uvs, indices, &mut corners); @@ -1365,7 +1374,7 @@ mod tests { let determinant = (mesh.uvs[1].as_dvec2() - mesh.uvs[0].as_dvec2()).perp_dot(mesh.uvs[2].as_dvec2() - mesh.uvs[0].as_dvec2()); assert!(determinant < 0.0); mesh.compute_tangents(); - assert!(mesh.tangents.iter().all(|tangent| tangent.w < 0.0)); + assert!(mesh.tangents.iter().all(|tangent| tangent.w > 0.0)); } #[test] @@ -1383,7 +1392,7 @@ mod tests { assert!(!mikk_uvs_safe(&mesh.positions, &mesh.uvs, &mesh.indices)); mesh.compute_tangents(); for tangent in &mesh.tangents { - assert_eq!(tangent.w.is_sign_negative(), wide_determinant.is_sign_negative()); + assert_ne!(tangent.w.is_sign_negative(), wide_determinant.is_sign_negative()); } } @@ -1475,7 +1484,7 @@ mod tests { let corners = mesh.corner_tangents(); assert_eq!(corners[0].w, corners[3].w); for &tangent in &corners[0..3] { - assert!((Vec3::Z.cross(tangent.truncate()) * tangent.w).dot(Vec3::Y) > 0.0); + assert!((Vec3::Z.cross(tangent.truncate()) * tangent.w).dot(Vec3::Y) < 0.0); } } @@ -1679,7 +1688,7 @@ mod tests { let corners = mesh.corner_tangents(); for &tangent in &corners[copies * 3..copies * 3 + 3] { assert_eq!(tangent, corners[0]); - assert_eq!(tangent.w, -1.0); + assert_eq!(tangent.w, 1.0); } assert!(corners[copies * 3 + 3..].iter().all(|tangent| tangent.is_finite() && tangent.w == 1.0)); } @@ -1720,7 +1729,7 @@ mod tests { for tangent in mesh.tangents { assert!(tangent.truncate().dot(Vec3::X) > 0.99, "{offset} {scale} {orientation}: {tangent:?}"); let bitangent = Vec3::Z.cross(tangent.truncate()) * tangent.w; - assert!(bitangent.dot(Vec3::Y * orientation) > 0.99, "{offset} {scale} {orientation}: {tangent:?}"); + assert!(bitangent.dot(-Vec3::Y * orientation) > 0.99, "{offset} {scale} {orientation}: {tangent:?}"); } } } @@ -2139,6 +2148,30 @@ mod tests { assert!(m.tangents.iter().all(|t| t.is_finite()), "{:?}", m.tangents); } + #[test] + fn unmirrored_quad_keeps_a_positive_bitangent_sign() { + // glTF UVs (v down) on a quad facing +Z: u follows +X and v decreases along +Y, so the + // bitangent `cross(N, T) * w` must point up the image (+Y), which needs w = +1. + let quad = || { + Mesh::from_parts( + vec![Vec3::ZERO, Vec3::X, Vec3::new(1.0, 1.0, 0.0), Vec3::Y], + Some(vec![Vec3::Z; 4]), + vec![Vec2::Y, Vec2::ONE, Vec2::X, Vec2::ZERO], + vec![0, 1, 2, 0, 2, 3], + "Default", + ) + .unwrap() + }; + let mut split = quad(); + assert!(split.compute_tangents_split().is_empty()); + for m in [quad(), split] { + assert_eq!(m.tangents.len(), 4); + for t in &m.tangents { + assert!((t.truncate() - Vec3::X).length() < 1e-4 && t.w == 1.0, "{t:?}"); + } + } + } + #[test] fn far_and_tiny_triangles_keep_their_tangent() { for edge in [1e-20_f32, 1e20] { @@ -2151,7 +2184,7 @@ mod tests { ) .unwrap(); for t in &m.tangents { - assert!((t.truncate() - Vec3::X).length() < 1e-4 && t.w == -1.0, "edge {edge}: {t:?}"); + assert!((t.truncate() - Vec3::X).length() < 1e-4 && t.w == 1.0, "edge {edge}: {t:?}"); } } } @@ -2166,7 +2199,7 @@ mod tests { *uv = Vec2::new(uv.x * flip.x, uv.y * flip.y); } m.compute_tangents(); - let fallback = simple_tangents(&m.positions, &m.normals, &m.uvs, &m.indices); + let fallback = simple_tangents(&m.positions, &m.normals, &tangent_uvs(&m.uvs), &m.indices); assert_eq!(m.tangents.len(), 4); for (&index, simple) in m.indices.iter().zip(&fallback) { let mikk = m.tangents[index as usize]; diff --git a/crates/mesh-ops/src/primitives.rs b/crates/mesh-ops/src/primitives.rs index d89ea04a68..65015a5d7c 100644 --- a/crates/mesh-ops/src/primitives.rs +++ b/crates/mesh-ops/src/primitives.rs @@ -256,7 +256,7 @@ pub fn preview_orb() -> Mesh { .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) + (around - *n * n.dot(around)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()).extend(1.0) }) .collect(); m @@ -545,7 +545,8 @@ mod tests { } /// Every triangle's winding agrees with its vertex normals, UVs stay in 0..1 (u in 0..max_u), - /// and each reconstructed bitangent follows increasing v where the UV gradient is defined. + /// tangent frames are unit length and perpendicular to their normals, and the UV mapping is + /// not mirrored (tangent handedness +1). fn check(m: &Mesh, max_u: f32) { m.validate().unwrap(); let mut bad = 0; @@ -571,6 +572,9 @@ mod tests { assert!(tangent.truncate().dot(normal).abs() < 1e-3, "{tangent:?}, {normal:?}"); assert!(tangent.w == 1.0 || tangent.w == -1.0, "{tangent:?}"); } + let mirrored = m.tangents.iter().filter(|t| t.w < 0.0).count(); + assert!(mirrored * 50 < m.tangents.len().max(1), "{mirrored} mirrored tangents"); + // glTF UVs run v down the image, and the bitangent `cross(N, T) * w` points up it. let (mut opposed, mut tested) = (0, 0); for &[a, b, c] in m.indices.as_chunks::<3>().0 { let (a, b, c) = (a as usize, b as usize, c as usize); @@ -580,18 +584,18 @@ mod tests { continue; } let (e1, e2) = (m.positions[b].as_dvec3() - m.positions[a].as_dvec3(), m.positions[c].as_dvec3() - m.positions[a].as_dvec3()); - let Some(bitangent) = ((e2 * d1.x - e1 * d2.x) / determinant).try_normalize() else { continue }; + let Some(increasing_v) = ((e2 * d1.x - e1 * d2.x) / determinant).try_normalize() else { continue }; for vertex in [a, b, c] { let tangent = m.tangents[vertex]; let reconstructed = m.normals[vertex].as_dvec3().cross(tangent.truncate().as_dvec3()) * tangent.w as f64; tested += 1; - let alignment = reconstructed.dot(bitangent); + let alignment = reconstructed.dot(-increasing_v); assert!(alignment.is_finite(), "vertex {vertex}: {alignment}"); opposed += usize::from(alignment < 0.0); } } assert!(tested > 0); - assert!(opposed * 50 < tested, "{opposed} tangent frames oppose increasing v"); + assert!(opposed * 50 < tested, "{opposed} bitangents point down the image"); } #[test] From 716a24ce40c3a797b1d9cb9fa654cc41654368bb Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 29 Nov 2026 22:38:29 -0500 Subject: [PATCH 31/31] svg(paths): preserve source group ancestry during import (#4374) * svg(paths): preserve source group ancestry during import * svg(paths): support namespaced group metadata attributes --- crates/svg/src/paths.rs | 178 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 177 insertions(+), 1 deletion(-) diff --git a/crates/svg/src/paths.rs b/crates/svg/src/paths.rs index 013c6a252b..3bd57521d7 100644 --- a/crates/svg/src/paths.rs +++ b/crates/svg/src/paths.rs @@ -27,6 +27,11 @@ pub trait Kind: Clone + Default { /// styles and stylesheets, as well as the presentation properties the reader tracks itself. const PROPERTIES: &'static [&'static str] = &[]; + /// Optional raw attributes to retain on source groups (for example an editor's + /// document-local group ID). Unlike computed properties, these do not inherit. + /// At most 16 attributes per group, with values bounded by `MAX_GROUP_LABEL`. + const GROUP_ATTRIBUTES: &'static [GroupAttribute] = &[]; + /// The tag an element sets, from its computed style and `class` attribute; `None` inherits /// its parent's. fn of(style: &StyleMap, class: &str) -> Option; @@ -81,18 +86,69 @@ pub struct Shape { /// `inkscape:groupmode="layer"`, named by its `inkscape:label`, else its `id`, else empty. /// `None` outside any layer. At most [`MAX_LAYER_NAME`] characters. pub layer: Option, + /// Innermost retained source group, an index into [`Imported::groups`]. + pub group: Option, } /// Most characters of a layer name kept in [`Shape::layer`]. pub const MAX_LAYER_NAME: usize = 256; const INKSCAPE_NS: &str = "http://www.inkscape.org/namespaces/inkscape"; +/// Maximum characters retained for a group's source ID, label or requested attribute. +pub const MAX_GROUP_LABEL: usize = 256; +const MAX_GROUP_ATTRIBUTES: usize = 16; +const MAX_GROUP_METADATA_BYTES: usize = 8 * 1024 * 1024; + +/// An attribute selector for group metadata. Namespace URIs, not document-local +/// prefixes, identify namespaced XML attributes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct GroupAttribute { + pub namespace: Option<&'static str>, + pub name: &'static str, +} + +impl GroupAttribute { + pub const fn unqualified(name: &'static str) -> Self { + Self { namespace: None, name } + } + + pub const fn namespaced(namespace: &'static str, name: &'static str) -> Self { + Self { namespace: Some(namespace), name } + } +} + +/// A requested attribute and its bounded raw value. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GroupMetadata { + pub attribute: GroupAttribute, + pub value: String, +} + +/// A source SVG `` containing imported drawable geometry. Groups are in traversal order +/// (parents before children). Each expansion of a reused group has a distinct index even if +/// its source ID is the same; a source ID is a label, not a unique imported identity. +#[derive(Debug, Clone, PartialEq)] +pub struct Group { + pub parent: Option, + /// Raw source ID, if present. + pub source_id: Option, + /// Inkscape label, when present, otherwise the source ID. + pub label: Option, + /// Effective caller-defined kind after the normal style cascade. + pub kind: K, + /// Only attributes explicitly requested by [`Kind::GROUP_ATTRIBUTES`]. + pub attributes: Vec, +} + /// What [`import`] read. Shapes may lie outside the `width_mm` × `height_mm` viewport. #[derive(Debug, Clone, PartialEq)] pub struct Imported { pub width_mm: f64, pub height_mm: f64, pub shapes: Vec>, + /// Ancestors of the returned shapes; empty groups are omitted. A caller that drops + /// geometries after clipping may prune their groups as part of its model mapping. + pub groups: Vec>, pub clips: Vec, /// What was skipped or approximated. A caller adding its own goes through [`push_warning`] /// with `dropped_warnings`, to keep the list bounded. @@ -386,6 +442,7 @@ struct ImportState { clips: Vec, /// The innermost Inkscape layer's name ([`Shape::layer`]). layer: Option>, + group: Option, } impl Default for ImportState { @@ -398,6 +455,7 @@ impl Default for ImportState { inherited_style: std::collections::HashMap::new(), clips: Vec::new(), layer: None, + group: None, } } } @@ -424,7 +482,7 @@ pub(crate) const MAX_CSS_SELECTOR_CHECKS: usize = 5_000_000; /// combinators, `:not()`, `:first-child`, `:last-child`, `:root`, selector lists, and a bounded /// presentation-property cascade. Curves stay curves: nothing is flattened. /// -/// Each shape carries its stroke paint as written and the `clip-path` regions that apply to it; +/// Each shape carries its source group ancestry, stroke paint as written and the `clip-path` regions that apply to it; /// [`Imported::clipped_path`] returns its geometry with those clips applied. /// /// What cannot be represented is skipped with a line in [`Imported::warnings`]: `` (no @@ -473,6 +531,8 @@ pub fn import(svg: &str, name: &str) -> Result, Error> { reference_stack: Vec::new(), instance_count: 0, shapes: Vec::new(), + groups: Vec::new(), + group_metadata_bytes: 0, clips: Vec::new(), clip_pieces: 0, segments: 0, @@ -482,16 +542,50 @@ pub fn import(svg: &str, name: &str) -> Result, Error> { }; let base = ImportState { transform: viewport, ..ImportState::default() }; import_node(root, base, 0, &mut context)?; + let groups = retain_drawable_groups(context.groups, &mut context.shapes); Ok(Imported { width_mm, height_mm, shapes: context.shapes, + groups, clips: context.clips, warnings: context.warnings, dropped_warnings: context.dropped_warnings, }) } +/// Keep exactly the groups that own drawable shapes and their ancestors, remapping the +/// indices without another XML walk. Parent groups precede their descendants. +fn retain_drawable_groups(groups: Vec>, shapes: &mut [Shape]) -> Vec> { + let mut used = vec![false; groups.len()]; + for shape in shapes.iter() { + if let Some(index) = shape.group { + used[index] = true; + } + } + for (index, group) in groups.iter().enumerate().rev() { + if used[index] + && let Some(parent) = group.parent + { + used[parent] = true; + } + } + let mut remap = vec![None; groups.len()]; + let mut retained = Vec::new(); + for (index, mut group) in groups.into_iter().enumerate() { + if !used[index] { + continue; + } + group.parent = group.parent.and_then(|parent| remap[parent]); + remap[index] = Some(retained.len()); + retained.push(group); + } + for shape in shapes { + shape.group = shape.group.and_then(|index| remap[index]); + } + retained +} + struct ImportContext<'a, 'input, K> { visited: usize, path_name: &'a str, @@ -500,6 +594,8 @@ struct ImportContext<'a, 'input, K> { reference_stack: Vec, instance_count: usize, shapes: Vec>, + groups: Vec>, + group_metadata_bytes: usize, clips: Vec, clip_pieces: usize, segments: usize, @@ -609,6 +705,32 @@ fn import_node<'a, 'input, K: Kind>( state.display_none = true; } } + if tag == "g" && !state.display_none { + let bounded = |value: &str| value.chars().take(MAX_GROUP_LABEL).collect::(); + let source_id = node.attribute("id").map(bounded); + let label = node.attribute((INKSCAPE_NS, "label")).map(bounded).or_else(|| source_id.clone()); + let attributes: Vec = K::GROUP_ATTRIBUTES + .iter() + .take(MAX_GROUP_ATTRIBUTES) + .filter_map(|&attribute| { + let value = match attribute.namespace { + Some(namespace) => node.attribute((namespace, attribute.name)), + None => node.attribute(attribute.name), + }?; + Some(GroupMetadata { attribute, value: bounded(value) }) + }) + .collect(); + let bytes = source_id.as_ref().map_or(0, String::len) + + label.as_ref().map_or(0, String::len) + + attributes.iter().map(|item| item.value.len()).sum::(); + context.group_metadata_bytes = context.group_metadata_bytes.saturating_add(bytes); + if context.group_metadata_bytes > MAX_GROUP_METADATA_BYTES { + return Err(svg_error(context.path_name, "SVG group metadata exceeds the import limit")); + } + let index = context.groups.len(); + context.groups.push(Group { parent: state.group, source_id, label, kind: state.kind.clone(), attributes }); + state.group = Some(index); + } if !state.display_none && !state.visibility_hidden { for (property, effect) in [("mask", "the art is imported unmasked"), ("filter", "the art is imported unfiltered")] { if style.get(property).is_some_and(|v| v != "none") { @@ -699,6 +821,7 @@ fn import_node<'a, 'input, K: Kind>( fill_rule: if style.get("fill-rule").is_some_and(|value| value == "evenodd") { FillRule::EvenOdd } else { FillRule::NonZero }, clips: state.clips.clone(), layer: state.layer.as_deref().map(str::to_string), + group: state.group, })); } for child in node.children().filter(|n| n.is_element()) { @@ -1937,6 +2060,8 @@ mod tests { } impl Kind for Tag { + const GROUP_ATTRIBUTES: &'static [GroupAttribute] = + &[GroupAttribute::unqualified("data-group"), GroupAttribute::namespaced("urn:editor-metadata", "group-id")]; const PROPERTIES: &'static [&'static str] = &["data-kind"]; fn of(style: &StyleMap, class: &str) -> Option { @@ -2160,6 +2285,57 @@ mod tests { assert!(near(b.x0, 12.0) && near(b.y0, 24.0) && near(b.width(), 6.0), "{b:?}"); } + #[test] + fn group_ancestry_uses_the_geometry_walk_and_keeps_source_metadata() { + let got = read( + r#" + + + + + + + + + "#, + ); + assert_eq!(got.shapes.len(), 3); + assert_eq!(got.groups.len(), 2); + assert_eq!(got.groups[0].source_id.as_deref(), Some("decor")); + assert_eq!(got.groups[0].label.as_deref(), Some("Decorative motif")); + assert_eq!( + got.groups[0].attributes, + vec![ + GroupMetadata { attribute: GroupAttribute::unqualified("data-group"), value: "15".into() }, + GroupMetadata { attribute: GroupAttribute::namespaced("urn:editor-metadata", "group-id"), value: "42".into() }, + ] + ); + assert!(got.groups[0].parent.is_none()); + assert_eq!(got.groups[1].source_id.as_deref(), Some("details")); + assert_eq!(got.groups[1].parent, Some(0)); + assert!(got.groups[1].attributes.is_empty()); + assert_eq!(got.shapes.iter().map(|s| s.group).collect::>(), [Some(1), Some(0), None]); + } + + #[test] + fn repeated_use_groups_have_distinct_membership_at_each_site() { + let got = read( + r##" + + + + + + "##, + ); + assert_eq!(got.shapes.len(), 2); + assert_eq!(got.groups.len(), 5); + assert_eq!(got.groups.iter().map(|g| g.parent).collect::>(), [None, Some(0), Some(1), Some(0), Some(3)]); + assert_eq!(got.shapes.iter().map(|s| s.group).collect::>(), [Some(2), Some(4)]); + assert_eq!(got.groups[1].source_id, got.groups[3].source_id); + assert!(bounds(&got, 1).x0 > bounds(&got, 0).x0); + } + #[test] fn local_use_instances_take_x_y_transform_and_symbol_viewboxes() { let got = read(