diff --git a/.github/workflows/formats.yml b/.github/workflows/formats.yml index 7e7ea19b7b..22d90712e8 100644 --- a/.github/workflows/formats.yml +++ b/.github/workflows/formats.yml @@ -15,6 +15,7 @@ on: - "crates/silhouette-studio/**" - "crates/tiff/**" - "crates/heif/**" + - "crates/pst/**" - "crates/cms/**" - "crates/cdr/**" - "crates/texture/**" @@ -34,6 +35,7 @@ on: - "crates/silhouette-studio/**" - "crates/tiff/**" - "crates/heif/**" + - "crates/pst/**" - "crates/cms/**" - "crates/cdr/**" - "crates/texture/**" @@ -69,7 +71,8 @@ jobs: - { crate: craft-svg-paths, features: "" } - { crate: craft-silhouette-studio, features: "" } - { crate: craft-tiff, features: "" } - - { crate: craft-heif, features: "testdata" } + - { crate: craft-heif, features: "testdata test-support" } + - { crate: craft-pst, features: "test-writer test-support" } - { crate: craft-cms, features: "" } - { crate: craft-cdr, features: "synth" } - { crate: craft-texture, features: "dds parallel" } diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 1464858433..112bfe4e93 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -125,6 +125,8 @@ The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper `crates/audio-dsp` combines FilmCraft `crates/audio-dsp` at `3f137a7ed420cac79b32145f5243b7f98b31f71c` and SoundCraft `crates/dsp` at `648ed9db9a0e98cc55643babffac381521a556c8` (both MIT OR Apache-2.0). `crates/audio-dsp/NOTICE` keeps the copyright notices of both projects. +`crates/audio-dsp/src/effects/voice.rs` adapts the two crossfaded read taps of SoundCraft `crates/dsp/src/plugins/pitch.rs` and the YIN pitch tracker of `crates/dsp/src/pitch_detect.rs` at `915481be1b49d7e0502e07b059d0c0198c61911a` (MIT OR Apache-2.0). The taps are centered on a fixed 10 ms latency and spaced by whole periods of the tracked pitch, and the tracker runs on a decimated copy of the input in buffers sized at creation. + ## GIMP palette reader `crates/palette` extracts the GPL text parser from AniCraft `crates/doc/src/swatch.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0), introduced by Tanish Manku in `a64130a9da9bdde545463b852d95d6a6774b1dfd` (AniCraft #270). The import preserves Tanish as primary author. Neutral RGB/name adaptation separates application display-name sanitization and the `Untitled` policy; validation tests and integration are subsequent Dylan M. Taylor changes. diff --git a/Cargo.lock b/Cargo.lock index 4ceb52f2fe..f897e83d12 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1790,6 +1790,7 @@ dependencies = [ "craft-drawingml", "craft-dwg", "craft-dxf", + "craft-ease", "craft-ecproj-format", "craft-elf", "craft-eps", @@ -1830,6 +1831,7 @@ dependencies = [ "craft-html", "craft-http-url", "craft-i18n", + "craft-i18n-build", "craft-ical", "craft-idml", "craft-image-codecs", @@ -1873,6 +1875,7 @@ dependencies = [ "craft-ora", "craft-pages", "craft-palette", + "craft-pbr", "craft-pcap", "craft-pcraft-bundle", "craft-pcraft-format", @@ -2275,6 +2278,7 @@ version = "0.1.0" dependencies = [ "craft-ai-agents", "craft-atomic", + "craft-control-protocol", "craft-flags", "dirs", "getrandom 0.3.4", @@ -2567,6 +2571,14 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-ease" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "craft-ecproj-format" version = "0.1.0" @@ -3563,6 +3575,7 @@ dependencies = [ "craft-pbr", "craft-texture", "glam 0.30.10", + "naga", "rayon", "thiserror 2.0.21", ] diff --git a/Cargo.toml b/Cargo.toml index 2a177a9b59..0782449467 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -102,6 +102,7 @@ craft-deckcraft-format = { path = "crates/deckcraft-format" } craft-designcraft-format = { path = "crates/designcraft-format" } craft-dxf = { path = "crates/dxf" } craft-drawingml = { path = "crates/drawingml" } +craft-ease = { path = "crates/ease" } craft-eps = { path = "crates/eps" } craft-elf = { path = "crates/elf" } craft-file-formats = { path = "crates/file-formats" } diff --git a/NOTICE b/NOTICE index 78b8fdbfe6..a2cbbb811e 100644 --- a/NOTICE +++ b/NOTICE @@ -229,6 +229,26 @@ The colour management module in crates/cms is extracted from: Licensed MIT OR Apache-2.0. Its generated ICC profile is dedicated to the public domain (CC0-1.0); see ATTRIBUTION.md. +The image-based lighting in crates/pbr (craft-pbr) is adapted from: +- TextureCraft, crates/render/src/ibl.rs, revision fe8ee1bdb0243335560d3e726633cc0433ee99fc, + copied without its tests to crates/pbr/tests/it/reference/texturecraft.rs. + https://github.com/storytold/texturecraft + Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors. +- MaterialCraft, crates/render/src/ibl.rs, revision 4ff5af9af7371613ee37b186e03caf49ee6dbd88, + whose differing parts are copied to crates/pbr/tests/it/reference/materialcraft.rs. + https://github.com/storytold/materialcraft + Copyright (c) 2026 ArtCraft Team and the MaterialCraft contributors. +The BRDF, environment BRDF and default environment in crates/pbr are adapted from: +- EffectCraft, crates/render/src/three_d/adv/shade.rs and adv/scene.rs, revision + 41da144555a1c8ddbbe94876a00259832322d00c, whose shading functions and default environment + are copied to crates/pbr/tests/it/reference/effectcraft.rs. + https://github.com/storytold/effectcraft + Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors. +The WGSL text in crates/pbr/src/shade.wgsl is adapted from: +- EffectCraft, crates/gpu/src/shaders/advanced3d.wgsl, revision + f4d45dfef3a280d96aff1d4eb5f1950160adefc2 (above). +All four sources are licensed MIT OR Apache-2.0. crates/pbr/README.md lists the changes from them. + Optional PDF writer Krilla 0.8.2 (https://github.com/LaurenzV/krilla), MIT OR Apache-2.0. diff --git a/README.md b/README.md index b80d6074a5..f9aabaf166 100644 --- a/README.md +++ b/README.md @@ -129,6 +129,10 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit EMU units and `a:xfrm`, colours with theme slots and colour transforms, preset shape outlines (`a:prstGeom`), custom geometry with guide formulas (`a:custGeom`) and preset text warps (`a:prstTxWarp`). From DeckCraft. Takes `craft-xml` trees; packages stay with each format. +- [`craft-ease`](crates/ease/README.md): easing curves, keyed tracks, constant-speed motion paths + and damped springs for animation: named eases, CSS `cubic-bezier()`, speed and influence, + editable custom and sampled curves, hold keys and a spring stepped by its exact solution. + From AniCraft and EffectCraft. No dependencies without the optional `serde` feature. - [`craft-elf`](crates/elf/src/lib.rs): ELF program headers and dynamic section entries from untrusted bytes, from Craft Anything: 32- or 64-bit in either byte order, bounded counts and overflow-checked offsets, virtual-address-to-file mapping through `PT_LOAD`, and segment, permission and dynamic tag names. - [`craft-eps`](crates/eps/README.md): Encapsulated PostScript files as a container: the binary preview header (read and write), the DSC header comments and bounding boxes (also `(atend)`), diff --git a/crates/audio-dsp/README.md b/crates/audio-dsp/README.md index fce5926b91..ce6724bb8e 100644 --- a/crates/audio-dsp/README.md +++ b/crates/audio-dsp/README.md @@ -12,7 +12,8 @@ and contains no `unsafe` code. (compressor, expander and gate, limiter, maximizer, multiband and tube-modeled compressors), delays and reverbs (including convolution and surround), modulation, restoration (denoise, dehum, click remover, de-esser, de-reverb, speech enhancement), channel tools, distortion, - dither, a signal generator and a loudness meter. + dither, a signal generator, a loudness meter, and a pitch shifter for a live voice with 10 ms + of latency. - `loudness`: an ITU-R BS.1770-4 / EBU R128 meter with momentary, short-term and integrated loudness, loudness range (EBU Tech 3342), sample peak and true peak. - `pan`: stereo pan laws, a surround panner over any layout of up to 16 speakers, and first-order @@ -76,6 +77,9 @@ The crate combines two crates from the ArtCraft apps, with changes: `648ed9db9a0e98cc55643babffac381521a556c8`: the tail length, offline mode, events, saved state and editor parts of the trait, the maximizer, dither, panning, the signal generator and the offline resampler. +- [storytold/soundcraft](https://github.com/storytold/soundcraft) `crates/dsp` at + `915481be1b49d7e0502e07b059d0c0198c61911a`: the two crossfaded read taps of the voice pitch + shifter (`src/plugins/pitch.rs`) and its YIN pitch tracker (`src/pitch_detect.rs`). `NOTICE` keeps the copyright notices of both projects. diff --git a/crates/audio-dsp/src/effects.rs b/crates/audio-dsp/src/effects.rs index 679b7c5f9a..42ec2261ce 100644 --- a/crates/audio-dsp/src/effects.rs +++ b/crates/audio-dsp/src/effects.rs @@ -17,6 +17,7 @@ pub(crate) mod special; mod stft; pub(crate) mod time; pub(crate) mod util; +pub(crate) mod voice; pub(crate) use channel::{Amplify, Balance, ChannelVolume, Invert, Route, Routing}; pub(crate) use declick::ClickRemover; @@ -35,6 +36,7 @@ pub(crate) use reverbs::{ConvolutionReverb, SurroundReverb}; pub use special::LoudnessMeterFx; pub(crate) use special::{AmbisonicsPanner, Binauralizer, ChannelMixer, Distortion, GuitarSuite, Mastering, Mute, StereoExpander, VocalEnhancer}; pub(crate) use time::{Delay, Reverb}; +pub use voice::VoicePitch; use crate::{AudioEffect, ParamSpec, sane_channels, sane_sample_rate}; @@ -124,6 +126,7 @@ static REGISTRY: &[EffectInfo] = &[ entry!("dehum", "DeHum", Restoration, DeHum), entry!("denoise", "DeNoise", Restoration, DeNoise), entry!("pitch_shifter", "Pitch Shifter", Pitch, PitchShifter), + entry!("voice_pitch", "Voice Pitch", Pitch, VoicePitch), entry!("deesser", "DeEsser", Restoration, DeEsser), entry!("dereverb", "DeReverb", Restoration, DeReverb), entry!("speech_enhance", "Enhance Speech", Filter, SpeechEnhance), diff --git a/crates/audio-dsp/src/effects/behavior_tests.rs b/crates/audio-dsp/src/effects/behavior_tests.rs index 0b6f05a802..662046f75c 100644 --- a/crates/audio-dsp/src/effects/behavior_tests.rs +++ b/crates/audio-dsp/src/effects/behavior_tests.rs @@ -147,7 +147,7 @@ fn latency_is_where_the_impulse_lands() { // settings (FFT filter / convolution / existing STFT effects). The click remover repairs a // lone impulse in silence as a click, so its latency is checked on noise by // `neutral_settings_are_delayed_identity`. - for (id, p) in [("fft_filter", vec![]), ("convolution_reverb", vec![("mix", 0.0)])] { + for (id, p) in [("fft_filter", vec![]), ("convolution_reverb", vec![("mix", 0.0)]), ("voice_pitch", vec![])] { let mut e = fx(id, &p); let lat = e.latency(); assert!(lat > 0, "{id}"); @@ -976,6 +976,7 @@ fn direct_constructors_cap_the_channel_count() { channel::Amplify, filters::FullParametricEq, pitch::PitchShifter, + voice::VoicePitch, ); } diff --git a/crates/audio-dsp/src/effects/voice.rs b/crates/audio-dsp/src/effects/voice.rs new file mode 100644 index 0000000000..af487cdbbb --- /dev/null +++ b/crates/audio-dsp/src/effects/voice.rs @@ -0,0 +1,575 @@ +//! Voice pitch shifter for live use: two read taps sweep through a short delay line and crossfade +//! (sin² and cos² gains), so the output moves by the pitch ratio with a latency of 10 ms. +//! +//! The taps sit half a sweep apart and are centered on the latency, so the delay of each one +//! stays within `latency ± spacing`. A pitch tracker (YIN, on a copy of the input low-passed and +//! decimated to about 12 kHz, over the last 42.7 ms of history) sets the spacing to a whole number +//! of periods whenever one tap passes the center, so the two taps read the same point of a +//! period and a voiced sound crossfades without beating. A period longer than the room inside the +//! latency (below about 100 Hz), and unvoiced input, use the widest spacing that fits; below +//! 100 Hz each crossfade then steps the phase of the voice, which can move its pitch by a few +//! hertz (5 Hz for 85 Hz shifted up 5 semitones). At a shift +//! of 0 the effect crossfades over 20 ms to the input delayed by the latency, so a neutral setting +//! is a plain delay. + +use crate::biquad::{Biquad, Coeffs, FilterType}; +use crate::{AudioEffect, ParamSpec, ParamValues, Unit, block_len, flush32, param_plumbing}; +use std::f64::consts::PI; + +/// Latency, and the most a tap may read either side of it. +const LATENCY_MS: f32 = 10.0; +/// Lowest and highest fundamental the tracker reports. +const MIN_HZ: f32 = 70.0; +const MAX_HZ: f32 = 1000.0; +/// Rate the tracker analyzes at, before rounding to a whole decimation factor. +const TRACK_RATE: f32 = 12_000.0; +/// YIN's threshold on the cumulative mean normalized difference. +const THRESHOLD: f32 = 0.15; +/// Length of the crossfade to and from the plain delay at a shift of 0. +const BYPASS_MS: f32 = 20.0; +/// Samples kept between a tap and the newest sample, for the cubic interpolation. +const MARGIN: f64 = 2.0; +/// Largest step of the sweep phase per sample; one step never crosses two tap boundaries. +const MAX_STEP: f64 = 0.45; +/// Analysis input is clipped to this level, so a huge sample cannot overflow the tracker. +const TRACK_CLIP: f64 = 1.0e4; + +/// Fundamental period of the recent input, from YIN (de Cheveigné and Kawahara, 2002) run on a +/// low-passed, decimated copy. Every buffer is sized at creation. +/// +/// It keeps two copies: the mean of the channels, and the first channel alone. A frame whose +/// mean holds less than a quarter of the first channel's energy (channels of opposite polarity +/// cancel in the mean) is analyzed on the first channel. +#[derive(Clone, Debug)] +struct Tracker { + /// Input samples per analysis sample. + factor: usize, + count: usize, + coeffs: [Coeffs; 2], + feeds: [Feed; 2], + at: usize, + hop: usize, + since: usize, + frame: Vec, + diff: Vec, + min_tau: usize, + max_tau: usize, + /// Period in input samples, or `None` when the last frame was unvoiced. + period: Option, +} + +impl Tracker { + fn new(sample_rate: f32) -> Self { + let factor = (sample_rate / TRACK_RATE).round().max(1.0) as usize; + let rate = sample_rate / factor as f32; + let max_hz = MAX_HZ.min(rate / 4.0); + let min_tau = ((rate / max_hz).floor() as usize).max(2); + let max_tau = (rate / MIN_HZ).ceil() as usize + 1; + let len = (2 * max_tau + 2).next_power_of_two(); + // Fourth-order Butterworth low-pass at a quarter of the analysis rate. + let (sr, fc) = (sample_rate as f64, rate as f64 / 4.0); + let coeffs = [0.541_196_1, 1.306_563].map(|q| Coeffs::design(FilterType::LowPass, sr, fc, q, 0.0)); + Tracker { + factor, + count: 0, + coeffs, + feeds: [Feed::new(len), Feed::new(len)], + at: 0, + hop: len / 4, + since: 0, + frame: vec![0.0; len], + diff: vec![0.0; max_tau + 2], + min_tau, + max_tau, + period: None, + } + } + + fn reset(&mut self) { + self.count = 0; + self.feeds.iter_mut().for_each(Feed::reset); + self.at = 0; + self.since = 0; + self.period = None; + } + + /// Takes one input sample, as the mean of the channels and the first channel; runs an + /// analysis every `hop` analysis samples. + fn push(&mut self, mean: f32, first: f32) { + let clipped = [mean, first].map(|x| (x as f64).clamp(-TRACK_CLIP, TRACK_CLIP)); + for (feed, x) in self.feeds.iter_mut().zip(clipped) { + feed.filter(&self.coeffs, x); + } + self.count += 1; + if self.count < self.factor { + return; + } + self.count = 0; + let mask = self.frame.len() - 1; + for feed in &mut self.feeds { + feed.ring[self.at] = feed.last as f32; + } + self.at = (self.at + 1) & mask; + self.since += 1; + if self.since >= self.hop { + self.since = 0; + self.analyze(); + } + } + + fn analyze(&mut self) { + let [mean, first] = [0, 1].map(|f| self.feeds[f].ring.iter().map(|v| v * v).sum::()); + let feed = if mean < 0.25 * first { &self.feeds[1] } else { &self.feeds[0] }; + let mask = self.frame.len() - 1; + for (i, v) in self.frame.iter_mut().enumerate() { + *v = feed.ring[(self.at + i) & mask]; + } + self.period = yin(&self.frame, &mut self.diff, self.min_tau, self.max_tau).map(|t| t * self.factor as f64); + } + + /// Tap spacing for the current period: the most whole periods that fit in `max`, or `max` + /// itself for unvoiced input and for a period longer than `max`. + fn spacing(&self, max: f64) -> f64 { + match self.period { + Some(t) if t <= max => (max / t).floor() * t, + _ => max, + } + } +} + +/// One low-passed, decimated copy of the input that the tracker can analyze. +#[derive(Clone, Debug)] +struct Feed { + lowpass: [Biquad; 2], + /// The newest low-passed sample, kept at every input sample. + last: f64, + ring: Vec, +} + +impl Feed { + fn new(len: usize) -> Self { + Feed { lowpass: [Biquad::new(), Biquad::new()], last: 0.0, ring: vec![0.0; len] } + } + + fn reset(&mut self) { + self.lowpass.iter_mut().for_each(Biquad::reset); + self.last = 0.0; + self.ring.iter_mut().for_each(|v| *v = 0.0); + } + + fn filter(&mut self, coeffs: &[Coeffs; 2], x: f64) { + let y = self.lowpass[0].tick(&coeffs[0], x); + self.last = self.lowpass[1].tick(&coeffs[1], y); + } +} + +/// YIN on `frame`: the lag in samples, with parabolic interpolation, or `None` when no lag in +/// `min_tau..max_tau` falls below the threshold. `diff` holds at least `max_tau + 1` values. +fn yin(frame: &[f32], diff: &mut [f32], min_tau: usize, max_tau: usize) -> Option { + let w = frame.len().checked_sub(max_tau)?; + if max_tau <= min_tau + 2 || diff.len() <= max_tau || w == 0 { + return None; + } + difference(frame, &mut diff[..=max_tau], w); + normalize(&mut diff[..=max_tau]); + pick(&diff[..=max_tau], min_tau) +} + +/// Squared difference of the frame with itself at every lag. +fn difference(frame: &[f32], diff: &mut [f32], w: usize) { + diff[0] = 0.0; + for (tau, d) in diff.iter_mut().enumerate().skip(1) { + *d = frame[..w].iter().zip(&frame[tau..tau + w]).map(|(a, b)| (a - b) * (a - b)).sum(); + } +} + +/// Cumulative mean normalized difference, in place. +fn normalize(diff: &mut [f32]) { + diff[0] = 1.0; + let mut running = 0.0f32; + for (tau, d) in diff.iter_mut().enumerate().skip(1) { + running += *d; + *d = if running > 0.0 { *d * tau as f32 / running } else { 1.0 }; + } +} + +/// The first dip below the threshold, walked to its local minimum and interpolated. +fn pick(cmnd: &[f32], min_tau: usize) -> Option { + let last = cmnd.len() - 1; + let mut tau = (min_tau..last).find(|&t| cmnd[t] < THRESHOLD)?; + while tau + 1 < last && cmnd[tau + 1] < cmnd[tau] { + tau += 1; + } + let (a, b, c) = (cmnd[tau - 1] as f64, cmnd[tau] as f64, cmnd[tau + 1] as f64); + let denom = a - 2.0 * b + c; + let shift = if denom.abs() > 1e-12 { (0.5 * (a - c) / denom).clamp(-1.0, 1.0) } else { 0.0 }; + Some(tau as f64 + shift) +} + +/// Four-point cubic Hermite read of `line` at a fractional `delay` behind `pos`. `delay` is at +/// least 2 and leaves two samples in the line behind it. +#[inline] +fn read(line: &[f32], mask: usize, pos: usize, delay: f64) -> f64 { + let i = delay as usize; + let f = delay - i as f64; + let at = |k: usize| line[(pos + line.len() - k) & mask] as f64; + let (ym1, y0, y1, y2) = (at(i - 1), at(i), at(i + 1), at(i + 2)); + let c1 = 0.5 * (y1 - ym1); + let c2 = ym1 - 2.5 * y0 + 2.0 * y1 - 0.5 * y2; + let c3 = 0.5 * (y2 - ym1) + 1.5 * (y0 - y1); + ((c3 * f + c2) * f + c1) * f + y0 +} + +/// Read positions and gains of both taps for one sample. +#[derive(Clone, Copy, Debug)] +struct Taps { + wet: f64, + delay_a: f64, + gain_a: f64, + delay_b: f64, +} + +/// Pitch shifter for a live voice, 10 ms of latency (±24 semitones and ±100 cents). +pub struct VoicePitch { + pv: ParamValues, + latency: usize, + /// Widest tap spacing that keeps both taps inside the line, in samples. + max_spacing: f64, + lines: Vec>, + mask: usize, + pos: usize, + tracker: Tracker, + ratio: f64, + /// Sweep phase in `[0, 1)`: tap A is at the latency when it is 0.5, tap B when it is 0. + phase: f64, + spacing: f64, + /// Share of the shifted signal against the plain delay. + wet: f64, + wet_step: f64, +} + +impl VoicePitch { + pub const PARAMS: &'static [ParamSpec] = &[ + ParamSpec::new("semitones", "Pitch", -24.0, 24.0, 0.0, Unit::Semitones), + ParamSpec::new("cents", "Fine Tune (cents)", -100.0, 100.0, 0.0, Unit::None), + ]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let ch = crate::sane_channels(channels); + let latency = ((sample_rate * LATENCY_MS / 1000.0).round() as usize).max(4); + let len = (2 * latency + 8).next_power_of_two(); + let mut s = VoicePitch { + pv: ParamValues::new(Self::PARAMS), + latency, + max_spacing: latency as f64 - MARGIN, + lines: vec![vec![0.0; len]; ch], + mask: len - 1, + pos: 0, + tracker: Tracker::new(sample_rate), + ratio: 1.0, + phase: 0.5, + spacing: latency as f64 - MARGIN, + wet: 0.0, + wet_step: 1.0 / (sample_rate * BYPASS_MS / 1000.0).max(1.0) as f64, + }; + s.apply_params(true); + s + } + + fn apply_params(&mut self, snap: bool) { + let shift = self.pv.v("semitones") as f64 + self.pv.v("cents") as f64 / 100.0; + self.ratio = 2f64.powf(shift / 12.0); + if snap { + self.wet = self.target_wet(); + } + } + + fn target_wet(&self) -> f64 { + if self.ratio == 1.0 { 0.0 } else { 1.0 } + } + + /// Moves the crossfade and the sweep by one sample and returns where the taps read. + fn advance(&mut self) -> Taps { + let target = self.target_wet(); + self.wet = if self.wet < target { (self.wet + self.wet_step).min(target) } else { (self.wet - self.wet_step).max(target) }; + if self.wet == 0.0 { + // Fully on the plain delay: the next shift starts with tap A at the latency. + self.phase = 0.5; + self.spacing = self.max_spacing; + } else { + self.sweep(); + } + let pb = if self.phase >= 0.5 { self.phase - 0.5 } else { self.phase + 0.5 }; + let (l, s) = (self.latency as f64, self.spacing); + Taps { wet: self.wet, delay_a: l + (self.phase - 0.5) * 2.0 * s, gain_a: (PI * self.phase).sin().powi(2), delay_b: l + (pb - 0.5) * 2.0 * s } + } + + /// Advances the sweep phase. A tap whose delay changes by `1 - ratio` per sample reads the + /// input `ratio` times as fast. + fn sweep(&mut self) { + let step = ((1.0 - self.ratio) / (2.0 * self.spacing)).clamp(-MAX_STEP, MAX_STEP); + let raw = self.phase + step; + let wrapped = !(0.0..1.0).contains(&raw); + let p = raw - raw.floor(); + if wrapped || (p >= 0.5) != (self.phase >= 0.5) { + self.regrain(p, wrapped); + } else { + self.phase = p; + } + } + + /// One tap has just passed the latency and the other is silent at the end of its sweep: + /// take the tracker's spacing, and scale the centered tap's small offset so its delay does + /// not jump. + fn regrain(&mut self, p: f64, wrapped: bool) { + let new = self.tracker.spacing(self.max_spacing); + let k = self.spacing / new; + self.spacing = new; + let phase = if wrapped { + // Tap B is centered; its offset from the center is `p` (just past 0) or `p - 1`. + let u = (if p < 0.5 { p } else { p - 1.0 }) * k; + let u = u.clamp(-MAX_STEP, MAX_STEP); + if u < 0.0 { u + 1.0 } else { u } + } else { + 0.5 + ((p - 0.5) * k).clamp(-MAX_STEP, MAX_STEP) + }; + self.phase = if phase < 1.0 { phase } else { 0.0 }; + } +} + +impl AudioEffect for VoicePitch { + param_plumbing!("voice_pitch"); + fn latency(&self) -> usize { + self.latency + } + fn tail_samples(&self) -> usize { + // A tap reads up to `latency + max_spacing` samples back and the cubic read two samples + // more, which is twice the latency in all. + self.latency + } + fn reset(&mut self) { + self.lines.iter_mut().for_each(|l| l.iter_mut().for_each(|v| *v = 0.0)); + self.pos = 0; + self.tracker.reset(); + self.phase = 0.5; + self.spacing = self.max_spacing; + self.wet = self.target_wet(); + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let len = block_len(channels); + let ch = channels.len().min(self.lines.len()); + let dry_at = self.mask + 1 - self.latency; + for i in 0..len { + let mut sum = 0.0f32; + for (line, io) in self.lines.iter_mut().zip(channels.iter()) { + // A non-finite sample is stored as silence, so it never reaches the output. + let x = flush32(io[i]); + line[self.pos] = x; + sum += x; + } + let first = self.lines[0][self.pos]; + self.tracker.push(sum / ch as f32, first); + let t = self.advance(); + for (line, io) in self.lines.iter().zip(channels.iter_mut()) { + let dry = line[(self.pos + dry_at) & self.mask] as f64; + let y = if t.wet == 0.0 { + dry + } else { + let shifted = + t.gain_a * read(line, self.mask, self.pos, t.delay_a) + (1.0 - t.gain_a) * read(line, self.mask, self.pos, t.delay_b); + t.wet * shifted + (1.0 - t.wet) * dry + }; + io[i] = y.clamp(-f32::MAX as f64, f32::MAX as f64) as f32; + } + self.pos = (self.pos + 1) & self.mask; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::*; + + const SR: f32 = 48000.0; + + fn shifter(semitones: f32, cents: f32) -> VoicePitch { + let mut p = VoicePitch::new(SR, 2); + assert!(p.set_param("semitones", semitones) && p.set_param("cents", cents)); + p.reset(); + p + } + + fn run(p: &mut VoicePitch, x: &[f32]) -> Vec { + let (mut l, mut r) = (x.to_vec(), x.to_vec()); + p.process(&mut [&mut l, &mut r]); + assert_eq!(l, r, "both channels get the same shift"); + l + } + + /// One second of output after the first half second. + fn settled(y: &[f32]) -> &[f32] { + &y[SR as usize / 2..SR as usize * 3 / 2] + } + + /// Frequency of the strongest component between `lo` and `hi` Hz, to 0.01 Hz. + fn peak_hz(x: &[f32], lo: f64, hi: f64) -> f64 { + let best = |from: f64, to: f64, step: f64| { + let n = ((to - from) / step) as usize; + (0..=n) + .map(|i| from + i as f64 * step) + .max_by(|a, b| tone_amplitude(x, *a, SR as f64).total_cmp(&tone_amplitude(x, *b, SR as f64))) + .unwrap_or(from) + }; + let coarse = best(lo, hi, 0.25); + best(coarse - 0.25, coarse + 0.25, 0.01) + } + + fn cents(f: f64, want: f64) -> f64 { + 1200.0 * (f / want).log2() + } + + /// A voiced tone shifted by an octave either way, or by a fifth with a fine offset, lands on + /// the shifted frequency within 2 cents. + #[test] + fn a_shifted_tone_reads_the_shifted_frequency() { + for (f_in, semis, fine) in [(220.0, 12.0, 0.0), (220.0, -12.0, 0.0), (180.0, 7.0, 30.0), (110.0, -24.0, 0.0)] { + let mut p = shifter(semis, fine); + let y = run(&mut p, &sine(f_in, 0.5, SR as f64, SR as usize * 2, 0.0)); + let want = f_in * 2f64.powf((semis as f64 + fine as f64 / 100.0) / 12.0); + let got = peak_hz(settled(&y), want * 0.9, want * 1.1); + assert!(cents(got, want).abs() < 2.0, "{f_in} Hz {semis:+} st {fine:+} ct: {got} Hz, want {want}"); + } + } + + /// On a voiced tone the taps are spaced by whole periods, so the crossfades do not beat: + /// almost all the output is the shifted tone. + #[test] + fn a_voiced_tone_crossfades_without_beating() { + for (f_in, semis) in [(220.0, 7.0), (150.0, -5.0), (300.0, 12.0)] { + let mut p = shifter(semis, 0.0); + let y = run(&mut p, &sine(f_in, 0.5, SR as f64, SR as usize * 2, 0.0)); + let rest = beside_tone_db(&y, f_in * 2f64.powf(semis as f64 / 12.0)); + assert!(rest < -40.0, "{f_in} Hz {semis:+} st: {rest:.1} dB beside the tone"); + } + } + + /// A voice whose two channels have opposite polarity, which cancel in their mean, is still + /// tracked and crossfades without beating. + #[test] + fn opposite_polarity_channels_are_still_tracked() { + let mut p = shifter(7.0, 0.0); + let mut l = sine(220.0, 0.5, SR as f64, SR as usize * 2, 0.0); + let mut r: Vec = l.iter().map(|v| -v).collect(); + p.process(&mut [&mut l, &mut r]); + assert!(l.iter().zip(&r).all(|(a, b)| *a == -*b)); + let rest = beside_tone_db(&l, 220.0 * 2f64.powf(7.0 / 12.0)); + assert!(rest < -40.0, "{rest:.1} dB beside the tone"); + } + + /// Level of everything but the strongest component near `want`, against that component, in + /// the settled output. + fn beside_tone_db(y: &[f32], want: f64) -> f64 { + let tail = settled(y); + let tone = tone_amplitude(tail, peak_hz(tail, want * 0.98, want * 1.02), SR as f64) / std::f64::consts::SQRT_2; + db((rms(tail).powi(2) - tone * tone).max(0.0).sqrt() / tone) + } + + /// The output of a burst, shifted or not, comes from taps within the spacing of the latency: + /// nothing sounds earlier than `latency - tail` or later than `latency + tail` around it. + #[test] + fn a_shifted_burst_stays_within_the_spacing_of_the_latency() { + for semis in [0.0, -24.0, -3.0, 5.0, 24.0] { + let mut p = shifter(semis, 0.0); + let (n, at, len) = (8000, 1777, 1000); + let mut rng = Rng::new(7); + let mut x = vec![0.0f32; n]; + x[at..at + len].iter_mut().for_each(|v| *v = 0.5 * rng.uniform()); + let y = run(&mut p, &x); + let reach = p.tail_samples(); + let (lo, hi) = (at + p.latency() - reach, at + len + p.latency() + reach); + assert!(y.iter().enumerate().all(|(i, v)| *v == 0.0 || (lo..hi).contains(&i)), "{semis}"); + assert!(y.iter().any(|v| v.abs() > 0.05), "{semis}: the burst is lost"); + } + } + + /// Over whole sweeps, the oldest sample either tap reads, interpolation included, lies within + /// the latency plus the tail, so a render that compensates the latency and runs the tail past + /// the end of the input keeps every sample the taps still hold. + #[test] + fn the_tail_covers_the_oldest_sample_a_tap_reads() { + for semis in [-24.0, -3.0, 5.0, 24.0] { + let mut p = shifter(semis, 0.0); + let oldest = (0..SR as usize).map(|_| p.advance()).map(|t| t.delay_a.max(t.delay_b) as usize + 2).max().unwrap_or(0); + assert!(oldest > p.latency(), "{semis}: the taps never sweep past the latency"); + assert!(oldest <= p.latency() + p.tail_samples(), "{semis}: a tap reads {oldest} samples back"); + } + } + + /// A gliding voiced tone with a shift change part way gives the same output however the + /// stream is cut into blocks, spacing changes included. + #[test] + fn output_does_not_depend_on_how_the_stream_is_cut() { + let n = 40_000; + let x: Vec = (0..n) + .map(|i| (0.4 * (2.0 * std::f64::consts::PI * (120.0 * i as f64 / 48_000.0 + 0.6 * (i as f64 / 48_000.0).powi(2) * 200.0)).sin()) as f32) + .collect(); + let change = 17_321; + let run_cut = |sizes: &mut dyn FnMut() -> usize| { + let mut p = shifter(4.0, -20.0); + let mut y = x.clone(); + let mut pos = 0; + while pos < n { + if pos == change { + p.set_param("semitones", -9.0); + } + let mut len = sizes().min(n - pos); + if pos < change { + len = len.min(change - pos); + } + p.process(&mut [&mut y[pos..pos + len]]); + pos += len; + } + y + }; + let whole = run_cut(&mut || usize::MAX); + let mut rng = Rng::new(11); + let cut = run_cut(&mut || (rng.next_u64() % 700) as usize); + assert!(whole.iter().zip(&cut).all(|(a, b)| a.to_bits() == b.to_bits())); + } + + /// NaN, infinite and the largest finite samples in a shifted voice give finite output, and + /// the voice is still shifted afterwards. + #[test] + fn non_finite_and_huge_samples_give_finite_output() { + let mut p = shifter(-7.0, 0.0); + let mut x = sine(200.0, 0.5, SR as f64, SR as usize * 2, 0.0); + for (i, bad) in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX, -f32::MAX].into_iter().enumerate() { + x[3000 + i * 1500] = bad; + x[3001 + i * 1500] = bad; + } + let y = run(&mut p, &x); + assert!(y.iter().all(|v| v.is_finite())); + let want = 200.0 * 2f64.powf(-7.0 / 12.0); + let tail = settled(&y); + assert!(cents(peak_hz(tail, want * 0.9, want * 1.1), want).abs() < 2.0); + assert!(db(rms(tail) / (0.5 / std::f64::consts::SQRT_2)).abs() < 1.0, "level {}", rms(tail)); + } + + /// The tracker finds a voice's period down to 70 Hz and reports nothing for silence. + #[test] + fn the_tracker_reaches_70_hz() { + for f in [72.0, 110.0, 440.0, 950.0] { + let mut t = Tracker::new(SR); + for v in sine(f, 0.3, SR as f64, SR as usize / 4, 0.0) { + t.push(v, v); + } + let period = t.period.unwrap_or(0.0); + assert!((SR as f64 / period / f - 1.0).abs() < 0.005, "{f} Hz read as {} Hz", SR as f64 / period); + } + let mut t = Tracker::new(SR); + (0..SR as usize / 4).for_each(|_| t.push(0.0, 0.0)); + assert!(t.period.is_none()); + } +} diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index fba2839184..a7974a705d 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -121,7 +121,7 @@ file is committed. | R50 | Bit 5 (0x20) of the outline's line type scales the outline's width and dashes with the shape's matrix. The engine multiplies them by the square root of the matrix's area factor (VectorCraft's own value for a matrix that scales x and y differently) | S: UC `outl_scale_with_cdr7.cdr` to `outl_scale_with_cdr12.cdr`, of whose outlines only one, 3.969 mm wide, has line type 0x22 and the others 0x02 or 0x01; TDF 76771 (version 15), whose outline of line type 0x22 is 10 mm wide on a shape that the matrix stretches and skews, and whose picture draws that outline several times wider and skewed | sample (the bit; the single width for a matrix that scales x and y differently: VectorCraft's own) | | R51 | A `trfd` offsets table holds one offset more than the entries; each entry runs from its offset to the next, and the last offset is the record's end | KF L1079, L1113-L1121; S: every `trfd` of versions 4 to 25 in the sample files (25,425 records) has the extra offset, equal to the record's length | public-spec | | R52 | Byte 0 of argument 14001 is the fill's winding flag. VectorCraft reads a byte other than 0 as the nonzero fill rule, and 0 or an object without the argument as even-odd | KF L575-L583, L1047; S: the argument is 4 bytes in the sample files that carry it, with byte 0 = 1 on LT `complexshape_blackfill_nooutline` of `testset/12` and `testset/15` to `testset/25` and on objects of TDF 127576 (13) and 60026 (14), and 0 on 27 objects of TP `example.cdr` (17) | public-spec (the flag: KF; which rule each value means, and the rule without the argument: VectorCraft's own reading, and a wrong reading fills or leaves holes where a curve's subpaths overlap) | -| R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id (an ASCII letter, then three ASCII letters, digits or spaces), the next id is the first at an even distance of 2 to 64 bytes that names a chunk the reader uses or whose length keeps it inside its list (VectorCraft's own rule) | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample | +| R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id (an ASCII letter, then three ASCII letters, digits or spaces), the next id is the first at an even distance of 2 to 64 bytes that names a chunk the reader uses or whose length keeps it inside its list. When that chunk is one the reader passes over or a `page`, the reader may resume instead at a `page` chunk that starts 8 to 64 bytes after it, inside its body, is not empty, ends inside the list and, when the chunk found ends inside the list, reaches its end. It does so only when that page reads with objects and without damage in its instructions, and when walking on from the chunk found and from the page, each without this recovery and entering lists as the reader does, reaches the same position inside the same lists, or leaves the list (at its end, or at stray bytes with no chunk id after them), within 16 steps, with every chunk the reader uses that the first walk reads before then also read by the second, with its body cut at the same place (pages that read without objects aside). Of the chunks that only the second walk reads, or that it reads with its body cut at another place than the first walk does, the header or a table is used only when no other chunk of its id is read, and a page is kept only when it reads with objects and without damage in its instructions. Letters spelling `page` whose length runs past the list are checked the same way. In one read, the search for pages to resume at spends at most four times the length of the RIFF form (cut at the file's length), or 1,048,576 when that is more, counting 64 for each step of a walk and the length of each page body judged; past that, the reader resumes at the first chunk id found. It does the same when a limit stops the read of a page it judges. Pages kept this way are read after the other pages, so they spend only what the limits leave, and keep their place in the file; each is judged once more before it is read. One that a limit stops, or leaves without objects, is left out with the warning for limits; one the limits cut short is read as far as they allow, as other pages are. When the chunks that only these recoveries read make the read stop at a limit, the file is read again without the recoveries, with the warning for limits. Resuming at an inner page, at a chunk the reader passes over that is not followed by another chunk id or by the list's end, or after letters whose length runs past the list is reported as damage (this reader's own rule) | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample | | R54 | `cont`: byte 52 is the coordinate size as an ASCII digit, `4` for 32-bit coordinates and `2` for 16-bit ones (refused); bytes 64 to 72 hold an f64, the size of a coordinate unit in meters. A value that isn't above 0 and at most 1 reads as 0.1 µm (VectorCraft's own fallback) | CN "Container"; S: the nine CX files with `4` all hold 1e-7; `abydos.cmx`, `CM33.CMX`, `LIZARDS.CMX`, `output.000.cmx` and `test.cmx` hold `2` | sample | | R55 | A table (`rclr`, `rpen`, `rott`, `rdot`, `rotl`) is a u16 entry count, then one field list per entry; an instruction's body is field lists too. A field is a u8 tag, a u16 length counting its 3 header bytes, and the data; 0xff ends the list. Objects name table entries from 1 | CN "Tables"; S: every one of these tables in the nine CX files with 32-bit coordinates reads its count of entries with no bytes left | sample | | R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); S: every color of the nine CX files is model 2 in the older fields | sample (model 2), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) | diff --git a/crates/cdr/src/cmx.rs b/crates/cdr/src/cmx.rs index 4960c4b8df..9dee077b26 100644 --- a/crates/cdr/src/cmx.rs +++ b/crates/cdr/src/cmx.rs @@ -4,6 +4,8 @@ //! and outlines (R63). Text, images, rectangles, ellipses, clipping paths, other fills and lenses //! are left out with a warning. +use std::collections::BTreeSet; + use crate::bytes::{Rd, u32_at}; use crate::geometry::path_of; use crate::layout::{self, Profile}; @@ -19,6 +21,16 @@ const FORM: [u8; 4] = *b"CMX1"; const DEFAULT_UNIT: f64 = 1e-7; /// How far past a chunk that runs short the next chunk id is looked for (R53). const RESYNC: usize = 64; +/// How many steps (a chunk, or a jump over stray bytes) the reader walks on from a position it +/// could resume at, to compare it with the first chunk id found (R53). +const LOOKAHEAD: usize = 16; +/// The work counted for one step of a walk ([`walk`]) against [`PROBE_FLOOR`] (R53). +const STEP_COST: usize = 64; +/// The least work one read may spend on recoveries after stray bytes (R53), counted as +/// [`STEP_COST`] for each step of a walk and as the length of each page body judged. A read may +/// spend four times the length of the RIFF form, cut at the file's length, when that is more. Past it, the reader resumes at the +/// first chunk id found. +const PROBE_FLOOR: usize = 1 << 20; /// The chunks the reader uses (R53 to R60). const READ_IDS: [[u8; 4]; 9] = [*b"LIST", *b"cont", *b"page", *b"rclr", *b"rpen", *b"rott", *b"rdot", *b"rotl", *b"rota"]; /// The most UTF-16 units read of a layer's name; [`name`] keeps 256 of them. @@ -52,6 +64,15 @@ struct Chunk<'a> { id: [u8; 4], body: &'a [u8], start: usize, + /// Only a recovery after stray bytes reads the chunk ([`inner_page`]): the header or a table + /// is taken from it only when no other chunk of its id is read, and a page is kept only when it + /// reads with objects and without damage in its instructions. + recovered: bool, +} + +/// The first chunk of id `id` that is not recovered, or else the first recovered one. +fn first_of<'c, 'a>(chunks: &'c [Chunk<'a>], id: &[u8; 4]) -> Option<&'c Chunk<'a>> { + chunks.iter().find(|c| c.id == *id && !c.recovered).or_else(|| chunks.iter().find(|c| c.id == *id)) } /// The tables that page instructions refer to by 1-based index (R55 to R59). @@ -66,9 +87,35 @@ struct Tables { /// Line type, screen, color, arrowheads, pen and dashes. outlines: Vec>, arrowheads: Vec<(u16, u16)>, + /// Missing entries are not reported as damage: a page is read only to judge its instructions + /// ([`page_reads`]). + quiet: bool, } +/// The drawing in `bytes` (R53 to R63). When the chunks that only a recovery after stray bytes +/// reads make the read stop at a limit, the file is read again without the recovery, with the +/// warning for limits. pub(crate) fn drawing(bytes: &[u8], budget: &mut Budget) -> Result { + let fresh = budget.clone(); + match read_drawing(bytes, budget, true) { + Err(Error::Limit(_)) => { + *budget = fresh; + let mut d = read_drawing(bytes, budget, false)?; + push(&mut d.warnings, Warning::TooDeep); + Ok(d) + } + read => read, + } +} + +/// The drawing as the reader reads it when it resumes after stray bytes only at the first chunk +/// id found, never at a page inside that chunk (R53). +#[cfg(any(test, feature = "synth"))] +pub(crate) fn drawing_without_recovery(bytes: &[u8], budget: &mut Budget) -> Result { + read_drawing(bytes, budget, false) +} + +fn read_drawing(bytes: &[u8], budget: &mut Budget, recover: bool) -> Result { if !is_cmx(bytes) { return Err(Error::NotCmx); } @@ -76,8 +123,8 @@ pub(crate) fn drawing(bytes: &[u8], budget: &mut Budget) -> Result {} Some(b'2') => return Err(Error::Unsupported("CMX files with 16-bit coordinates")), @@ -86,15 +133,38 @@ pub(crate) fn drawing(bytes: &[u8], budget: &mut Budget) -> Result 0.0 && *m <= 1.0).unwrap_or(DEFAULT_UNIT); let unit = meters / 0.0254 * 72.0; let tables = Tables::read(&chunks, unit, budget, &mut warn)?; + // The pages read without the recovery go first, so that recovered pages spend only what the + // limits leave after them; the pages keep the order of the file. let mut pages = Vec::new(); - for c in chunks.iter().filter(|c| c.id == *b"page") { - pages.push(PageRead::new(&tables, unit, budget, &mut warn).read(c)?); + for c in chunks.iter().filter(|c| c.id == *b"page" && !c.recovered) { + pages.push((c.start, PageRead::new(&tables, unit, budget, &mut warn).read(c)?)); } + for c in chunks.iter().filter(|c| c.id == *b"page" && c.recovered) { + // A recovered page is judged however much the recoveries spent. One that a limit stops, + // or leaves without objects, is left out with the warning that says so; one the limits + // cut short is read as far as they allow, as the other pages are. + let read = match judgement(c, budget) { + Ok((true, false, _)) => PageRead::new(&tables, unit, budget, &mut warn).read(c), + Ok((_, _, true)) | Err(Error::Limit(_)) => { + push(&mut warn, Warning::TooDeep); + continue; + } + _ => continue, + }; + match read { + Ok(page) => pages.push((c.start, page)), + Err(Error::Limit(_)) => push(&mut warn, Warning::TooDeep), + Err(e) => return Err(e), + } + } + pages.sort_by_key(|(start, _)| *start); + let pages = pages.into_iter().map(|(_, page)| page).collect(); Ok(Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: warn }) } -/// The chunks of the file in order, those inside `LIST` chunks in place (R53). -fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec) -> Result>, Error> { +/// The chunks of the file in order, those inside `LIST` chunks in place (R53). With `recover`, the +/// reader may resume after stray bytes at a page inside the first chunk id found ([`inner_page`]). +fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec, recover: bool) -> Result>, Error> { let declared = u32_at(b, 4).and_then(|n| (n as usize).checked_add(8)).unwrap_or(b.len()); if declared > b.len() { // The file was cut short of the size its header gives. @@ -102,15 +172,23 @@ fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec) -> Resu } let end = declared.min(b.len()); let mut out = Vec::new(); - // (position, end, depth) of the lists still to walk; a list's children go before the rest of - // the list that holds it. - let mut stack = vec![(12usize, end, 0usize)]; - while let Some((mut pos, end, depth)) = stack.pop() { + // Where the chunks start that only a recovery reads ([`rejoins`]). + let mut extra = BTreeSet::new(); + // The work the recoveries may still spend ([`PROBE_FLOOR`]). + let mut left = end.saturating_mul(4).max(PROBE_FLOOR); + // (position, end, depth, recovered) of the lists still to walk; a list's children go before + // the rest of the list that holds it. + let mut stack = vec![(12usize, end, 0usize, false)]; + while let Some((mut pos, end, depth, in_recovered)) = stack.pop() { while pos.saturating_add(8) <= end { let Some(id) = Rd::at(b, pos).fourcc() else { break }; if !is_id(&id) { - match resync(b, pos, end) { - Some(next) => { + match resync(b, pos, end, depth, recover.then_some(&*budget), &mut left) { + Some((next, damaged, found)) => { + if damaged { + push(warn, Warning::Damaged); + } + extra.extend(found); pos = next; continue; } @@ -126,30 +204,38 @@ fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec) -> Resu let stop = start.saturating_add(size); if stop > end { // Stray bytes that happen to start with four letters give a length past the list: - // look for the next chunk id after them. A chunk the reader uses is kept, cut at - // the end of the list. - if !READ_IDS.contains(&id) - && let Some(next) = resync(b, pos, end) - { + // look for the next chunk id after them, and report the damage. A chunk the reader + // uses is kept, cut at the end of the list, unless it is a page that holds a page + // the reader resumes at. + push(warn, Warning::Damaged); + let resume = if !READ_IDS.contains(&id) { + resync(b, pos, end, depth, recover.then_some(&*budget), &mut left).map(|(next, _, found)| (next, found)) + } else if recover && id == *b"page" { + inner_page(b, pos, end, depth, budget, &mut left) + } else { + None + }; + if let Some((next, found)) = resume { + extra.extend(found); pos = next; continue; } - push(warn, Warning::Damaged); } let stop = stop.min(end); let next = stop.saturating_add(size & 1); + let recovered = in_recovered || extra.contains(&pos); if id == LIST { if depth >= budget.limits.depth { push(warn, Warning::TooDeep); pos = next; continue; } - stack.push((next, end, depth)); - stack.push((start + 4, stop, depth + 1)); + stack.push((next, end, depth, in_recovered)); + stack.push((start + 4, stop, depth + 1, recovered)); break; } if let Some(body) = b.get(start..stop) { - out.push(Chunk { id, body, start }); + out.push(Chunk { id, body, start, recovered }); } pos = next; } @@ -162,15 +248,199 @@ fn is_id(t: &[u8]) -> bool { matches!(t, [first, rest @ ..] if t.len() == 4 && first.is_ascii_alphabetic() && rest.iter().all(|c| c.is_ascii_alphanumeric() || *c == b' ')) } -/// Where the next chunk after `pos` lies: the first chunk id at an even distance of 2 to [`RESYNC`] -/// bytes that names a chunk the reader uses, or another chunk whose length keeps it inside the list -/// that ends at `end` (R53). -fn resync(b: &[u8], pos: usize, end: usize) -> Option { - let fits = |p: usize| u32_at(b, p + 4).and_then(|s| (p + 8).checked_add(s as usize)).is_some_and(|stop| stop <= end); - let chunk_at = |p: usize| Rd::at(b, p).fourcc().is_some_and(|id| is_id(&id) && (READ_IDS.contains(&id) || fits(p))); +/// The chunk id at `p`, when the four bytes there read as one. +fn id_at(b: &[u8], p: usize) -> Option<[u8; 4]> { + Rd::at(b, p).fourcc().filter(|id| is_id(id)) +} + +/// Where the body of the chunk at `p` ends by its length, before its pad byte. +fn chunk_stop(b: &[u8], p: usize) -> Option { + u32_at(b, p + 4).and_then(|s| (p + 8).checked_add(s as usize)) +} + +/// The first chunk id after `pos`, at an even distance of 2 to [`RESYNC`] bytes, that names a +/// chunk the reader uses or another chunk whose length keeps it inside the list that ends at `end` +/// (R53). +fn first_chunk(b: &[u8], pos: usize, end: usize) -> Option { + let fits = |p: usize| chunk_stop(b, p).is_some_and(|stop| stop <= end); + let chunk_at = |p: usize| id_at(b, p).is_some_and(|id| READ_IDS.contains(&id) || fits(p)); (pos + 2..=pos.saturating_add(RESYNC).min(end.saturating_sub(8))).step_by(2).find(|&p| chunk_at(p)) } +/// Where the next chunk after stray bytes at `pos` lies, whether the bytes passed over are +/// reported as damage, and where the chunks start that only the recovery reads (R53). It is +/// [`first_chunk`], or, with `judge` (the read's budget), a page inside that chunk ([`inner_page`]), +/// found with at most `left` work ([`PROBE_FLOOR`]). The flag is set when the reader resumes at an +/// inner page, or at a chunk it passes over that is not followed by another chunk id or by the end +/// of the list. `depth` is how many lists hold the one that ends at `end`. +fn resync(b: &[u8], pos: usize, end: usize, depth: usize, judge: Option<&Budget>, left: &mut usize) -> Option<(usize, bool, Vec)> { + let p = first_chunk(b, pos, end)?; + if let Some((k, found)) = judge.and_then(|budget| inner_page(b, p, end, depth, budget, left)) { + return Some((k, true, found)); + } + let known = id_at(b, p).is_some_and(|id| READ_IDS.contains(&id)); + let followed = chunk_stop(b, p).filter(|stop| *stop <= end).is_some_and(|stop| { + let n = stop.saturating_add((stop - p - 8) & 1); + n >= end || (n.saturating_add(8) <= end && id_at(b, n).is_some()) + }); + Some((p, !known && !followed, Vec::new())) +} + +/// A page the reader resumes at instead of the chunk at `p`, the first chunk id after stray bytes +/// or letters spelling `page` whose length runs past the list (R53). It is a page id at an even +/// distance of 8 to [`RESYNC`] bytes after `p`, inside the body of that chunk, whose length is not +/// 0, keeps it inside the list and, when the chunk at `p` ends inside the list, reaches the end of +/// that chunk. A `LIST`, the header and the tables at `p` are always kept. Walking on from `p` and +/// from the page by the reader's rule without this recovery must meet ([`rejoins`]). The first page +/// that meets is taken, with the chunks only the walk from it reads. The walks and the pages judged +/// spend `left` ([`PROBE_FLOOR`]); when it runs out, no page is taken. `depth` is how many lists +/// hold the one that ends at `end`. +fn inner_page(b: &[u8], p: usize, end: usize, depth: usize, budget: &Budget, left: &mut usize) -> Option<(usize, Vec)> { + let id = id_at(b, p)?; + if READ_IDS.contains(&id) && id != *b"page" { + return None; + } + let stop = chunk_stop(b, p).filter(|stop| *stop <= end); + let body_end = stop.unwrap_or(end); + // The chunk at `k` ends, with its pad byte, at or past the end of the chunk at `p`. + let reaches = + |k: usize| chunk_stop(b, k).is_some_and(|s| s > k + 8 && s <= end && stop.is_none_or(|stop| s.saturating_add((s - k - 8) & 1) >= stop)); + let mut found = (p + 8..=p.saturating_add(RESYNC).min(end.saturating_sub(8))) + .step_by(2) + .filter(|&k| k < body_end && id_at(b, k) == Some(*b"page") && reaches(k)) + .peekable(); + found.peek()?; + let lists = budget.limits.depth.saturating_sub(depth); + let first = walk(b, p, end, lists, left)?; + found.find_map(|k| { + let alt = walk(b, k, end, lists, left)?; + rejoins(b, &first, &alt, budget, left).map(|extra| (k, extra)) + }) +} + +/// Positions a walk through a list passes and the chunks it reads, for at most [`LOOKAHEAD`] +/// steps. +struct Walk { + /// Where the walk starts, and its place after each step: the position, and for each `LIST` + /// chunk it is inside, where that list's body ends and where the reader goes on after it. + at: Vec<(usize, Vec<(usize, usize)>)>, + /// Where each chunk the walk read starts, and where its body ends, cut at the end of the list + /// that holds it; a `LIST` chunk it enters counts by the chunks inside. + read: Vec<(usize, usize)>, + /// The walk left the list it started in: at its end, or at stray bytes with no chunk id after + /// them, where [`chunks`] stops reading that list too. + ended: bool, +} + +/// Walk the list that ends at `end` from `from` as [`chunks`] does without recovery, entering at +/// most `lists` nested `LIST` chunks as it does, and spending [`STEP_COST`] of `left` for each step; +/// `None` when `left` runs out first. +fn walk(b: &[u8], from: usize, end: usize, lists: usize, left: &mut usize) -> Option { + let mut w = Walk { at: vec![(from, Vec::new())], read: Vec::new(), ended: false }; + let mut pos = from; + let mut inside: Vec<(usize, usize)> = Vec::new(); + for _ in 0..LOOKAHEAD { + *left = left.checked_sub(STEP_COST)?; + let list_end = inside.last().map_or(end, |&(stop, _)| stop); + match step(b, pos, list_end) { + Some((next, Some(chunk))) if id_at(b, chunk) == Some(LIST) && inside.len() < lists => { + // [`chunks`] reads the list's children before the rest of the list that holds it. + let stop = chunk_stop(b, chunk).map_or(list_end, |stop| stop.min(list_end)); + inside.push((stop, next)); + pos = chunk + 12; + } + Some((next, chunk)) => { + w.read.extend(chunk.map(|c| (c, chunk_stop(b, c).map_or(list_end, |stop| stop.min(list_end))))); + pos = next; + } + None => match inside.pop() { + Some((_, after)) => pos = after, + None => { + w.ended = true; + break; + } + }, + } + w.at.push((pos, inside.clone())); + } + Some(w) +} + +/// One step of [`chunks`] without recovery at `pos`: the position after it, and where the chunk +/// it read starts when it read one; `None` when the walk ends there. +fn step(b: &[u8], pos: usize, end: usize) -> Option<(usize, Option)> { + if pos.saturating_add(8) > end { + return None; + } + let id = Rd::at(b, pos).fourcc()?; + if !is_id(&id) { + return first_chunk(b, pos, end).map(|next| (next, None)); + } + let size = u32_at(b, pos + 4).map_or(0, |s| s as usize); + let stop = (pos + 8).saturating_add(size); + if stop > end + && !READ_IDS.contains(&id) + && let Some(next) = first_chunk(b, pos, end) + { + return Some((next, None)); + } + Some((stop.min(end).saturating_add(size & 1), Some(pos))) +} + +/// Where the chunks start that the walk from an inner page `alt` reads and the walk from the first +/// chunk id `first` does not read with the same body, when the two walks meet at a place both pass (a position inside the +/// same lists) or both end, and `alt` reads at least what `first` reads until then (R53). The page +/// `alt` starts at reads with objects and without damage in its instructions. Each chunk the reader +/// uses that `first` reads before that point, `alt` reads too, with the same body, unless it is a +/// page that reads without objects. The pages judged spend `left`; when it runs out, or when the +/// read of a page judged stops, the walks do not meet. +fn rejoins(b: &[u8], first: &Walk, alt: &Walk, budget: &Budget, left: &mut usize) -> Option> { + let meet = first.at.iter().find(|q| alt.at.contains(q)).map(|(q, _)| *q).or((first.ended && alt.ended).then_some(usize::MAX))?; + let uses = |q: usize| q < meet && id_at(b, q).is_some_and(|id| READ_IDS.contains(&id)); + let used = |w: &Walk| -> Vec<(usize, usize)> { w.read.iter().copied().filter(|&(q, _)| uses(q)).collect() }; + let (kept, taken) = (used(first), used(alt)); + let (start, stop) = *alt.read.first()?; + if page_reads(b, start, stop, budget, left)? != (true, false) { + return None; + } + for &(q, stop) in kept.iter().filter(|q| !taken.contains(q)) { + // A page that reads without objects is the only chunk the walk from `alt` may leave out, + // or read with a body cut shorter by a list. + if id_at(b, q) != Some(*b"page") || page_reads(b, q, stop, budget, left)?.0 { + return None; + } + } + Some(taken.into_iter().filter(|q| !kept.contains(q)).map(|(q, _)| q).collect()) +} + +/// Whether the page chunk at `at` reads with objects, and whether its instructions read with +/// damage ([`judge_page`]); `None` when `left` does not cover its body or the read stops. +fn page_reads(b: &[u8], at: usize, end: usize, budget: &Budget, left: &mut usize) -> Option<(bool, bool)> { + let stop = chunk_stop(b, at).map_or(end, |stop| stop.min(end)); + let Some(body) = b.get(at + 8..stop) else { return Some((false, true)) }; + judge_page(&Chunk { id: *b"page", body, start: at + 8, recovered: true }, budget, left) +} + +/// Whether page `c` reads with objects, and whether its instructions read with damage. It is read +/// with empty tables whose missing entries are not reported, and with a copy of `budget` so that the +/// read's own budget is not spent. The length of its body is taken from `left` first; `None` when +/// `left` holds less, or when the read stops. +fn judge_page(c: &Chunk, budget: &Budget, left: &mut usize) -> Option<(bool, bool)> { + *left = left.checked_sub(c.body.len())?; + judgement(c, budget).ok().map(|(objects, damaged, _)| (objects, damaged)) +} + +/// Whether page `c` reads with objects, whether its instructions read with damage, and whether +/// the read left something out at one of the limits, read as [`judge_page`] reads it; the error +/// when the read stops. +fn judgement(c: &Chunk, budget: &Budget) -> Result<(bool, bool, bool), Error> { + let tables = Tables { quiet: true, ..Tables::default() }; + let mut scratch = budget.clone(); + let mut warn = Vec::new(); + let page = PageRead::new(&tables, 1.0, &mut scratch, &mut warn).read(c)?; + Ok((!page.layers.is_empty(), warn.contains(&Warning::Damaged), warn.contains(&Warning::TooDeep))) +} + /// The end of the field list at `pos` of `b`: after its 0xff, or the end of `b` when a field runs /// past it (R55). fn list_end(b: &[u8], mut pos: usize) -> usize { @@ -224,7 +494,7 @@ fn entries<'a>(d: &'a [u8], budget: &mut Budget) -> Result, Error> impl Tables { /// The first chunk of each table; a table that is missing is empty. fn read(chunks: &[Chunk], unit: f64, budget: &mut Budget, warn: &mut Vec) -> Result { - let first = |id: &[u8; 4]| chunks.iter().find(|c| c.id == *id).map_or(&[][..], |c| c.body); + let first = |id: &[u8; 4]| first_of(chunks, id).map_or(&[][..], |c| c.body); // A color record of field 10 holds a property list as a `.cdr` fill does (R56). let record = layout::for_version(1300); let mut t = Tables::default(); @@ -265,26 +535,26 @@ impl Tables { } /// Entry `index` (1-based) of `list`, or `None` with a warning when there is none. - fn get(list: &[Option], index: u16, warn: &mut Vec) -> Option { + fn get(&self, list: &[Option], index: u16, warn: &mut Vec) -> Option { let found = usize::from(index).checked_sub(1).and_then(|i| list.get(i)).cloned().flatten(); - if found.is_none() { + if found.is_none() && !self.quiet { push(warn, Warning::Damaged); } found } fn color(&self, index: u16, warn: &mut Vec) -> Color { - Tables::get(&self.colors, index, warn).unwrap_or(Color::Rgb([0.0; 3])) + self.get(&self.colors, index, warn).unwrap_or(Color::Rgb([0.0; 3])) } /// The outline of `rotl` entry `index`, or `None` when its line type draws none (R57, R58). fn outline(&self, index: u16, budget: &mut Budget, warn: &mut Vec) -> Option { - let [line, _screen, color, arrows, pen, dash] = Tables::get(&self.outlines, index, warn)?; - let (flags, caps_join) = Tables::get(&self.line_types, line, warn).unwrap_or((2, 0)); + let [line, _screen, color, arrows, pen, dash] = self.get(&self.outlines, index, warn)?; + let (flags, caps_join) = self.get(&self.line_types, line, warn).unwrap_or((2, 0)); if flags & 1 != 0 { return None; } - let width = Tables::get(&self.pens, pen, warn).unwrap_or(0.0); + let width = self.get(&self.pens, pen, warn).unwrap_or(0.0); let mut dashes = Vec::new(); if flags & 4 != 0 { let stored = usize::from(dash).checked_sub(1).and_then(|i| self.dashes.get(i)); diff --git a/crates/cdr/src/lib.rs b/crates/cdr/src/lib.rs index 5107482088..5c358d2f04 100644 --- a/crates/cdr/src/lib.rs +++ b/crates/cdr/src/lib.rs @@ -10,7 +10,7 @@ //! and status; code cites the row ids (R1 ...). Reading is bounded by [`Limits`], never recurses and does not //! panic. //! -//! [`write`] writes a [`Drawing`] as a `.cdr` file of version 15, laying out each record as the +//! [`write()`] writes a [`Drawing`] as a `.cdr` file of version 15, laying out each record as the //! reader reads it. Nothing here writes `.cmx` files. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] diff --git a/crates/cdr/src/limits.rs b/crates/cdr/src/limits.rs index bb9804557f..5ceceea8ec 100644 --- a/crates/cdr/src/limits.rs +++ b/crates/cdr/src/limits.rs @@ -74,7 +74,7 @@ impl Default for Limits { } /// The running counters of one read against its [`Limits`]. -#[derive(Debug)] +#[derive(Clone, Debug)] pub(crate) struct Budget { pub(crate) limits: Limits, inflated: usize, diff --git a/crates/cdr/src/synth_cmx.rs b/crates/cdr/src/synth_cmx.rs index c70fd8545c..309840e57f 100644 --- a/crates/cdr/src/synth_cmx.rs +++ b/crates/cdr/src/synth_cmx.rs @@ -285,3 +285,12 @@ pub fn sample() -> Vec { children.extend(tables()); riff(&children) } + +/// Read `bytes` as [`crate::read_cmx`] does, except that after stray bytes the reader resumes only +/// at the first chunk id found, never at a page inside that chunk (R53). Tests compare the two. +pub fn read_cmx_without_recovery(bytes: &[u8], limits: crate::Limits) -> Result { + if bytes.len() > limits.input { + return Err(crate::Error::Limit("input size")); + } + crate::cmx::drawing_without_recovery(bytes, &mut crate::limits::Budget::new(limits)) +} diff --git a/crates/cdr/tests/it/cmx.rs b/crates/cdr/tests/it/cmx.rs index 0067d981b7..dab5ddd08e 100644 --- a/crates/cdr/tests/it/cmx.rs +++ b/crates/cdr/tests/it/cmx.rs @@ -1,11 +1,39 @@ //! Reading synthetic `.cmx` files built from the layouts in `PROVENANCE.md` (R53 to R63), and //! hostile ones. -use craft_cdr::model::{Cap, Color, Geometry, Join, Object, Shape}; +use craft_cdr::model::{Cap, Color, Geometry, Join, Object, Page, Shape}; use craft_cdr::synth_cmx::*; -use craft_cdr::{Error, Limits, Warning, is_cdr, is_cmx, read_cmx}; +use craft_cdr::{Drawing, Error, Limits, Warning, is_cdr, is_cmx, read_cmx}; use proptest::prelude::*; +/// Read `bytes`, and check that the reader never reads less than it does when it resumes after +/// stray bytes only at the first chunk id found (R53): when that read succeeds, this one does too, +/// and every page that read holds with objects is read here unchanged and in the same order. +fn read_checked(bytes: &[u8], limits: Limits) -> Result { + read_compared(bytes, limits, |p, q| p == q) +} + +/// As [`read_checked`], except that a page only has to keep its layers and the number of objects +/// on each: a header or a table that only the recovery reads may change their colors and sizes +/// (R53). +fn read_kept(bytes: &[u8], limits: Limits) -> Result { + read_compared(bytes, limits, |p, q| { + p.layers.len() == q.layers.len() && p.layers.iter().zip(&q.layers).all(|(a, b)| a.name == b.name && a.objects.len() == b.objects.len()) + }) +} + +fn read_compared(bytes: &[u8], limits: Limits, same: fn(&Page, &Page) -> bool) -> Result { + let d = read_cmx(bytes, limits); + if let Ok(first) = read_cmx_without_recovery(bytes, limits) { + let Ok(read) = &d else { panic!("{d:?} where the first chunk id gives {first:?}") }; + let mut rest = read.pages.iter(); + for p in first.pages.iter().filter(|p| !p.layers.is_empty()) { + assert!(rest.any(|q| same(q, p)), "{p:?} is not read"); + } + } + d +} + fn shape(o: &Object) -> &Shape { match o { Object::Shape(s) => s, @@ -52,7 +80,7 @@ fn a_cmx_file_is_told_from_a_cdr_drawing() { #[test] fn pages_layers_groups_and_curves() { - let d = read_cmx(&sample(), Limits::default()).unwrap(); + let d = read_checked(&sample(), Limits::default()).unwrap(); assert_eq!(d.version, 0); assert!(d.warnings.is_empty(), "{:?}", d.warnings); assert_eq!(d.pages.len(), 1); @@ -107,7 +135,7 @@ fn layer_names_and_layers_without_objects() { end_layer(), end_page(), ]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); let page = &d.pages[0]; assert_eq!(page.size, None); // The empty layer is left out, and the UTF-16 name wins over the 8-bit one. @@ -118,7 +146,7 @@ fn layer_names_and_layers_without_objects() { #[test] fn objects_before_any_layer_get_one() { let p = page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); assert_eq!(d.pages[0].layers.len(), 1); // The layer is left unnamed, as a `.cdr` drawing's is; the importer names it by its place. assert_eq!(d.pages[0].layers[0].name, ""); @@ -134,7 +162,7 @@ fn a_page_without_a_size_takes_the_drawings_bounds() { end_layer(), end_page(), ]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); let page = &d.pages[0]; let side = 100.0 / 25.4 * 72.0; let (w, h) = page.size.unwrap(); @@ -150,7 +178,7 @@ fn curves_and_open_groups() { curve(&attrs(None, Some(1), false), &[(0, 0), (100, 0), (100, 100), (0, 100), (200, 200), (300, 200)], &[0x00, 0xc0, 0xc0, 0x84, 0x00, 0x44]); // A group the layer leaves open closes with it. let p = page(&[begin_page(None), begin_layer("L", None), begin_group(), c, end_layer()]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); let objects = &d.pages[0].layers[0].objects; let Object::Group { objects: kids, .. } = &objects[0] else { panic!("{objects:?}") }; let s = shape(&kids[0]); @@ -164,7 +192,7 @@ fn curves_and_open_groups() { #[test] fn a_curve_without_its_points_is_reported() { let p = page(&[begin_page(None), begin_layer("L", None), instr(67, &fields(&[field(1, &attrs(Some(1), None, false))])), end_layer()]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); } @@ -174,7 +202,7 @@ fn a_layer_name_too_short_to_read_in_utf_16_reads_in_8_bit() { d.extend(b"Art"); let layer = instr(11, &fields(&[field(1, &d), field(4, &[3, 0])])); let p = page(&[begin_page(None), layer, square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); assert_eq!(d.pages[0].layers[0].name, "Art"); } @@ -192,7 +220,7 @@ fn what_is_not_read_is_reported() { square(&attrs(Some(1), None, true), 0, 0, 1000), end_layer(), ]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); for w in [Warning::UnsupportedObjects, Warning::UnsupportedFills, Warning::Lenses] { assert!(d.warnings.contains(&w), "{w:?}: {:?}", d.warnings); } @@ -213,7 +241,7 @@ fn colors_of_other_models_and_missing_entries() { square(&attrs(Some(2), None, false), 0, 0, 1000), ])); children.push(table(b"rclr", &[color(7, &[1, 2, 3, 4]), color(3, &[255, 0, 0, 255])])); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert!(d.warnings.contains(&Warning::UnknownColors) && d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); let objects = &d.pages[0].layers[0].objects; assert_eq!(shape(&objects[0]).fill, Some(Color::Cmyk([1.0, 0.0, 0.0, 1.0]))); @@ -231,7 +259,7 @@ fn gray_cmy_and_rgb_colors_of_the_older_fields() { square(&attrs(Some(3), None, false), 0, 0, 1000), ])); children.push(table(b"rclr", &[color(9, &[51]), color(4, &[255, 0, 51]), color(5, &[255, 0, 0])])); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert!(d.warnings.is_empty(), "{:?}", d.warnings); let objects = &d.pages[0].layers[0].objects; // The model holds objects front to back: the RGB square, the CMY one, then the gray one. @@ -251,7 +279,7 @@ fn outline_arrowheads_are_reported() { children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(None, Some(1), false), 0, 0, 1000)])); children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rota"))); children.push(arrowheads(&[(0, 2)])); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert_eq!(d.warnings, vec![Warning::Arrowheads]); } @@ -275,7 +303,7 @@ fn a_long_instruction_and_a_jump_over_image_bytes() { .concat(); let mut children = vec![cont(b'4', 1e-7), chunk(b"page", &body)]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); // The images jumped over are not read, and the warning says so. assert_eq!(d.warnings, [Warning::UnsupportedObjects]); assert_eq!(d.pages[0].layers[0].objects.len(), 1); @@ -286,7 +314,7 @@ fn bytes_after_a_chunk_that_runs_short_are_passed_over() { let stray = vec![0x10, 0x00, 0x16, 0x00, 0x01, 0x0b, 0x00, 0x01, 0, 0, 0, 0, 0, 0, 0, 0xff]; let mut children = vec![cont(b'4', 1e-7), stray, list(b"pgls", &[page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)])])]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert!(d.warnings.is_empty(), "{:?}", d.warnings); assert_eq!(d.pages[0].layers[0].objects.len(), 1); } @@ -295,12 +323,12 @@ fn bytes_after_a_chunk_that_runs_short_are_passed_over() { fn other_byte_orders_and_coordinate_sizes_are_refused() { let mut f = sample(); f[..4].copy_from_slice(b"RIFX"); - assert_eq!(read_cmx(&f, Limits::default()), Err(Error::Unsupported("big-endian CMX files"))); + assert_eq!(read_checked(&f, Limits::default()), Err(Error::Unsupported("big-endian CMX files"))); let mut children = vec![cont(b'2', 1e-3)]; children.extend(tables()); - assert_eq!(read_cmx(&riff(&children), Limits::default()), Err(Error::Unsupported("CMX files with 16-bit coordinates"))); - assert_eq!(read_cmx(&riff(&tables()), Limits::default()), Err(Error::Damaged("CMX header"))); - assert_eq!(read_cmx(&riff(&[cont(b'9', 1e-7)]), Limits::default()), Err(Error::Damaged("CMX header"))); + assert_eq!(read_checked(&riff(&children), Limits::default()), Err(Error::Unsupported("CMX files with 16-bit coordinates"))); + assert_eq!(read_checked(&riff(&tables()), Limits::default()), Err(Error::Damaged("CMX header"))); + assert_eq!(read_checked(&riff(&[cont(b'9', 1e-7)]), Limits::default()), Err(Error::Damaged("CMX header"))); } #[test] @@ -308,7 +336,7 @@ fn a_header_without_a_usable_unit_reads_0_1_micrometers() { for meters in [0.0, -1.0, f64::NAN, 2.0] { let mut children = vec![cont(b'4', meters), page(&[begin_page(Some((2_100_000, 2_970_000)))])]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); let (w, _) = d.pages[0].size.unwrap(); assert!(near(w, 210.0 / 25.4 * 72.0), "{meters}: {w}"); } @@ -325,7 +353,7 @@ fn groups_past_the_depth_limit_are_left_out() { ins.push(end_group()); } ins.push(square(&attrs(Some(1), None, false), 0, 0, 1000)); - let d = read_cmx(&file(&[page(&ins)]), Limits { depth: 3, ..Limits::default() }).unwrap(); + let d = read_checked(&file(&[page(&ins)]), Limits { depth: 3, ..Limits::default() }).unwrap(); assert!(d.warnings.contains(&Warning::TooDeep)); // The square after the groups is still read, beside the three groups kept. let objects = &d.pages[0].layers[0].objects; @@ -346,18 +374,18 @@ fn groups_past_the_depth_limit_are_left_out() { fn counts_past_the_limits_are_bounded() { let ins: Vec> = std::iter::once(begin_page(None)).chain((0..50).map(|_| square(&attrs(Some(1), None, false), 0, 0, 1000))).collect(); let f = file(&[page(&ins)]); - let d = read_cmx(&f, Limits { objects: 10, ..Limits::default() }).unwrap(); + let d = read_checked(&f, Limits { objects: 10, ..Limits::default() }).unwrap(); assert_eq!(d.pages[0].layers[0].objects.len(), 10); assert!(d.warnings.contains(&Warning::TooDeep)); - let d = read_cmx(&f, Limits { coordinates: 12, ..Limits::default() }).unwrap(); + let d = read_checked(&f, Limits { coordinates: 12, ..Limits::default() }).unwrap(); assert_eq!(d.pages[0].layers[0].objects.len(), 2); - assert_eq!(read_cmx(&f, Limits { chunks: 20, ..Limits::default() }), Err(Error::Limit("chunk count"))); - assert_eq!(read_cmx(&f, Limits { input: 10, ..Limits::default() }), Err(Error::Limit("input size"))); + assert_eq!(read_checked(&f, Limits { chunks: 20, ..Limits::default() }), Err(Error::Limit("chunk count"))); + assert_eq!(read_checked(&f, Limits { input: 10, ..Limits::default() }), Err(Error::Limit("input size"))); let dashed = |n: u16| { let mut children = vec![cont(b'4', 1e-7)]; children.push(page(&[begin_page(None), square(&attrs(None, Some(3), false), 0, 0, 1000), square(&attrs(None, Some(3), false), 0, 0, 1000)])); children.extend(tables()); - read_cmx(&riff(&children), Limits { dashes: usize::from(n), ..Limits::default() }).unwrap() + read_checked(&riff(&children), Limits { dashes: usize::from(n), ..Limits::default() }).unwrap() }; let d = dashed(3); let o: Vec = d.pages[0].layers[0].objects.iter().map(|o| shape(o).outline.as_ref().unwrap().dashes.len()).collect(); @@ -372,7 +400,7 @@ fn a_curve_cut_short_keeps_the_points_it_holds() { let at = c.windows(2).position(|w| w == [3, 0]).unwrap(); c[at] = 9; let p = page(&[begin_page(None), c]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); assert!(d.warnings.contains(&Warning::Damaged)); assert_eq!(d.pages[0].layers[0].objects.len(), 1); } @@ -387,7 +415,7 @@ fn a_curve_that_lost_type_bytes_keeps_its_first_points() { } g.extend([0x0c, 0x44]); let c = instr(67, &fields(&[field(1, &attrs(None, Some(1), false)), field(2, &g)])); - let d = read_cmx(&file(&[page(&[begin_page(None), c])]), Limits::default()).unwrap(); + let d = read_checked(&file(&[page(&[begin_page(None), c])]), Limits::default()).unwrap(); assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); let Geometry::Path(p) = &shape(&d.pages[0].layers[0].objects[0]).geometry else { panic!() }; let side = 100.0 / 25.4 * 72.0; @@ -403,14 +431,14 @@ fn a_file_cut_short_of_its_declared_size_is_reported() { let mut f = file(&[]); let declared = (f.len() as u32 - 8 + 100).to_le_bytes(); f[4..8].copy_from_slice(&declared); - let d = read_cmx(&f, Limits::default()).unwrap(); + let d = read_checked(&f, Limits::default()).unwrap(); assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); } #[test] fn a_page_that_ends_inside_an_instruction_is_reported() { let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), vec![1, 0]]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); assert_eq!(d.pages[0].layers[0].objects.len(), 1); } @@ -420,7 +448,7 @@ fn a_chunk_64_bytes_past_stray_bytes_is_found() { let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); let mut children = vec![cont(b'4', 1e-7), [vec![1u8; 64], p].concat()]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert_eq!(d.pages.len(), 1); assert_eq!(d.pages[0].layers[0].objects.len(), 1); } @@ -432,7 +460,687 @@ fn stray_letters_with_a_length_past_the_file_are_passed_over() { let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); let mut children = vec![cont(b'4', 1e-7), [stray, p].concat()]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +/// Stray bytes, then letters whose length covers exactly the page chunk after them, then the page. +fn page_inside_stray_letters(stray: &[u8]) -> Vec { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = stray.to_vec(); + b.extend(b"abcd"); + b.extend((p.len() as u32).to_le_bytes()); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + riff(&children) +} + +#[test] +fn after_stray_letters_the_page_is_preferred_to_letters_that_hold_it() { + let mut stray = b"wxyz".to_vec(); + stray.extend(0xFFFF_FF00u32.to_le_bytes()); + let d = read_checked(&page_inside_stray_letters(&stray), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_the_page_is_preferred_to_letters_that_hold_it() { + let d = read_checked(&page_inside_stray_letters(&[1, 1]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn letters_64_bytes_past_stray_bytes_do_not_hide_the_page_they_hold() { + let d = read_checked(&page_inside_stray_letters(&[1; 64]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_page_after_three_page_headers_that_do_not_read_inside_letters_is_read() { + // Stray bytes, then letters whose length covers three page headers that reach its end and + // whose instructions do not fit, then the page. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let len = 24 + p.len(); + let mut body = Vec::new(); + for k in 0..3 { + body.extend(b"page"); + body.extend(((len - 8 * k - 8) as u32).to_le_bytes()); + } + body.extend(p); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend((body.len() as u32).to_le_bytes()); + b.extend(body); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_recoveries_stop_once_a_read_has_spent_its_allowance() { + // Many copies of stray bytes followed by a chunk the reader passes over that holds a page: + // the first pages are read, and once the checks have spent the read's allowance the reader + // resumes at the chunk that holds each page, as it does without the recovery. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut unit = vec![1u8; 2]; + unit.extend(chunk(b"inf1", &p)); + let copies = 2000; + let mut children = vec![cont(b'4', 1e-7), unit.repeat(copies)]; + children.extend(tables()); + let f = riff(&children); + let d = read_checked(&f, Limits::default()).unwrap(); + assert!(!d.pages.is_empty() && d.pages.len() < copies, "{} of {copies} pages", d.pages.len()); + assert!(read_cmx_without_recovery(&f, Limits::default()).unwrap().pages.is_empty()); +} + +#[test] +fn after_stray_bytes_a_page_past_a_limit_is_left_out_with_a_warning() { + let f = page_inside_stray_letters(&[1, 1]); + let all = read_cmx(&f, Limits::default()).unwrap().pages.len(); + assert_eq!(all, 1); + let mut cut = 0; + for chunks in 1..200 { + let Ok(d) = read_checked(&f, Limits { chunks, ..Limits::default() }) else { continue }; + if d.pages.len() < all { + cut += 1; + assert!(d.warnings.contains(&Warning::TooDeep), "{chunks}: {:?}", d.warnings); + } + } + assert!(cut > 0); +} + +#[test] +fn a_recovered_page_spends_only_what_the_limits_leave_after_the_other_pages() { + // Stray bytes, letters whose length covers a page, the page, then another page: with room for + // one object, the last page keeps it and the warning tells of the page left out; with room for + // both, the recovered page reads first. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let q = page(&[begin_page(None), begin_layer("M", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend((p.len() as u32).to_le_bytes()); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b, q]; + children.extend(tables()); + let f = riff(&children); + let d = read_checked(&f, Limits { objects: 1, ..Limits::default() }).unwrap(); + assert_eq!(d.pages.len(), 1, "{:?}", d.pages); + let last = d.pages.last().unwrap(); + assert_eq!((last.layers[0].name.as_str(), last.layers[0].objects.len()), ("M", 1)); + assert!(d.warnings.contains(&Warning::TooDeep), "{:?}", d.warnings); + let d = read_checked(&f, Limits::default()).unwrap(); + assert_eq!(d.pages.iter().map(|p| p.layers[0].name.as_str()).collect::>(), ["L", "M"]); +} + +#[test] +fn chunks_only_a_recovery_reads_do_not_stop_a_read_that_fits_without_them() { + // A page, then letters spelling `page` whose length runs past the file and that hold another + // page and an empty chunk: at every chunk limit at which the file opens without the recovery, + // it opens with it, and where the recovered page does not fit, the warning tells of it. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let q = page(&[begin_page(None), begin_layer("M", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]); + let mut b = b"page".to_vec(); + b.extend(0xFFFF_FF00u32.to_le_bytes()); + b.extend(q); + b.extend(chunk(b"junk", &[])); + let mut children = vec![cont(b'4', 1e-7)]; + children.extend(tables()); + children.push(p); + children.push(b); + let f = riff(&children); + let names = |d: &Drawing| d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.clone()).collect::>(); + assert_eq!(names(&read_checked(&f, Limits::default()).unwrap()), ["L", "M"]); + let mut cut = 0; + for chunks in 1..200 { + let limits = Limits { chunks, ..Limits::default() }; + if read_cmx_without_recovery(&f, limits).is_err() { + continue; + } + let d = read_checked(&f, limits).unwrap(); + if names(&d) != ["L", "M"] { + cut += 1; + assert!(d.warnings.contains(&Warning::TooDeep), "{chunks}: {:?}", d.warnings); + } + } + assert!(cut > 0); +} + +#[test] +fn after_stray_bytes_a_page_is_read_when_the_chunk_found_lands_inside_a_list() { + // Stray bytes, then letters whose length ends on the header of an empty page at the end of the + // page after them. That empty page's length ends on the first page inside the list that + // follows. Walking on from the page reads the same page inside the list, so the page is read. + let (name, q) = ["Q", "Qa"] + .iter() + .map(|n| { + let carried = long_instr(-1, &[b"page".as_slice(), &12u32.to_le_bytes()].concat()); + (*n, [begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), carried].concat()) + }) + .find(|(_, body)| body.len() % 2 == 0) + .unwrap(); + let r = page(&[begin_page(None), begin_layer("R", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend((q.len() as u32).to_le_bytes()); + b.extend(chunk(b"page", &q)); + b.extend(list(b"pgls", &[r])); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + let names: Vec<&str> = d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.as_str()).collect(); + assert_eq!(names, [name, "R"]); +} + +#[test] +fn after_stray_bytes_a_page_is_not_read_when_a_list_cuts_short_the_page_both_walks_reach() { + // As above, except that the list ends after the header of the page inside it, so walking on + // from the inner page reads that page without its body. Walking on from the letters reads the + // whole page, so the reader resumes at the letters and the page keeps its square. + let (name, q) = ["Q", "Qa"] + .iter() + .map(|n| { + let carried = long_instr(-1, &[b"page".as_slice(), &12u32.to_le_bytes()].concat()); + (*n, [begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), carried].concat()) + }) + .find(|(_, body)| body.len() % 2 == 0) + .unwrap(); + let r = page(&[begin_page(None), begin_layer("R", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend((q.len() as u32).to_le_bytes()); + b.extend(chunk(b"page", &q)); + b.extend(b"LIST"); + b.extend(12u32.to_le_bytes()); + b.extend(b"pgls"); + b.extend(r); + let mut children = vec![cont(b'4', 1e-7)]; + children.extend(tables()); + children.push(b); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + let names: Vec<&str> = d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.as_str()).collect(); + assert!(!names.contains(&name), "{names:?}"); + assert_eq!(names, ["R"]); + assert_eq!(d.pages.last().unwrap().layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_page_a_list_cuts_short_only_without_the_recovery_is_judged_as_recovered() { + // Stray bytes, then letters whose length ends on the header of a list at the end of the page + // after them. The list ends after the header of the next page, so the walk from the letters + // reads that page without its body, and the walk from the page inside the letters reads the + // whole page. Only the recovery reads that whole page, and it ends inside an instruction, so the + // reader leaves it out. + let (name, q) = ["Q", "Qa"] + .iter() + .map(|n| { + let carried = long_instr(-1, &[b"LIST".as_slice(), &12u32.to_le_bytes(), b"pgls"].concat()); + (*n, [begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), carried].concat()) + }) + .find(|(_, body)| body.len() % 2 == 0) + .unwrap(); + let r = page(&[begin_page(None), begin_layer("R", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer(), vec![1, 0]]); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend((q.len() as u32 - 4).to_le_bytes()); + b.extend(chunk(b"page", &q)); + b.extend(r); + let mut children = vec![cont(b'4', 1e-7)]; + children.extend(tables()); + children.push(b); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + let names: Vec<&str> = d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.as_str()).collect(); + assert_eq!(names, [name]); +} + +#[test] +fn after_stray_bytes_a_page_whose_check_stops_at_a_limit_is_not_replaced_by_a_page_inside_it() { + // Stray bytes, then letters whose body holds the start of a page of one square. That page's last + // instruction carries the page of thirty squares that follows the letters, and ends where it + // ends. At a chunk limit that stops the check of the page of thirty squares while the check of + // the page inside the letters fits, the page inside the letters never takes its place. + let squares = (1..=30).map(|i| square(&attrs(Some(1), None, false), 0, 0, 100 * i)); + let p = page(&[begin_page(None), begin_layer("P", None)].into_iter().chain(squares).chain([end_layer()]).collect::>()); + let carried = long_instr(-1, &p); + let head = &carried[..carried.len() - p.len()]; + let q = ["Q", "Qa"] + .iter() + .map(|n| [begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer(), head.to_vec()].concat()) + .find(|body| body.len() % 2 == 0) + .unwrap(); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend((q.len() as u32 + 8).to_le_bytes()); + b.extend(b"page"); + b.extend(((q.len() + p.len()) as u32).to_le_bytes()); + b.extend(q); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7)]; + children.extend(tables()); + children.push(b); + let f = riff(&children); + let names = |d: &Drawing| d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.clone()).collect::>(); + assert_eq!(names(&read_checked(&f, Limits::default()).unwrap()), ["P"]); + for chunks in 1..200 { + if let Ok(d) = read_checked(&f, Limits { chunks, ..Limits::default() }) { + assert_eq!(names(&d), ["P"], "{chunks}: {:?}", d.warnings); + } + } +} + +/// A page that fills with color 1, then, inside a list, letters spelling `page` whose length runs +/// past the list and that hold another page and a color table of one red entry, then `after`. +fn page_and_recovered_red(after: &[Vec]) -> Vec { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let q = page(&[begin_page(None), begin_layer("M", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]); + let mut b = b"page".to_vec(); + b.extend(0xFFFF_FF00u32.to_le_bytes()); + b.extend(q); + b.extend(table(b"rclr", &[color(5, &[255, 0, 0])])); + let mut children = vec![cont(b'4', 1e-7)]; + children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rclr"))); + children.push(p); + children.push(list(b"pgls", &[b])); + children.extend(after.iter().cloned()); + riff(&children) +} + +/// The fill of the first object of each page. +fn fills(d: &Drawing) -> Vec> { + d.pages.iter().map(|p| shape(&p.layers[0].objects[0]).fill.clone()).collect() +} + +#[test] +fn a_color_table_only_the_recovery_reads_colors_every_page() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000)]); + let red = fills(&read_checked(&file(&[p]), Limits::default()).unwrap())[0].clone(); + assert!(red.is_some()); + let d = read_kept(&page_and_recovered_red(&[]), Limits::default()).unwrap(); + assert_eq!(fills(&d), [red.clone(), red]); +} + +#[test] +fn a_color_table_read_without_the_recovery_wins_over_one_only_the_recovery_reads() { + let green = table(b"rclr", &[color(5, &[0, 255, 0])]); + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000)])); + children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rclr"))); + children.push(green.clone()); + let green_fill = fills(&read_checked(&riff(&children), Limits::default()).unwrap())[0].clone(); + let d = read_checked(&page_and_recovered_red(&[green]), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 2); + assert_eq!(fills(&d), [green_fill.clone(), green_fill]); +} + +#[test] +fn after_stray_bytes_a_page_inside_a_chunk_with_more_after_it_is_not_read() { + // Stray bytes, a chunk the reader passes over that holds a page followed by another chunk, + // then the page: only the last page is read. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &[p.clone(), chunk(b"junk", &[0; 4])].concat())); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); +} + +#[test] +fn a_list_between_stray_bytes_is_read_as_a_list() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let b = [vec![1u8; 2], list(b"pgls", &[p.clone(), p]), vec![1u8; 2]].concat(); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 2); +} + +#[test] +fn after_stray_bytes_an_empty_page_header_inside_another_chunk_is_not_a_page() { + // Stray bytes, a chunk the reader passes over that holds only an empty page header, then the + // page: only the page is read. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &chunk(b"page", &[]))); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_an_empty_page_is_kept_before_the_next_page() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"page", &[])); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 2); + assert!(d.pages[0].layers.is_empty(), "{:?}", d.pages[0].layers); + assert_eq!(d.pages[1].layers[0].objects.len(), 1); +} + +#[test] +fn a_page_between_stray_bytes_is_preferred_to_letters_that_end_inside_it() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend(8u32.to_le_bytes()); + b.extend(p); + b.extend([1u8; 2]); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_page_is_preferred_to_page_letters_that_end_inside_it() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(b"page"); + b.extend(8u32.to_le_bytes()); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_page_between_stray_bytes_is_kept() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let b = [vec![1u8; 2], p, vec![1u8; 2]].concat(); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_page_header_that_ends_inside_another_chunk_is_not_a_page() { + // Stray bytes, a chunk the reader passes over whose body starts with a short page chunk, more + // stray bytes, then the page: only the last page is read. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut inner = b"page".to_vec(); + inner.extend(4u32.to_le_bytes()); + inner.extend([0; 10]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &inner)); + b.extend([1u8; 2]); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + // The chunk passed over is followed by more stray bytes, and the warning says so. + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_header_too_short_to_read_inside_another_chunk_is_passed_over() { + // Stray bytes, then a chunk the reader passes over that holds a one-byte header, then the + // header: the drawing opens with the header after it. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let first = [vec![1u8; 2], chunk(b"inf1", &chunk(b"cont", &[0]))].concat(); + let mut children = vec![first, cont(b'4', 1e-7), p]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_letters_ending_on_a_layer_name_do_not_hide_the_page() { + // Stray bytes, then letters whose length ends on the letters of a layer name inside the page + // after them, then the page. + let names = ["Background", "aBackground"]; + let (p, at) = names + .iter() + .map(|n| page(&[begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()])) + .find_map(|p| p.windows(4).position(|w| w == b"Back").filter(|at| at % 2 == 0).map(|at| (p, at))) + .unwrap(); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend((at as u32).to_le_bytes()); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_page_followed_by_a_chunk_inside_another_chunk_is_not_read_before_more_stray_bytes() { + // Stray bytes, a chunk the reader passes over that holds a page and another chunk, more stray + // bytes, then the page: only the last page is read. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &[p.clone(), chunk(b"junk", &[0; 4])].concat())); + b.extend([1u8; 2]); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); +} + +#[test] +fn after_stray_bytes_a_header_without_a_coordinate_size_inside_another_chunk_is_passed_over() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let first = [vec![1u8; 2], chunk(b"inf1", &chunk(b"cont", &[0; 60]))].concat(); + let mut children = vec![first, cont(b'4', 1e-7), p]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_table_inside_another_chunk_that_ends_inside_the_next_page_is_passed_over() { + // Stray bytes, a chunk the reader passes over that holds the start of a color table whose + // length ends inside the page after more stray bytes: the page is read. + let sq = square(&attrs(Some(1), None, false), 0, 0, 1000); + let p = page(&[begin_page(None), begin_layer("L", None), sq.clone(), sq.clone(), sq, end_layer()]); + let mut inner = b"rclr".to_vec(); + inner.extend(14u32.to_le_bytes()); + inner.extend([0; 2]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &inner)); + b.extend([1u8; 2]); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 3); +} + +#[test] +fn a_page_between_stray_bytes_is_kept_when_its_body_holds_chunk_letters() { + // A layer name near the start of the page holds a color table chunk and another chunk id. + let mut tail = b"rclr".to_vec(); + tail.extend([4, 0, 0, 0, 0, 0, 0, 0]); + tail.extend(b"junk"); + tail.extend([0; 4]); + let tail = String::from_utf8(tail).unwrap(); + let (p, at) = ["", "x"] + .iter() + .map(|pre| { + page(&[begin_page(None), begin_layer(&format!("{pre}{tail}"), None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]) + }) + .find_map(|p| p.windows(4).position(|w| w == b"rclr").filter(|at| at % 2 == 0).map(|at| (p, at))) + .unwrap(); + assert!((8..=64).contains(&at), "{at}"); + let b = [vec![1u8; 2], p, vec![1u8; 2]].concat(); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_page_too_short_for_an_instruction_inside_another_chunk_is_not_a_page() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &chunk(b"page", &[0; 2]))); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_short_page_is_not_hidden_by_a_table_inside_the_chunk_before_it() { + // Stray bytes, a chunk the reader passes over that holds the start of a color table whose + // length ends inside the short page after more stray bytes: the page is read. + let p = page(&[begin_page(None)]); + let mut inner = b"rclr".to_vec(); + inner.extend(10u32.to_le_bytes()); + inner.extend([0; 2]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &inner)); + b.extend([1u8; 2]); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); +} + +#[test] +fn a_last_page_before_stray_bytes_at_the_end_of_the_file_is_preferred_to_letters_that_end_inside_it() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(b"abcd"); + b.extend(8u32.to_le_bytes()); + b.extend(p); + b.extend([1u8; 2]); + let mut children = vec![cont(b'4', 1e-7)]; + children.extend(tables()); + children.push(b); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_page_between_stray_bytes_is_kept_when_its_body_holds_a_table_that_reaches_its_end() { + // Bytes the page's long instruction carries hold a color table whose length reaches the end + // of the page. + let sq = square(&attrs(Some(1), None, false), 0, 0, 1000); + let mut table = b"rclr".to_vec(); + let rest = [begin_layer("L", None), sq, end_layer()].concat(); + // The table's body: the rest of the long instruction (2 bytes), then the instructions after it. + table.extend(((2 + rest.len()) as u32).to_le_bytes()); + table.extend([0; 2]); + let carried = long_instr(-1, &table); + let p = page(&[begin_page(None), carried, rest]); + let at = p.windows(4).position(|w| w == b"rclr").unwrap(); + assert!(at % 2 == 0 && (8..=64).contains(&at), "{at}"); + let b = [vec![1u8; 2], p, vec![1u8; 2]].concat(); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_page_whose_first_instruction_is_empty_inside_another_chunk_is_not_a_page() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &chunk(b"page", &[0; 4]))); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_header_between_stray_bytes_is_kept_when_its_body_holds_a_table_that_reaches_its_end() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut c = cont(b'4', 1e-7); + let inner = (c.len() - 24) as u32; + c[16..20].copy_from_slice(b"rclr"); + c[20..24].copy_from_slice(&inner.to_le_bytes()); + let mut children = vec![[vec![1u8; 2], c, vec![1u8; 2]].concat(), p]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_a_table_whose_entries_do_not_fit_inside_another_chunk_is_passed_over() { + // Stray bytes, then a chunk the reader passes over that holds a color table of one entry with + // no bytes for it, then the real tables: the colors come from the real tables. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let read = |junk: &[u8]| { + let mut children = vec![cont(b'4', 1e-7), junk.to_vec()]; + children.extend(tables()); + children.push(p.clone()); + read_checked(&riff(&children), Limits::default()).unwrap() + }; + let junk = [vec![1u8; 2], chunk(b"inf1", &chunk(b"rclr", &[1, 0]))].concat(); + let d = read(&junk); + let clean = read(&[]); + assert_eq!(format!("{:?}", d.pages), format!("{:?}", clean.pages)); +} + +#[test] +fn after_stray_bytes_a_page_whose_second_instruction_is_empty_inside_another_chunk_is_not_a_page() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &chunk(b"page", &[instr(-1, &[]), vec![0; 4]].concat()))); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn after_stray_bytes_page_letters_with_a_length_past_the_list_do_not_hide_the_page() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(b"page"); + b.extend(0xFFFF_FF00u32.to_le_bytes()); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); assert_eq!(d.pages.len(), 1); assert_eq!(d.pages[0].layers[0].objects.len(), 1); } @@ -444,7 +1152,7 @@ fn a_dash_pattern_of_zero_lengths_draws_a_solid_line() { children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rdot") && !t.starts_with(b"rotl"))); children.push(table(b"rdot", &[dashes(&[0, 0])])); children.push(table(b"rotl", &[outline([3, 1, 2, 1, 1, 1])])); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert!(d.warnings.is_empty(), "{:?}", d.warnings); let o = shape(&d.pages[0].layers[0].objects[0]).outline.clone().unwrap(); assert!(o.dashes.is_empty(), "{:?}", o.dashes); @@ -462,7 +1170,7 @@ fn a_curve_field_that_lost_points_is_left_out() { g.extend(1_000_000i32.to_le_bytes()); g.extend([0x40, 0x42]); let c = instr(67, &fields(&[field(1, &attrs(Some(1), None, false)), field(2, &g)])); - let d = read_cmx(&file(&[page(&[begin_page(None), begin_layer("L", None), c])]), Limits::default()).unwrap(); + let d = read_checked(&file(&[page(&[begin_page(None), begin_layer("L", None), c])]), Limits::default()).unwrap(); assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); assert!(d.pages[0].layers.is_empty(), "{:?}", d.pages[0].layers); } @@ -476,7 +1184,7 @@ fn a_chunk_whose_id_has_a_digit_is_found_after_stray_bytes() { b.extend(p); let mut children = vec![cont(b'4', 1e-7), b]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert!(d.warnings.is_empty(), "{:?}", d.warnings); assert_eq!(d.pages.len(), 1); assert_eq!(d.pages[0].layers[0].objects.len(), 1); @@ -493,7 +1201,7 @@ fn padding_and_ids_with_impossible_lengths_are_not_taken_for_chunks() { b.extend(p); let mut children = vec![cont(b'4', 1e-7), b]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert!(d.warnings.is_empty(), "{:?}", d.warnings); assert_eq!(d.pages.len(), 1); assert_eq!(d.pages[0].layers[0].objects.len(), 1); @@ -513,7 +1221,7 @@ fn after_stray_bytes_a_chunk_the_reader_passes_over_keeps_what_it_holds() { b.extend(p); let mut children = vec![cont(b'4', 1e-7), b]; children.extend(tables()); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); assert!(d.warnings.is_empty(), "{:?}", d.warnings); assert_eq!(d.pages.len(), 1); assert_eq!(d.pages[0].layers[0].objects.len(), 1); @@ -525,7 +1233,7 @@ fn a_canvas_or_a_container_is_reported() { let mut a = attrs(Some(1), None, false); a[0] |= bit; let p = page(&[begin_page(None), begin_layer("L", None), square(&a, 0, 0, 1000), end_layer()]); - let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let d = read_checked(&file(&[p]), Limits::default()).unwrap(); assert_eq!(d.warnings, vec![Warning::UnsupportedObjects], "{bit}"); assert!(shape(&d.pages[0].layers[0].objects[0]).fill.is_some()); } @@ -536,7 +1244,7 @@ fn a_library_color_with_its_name_reads_as_a_spot_color() { let mut children = vec![cont(b'4', 1e-7)]; children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000)])); children.push(table(b"rclr", &[color_record_named(5, [0, 0, 255, 0], Some("Brick 12"))])); - let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let d = read_checked(&riff(&children), Limits::default()).unwrap(); match shape(&d.pages[0].layers[0].objects[0]).fill.clone() { Some(Color::Spot { name, tint, look }) => { assert_eq!((name.as_str(), tint), ("Brick 12", 1.0)); @@ -553,7 +1261,7 @@ proptest! { fn never_panics_on_garbage(bytes in prop::collection::vec(any::(), 0..2048)) { let mut b = b"RIFF\0\0\0\0CMX1".to_vec(); b.extend(bytes); - let _ = read_cmx(&b, Limits::default()); + let _ = read_kept(&b, Limits::default()); } #[test] @@ -563,6 +1271,6 @@ proptest! { for (at, v) in edits { b[at % n] = v; } - let _ = read_cmx(&b, Limits::default()); + let _ = read_kept(&b, Limits::default()); } } diff --git a/crates/cloud-local/README.md b/crates/cloud-local/README.md index a5006c2ca3..a3c8d53c9e 100644 --- a/crates/cloud-local/README.md +++ b/crates/cloud-local/README.md @@ -37,3 +37,16 @@ write never truncates its target in place. It writes a new sibling file and rena over the target, so the target's directory entry is replaced rather than its bytes being overwritten. A rename only ever changes one name; it does not reach through to any other name, inside the root or out, that happens to point at the same inode. + +## Concurrent saves + +A `Job::Write` checks the file's etag again just before the rename, and holds one lock for this +process from that check until the rename is done. Within one process, when two saves are made +from the same etag, the second gets `Fault::Conflict`, unless the first save left the file with an +unchanged etag (see the next paragraph). A second process writing the same folder does not take +that lock, so its save can still land between the check and the rename. A deployment that needs +the guarantee across processes needs a backend whose provider offers a conditional write. + +The etag is the file's length and modification time. On a filesystem whose timestamps are coarser +than the time between two saves, two saves of the same length can leave the same etag, and the +second save is then not refused. diff --git a/crates/cloud-local/src/lib.rs b/crates/cloud-local/src/lib.rs index 715a870842..5fca54f9b7 100644 --- a/crates/cloud-local/src/lib.rs +++ b/crates/cloud-local/src/lib.rs @@ -62,6 +62,7 @@ use std::ffi::OsStr; use std::fs; use std::io::{Read as _, Write as _}; use std::path::{Component, Path, PathBuf}; +use std::sync::Mutex; use std::sync::atomic::{AtomicU64, Ordering}; use cap_std::fs::{Dir, OpenOptions}; @@ -208,8 +209,9 @@ fn is_windows_reserved_name(name: &str) -> bool { /// outright first, because a Unix build's [`Component`] parser does not /// treat either as a separator and would wave a Windows drive letter or UNC /// prefix (`C:`, `\\server\share`) straight through as one ordinary name. A -/// Windows reserved device name is refused the same way. None of this costs -/// anything here, unlike applying it to a name `list` merely discovered. +/// Windows reserved device name is refused the same way, and so is a name +/// [`is_temp_name`] matches, which [`list`] would leave out. None of this +/// costs anything here, unlike applying it to a name `list` merely discovered. fn confine_name(name: &str) -> Result<&str, Fault> { if name.contains('\\') || name.contains(':') { return Err(Fault::Refused(format!("{name} is not a plain file name"))); @@ -217,6 +219,9 @@ fn confine_name(name: &str) -> Result<&str, Fault> { if is_windows_reserved_name(name) { return Err(Fault::Refused(format!("{name} is a reserved device name on Windows"))); } + if is_temp_name(name) { + return Err(Fault::Refused(format!("{name} is a name this backend uses for its temporary files"))); + } confine_segment(name) } @@ -252,6 +257,13 @@ fn io_fault(error: &std::io::Error) -> Fault { } } +/// Lists the files and folders in `path`. +/// +/// A regular file whose name [`is_temp_name`] matches is left out before its +/// metadata is read. Such a file is a save in progress, or one that was +/// stopped between its create and its rename, and it is not a document. +/// [`confine_name`] refuses these names for a new file. A folder or a link +/// with such a name is listed. fn list(root: &Path, path: &str) -> Result, Fault> { let rel = relative(path)?; let dir = open_root(root)?; @@ -260,8 +272,11 @@ fn list(root: &Path, path: &str) -> Result, Fault> { let mut entries = Vec::new(); for item in read { let item = item.map_err(|error| io_fault(&error))?; - let meta = item.metadata().map_err(|error| io_fault(&error))?; let name = item.file_name().to_string_lossy().into_owned(); + if is_temp_name(&name) && item.file_type().is_ok_and(|kind| kind.is_file()) { + continue; + } + let meta = item.metadata().map_err(|error| io_fault(&error))?; let id = child_path(path, &name); entries.push(Entry { room: format!("local:{id}"), @@ -322,64 +337,154 @@ fn read(root: &Path, entry: &Entry) -> Result<(Entry, Vec), Fault> { /// so a hard link sharing the target's inode keeps its own, unmodified copy: /// the rename replaces `entry.id`'s directory entry, and never reaches /// through to any other name pointing at the same inode. +/// +/// The etag is checked once before any bytes are written, and again under +/// [`WRITE_LOCK`] just before the rename. Two saves made from the same etag +/// at once otherwise both pass the check before either renames, both report +/// success, and the later rename replaces the first save without a +/// [`Fault::Conflict`]. fn write(root: &Path, entry: &Entry, bytes: &[u8]) -> Result { let rel = relative(&entry.id)?; let dir = open_root(root)?; - match dir.symlink_metadata(&rel) { - Ok(meta) if meta.is_symlink() => return Err(Fault::Refused("that path is a link, not a plain file".to_owned())), - Ok(meta) => { - if Some(etag_of(&meta)) != entry.etag { - return Err(Fault::Conflict); - } - } - Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} - Err(error) => return Err(io_fault(&error)), - } + check_unchanged(&dir, &rel, entry)?; if let Some(parent) = rel.parent() { dir.create_dir_all(parent).map_err(|error| io_fault(&error))?; } - write_replacing(&dir, &rel, bytes)?; - let meta = dir.metadata(&rel).map_err(|error| io_fault(&error))?; + let meta = write_replacing(&dir, &rel, bytes, || check_unchanged(&dir, &rel, entry))?; Ok(Entry { size: Some(meta.len()), etag: Some(etag_of(&meta)), ..entry.clone() }) } +/// Refuses a link at `rel`, and a file whose etag is no longer `entry.etag`. +/// A file that does not exist passes. +fn check_unchanged(dir: &Dir, rel: &Path, entry: &Entry) -> Result<(), Fault> { + match dir.symlink_metadata(rel) { + Ok(meta) if meta.is_symlink() => Err(Fault::Refused("that path is a link, not a plain file".to_owned())), + Ok(meta) if Some(etag_of(&meta)) != entry.etag => Err(Fault::Conflict), + Ok(_) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(io_fault(&error)), + } +} + +/// Held by [`write_replacing`] from its last check until the rename is done +/// and the new file's metadata is read, and by [`create_in_place`] from the +/// moment it creates its file until the file is complete or removed. No other +/// save in this process can change the file between a save's check and its +/// rename, a save cannot replace a file that `create_in_place` is still +/// writing, and `create_in_place` cannot remove a replacement when its own +/// write fails. The temporary file is written and synced before the lock is +/// taken, so a slow save does not hold up the others. Another process writing +/// the same folder is not covered. +static WRITE_LOCK: Mutex<()> = Mutex::new(()); + /// The next in a run of sibling temporary names, unique within this process. /// Not meant to resist a second process picking the same name; the create -/// this writes with is exclusive (`create_new`), so a collision there is -/// just retried under a new counter value rather than silently overwritten. +/// [`open_temp`] does is exclusive (`create_new`), so a collision there is +/// retried under a new counter value rather than silently overwritten. static TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0); +/// How many temporary names [`open_temp`] tries before it gives up. +const TEMP_ATTEMPTS: usize = 16; + +/// The start of every name [`temp_name`] makes. +const TEMP_PREFIX: &str = ".craft-save-"; + +/// The end of every name [`temp_name`] makes. +const TEMP_SUFFIX: &str = ".tmp"; + +/// The temporary name for process `pid`, clock part `started` and sequence +/// value `n`. [`is_temp_name`] matches every name this returns. +fn temp_name(pid: u32, started: u128, n: u64) -> String { + format!("{TEMP_PREFIX}{pid}-{started:x}-{n}{TEMP_SUFFIX}") +} + +/// Whether [`temp_name`] returns exactly `name` for some process id, clock +/// part and sequence value. The three parts are read back from `name` and +/// passed to `temp_name`, so a name the two would format differently (a +/// leading zero, an uppercase hexadecimal digit, a sign) does not match. +/// [`list`] leaves these names out. A name with only the same prefix and +/// suffix, such as `.craft-save-notes.tmp`, does not match and is listed. +fn is_temp_name(name: &str) -> bool { + let Some(middle) = name.strip_prefix(TEMP_PREFIX).and_then(|rest| rest.strip_suffix(TEMP_SUFFIX)) else { + return false; + }; + let mut parts = middle.split('-'); + let (Some(pid), Some(started), Some(n), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else { + return false; + }; + match (pid.parse::(), u128::from_str_radix(started, 16), n.parse::()) { + (Ok(pid), Ok(started), Ok(n)) => temp_name(pid, started, n) == name, + _ => false, + } +} + +/// Creates a new hidden temporary file beside `rel`, named from +/// [`TEMP_SEQUENCE`], and returns its path and handle. A name that already +/// exists (a file another process or an earlier run left) is skipped for the +/// next one, and never opened or removed. The name does not include `rel`'s +/// file name, so a file name near the filesystem's length limit still gets a +/// temporary name that fits. +fn open_temp(dir: &Dir, rel: &Path) -> Result<(PathBuf, cap_std::fs::File), Fault> { + if rel.file_name().is_none() { + return Err(Fault::Refused("that path names no file".to_owned())); + } + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + // The clock part keeps a stale file from an earlier run with the same + // process id from matching a run of names, so needing all the attempts + // takes 16 files made for this exact moment. + let started = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |since| since.as_nanos()); + #[cfg(test)] + let started = if tests::FIXED_TEMP_CLOCK.with(std::cell::Cell::get) { 0 } else { started }; + let mut last = None; + for _ in 0..TEMP_ATTEMPTS { + let temp_name = temp_name(std::process::id(), started, TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed)); + let temp_rel = match rel.parent() { + Some(parent) if !parent.as_os_str().is_empty() => parent.join(&temp_name), + _ => PathBuf::from(&temp_name), + }; + match dir.open_with(&temp_rel, &options) { + Ok(handle) => return Ok((temp_rel, handle)), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => last = Some(error), + Err(error) => return Err(io_fault(&error)), + } + } + Err(last.map_or_else(|| Fault::Unreachable("no temporary name was free".to_owned()), |error| io_fault(&error))) +} + /// Writes `bytes` to a new sibling of `rel` inside `dir`, then renames that /// sibling over `rel`. See the module docs for why: a direct write would /// truncate whatever `rel` currently names in place, and if that happens to /// be a hard link to a file outside `root`, the outside copy would be /// corrupted along with it. A rename only ever replaces `rel`'s own /// directory entry. -fn write_replacing(dir: &Dir, rel: &Path, bytes: &[u8]) -> Result<(), Fault> { - let name = rel.file_name().ok_or_else(|| Fault::Refused("that path names no file".to_owned()))?; - let mut temp_name = OsStr::new(".").to_os_string(); - temp_name.push(name); - temp_name.push(format!(".tmp-{}-{}", std::process::id(), TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed))); - let temp_rel = match rel.parent() { - Some(parent) if !parent.as_os_str().is_empty() => parent.join(&temp_name), - _ => PathBuf::from(&temp_name), - }; - let mut options = OpenOptions::new(); - options.write(true).create_new(true); - let written = (|| -> Result<(), Fault> { - let mut handle = dir.open_with(&temp_rel, &options).map_err(|error| io_fault(&error))?; - handle.write_all(bytes).map_err(|error| io_fault(&error))?; - handle.sync_all().map_err(|error| io_fault(&error)) - })(); +/// +/// `check` runs under [`WRITE_LOCK`] right before the rename; when it fails, +/// the temporary file is removed and `rel` is left as it was. Returns the +/// metadata of the file just published. +fn write_replacing(dir: &Dir, rel: &Path, bytes: &[u8], check: impl FnOnce() -> Result<(), Fault>) -> Result { + let (temp_rel, mut handle) = open_temp(dir, rel)?; + let written = handle.write_all(bytes).map_err(|error| io_fault(&error)).and_then(|()| handle.sync_all().map_err(|error| io_fault(&error))); + drop(handle); if let Err(fault) = written { let _ = dir.remove_file(&temp_rel); return Err(fault); } - if let Err(error) = dir.rename(&temp_rel, dir, rel) { + #[cfg(test)] + tests::before_lock(); + let published = { + let _serialized = WRITE_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + check().and_then(|()| { + #[cfg(test)] + tests::after_check(); + dir.rename(&temp_rel, dir, rel).map_err(|error| io_fault(&error))?; + dir.metadata(rel).map_err(|error| io_fault(&error)) + }) + }; + if published.is_err() { let _ = dir.remove_file(&temp_rel); - return Err(io_fault(&error)); } - Ok(()) + published } fn create(root: &Path, folder: &str, name: &str, bytes: &[u8]) -> Result { @@ -397,24 +502,46 @@ fn create(root: &Path, folder: &str, name: &str, bytes: &[u8]) -> Result handle, - Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { - return Err(Fault::Refused(format!("{name} already exists"))); - } + // A taken name is refused before any bytes are written. The hard link + // below is still the check that settles a race. + match dir.symlink_metadata(&rel) { + Ok(_) => return Err(Fault::Refused(format!("{name} already exists"))), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(error) => return Err(io_fault(&error)), - }; - handle.write_all(bytes).map_err(|error| io_fault(&error))?; + } + // The bytes go to a sibling temporary file first. A write that fails part + // way (a full disk, a lost share) leaves only that file, which is removed, + // so the name stays free for the next Save As instead of holding a partial + // file that makes it fail with "already exists". + let (temp_rel, mut handle) = open_temp(&dir, &rel)?; + let written = write_new(&mut handle, bytes).and_then(|()| sync_new(&handle)); drop(handle); + if let Err(fault) = written { + let _ = dir.remove_file(&temp_rel); + return Err(fault); + } + // The finished file takes `name` with a hard link, not an `exists` check + // ahead of a rename: two creates of the same name racing both see "not + // there yet" otherwise, and the second silently replaces the first. A link + // fails when the name is taken, so the loser gets an error instead of a + // chance to overwrite the winner. It also fails when `name` already exists + // as a symlink, dangling or not. + #[cfg(not(test))] + let linked = dir.hard_link(&temp_rel, &dir, &rel); + #[cfg(test)] + let linked = if tests::NO_HARD_LINKS.with(std::cell::Cell::get) { + Err(std::io::Error::other("no hard links")) + } else { + dir.hard_link(&temp_rel, &dir, &rel) + }; + let _ = dir.remove_file(&temp_rel); + match linked { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => return Err(Fault::Refused(format!("{name} already exists"))), + // A filesystem without hard links (FAT, some network shares): the + // temporary copy is gone by now, and the file is created in place. + Err(_) => create_in_place(&dir, &rel, name, bytes)?, + } let meta = dir.metadata(&rel).map_err(|error| io_fault(&error))?; let id = child_path(folder, name); Ok(Entry { @@ -432,9 +559,314 @@ fn create(root: &Path, folder: &str, name: &str, bytes: &[u8]) -> Result Result<(), Fault> { + let _writing = WRITE_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut create_options = OpenOptions::new(); + create_options.write(true).create_new(true); + let mut handle = match dir.open_with(rel, &create_options) { + Ok(handle) => handle, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => return Err(Fault::Refused(format!("{name} already exists"))), + Err(error) => return Err(io_fault(&error)), + }; + let written = write_new(&mut handle, bytes).and_then(|()| sync_new(&handle)); + drop(handle); + #[cfg(test)] + tests::in_place_finished(); + if written.is_err() { + let _ = dir.remove_file(rel); + } + written +} + +/// Syncs a file [`create`] is making. +fn sync_new(handle: &cap_std::fs::File) -> Result<(), Fault> { + #[cfg(test)] + if tests::FAIL_CREATE_SYNC.with(|countdown| { + let left = countdown.get(); + countdown.set(left.saturating_sub(1)); + left == 1 + }) { + return Err(Fault::Unreachable("no space left on device".to_owned())); + } + handle.sync_all().map_err(|error| io_fault(&error)) +} + +/// Writes the bytes of a file [`create`] is making. +fn write_new(handle: &mut cap_std::fs::File, bytes: &[u8]) -> Result<(), Fault> { + #[cfg(test)] + if tests::FAIL_CREATE_WRITE.with(|countdown| { + let left = countdown.get(); + countdown.set(left.saturating_sub(1)); + left == 1 + }) { + let half = bytes.get(..bytes.len() / 2).unwrap_or_default(); + handle.write_all(half).map_err(|error| io_fault(&error))?; + return Err(Fault::Unreachable("no space left on device".to_owned())); + } + handle.write_all(bytes).map_err(|error| io_fault(&error)) +} + #[cfg(test)] mod tests { use super::*; + use std::sync::mpsc; + + /// Run once by the next [`write`] to pass its etag check, then cleared. + type Hook = Box; + static AFTER_CHECK: Mutex> = Mutex::new(None); + + pub(super) fn after_check() { + let hook = AFTER_CHECK.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take(); + if let Some(hook) = hook { + hook(); + } + } + + /// Run once by the next [`write_replacing`] to finish its temporary file, + /// before it takes [`WRITE_LOCK`], then cleared. + static BEFORE_LOCK: Mutex> = Mutex::new(None); + + pub(super) fn before_lock() { + let hook = BEFORE_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take(); + if let Some(hook) = hook { + hook(); + } + } + + fn entry_for(id: &str) -> Entry { + Entry { + room: format!("local:{id}"), + name: id.trim_start_matches('/').to_owned(), + kind: EntryKind::File, + size: None, + modified: None, + mime: None, + etag: None, + writable: true, + shared_by: None, + path: id.to_owned(), + id: id.to_owned(), + } + } + + #[test] + fn two_saves_from_one_etag_cannot_both_pass_the_check() { + let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let root = tempfile::tempdir().unwrap(); + std::fs::write(root.path().join("Note.txt"), b"original").unwrap(); + let (read_entry, _) = read(root.path(), &entry_for("/Note.txt")).unwrap(); + + let (checked_tx, checked_rx) = mpsc::channel::<()>(); + let (go_tx, go_rx) = mpsc::channel::<()>(); + *AFTER_CHECK.lock().unwrap() = Some(Box::new(move || { + checked_tx.send(()).unwrap(); + go_rx.recv().unwrap(); + })); + + let first = { + let (root, entry) = (root.path().to_owned(), read_entry.clone()); + std::thread::spawn(move || write(&root, &entry, b"first save")) + }; + checked_rx.recv().unwrap(); + // The first save has passed its check and not yet renamed. A second + // save must not be able to reach its own check in between. + assert!(WRITE_LOCK.try_lock().is_err(), "the check and the rename must run under one lock"); + // The second save passes its early check and writes its temporary + // file before the first one renames, so only the recheck under the + // lock can refuse it. + let (ready_tx, ready_rx) = mpsc::channel::<()>(); + *BEFORE_LOCK.lock().unwrap() = Some(Box::new(move || ready_tx.send(()).unwrap())); + let second = { + let (root, entry) = (root.path().to_owned(), read_entry.clone()); + std::thread::spawn(move || write(&root, &entry, b"second save")) + }; + ready_rx.recv().unwrap(); + go_tx.send(()).unwrap(); + + assert!(first.join().unwrap().is_ok()); + assert!(matches!(second.join().unwrap(), Err(Fault::Conflict)), "the second save started from a stale etag"); + assert_eq!(std::fs::read(root.path().join("Note.txt")).unwrap(), b"first save"); + let left: Vec<_> = std::fs::read_dir(root.path()).unwrap().map(|item| item.unwrap().file_name()).collect(); + assert_eq!(left, ["Note.txt"], "the refused save's temporary file is removed"); + } + + thread_local! { + /// When set to n, the nth [`write_new`] call on this thread from now + /// writes half its bytes and fails. 0 turns it off. + pub(super) static FAIL_CREATE_WRITE: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Makes [`create`] on this thread take the path for a filesystem + /// without hard links. + pub(super) static NO_HARD_LINKS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Makes [`open_temp`] on this thread use 0 for its clock part. + pub(super) static FIXED_TEMP_CLOCK: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// When set to n, the nth [`sync_new`] call on this thread from now + /// fails. 0 turns it off. + pub(super) static FAIL_CREATE_SYNC: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Run once by [`create_in_place`] on this thread after its write and + /// sync, before it removes a failed file. + static IN_PLACE_FINISHED: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; + } + + pub(super) fn in_place_finished() { + if let Some(hook) = IN_PLACE_FINISHED.with(|hook| hook.borrow_mut().take()) { + hook(); + } + } + + #[test] + fn without_hard_links_a_failed_sync_leaves_no_file_and_keeps_a_concurrent_save() { + let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let root = tempfile::tempdir().unwrap(); + let path = root.path().to_path_buf(); + let held = std::rc::Rc::new(std::cell::Cell::new(false)); + let saver = std::rc::Rc::new(std::cell::RefCell::new(None)); + let (seen_held, seen_saver) = (held.clone(), saver.clone()); + IN_PLACE_FINISHED.with(|hook| { + *hook.borrow_mut() = Some(Box::new(move || { + seen_held.set(WRITE_LOCK.try_lock().is_err()); + // A save of the same name starts while the failed file is + // still there. It must not land before that file is removed. + *seen_saver.borrow_mut() = Some(std::thread::spawn(move || { + let dir = open_root(&path).unwrap(); + write_replacing(&dir, Path::new("Minutes.txt"), b"saved meanwhile", || Ok(())) + })); + })); + }); + NO_HARD_LINKS.with(|off| off.set(true)); + // The temporary copy syncs, then the in-place file's sync fails. + FAIL_CREATE_SYNC.with(|fail| fail.set(2)); + let failed = create(root.path(), "", "Minutes.txt", b"the whole document"); + FAIL_CREATE_SYNC.with(|fail| fail.set(0)); + NO_HARD_LINKS.with(|off| off.set(false)); + + assert!(matches!(failed, Err(Fault::Unreachable(_))), "a failed sync is a failed create: {failed:?}"); + assert!(held.get(), "the in-place file is written and removed under the write lock"); + let saver = saver.borrow_mut().take().unwrap(); + saver.join().unwrap().unwrap(); + let left: Vec<_> = std::fs::read_dir(root.path()).unwrap().map(|item| item.unwrap().file_name()).collect(); + assert_eq!(left, ["Minutes.txt"]); + assert_eq!(std::fs::read(root.path().join("Minutes.txt")).unwrap(), b"saved meanwhile", "the removal took only the failed file"); + } + + /// Held by the tests that make temporary files, so the next value of + /// [`TEMP_SEQUENCE`] is known to the test that reads it. + static TEMP_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + #[test] + fn a_stale_temporary_file_is_skipped_and_kept() { + let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let root = tempfile::tempdir().unwrap(); + let next = TEMP_SEQUENCE.load(Ordering::Relaxed); + let stale: Vec<_> = (next..next + 3).map(|n| temp_name(std::process::id(), 0, n)).collect(); + for name in &stale { + std::fs::write(root.path().join(name), b"left by an earlier run").unwrap(); + } + FIXED_TEMP_CLOCK.with(|fixed| fixed.set(true)); + let made = create(root.path(), "", "Minutes.txt", b"minutes"); + FIXED_TEMP_CLOCK.with(|fixed| fixed.set(false)); + made.unwrap(); + assert_eq!(std::fs::read(root.path().join("Minutes.txt")).unwrap(), b"minutes"); + for name in &stale { + assert_eq!(std::fs::read(root.path().join(name)).unwrap(), b"left by an earlier run", "{name} is not this call's file"); + } + } + + #[test] + fn a_listing_leaves_out_a_temporary_file_a_stopped_save_left() { + let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let root = tempfile::tempdir().unwrap(); + std::fs::create_dir(root.path().join("Archive")).unwrap(); + std::fs::write(root.path().join("Minutes.txt"), b"minutes").unwrap(); + std::fs::write(root.path().join(".craft-save-notes.tmp"), b"a person's own file").unwrap(); + let folder = temp_name(1, 2, 3); + std::fs::create_dir(root.path().join(&folder)).unwrap(); + let dir = open_root(root.path()).unwrap(); + // A save stopped after its create and before its rename leaves the + // temporary file, at the root and inside a folder. + let (at_root, handle) = open_temp(&dir, Path::new("Minutes.txt")).unwrap(); + drop(handle); + let (in_folder, handle) = open_temp(&dir, &Path::new("Archive").join("Agenda.txt")).unwrap(); + drop(handle); + assert!(root.path().join(&at_root).exists() && root.path().join(&in_folder).exists()); + + let names: Vec<_> = list(root.path(), "").unwrap().into_iter().map(|entry| entry.name).collect(); + assert_eq!(names, [".craft-save-1-2-3.tmp", "Archive", ".craft-save-notes.tmp", "Minutes.txt"], "a folder with the pattern stays listed"); + assert!(list(root.path(), "/Archive").unwrap().is_empty()); + } + + #[test] + fn a_create_refuses_a_name_a_listing_would_leave_out() { + let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let root = tempfile::tempdir().unwrap(); + let name = temp_name(1, 2, 3); + assert!(matches!(create(root.path(), "", &name, b"bytes"), Err(Fault::Refused(_)))); + assert_eq!(std::fs::read_dir(root.path()).unwrap().count(), 0); + create(root.path(), "", ".craft-save-notes.tmp", b"bytes").unwrap(); + } + + #[test] + fn is_temp_name_matches_only_the_names_temp_name_makes() { + assert!(is_temp_name(&temp_name(4242, 0x1a2b, 7))); + assert!(is_temp_name(&temp_name(u32::MAX, u128::MAX, u64::MAX))); + for other in [ + ".craft-save-notes.tmp", + ".craft-save-1-2.tmp", + ".craft-save-1-2-3-4.tmp", + ".craft-save--2-3.tmp", + ".craft-save-1-xy-3.tmp", + "craft-save-1-2-3.tmp", + ".craft-save-1-2-3.tmp.txt", + ".craft-save-01-2-3.tmp", + ".craft-save-1-2A-3.tmp", + ".craft-save-+1-2-3.tmp", + ] { + assert!(!is_temp_name(other), "{other} is not a temporary name"); + } + } + + #[test] + fn without_hard_links_a_create_still_refuses_a_taken_name_and_cleans_up() { + let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let root = tempfile::tempdir().unwrap(); + NO_HARD_LINKS.with(|off| off.set(true)); + let made = create(root.path(), "", "Minutes.txt", b"first"); + let taken = create(root.path(), "", "Minutes.txt", b"second"); + // The temporary copy is written, then the in-place write fails. + FAIL_CREATE_WRITE.with(|fail| fail.set(2)); + let failed = create(root.path(), "", "Agenda.txt", b"the whole agenda"); + FAIL_CREATE_WRITE.with(|fail| fail.set(0)); + NO_HARD_LINKS.with(|off| off.set(false)); + + assert_eq!(made.unwrap().size, Some(5)); + assert!(matches!(taken, Err(Fault::Refused(_)))); + assert!(matches!(failed, Err(Fault::Unreachable(_)))); + let left: Vec<_> = std::fs::read_dir(root.path()).unwrap().map(|item| item.unwrap().file_name()).collect(); + assert_eq!(left, ["Minutes.txt"], "only the finished file is left"); + assert_eq!(std::fs::read(root.path().join("Minutes.txt")).unwrap(), b"first"); + } + + #[test] + fn a_create_whose_write_fails_leaves_no_file_behind() { + let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let root = tempfile::tempdir().unwrap(); + FAIL_CREATE_WRITE.with(|fail| fail.set(1)); + let failed = create(root.path(), "", "Minutes.txt", b"the whole document"); + FAIL_CREATE_WRITE.with(|fail| fail.set(0)); + assert!(matches!(failed, Err(Fault::Unreachable(_)))); + assert_eq!(std::fs::read_dir(root.path()).unwrap().count(), 0, "no partial or temporary file is left"); + + let retried = create(root.path(), "", "Minutes.txt", b"the whole document").unwrap(); + assert_eq!(retried.size, Some(18)); + assert_eq!(std::fs::read(root.path().join("Minutes.txt")).unwrap(), b"the whole document"); + } #[test] fn a_parent_segment_cannot_walk_out_of_root() { diff --git a/crates/cloud-ui/src/cloud/backend.rs b/crates/cloud-ui/src/cloud/backend.rs index f92328cef2..d5479f3397 100644 --- a/crates/cloud-ui/src/cloud/backend.rs +++ b/crates/cloud-ui/src/cloud/backend.rs @@ -70,6 +70,9 @@ pub enum Event { }, } +/// An answer with the account generation its job was issued in. +pub(crate) type Stamped = (u64, Event); + /// Where a worker's answers go. /// /// Handed to [`CloudBackend::submit`] with the job it belongs to. A worker is @@ -77,7 +80,10 @@ pub enum Event { /// sign-in reports the URL it wants a browser pointed at and then reports that /// the user finished there. A send after the window closed is not a failure. pub struct Post { - tx: Sender, + /// Each event goes with the generation its job was issued in, so + /// [`super::pump`] can drop one that waited in the channel across a + /// sign-out or a new sign-in. + tx: Sender, /// The window's account generation as of the moment the job this answers /// was issued, beside a handle to what it is now. A sign-out or a new /// sign-in bumps the live value; a reply that arrives after is for a @@ -87,7 +93,7 @@ pub struct Post { } impl Post { - pub(crate) fn new(tx: Sender, generation: Arc) -> Post { + pub(crate) fn new(tx: Sender, generation: Arc) -> Post { let issued = generation.load(Ordering::Relaxed); Post { tx, generation, issued } } @@ -99,16 +105,19 @@ impl Post { Post { tx: self.tx.clone(), generation: self.generation.clone(), issued: self.issued } } - /// Delivers the event, unless the window has signed out or signed in - /// again since the job this answers was issued. Silently dropping it - /// there, rather than delivering it, is what keeps a late reply from - /// restoring the previous session's account, files or busy state on top - /// of whatever replaced it. + /// Queues the event with the generation its job was issued in. + /// + /// [`super::pump`] holds the check that keeps a late reply from restoring + /// the previous session's account, files or busy state on top of whatever + /// replaced it: it drops every event whose generation is not the current + /// one, including an event sent here just before a sign-out or a new + /// sign-in. This method only skips the send when the generation has + /// already moved on, so an answer that `pump` would drop is not queued. pub fn send(&self, event: Event) { if self.generation.load(Ordering::Relaxed) != self.issued { return; } - let _ = self.tx.send(event); + let _ = self.tx.send((self.issued, event)); } } diff --git a/crates/cloud-ui/src/cloud/conflict_tests.rs b/crates/cloud-ui/src/cloud/conflict_tests.rs index 1e22e815fe..8a1426be37 100644 --- a/crates/cloud-ui/src/cloud/conflict_tests.rs +++ b/crates/cloud-ui/src/cloud/conflict_tests.rs @@ -214,6 +214,53 @@ fn sign_out_recovers_save_after_a_backend_job_never_replies() { assert!(saved.is_ok(), "after sign-out and sign-in, Save is still refused: {saved:?}; busy={:?}", app.cloud.busy.as_ref().map(Busy::text)); } +/// While a sign-in waits on the browser, the previous account may still be the one the service +/// answers for. No folder is listed until the sign-in answers, and then both are listed again, +/// so a listing from before the sign-in does not stay on screen as the new account's files. +#[test] +fn folders_are_listed_again_only_after_a_sign_in_answers() { + let (mut app, held, _log) = two_tabs(); + let ctx = egui::Context::default(); + start(&mut app); + held.take(|j| matches!(j, Job::Account)).unwrap().1.send(Event::Account(Ok(account("Ada")))); + held.take(|j| matches!(j, Job::List(_))).unwrap().1.send(Event::Listed { path: String::new(), entries: Ok(vec![entry("/Ada.note", "a1")]) }); + drain(&mut app, &ctx); + assert!(app.cloud.mine.loaded); + + sign_in(&mut app); + start(&mut app); + drain(&mut app, &ctx); + assert!(held.take(|j| matches!(j, Job::List(_))).is_none(), "a folder is listed before the sign-in says who is signed in"); + assert!(report(&app)["entries"].as_array().is_some_and(Vec::is_empty), "the previous account's files stay on screen during sign-in"); + + held.take(|j| matches!(j, Job::SignIn)).unwrap().1.send(Event::Account(Ok(account("Grace")))); + drain(&mut app, &ctx); + assert!(!app.cloud.mine.loading && !app.cloud.mine.loaded && !app.cloud.shared.loading && !app.cloud.shared.loaded); + start(&mut app); + let (_, list_post) = held.take(|j| matches!(j, Job::List(_))).expect("the root folder is listed again once the sign-in answers"); + list_post.send(Event::Listed { path: String::new(), entries: Ok(vec![entry("/Grace.note", "g1")]) }); + drain(&mut app, &ctx); + assert_eq!(report(&app)["entries"], serde_json::json!(["Grace.note"])); +} + +/// A sign-in empties the folder the Save As page was showing. Until it answers, a save would go +/// to the root rather than the folder the user picked, so Save As refuses. +#[test] +fn save_as_waits_for_a_sign_in_to_answer() { + let (mut app, held, _log) = two_tabs(); + browse(&mut app, "/Projects"); + sign_in(&mut app); + let folder = app.cloud.mine.path.clone(); + let refused = save_as(&mut app, &folder, "B"); + assert!(refused.is_err(), "Save As went ahead during sign-in: {refused:?}"); + assert!(held.take(|j| matches!(j, Job::Create { .. })).is_none()); + + held.take(|j| matches!(j, Job::SignIn)).unwrap().1.send(Event::Account(Ok(account("Ada")))); + drain(&mut app, &egui::Context::default()); + assert!(save_as(&mut app, "", "B").is_ok()); + assert!(held.take(|j| matches!(j, Job::Create { .. })).is_some()); +} + /// An account and a listing answer a job issued before sign-out. Landing after it, they must /// not put the previous session's account and file names on screen with nobody signed in. #[test] diff --git a/crates/cloud-ui/src/cloud/mod.rs b/crates/cloud-ui/src/cloud/mod.rs index b1013a8ad4..fb3f0a5541 100644 --- a/crates/cloud-ui/src/cloud/mod.rs +++ b/crates/cloud-ui/src/cloud/mod.rs @@ -178,7 +178,8 @@ pub struct Guest { /// exists. pub struct CloudFiles { backend: Option>, - events: (Sender, Receiver), + /// Each answer with the account generation its job was issued in. + events: (Sender, Receiver), /// The badge and its menu. Signing in is the only way into any of this. /// The badge is the only control that offers it. It lives here. An /// application declares no field for it. @@ -215,9 +216,14 @@ pub struct CloudFiles { /// stay set after a failed sign-in. sign_in_from_menu: bool, /// Bumped on sign-out and on a new sign-in. Stamped onto every [`Post`] - /// handed out by [`submit`] so a reply to a job issued before the bump is - /// dropped rather than applied to the session that replaced it. + /// handed out by [`submit`] and onto every answer it queues. [`pump`] + /// drops an answer to a job issued before the bump rather than applying + /// it to the session that replaced it. account_generation: Arc, + /// Set by [`sign_in`] and cleared by the account answer that follows it. + /// While it is set both folders read as loading, so no listing is asked + /// for before the service says who is now signed in. + relist_after_sign_in: bool, /// The document Save As must act on, when it is not the active one. /// /// Set only by the conflict modal's "Save as a copy", so the copy it asks @@ -256,6 +262,7 @@ impl CloudFiles { guest: None, sign_in_from_menu: false, account_generation: Arc::new(AtomicU64::new(0)), + relist_after_sign_in: false, save_as_target: None, } } @@ -371,11 +378,17 @@ pub fn sign_in(app: &mut A) { cloud.link = None; cloud.status = Some(working); // A new session. A job the previous one left outstanding may never - // answer, and if it does, that answer is not about this account: see - // `Post::send`. Busy goes with it, or a stuck read from before this + // answer, and if it does, that answer is not about this account: `pump` + // drops it. Busy goes with it, or a stuck read from before this // sign-in would leave Save refused for a session that never asked for it. + // A folder listing that was outstanding is dropped the same way. Both + // folders wait for the account answer, which empties them so the next + // frame lists them for the account that is now signed in. cloud.account_generation.fetch_add(1, Ordering::Relaxed); cloud.busy = None; + cloud.mine = Folder { loading: true, ..Folder::default() }; + cloud.shared = Folder { loading: true, ..Folder::default() }; + cloud.relist_after_sign_in = true; submit(app, Job::SignIn); } @@ -396,26 +409,32 @@ pub fn sign_out(app: &mut A) { cloud.status = Some(signed_out); // The session this window had ends here. A job it started may never // answer, and a reply that does arrive late must not land on whatever - // comes next: see `Post::send`. Busy goes with it, so an open or a save + // comes next: `pump` drops it. Busy goes with it, so an open or a save // that never heard back does not refuse every one after it forever. cloud.account_generation.fetch_add(1, Ordering::Relaxed); cloud.busy = None; + cloud.relist_after_sign_in = false; cloud.save_as_target = None; submit(app, Job::SignOut); } /// Lists one folder. An empty path is the user's root. +/// +/// Nothing is sent while a sign-in waits for its answer. A listing sent then +/// can answer after the account does, and its files may be the previous +/// account's; the answer empties the folder so it is listed again. pub fn browse(app: &mut A, path: &str) { - if !available(app) { + if !available(app) || app.cloud().relist_after_sign_in { return; } app.cloud_mut().mine.begin(path); submit(app, Job::List(path.to_owned())); } -/// Lists what other people have shared with this user. +/// Lists what other people have shared with this user. Like [`browse`], it +/// sends nothing while a sign-in waits for its answer. pub fn load_shared(app: &mut A) { - if !available(app) { + if !available(app) || app.cloud().relist_after_sign_in { return; } app.cloud_mut().shared.begin(""); @@ -608,6 +627,9 @@ pub fn save_as(app: &mut A, folder: &str, name: &str) -> Result(app: &mut A, ctx: &egui::Context) { while let Ok(event) = app.cloud().events.1.try_recv() { arrived.push(event); } - for event in arrived { + for (issued, event) in arrived { + // A worker that sent just before a sign-out or a new sign-in passed + // `Post::send`'s check, and its answer waited here while the session + // changed. It is about the session that is gone. + if issued != app.cloud().account_generation.load(Ordering::Relaxed) { + continue; + } apply(app, event); } poll_link(app); @@ -649,6 +677,15 @@ pub fn pump(app: &mut A, ctx: &egui::Context) { fn apply(app: &mut A, event: Event) { let noun = app.kind().noun; + if matches!(event, Event::Account(_)) && app.cloud().relist_after_sign_in { + // The sign-in has answered, whether or not it succeeded. Both folders + // are emptied and not loading, so `start` and the Open page list them + // again for whoever is signed in now. + let cloud = app.cloud_mut(); + cloud.relist_after_sign_in = false; + cloud.mine = Folder::default(); + cloud.shared = Folder::default(); + } match event { Event::Account(Ok(account)) => { let linked = account.provider_linked; diff --git a/crates/cloud-ui/src/cloud/pages.rs b/crates/cloud-ui/src/cloud/pages.rs index 86e71d1c88..e969ecc28c 100644 --- a/crates/cloud-ui/src/cloud/pages.rs +++ b/crates/cloud-ui/src/cloud/pages.rs @@ -422,7 +422,9 @@ pub fn save_page(app: &mut A, ui: &mut Ui) -> bool { asked = typing.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); }); ui.add_space(10.0); - let ready = app.cloud().busy.is_none() && !document_name(&app.cloud().save_name, kind).is_empty(); + // A sign-in in progress has emptied the folder, so the destination is not + // the one the user picked until the folders are listed again. + let ready = app.cloud().busy.is_none() && !app.cloud().relist_after_sign_in && !document_name(&app.cloud().save_name, kind).is_empty(); if ui.add_enabled(ready, egui::Button::new(save_label)).clicked() { asked = true; } diff --git a/crates/cloud-ui/src/cloud/tests.rs b/crates/cloud-ui/src/cloud/tests.rs index 875612144f..82f818db01 100644 --- a/crates/cloud-ui/src/cloud/tests.rs +++ b/crates/cloud-ui/src/cloud/tests.rs @@ -197,6 +197,12 @@ fn pumped(app: &mut Notebook, ctx: &egui::Context) { ctx.end_pass().textures_delta.clear(); } +/// Puts an answer in the channel as a worker for the current session would. +fn deliver(app: &Notebook, event: Event) { + let issued = app.cloud.account_generation.load(Ordering::Relaxed); + app.cloud.events.0.send((issued, event)).unwrap(); +} + fn wired() -> (Notebook, Arc>>, egui::Context) { let mut app = Notebook::new(); let jobs = Arc::new(Mutex::new(Vec::new())); @@ -339,7 +345,7 @@ fn a_refused_save_is_put_to_the_user_and_never_retried() { pumped(&mut app, &ctx); jobs.lock().unwrap().clear(); // What a service answers when somebody else saved first. - app.cloud.events.0.send(Event::Saved { uid: 1, entry: Err(Fault::Conflict) }).unwrap(); + deliver(&app, Event::Saved { uid: 1, entry: Err(Fault::Conflict) }); pumped(&mut app, &ctx); assert_eq!(report(&app)["conflict"]["name"], "Minutes.note", "the user is told, and asked what to do"); assert_eq!(app.did().dropped, vec![1], "the version that did not land is forgotten"); @@ -349,7 +355,7 @@ fn a_refused_save_is_put_to_the_user_and_never_retried() { #[test] fn no_account_yet_is_an_offer_to_link_and_never_an_error() { let (mut app, _jobs, ctx) = wired(); - app.cloud.events.0.send(Event::Account(Err(Fault::NotLinked))).unwrap(); + deliver(&app, Event::Account(Err(Fault::NotLinked))); pumped(&mut app, &ctx); assert_eq!(report(&app)["link"], "offered"); assert_eq!(report(&app)["accountError"], serde_json::Value::Null, "not having linked an account yet is not a failure"); @@ -359,7 +365,7 @@ fn no_account_yet_is_an_offer_to_link_and_never_an_error() { #[test] fn a_browser_round_trip_is_polled_until_the_user_is_done() { let (mut app, jobs, ctx) = wired(); - app.cloud.events.0.send(Event::Browser { url: "https://cloud.example/link/abc".to_owned(), handle: Some("abc".to_owned()) }).unwrap(); + deliver(&app, Event::Browser { url: "https://cloud.example/link/abc".to_owned(), handle: Some("abc".to_owned()) }); pumped(&mut app, &ctx); assert_eq!(app.did().urls, vec!["https://cloud.example/link/abc".to_owned()], "the browser is opened for them"); assert_eq!(report(&app)["link"]["waiting"], "https://cloud.example/link/abc"); @@ -403,11 +409,10 @@ fn working_together_needs_somewhere_for_the_room_to_be_keyed_on() { #[test] fn a_conversation_uses_the_hosts_chat_opener() { let (mut app, _, ctx) = wired(); - app.cloud - .events - .0 - .send(Event::Conversation(Ok(craft_cloud::Conversation { url: "https://cloud.example.net/call/room".to_owned(), name: "Talk".to_owned() }))) - .unwrap(); + deliver( + &app, + Event::Conversation(Ok(craft_cloud::Conversation { url: "https://cloud.example.net/call/room".to_owned(), name: "Talk".to_owned() })), + ); pumped(&mut app, &ctx); @@ -430,6 +435,75 @@ fn signing_out_forgets_everything_this_window_knew() { assert!(jobs.lock().unwrap().iter().any(|j| matches!(j, Job::SignOut)), "the service is told, so the saved token goes too"); } +#[test] +fn an_answer_queued_before_the_session_changed_is_dropped() { + let (mut app, _jobs, ctx) = wired(); + let old = Account { display: "Ada Lovelace".to_owned(), capabilities: vec![Capability::Files], provider_linked: true }; + + // A worker answers, and the answers wait in the channel while the user + // signs out in the same frame. + let post = Post::new(app.cloud.events.0.clone(), app.cloud.account_generation.clone()); + post.send(Event::Account(Ok(old))); + post.dup().send(Event::Listed { path: String::new(), entries: Ok(vec![file("/Minutes.note")]) }); + sign_out(&mut app); + pumped(&mut app, &ctx); + let state = report(&app); + assert_eq!(state["account"], serde_json::Value::Null, "the previous session's account must not come back"); + assert_eq!(state["entries"], serde_json::json!([]), "nor its files"); + + // The same across a new sign-in. + let post = Post::new(app.cloud.events.0.clone(), app.cloud.account_generation.clone()); + post.send(Event::Listed { path: String::new(), entries: Ok(vec![file("/Stale.note")]) }); + sign_in(&mut app); + pumped(&mut app, &ctx); + assert_eq!(report(&app)["entries"], serde_json::json!([]), "a listing for the signed-out session is not shown to the new one"); +} + +#[test] +fn a_sign_in_that_drops_a_listing_leaves_no_folder_loading() { + let (mut app, _jobs, ctx) = wired(); + + // Both listings are asked for, and the answer to the first waits in the + // channel while the user signs in again. The shared one never answers. + browse(&mut app, ""); + load_shared(&mut app); + sign_in(&mut app); + pumped(&mut app, &ctx); + assert!(!app.cloud.mine.loading, "a dropped listing must not leave the folder loading forever"); + assert!(!app.cloud.shared.loading, "nor the shared one, which would then never be asked for again"); + + // A listing the new session asks for still completes. + browse(&mut app, ""); + pumped(&mut app, &ctx); + assert!(app.cloud.mine.loaded); + assert_eq!(report(&app)["entries"], serde_json::json!(["Minutes.note", "Archive"])); +} + +#[test] +fn a_listing_asked_for_before_the_sign_in_answers_is_not_sent() { + let (mut app, jobs, ctx) = wired(); + sign_in(&mut app); + jobs.lock().unwrap().clear(); + + // Asked for after the sign-in and before its answer. A listing sent now + // could answer after the account does, and its files may be the previous + // account's. + browse(&mut app, ""); + load_shared(&mut app); + assert!( + !jobs.lock().unwrap().iter().any(|j| matches!(j, Job::List(_) | Job::SharedWithMe)), + "no listing goes out while the sign-in is outstanding" + ); + pumped(&mut app, &ctx); + assert!(!app.cloud.mine.loaded && !app.cloud.mine.loading, "the folder waits to be listed for the new account"); + assert!(!app.cloud.shared.loaded && !app.cloud.shared.loading, "and so does the shared one"); + + // Once the sign-in has answered, a listing goes through. + browse(&mut app, ""); + pumped(&mut app, &ctx); + assert!(app.cloud.mine.loaded); +} + #[test] fn bytes_are_said_the_way_a_person_reads_them() { assert_eq!(size_text(None), ""); diff --git a/crates/cloud-ui/src/share/mod.rs b/crates/cloud-ui/src/share/mod.rs index e380674119..b4739909fc 100644 --- a/crates/cloud-ui/src/share/mod.rs +++ b/crates/cloud-ui/src/share/mod.rs @@ -675,14 +675,17 @@ impl ShareDialog { } } Answer::Granted { shared, failed } => { - // A link was asked for in order to be handed out, so it goes - // to the clipboard without a second click. - if let Some(url) = shared.iter().find_map(|s| s.url.clone()) { - ctx.copy_text(url); - } if let Some(sheet) = &mut self.open && sheet.granting == Some(seq) { + // A link was asked for in order to be handed out, so it + // goes to the clipboard without a second click. Only for + // the sheet that asked: a grant answered after the sheet + // closed or moved to another document leaves the + // clipboard alone. + if let Some(url) = shared.iter().find_map(|s| s.url.clone()) { + ctx.copy_text(url); + } sheet.granting = None; sheet.error = None; // Recipients that went through leave the picker. The ones @@ -918,9 +921,11 @@ fn draw(ui: &mut Ui, sheet: &mut Sheet, avatars: &HashMap, label ui.add(egui::TextEdit::singleline(&mut sheet.link_key).hint_text(labels.key_hint.as_str()).password(true).desired_width(150.0)); } // A key the server insists on cannot be skipped, so the control - // stays disabled until one is typed. + // stays disabled until one is typed. It also waits, as Send does, + // while a grant is in flight: the answer to that grant is the one + // the sheet takes, and an earlier link would be dropped. let keyed = !sheet.link_key.trim().is_empty(); - let ready = keyed || !allowed.key_required; + let ready = (keyed || !allowed.key_required) && sheet.granting.is_none(); if ui.add_enabled(ready, egui::Button::new(labels.create_link.as_str())).clicked() { acts.push(Act::Grant(Grant { id: sheet.id.clone(), diff --git a/crates/cloud-ui/src/share/tests.rs b/crates/cloud-ui/src/share/tests.rs index dfdb3eb1e3..eba1a23551 100644 --- a/crates/cloud-ui/src/share/tests.rs +++ b/crates/cloud-ui/src/share/tests.rs @@ -240,6 +240,85 @@ fn a_share_reaching_four_of_five_names_the_fifth() { assert_eq!(left.chosen.first().map(|c| &c.target), Some(&ShareTarget::Email("nobody@@".into()))); } +fn copied(ctx: &Context) -> Vec { + ctx.output(|o| o.commands.iter().filter_map(|c| if let egui::OutputCommand::CopyText(text) = c { Some(text.clone()) } else { None }).collect()) +} + +fn ask_for_link(dialog: &mut ShareDialog) -> u64 { + let granting = dialog.issue(Request::Grant(Grant { + id: "files/budget.xlsx".into(), + password: None, + targets: Vec::new(), + permission: Permission::View, + note: None, + notify: false, + })); + if let Some(sheet) = &mut dialog.open { + sheet.granting = Some(granting); + } + granting +} + +fn link(url: &str) -> Answer { + let mut made = share("s1", ShareTarget::Email("anyone@example.com".into())); + made.url = Some(url.into()); + Answer::Granted { shared: vec![made], failed: Vec::new() } +} + +#[test] +fn a_granted_link_goes_to_the_clipboard() { + let (ctx, mut dialog, _) = ready(); + let granting = ask_for_link(&mut dialog); + dialog.receive(&ctx, granting, Ok(link("https://cloud.example/l/budget"))); + assert_eq!(copied(&ctx), ["https://cloud.example/l/budget"]); +} + +#[test] +fn a_link_granted_after_the_sheet_moved_on_is_not_copied() { + let (ctx, mut dialog, _) = ready(); + let granting = ask_for_link(&mut dialog); + dialog.close(); + dialog.open("files/plan.docx", "Plan"); + dialog.receive(&ctx, granting, Ok(link("https://cloud.example/l/budget"))); + assert!(copied(&ctx).is_empty(), "the budget's link must not replace the clipboard while the plan is open"); + + let (ctx, mut dialog, _) = ready(); + let granting = ask_for_link(&mut dialog); + dialog.close(); + dialog.receive(&ctx, granting, Ok(link("https://cloud.example/l/budget"))); + assert!(copied(&ctx).is_empty(), "nor after the sheet closed"); +} + +/// Whether one frame of the sheet offers "Get a link" as a button that can +/// be pressed, read off the accessibility tree. +fn link_button_enabled(dialog: &mut ShareDialog) -> Option { + let ctx = Context::default(); + ctx.enable_accesskit(); + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 900.0))), ..Default::default() }; + let mut output = ctx.run_ui(raw, |ui| dialog.show_in(ui)); + output.textures_delta.clear(); + let tree = output.platform_output.accesskit_update?; + tree.nodes + .iter() + .find(|(_, node)| node.role() == egui::accesskit::Role::Button && node.label() == Some("Get a link")) + .map(|(_, node)| !node.is_disabled()) +} + +#[test] +fn get_a_link_waits_while_a_grant_is_in_flight() { + let ctx = Context::default(); + let mut dialog = ShareDialog::new(); + dialog.connect(Silent::default()); + dialog.collect(&ctx); + dialog.receive(&ctx, 1, Ok(can(vec![Capability::Sharing, Capability::LinkShares]))); + dialog.open("files/budget.xlsx", "Budget"); + assert_eq!(link_button_enabled(&mut dialog), Some(true)); + let granting = ask_for_link(&mut dialog); + assert_eq!(link_button_enabled(&mut dialog), Some(false), "a second grant would make the first one's link be dropped"); + dialog.receive(&ctx, granting, Ok(link("https://cloud.example/l/budget"))); + assert_eq!(link_button_enabled(&mut dialog), Some(true)); +} + #[test] fn a_refusal_that_stopped_the_whole_call_is_not_a_failed_recipient() { let (ctx, mut dialog, _) = ready(); diff --git a/crates/control-protocol/src/lib.rs b/crates/control-protocol/src/lib.rs index d62f1488fa..8194dc8e96 100644 --- a/crates/control-protocol/src/lib.rs +++ b/crates/control-protocol/src/lib.rs @@ -72,12 +72,14 @@ pub enum ReadFailure { Rejected(String), } -/// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped). +/// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped, and a `\r` +/// before it). The `\r\n` or `\n` does not count toward `max`. /// `Ok(false)` at end of stream; `Err` when the line is too long or the read fails. pub fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec, max: usize) -> Result { buf.clear(); - // `take` bounds the bytes buffered for one line: a peer can't make us allocate more than `max`. - let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1); + // `take` bounds the bytes buffered for one line: a peer can't make us allocate more than + // `max + 2`, the line and its `\r\n`. + let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(2); let n = reader.take(limit).read_until(b'\n', buf).map_err(|e| match e.kind() { std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock => ReadFailure::Timeout, _ => ReadFailure::Rejected(e.to_string()), @@ -90,12 +92,11 @@ pub fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec, max: usiz if buf.last() == Some(&b'\r') { buf.pop(); } - return Ok(true); } if buf.len() > max { return Err(ReadFailure::Rejected(format!("request line longer than {max} bytes; closing the connection"))); } - // Last line without a newline, then end of stream. + // A complete line, or the last line without a newline, then end of stream. Ok(true) } @@ -268,6 +269,11 @@ mod tests { assert_eq!(read_bounded_line(&mut &b"abc"[..], &mut buf, 3), Ok(true)); assert_eq!(buf, b"abc"); assert!(matches!(read_bounded_line(&mut &b"abcd"[..], &mut buf, 3), Err(ReadFailure::Rejected(_)))); + // The cap counts the line without its `\r\n` or `\n`. + assert_eq!(read_bounded_line(&mut &b"abc\r\n"[..], &mut buf, 3), Ok(true)); + assert_eq!(buf, b"abc"); + assert!(matches!(read_bounded_line(&mut &b"abcd\n"[..], &mut buf, 3), Err(ReadFailure::Rejected(_)))); + assert!(matches!(read_bounded_line(&mut &b"abcd\r\n"[..], &mut buf, 3), Err(ReadFailure::Rejected(_)))); let mut out = Vec::new(); serve_lines(&b"{broken}\n"[..], &mut out, "secret", 1024, |_, _| panic!("must not dispatch")); let reply: Value = serde_json::from_slice(&out).unwrap(); diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index 3e756aff75..efe1f1e446 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -24,6 +24,8 @@ serde_json = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] # The per-launch control token: 32 random bytes from the operating system (MIT OR Apache-2.0). getrandom = "0.3" +# The request-line reader and the reply's result, shared with servers built on it (MIT OR Apache-2.0, ours). +craft-control-protocol = { workspace = true } # The launcher's app list, read in one place for the launcher, the gateway and every app (MIT OR Apache-2.0, ours). craft-ai-agents = { workspace = true, optional = true } craft-atomic = { workspace = true, optional = true } diff --git a/crates/control/src/client.rs b/crates/control/src/client.rs index cbad788504..346602759b 100644 --- a/crates/control/src/client.rs +++ b/crates/control/src/client.rs @@ -117,13 +117,10 @@ impl Request { } } -/// A control reply as a call's result: its `result`, or its `error`. +/// A control reply as a call's result: its `result`, or its `error` +/// ([`craft_control_protocol::reply_result`]). pub fn outcome(v: &Value) -> Result { - if v.get("ok").and_then(Value::as_bool) == Some(true) { - Ok(v.get("result").cloned().unwrap_or(Value::Null)) - } else { - Err(v.get("error").and_then(Value::as_str).unwrap_or("error").to_string()) - } + craft_control_protocol::reply_result(v) } /// A request the app said is still running. Its reply will come on this connection, through diff --git a/crates/control/src/server.rs b/crates/control/src/server.rs index 85664a1aa9..a276060c81 100644 --- a/crates/control/src/server.rs +++ b/crates/control/src/server.rs @@ -10,6 +10,7 @@ use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use std::time::{Duration, Instant}; +use craft_control_protocol::ReadFailure; use serde_json::{Value, json}; use crate::Effect; @@ -215,35 +216,19 @@ pub fn new_token() -> Option { Some(bytes.iter().map(|b| format!("{b:02x}")).collect()) } -/// One line without its newline, or `None` at the end of the stream. A client that sends -/// gigabytes with no newline would otherwise make this thread allocate until the process is -/// killed, so the line is refused as soon as it passes `max`. +/// One line without its newline (and a `\r` before it), or `None` at the end of the stream, read +/// with [`craft_control_protocol::read_bounded_line`]. A line of more than `max` bytes, not +/// counting its `\r\n` or `\n`, is refused with `InvalidData`, and at most `max + 2` bytes of it +/// are buffered, so a client that sends gigabytes with no newline cannot make this thread +/// allocate until the process is killed. A read that times out (the token deadline) fails with +/// `TimedOut`. fn read_line(r: &mut impl BufRead, max: usize) -> std::io::Result>> { let mut line = Vec::new(); - loop { - let (done, used) = { - let available = r.fill_buf()?; - if available.is_empty() { - return Ok((!line.is_empty()).then_some(line)); - } - match available.iter().position(|b| *b == b'\n') { - Some(i) => { - line.extend_from_slice(available.get(..i).unwrap_or(&[])); - (true, i + 1) - } - None => { - line.extend_from_slice(available); - (false, available.len()) - } - } - }; - r.consume(used); - if done { - return Ok(Some(line)); - } - if line.len() > max { - return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "request too large")); - } + match craft_control_protocol::read_bounded_line(r, &mut line, max) { + Ok(true) => Ok(Some(line)), + Ok(false) => Ok(None), + Err(ReadFailure::Timeout) => Err(std::io::ErrorKind::TimedOut.into()), + Err(ReadFailure::Rejected(e)) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e)), } } @@ -1335,7 +1320,73 @@ mod tests { let mut r = BufReader::new(flood.as_slice()); let e = read_line(&mut r, MAX_LINE).unwrap_err(); assert_eq!(e.kind(), std::io::ErrorKind::InvalidData); - assert!(e.to_string().contains("request too large"), "{e}"); + assert!(e.to_string().contains(&format!("longer than {MAX_LINE} bytes")), "{e}"); + } + + /// The cap is exact: a line of `max` bytes is read, and one byte more is refused even when its + /// newline arrives in the same read as the rest of it. The `\r\n` or `\n` after the line does + /// not count toward the cap. + #[test] + fn the_cap_holds_for_a_line_read_at_once() { + for end in [&b"\n"[..], &b"\r\n"[..]] { + let mut fits = vec![b'A'; 1000]; + fits.extend_from_slice(end); + assert_eq!(read_line(&mut BufReader::new(fits.as_slice()), 1000).unwrap().unwrap().len(), 1000); + let mut over = vec![b'A'; 1001]; + over.extend_from_slice(end); + let e = read_line(&mut BufReader::new(over.as_slice()), 1000).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::InvalidData); + } + } + + /// The cap holds when the line arrives a few bytes at a time, and at the end of the stream: + /// a `\r\n` split across two reads does not count toward it, and a last line of one byte + /// more than the cap with no newline is refused. + #[test] + fn the_cap_holds_across_reads() { + let mut fits = vec![b'A'; 1000]; + fits.extend_from_slice(b"\r\n"); + assert_eq!(read_line(&mut BufReader::with_capacity(7, fits.as_slice()), 1000).unwrap().unwrap().len(), 1000); + let last = vec![b'A'; 1001]; + let e = read_line(&mut BufReader::with_capacity(7, last.as_slice()), 1000).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::InvalidData); + } + + /// A read interrupted by a signal is tried again instead of ending the connection, and a + /// `\r` before the newline is not part of the line. + #[test] + fn interrupted_reads_are_retried() { + struct Interrupting(Vec<&'static [u8]>); + impl std::io::Read for Interrupting { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if self.0.is_empty() { + return Ok(0); + } + let chunk = self.0.remove(0); + if chunk.is_empty() { + return Err(std::io::ErrorKind::Interrupted.into()); + } + buf[..chunk.len()].copy_from_slice(chunk); + Ok(chunk.len()) + } + } + let mut r = BufReader::new(Interrupting(vec![b"", b"{\"a\"", b"", b":1}\r\n"])); + assert_eq!(read_line(&mut r, MAX_LINE).unwrap().unwrap(), b"{\"a\":1}"); + assert!(read_line(&mut r, MAX_LINE).unwrap().is_none()); + } + + /// A read that times out before the token is shown fails with `TimedOut`, which closes the + /// connection without a reply. + #[test] + fn timed_out_reads_report_timed_out() { + struct Slow; + impl std::io::Read for Slow { + fn read(&mut self, _: &mut [u8]) -> std::io::Result { + Err(std::io::ErrorKind::WouldBlock.into()) + } + } + let e = read_line(&mut BufReader::new(Slow), MAX_LINE).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::TimedOut); } /// Ordinary framing: lines split on newlines, blank lines kept, no trailing newline needed. diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index c80ef7e2da..cb06fa708a 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -229,6 +229,9 @@ craft-ppt-binary = { workspace = true, optional = true } craft-sqlite = { workspace = true, optional = true } craft-audio-dsp = { workspace = true, optional = true } craft-sbs = { workspace = true, optional = true } +craft-ease = { workspace = true, optional = true } +craft-i18n-build = { workspace = true, optional = true } +craft-pbr = { workspace = true, optional = true } [features] ui = [ @@ -442,6 +445,9 @@ dwg = ["dep:craft-dwg"] dxf = ["dep:craft-dxf"] +ease = ["dep:craft-ease"] +ease-serde = ["ease", "craft-ease/serde"] + ecproj-format = ["dep:craft-ecproj-format"] elf = ["dep:craft-elf"] @@ -557,6 +563,8 @@ http-url = ["dep:craft-http-url"] i18n-collate = ["craft-i18n/collate"] +i18n-build = ["dep:craft-i18n-build"] + ical = ["dep:craft-ical"] idml = ["dep:craft-idml"] @@ -564,6 +572,7 @@ idml = ["dep:craft-idml"] image-codecs = ["dep:craft-image-codecs"] image-codecs-avif = ["image-codecs", "craft-image-codecs/avif"] image-codecs-avif-decode = ["image-codecs", "craft-image-codecs/avif-decode"] +image-codecs-cms = ["image-codecs", "craft-image-codecs/cms"] image-codecs-corpus = ["image-codecs", "craft-image-codecs/corpus"] image-codecs-heif = ["image-codecs", "craft-image-codecs/heif"] image-codecs-jxl = ["image-codecs", "craft-image-codecs/jxl"] @@ -666,6 +675,7 @@ odf = ["dep:craft-odf"] odf-text = ["odf", "craft-odf/text"] ods = ["dep:craft-ods"] +ods-test-support = ["ods", "craft-ods/test-support"] offcrypto = ["dep:craft-offcrypto"] @@ -680,6 +690,9 @@ pages = ["dep:craft-pages", "keymap", "text"] palette = ["dep:craft-palette"] +pbr = ["dep:craft-pbr"] +pbr-parallel = ["pbr", "craft-pbr/parallel"] + pcap = ["dep:craft-pcap"] pcraft-bundle = ["dep:craft-pcraft-bundle"] diff --git a/crates/craft/src/lib.rs b/crates/craft/src/lib.rs index b465304399..8946df18b6 100644 --- a/crates/craft/src/lib.rs +++ b/crates/craft/src/lib.rs @@ -103,6 +103,8 @@ pub use craft_drawingml as drawingml; pub use craft_dwg as dwg; #[cfg(feature = "dxf")] pub use craft_dxf as dxf; +#[cfg(feature = "ease")] +pub use craft_ease as ease; #[cfg(feature = "ecproj-format")] pub use craft_ecproj_format as ecproj_format; #[cfg(feature = "elf")] @@ -181,6 +183,8 @@ pub use craft_html as html; #[cfg(feature = "http-url")] pub use craft_http_url as http_url; pub use craft_i18n as i18n; +#[cfg(feature = "i18n-build")] +pub use craft_i18n_build as i18n_build; #[cfg(feature = "ical")] pub use craft_ical as ical; #[cfg(feature = "idml")] @@ -267,6 +271,8 @@ pub use craft_ora as ora; pub use craft_pages as pages; #[cfg(feature = "palette")] pub use craft_palette as palette; +#[cfg(feature = "pbr")] +pub use craft_pbr as pbr; #[cfg(feature = "pcap")] pub use craft_pcap as pcap; #[cfg(feature = "pcraft-bundle")] diff --git a/crates/dwg/README.md b/crates/dwg/README.md index 80088a89e6..495db1ff71 100644 --- a/crates/dwg/README.md +++ b/crates/dwg/README.md @@ -13,7 +13,7 @@ startup and call `serve_if_asked()` before normal argument handling. Subsequent is contained to that child. The worker has no operating-system memory limit yet. Without a configured worker, conversions are refused rather than run in the current process: call `allow_in_process()` only for input that is known to be trusted (tests, or bytes this process -produced itself). Coordinates, once a worker is configured but cannot start, also fail closed. +produced itself). Conversions, once a worker is configured but cannot start, also fail closed. The bridge is not built for `wasm32` or FreeBSD/aarch64. Those targets retain the public API and return a clear unsupported-build error. The `acadrust` 0.6.6 dependency is used unmodified under diff --git a/crates/dwg/src/worker.rs b/crates/dwg/src/worker.rs index 1d16f5701b..bb73f1b348 100644 --- a/crates/dwg/src/worker.rs +++ b/crates/dwg/src/worker.rs @@ -6,8 +6,9 @@ //! that reads one request from standard input and writes one reply to standard output. A file that //! kills the worker then costs that one open or save, and every other open drawing stays safe. //! -//! Without a worker [`decode`] and [`encode_as`] refuse rather than run the conversion in the -//! calling process, because the third-party code is the part that can end a process. +//! Without a worker [`decode`], [`encode_as`], [`encode_noted`] and [`encode_kept_noted`] refuse +//! rather than run the conversion in the calling process, because the third-party code is the part +//! that can end a process. //! [`allow_in_process`] is the explicit exception, for input the caller knows is trusted (tests, or //! bytes this process produced itself). There's no memory limit on the worker yet: that takes //! per-platform system calls, which `unsafe_code = "forbid"` keeps out of this crate. @@ -62,7 +63,9 @@ pub fn use_worker(program: PathBuf, args: Vec) { } /// Use a copy of this program as the worker, started with [`WORKER_ARG`]. If its path can't be -/// found, the reader and writer stay in this process. +/// found, the worker setting does not change. When no worker was set before, [`decode`], +/// [`encode_as`], [`encode_noted`] and [`encode_kept_noted`] then refuse unless +/// [`allow_in_process`] was called. pub fn use_own_worker() { match std::env::current_exe() { Ok(program) => use_worker(program, vec![WORKER_ARG.into()]), @@ -70,7 +73,8 @@ pub fn use_own_worker() { } } -/// Let [`decode`] and [`encode_as`] run the conversion in this process when no worker is set. +/// Let [`decode`], [`encode_as`], [`encode_noted`] and [`encode_kept_noted`] run the conversion in +/// this process when no worker is set. /// /// This opts out of the isolation the crate exists for: the third-party code allocates from sizes /// a hostile file declares, and a failed allocation ends the process. Call it for input the caller diff --git a/crates/ease/Cargo.toml b/crates/ease/Cargo.toml new file mode 100644 index 0000000000..c14b54f0d2 --- /dev/null +++ b/crates/ease/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "craft-ease" +description = "Easing curves, keyed tracks, motion paths and springs for animation: named eases, cubic Bezier and speed/influence eases, editable custom curves, sampled tables, hold keys, constant-speed Bezier paths and an O(1) damped spring" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[features] +default = ["serde"] +# Reading and writing eases (spring eases included) and tracks with serde. +serde = ["dep:serde"] + +[dependencies] +serde = { workspace = true, features = ["rc"], optional = true } + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/crates/ease/README.md b/crates/ease/README.md new file mode 100644 index 0000000000..fc5612f6cc --- /dev/null +++ b/crates/ease/README.md @@ -0,0 +1,102 @@ +# craft-ease + +Easing curves, keyed tracks, constant-speed motion paths and damped springs for animation in the +Craft apps. The crate depends only on the standard library, with `serde` as an optional feature +(on by default). It builds for `wasm32-unknown-unknown`. + +Its parts come from AniCraft and EffectCraft: + +- `Easing`, `CustomEase`, `SampledEase` and the curve editing came from AniCraft's `anicraft-doc` + (`crates/doc/src/easing.rs`). They now use `f64` and the crate's own `Vec2`, the Back and + Elastic In Out curves follow the published equations, and `Hold` and `Spring` are new + variants. +- Speed and influence eases, hold keys and the constant-speed motion paths came from + EffectCraft's `effectcraft-keyframe` (`crates/keyframe/src/lib.rs`). `Track` takes any + `Animatable` value instead of the app's value type, and `MotionPath` continues in a straight + line past either end. +- `Spring` replaces AniCraft's stepped spring (`crates/doc/src/spring.rs`) with the exact + solution of the damped spring equation, so a step costs O(1) and any step length is stable. + +Licensed under MIT OR Apache-2.0. + +## Contents + +- `Easing` maps linear progress `t` in `0..=1` to eased progress. The variants are no ease + (`Linear`), `Hold`, the Classic slider (−100 to +100), nine named families (Quad, Cubic, Quart, + Quint, Sine, Back, Circ, Bounce, Elastic) each In, Out and In Out, `CubicBezier` as the CSS + Easing Functions specification defines `cubic-bezier()`, an editable `CustomEase`, a + `SampledEase` table and a physical `SpringEase`. `Easing::apply(t)` returns exactly 0 for + `t <= 0` and NaN, and exactly 1 for `t >= 1`. It does not allocate. +- `Easing::from_temporal` builds the cubic Bezier for a segment from the speed and influence of + its two sides (`TemporalEase`), as keyframe velocity dialogs give them. `Easing::temporal` + reads them back. +- `Track` holds keys of any `Animatable` value (`f32`, `f64`, `Vec2`, `[f32; N]`, + `[f64; N]`), each with the ease to the next key. `Track::sample` is a binary search and does + not allocate. +- `MotionPath` is a chain of cubic Bezier segments with an arc-length table per segment, built + once. `point_at` and `point_at_length` move at constant speed along it and continue in a + straight line past either end. `MotionPath::through` sets the handles of a smooth path through + a list of anchors. +- `Spring` and `SpringState` move a value toward a target. `SpringState::step` applies the exact + solution of the damped spring equation over the step, so a step costs O(1), any step length is + stable, and many short steps give the same value as one long one. + +## Checked and lenient constructors + +Every type has a checked constructor that returns `EaseError` for a value that is not finite or +is out of range: `Easing::cubic_bezier`, `Easing::from_temporal`, `Easing::spring`, +`CustomEase::try_new`, `SampledEase::try_new`, `Track::from_keys`, `MotionPath::new`, +`Spring::new` and `Spring::from_physical`. `CustomEase::new` and `SampledEase::new` repair what +they are given instead, and files are read through the same repairs. Reading a track refuses a +file with more than `MAX_TRACK_KEYS` keys while it reads. + +## Limits + +| Constant | Value | +| --- | --- | +| `MAX_EASE_Y` | 10 (eased values stay within ±10) | +| `MAX_EASE_POINTS` | 64 points in a custom ease | +| `MAX_EASE_SAMPLES` | 1,025 samples in a sampled ease | +| `MAX_TRACK_KEYS` | 100,000 keys in a track | +| `MAX_PATH_SEGMENTS` | 10,000 segments in a motion path | +| `MAX_SPRING_HZ` | 10,000 swings a second | +| `MAX_DAMPING_RATIO` | 1,000,000 | +| `MIN_INFLUENCE` | 0.001 | + +## Sources + +- The named families are the easing equations published by Robert Penner. Back In Out and + Elastic In Out use the published In Out equations, which scale Back's overshoot by 1.525 and + give Elastic a longer period. +- `CubicBezier` follows the CSS Easing Functions Level 1 specification. + +## Details + +- Values are `f64` throughout. +- The `serde` feature reads and writes `Easing` (spring eases included) and `Track`. + `MotionPath`, `Spring` and `SpringState` are not serialized. +- Serialized eases keep their form: presets are strings such as `"QuadIn"`, and `Classic`, + `CubicBezier`, `Custom` and `Sampled` are one-key objects. `Hold` and `Spring` are the last + variants. A track is read from its fields by name or in order. +- `Easing::apply` returns exactly 0 and 1 at the ends for every variant, and `+∞` gives 1. +- `CubicBezier` keeps y1 and y2 within ±10 when it is evaluated. Its solver inverts the curve + with both handles at full reach in closed form, and otherwise stops within 1e-12 of the span + in at most 64 steps. +- A sampled ease's name drops control characters, bidirectional overrides and invisible format + characters such as zero-width spaces. A sampled ease with no name left is named "Sampled ease". + Reading a file keeps the first 65,536 entries of a custom ease's points or a sampled ease's + values and skips the rest. +- Without the `serde` feature the crate has no dependencies, and its tests that read and write + files are left out. +- `Track` takes `Easing::Hold` for held keys and treats −0 and +0 as one time. It samples keys + at opposite ends of the `f64` range without overflow, and returns `EaseError::Overflow` when + an overshooting ease carries a value past what its type holds. +- Speed and influence become a `CubicBezier` (`Easing::from_temporal`), with the influence + allowed from 0.001 to 1 on each side, including a sum above 1. +- Motion paths are measured by Gauss-Legendre quadrature per table cell with Newton refinement. + `MotionPath::through` sets each handle to a sixth of the line between the anchor's neighbors. + A segment whose handles lie on its chord is treated as a straight line. +- `Spring::from_physical(mass, stiffness, damping)` takes a mass, a stiffness and a damping + coefficient. A spring ease that is still moving after 10 seconds has the distance it is still + off taken out evenly over the ease, so it reaches 1 without a jump. Any other spring ease is + within about 0.1 % of 1 just before it reaches 1. diff --git a/crates/ease/src/custom.rs b/crates/ease/src/custom.rs new file mode 100644 index 0000000000..af4e4cd57d --- /dev/null +++ b/crates/ease/src/custom.rs @@ -0,0 +1,450 @@ +//! [`CustomEase`]: an editable curve of several Bezier segments from (0, 0) to (1, 1). + +use crate::{EaseError, Vec2, bez, solve_monotonic}; + +/// Most points (anchors) a custom ease keeps; longer curves are thinned evenly. +pub const MAX_EASE_POINTS: usize = 64; +/// Values a custom ease (and its handles) may reach: overshoot well past 0..1, never unbounded. +pub const MAX_EASE_Y: f64 = 10.0; +/// Most points read from a file or a caller before thinning (bounds the sort). +const MAX_EASE_INPUT: usize = 65_536; + +/// A point of a custom ease: where it is (x = time, y = progress), its handles as offsets from +/// it (in toward the previous point, out toward the next), and whether it is smooth (handles in +/// line, moved together) or a corner. In files the in handle is `"in"`. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct EasePoint { + pub at: Vec2, + #[cfg_attr(feature = "serde", serde(rename = "in", default))] + pub h_in: Vec2, + #[cfg_attr(feature = "serde", serde(default))] + pub out: Vec2, + #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "is_false"))] + pub smooth: bool, +} + +#[cfg(feature = "serde")] +fn is_false(b: &bool) -> bool { + !*b +} + +/// Which handle of a point. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Handle { + In, + Out, +} + +/// A custom ease: Bezier segments through its points, from (0, 0) to (1, 1). +/// +/// Always valid, however it was made: 2 to [`MAX_EASE_POINTS`] finite points sorted by x, the +/// ends fixed at (0, 0) and (1, 1), every handle reaching toward its neighbor in x and every +/// segment's x running forwards (so time never runs backwards), and every value within +/// ±[`MAX_EASE_Y`]. A handle whose x lies between its point and that neighbor always keeps x +/// running forwards; a handle may reach past the neighbor (as a piece of a split segment can) +/// only while its segment's x still runs forwards. Reading a file repairs a curve the way +/// [`CustomEase::new`] does. +#[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "serde", serde(from = "CustomEaseFile"))] +pub struct CustomEase { + points: Vec, +} + +#[cfg(feature = "serde")] +#[derive(serde::Deserialize)] +struct CustomEaseFile { + #[serde(default, deserialize_with = "read_points")] + points: Vec, +} + +/// The first [`MAX_EASE_INPUT`] points of a file's list, the way [`CustomEase::new`] keeps them. +#[cfg(feature = "serde")] +fn read_points<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + crate::read_first(d, MAX_EASE_INPUT) +} + +#[cfg(feature = "serde")] +impl From for CustomEase { + fn from(f: CustomEaseFile) -> CustomEase { + CustomEase::new(f.points) + } +} + +impl Default for CustomEase { + fn default() -> CustomEase { + CustomEase::linear() + } +} + +impl CustomEase { + /// The straight line, its handles a third of the way along. + pub fn linear() -> CustomEase { + CustomEase::linear_points() + } + + /// One segment with handles `(x1, y1)` and `(x2, y2)` in the unit box (x is clamped to + /// `0..=1`). + pub fn from_bezier(x1: f64, y1: f64, x2: f64, y2: f64) -> CustomEase { + let (x1, x2) = (x1.clamp(0.0, 1.0), x2.clamp(0.0, 1.0)); + CustomEase::new(vec![ + EasePoint { at: Vec2::ZERO, h_in: Vec2::ZERO, out: Vec2::new(x1, y1), smooth: false }, + EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::new(x2 - 1.0, y2 - 1.0), out: Vec2::ZERO, smooth: false }, + ]) + } + + /// The curve of absolute points `[p0, c1, c2, p1, c3, c4, p2, …]` (3n + 1 of them): `None` + /// when the count is wrong. + pub fn from_flat(pts: &[Vec2]) -> Option { + if pts.len() < 4 || pts.len() % 3 != 1 || pts.len() > MAX_EASE_INPUT { + return None; + } + let mut out: Vec = Vec::with_capacity(pts.len() / 3 + 1); + for (i, at) in pts.iter().enumerate().step_by(3) { + let h_in = if i == 0 { Vec2::ZERO } else { pts.get(i - 1).map_or(Vec2::ZERO, |c| *c - *at) }; + let h_out = pts.get(i + 1).map_or(Vec2::ZERO, |c| *c - *at); + // Handles in line (opposite ways) make a smooth point, as an editor would draw it. + let smooth = h_in.length() > 1e-6 && h_out.length() > 1e-6 && (h_in.normalized().dot(h_out.normalized()) + 1.0).abs() < 1e-3; + out.push(EasePoint { at: *at, h_in, out: h_out, smooth }); + } + Some(CustomEase::new(out)) + } + + /// A curve from points a caller supplies, checked: an error for a point or handle that is + /// not finite, fewer than 2 points or more than [`MAX_EASE_POINTS`]. The points are then + /// sorted, the ends pinned and the handles brought within reach as [`CustomEase::new`] does. + pub fn try_new(pts: Vec) -> Result { + if pts.iter().any(|p| !(p.at.is_finite() && p.h_in.is_finite() && p.out.is_finite())) { + return Err(EaseError::NotFinite("ease point")); + } + if pts.len() < 2 { + return Err(EaseError::TooFew { what: "a custom ease", need: 2 }); + } + if pts.len() > MAX_EASE_POINTS { + return Err(EaseError::Full(MAX_EASE_POINTS)); + } + Ok(CustomEase::new(pts)) + } + + /// A valid curve from any points, as a file holds them (see the type's docs): non-finite + /// points are dropped and non-finite handles zeroed, the rest sorted by x, a curve longer + /// than [`MAX_EASE_POINTS`] thinned evenly, the ends pinned and every handle brought within + /// reach. Fewer than two points make the straight line. + pub fn new(mut pts: Vec) -> CustomEase { + pts.truncate(MAX_EASE_INPUT); + pts.retain(|p| p.at.is_finite()); + for p in pts.iter_mut() { + p.at = Vec2::new(p.at.x.clamp(0.0, 1.0), p.at.y.clamp(-MAX_EASE_Y, MAX_EASE_Y)); + if !p.h_in.is_finite() { + p.h_in = Vec2::ZERO; + } + if !p.out.is_finite() { + p.out = Vec2::ZERO; + } + } + pts.sort_by(|a, b| a.at.x.total_cmp(&b.at.x)); + if pts.len() > MAX_EASE_POINTS { + let n = pts.len(); + let keep: Vec = (0..MAX_EASE_POINTS).map(|k| k * (n - 1) / (MAX_EASE_POINTS - 1)).collect(); + pts = keep.into_iter().filter_map(|i| pts.get(i).copied()).collect(); + } + if pts.len() < 2 { + return CustomEase::linear_points(); + } + if let Some(p) = pts.first_mut() { + p.at = Vec2::ZERO; + } + if let Some(p) = pts.last_mut() { + p.at = Vec2::new(1.0, 1.0); + } + let mut c = CustomEase { points: pts }; + // A point marked smooth whose handles are not in line is a corner: it loses the mark + // before the handles are brought within reach, so they are clipped as a corner's, and + // again if bringing them within reach put them out of line. + c.clear_broken_smooth(); + c.clamp_handles(); + c.clear_broken_smooth(); + c + } + + /// Clears the smooth mark of every end and of every point whose handles are not in line. + fn clear_broken_smooth(&mut self) { + let n = self.points.len(); + for (i, p) in self.points.iter_mut().enumerate() { + if p.smooth && (i == 0 || i + 1 == n || !handles_in_line(p.h_in, p.out)) { + p.smooth = false; + } + } + } + + /// [`CustomEase::linear`] built directly (so [`CustomEase::new`] does not recurse). + fn linear_points() -> CustomEase { + let third = 1.0 / 3.0; + CustomEase { + points: vec![ + EasePoint { at: Vec2::ZERO, h_in: Vec2::ZERO, out: Vec2::new(third, third), smooth: false }, + EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::new(-third, -third), out: Vec2::ZERO, smooth: false }, + ], + } + } + + /// Brings every handle within reach (see the type's docs): each handle toward its neighbor + /// in x and within ±[`MAX_EASE_Y`], then, in a segment whose x would run backwards, each + /// handle that reaches past the neighbor back to it. A smooth point's handles are shortened + /// along their own line, so they stay in line; a corner's are clipped. + fn clamp_handles(&mut self) { + let n = self.points.len(); + for (i, p) in self.points.iter_mut().enumerate() { + let (lo, hi) = (-MAX_EASE_Y - p.at.y, MAX_EASE_Y - p.at.y); + p.h_in = if i == 0 { Vec2::ZERO } else { fit_y(Vec2::new(p.h_in.x.min(0.0), p.h_in.y), lo, hi, p.smooth) }; + p.out = if i + 1 == n { Vec2::ZERO } else { fit_y(Vec2::new(p.out.x.max(0.0), p.out.y), lo, hi, p.smooth) }; + } + for i in 1..n { + let (Some(a), Some(b)) = (self.points.get(i - 1).copied(), self.points.get(i).copied()) else { continue }; + let span = b.at.x - a.at.x; + if runs_forwards(span, a.out.x, -b.h_in.x) { + continue; + } + if let Some(p) = self.points.get_mut(i - 1) { + p.out = fit_x(p.out, span, p.smooth); + } + if let Some(p) = self.points.get_mut(i) { + p.h_in = fit_x(p.h_in, span, p.smooth); + } + } + } + + pub fn points(&self) -> &[EasePoint] { + &self.points + } + + /// The control points of segment `i` (from point `i` to point `i + 1`), absolute; x runs + /// forwards along it (see the type's docs). + pub fn segment(&self, i: usize) -> Option<[Vec2; 4]> { + let (a, b) = (self.points.get(i)?, self.points.get(i.checked_add(1)?)?); + Some([a.at, a.at + a.out, b.at + b.h_in, b.at]) + } + + /// The segment that time `t` falls in. + fn segment_at(&self, t: f64) -> usize { + self.points.partition_point(|p| p.at.x <= t).saturating_sub(1).min(self.points.len().saturating_sub(2)) + } + + /// The eased value at time `t` (0 at the start, 1 at the end, anything between, overshoot + /// included). `t` outside `0..=1` is clamped, and NaN reads as 0. + pub fn apply(&self, t: f64) -> f64 { + if t.is_nan() || t <= 0.0 { + return 0.0; + } + if t >= 1.0 { + return 1.0; + } + let Some([p0, p1, p2, p3]) = self.segment(self.segment_at(t)) else { return t }; + if p3.x <= p0.x { + return p3.y; + } + let s = solve_monotonic(t, [p0.x, p1.x, p2.x, p3.x]); + bez(s, [p0.y, p1.y, p2.y, p3.y]) + } + + /// Adds a point on the curve at time `t`, leaving its shape as it was (the segment is split + /// in two): the new curve and the point's index. `None` at the ends, on an existing point, + /// where the split cannot be placed at `t` (on a curve so flat there that its time cannot be + /// solved closely enough), or when the curve is full. + pub fn insert_at(&self, t: f64) -> Option<(CustomEase, usize)> { + if !(t > 0.0 && t < 1.0) || self.points.len() >= MAX_EASE_POINTS || self.points.iter().any(|p| p.at.x == t) { + return None; + } + let i = self.segment_at(t); + let [p0, p1, p2, p3] = self.segment(i)?; + let s = solve_monotonic(t, [p0.x, p1.x, p2.x, p3.x]); + // de Casteljau at s. + let (a, b, c) = (p0.lerp(p1, s), p1.lerp(p2, s), p2.lerp(p3, s)); + let (d, e) = (a.lerp(b, s), b.lerp(c, s)); + let m = d.lerp(e, s); + // Refused when the split cannot be placed at `t`: it lands on an anchor, or farther from + // `t` than a millionth of the way to the nearer anchor. + if !(m.x > p0.x && m.x < p3.x && (m.x - t).abs() <= 1e-6 * (t - p0.x).min(p3.x - t)) { + return None; + } + let mut pts = self.points.clone(); + if let Some(q) = pts.get_mut(i) { + q.out = a - p0; + } + if let Some(q) = pts.get_mut(i + 1) { + q.h_in = c - p3; + } + pts.insert(i + 1, EasePoint { at: m, h_in: d - m, out: e - m, smooth: true }); + Some((CustomEase::new(pts), i + 1)) + } + + /// Moves point `i` (not an end) to `to`, its handles with it; its x stays between its + /// neighbors' so time keeps running forwards. `None` for an end, a missing point or a + /// non-finite `to`. + pub fn move_point(&self, i: usize, to: Vec2) -> Option { + if i == 0 || i >= self.points.len().saturating_sub(1) || !to.is_finite() { + return None; + } + let (lo, hi) = (self.points.get(i - 1)?.at.x, self.points.get(i + 1)?.at.x); + let mut c = self.clone(); + let p = c.points.get_mut(i)?; + p.at = Vec2::new(to.x.clamp(lo, hi), to.y.clamp(-MAX_EASE_Y, MAX_EASE_Y)); + c.clamp_handles(); + Some(c) + } + + /// Moves handle `which` of point `i` to `to` (absolute); a smooth point's other handle turns + /// to stay in line, keeping its length. `None` for a handle the point does not have (the + /// first point's in, the last's out) or a non-finite `to`. + pub fn move_handle(&self, i: usize, which: Handle, to: Vec2) -> Option { + let n = self.points.len(); + if !to.is_finite() || i >= n || (which == Handle::In && i == 0) || (which == Handle::Out && i + 1 == n) { + return None; + } + let mut c = self.clone(); + let p = c.points.get_mut(i)?; + let off = to - p.at; + match which { + Handle::In => p.h_in = off, + Handle::Out => p.out = off, + } + c.clamp_handles(); + if i > 0 && i + 1 < n { + let (prev, next) = (c.points.get(i - 1)?.at.x, c.points.get(i + 1)?.at.x); + if let Some(p) = c.points.get_mut(i).filter(|p| p.smooth) { + let at = p.at; + let (moved, other, x_reach) = match which { + Handle::In => (p.h_in, &mut p.out, next - at.x), + Handle::Out => (p.out, &mut p.h_in, prev - at.x), + }; + let dir = -moved.normalized(); + if dir != Vec2::ZERO { + // Shortened to stay within reach along `dir`, so the clamp below does not + // turn it out of line. + // A handle with no length is given one, so the point stays smooth. + let mut len = other.length(); + if len <= 0.0 { + len = 1e-3; + } + if dir.x != 0.0 { + len = len.min((x_reach / dir.x).max(0.0)); + } + if dir.y != 0.0 { + let y_reach = if dir.y > 0.0 { MAX_EASE_Y - at.y } else { -MAX_EASE_Y - at.y }; + len = len.min((y_reach / dir.y).max(0.0)); + } + *other = dir * len; + } + } + } + c.clamp_handles(); + Some(c) + } + + /// Removes point `i` (not an end). `None` for an end or a missing point. + pub fn remove(&self, i: usize) -> Option { + if i == 0 || i >= self.points.len().saturating_sub(1) { + return None; + } + let mut pts = self.points.clone(); + pts.remove(i); + Some(CustomEase::new(pts)) + } + + /// Makes point `i` smooth (its handles in line with its neighbors' chord, a third of the way + /// to each) or a corner (its handles on the point, so the curve turns sharply there). + pub fn set_smooth(&self, i: usize, smooth: bool) -> Option { + let n = self.points.len(); + let prev = if i == 0 { None } else { self.points.get(i - 1).map(|p| p.at) }; + let next = i.checked_add(1).and_then(|j| self.points.get(j)).map(|p| p.at); + let mut c = self.clone(); + let p = c.points.get_mut(i)?; + p.smooth = smooth && i > 0 && i + 1 < n; + if smooth { + let (a, b) = (prev.unwrap_or(p.at), next.unwrap_or(p.at)); + let chord = b - a; + let dir = if chord.x > 1e-6 { chord * (1.0 / chord.x) } else { Vec2::new(1.0, 0.0) }; + if prev.is_some() { + p.h_in = -dir * ((p.at.x - a.x) / 3.0); + } + if next.is_some() { + p.out = dir * ((b.x - p.at.x) / 3.0); + } + } else { + p.h_in = Vec2::ZERO; + p.out = Vec2::ZERO; + } + c.clamp_handles(); + Some(c) + } + + /// The flat list of absolute points `[p0, c1, c2, p1, …]` (see [`CustomEase::from_flat`]). + pub fn to_flat(&self) -> Vec { + let mut out = Vec::with_capacity(self.points.len() * 3); + for (i, p) in self.points.iter().enumerate() { + if i > 0 { + out.push(p.at + p.h_in); + } + out.push(p.at); + if i + 1 < self.points.len() { + out.push(p.at + p.out); + } + } + out + } +} + +/// Whether a segment `span` wide in x whose out handle reaches `a` forwards and whose in handle +/// reaches `c` backwards (both at least 0) runs forwards in x. Its x′ is the quadratic with +/// Bernstein coefficients `a`, `span − a − c` and `c`, which is never negative when the middle +/// one is at least −√(ac); that always holds while neither handle reaches past the other end, +/// and never holds when one reaches past 4/3 of the span. The test is made on reaches divided by +/// the span, so squaring them does not underflow on a very narrow segment. +fn runs_forwards(span: f64, a: f64, c: f64) -> bool { + if a <= span && c <= span { + return true; + } + if a > 2.0 * span || c > 2.0 * span { + return false; + } + // Here span > 0: a handle reaches past it, and no more than twice it. + let (a, c) = (a / span, c / span); + let b = 1.0 - a - c; + b >= 0.0 || b * b <= a * c * (1.0 + 1e-12) +} + +/// Whether handles `a` and `b` point opposite ways along one line (as a smooth point's do), or +/// one of them has no length. +fn handles_in_line(a: Vec2, b: Vec2) -> bool { + a.length() <= 1e-9 || b.length() <= 1e-9 || (a.normalized().dot(b.normalized()) + 1.0).abs() < 1e-3 +} + +/// Handle `h` (an offset) with its y within `lo..=hi`: a smooth point's shortened along its line, +/// a corner's clipped. +fn fit_y(h: Vec2, lo: f64, hi: f64, smooth: bool) -> Vec2 { + let k = if h.y > hi { + hi / h.y + } else if h.y < lo { + lo / h.y + } else { + return h; + }; + if smooth { Vec2::new(h.x * k, (h.y * k).clamp(lo, hi)) } else { Vec2::new(h.x, h.y.clamp(lo, hi)) } +} + +/// Handle `h` (an offset) reaching at most `span` in x: a smooth point's shortened along its line, +/// a corner's clipped. +fn fit_x(h: Vec2, span: f64, smooth: bool) -> Vec2 { + let reach = h.x.abs(); + if reach <= span { + return h; + } + let span = span.max(0.0); + if smooth { + let k = span / reach; + Vec2::new((h.x * k).clamp(-span, span), h.y * k) + } else { + Vec2::new(span.copysign(h.x), h.y) + } +} diff --git a/crates/ease/src/easing.rs b/crates/ease/src/easing.rs new file mode 100644 index 0000000000..807fcd4590 --- /dev/null +++ b/crates/ease/src/easing.rs @@ -0,0 +1,655 @@ +//! [`Easing`]: maps linear progress to eased progress. + +use std::sync::Arc; + +use crate::custom::{CustomEase, EasePoint, MAX_EASE_Y}; +use crate::sampled::SampledEase; +use crate::spring::Spring; +use crate::{EaseError, Vec2, bez, finite, solve_monotonic, within}; + +/// The Back family's overshoot (about 10 %). +const BACK: f64 = 1.701_58; +/// Back In Out's overshoot, as the published equation scales it. +const BACK_IN_OUT: f64 = BACK * 1.525; +/// The smallest influence a [`TemporalEase`] may have. +pub const MIN_INFLUENCE: f64 = 0.001; + +/// The families of named eases. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum EaseFamily { + Quad, + Cubic, + Quart, + Quint, + Sine, + Back, + Circ, + Bounce, + Elastic, +} + +impl EaseFamily { + pub const ALL: [EaseFamily; 9] = [ + EaseFamily::Quad, + EaseFamily::Cubic, + EaseFamily::Quart, + EaseFamily::Quint, + EaseFamily::Sine, + EaseFamily::Back, + EaseFamily::Circ, + EaseFamily::Bounce, + EaseFamily::Elastic, + ]; + + /// The family's English name. + pub fn label(self) -> &'static str { + match self { + EaseFamily::Quad => "Quad", + EaseFamily::Cubic => "Cubic", + EaseFamily::Quart => "Quart", + EaseFamily::Quint => "Quint", + EaseFamily::Sine => "Sine", + EaseFamily::Back => "Back", + EaseFamily::Circ => "Circ", + EaseFamily::Bounce => "Bounce", + EaseFamily::Elastic => "Elastic", + } + } + + /// The ease in, `In(t)`. With `in_out` set, the curve whose halves make In Out: the + /// published In Out equations scale Back's overshoot by 1.525 and give Elastic a longer + /// period (4.5 instead of 3 per unit) and its own phase; the other families use `In(t)`. + fn ease_in(self, t: f64, in_out: bool) -> f64 { + use std::f64::consts::PI; + match self { + EaseFamily::Quad => t * t, + EaseFamily::Cubic => t * t * t, + EaseFamily::Quart => t * t * t * t, + EaseFamily::Quint => t * t * t * t * t, + EaseFamily::Sine => 1.0 - (t * PI * 0.5).cos(), + EaseFamily::Back => { + let c = if in_out { BACK_IN_OUT } else { BACK }; + (c + 1.0) * t * t * t - c * t * t + } + EaseFamily::Circ => 1.0 - (1.0 - t * t).max(0.0).sqrt(), + EaseFamily::Bounce => 1.0 - bounce_out(1.0 - t), + EaseFamily::Elastic => { + if t <= 0.0 { + 0.0 + } else if t >= 1.0 { + 1.0 + } else if in_out { + -(2f64.powf(10.0 * t - 10.0)) * ((10.0 * t - 11.125) * (2.0 * PI / 4.5)).sin() + } else { + -(2f64.powf(10.0 * t - 10.0)) * ((10.0 * t - 10.75) * (2.0 * PI / 3.0)).sin() + } + } + } + } + + /// Where the ease in changes formula (other than 0 and 1): Bounce is four parabolas. + fn breaks_in(self) -> &'static [f64] { + match self { + // 1 − the Out breakpoints (1/2.75, 2/2.75, 2.5/2.75), in order. + EaseFamily::Bounce => &[0.25 / 2.75, 0.75 / 2.75, 1.75 / 2.75], + _ => &[], + } + } + + /// Bezier segments per ease in that draw it to within a hair (see [`Easing::to_custom`]); + /// cubic polynomials (Quad, Cubic, Back) and the parabolas of Bounce are exact with one. + fn pieces_in(self) -> usize { + match self { + EaseFamily::Quad | EaseFamily::Cubic | EaseFamily::Back | EaseFamily::Bounce | EaseFamily::Circ => 1, + EaseFamily::Quart | EaseFamily::Quint | EaseFamily::Sine => 4, + EaseFamily::Elastic => 24, + } + } +} + +fn bounce_out(t: f64) -> f64 { + const N: f64 = 7.5625; + const D: f64 = 2.75; + if t < 1.0 / D { + N * t * t + } else if t < 2.0 / D { + let u = t - 1.5 / D; + N * u * u + 0.75 + } else if t < 2.5 / D { + let u = t - 2.25 / D; + N * u * u + 0.9375 + } else { + let u = t - 2.625 / D; + N * u * u + 0.984_375 + } +} + +/// Which way a named ease eases. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum EaseDir { + In, + Out, + InOut, +} + +impl EaseDir { + pub const ALL: [EaseDir; 3] = [EaseDir::In, EaseDir::Out, EaseDir::InOut]; + + pub fn label(self) -> &'static str { + match self { + EaseDir::In => "In", + EaseDir::Out => "Out", + EaseDir::InOut => "In Out", + } + } +} + +/// One side of a segment's ease as a keyframe velocity dialog gives it: `speed` normalized +/// (speed × segment duration ÷ value change, so 1 is the straight line's speed) and +/// `influence` the fraction of the segment its handle reaches. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct TemporalEase { + pub speed: f64, + pub influence: f64, +} + +impl TemporalEase { + /// A side that leaves at rest with a third of the segment's influence. + pub const EASY: TemporalEase = TemporalEase { speed: 0.0, influence: 1.0 / 3.0 }; + /// A linear side next to an eased one: the segment's average speed with a sixth of its + /// influence. + pub const LINEAR: TemporalEase = TemporalEase { speed: 1.0, influence: 1.0 / 6.0 }; +} + +/// A damped spring as an ease: a mass on a spring with damping, released from 0 toward 1 and +/// played over the time it takes to stay within 0.1 % of 1 (at most 10 seconds of its motion). +/// Values outside the ranges [`Spring::from_physical`] accepts are brought into them when the +/// ease is evaluated. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct SpringEase { + pub mass: f64, + pub stiffness: f64, + pub damping: f64, +} + +impl SpringEase { + /// A gentle spring with a small overshoot (mass 1, stiffness 100, damping 15). + pub const GENTLE: SpringEase = SpringEase { mass: 1.0, stiffness: 100.0, damping: 15.0 }; + + fn apply(self, t: f64) -> f64 { + Spring::physical_lenient(self.mass, self.stiffness, self.damping).ease(t) + } +} + +/// Maps linear progress `t ∈ [0, 1]` to eased progress. +/// +/// The unit variants are the named presets; their names are the file format and the names +/// commands use. [`Easing::apply`] returns exactly 0 for `t <= 0` (and for NaN) and exactly 1 +/// for `t >= 1`, whatever the variant holds. +#[derive(Clone, Debug, Default, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum Easing { + #[default] + Linear, + QuadIn, + QuadOut, + QuadInOut, + CubicIn, + CubicOut, + CubicInOut, + /// The traditional single-slider ease: −100 (ease in) … 0 (linear) … +100 (ease out). + Classic(f64), + /// A cubic Bezier through (0, 0), (x1, y1), (x2, y2), (1, 1), as the CSS Easing Functions + /// specification defines `cubic-bezier()`. Evaluation keeps x1 and x2 within `0..=1` and + /// y1 and y2 within ±[`MAX_EASE_Y`]. + CubicBezier(f64, f64, f64, f64), + QuartIn, + QuartOut, + QuartInOut, + QuintIn, + QuintOut, + QuintInOut, + SineIn, + SineOut, + SineInOut, + BackIn, + BackOut, + BackInOut, + CircIn, + CircOut, + CircInOut, + BounceIn, + BounceOut, + BounceInOut, + ElasticIn, + ElasticOut, + ElasticInOut, + /// A curve of several Bezier segments, shared when copied. + Custom(Arc), + /// A table of values, read between samples by straight lines. + Sampled(Arc), + /// A damped spring. + Spring(SpringEase), + /// Stays at the start until the end, then jumps: 0 for `t < 1`. + Hold, +} + +impl Easing { + pub const LINEAR_LABEL: &'static str = "Linear"; + /// The `smooth` alias's curve. + pub const SMOOTH: Easing = Easing::CubicBezier(0.25, 0.1, 0.25, 1.0); + + /// A cubic Bezier ease, checked: every value finite, `x1` and `x2` within `0..=1` (so time + /// runs forwards), `y1` and `y2` within ±[`MAX_EASE_Y`]. + pub fn cubic_bezier(x1: f64, y1: f64, x2: f64, y2: f64) -> Result { + within(x1, 0.0, 1.0, "x1")?; + within(x2, 0.0, 1.0, "x2")?; + within(y1, -MAX_EASE_Y, MAX_EASE_Y, "y1")?; + within(y2, -MAX_EASE_Y, MAX_EASE_Y, "y2")?; + Ok(Easing::CubicBezier(x1, y1, x2, y2)) + } + + /// The ease of a segment from its two sides: `out` leaving the first key, `into` arriving at + /// the second. Each influence must be within [`MIN_INFLUENCE`] to 1 and each speed finite. + /// The result is the cubic Bezier with handles `(i0, s0 × i0)` and `(1 − i1, 1 − s1 × i1)`. + pub fn from_temporal(out: TemporalEase, into: TemporalEase) -> Result { + finite(out.speed, "out speed")?; + finite(into.speed, "in speed")?; + let i0 = within(out.influence, MIN_INFLUENCE, 1.0, "out influence")?; + let i1 = within(into.influence, MIN_INFLUENCE, 1.0, "in influence")?; + let (y1, y2) = (out.speed * i0, 1.0 - into.speed * i1); + if !(y1.abs() <= MAX_EASE_Y && y2.abs() <= MAX_EASE_Y) { + return Err(EaseError::OutOfRange { what: "speed × influence", min: -MAX_EASE_Y, max: MAX_EASE_Y }); + } + Ok(Easing::CubicBezier(i0, y1, 1.0 - i1, y2)) + } + + /// The two sides of an ease that one cubic Bezier draws (see [`Easing::from_temporal`] and + /// [`Easing::as_bezier`]). A handle with no reach has speed 0. `None` when a handle's reach + /// is so short that its speed is too large to represent. + pub fn temporal(&self) -> Option<(TemporalEase, TemporalEase)> { + let (x1, y1, x2, y2) = self.as_bezier()?; + let (i0, i1) = (x1.clamp(0.0, 1.0), (1.0 - x2).clamp(0.0, 1.0)); + let s0 = if i0 > 0.0 { y1 / i0 } else { 0.0 }; + let s1 = if i1 > 0.0 { (1.0 - y2) / i1 } else { 0.0 }; + if !(s0.is_finite() && s1.is_finite()) { + return None; + } + Some((TemporalEase { speed: s0, influence: i0 }, TemporalEase { speed: s1, influence: i1 })) + } + + /// A spring ease, checked as [`Spring::from_physical`] checks its values. + pub fn spring(mass: f64, stiffness: f64, damping: f64) -> Result { + Spring::from_physical(mass, stiffness, damping)?; + Ok(Easing::Spring(SpringEase { mass, stiffness, damping })) + } + + /// The named ease of `family` easing `dir`. + pub fn preset(family: EaseFamily, dir: EaseDir) -> Easing { + use EaseDir::*; + use EaseFamily::*; + match (family, dir) { + (Quad, In) => Easing::QuadIn, + (Quad, Out) => Easing::QuadOut, + (Quad, InOut) => Easing::QuadInOut, + (Cubic, In) => Easing::CubicIn, + (Cubic, Out) => Easing::CubicOut, + (Cubic, InOut) => Easing::CubicInOut, + (Quart, In) => Easing::QuartIn, + (Quart, Out) => Easing::QuartOut, + (Quart, InOut) => Easing::QuartInOut, + (Quint, In) => Easing::QuintIn, + (Quint, Out) => Easing::QuintOut, + (Quint, InOut) => Easing::QuintInOut, + (Sine, In) => Easing::SineIn, + (Sine, Out) => Easing::SineOut, + (Sine, InOut) => Easing::SineInOut, + (Back, In) => Easing::BackIn, + (Back, Out) => Easing::BackOut, + (Back, InOut) => Easing::BackInOut, + (Circ, In) => Easing::CircIn, + (Circ, Out) => Easing::CircOut, + (Circ, InOut) => Easing::CircInOut, + (Bounce, In) => Easing::BounceIn, + (Bounce, Out) => Easing::BounceOut, + (Bounce, InOut) => Easing::BounceInOut, + (Elastic, In) => Easing::ElasticIn, + (Elastic, Out) => Easing::ElasticOut, + (Elastic, InOut) => Easing::ElasticInOut, + } + } + + /// The family and direction of a named ease. + pub fn family(&self) -> Option<(EaseFamily, EaseDir)> { + use EaseDir::*; + use EaseFamily::*; + Some(match self { + Easing::QuadIn => (Quad, In), + Easing::QuadOut => (Quad, Out), + Easing::QuadInOut => (Quad, InOut), + Easing::CubicIn => (Cubic, In), + Easing::CubicOut => (Cubic, Out), + Easing::CubicInOut => (Cubic, InOut), + Easing::QuartIn => (Quart, In), + Easing::QuartOut => (Quart, Out), + Easing::QuartInOut => (Quart, InOut), + Easing::QuintIn => (Quint, In), + Easing::QuintOut => (Quint, Out), + Easing::QuintInOut => (Quint, InOut), + Easing::SineIn => (Sine, In), + Easing::SineOut => (Sine, Out), + Easing::SineInOut => (Sine, InOut), + Easing::BackIn => (Back, In), + Easing::BackOut => (Back, Out), + Easing::BackInOut => (Back, InOut), + Easing::CircIn => (Circ, In), + Easing::CircOut => (Circ, Out), + Easing::CircInOut => (Circ, InOut), + Easing::BounceIn => (Bounce, In), + Easing::BounceOut => (Bounce, Out), + Easing::BounceInOut => (Bounce, InOut), + Easing::ElasticIn => (Elastic, In), + Easing::ElasticOut => (Elastic, Out), + Easing::ElasticInOut => (Elastic, InOut), + Easing::Linear + | Easing::Classic(_) + | Easing::CubicBezier(..) + | Easing::Custom(_) + | Easing::Sampled(_) + | Easing::Spring(_) + | Easing::Hold => return None, + }) + } + + /// Every named preset: no ease, then each family In, Out, In Out. + pub fn named() -> impl Iterator { + std::iter::once(Easing::Linear).chain(EaseFamily::ALL.into_iter().flat_map(|f| EaseDir::ALL.into_iter().map(move |d| Easing::preset(f, d)))) + } + + /// The preset's name in commands and files (`"QuadIn"`, `"ElasticInOut"`, `"Hold"`), `None` + /// for eases with values. + pub fn name(&self) -> Option { + match self { + Easing::Linear => Some("Linear".into()), + Easing::Hold => Some("Hold".into()), + _ => self.family().map(|(f, d)| format!("{}{}", f.label(), d.label().replace(' ', ""))), + } + } + + /// The preset named `name`, ignoring case, spaces, `-` and `_` (`"back in out"`), with the + /// aliases `none`, `easein`, `easeout`, `easeinout` and `smooth`. + pub fn from_name(name: &str) -> Option { + // No preset or alias is longer than this, so a longer name is unknown and is not copied + // past it. + const LONGEST: usize = 12; + let key: String = name.chars().filter(|c| !matches!(c, '-' | '_' | ' ')).flat_map(char::to_lowercase).take(LONGEST + 1).collect(); + if key.chars().count() > LONGEST { + return None; + } + match key.as_str() { + "none" | "noease" => return Some(Easing::Linear), + "hold" => return Some(Easing::Hold), + "easein" => return Some(Easing::QuadIn), + "easeout" => return Some(Easing::QuadOut), + "easeinout" => return Some(Easing::QuadInOut), + "smooth" => return Some(Easing::SMOOTH), + _ => {} + } + Easing::named().find(|e| e.name().is_some_and(|n| n.to_lowercase() == key)) + } + + /// An English label for menus and reports. + pub fn label(&self) -> String { + match self { + Easing::Linear => Easing::LINEAR_LABEL.to_string(), + Easing::Hold => "Hold".to_string(), + Easing::Classic(s) => format!("Classic {s:+.0}"), + Easing::CubicBezier(..) if *self == Easing::SMOOTH => "Smooth (bezier)".to_string(), + Easing::CubicBezier(a, b, c, d) => format!("Bezier({a:.2}, {b:.2}, {c:.2}, {d:.2})"), + Easing::Custom(_) => "Custom".to_string(), + Easing::Sampled(s) => s.name().to_string(), + Easing::Spring(s) => format!("Spring {:.0}, {:.0}, {:.0}", s.mass, s.stiffness, s.damping), + other => other.family().map_or_else(|| "Custom".to_string(), |(f, d)| format!("{} {}", f.label(), d.label())), + } + } + + /// The single cubic Bezier `(x1, y1, x2, y2)` that draws this ease: exact for linear, the + /// Classic slider, the Quad, Cubic and Back eases in and out, and a custom ease of one + /// segment; the Quad and Cubic in-outs get their usual one-curve approximations. `None` for + /// eases one curve cannot draw (Bounce, Elastic, the other families, hold, springs, sampled + /// tables, custom eases of several segments, and a custom ease of one segment whose handle + /// reaches past the unit box in x). + pub fn as_bezier(&self) -> Option<(f64, f64, f64, f64)> { + const THIRD: f64 = 1.0 / 3.0; + Some(match self { + Easing::Linear => (THIRD, THIRD, 2.0 * THIRD, 2.0 * THIRD), + // t², t³ and (c+1)t³ − ct² and their mirrors, with x(s) = s. + Easing::QuadIn => (THIRD, 0.0, 2.0 * THIRD, THIRD), + Easing::QuadOut => (THIRD, 2.0 * THIRD, 2.0 * THIRD, 1.0), + Easing::CubicIn => (THIRD, 0.0, 2.0 * THIRD, 0.0), + Easing::CubicOut => (THIRD, 1.0, 2.0 * THIRD, 1.0), + Easing::BackIn => (THIRD, 0.0, 2.0 * THIRD, -BACK * THIRD), + Easing::BackOut => (THIRD, 1.0 + BACK * THIRD, 2.0 * THIRD, 1.0), + Easing::QuadInOut => (0.45, 0.0, 0.55, 1.0), + Easing::CubicInOut => (0.65, 0.0, 0.35, 1.0), + Easing::Classic(strength) => { + // The quadratic 2(1 − t)t·c + t², raised to a cubic. + let c = 0.5 + 0.5 * classic_strength(*strength); + (THIRD, 2.0 * c * THIRD, 2.0 * THIRD, (2.0 * c + 1.0) * THIRD) + } + Easing::CubicBezier(a, b, c, d) => bezier_handles(*a, *b, *c, *d), + Easing::Custom(c) => match c.points() { + [a, b] if a.out.x <= 1.0 && b.h_in.x >= -1.0 => (a.out.x, a.out.y, b.at.x + b.h_in.x, b.at.y + b.h_in.y), + _ => return None, + }, + _ => return None, + }) + } + + /// Eased progress at `t`: exactly 0 for `t <= 0` or NaN, exactly 1 for `t >= 1`. + pub fn apply(&self, t: f64) -> f64 { + if t.is_nan() || t <= 0.0 { + return 0.0; + } + if t >= 1.0 { + return 1.0; + } + let v = match self { + Easing::Linear => t, + Easing::Hold => 0.0, + Easing::Classic(strength) => { + // Quadratic Bezier with the middle control point moved by `strength`. + let c = 0.5 + 0.5 * classic_strength(*strength); + 2.0 * (1.0 - t) * t * c + t * t + } + Easing::CubicBezier(x1, y1, x2, y2) => { + let (x1, y1, x2, y2) = bezier_handles(*x1, *y1, *x2, *y2); + bez(solve_monotonic(t, [0.0, x1, x2, 1.0]), [0.0, y1, y2, 1.0]) + } + Easing::Custom(c) => c.apply(t), + Easing::Sampled(s) => s.apply(t), + Easing::Spring(s) => s.apply(t), + named => match named.family() { + Some((f, d)) => eval_named(f, d, t), + None => t, + }, + }; + if v.is_finite() { v } else { t } + } + + /// This ease as a custom curve for a graph editor: exact for linear, Classic, a Bezier, + /// the Quad, Cubic, Back and Bounce families and custom eases; Circ is two circular arcs, + /// and Quart, Quint, Sine and Elastic are fitted by matching values and slopes at a few + /// points (all within 0.5 % of the range everywhere). A sampled ease or a spring becomes the + /// straight segments through [`crate::POLYLINE_POINTS`] of its values, and a hold a corner + /// at the end. + pub fn to_custom(&self) -> CustomEase { + match self { + Easing::Custom(c) => (**c).clone(), + Easing::Sampled(s) => s.to_polyline(), + Easing::Spring(_) => { + let n = crate::MAX_EASE_SAMPLES; + let values = (0..n).map(|i| self.apply(i as f64 / (n - 1) as f64)).collect(); + SampledEase::new("Spring", "", "", values).to_polyline() + } + Easing::Hold => { + // Flat at 0 across the segment, then straight up to 1 at the end. + let third = 1.0 / 3.0; + CustomEase::new(vec![ + EasePoint { at: Vec2::ZERO, h_in: Vec2::ZERO, out: Vec2::new(third, 0.0), smooth: false }, + EasePoint { at: Vec2::new(1.0, 0.0), h_in: Vec2::new(-third, 0.0), out: Vec2::ZERO, smooth: false }, + EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::ZERO, out: Vec2::ZERO, smooth: false }, + ]) + } + Easing::Linear => CustomEase::linear(), + Easing::Classic(_) | Easing::CubicBezier(..) => { + let Some((x1, y1, x2, y2)) = self.as_bezier() else { return CustomEase::linear() }; + CustomEase::from_bezier(x1, y1, x2, y2) + } + named => match named.family() { + Some((f, d)) => fit_named(f, d), + None => CustomEase::linear(), + }, + } + } + + /// The custom curve, when this is one. + pub fn custom(&self) -> Option<&CustomEase> { + match self { + Easing::Custom(c) => Some(c), + _ => None, + } + } + + /// The sampled curve, when this is one. + pub fn sampled(&self) -> Option<&SampledEase> { + match self { + Easing::Sampled(s) => Some(s), + _ => None, + } + } +} + +/// A cubic Bezier's handles as evaluation uses them: x within `0..=1`, y within ±[`MAX_EASE_Y`], +/// and the straight line for a handle that is not finite. +fn bezier_handles(x1: f64, y1: f64, x2: f64, y2: f64) -> (f64, f64, f64, f64) { + if ![x1, y1, x2, y2].iter().all(|v| v.is_finite()) { + return (1.0 / 3.0, 1.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0); + } + (x1.clamp(0.0, 1.0), y1.clamp(-MAX_EASE_Y, MAX_EASE_Y), x2.clamp(0.0, 1.0), y2.clamp(-MAX_EASE_Y, MAX_EASE_Y)) +} + +fn classic_strength(s: f64) -> f64 { + if s.is_finite() { s.clamp(-100.0, 100.0) / 100.0 } else { 0.0 } +} + +fn eval_named(f: EaseFamily, d: EaseDir, t: f64) -> f64 { + match d { + EaseDir::In => f.ease_in(t, false), + EaseDir::Out => 1.0 - f.ease_in(1.0 - t, false), + EaseDir::InOut => { + if t < 0.5 { + 0.5 * f.ease_in(2.0 * t, true) + } else { + 1.0 - 0.5 * f.ease_in(2.0 - 2.0 * t, true) + } + } + } +} + +/// The slope of `y` at `x`, from inside `[lo, hi]`: one-sided, a step in from `x` (so a value +/// pinned at an end, as Elastic's are, does not count), exact for parabolas but for that step. +fn slope(y: &dyn Fn(f64) -> f64, x: f64, lo: f64, hi: f64) -> f64 { + const H: f64 = 1e-6; + let s = if x + 3.0 * H <= hi { + let d = (-3.0 * y(x + H) + 4.0 * y(x + 2.0 * H) - y(x + 3.0 * H)) / (2.0 * H); + let d2 = (y(x + H) - 2.0 * y(x + 2.0 * H) + y(x + 3.0 * H)) / (H * H); + d - d2 * H + } else if x - 3.0 * H >= lo { + let d = (3.0 * y(x - H) - 4.0 * y(x - 2.0 * H) + y(x - 3.0 * H)) / (2.0 * H); + let d2 = (y(x - H) - 2.0 * y(x - 2.0 * H) + y(x - 3.0 * H)) / (H * H); + d + d2 * H + } else { + 0.0 + }; + if s.is_finite() { s } else { 0.0 } +} + +/// The ease in of `f` (its In Out form with `in_out`) as Bezier points: Hermite segments (value +/// and slope matched at each end, so exact for cubic polynomials and for each parabola of +/// Bounce), except Circ, whose quarter circle is two 45° arcs (within 4·10⁻⁶ of the circle). +fn fit_in(f: EaseFamily, in_out: bool) -> Vec { + let pt = |x: f64, y: f64, i: (f64, f64), o: (f64, f64)| EasePoint { + at: Vec2::new(x, y), + h_in: Vec2::new(i.0, i.1), + out: Vec2::new(o.0, o.1), + smooth: false, + }; + if f == EaseFamily::Circ { + // The circle about (0, 1) from (0, 0) to (1, 1); each arc's handles are k = 4/3·tan(φ/4) + // long along the tangents. + let k = 4.0 / 3.0 * (std::f64::consts::PI / 16.0).tan(); + let c = std::f64::consts::FRAC_1_SQRT_2; + return vec![pt(0.0, 0.0, (0.0, 0.0), (k, 0.0)), pt(c, 1.0 - c, (-k * c, -k * c), (k * c, k * c)), pt(1.0, 1.0, (0.0, -k), (0.0, 0.0))]; + } + let y = move |t: f64| f.ease_in(t, in_out); + let mut xs: Vec = Vec::new(); + let pieces = f.pieces_in(); + let bounds: Vec = std::iter::once(0.0).chain(f.breaks_in().iter().copied()).chain(std::iter::once(1.0)).collect(); + for w in bounds.windows(2) { + if let [a, c] = w { + xs.extend((0..pieces).map(|k| a + (c - a) * k as f64 / pieces as f64)); + } + } + xs.push(1.0); + let mut pts: Vec = xs.iter().map(|&x| pt(x, y(x), (0.0, 0.0), (0.0, 0.0))).collect(); + for i in 0..xs.len().saturating_sub(1) { + let (Some(&a), Some(&b)) = (xs.get(i), xs.get(i + 1)) else { continue }; + let h = (b - a) / 3.0; + let (sa, sb) = (slope(&y, a, a, b), slope(&y, b, a, b)); + if let Some(p) = pts.get_mut(i) { + p.out = Vec2::new(h, sa * h); + } + if let Some(p) = pts.get_mut(i + 1) { + p.h_in = Vec2::new(-h, -sb * h); + } + } + pts +} + +/// The curve turned half a turn about (½, ½): an ease in becomes the ease out. +fn mirrored(pts: &[EasePoint]) -> Vec { + pts.iter().rev().map(|p| EasePoint { at: Vec2::new(1.0 - p.at.x, 1.0 - p.at.y), h_in: -p.out, out: -p.h_in, smooth: p.smooth }).collect() +} + +fn scaled(pts: &[EasePoint], by: f64, from: Vec2) -> Vec { + pts.iter().map(|p| EasePoint { at: from + p.at * by, h_in: p.h_in * by, out: p.out * by, smooth: p.smooth }).collect() +} + +/// A named ease as a custom curve (see [`Easing::to_custom`]). +fn fit_named(f: EaseFamily, d: EaseDir) -> CustomEase { + let mut pts = match d { + EaseDir::In => fit_in(f, false), + EaseDir::Out => mirrored(&fit_in(f, false)), + EaseDir::InOut => { + let half = fit_in(f, true); + let mut a = scaled(&half, 0.5, Vec2::ZERO); + let b = scaled(&mirrored(&half), 0.5, Vec2::new(0.5, 0.5)); + // The two halves meet at (½, ½): one point, the first half's in, the second's out. + if let (Some(last), Some(first)) = (a.last_mut(), b.first()) { + last.out = first.out; + } + a.extend(b.into_iter().skip(1)); + a + } + }; + // Points where the slope carries on are smooth (Bounce's floor hits are corners). + let n = pts.len(); + for (i, p) in pts.iter_mut().enumerate() { + p.smooth = + i > 0 && i + 1 < n && p.h_in.length() > 1e-9 && p.out.length() > 1e-9 && (p.h_in.normalized().dot(p.out.normalized()) + 1.0).abs() < 1e-3; + } + CustomEase::new(pts) +} diff --git a/crates/ease/src/lib.rs b/crates/ease/src/lib.rs new file mode 100644 index 0000000000..b63fb31e13 --- /dev/null +++ b/crates/ease/src/lib.rs @@ -0,0 +1,228 @@ +//! Easing curves, keyed tracks, motion paths and springs. +//! +//! * [`Easing`] maps linear progress `t` in `0..=1` to eased progress: no ease, hold, the +//! Classic slider, nine named families (Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce, +//! Elastic), each In, Out and In Out, one cubic Bezier (also built from speed and influence, +//! [`TemporalEase`]), an editable multi-segment [`CustomEase`], a [`SampledEase`] table and a +//! [`SpringEase`]. [`Easing::apply`] is a pure function that does not allocate, and it returns +//! exactly 0 at the start and exactly 1 at the end. +//! * [`Track`] holds keys of any [`Animatable`] value (`f32`, `f64`, [`Vec2`], `[f32; N]`, +//! `[f64; N]`) at times in seconds, each easing into the next. Sampling is a binary search and +//! does not allocate for these value types; for another [`Animatable`] type it allocates +//! whatever that type's `Clone` and `Animatable` implementations allocate. +//! * [`MotionPath`] is a chain of cubic Bezier segments with arc-length tables built once, for +//! constant-speed motion along a curve. +//! * [`Spring`] and [`SpringState`] move a value toward a target as a damped spring. Each step +//! uses the exact solution of the spring equation, so a step costs the same at any frame rate +//! and length. +//! +//! The named families are the classic public easing equations published by Robert Penner. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod custom; +mod easing; +mod path; +mod sampled; +mod spring; +mod track; +mod vec2; + +pub use custom::{CustomEase, EasePoint, Handle, MAX_EASE_POINTS, MAX_EASE_Y}; +pub use easing::{EaseDir, EaseFamily, Easing, MIN_INFLUENCE, SpringEase, TemporalEase}; +pub use path::{MAX_PATH_SEGMENTS, MotionPath}; +pub use sampled::{MAX_EASE_SAMPLES, POLYLINE_POINTS, SampledEase}; +pub use spring::{MAX_DAMPING_RATIO, MAX_SPRING_HZ, Spring, SpringState}; +pub use track::{Animatable, Key, MAX_TRACK_KEYS, Track}; +pub use vec2::Vec2; + +/// Why a value was refused. +#[derive(Clone, Debug, PartialEq)] +pub enum EaseError { + /// The named input is NaN or infinite. + NotFinite(&'static str), + /// The named input is outside the range it must lie in. + OutOfRange { what: &'static str, min: f64, max: f64 }, + /// A track or path holds as many entries as it may. + Full(usize), + /// A path or curve needs more points than it was given. + TooFew { what: &'static str, need: usize }, + /// The track has no keys. + Empty, + /// Two keys are at this time. + SameTime(f64), + /// The result is too large to represent. + Overflow, +} + +impl std::fmt::Display for EaseError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + EaseError::NotFinite(what) => write!(f, "{what} is not a finite number"), + EaseError::OutOfRange { what, min, max } => write!(f, "{what} must be between {min} and {max}"), + EaseError::Full(n) => write!(f, "at most {n} entries are allowed"), + EaseError::TooFew { what, need } => write!(f, "{what} needs at least {need} points"), + EaseError::Empty => write!(f, "the track has no keys"), + EaseError::SameTime(t) => write!(f, "two keys are at {t} s"), + EaseError::Overflow => write!(f, "the result is too large"), + } + } +} + +impl std::error::Error for EaseError {} + +/// `v` itself when it is finite. +pub(crate) fn finite(v: f64, what: &'static str) -> Result { + if v.is_finite() { Ok(v) } else { Err(EaseError::NotFinite(what)) } +} + +/// `v` itself when it is finite and within `min..=max`. +pub(crate) fn within(v: f64, min: f64, max: f64, what: &'static str) -> Result { + let v = finite(v, what)?; + if (min..=max).contains(&v) { Ok(v) } else { Err(EaseError::OutOfRange { what, min, max }) } +} + +/// The value `t` of the way from `a` to `b`. When a step on the way is too large to represent +/// (`a` and `b` near opposite ends of the `f64` range, or an overshooting `t`), it is worked +/// out at half scale, so only a result too large to represent is infinite. `t` of exactly 0 or +/// 1 returns `a` or `b` itself. +pub(crate) fn lerp(a: f64, b: f64, t: f64) -> f64 { + if t == 0.0 { + return a; + } + if t == 1.0 { + return b; + } + let r = a + (b - a) * t; + if r.is_finite() { r } else { 2.0 * (0.5 * a + (0.5 * b - 0.5 * a) * t) } +} + +/// Reads a list, keeping its first `max` entries and skipping the rest without storing them. +#[cfg(feature = "serde")] +pub(crate) fn read_first<'de, D, T>(d: D, max: usize) -> Result, D::Error> +where + D: serde::Deserializer<'de>, + T: serde::Deserialize<'de>, +{ + use serde::de::{IgnoredAny, SeqAccess, Visitor}; + struct V(usize, std::marker::PhantomData); + impl<'de, T: serde::Deserialize<'de>> Visitor<'de> for V { + type Value = Vec; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "a list") + } + fn visit_seq>(self, mut seq: A) -> Result, A::Error> { + let mut out = Vec::with_capacity(seq.size_hint().unwrap_or(0).min(self.0).min(1024)); + while out.len() < self.0 { + match seq.next_element()? { + Some(v) => out.push(v), + None => return Ok(out), + } + } + while seq.next_element::()?.is_some() {} + Ok(out) + } + } + d.deserialize_seq(V(max, std::marker::PhantomData)) +} + +/// Reads a string and keeps only what `clean` makes of it, so a long string in a file is never +/// copied whole into the value. +/// +/// This bounds the memory the value keeps. A format that has to decode escapes may still build +/// the whole string in a temporary buffer first; that buffer is no larger than the input, so the +/// caller bounds it by limiting the size of the file it reads. +#[cfg(feature = "serde")] +pub(crate) fn read_cleaned<'de, D: serde::Deserializer<'de>>(d: D, clean: fn(&str) -> String) -> Result { + struct V(fn(&str) -> String); + impl serde::de::Visitor<'_> for V { + type Value = String; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "a string") + } + fn visit_str(self, s: &str) -> Result { + Ok((self.0)(s)) + } + } + d.deserialize_str(V(clean)) +} + +/// Cubic Bezier in one dimension. +pub(crate) fn bez(t: f64, p: [f64; 4]) -> f64 { + let mt = 1.0 - t; + mt * mt * mt * p[0] + 3.0 * mt * mt * t * p[1] + 3.0 * mt * t * t * p[2] + t * t * t * p[3] +} + +/// The derivative of [`bez`]. +pub(crate) fn dbez(t: f64, p: [f64; 4]) -> f64 { + let mt = 1.0 - t; + 3.0 * mt * mt * (p[1] - p[0]) + 6.0 * mt * t * (p[2] - p[1]) + 3.0 * t * t * (p[3] - p[2]) +} + +/// Most steps [`solve_monotonic`] takes. +pub(crate) const SOLVE_STEPS: u32 = 64; +/// How close [`solve_monotonic`] brings `bez(s)` to `x`, relative to the curve's span. +pub(crate) const SOLVE_TOLERANCE: f64 = 1e-12; + +/// The parameter where the Bezier `p` (non-decreasing, as it is when its inner points lie +/// between its ends) reaches `x`: Newton steps kept inside a shrinking bracket, halving when a step leaves it, to +/// within [`SOLVE_TOLERANCE`] of the span in at most [`SOLVE_STEPS`] steps. The curve is solved +/// shifted to start at 0 and scaled to a span of 1, so a narrow segment far from 0 is solved as +/// precisely as a wide one. The curve with both handles at full reach (`p1 = p3`, `p2 = p0`), +/// whose slope is zero halfway, is inverted in closed form. +pub(crate) fn solve_monotonic(x: f64, p: [f64; 4]) -> f64 { + solve_counted(x, p).0 +} + +/// [`solve_monotonic`] and the number of steps it took. +pub(crate) fn solve_counted(x: f64, p: [f64; 4]) -> (f64, u32) { + let span = p[3] - p[0]; + if span.is_nan() || span <= 0.0 { + return (0.5, 0); + } + if x <= p[0] { + return (0.0, 0); + } + if x >= p[3] { + return (1.0, 0); + } + let u = (x - p[0]) / span; + if p[1] == p[3] && p[2] == p[0] { + // x(s) = 0.5 + 4 (s − 0.5)³ on the unit span. + return ((0.5 + ((u - 0.5) * 0.25).cbrt()).clamp(0.0, 1.0), 0); + } + let q = [0.0, (p[1] - p[0]) / span, (p[2] - p[0]) / span, 1.0]; + let (mut lo, mut hi) = (0.0f64, 1.0f64); + let mut s = u.clamp(0.0, 1.0); + for step in 1..=SOLVE_STEPS { + let err = bez(s, q) - u; + if err.abs() <= SOLVE_TOLERANCE { + return (s, step); + } + if err < 0.0 { + lo = s; + } else { + hi = s; + } + let d = dbez(s, q); + let next = if d.abs() > 1e-300 { s - err / d } else { f64::NAN }; + s = if next > lo && next < hi { next } else { 0.5 * (lo + hi) }; + } + (s, SOLVE_STEPS) +} + +#[cfg(test)] +#[path = "tests/easing_tests.rs"] +mod easing_tests; + +#[cfg(test)] +#[path = "tests/track_tests.rs"] +mod track_tests; + +#[cfg(test)] +#[path = "tests/path_tests.rs"] +mod path_tests; + +#[cfg(test)] +#[path = "tests/spring_tests.rs"] +mod spring_tests; diff --git a/crates/ease/src/path.rs b/crates/ease/src/path.rs new file mode 100644 index 0000000000..fc6a065511 --- /dev/null +++ b/crates/ease/src/path.rs @@ -0,0 +1,355 @@ +//! [`MotionPath`]: constant-speed motion along a chain of cubic Bezier segments. + +use crate::{EaseError, Vec2, bez, dbez}; + +/// Most segments one path holds. +pub const MAX_PATH_SEGMENTS: usize = 10_000; +/// Cells in each segment's arc-length table. +const ARC_N: usize = 32; +/// Most steps `Segment::param_at` takes; halving a table cell this often reaches the smallest +/// step an `f64` parameter can take. +const PARAM_STEPS: u32 = 64; + +/// 5-point Gauss-Legendre nodes and weights on −1..1. +const GAUSS: [(f64, f64); 5] = [ + (0.0, 0.568_888_888_888_888_9), + (-0.538_469_310_105_683_1, 0.478_628_670_499_366_5), + (0.538_469_310_105_683_1, 0.478_628_670_499_366_5), + (-0.906_179_845_938_664, 0.236_926_885_056_189_1), + (0.906_179_845_938_664, 0.236_926_885_056_189_1), +]; + +#[derive(Clone, Debug, PartialEq)] +struct Segment { + p: [Vec2; 4], + /// Arc length from the segment's start at `u = i / ARC_N`. + table: [f64; ARC_N + 1], + /// Both handles on the chord: the segment is the straight line between its ends. + straight: bool, + /// The parameters inside `0..1` where the x or y derivative is zero, in order, with the + /// unused entries set to 1. Arc lengths are integrated in pieces split there, since the + /// speed has a kink where the curve stops and turns back. + stops: [f64; 4], + /// Arc length from the path's start to this segment's start. + start: f64, +} + +impl Segment { + fn new(p: [Vec2; 4], start: f64) -> Segment { + let straight = on_chord(p[0], p[1], p[3]) && on_chord(p[0], p[2], p[3]); + let stops = stationary(&p); + let mut table = [0.0; ARC_N + 1]; + if straight { + let len = p[0].distance(p[3]); + for (i, v) in table.iter_mut().enumerate() { + *v = len * (i as f64 / ARC_N as f64); + } + } else { + let mut acc = 0.0; + for i in 1..=ARC_N { + acc += arc(&p, &stops, (i - 1) as f64 / ARC_N as f64, i as f64 / ARC_N as f64); + if let Some(v) = table.get_mut(i) { + *v = acc; + } + } + } + Segment { p, table, straight, stops, start } + } + + fn length(&self) -> f64 { + self.table[ARC_N] + } + + fn point(&self, u: f64) -> Vec2 { + let p = &self.p; + Vec2::new(bez(u, [p[0].x, p[1].x, p[2].x, p[3].x]), bez(u, [p[0].y, p[1].y, p[2].y, p[3].y])) + } + + /// The parameter at arc length `s` from the segment's start (`0..=length`): the table + /// cell's straight-line guess refined with Newton steps on the true arc length, kept inside + /// a shrinking bracket and halving it when a step would leave it (where the curve stands + /// still, for one), until the arc length is within 1e-12 of the segment's length of `s`, in + /// at most [`PARAM_STEPS`] steps. + fn param_at(&self, s: f64) -> f64 { + let len = self.length(); + if len <= 0.0 { + return 0.0; + } + let s = s.clamp(0.0, len); + if self.straight { + return s / len; + } + let i = self.table.partition_point(|&v| v < s).clamp(1, ARC_N); + let (Some(&a), Some(&b)) = (self.table.get(i - 1), self.table.get(i)) else { return s / len }; + let (u0, u1) = ((i - 1) as f64 / ARC_N as f64, i as f64 / ARC_N as f64); + let mut u = u0 + if b > a { (s - a) / (b - a) } else { 0.0 } * (u1 - u0); + let (mut lo, mut hi) = (u0, u1); + for _ in 0..PARAM_STEPS { + let e = a + arc(&self.p, &self.stops, u0, u) - s; + if e.abs() <= 1e-12 * len { + break; + } + if e < 0.0 { + lo = u; + } else { + hi = u; + } + let d = speed(&self.p, u); + let next = if d > 0.0 { u - e / d } else { f64::NAN }; + u = if next > lo && next < hi { next } else { 0.5 * (lo + hi) }; + } + u + } + + /// The direction of travel at `u`, or the chord's where the curve's derivative vanishes. + fn direction(&self, u: f64) -> Vec2 { + let p = &self.p; + let d = Vec2::new(dbez(u, [p[0].x, p[1].x, p[2].x, p[3].x]), dbez(u, [p[0].y, p[1].y, p[2].y, p[3].y])).normalized(); + if d != Vec2::ZERO { + return d; + } + // At an end whose handle sits on it, the curve leaves toward the next control point. + let toward = if u < 0.5 { + [p[1], p[2], p[3]].into_iter().find(|q| *q != p[0]).map(|q| q - p[0]) + } else { + [p[2], p[1], p[0]].into_iter().find(|q| *q != p[3]).map(|q| p[3] - q) + }; + toward.unwrap_or(Vec2::ZERO).normalized() + } +} + +/// |dB/du|. +fn speed(p: &[Vec2; 4], u: f64) -> f64 { + Vec2::new(dbez(u, [p[0].x, p[1].x, p[2].x, p[3].x]), dbez(u, [p[0].y, p[1].y, p[2].y, p[3].y])).length() +} + +/// Arc length between parameters `a` and `b` (Gauss-Legendre; exact enough on one table cell), +/// in pieces split at the parameters `stops` that lie between them. +fn arc(p: &[Vec2; 4], stops: &[f64; 4], a: f64, b: f64) -> f64 { + let mut from = a; + let mut total = 0.0; + for &r in stops.iter().filter(|&&r| r > a && r < b) { + total += gauss(p, from, r); + from = r; + } + total + gauss(p, from, b) +} + +/// [`arc`] over one piece. Each term is scaled by the interval before they are added, so a +/// length near the largest `f64` does not overflow on the way. +fn gauss(p: &[Vec2; 4], a: f64, b: f64) -> f64 { + let (m, h) = ((a + b) * 0.5, (b - a) * 0.5); + GAUSS.iter().map(|(x, w)| w * h * speed(p, m + h * x)).sum::() +} + +/// The parameters inside `0..1` where the x or y derivative of the segment `p` is zero, sorted +/// and padded with 1 (see `Segment::stops`). +fn stationary(p: &[Vec2; 4]) -> [f64; 4] { + let mut out = [1.0; 4]; + let mut n = 0; + for k in [[p[0].x, p[1].x, p[2].x, p[3].x], [p[0].y, p[1].y, p[2].y, p[3].y]] { + for r in quadratic_roots(k[1] - k[0], k[2] - k[1], k[3] - k[2]) { + if let Some(slot) = out.get_mut(n) { + *slot = r; + n += 1; + } + } + } + out.sort_by(f64::total_cmp); + out +} + +/// The roots inside `0..1` of the quadratic with Bernstein coefficients `k0`, `k1` and `k2` +/// (a cubic's derivative, up to a factor of 3). The coefficients are scaled to the largest +/// first, so coordinates near the ends of the `f64` range do not overflow when squared. +fn quadratic_roots(k0: f64, k1: f64, k2: f64) -> impl Iterator { + let m = k0.abs().max(k1.abs()).max(k2.abs()); + let (k0, k1, k2) = if m.is_finite() && m > 0.0 { (k0 / m, k1 / m, k2 / m) } else { (0.0, 0.0, 0.0) }; + // a u² + b u + c in powers of u. + let (a, b, c) = (k0 - 2.0 * k1 + k2, 2.0 * (k1 - k0), k0); + let roots = if a.abs() < 1e-12 { + [if b != 0.0 { -c / b } else { f64::NAN }, f64::NAN] + } else { + let disc = b * b - 4.0 * a * c; + if disc < 0.0 { + [f64::NAN, f64::NAN] + } else { + // The root of larger size first, then the other from their product, without + // cancellation. + let q = -0.5 * (b + disc.sqrt().copysign(b)); + [q / a, if q != 0.0 { c / q } else { f64::NAN }] + } + }; + roots.into_iter().filter(|r| *r > 0.0 && *r < 1.0) +} + +/// Whether control point `c` lies on the segment `a`–`b` (within rounding). +fn on_chord(a: Vec2, c: Vec2, b: Vec2) -> bool { + let (mut d, mut v) = (b - a, c - a); + // Scaled to the largest component first, so squaring coordinates near 1e154 and above does + // not overflow and make a curve look straight. + let scale = d.x.abs().max(d.y.abs()).max(v.x.abs()).max(v.y.abs()); + if scale.is_finite() && scale > 0.0 { + (d, v) = (Vec2::new(d.x / scale, d.y / scale), Vec2::new(v.x / scale, v.y / scale)); + } + let dd = d.dot(d); + if dd <= 0.0 { + // A segment of zero length is straight when its handles sit on its point. + return v == Vec2::ZERO; + } + let t = v.dot(d) / dd; + let off = v - d * t; + (0.0..=1.0).contains(&t) && off.dot(off) <= dd * 1e-28 +} + +/// A path of cubic Bezier segments with an arc-length table per segment, built once, so a point +/// at a distance along it costs a binary search and a few curve evaluations and does not +/// allocate. +/// +/// A distance before the start or past the end continues in a straight line along the path's +/// direction there, so an ease that overshoots carries the motion past the end the same way on +/// curved and straight paths. +#[derive(Clone, Debug, PartialEq)] +pub struct MotionPath { + segments: Vec, + length: f64, + /// The first and last segments that have length (the first and last when none has), so the + /// ends' directions skip anchors repeated at an end. + ends: (usize, usize), +} + +impl MotionPath { + /// A path from the absolute points `[p0, c1, c2, p1, c3, c4, p2, …]` (3n + 1 of them, n from + /// 1 to [`MAX_PATH_SEGMENTS`]). An error for a wrong count, a point that is not finite, or + /// a path too long to measure. + pub fn new(points: &[Vec2]) -> Result { + if points.len() < 4 { + return Err(EaseError::TooFew { what: "a motion path", need: 4 }); + } + if points.len() % 3 != 1 { + return Err(EaseError::OutOfRange { what: "the point count (3n + 1)", min: 4.0, max: (3 * MAX_PATH_SEGMENTS + 1) as f64 }); + } + if points.len() > 3 * MAX_PATH_SEGMENTS + 1 { + return Err(EaseError::Full(MAX_PATH_SEGMENTS)); + } + if points.iter().any(|p| !p.is_finite()) { + return Err(EaseError::NotFinite("path point")); + } + let mut segments = Vec::with_capacity(points.len() / 3); + let mut start = 0.0; + for w in points.windows(4).step_by(3) { + let [a, b, c, d] = w else { continue }; + let s = Segment::new([*a, *b, *c, *d], start); + start += s.length(); + segments.push(s); + } + if !start.is_finite() { + return Err(EaseError::Overflow); + } + let first = segments.iter().position(|g| g.length() > 0.0).unwrap_or(0); + let last = segments.iter().rposition(|g| g.length() > 0.0).unwrap_or(segments.len().saturating_sub(1)); + Ok(MotionPath { segments, length: start, ends: (first, last) }) + } + + /// A smooth path through `anchors` (at least 2), its handles set automatically: each inner + /// anchor's handles point along the line from the anchor before it to the anchor after it, + /// a sixth of that line long, and an end anchor's handle points a sixth of the way toward + /// its neighbor. A side that faces an anchor at the same place has no handle, so two equal + /// anchors make a segment of zero length. + pub fn through(anchors: &[Vec2]) -> Result { + if anchors.len() < 2 { + return Err(EaseError::TooFew { what: "a motion path", need: 2 }); + } + if anchors.len() > MAX_PATH_SEGMENTS + 1 { + return Err(EaseError::Full(MAX_PATH_SEGMENTS)); + } + if anchors.iter().any(|p| !p.is_finite()) { + return Err(EaseError::NotFinite("path point")); + } + let n = anchors.len(); + let at = |i: usize| anchors.get(i).copied().unwrap_or(Vec2::ZERO); + let handles = |i: usize| -> (Vec2, Vec2) { + let (a, p, c) = (at(i.saturating_sub(1)), at(i), at((i + 1).min(n - 1))); + let out = (c - a) * (1.0 / 6.0); + let h_in = if i > 0 && a == p { Vec2::ZERO } else { -out }; + let h_out = if i + 1 < n && c == p { Vec2::ZERO } else { out }; + (h_in, h_out) + }; + let mut points = Vec::with_capacity(3 * n - 2); + for i in 0..n { + let (h_in, h_out) = handles(i); + if i > 0 { + points.push(at(i) + h_in); + } + points.push(at(i)); + if i + 1 < n { + points.push(at(i) + h_out); + } + } + MotionPath::new(&points) + } + + /// The path's length. + pub fn length(&self) -> f64 { + self.length + } + + /// How many segments the path has. + pub fn segments(&self) -> usize { + self.segments.len() + } + + /// The segment holding distance `s` (clamped to the path) and the distance into it. + fn locate(&self, s: f64) -> Option<(&Segment, f64)> { + let i = self.segments.partition_point(|g| g.start <= s).saturating_sub(1); + let g = self.segments.get(i)?; + Some((g, s - g.start)) + } + + /// The segments at the ends (see the `ends` field). + fn ends(&self) -> Option<(&Segment, &Segment)> { + Some((self.segments.get(self.ends.0)?, self.segments.get(self.ends.1)?)) + } + + /// The point `s` along the path. Before the start and past the end it continues along the + /// path's direction there; NaN and −∞ give the start, and +∞ the end. + pub fn point_at_length(&self, s: f64) -> Vec2 { + let Some((first, last)) = self.ends() else { return Vec2::ZERO }; + if s.is_nan() || s <= 0.0 { + let s = if s.is_finite() { s } else { 0.0 }; + return first.p[0] + first.direction(0.0) * s; + } + if s >= self.length { + let past = if s.is_finite() { s - self.length } else { 0.0 }; + return last.p[3] + last.direction(1.0) * past; + } + match self.locate(s) { + Some((g, into)) if g.straight => { + let len = g.length(); + if len > 0.0 { g.p[0].lerp(g.p[3], into / len) } else { g.p[0] } + } + Some((g, into)) => g.point(g.param_at(into)), + None => first.p[0], + } + } + + /// The point `progress` of the way along the path (0 the start, 1 the end). + pub fn point_at(&self, progress: f64) -> Vec2 { + self.point_at_length(progress * self.length) + } + + /// The unit direction of travel `s` along the path (zero for a path of zero length). + pub fn direction_at_length(&self, s: f64) -> Vec2 { + let Some((first, last)) = self.ends() else { return Vec2::ZERO }; + if s.is_nan() || s <= 0.0 { + return first.direction(0.0); + } + if s >= self.length { + return last.direction(1.0); + } + match self.locate(s) { + Some((g, into)) => g.direction(g.param_at(into)), + None => Vec2::ZERO, + } + } +} diff --git a/crates/ease/src/sampled.rs b/crates/ease/src/sampled.rs new file mode 100644 index 0000000000..314613166f --- /dev/null +++ b/crates/ease/src/sampled.rs @@ -0,0 +1,203 @@ +//! [`SampledEase`]: an ease kept as a table of values. + +use crate::Vec2; +use crate::custom::{CustomEase, EasePoint, MAX_EASE_Y}; + +/// Most samples a sampled ease keeps (longer tables are thinned evenly). +pub const MAX_EASE_SAMPLES: usize = 1025; +/// Points of the custom curve a sampled ease becomes when edited (of [`crate::MAX_EASE_POINTS`]). +pub const POLYLINE_POINTS: usize = 48; +/// Longest source or ease id a sampled ease keeps. +const MAX_EASE_ID: usize = 64; +/// Longest name a sampled ease keeps. +const MAX_EASE_NAME: usize = 64; + +/// An ease as a table: `values[i]` is the eased progress at `t = i / (n - 1)`, read between +/// samples by linear interpolation, so evaluation is a constant-time function of `t`. It keeps +/// a name and where it came from (a source id, such as a plug-in's, and the ease's id there). +/// +/// Always valid, however it was made: 2 to [`MAX_EASE_SAMPLES`] finite values within +/// ±[`MAX_EASE_Y`], starting at exactly 0 and ending at exactly 1. +#[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "serde", serde(from = "SampledEaseFile"))] +pub struct SampledEase { + name: String, + plugin: String, + ease: String, + values: Vec, +} + +#[cfg(feature = "serde")] +#[derive(serde::Deserialize)] +struct SampledEaseFile { + #[serde(default, deserialize_with = "read_name")] + name: String, + #[serde(default, deserialize_with = "read_id")] + plugin: String, + #[serde(default, deserialize_with = "read_id")] + ease: String, + #[serde(default, deserialize_with = "read_values")] + values: Vec, +} + +/// Most values read from a file's list; the rest are skipped. +#[cfg(feature = "serde")] +const MAX_SAMPLE_INPUT: usize = 65_536; + +#[cfg(feature = "serde")] +fn read_name<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + crate::read_cleaned(d, |s| ease_name(s).unwrap_or_default()) +} + +#[cfg(feature = "serde")] +fn read_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + crate::read_cleaned(d, ease_id) +} + +#[cfg(feature = "serde")] +fn read_values<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + crate::read_first(d, MAX_SAMPLE_INPUT) +} + +#[cfg(feature = "serde")] +impl From for SampledEase { + fn from(f: SampledEaseFile) -> SampledEase { + SampledEase::new(&f.name, &f.plugin, &f.ease, f.values) + } +} + +/// An id as a sampled ease keeps it: `[A-Za-z0-9._-]`, at most [`MAX_EASE_ID`] characters. +fn ease_id(s: &str) -> String { + s.chars().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')).take(MAX_EASE_ID).collect() +} + +/// A name as kept: control characters, bidirectional overrides and invisible format characters +/// (zero-width spaces and joiners, word joiners, the byte-order mark, soft hyphens) removed, +/// trimmed, at most [`MAX_EASE_NAME`] characters; `None` when nothing is left. +fn ease_name(name: &str) -> Option { + let n: String = name + .chars() + .filter(|c| { + !c.is_control() + && !matches!( + c, + '\u{ad}' | '\u{180e}' | '\u{200b}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2060}'..='\u{2069}' | '\u{feff}' + ) + }) + .skip_while(|c| c.is_whitespace()) + .take(MAX_EASE_NAME) + .collect(); + let n = n.trim().to_string(); + (!n.is_empty()).then_some(n) +} + +/// The index of the `k`th of [`MAX_EASE_SAMPLES`] samples spread evenly over `n` values, +/// computed in 128 bits so a long table cannot overflow a 32-bit `usize`. +pub(crate) fn thinned(k: usize, n: usize) -> usize { + let i = (k as u128) * (n.saturating_sub(1) as u128) / ((MAX_EASE_SAMPLES - 1) as u128); + usize::try_from(i).unwrap_or(usize::MAX) +} + +impl SampledEase { + /// A valid table from any values (see the type's docs): a longer table is thinned evenly, a + /// value that is not finite becomes the straight line's, values are clamped, the ends pinned; + /// fewer than two values make the straight line. + pub fn new(name: &str, plugin: &str, ease: &str, mut values: Vec) -> SampledEase { + if values.len() > MAX_EASE_SAMPLES { + let n = values.len(); + values = (0..MAX_EASE_SAMPLES).filter_map(|k| values.get(thinned(k, n)).copied()).collect(); + } + if values.len() < 2 { + values = vec![0.0, 1.0]; + } + let last = (values.len() - 1) as f64; + for (i, v) in values.iter_mut().enumerate() { + *v = if v.is_finite() { v.clamp(-MAX_EASE_Y, MAX_EASE_Y) } else { i as f64 / last }; + } + if let Some(v) = values.first_mut() { + *v = 0.0; + } + if let Some(v) = values.last_mut() { + *v = 1.0; + } + SampledEase { name: ease_name(name).unwrap_or_else(|| "Sampled ease".to_string()), plugin: ease_id(plugin), ease: ease_id(ease), values } + } + + /// The name an ease menu shows. + pub fn name(&self) -> &str { + &self.name + } + /// The id of the source it came from. + pub fn plugin(&self) -> &str { + &self.plugin + } + /// Its id within that source. + pub fn ease(&self) -> &str { + &self.ease + } + pub fn values(&self) -> &[f64] { + &self.values + } + + /// A table a caller supplies, checked: an error for a value that is not finite or outside + /// ±[`MAX_EASE_Y`], fewer than 2 values or more than [`MAX_EASE_SAMPLES`]. The ends are then + /// pinned to 0 and 1 as [`SampledEase::new`] does. + pub fn try_new(name: &str, plugin: &str, ease: &str, values: Vec) -> Result { + for v in &values { + crate::within(*v, -MAX_EASE_Y, MAX_EASE_Y, "sample")?; + } + if values.len() < 2 { + return Err(crate::EaseError::TooFew { what: "a sampled ease", need: 2 }); + } + if values.len() > MAX_EASE_SAMPLES { + return Err(crate::EaseError::Full(MAX_EASE_SAMPLES)); + } + Ok(SampledEase::new(name, plugin, ease, values)) + } + + /// The eased value at time `t`, between the two nearest samples. `t` outside `0..=1` is + /// clamped, and NaN reads as 0. + pub fn apply(&self, t: f64) -> f64 { + let t = if t.is_finite() { + t.clamp(0.0, 1.0) + } else if t > 0.0 { + 1.0 + } else { + 0.0 + }; + let last = self.values.len().saturating_sub(1); + if last == 0 { + return t; + } + let x = t * last as f64; + let i = (x.floor() as usize).min(last - 1); + let f = x - i as f64; + let (a, b) = (self.values.get(i).copied().unwrap_or(0.0), self.values.get(i + 1).copied().unwrap_or(1.0)); + a + (b - a) * f + } + + /// The custom curve of straight segments through [`POLYLINE_POINTS`] of its samples, for a + /// graph editor: editing a sampled ease makes it a custom ease drawn like it, with room left + /// to add points. + pub fn to_polyline(&self) -> CustomEase { + let n = self.values.len(); + let m = POLYLINE_POINTS.min(n).max(2); + let at: Vec = (0..m) + .map(|k| { + let i = k * (n - 1) / (m - 1); + Vec2::new(i as f64 / (n - 1).max(1) as f64, self.values.get(i).copied().unwrap_or(0.0)) + }) + .collect(); + let pts = at + .iter() + .enumerate() + .map(|(k, p)| { + let prev = if k == 0 { *p } else { at.get(k - 1).copied().unwrap_or(*p) }; + let next = at.get(k + 1).copied().unwrap_or(*p); + EasePoint { at: *p, h_in: (prev - *p) * (1.0 / 3.0), out: (next - *p) * (1.0 / 3.0), smooth: false } + }) + .collect(); + CustomEase::new(pts) + } +} diff --git a/crates/ease/src/spring.rs b/crates/ease/src/spring.rs new file mode 100644 index 0000000000..f50dedec43 --- /dev/null +++ b/crates/ease/src/spring.rs @@ -0,0 +1,247 @@ +//! Damped springs: [`Spring`] and [`SpringState`]. +//! +//! A spring pulls a value `x` toward a target with +//! +//! ```text +//! x'' = −ω² (x − target) − 2ζω x' +//! ``` +//! +//! where `ω` is the natural angular frequency and `ζ` the damping ratio (below 1 the value +//! overshoots and swings back, at 1 it arrives as fast as it can without overshooting, above 1 +//! it creeps in). [`SpringState::step`] moves the value by the exact solution of that equation +//! over the step, so a step costs O(1), any step length is stable, and many short steps give the +//! same value as one long one. + +use crate::{EaseError, within}; + +/// Highest natural frequency a spring may have, in swings per second. +pub const MAX_SPRING_HZ: f64 = 10_000.0; +/// Highest damping ratio a spring may have. +pub const MAX_DAMPING_RATIO: f64 = 1e6; +/// The ranges [`Spring::from_physical`] accepts: mass, stiffness and damping coefficient. +const MASS: (f64, f64) = (0.01, 1e4); +const STIFFNESS: (f64, f64) = (0.01, 1e6); +const DAMPING: (f64, f64) = (0.0, 1e6); +/// Longest motion a spring ease plays, in seconds of the spring's own time. +const MAX_SETTLE: f64 = 10.0; + +/// A damped spring's constants. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Spring { + omega: f64, + zeta: f64, +} + +impl Spring { + /// A spring that would swing `frequency` times a second without damping, with damping ratio + /// `damping`. `frequency` must be above 0 and at most [`MAX_SPRING_HZ`], `damping` within 0 + /// to [`MAX_DAMPING_RATIO`]. + pub fn new(frequency: f64, damping: f64) -> Result { + let f = within(frequency, 0.0, MAX_SPRING_HZ, "frequency")?; + if f <= 0.0 { + return Err(EaseError::OutOfRange { what: "frequency", min: f64::MIN_POSITIVE, max: MAX_SPRING_HZ }); + } + let z = within(damping, 0.0, MAX_DAMPING_RATIO, "damping")?; + Ok(Spring::raw(f, z)) + } + + /// A spring from two `0..=1` controls: `strength` sets the frequency from 0.5 to 10 swings a + /// second, evenly spread in pitch, and `damping` the ratio (0 swings on, 2/3 is critical, + /// 1 gives [`MAX_DAMPING_RATIO`]). + pub fn from_controls(strength: f64, damping: f64) -> Result { + let s = within(strength, 0.0, 1.0, "strength")?; + let d = within(damping, 0.0, 1.0, "damping")?; + let zeta = if d >= 1.0 { MAX_DAMPING_RATIO } else { (0.5 * d / (1.0 - d)).min(MAX_DAMPING_RATIO) }; + Ok(Spring::raw(0.5 * 20f64.powf(s), zeta)) + } + + /// A mass on a spring with damping: `mass` within 0.01 to 10,000, `stiffness` within 0.01 + /// to 1,000,000 and the damping coefficient `damping` within 0 to 1,000,000. An error when + /// the three give a damping ratio above [`MAX_DAMPING_RATIO`]. + pub fn from_physical(mass: f64, stiffness: f64, damping: f64) -> Result { + let m = within(mass, MASS.0, MASS.1, "mass")?; + let k = within(stiffness, STIFFNESS.0, STIFFNESS.1, "stiffness")?; + let c = within(damping, DAMPING.0, DAMPING.1, "damping")?; + if c / (2.0 * (k * m).sqrt()) > MAX_DAMPING_RATIO { + return Err(EaseError::OutOfRange { what: "damping ratio", min: 0.0, max: MAX_DAMPING_RATIO }); + } + Ok(Spring::physical(m, k, c)) + } + + /// [`Spring::from_physical`] with each value brought into its range (a value that is not + /// finite takes the default: mass 1, stiffness 100, damping 15). + pub(crate) fn physical_lenient(mass: f64, stiffness: f64, damping: f64) -> Spring { + let ok = |v: f64, (lo, hi): (f64, f64), d: f64| if v.is_finite() { v.clamp(lo, hi) } else { d }; + Spring::physical(ok(mass, MASS, 1.0), ok(stiffness, STIFFNESS, 100.0), ok(damping, DAMPING, 15.0)) + } + + fn physical(m: f64, k: f64, c: f64) -> Spring { + Spring { omega: (k / m).sqrt(), zeta: (c / (2.0 * (k * m).sqrt())).min(MAX_DAMPING_RATIO) } + } + + /// A spring from values already in range. + pub(crate) fn raw(frequency: f64, damping: f64) -> Spring { + Spring { omega: std::f64::consts::TAU * frequency, zeta: damping } + } + + /// Seconds until a spring released from rest stays within about 0.1 % of its target, at + /// least 0.05 and at most 10. + pub fn settle_time(&self) -> f64 { + let (w, z) = (self.omega, self.zeta); + // The slowest mode's decay rate; e^−6.9 is 0.1 %, and a critically or over-damped + // spring's larger lead factor needs about 9.2. Released from rest, an under-damped + // spring's offset stays within e^−ζωt · min(1/√(1 − ζ²), 1 + ζωt), so its lead factor + // grows by ln(1/√(1 − ζ²)) up to the critical spring's 9.2. + let (rate, k) = if z < 1.0 { (z * w, (6.9 - 0.5 * (1.0 - z * z).ln()).min(9.2)) } else { (w / (z + (z * z - 1.0).sqrt()), 9.2) }; + let settle = if rate > 1e-6 { (k / rate).clamp(0.05, MAX_SETTLE) } else { MAX_SETTLE }; + if settle.is_finite() { settle } else { MAX_SETTLE } + } + + /// The spring as an ease: released from rest at 0 toward 1, `t` of the way through its + /// [`Spring::settle_time`]. Exactly 0 at `t <= 0` and exactly 1 at `t >= 1`. A spring with + /// so little damping that it is still moving after 10 seconds has the distance it is still + /// off at that point taken out evenly over the ease, so it reaches 1 without a jump. + pub fn ease(&self, t: f64) -> f64 { + if t.is_nan() || t <= 0.0 { + return 0.0; + } + if t >= 1.0 { + return 1.0; + } + let settle = self.settle_time(); + let mut x = 1.0 + self.response(-1.0, 0.0, t * settle).0; + if settle >= MAX_SETTLE { + x -= t * self.response(-1.0, 0.0, settle).0; + } + if x.is_finite() { x } else { 1.0 } + } + + /// The natural angular frequency `ω`, in radians a second. + pub fn omega(&self) -> f64 { + self.omega + } + + /// The damping ratio `ζ`. + pub fn damping(&self) -> f64 { + self.zeta + } + + /// Offset and velocity `(y, v)` after `t` seconds, from offset `y0` (value minus target) and + /// velocity `v0`: the exact solution of the spring equation. + pub(crate) fn response(&self, y0: f64, v0: f64, t: f64) -> (f64, f64) { + let (w, z) = (self.omega, self.zeta); + if t <= 0.0 { + return (y0, v0); + } + // Past this much decay e^(−decay) is below the smallest f64: the spring has settled. + const SETTLED: f64 = 800.0; + // Damping ratios near 1 use the under- and over-damped solutions below, which stay + // precise there, so every ratio is solved as given; only exactly 1 is critical. + if z == 1.0 { + if w * t > SETTLED { + return (0.0, 0.0); + } + let b = v0 + w * y0; + let e = (-w * t).exp(); + // The velocity is e^−ωt (v0 − ω b t), written so v0 is not recovered by subtracting + // the rounded position terms. + return (e * (y0 + b * t), e * (v0 - w * (b * t))); + } + if z < 1.0 { + if z * w * t > SETTLED { + return (0.0, 0.0); + } + // 1 − ζ² as (1 − ζ)(1 + ζ), precise for ζ near 1. + let wd = w * ((1.0 - z) * (1.0 + z)).sqrt(); + let q = v0 + z * w * y0; + let e = (-z * w * t).exp(); + // A step so long that the phase overflows (a spring with little or no damping) is + // reduced by whole periods first. + let reduced = !(wd * t).is_finite(); + let phase = if reduced { wd * (t % (std::f64::consts::TAU / wd)) } else { wd * t }; + let (s, c) = phase.sin_cos(); + // sin(phase) / ωd is at most t, so it stays finite for a spring of any low frequency, + // where q / ωd alone would overflow. A small unreduced phase uses t · sin(phase) / phase + // from its series, which is t when ωd or the phase rounds to 0. + let sw = if !reduced && phase < 1e-4 { + let p2 = phase * phase; + t * (1.0 - p2 / 6.0 * (1.0 - p2 / 20.0)) + } else { + s / wd + }; + return (e * (y0 * c + q * sw), e * (v0 * c - (y0 * wd * s + z * w * q * sw))); + } + // ζ² − 1 as (ζ − 1)(ζ + 1), precise for ζ near 1. + let root = ((z - 1.0) * (z + 1.0)).sqrt(); + // r1 = −ω(ζ − √(ζ² − 1)), written without the cancellation for large ζ. + let (r1, r2) = (-w / (z + root), -w * (z + root)); + if -r1 * t > SETTLED { + return (0.0, 0.0); + } + // Written with the divided difference q = (e1 − e2) / (r1 − r2) rather than the two modes' + // coefficients, which overflow (in opposite signs) when r1 − r2 is tiny. + let (e1, e2) = ((r1 * t).exp(), (r2 * t).exp()); + let x = (r1 - r2) * t; + let q = if x <= 1.0 { + // e2 · t · (e^x − 1) / x, with its series where x is too small for expm1's quotient. + let g = if x < 1e-5 { 1.0 + x * (0.5 + x / 6.0) } else { x.exp_m1() / x }; + e2 * t * g + } else { + (e1 - e2) / (r1 - r2) + }; + (y0 * (e1 - r1 * q) + v0 * q, v0 * (e2 + r1 * q) - y0 * (w * w) * q) + } +} + +/// A value moved by a spring: where it is and how fast it moves. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct SpringState { + pub value: f64, + pub velocity: f64, +} + +impl SpringState { + /// A value at rest at `value`. + pub fn at(value: f64) -> SpringState { + SpringState { value, velocity: 0.0 } + } + + /// Moves the value `dt` seconds toward `target` (which holds still over the step) and + /// returns the new value. An error, with the state unchanged, for a `target` or `dt` that is + /// not finite, a negative `dt`, or a result too large to represent. A state whose value or + /// velocity is not finite is refused with [`EaseError::Overflow`] at every step length, and + /// stays as it is. + pub fn step(&mut self, spring: &Spring, target: f64, dt: f64) -> Result { + let target = crate::finite(target, "target")?; + let dt = within(dt, 0.0, f64::MAX, "step")?; + if !(self.value.is_finite() && self.velocity.is_finite()) { + return Err(EaseError::Overflow); + } + if dt == 0.0 { + return Ok(self.value); + } + let (y, v) = spring.response(self.value - target, self.velocity, dt); + let (mut value, mut v) = (target + y, v); + if !(value.is_finite() && v.is_finite()) { + // The motion is linear in the offset and velocity, so they are moved again scaled by + // a power of two to at most 2, for a value and target near opposite ends of the f64 + // range whose step overflowed on the way. + let (hy, hv) = (0.5 * self.value - 0.5 * target, 0.5 * self.velocity); + let m = hy.abs().max(hv.abs()); + let scale = if m > 0.0 && m.is_finite() { 2f64.powi((m.log2().ceil() as i32).min(1023)) } else { 1.0 }; + let (y, w) = spring.response(hy / scale, hv / scale, dt); + (value, v) = (2.0 * (0.5 * target + y * scale), 2.0 * (w * scale)); + } + if !(value.is_finite() && v.is_finite()) { + return Err(EaseError::Overflow); + } + *self = SpringState { value, velocity: v }; + Ok(value) + } + + /// Whether the value is within `tolerance` of `target` and moves slower than `tolerance` + /// a second. + pub fn settled(&self, target: f64, tolerance: f64) -> bool { + (self.value - target).abs() <= tolerance && self.velocity.abs() <= tolerance + } +} diff --git a/crates/ease/src/tests/easing_tests.rs b/crates/ease/src/tests/easing_tests.rs new file mode 100644 index 0000000000..96a21a004a --- /dev/null +++ b/crates/ease/src/tests/easing_tests.rs @@ -0,0 +1,1014 @@ +use crate::*; +use std::sync::Arc; + +fn all() -> Vec { + let mut v: Vec = Easing::named().collect(); + v.extend([Easing::Classic(-60.0), Easing::Classic(100.0), Easing::CubicBezier(0.25, 0.1, 0.25, 1.0), Easing::Custom(Arc::new(wave()))]); + v +} + +/// Every ease kind, values included. +fn every_kind() -> Vec { + let mut v = all(); + v.extend([Easing::Hold, Easing::Spring(SpringEase::GENTLE), Easing::Sampled(Arc::new(steps()))]); + v +} + +/// Three segments that overshoot both ways. +fn wave() -> CustomEase { + CustomEase::from_flat( + &[(0.0, 0.0), (0.1, 0.6), (0.2, 1.3), (0.3, 1.3), (0.4, 1.3), (0.5, -0.2), (0.6, 0.4), (0.7, 1.0), (0.9, 1.0), (1.0, 1.0)] + .map(|(x, y)| Vec2::new(x, y)), + ) + .unwrap() +} + +#[test] +fn a_narrow_custom_segment_is_evaluated_not_skipped() { + let d = 1e-10; + let e = CustomEase::from_flat( + &[ + (0.0, 0.0), + (0.1, 0.0), + (0.4, 0.0), + (0.5, 0.0), + (0.5 + d / 3.0, 1.0 / 3.0), + (0.5 + 2.0 * d / 3.0, 2.0 / 3.0), + (0.5 + d, 1.0), + (0.6, 1.0), + (0.9, 1.0), + (1.0, 1.0), + ] + .map(|(x, y)| Vec2::new(x, y)), + ) + .unwrap(); + let mid = e.apply(0.5 + d / 2.0); + assert!((mid - 0.5).abs() < 0.05, "{mid}"); +} + +/// Four steps, as a stepped ease samples them. +fn steps() -> SampledEase { + SampledEase::new("Stepped 4", "org.example.stepped-ease", "steps4", (0..257).map(|i| ((i as f64 / 256.0) * 4.0).floor() / 4.0).collect()) +} + +#[test] +fn endpoints_are_exact() { + for e in every_kind() { + assert_eq!(e.apply(0.0), 0.0, "{e:?}"); + assert_eq!(e.apply(1.0), 1.0, "{e:?}"); + assert_eq!(e.apply(-0.0), 0.0, "{e:?}"); + assert_eq!(e.apply(-5.0), 0.0, "{e:?}"); + assert_eq!(e.apply(5.0), 1.0, "{e:?}"); + assert_eq!(e.apply(f64::NEG_INFINITY), 0.0, "{e:?}"); + assert_eq!(e.apply(f64::INFINITY), 1.0, "{e:?}"); + assert_eq!(e.apply(f64::NAN), 0.0, "{e:?}"); + } +} + +#[test] +fn presets_at_known_times() { + use std::f64::consts::{FRAC_1_SQRT_2, PI}; + let cases: [(Easing, f64, f64); 22] = [ + (Easing::Linear, 0.3, 0.3), + (Easing::QuadIn, 0.5, 0.25), + (Easing::QuadOut, 0.5, 0.75), + (Easing::QuadInOut, 0.25, 0.125), + (Easing::CubicIn, 0.5, 0.125), + (Easing::CubicOut, 0.5, 0.875), + (Easing::QuartIn, 0.5, 0.0625), + (Easing::QuartInOut, 0.75, 0.96875), + (Easing::QuintIn, 0.5, 0.03125), + (Easing::QuintOut, 0.5, 0.96875), + (Easing::SineIn, 0.5, 1.0 - FRAC_1_SQRT_2), + (Easing::SineOut, 1.0 / 3.0, 0.5), + (Easing::SineInOut, 0.25, 0.5 * (1.0 - FRAC_1_SQRT_2)), + // (c + 1)/8 − c/4 with c = 1.70158: dips below zero first. + (Easing::BackIn, 0.5, -0.087_697_5), + (Easing::BackOut, 0.5, 1.087_697_5), + (Easing::CircIn, 0.6, 0.2), + (Easing::CircOut, 0.5, 0.866_025_403_784_438_6), + (Easing::BounceOut, 0.5, 0.765_625), + (Easing::BounceIn, 0.5, 0.234_375), + (Easing::BounceOut, 1.0 / 2.75, 1.0), + // −2⁻⁵ · sin(−5.75 · 2π/3) = −1/64; Out is its mirror. + (Easing::ElasticIn, 0.5, -0.015_625), + (Easing::ElasticOut, 0.5, 1.015_625), + ]; + for (e, t, want) in cases { + assert!((e.apply(t) - want).abs() < 1e-9, "{e:?} at {t}: {} vs {want}", e.apply(t)); + } + assert!((Easing::Classic(-100.0).apply(0.5) - 0.25).abs() < 1e-12); + assert!((Easing::Classic(100.0).apply(0.5) - 0.75).abs() < 1e-12); + assert!((Easing::SineIn.apply(1.0 / 3.0) - (1.0 - (PI / 6.0).cos())).abs() < 1e-12); +} + +/// Back and Elastic In Out follow the published In Out equations, which are not In's halves. +#[test] +fn back_and_elastic_in_out_follow_the_published_equations() { + for (e, t, want) in [ + (Easing::BackInOut, 0.25, -0.099_68), + (Easing::BackInOut, 0.75, 1.099_68), + (Easing::ElasticInOut, 0.25, 0.011_97), + (Easing::ElasticInOut, 0.4, -0.117_46), + (Easing::ElasticInOut, 0.75, 0.988_03), + ] { + assert!((e.apply(t) - want).abs() < 5e-6, "{e:?} at {t}: {}", e.apply(t)); + } + // Back In Out: ((2t)²((c+1)2t − c))/2 with c = 1.70158 × 1.525. + let c = 1.701_58 * 1.525; + for k in 1..20 { + let t = k as f64 / 40.0; + let want = (2.0 * t).powi(2) * ((c + 1.0) * 2.0 * t - c) / 2.0; + assert!((Easing::BackInOut.apply(t) - want).abs() < 1e-12, "{t}"); + } +} + +#[test] +fn out_mirrors_in_and_in_out_is_symmetric() { + for f in EaseFamily::ALL { + let (i, o, io) = (Easing::preset(f, EaseDir::In), Easing::preset(f, EaseDir::Out), Easing::preset(f, EaseDir::InOut)); + for k in 0..=40 { + let t = k as f64 / 40.0; + assert!((o.apply(t) - (1.0 - i.apply(1.0 - t))).abs() < 1e-12, "{f:?} at {t}"); + assert!((io.apply(t) + io.apply(1.0 - t) - 1.0).abs() < 1e-12, "{f:?} at {t}"); + // In Out is In's halves for every family but Back and Elastic. + if !matches!(f, EaseFamily::Back | EaseFamily::Elastic) { + assert!((io.apply(t * 0.5) - 0.5 * i.apply(t)).abs() < 1e-12, "{f:?} at {t}"); + } + } + assert_eq!(Easing::preset(f, EaseDir::In).family(), Some((f, EaseDir::In))); + } +} + +#[test] +fn monotonic_families_never_turn_back_and_the_others_overshoot() { + for e in all() { + let overshoots = matches!(e.family(), Some((EaseFamily::Back | EaseFamily::Elastic, _))) || e.custom().is_some(); + // Bounce turns back (off the floor) without leaving 0..1. + let turns = overshoots || matches!(e.family(), Some((EaseFamily::Bounce, _))); + let (mut lo, mut hi, mut prev, mut turned) = (0.0f64, 1.0f64, -1e-6f64, false); + for i in 0..=400 { + let v = e.apply(i as f64 / 400.0); + turned |= v < prev - 1e-4; + prev = v; + lo = lo.min(v); + hi = hi.max(v); + } + assert_eq!(turned, turns, "{e:?}"); + assert_eq!(lo < -1e-3 || hi > 1.0 + 1e-3, overshoots, "{e:?}: {lo}..{hi}"); + } +} + +/// The eases meant to be monotonic never step backwards on a fine grid, not even by rounding. +#[test] +fn monotonic_eases_are_non_decreasing_everywhere() { + let mut eases: Vec = [EaseFamily::Quad, EaseFamily::Cubic, EaseFamily::Quart, EaseFamily::Quint, EaseFamily::Sine, EaseFamily::Circ] + .into_iter() + .flat_map(|f| EaseDir::ALL.map(|d| Easing::preset(f, d))) + .collect(); + eases.extend([ + Easing::Linear, + Easing::Hold, + Easing::Classic(-100.0), + Easing::Classic(37.0), + Easing::Classic(100.0), + Easing::SMOOTH, + Easing::CubicBezier(1.0, 0.0, 0.0, 1.0), + Easing::CubicBezier(0.0, 1.0, 1.0, 0.0), + Easing::CubicBezier(0.9, 0.0, 0.1, 1.0), + ]); + eases.push(Easing::from_temporal(TemporalEase::EASY, TemporalEase::EASY).unwrap()); + eases.push(Easing::from_temporal(TemporalEase { speed: 0.0, influence: 1.0 }, TemporalEase { speed: 0.0, influence: 1.0 }).unwrap()); + eases.push(Easing::Spring(SpringEase { mass: 1.0, stiffness: 100.0, damping: 40.0 })); + for e in eases { + let mut prev = 0.0; + for i in 0..=20_000 { + let v = e.apply(i as f64 / 20_000.0); + assert!(v >= prev, "{e:?} steps back at {i}: {prev} → {v}"); + assert!((0.0..=1.0).contains(&v), "{e:?} leaves 0..1 at {i}: {v}"); + prev = v; + } + } +} + +#[test] +fn hostile_input_is_clamped() { + assert_eq!(Easing::Linear.apply(f64::NAN), 0.0); + assert_eq!(Easing::QuadIn.apply(5.0), 1.0); + assert_eq!(Easing::ElasticOut.apply(f64::INFINITY), 1.0); + assert!(Easing::CubicBezier(f64::NAN, 0.0, 1.0, 1.0).apply(0.5).is_finite()); + assert!(Easing::Classic(f64::INFINITY).apply(0.5).is_finite()); + assert!(Easing::Custom(Arc::new(wave())).apply(f64::NAN).is_finite()); + assert!(Easing::Spring(SpringEase { mass: f64::NAN, stiffness: -1.0, damping: f64::INFINITY }).apply(0.5).is_finite()); + // Huge handles are kept within ±MAX_EASE_Y when evaluated. + let wild = Easing::CubicBezier(0.5, 1e300, 0.5, -1e300); + for k in 0..=100 { + let v = wild.apply(k as f64 / 100.0); + assert!(v.abs() <= MAX_EASE_Y, "{k}: {v}"); + } + // Times next to the ends, and subnormal ones. + for e in all() { + for t in [f64::MIN_POSITIVE, 5e-324, 1e-300, 1.0 - f64::EPSILON / 2.0, 1.0 - 1e-16] { + assert!(e.apply(t).is_finite(), "{e:?} at {t}"); + } + } +} + +#[test] +fn checked_constructors_refuse_bad_values() { + assert!(Easing::cubic_bezier(0.2, 0.0, 0.8, 1.0).is_ok()); + assert_eq!(Easing::cubic_bezier(f64::NAN, 0.0, 0.8, 1.0), Err(EaseError::NotFinite("x1"))); + assert!(matches!(Easing::cubic_bezier(1.2, 0.0, 0.8, 1.0), Err(EaseError::OutOfRange { what: "x1", .. }))); + assert!(matches!(Easing::cubic_bezier(0.2, 0.0, -0.1, 1.0), Err(EaseError::OutOfRange { what: "x2", .. }))); + assert!(matches!(Easing::cubic_bezier(0.2, 11.0, 0.8, 1.0), Err(EaseError::OutOfRange { what: "y1", .. }))); + assert_eq!(Easing::cubic_bezier(0.2, 0.0, 0.8, f64::INFINITY), Err(EaseError::NotFinite("y2"))); + let ok = TemporalEase { speed: 0.0, influence: 0.5 }; + assert!(matches!( + Easing::from_temporal(TemporalEase { speed: 0.0, influence: 0.0 }, ok), + Err(EaseError::OutOfRange { what: "out influence", .. }) + )); + assert!(matches!( + Easing::from_temporal(ok, TemporalEase { speed: 0.0, influence: 1.5 }), + Err(EaseError::OutOfRange { what: "in influence", .. }) + )); + assert_eq!(Easing::from_temporal(TemporalEase { speed: f64::NAN, influence: 0.5 }, ok), Err(EaseError::NotFinite("out speed"))); + assert!(matches!(Easing::from_temporal(TemporalEase { speed: 1e6, influence: 0.5 }, ok), Err(EaseError::OutOfRange { .. }))); + assert!(Easing::spring(1.0, 100.0, 15.0).is_ok()); + assert!(matches!(Easing::spring(0.0, 100.0, 15.0), Err(EaseError::OutOfRange { what: "mass", .. }))); + assert_eq!(Easing::spring(1.0, f64::NAN, 15.0), Err(EaseError::NotFinite("stiffness"))); +} + +/// Sample values from a keyframe velocity dialog: two keys a second apart, both sides eased +/// with speed (units a second) and influence. The values are the ease's progress there. +#[test] +fn speed_and_influence_give_the_dialog_curves() { + for (out, into, samples) in [ + ( + TemporalEase { speed: 0.0, influence: 0.8 }, + TemporalEase { speed: 0.0, influence: 0.8 }, + [(0.1, 0.005_924_393_903_632_7), (0.25, 0.047_643_803_060_876_4), (0.4, 0.184_284_394_271_562), (0.75, 0.952_356_196_939_123)], + ), + ( + TemporalEase { speed: 0.2, influence: 0.8 }, + TemporalEase { speed: 0.8, influence: 0.6 }, + [(0.1, 0.022_575_494_262_157_7), (0.25, 0.069_984_188_941_293_1), (0.4, 0.149_334_636_959_052), (0.75, 0.738_196_785_378_389)], + ), + ( + TemporalEase { speed: 0.2, influence: 0.6 }, + TemporalEase { speed: 0.8, influence: 0.8 }, + [(0.1, 0.023_604_533_665_406), (0.25, 0.084_029_514_287_08), (0.4, 0.254_632_042_525_662), (0.75, 0.776_210_872_246_874)], + ), + ] { + let e = Easing::from_temporal(out, into).unwrap(); + for (t, want) in samples { + assert!((e.apply(t) - want).abs() < 1e-9, "{out:?} {into:?} at {t}: {} vs {want}", e.apply(t)); + } + let (o, i) = e.temporal().unwrap(); + assert!((o.speed - out.speed).abs() < 1e-12 && (o.influence - out.influence).abs() < 1e-12); + assert!((i.speed - into.speed).abs() < 1e-12 && (i.influence - into.influence).abs() < 1e-12); + } + // The straight line's speed with a third of influence on both sides is no ease. + let line = Easing::from_temporal(TemporalEase { speed: 1.0, influence: 1.0 / 3.0 }, TemporalEase { speed: 1.0, influence: 1.0 / 3.0 }).unwrap(); + for k in 0..=20 { + let t = k as f64 / 20.0; + assert!((line.apply(t) - t).abs() < 1e-12, "{t}"); + } + // Easy ease is symmetric and slow at its ends. + let easy = Easing::from_temporal(TemporalEase::EASY, TemporalEase::EASY).unwrap(); + assert!((easy.apply(0.5) - 0.5).abs() < 1e-12); + assert!(easy.apply(0.1) > 0.0 && easy.apply(0.1) < 0.1); +} + +/// Both handles at full influence leave the time curve flat halfway; the closed-form inverse +/// keeps that point exact. +#[test] +fn full_influence_is_solved_exactly_at_the_flat_midpoint() { + let e = Easing::from_temporal(TemporalEase { speed: 0.0, influence: 1.0 }, TemporalEase { speed: 0.0, influence: 1.0 }).unwrap(); + for t in [0.5 - 1e-9, 0.5 - 1e-12, 0.5, 0.5 + 1e-12, 0.5 + 1e-9, 0.1, 0.9] { + // x = 0.5 + 4 (u − 0.5)³ exactly, and y = bez(u, [0, 0, 1, 1]). + let u = 0.5 + ((t - 0.5) / 4.0f64).cbrt(); + let want = 3.0 * (1.0 - u) * u * u + u * u * u; + assert!((e.apply(t) - want).abs() < 1e-12, "{t}: {} vs {want}", e.apply(t)); + } +} + +/// The Bezier solver converges inside its step limit for any monotonic curve, to its tolerance. +#[test] +fn the_bezier_solver_converges_within_its_bound() { + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut rnd = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % 1_000_001) as f64 / 1_000_000.0 + }; + let mut worst = 0; + for _ in 0..20_000 { + let (x1, x2, t) = (rnd(), rnd(), rnd()); + let p = [0.0, x1, x2, 1.0]; + let (s, steps) = crate::solve_counted(t, p); + worst = worst.max(steps); + assert!(steps < crate::SOLVE_STEPS, "{p:?} at {t}"); + assert!((crate::bez(s, p) - t).abs() <= crate::SOLVE_TOLERANCE, "{p:?} at {t}: {}", crate::bez(s, p)); + } + // Near-flat curves, where Newton steps fail and halving takes over. + for (x1, x2) in [(1.0, 0.0), (0.999_999, 0.0), (1.0, 1e-9), (0.0, 1.0), (0.0, 0.0), (1.0, 1.0)] { + for k in 0..=1000 { + let t = k as f64 / 1000.0; + let p = [0.0, x1, x2, 1.0]; + let (s, steps) = crate::solve_counted(t, p); + assert!(steps < crate::SOLVE_STEPS && (crate::bez(s, p) - t).abs() <= crate::SOLVE_TOLERANCE, "{p:?} at {t}: {steps} steps"); + } + } + assert!(worst <= 20, "{worst} steps"); + // A narrow segment far from 0, where the curve's x values differ only in their last bits: + // x(s) = a + span s³, so the query halfway across the span is at s = 0.5^(1/3). + let (a, span) = (0.5, 2f64.powi(-52)); + let p = [a, a, a, a + span]; + let s = crate::solve_monotonic(a + span / 2.0, p); + assert!((s - 0.5f64.cbrt()).abs() < 1e-9, "{s}"); +} + +/// A handle so short that its speed overflows has no speed and influence form. +#[test] +fn a_handle_too_short_for_a_finite_speed_has_no_temporal_form() { + assert_eq!(Easing::CubicBezier(f64::from_bits(1), 1.0, 0.5, 0.5).temporal(), None); + assert!(Easing::CubicBezier(0.0, 0.0, 1.0, 1.0).temporal().is_some()); +} + +/// A Bezier with a handle past ±MAX_EASE_Y plays the same curve the graph editor shows for it. +#[test] +fn a_bezier_plays_the_curve_its_custom_form_draws() { + for e in [Easing::CubicBezier(0.3, 20.0, 0.6, 1.0), Easing::CubicBezier(0.3, -1e30, 0.6, 1e30)] { + let c = e.to_custom(); + for k in 0..=40 { + let t = k as f64 * 0.025; + assert!((e.apply(t) - c.apply(t)).abs() < 1e-5, "{e:?} at {t}: {} vs {}", e.apply(t), c.apply(t)); + } + } +} + +/// Any speed and influence a caller can supply either is refused or plays a finite curve. +#[test] +fn speed_and_influence_over_their_whole_range_play_finite_curves() { + let mut seed = 0x51_7cc1_b727_220au64; + let mut rnd = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % 1_000_001) as f64 / 1_000_000.0 + }; + let mut accepted = 0; + for _ in 0..20_000 { + // Speeds from 1e-4 to 1e4 either way, spread evenly in magnitude. + let side = |r: f64, i: f64| TemporalEase { + speed: (r - 0.5).signum() * 10f64.powf((r - 0.5).abs() * 16.0 - 4.0), + influence: MIN_INFLUENCE + i * (1.0 - MIN_INFLUENCE), + }; + let (out, into) = (side(rnd(), rnd()), side(rnd(), rnd())); + let Ok(e) = Easing::from_temporal(out, into) else { continue }; + accepted += 1; + for k in 0..=20 { + let v = e.apply(k as f64 / 20.0); + assert!(v.is_finite() && v.abs() <= MAX_EASE_Y, "{out:?} {into:?}: {v}"); + } + } + assert!(accepted > 5_000, "{accepted}"); +} + +/// Eases, tracks and paths can be shared between render and export threads. +#[test] +fn the_types_are_send_and_sync() { + fn check() {} + check::(); + check::>(); + check::>(); + check::(); + check::(); + check::(); +} + +#[test] +fn bezier_forms_draw_the_same_curves() { + // Exact for these. + for e in [ + Easing::Linear, + Easing::QuadIn, + Easing::QuadOut, + Easing::CubicIn, + Easing::CubicOut, + Easing::BackIn, + Easing::BackOut, + Easing::Classic(-60.0), + Easing::Classic(100.0), + Easing::CubicBezier(0.2, 1.4, 0.6, -0.3), + ] { + let (a, b, c, d) = e.as_bezier().unwrap(); + let bez = Easing::CubicBezier(a, b, c, d); + for i in 0..=20 { + let t = i as f64 / 20.0; + assert!((e.apply(t) - bez.apply(t)).abs() < 1e-9, "{e:?} at {t}"); + } + } + for e in [Easing::QuadInOut, Easing::CubicInOut] { + let (a, b, c, d) = e.as_bezier().unwrap(); + let bez = Easing::CubicBezier(a, b, c, d); + assert!((0..=20).all(|i| (e.apply(i as f64 / 20.0) - bez.apply(i as f64 / 20.0)).abs() < 0.08), "{e:?}"); + } + // One curve can't draw a bounce, a hold or a multi-segment ease. + assert_eq!(Easing::BounceOut.as_bezier(), None); + assert_eq!(Easing::Hold.as_bezier(), None); + assert_eq!(Easing::Custom(Arc::new(wave())).as_bezier(), None); + let one = Easing::Custom(Arc::new(CustomEase::from_bezier(0.1, 0.9, 0.3, 1.2))); + let (a, b, c, d) = one.as_bezier().unwrap(); + assert!((a - 0.1).abs() < 1e-15 && (b - 0.9).abs() < 1e-15 && (c - 0.3).abs() < 1e-15 && (d - 1.2).abs() < 1e-15); +} + +#[test] +fn every_preset_becomes_a_custom_curve_for_the_graph() { + for e in all() { + let c = e.to_custom(); + assert!(c.points().len() <= MAX_EASE_POINTS, "{e:?}"); + let exact = + matches!(e.family(), Some((EaseFamily::Quad | EaseFamily::Cubic | EaseFamily::Back | EaseFamily::Bounce, _))) || e.family().is_none(); + let tol = if exact { 2e-4 } else { 5e-3 }; + let mut worst = 0.0f64; + for i in 0..=500 { + let t = i as f64 / 500.0; + worst = worst.max((c.apply(t) - e.apply(t)).abs()); + } + assert!(worst < tol, "{e:?}: off by {worst} with {} points", c.points().len()); + } + // A hold stays flat until a jump at the end; a spring is its polyline. + let h = Easing::Hold.to_custom(); + for t in [1e-9, 0.25, 0.5, 0.9, 0.999_999] { + assert_eq!(h.apply(t), Easing::Hold.apply(t), "{t}"); + } + assert_eq!(h.apply(1.0), 1.0); + let s = Easing::Spring(SpringEase::GENTLE); + let sc = s.to_custom(); + assert_eq!(sc.points().len(), POLYLINE_POINTS); + assert!((0..=100).all(|i| (sc.apply(i as f64 / 100.0) - s.apply(i as f64 / 100.0)).abs() < 0.02)); +} + +#[test] +fn ease_in_is_slow_at_start() { + assert!(Easing::QuadIn.apply(0.25) < 0.25); + assert!(Easing::QuadOut.apply(0.25) > 0.25); + assert!(Easing::Classic(-100.0).apply(0.25) < 0.25); + assert!(Easing::Classic(100.0).apply(0.25) > 0.25); +} + +#[test] +fn hold_stays_at_the_start_until_the_end() { + for t in [1e-300, 0.25, 0.5, 0.999_999_999] { + assert_eq!(Easing::Hold.apply(t), 0.0); + } + assert_eq!(Easing::Hold.apply(1.0), 1.0); + assert_eq!(Easing::from_name("hold"), Some(Easing::Hold)); +} + +#[test] +fn names_round_trip_and_older_aliases_still_read() { + for e in Easing::named().chain([Easing::Hold]) { + let n = e.name().unwrap(); + assert_eq!(Easing::from_name(&n), Some(e.clone()), "{n}"); + // The file form is the same name. + #[cfg(feature = "serde")] + assert_eq!(serde_json::to_string(&e).unwrap(), format!("\"{n}\"")); + } + assert_eq!(Easing::from_name("back in-out"), Some(Easing::BackInOut)); + assert_eq!(Easing::from_name("ease_in"), Some(Easing::QuadIn)); + assert_eq!(Easing::from_name("Smooth"), Some(Easing::CubicBezier(0.25, 0.1, 0.25, 1.0))); + assert_eq!(Easing::from_name("wobble"), None); + // Separators do not count toward the longest name; a name longer than any preset is unknown. + assert_eq!(Easing::from_name(&format!("{}elastic in out{}", " ".repeat(10_000), "-".repeat(10_000))), Some(Easing::ElasticInOut)); + assert_eq!(Easing::from_name(&"x".repeat(100_000)), None); + assert_eq!(Easing::from_name("ElasticInOutX"), None); + assert_eq!(Easing::named().count(), 28); + assert_eq!(Easing::BounceInOut.label(), "Bounce In Out"); + // Files written with the variant names read back. + #[cfg(feature = "serde")] + { + let old: Vec = serde_json::from_str(r#"["QuadIn", {"Classic": 30.0}, {"CubicBezier": [0.1, 0.2, 0.3, 0.4]}, "Linear"]"#).unwrap(); + assert_eq!(old, [Easing::QuadIn, Easing::Classic(30.0), Easing::CubicBezier(0.1, 0.2, 0.3, 0.4), Easing::Linear]); + let spring: Easing = serde_json::from_str(r#"{"Spring": {"mass": 1.0, "stiffness": 600.0, "damping": 15.0}}"#).unwrap(); + assert_eq!(spring, Easing::Spring(SpringEase { mass: 1.0, stiffness: 600.0, damping: 15.0 })); + assert_eq!( + serde_json::to_string(&Easing::Spring(SpringEase::GENTLE)).unwrap(), + r#"{"Spring":{"mass":1.0,"stiffness":100.0,"damping":15.0}}"# + ); + } +} + +#[test] +fn a_multi_segment_curve_evaluates_continuously_through_its_points() { + let c = wave(); + assert_eq!(c.points().len(), 4); + for p in c.points() { + assert!((c.apply(p.at.x) - p.at.y).abs() < 1e-9 || p.at.x == 0.0, "{p:?}"); + } + let mut prev = c.apply(0.0); + for i in 1..=10_000 { + let v = c.apply(i as f64 / 10_000.0); + assert!((v - prev).abs() < 2e-3, "a jump at {i}: {prev} → {v}"); + prev = v; + } + // Rises past the end value, then falls back below where it was, as drawn. + assert!(c.apply(0.3) > 1.2 && c.apply(0.55) < 0.4); +} + +#[test] +fn adding_a_point_keeps_the_shape() { + let c = wave(); + let (d, i) = c.insert_at(0.42).unwrap(); + assert_eq!((d.points().len(), i), (5, 2)); + assert!(d.points()[2].smooth); + for k in 0..=200 { + let t = k as f64 / 200.0; + assert!((c.apply(t) - d.apply(t)).abs() < 1e-4, "at {t}"); + } + // Not at an end or on a point. + assert!(c.insert_at(0.0).is_none() && c.insert_at(1.0).is_none() && c.insert_at(0.3).is_none() && c.insert_at(f64::NAN).is_none()); +} + +/// Splitting a steep curve can put a piece's handle past that piece's other end in x; the piece +/// still runs forwards, so the handle is kept and the curve keeps its shape. +#[test] +fn adding_a_point_keeps_the_shape_where_the_pieces_handles_cross() { + let c = CustomEase::from_bezier(1.0, 0.0, 0.0, 1.0); + for t in [7.0 / 16.0, 0.2, 0.49, 0.51, 0.8] { + let (d, i) = c.insert_at(t).unwrap(); + assert_eq!(i, 1); + assert_forwards(&d); + // x is flat at 0.5, so a solve within 1e-12 in x is within about 1e-4 in y there. + assert!((d.apply(0.5) - 0.5).abs() < 2e-4, "{t}: {}", d.apply(0.5)); + for k in 0..=400 { + let u = k as f64 / 400.0; + let tol = if (u - 0.5).abs() > 0.05 { 1e-9 } else { 2e-4 }; + assert!((c.apply(u) - d.apply(u)).abs() < tol, "{t} at {u}: {} vs {}", c.apply(u), d.apply(u)); + } + // Removing the point again leaves a valid curve of one segment. + assert_forwards(&d.remove(1).unwrap()); + } + // A handle past the far end is kept only while x still runs forwards. + let one = |out_x: f64| { + CustomEase::new(vec![ + EasePoint { at: Vec2::ZERO, out: Vec2::new(out_x, 0.0), ..Default::default() }, + EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::new(-0.4, 0.0), ..Default::default() }, + ]) + }; + let (kept, cut) = (one(1.2), one(2.5)); + assert_eq!((kept.points()[0].out.x, cut.points()[0].out.x), (1.2, 1.0)); + assert_forwards(&kept); + assert_forwards(&cut); + // Such a curve is not a cubic-bezier() one, and from_bezier keeps x in the unit box. + assert_eq!(Easing::Custom(Arc::new(kept)).as_bezier(), None); + assert_eq!(Easing::Custom(Arc::new(cut)).as_bezier(), Some((1.0, 0.0, 0.6, 1.0))); + assert_eq!(CustomEase::from_bezier(1.2, 0.0, -0.1, 1.0).points()[0].out.x, 1.0); + assert_eq!(CustomEase::from_bezier(1.2, 0.0, -0.1, 1.0).points()[1].h_in.x, -1.0); +} + +/// A smooth point near the value limit has its handles shortened along their line, so they stay +/// in line. +#[test] +fn a_smooth_point_near_the_value_limit_keeps_its_handles_in_line() { + let c = CustomEase::new(vec![ + EasePoint { at: Vec2::ZERO, ..Default::default() }, + EasePoint { at: Vec2::new(0.1, 9.9), ..Default::default() }, + EasePoint { at: Vec2::new(1.0, 1.0), ..Default::default() }, + ]); + let s = c.set_smooth(1, true).unwrap(); + let p = s.points()[1]; + assert!(p.smooth && p.out.length() > 0.05 && p.h_in.length() > 0.01 && in_line(&p), "{p:?}"); + assert!(p.at.y + p.out.y <= MAX_EASE_Y && p.at.y + p.h_in.y >= -MAX_EASE_Y, "{p:?}"); + assert_forwards(&s); + // Moving the smooth point up to the limit, or next to a neighbor, keeps them in line too. + for to in [Vec2::new(0.5, 9.99), Vec2::new(0.999, 5.0), Vec2::new(0.001, -9.99)] { + let m = s.move_point(1, to).unwrap(); + let q = m.points()[1]; + assert!(q.smooth && in_line(&q), "{to:?}: {q:?}"); + assert_forwards(&m); + } +} + +#[test] +fn point_edits_keep_time_running_forwards() { + let c = wave(); + // Dragging a point past its neighbor stops at the neighbor. + let d = c.move_point(1, Vec2::new(0.95, 2.0)).unwrap(); + assert_eq!(d.points()[1].at, Vec2::new(0.6, 2.0)); + // The ends don't move. + assert!(c.move_point(0, Vec2::new(0.5, 0.5)).is_none() && c.move_point(3, Vec2::new(0.5, 0.5)).is_none()); + // A handle dragged backwards in time stops at its point. + let h = c.move_handle(1, Handle::Out, Vec2::new(0.0, 5.0)).unwrap(); + assert_eq!(h.points()[1].out.x, 0.0); + // A smooth point's other handle turns with it. + let s = c.set_smooth(1, true).unwrap(); + let t = s.move_handle(1, Handle::Out, Vec2::new(0.45, 1.5)).unwrap(); + let p = t.points()[1]; + assert!(p.smooth && (p.h_in.normalized().dot(p.out.normalized()) + 1.0).abs() < 1e-4, "{p:?}"); + // A corner has its handles on the point. + let k = s.set_smooth(1, false).unwrap(); + assert_eq!((k.points()[1].h_in, k.points()[1].out), (Vec2::ZERO, Vec2::ZERO)); + // Removing. + assert_eq!(c.remove(2).unwrap().points().len(), 3); + assert!(c.remove(0).is_none() && c.remove(3).is_none()); +} + +/// Whether a smooth inner point's handles are in line (or one of them has no length). +fn in_line(p: &EasePoint) -> bool { + let (a, b) = (p.h_in, p.out); + a.length() < 1e-9 || b.length() < 1e-9 || (a.normalized().dot(b.normalized()) + 1.0).abs() < 1e-9 +} + +/// Turning a smooth point's other handle keeps it in line even where it has less room on its +/// side than its length: it is shortened along the line instead of clamped out of it. +#[test] +fn a_smooth_point_keeps_its_handles_in_line_near_a_neighbor() { + let c = CustomEase::new(vec![ + EasePoint { at: Vec2::ZERO, h_in: Vec2::ZERO, out: Vec2::new(0.3, 0.0), smooth: false }, + EasePoint { at: Vec2::new(0.9, 0.5), h_in: Vec2::new(-0.1, -0.3), out: Vec2::new(0.1, 0.3), smooth: true }, + EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::new(-0.05, 0.0), out: Vec2::ZERO, smooth: false }, + ]); + let d = c.move_handle(1, Handle::In, Vec2::new(0.5, 0.1)).unwrap(); + let p = d.points()[1]; + assert!(p.smooth && p.out.length() > 0.05 && in_line(&p), "{p:?}"); + assert!(p.out.x <= 0.1 + 1e-12, "{p:?}"); + assert_forwards(&d); + // The same near the y limit. + let e = CustomEase::new(vec![ + EasePoint { at: Vec2::ZERO, h_in: Vec2::ZERO, out: Vec2::ZERO, smooth: false }, + EasePoint { at: Vec2::new(0.5, 9.9), h_in: Vec2::new(-0.2, 0.0), out: Vec2::new(0.2, 0.0), smooth: true }, + EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::ZERO, out: Vec2::ZERO, smooth: false }, + ]); + let f = e.move_handle(1, Handle::Out, Vec2::new(0.6, 9.0)).unwrap(); + let q = f.points()[1]; + assert!(q.h_in.length() > 0.05 && in_line(&q) && q.at.y + q.h_in.y <= MAX_EASE_Y + 1e-12, "{q:?}"); +} + +/// Turning a smooth point's other handle keeps that handle's length when it fits, however short. +#[test] +fn turning_a_smooth_point_keeps_a_short_other_handle_short() { + let c = CustomEase::new(vec![ + EasePoint { at: Vec2::ZERO, ..Default::default() }, + EasePoint { at: Vec2::new(0.5, 0.5), h_in: Vec2::new(-0.0005, 0.0), out: Vec2::new(0.2, 0.0), smooth: true }, + EasePoint { at: Vec2::new(1.0, 1.0), ..Default::default() }, + ]); + let d = c.move_handle(1, Handle::Out, Vec2::new(0.7, 0.6)).unwrap(); + let p = d.points()[1]; + assert!(p.smooth && in_line(&p) && (p.h_in.length() - 0.0005).abs() < 1e-15, "{p:?}"); + // A handle with no length is given one. + let z = CustomEase::new(vec![ + EasePoint { at: Vec2::ZERO, ..Default::default() }, + EasePoint { at: Vec2::new(0.5, 0.5), out: Vec2::new(0.2, 0.0), smooth: true, ..Default::default() }, + EasePoint { at: Vec2::new(1.0, 1.0), ..Default::default() }, + ]); + let q = z.move_handle(1, Handle::Out, Vec2::new(0.7, 0.6)).unwrap().points()[1]; + assert!(q.smooth && in_line(&q) && (q.h_in.length() - 1e-3).abs() < 1e-15, "{q:?}"); +} + +/// A point marked smooth whose handles are not in line is read as a corner, its handles kept. +#[test] +fn a_smooth_mark_on_a_corner_is_cleared() { + let pts = |out: Vec2| { + vec![ + EasePoint { at: Vec2::ZERO, out: Vec2::new(0.1, 0.0), smooth: true, ..Default::default() }, + EasePoint { at: Vec2::new(0.5, 0.5), h_in: Vec2::new(-0.1, 0.0), out, smooth: true }, + EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::new(-0.1, 0.0), smooth: true, ..Default::default() }, + ] + }; + let corner = CustomEase::new(pts(Vec2::new(0.1, 0.1))); + let p = corner.points()[1]; + assert!(!p.smooth && p.h_in == Vec2::new(-0.1, 0.0) && p.out == Vec2::new(0.1, 0.1), "{p:?}"); + let smooth = CustomEase::new(pts(Vec2::new(0.2, 0.0))); + assert!(smooth.points()[1].smooth); + // The ends have one handle each and are never smooth. + assert!(!smooth.points()[0].smooth && !smooth.points()[2].smooth); + // Past the value limit, such a point's handle is clipped as a corner's: its x is kept. + let high = CustomEase::new(vec![ + EasePoint { at: Vec2::ZERO, ..Default::default() }, + EasePoint { at: Vec2::new(0.5, 9.5), h_in: Vec2::new(-0.2, 2.0), out: Vec2::new(0.1, 0.0), smooth: true }, + EasePoint { at: Vec2::new(1.0, 1.0), ..Default::default() }, + ]); + let q = high.points()[1]; + assert!(!q.smooth && q.h_in == Vec2::new(-0.2, 0.5), "{q:?}"); + #[cfg(feature = "serde")] + { + let f: CustomEase = serde_json::from_str( + r#"{"points": [ + {"at": {"x": 0.0, "y": 0.0}, "out": {"x": 0.1, "y": 0.0}, "smooth": true}, + {"at": {"x": 0.5, "y": 0.5}, "in": {"x": -0.1, "y": 0.0}, "out": {"x": 0.1, "y": 0.1}, "smooth": true}, + {"at": {"x": 1.0, "y": 1.0}, "in": {"x": -0.1, "y": 0.0}, "smooth": true} + ]}"#, + ) + .unwrap(); + assert_eq!(f, corner); + } +} + +/// A point can be added at any time strictly inside the curve that is not already a point's. +#[test] +fn a_point_can_be_added_close_to_an_end_or_a_point() { + let line = CustomEase::linear(); + let (d, i) = line.insert_at(0.00005).unwrap(); + assert_eq!((d.points().len(), i), (3, 1)); + assert!((d.points()[1].at.x - 0.00005).abs() < 1e-15, "{:?}", d.points()[1]); + assert_forwards(&d); + let (e, _) = d.insert_at(0.00006).unwrap(); + assert_eq!(e.points().len(), 4); + assert_forwards(&e); + for k in 0..=200 { + let t = k as f64 / 200.0; + assert!((e.apply(t) - t).abs() < 1e-9, "at {t}"); + } + assert!(d.insert_at(d.points()[1].at.x).is_none()); + // Where the curve is too flat in x to solve for the time, no point is added rather than one + // at another time. + let flat = CustomEase::from_bezier(0.0, 0.0, 0.0, 0.0); + assert!(flat.insert_at(1e-13).is_none()); + let (g, _) = flat.insert_at(0.3).unwrap(); + assert!((g.points()[1].at.x - 0.3).abs() < 1e-9, "{:?}", g.points()[1]); +} + +/// On a segment far narrower than its handle's reach can underflow when squared, a handle that +/// would make x run backwards is still brought back. +#[test] +fn a_very_narrow_segment_does_not_run_backwards() { + let c = CustomEase::new(vec![ + EasePoint { at: Vec2::ZERO, out: Vec2::new(1.5e-180, 0.0), ..Default::default() }, + EasePoint { at: Vec2::new(1e-180, 0.5), ..Default::default() }, + EasePoint { at: Vec2::new(1.0, 1.0), ..Default::default() }, + ]); + let [a, b, cc, d] = c.segment(0).unwrap(); + // x on the span 0..1, sampled: it never decreases. + let span = d.x - a.x; + let xs = [0.0, (b.x - a.x) / span, (cc.x - a.x) / span, 1.0]; + let mut prev = 0.0; + for k in 0..=1000 { + let x = crate::bez(k as f64 / 1000.0, xs); + assert!(x >= prev - 1e-15, "{xs:?} at {k}: {x} after {prev}"); + prev = x; + } + assert_forwards(&c); +} + +/// Every segment's x never decreases: its handles reach toward their neighbors, and x′ (a +/// quadratic with Bernstein coefficients b − a, cc − b and d − cc) is never negative. +fn assert_forwards(c: &CustomEase) { + let pts = c.points(); + assert!(pts.len() >= 2 && pts.len() <= MAX_EASE_POINTS); + assert_eq!((pts[0].at, pts[pts.len() - 1].at), (Vec2::ZERO, Vec2::new(1.0, 1.0))); + for i in 0..pts.len() - 1 { + let [a, b, cc, d] = c.segment(i).unwrap(); + // Divided by the span, so squaring does not underflow on a narrow segment. + let unit = if d.x > a.x { d.x - a.x } else { 1.0 }; + let (k0, k1, k2) = ((b.x - a.x) / unit, (cc.x - b.x) / unit, (d.x - cc.x) / unit); + let forwards = a.x <= d.x && k0 >= 0.0 && k2 >= 0.0 && (k1 >= 0.0 || k1 * k1 <= k0 * k2 * (1.0 + 1e-9)); + assert!(forwards, "segment {i}: {a:?} {b:?} {cc:?} {d:?}"); + for v in [a, b, cc, d] { + assert!(v.is_finite() && v.y.abs() <= MAX_EASE_Y + 1e-9); + } + } + for k in 0..=100 { + assert!(c.apply(k as f64 / 100.0).is_finite()); + } +} + +#[test] +fn x_stays_monotonic_after_any_edit() { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut rnd = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % 10_000) as f64 / 10_000.0 + }; + let mut c = wave(); + for _ in 0..3000 { + let n = c.points().len(); + let i = (rnd() * n as f64) as usize % n; + let to = Vec2::new(rnd() * 1.6 - 0.3, rnd() * 30.0 - 15.0); + let op = (rnd() * 6.0) as u32; + let next = match op { + 0 => c.insert_at(rnd()).map(|r| r.0), + 1 => c.move_point(i, to), + 2 => c.move_handle(i, Handle::In, to), + 3 => c.move_handle(i, Handle::Out, to), + 4 => c.set_smooth(i, rnd() > 0.5), + _ => { + if n > 6 { + c.remove(i) + } else { + None + } + } + }; + if let Some(d) = next { + assert_forwards(&d); + if matches!(op, 2 | 3) + && let Some(p) = d.points().get(i).filter(|p| p.smooth) + { + assert!(in_line(p), "{p:?}"); + } + c = d; + } + } +} + +#[test] +fn the_largest_index_is_a_missing_point() { + let w = wave(); + assert!(w.segment(usize::MAX).is_none()); + assert!(w.move_point(usize::MAX, Vec2::new(0.5, 0.5)).is_none()); + assert!(w.move_handle(usize::MAX, Handle::Out, Vec2::new(0.1, 0.1)).is_none()); + assert!(w.remove(usize::MAX).is_none()); + assert!(w.set_smooth(usize::MAX, true).is_none()); +} + +#[test] +fn hostile_curves_are_repaired() { + // NaN, reversed x, out-of-range values and handles reaching backwards. + let nan = EasePoint { at: Vec2::new(f64::NAN, 0.5), ..Default::default() }; + let pts = vec![ + EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::new(-5.0, f64::INFINITY), ..Default::default() }, + EasePoint { at: Vec2::new(0.6, 400.0), h_in: Vec2::new(3.0, 0.0), out: Vec2::new(-2.0, 0.0), smooth: true }, + nan, + EasePoint { at: Vec2::new(0.2, -1.0), ..Default::default() }, + EasePoint { at: Vec2::new(-3.0, 0.0), out: Vec2::new(f64::NAN, 1.0), ..Default::default() }, + ]; + assert_eq!(CustomEase::try_new(pts.clone()), Err(EaseError::NotFinite("ease point"))); + let c = CustomEase::new(pts); + assert_eq!(c.points().len(), 4); + assert_forwards(&c); + assert_eq!(c.points()[2].at, Vec2::new(0.6, MAX_EASE_Y)); + // Thousands of points are thinned to the cap, and stay a valid curve. + let many: Vec = (0..20_000) + .map(|i| EasePoint { + at: Vec2::new(((i * 7919) % 20_000) as f64 / 20_000.0, (i as f64 * 0.37).sin()), + out: Vec2::new(0.5, 0.0), + h_in: Vec2::new(-0.5, 0.0), + smooth: false, + }) + .collect(); + assert_eq!(CustomEase::try_new(many.clone()), Err(EaseError::Full(MAX_EASE_POINTS))); + let c = CustomEase::new(many); + assert_eq!(c.points().len(), MAX_EASE_POINTS); + assert_forwards(&c); + // Too few points: the line. + assert_eq!(CustomEase::new(vec![nan]), CustomEase::linear()); + assert_eq!(CustomEase::try_new(vec![EasePoint::default()]), Err(EaseError::TooFew { what: "a custom ease", need: 2 })); + // From a file, the same repairs. + #[cfg(feature = "serde")] + { + let f: CustomEase = serde_json::from_str( + r#"{"points": [{"at": {"x": 0.9, "y": 3.0}}, {"at": {"x": 0.1, "y": 0.0}, "out": {"x": -1.0, "y": 0.0}}, {"at": {"x": 0.5, "y": 0.5}}]}"#, + ) + .unwrap(); + assert_forwards(&f); + let e: Easing = serde_json::from_str(r#"{"Custom": {"points": []}}"#).unwrap(); + assert_eq!(e, Easing::Custom(Arc::new(CustomEase::linear()))); + } +} + +#[test] +fn custom_eases_round_trip_through_files_and_flat_lists() { + #[cfg(feature = "serde")] + { + let e = Easing::Custom(Arc::new(wave())); + let back: Easing = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap(); + assert_eq!(back, e); + } + let flat = wave().to_flat(); + assert_eq!(flat.len(), 10); + assert_eq!(CustomEase::from_flat(&flat), Some(wave())); + assert!(CustomEase::from_flat(&flat[..9]).is_none()); +} + +#[test] +fn a_sampled_ease_reads_its_table_between_samples() { + let s = steps(); + let e = Easing::Sampled(Arc::new(s.clone())); + assert_eq!((e.apply(0.0), e.apply(0.1), e.apply(0.25), e.apply(0.6), e.apply(0.9), e.apply(1.0)), (0.0, 0.0, 0.25, 0.5, 0.75, 1.0)); + // Between two samples, the straight line between them. + let lin = SampledEase::new("Line", "p", "l", vec![0.0, 0.5, 1.0]); + assert!((lin.apply(0.25) - 0.25).abs() < 1e-12 && (lin.apply(0.75) - 0.75).abs() < 1e-12); + // Time outside 0..1, or not a number, is clamped. + assert_eq!((e.apply(-3.0), e.apply(7.0), e.apply(f64::NAN)), (0.0, 1.0, 0.0)); + assert_eq!(e.label(), "Stepped 4"); + assert!(e.family().is_none() && e.as_bezier().is_none()); + assert_eq!(e.sampled().map(|s| (s.plugin(), s.ease())), Some(("org.example.stepped-ease", "steps4"))); +} + +#[test] +fn a_sampled_ease_is_always_valid() { + let s = SampledEase::new(" ", "bad id!/..", "x\u{202e}y", vec![0.3, f64::NAN, 99.0, -f64::INFINITY, 0.2]); + assert_eq!(s.values(), &[0.0, 0.25, MAX_EASE_Y, 0.75, 1.0]); + assert_eq!((s.name(), s.plugin(), s.ease()), ("Sampled ease", "badid..", "xy")); + assert_eq!(SampledEase::new("x", "p", "e", vec![]).values(), &[0.0, 1.0]); + assert_eq!(SampledEase::new("x", "p", "e", vec![0.5]).values(), &[0.0, 1.0]); + let long = SampledEase::new("x", "p", "e", (0..100_000).map(|i| i as f64 / 99_999.0).collect()); + assert_eq!(long.values().len(), MAX_EASE_SAMPLES); + assert!((long.apply(0.5) - 0.5).abs() < 1e-3); + // The checked form refuses instead. + assert_eq!(SampledEase::try_new("x", "p", "e", vec![0.0, f64::NAN, 1.0]), Err(EaseError::NotFinite("sample"))); + assert!(matches!(SampledEase::try_new("x", "p", "e", vec![0.0, 99.0, 1.0]), Err(EaseError::OutOfRange { .. }))); + assert_eq!(SampledEase::try_new("x", "p", "e", vec![0.0]), Err(EaseError::TooFew { what: "a sampled ease", need: 2 })); + assert_eq!(SampledEase::try_new("x", "p", "e", vec![0.5; MAX_EASE_SAMPLES + 1]), Err(EaseError::Full(MAX_EASE_SAMPLES))); + assert_eq!(SampledEase::try_new("x", "p", "e", vec![0.2, 0.5, 0.9]).unwrap().values(), &[0.0, 0.5, 1.0]); +} + +/// Thinning a table picks evenly spread samples, first and last included, for any length a +/// `usize` can hold (a 32-bit target overflows `k · (n − 1)` from about 4.2 million values). +#[test] +fn thinning_a_huge_table_does_not_overflow() { + use crate::sampled::thinned; + let last = MAX_EASE_SAMPLES - 1; + for n in [MAX_EASE_SAMPLES + 1, 5_000_000, usize::MAX / 3, usize::MAX] { + assert_eq!(thinned(0, n), 0); + assert_eq!(thinned(last, n), n - 1, "{n}"); + assert!(thinned(last / 2, n) >= (n - 1) / 2 - 1 && thinned(last / 2, n) <= (n - 1) / 2, "{n}"); + assert!((1..=last).all(|k| thinned(k, n) > thinned(k - 1, n)), "{n}"); + } +} + +/// Invisible format characters do not count as a name, so a name of only those shows as +/// "Sampled ease"; they are taken out of a visible name too. +#[test] +fn a_sampled_ease_name_of_invisible_characters_is_no_name() { + let blank: String = "\u{200b}\u{200d}\u{feff}\u{2060}\u{ad}".repeat(13); + assert_eq!(SampledEase::new(&blank, "p", "e", vec![0.0, 1.0]).name(), "Sampled ease"); + assert_eq!(SampledEase::new(" \u{200b} Bounce\u{200d}y \u{feff}", "p", "e", vec![0.0, 1.0]).name(), "Bouncey"); + // A visible name longer than the limit keeps its first 64 characters, after leading padding. + let padded = format!("{}{}", " \u{200b}".repeat(100), "a".repeat(80)); + assert_eq!(SampledEase::new(&padded, "p", "e", vec![0.0, 1.0]).name(), "a".repeat(64)); +} + +#[cfg(feature = "serde")] +#[test] +fn a_sampled_ease_round_trips_through_the_file_format_and_survives_bad_files() { + let e = Easing::Sampled(Arc::new(steps())); + let text = serde_json::to_string(&e).unwrap(); + assert!( + text.starts_with("{\"Sampled\":{\"name\":\"Stepped 4\",\"plugin\":\"org.example.stepped-ease\",\"ease\":\"steps4\",\"values\":[0.0,"), + "{text}" + ); + assert_eq!(serde_json::from_str::(&text).unwrap(), e); + // A hand-edited table is made valid on load; a value that is not a number is a broken file. + assert!(serde_json::from_str::(r#"{"Sampled":{"values":[5,0.5,"x"]}}"#).is_err()); + let odd: Easing = serde_json::from_str(r#"{"Sampled":{"name":"Odd","values":[5,0.5,-20]}}"#).unwrap(); + assert_eq!(odd.sampled().unwrap().values(), &[0.0, 0.5, 1.0]); +} + +/// A file with a huge list loads from its first 65,536 entries; the rest are skipped unread, +/// so they are never stored (here they would not even parse as entries). +#[cfg(feature = "serde")] +#[test] +fn huge_lists_in_files_are_read_only_up_to_a_limit() { + let mut values = String::from(r#"{"Sampled":{"values":["#); + for i in 0..70_000 { + values.push_str(if i < 65_536 { "0.5," } else { r#"{"not":"a value"},"# }); + } + values.push_str("1]}}"); + let e: Easing = serde_json::from_str(&values).unwrap(); + assert_eq!(e.sampled().unwrap().values().len(), MAX_EASE_SAMPLES); + let mut points = String::from(r#"{"Custom":{"points":["#); + for i in 0..70_000 { + points.push_str(if i < 65_536 { r#"{"at":{"x":0.5,"y":0.5}},"# } else { r#""not a point","# }); + } + points.push_str(r#"{"at":{"x":1,"y":1}}]}}"#); + let c: Easing = serde_json::from_str(&points).unwrap(); + assert!(matches!(&c, Easing::Custom(f) if f.points().len() <= MAX_EASE_POINTS), "{c:?}"); + // A long name keeps only its first characters. + let long = format!(r#"{{"Sampled":{{"name":"{}","plugin":"p","ease":"e","values":[0,1]}}}}"#, "é".repeat(100_000)); + let s: Easing = serde_json::from_str(&long).unwrap(); + assert_eq!(s.sampled().unwrap().name(), "é".repeat(64)); + // Characters the cleanup removes do not push the kept text out of reach. + let padded = format!(r#"{{"Sampled":{{"name":"{}Curve","plugin":"{}p1","ease":"e","values":[0,1]}}}}"#, " ".repeat(10_000), "!".repeat(10_000)); + let s: Easing = serde_json::from_str(&padded).unwrap(); + assert_eq!((s.sampled().unwrap().name(), s.sampled().unwrap().plugin()), ("Curve", "p1")); +} + +#[test] +fn a_sampled_ease_becomes_a_custom_curve_through_its_samples() { + let wave = SampledEase::new( + "Wave", + "p", + "w", + (0..257) + .map(|i| { + let t = i as f64 / 256.0; + t + 0.2 * (t * std::f64::consts::TAU).sin() + }) + .collect(), + ); + let c = wave.to_polyline(); + assert_eq!(c.points().len(), POLYLINE_POINTS); + for i in 0..=100 { + let t = i as f64 / 100.0; + assert!((c.apply(t) - wave.apply(t)).abs() < 0.01, "t = {t}: {} vs {}", c.apply(t), wave.apply(t)); + } + let short = SampledEase::new("Short", "p", "s", vec![0.0, 0.8, 1.0]).to_polyline(); + assert_eq!(short.points().len(), 3); + assert!((short.apply(0.5) - 0.8).abs() < 1e-3); +} diff --git a/crates/ease/src/tests/path_tests.rs b/crates/ease/src/tests/path_tests.rs new file mode 100644 index 0000000000..5d7891140d --- /dev/null +++ b/crates/ease/src/tests/path_tests.rs @@ -0,0 +1,227 @@ +use crate::*; + +/// A quarter circle of radius 100 about the origin, from (100, 0) to (0, 100). +fn quarter() -> MotionPath { + let k = 4.0 / 3.0 * (std::f64::consts::PI / 8.0).tan() * 100.0; + MotionPath::new(&[Vec2::new(100.0, 0.0), Vec2::new(100.0, k), Vec2::new(k, 100.0), Vec2::new(0.0, 100.0)]).unwrap() +} + +/// The length of the curve through `n` evenly spaced points along it. +fn polyline_length(p: &MotionPath, n: usize) -> f64 { + (1..=n).map(|i| p.point_at_length(p.length() * i as f64 / n as f64).distance(p.point_at_length(p.length() * (i - 1) as f64 / n as f64))).sum() +} + +/// A tiny curve is walked at constant speed like the same curve at full size. +#[test] +fn a_tiny_curve_is_walked_at_constant_speed() { + let r = 1e-15; + let k = 4.0 / 3.0 * (std::f64::consts::PI / 8.0).tan() * r; + let tiny = MotionPath::new(&[Vec2::new(r, 0.0), Vec2::new(r, k), Vec2::new(k, r), Vec2::new(0.0, r)]).unwrap(); + let big = quarter(); + for i in 1..20 { + let t = i as f64 / 20.0; + let (a, b) = (tiny.point_at(t), big.point_at(t)); + assert!((a.x / r - b.x / 100.0).abs() < 1e-9 && (a.y / r - b.y / 100.0).abs() < 1e-9, "{t}: {a:?} vs {b:?}"); + } +} + +#[test] +fn a_curve_is_measured_and_walked_at_constant_speed() { + let p = quarter(); + // The Bezier quarter circle is within 0.03 % of the circle's length. + assert!((p.length() - 50.0 * std::f64::consts::PI).abs() < 0.05, "{}", p.length()); + assert!((polyline_length(&p, 20_000) - p.length()).abs() < 1e-6, "{} vs {}", polyline_length(&p, 20_000), p.length()); + // Equal steps of distance are equal chords. + let n = 200; + let steps: Vec = (1..=n).map(|i| p.point_at(i as f64 / n as f64).distance(p.point_at((i - 1) as f64 / n as f64))).collect(); + let (lo, hi) = steps.iter().fold((f64::MAX, f64::MIN), |(lo, hi), s| (lo.min(*s), hi.max(*s))); + assert!(hi - lo < 1e-6, "{lo}..{hi}"); + assert_eq!(p.point_at(0.0), Vec2::new(100.0, 0.0)); + let end = p.point_at(1.0); + assert!(end.distance(Vec2::new(0.0, 100.0)) < 1e-9, "{end:?}"); + // Each point is on the curve: about 100 from the center. + for i in 0..=50 { + let r = p.point_at(i as f64 / 50.0).length(); + assert!((r - 100.0).abs() < 0.03, "{r}"); + } +} + +#[test] +fn a_straight_segment_with_uneven_handles_still_moves_evenly() { + // Handles on the chord but bunched near the start: the curve's own parameter speeds up. + let p = MotionPath::new(&[Vec2::ZERO, Vec2::new(1.0, 0.0), Vec2::new(2.0, 0.0), Vec2::new(100.0, 0.0)]).unwrap(); + assert_eq!(p.length(), 100.0); + for i in 0..=10 { + assert_eq!(p.point_at(i as f64 / 10.0), Vec2::new(i as f64 * 10.0, 0.0)); + } +} + +#[test] +fn past_the_ends_the_motion_continues_along_the_path() { + let p = quarter(); + // At the end the circle heads in −x; past it the point keeps going that way. + let past = p.point_at_length(p.length() + 10.0); + assert!(past.distance(Vec2::new(-10.0, 100.0)) < 1e-6, "{past:?}"); + let before = p.point_at_length(-5.0); + assert!(before.distance(Vec2::new(100.0, -5.0)) < 1e-6, "{before:?}"); + // A track's overshooting ease drives the same distance through point_at. + let over = Easing::BackOut; + let peak = (1..100).map(|i| over.apply(i as f64 / 100.0)).fold(f64::MIN, f64::max); + let beyond = p.point_at(peak); + assert!(beyond.x < 0.0 && (beyond.y - 100.0).abs() < 1e-6, "{beyond:?}"); + let d = p.direction_at_length(p.length() * 2.0); + assert!(d.distance(Vec2::new(-1.0, 0.0)) < 1e-9, "{d:?}"); + assert_eq!(p.point_at_length(f64::INFINITY), p.point_at(1.0)); + assert_eq!(p.point_at_length(f64::NAN), Vec2::new(100.0, 0.0)); + assert_eq!(p.point_at_length(f64::NEG_INFINITY), Vec2::new(100.0, 0.0)); + let flat = MotionPath::new(&[Vec2::ZERO, Vec2::new(1.0, 0.0), Vec2::new(2.0, 0.0), Vec2::new(3.0, 0.0)]).unwrap(); + assert_eq!(flat.point_at_length(f64::NEG_INFINITY), Vec2::ZERO); +} + +/// Moving a handle off the chord by a rounding error does not change where an overshoot goes. +#[test] +fn an_overshoot_goes_the_same_way_on_a_straight_and_an_almost_straight_path() { + let straight = MotionPath::new(&[Vec2::ZERO, Vec2::new(30.0, 0.0), Vec2::new(70.0, 0.0), Vec2::new(100.0, 0.0)]).unwrap(); + let bent = MotionPath::new(&[Vec2::ZERO, Vec2::new(30.0, 1e-6), Vec2::new(70.0, 0.0), Vec2::new(100.0, 0.0)]).unwrap(); + for progress in [-0.2, 1.1, 1.25] { + let (a, b) = (straight.point_at(progress), bent.point_at(progress)); + assert!(a.distance(b) < 0.01, "{progress}: {a:?} vs {b:?}"); + } + assert!(straight.point_at(1.25).distance(Vec2::new(125.0, 0.0)) < 1e-9); +} + +#[test] +fn a_path_through_anchors_passes_through_each_one() { + let anchors = [Vec2::new(0.0, 0.0), Vec2::new(100.0, 50.0), Vec2::new(200.0, 0.0), Vec2::new(300.0, 80.0)]; + let p = MotionPath::through(&anchors).unwrap(); + assert_eq!(p.segments(), 3); + // Each anchor is reached at some distance along it. + for a in anchors { + let nearest = (0..=4000).map(|i| p.point_at(i as f64 / 4000.0).distance(a)).fold(f64::MAX, f64::min); + assert!(nearest < 0.1, "{a:?}: {nearest}"); + } + // Smooth through the inner anchors: no turn in direction across them. + let mut prev = p.direction_at_length(0.0); + for i in 1..=2000 { + let d = p.direction_at_length(p.length() * i as f64 / 2000.0); + assert!(d.dot(prev) > 0.99, "a corner at {i}"); + prev = d; + } + // Two anchors at one place make a segment of zero length, which is skipped over. + let q = MotionPath::through(&[Vec2::ZERO, Vec2::new(10.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(20.0, 0.0)]).unwrap(); + assert!((q.length() - 20.0).abs() < 1e-9, "{}", q.length()); + assert!(q.point_at(0.75).distance(Vec2::new(15.0, 0.0)) < 1e-6); + // Anchors repeated at either end still let the motion continue past it. + let r = MotionPath::through(&[Vec2::ZERO, Vec2::ZERO, Vec2::new(10.0, 0.0), Vec2::new(10.0, 0.0)]).unwrap(); + assert!(r.point_at(1.2).distance(Vec2::new(12.0, 0.0)) < 1e-6, "{:?}", r.point_at(1.2)); + assert!(r.point_at(-0.1).distance(Vec2::new(-1.0, 0.0)) < 1e-6, "{:?}", r.point_at(-0.1)); + assert!(r.direction_at_length(20.0).distance(Vec2::new(1.0, 0.0)) < 1e-9); + assert!(r.direction_at_length(-1.0).distance(Vec2::new(1.0, 0.0)) < 1e-9); +} + +#[test] +fn bad_paths_are_refused() { + assert_eq!(MotionPath::new(&[Vec2::ZERO; 3]), Err(EaseError::TooFew { what: "a motion path", need: 4 })); + assert!(matches!(MotionPath::new(&[Vec2::ZERO; 5]), Err(EaseError::OutOfRange { .. }))); + assert_eq!(MotionPath::new(&[Vec2::ZERO, Vec2::new(f64::NAN, 0.0), Vec2::ZERO, Vec2::ZERO]), Err(EaseError::NotFinite("path point"))); + assert_eq!(MotionPath::new(&vec![Vec2::ZERO; 3 * MAX_PATH_SEGMENTS + 4]), Err(EaseError::Full(MAX_PATH_SEGMENTS))); + assert_eq!(MotionPath::through(&[Vec2::ZERO]), Err(EaseError::TooFew { what: "a motion path", need: 2 })); + assert_eq!(MotionPath::through(&[Vec2::ZERO, Vec2::new(0.0, f64::INFINITY)]), Err(EaseError::NotFinite("path point"))); + // A path too long to measure. + assert_eq!( + MotionPath::new(&[Vec2::new(-f64::MAX, 0.0), Vec2::new(-f64::MAX, 0.0), Vec2::new(f64::MAX, 0.0), Vec2::new(f64::MAX, 0.0)]), + Err(EaseError::Overflow) + ); + // A path of one point stands still. + let still = MotionPath::new(&[Vec2::new(3.0, 4.0); 4]).unwrap(); + assert_eq!((still.length(), still.point_at(0.5), still.direction_at_length(1.0)), (0.0, Vec2::new(3.0, 4.0), Vec2::ZERO)); +} + +/// A curve with huge coordinates (whose squares overflow) is walked as the same curve scaled, +/// not taken for a straight line. +#[test] +fn a_huge_curve_is_not_taken_for_a_straight_line() { + let shape = |k: f64| MotionPath::new(&[Vec2::ZERO, Vec2::new(0.0, k), Vec2::new(0.0, k), Vec2::new(2.0 * k, 0.0)]).unwrap(); + let (small, huge) = (shape(1.0), shape(1e154)); + for i in 0..=10 { + let t = i as f64 / 10.0; + let (a, b) = (small.point_at(t), huge.point_at(t)); + assert!((b.x / 1e154 - a.x).abs() < 1e-9 && (b.y / 1e154 - a.y).abs() < 1e-9, "{t}: {a:?} vs {b:?}"); + } + assert!(huge.point_at(0.5).y > 5e153, "{:?}", huge.point_at(0.5)); + // A long chord with handles a small distance off it still bends. + let long = MotionPath::new(&[Vec2::ZERO, Vec2::new(1e12 / 3.0, 1000.0), Vec2::new(2e12 / 3.0, 1000.0), Vec2::new(1e12, 0.0)]).unwrap(); + let mid = long.point_at_length(long.length() / 2.0); + assert!((mid.y - 750.0).abs() < 1.0, "{mid:?}"); +} + +/// Paths whose length is representable are measured even when their scale is near the f64 limit. +#[test] +fn a_path_near_the_largest_length_is_measured() { + let straight = MotionPath::new(&[Vec2::ZERO, Vec2::new(1e307 / 3.0, 0.0), Vec2::new(2e307 / 3.0, 0.0), Vec2::new(1e307, 0.0)]).unwrap(); + assert_eq!(straight.length(), 1e307); + assert!((straight.point_at(0.5).x / 5e306 - 1.0).abs() < 1e-12, "{:?}", straight.point_at(0.5)); + let curved = MotionPath::new(&[Vec2::ZERO, Vec2::ZERO, Vec2::new(0.0, 1e306), Vec2::new(5e307, 0.0)]).unwrap(); + assert!(curved.length() > 5e307 && curved.length() < 5.2e307, "{}", curved.length()); + assert!(curved.point_at(1.0).distance(Vec2::new(5e307, 0.0)) < 1e295); +} + +/// A distance close to a start where the curve stands still is found on the curve, not where a +/// few Newton steps from the table's guess happen to stop. +#[test] +fn a_short_distance_from_a_still_start_is_found() { + let p = MotionPath::new(&[Vec2::ZERO, Vec2::ZERO, Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0)]).unwrap(); + for s in [1e-10, 1e-8, 1e-6] { + let q = p.point_at_length(s); + // The curve leaves the start straight up, so the point is `s` above it. + assert!((q.y - s).abs() < 1e-11 && q.x.abs() < 1e-9, "{s}: {q:?}"); + } +} + +#[test] +fn a_vector_of_any_finite_size_has_a_unit_direction() { + let h = std::f64::consts::FRAC_1_SQRT_2; + let big = Vec2::new(f64::MAX, f64::MAX).normalized(); + assert!((big.x - h).abs() < 1e-15 && (big.y - h).abs() < 1e-15, "{big:?}"); + assert_eq!(Vec2::new(-f64::MAX, 0.0).normalized(), Vec2::new(-1.0, 0.0)); + let tiny = Vec2::new(f64::from_bits(1), f64::from_bits(1)).normalized(); + assert!((tiny.x - h).abs() < 1e-15 && (tiny.y - h).abs() < 1e-15, "{tiny:?}"); + let odd = Vec2::new(3.0 * f64::from_bits(1), -4.0 * f64::from_bits(1)).normalized(); + assert!((odd.x - 0.6).abs() < 1e-15 && (odd.y + 0.8).abs() < 1e-15, "{odd:?}"); + assert_eq!(Vec2::ZERO.normalized(), Vec2::ZERO); + assert_eq!(Vec2::new(f64::INFINITY, 1.0).normalized(), Vec2::ZERO); + assert_eq!(Vec2::new(1.0, f64::NAN).normalized(), Vec2::ZERO); +} + +/// The ends of an interpolation are the end values themselves, even where the difference +/// between them rounds. +#[test] +fn interpolating_returns_the_exact_ends() { + let (a, b) = (Vec2::new(1e20, -3.0), Vec2::new(1.0, 1e-30)); + assert_eq!(a.lerp(b, 0.0), a); + assert_eq!(a.lerp(b, 1.0), b); + assert_eq!(Vec2::new(-f64::MAX, 0.0).lerp(Vec2::new(f64::MAX, 0.0), 1.0), Vec2::new(f64::MAX, 0.0)); +} + +/// A curve that stops and turns back inside one table cell is measured to its true length: x +/// runs out to 4/9 at u = 1/3 and back to 0, so the length is 8/9. +#[test] +fn a_curve_that_turns_back_is_measured_exactly() { + let p = MotionPath::new(&[Vec2::ZERO, Vec2::new(1.0, 0.0), Vec2::ZERO, Vec2::ZERO]).unwrap(); + assert!((p.length() - 8.0 / 9.0).abs() < 1e-12, "{}", p.length()); + let turn = p.point_at_length(4.0 / 9.0); + assert!((turn.x - 4.0 / 9.0).abs() < 1e-9 && turn.y == 0.0, "{turn:?}"); + for (s, x) in [(0.2, 0.2), (0.6, 4.0 / 9.0 - (0.6 - 4.0 / 9.0)), (0.8, 4.0 / 9.0 - (0.8 - 4.0 / 9.0))] { + let q = p.point_at_length(s); + assert!((q.x - x).abs() < 1e-9, "{s}: {q:?} vs {x}"); + } +} + +#[test] +fn a_long_path_finds_its_segment_by_binary_search() { + let anchors: Vec = (0..=MAX_PATH_SEGMENTS).map(|i| Vec2::new(i as f64, ((i as f64) * 0.1).sin())).collect(); + let p = MotionPath::through(&anchors).unwrap(); + assert_eq!(p.segments(), MAX_PATH_SEGMENTS); + let mid = p.point_at(0.5); + assert!(mid.x > 4000.0 && mid.x < 6000.0, "{mid:?}"); +} diff --git a/crates/ease/src/tests/spring_tests.rs b/crates/ease/src/tests/spring_tests.rs new file mode 100644 index 0000000000..bbc7cb0d82 --- /dev/null +++ b/crates/ease/src/tests/spring_tests.rs @@ -0,0 +1,347 @@ +use crate::*; + +/// A spring released from 0 toward 1, `t` seconds in, from the closed forms written out +/// separately: under-damped, critically damped and over-damped. +fn released(w: f64, z: f64, t: f64) -> f64 { + if z < 1.0 { + let wd = w * (1.0 - z * z).sqrt(); + 1.0 - (-z * w * t).exp() * ((wd * t).cos() + z * w / wd * (wd * t).sin()) + } else if (z - 1.0).abs() < 1e-9 { + 1.0 - (-w * t).exp() * (1.0 + w * t) + } else { + let s = (z * z - 1.0).sqrt(); + let (r1, r2) = (-w / (z + s), -w * (z + s)); + 1.0 - (r2 * (r1 * t).exp() - r1 * (r2 * t).exp()) / (r2 - r1) + } +} + +const PRESETS: [(f64, f64, f64); 5] = [(1.0, 100.0, 15.0), (1.0, 300.0, 20.0), (1.0, 600.0, 15.0), (1.0, 80.0, 20.0), (2.5, 40.0, 2.0)]; + +#[test] +fn a_physical_spring_ease_matches_the_closed_form() { + for (m, k, c) in PRESETS { + let spring = Spring::from_physical(m, k, c).unwrap(); + let (w, z) = ((k / m).sqrt(), c / (2.0 * (k * m).sqrt())); + assert!((spring.omega() - w).abs() < 1e-12 && (spring.damping() - z).abs() < 1e-12); + let rate = if z < 1.0 { z * w } else { w / (z + (z * z - 1.0).sqrt()) }; + let lead = if z < 1.0 { (6.9 - 0.5 * (1.0 - z * z).ln()).min(9.2) } else { 9.2 }; + let settle = (lead / rate).clamp(0.05, 10.0); + assert!((spring.settle_time() - settle).abs() < 1e-12); + let ease = Easing::Spring(SpringEase { mass: m, stiffness: k, damping: c }); + // A spring cut short at 10 seconds has what it is still off taken out evenly. + let rest = if settle < 10.0 { 0.0 } else { 1.0 - released(w, z, settle) }; + for i in 1..1000 { + let t = i as f64 / 1000.0; + let want = released(w, z, t * settle) + t * rest; + assert!((ease.apply(t) - want).abs() < 1e-12, "{m} {k} {c} at {t}: {} vs {want}", ease.apply(t)); + } + // It ends within 0.1 % (0.2 % for the slower lead factor) of 1 before the jump to 1. + assert!((ease.apply(0.999_999) - 1.0).abs() < 2e-3, "{m} {k} {c}"); + } +} + +/// A step of no time returns the value unchanged, even when its distance to the target is too +/// large to represent. +#[test] +fn a_zero_length_step_keeps_a_far_value() { + let spring = Spring::new(1.0, 0.5).unwrap(); + let mut s = SpringState::at(1e308); + assert_eq!(s.step(&spring, -1e308, 0.0), Ok(1e308)); + assert_eq!(s, SpringState::at(1e308)); + // A state that is not finite is still refused. + let mut bad = SpringState::at(f64::NAN); + assert_eq!(bad.step(&spring, 0.0, 0.0), Err(EaseError::Overflow)); +} + +/// A value and target at opposite ends of the f64 range move like any others. +#[test] +fn a_step_across_the_whole_range_does_not_overflow() { + let spring = Spring::new(1.0, 1.0).unwrap(); + let mut s = SpringState::at(f64::MAX); + let v = s.step(&spring, -f64::MAX, 10.0).unwrap(); + assert!(v.is_finite() && v < 0.0 && s.velocity.is_finite(), "{s:?}"); +} + +/// The smallest positive target is reached. +#[test] +fn a_spring_reaches_a_subnormal_target() { + let spring = Spring::new(1.0, 1.0).unwrap(); + let mut s = SpringState::at(0.0); + assert_eq!(s.step(&spring, f64::from_bits(1), 1000.0), Ok(f64::from_bits(1))); +} + +/// A spring of the lowest frequency still moves at its velocity over a step. +#[test] +fn a_very_slow_spring_steps_without_overflow() { + let spring = Spring::new(1e-320, 0.0).unwrap(); + let mut s = SpringState { value: 0.0, velocity: 1.0 }; + let v = s.step(&spring, 0.0, 1.0).unwrap(); + assert!((v - 1.0).abs() < 1e-12 && (s.velocity - 1.0).abs() < 1e-12, "{s:?}"); + // The same over-damped. + let spring = Spring::new(1e-320, 2.0).unwrap(); + let mut s = SpringState { value: 0.0, velocity: 1.0 }; + let v = s.step(&spring, 0.0, 1.0).unwrap(); + assert!((v - 1.0).abs() < 1e-12 && (s.velocity - 1.0).abs() < 1e-12, "{s:?}"); +} + +/// Physical values whose damping ratio is above the limit are refused, not changed. +#[test] +fn physical_values_past_the_damping_ratio_limit_are_refused() { + assert_eq!( + Spring::from_physical(0.01, 0.01, 1_000_000.0), + Err(EaseError::OutOfRange { what: "damping ratio", min: 0.0, max: MAX_DAMPING_RATIO }) + ); + assert!(Spring::from_physical(0.01, 0.01, 19.0).is_ok()); +} + +/// A spring just under critical damping is within about 0.1 % of 1 just before the end, so the +/// ease does not jump when it reaches 1. +#[test] +fn a_nearly_critical_spring_ease_ends_without_a_jump() { + for z in [0.5, 0.9, 0.99, 0.999, 0.9999, 1.0 - 2e-4] { + let s = Spring::new(1.0, z).unwrap(); + let end = s.ease(1.0 - 1e-9); + assert!((end - 1.0).abs() < 1.1e-3, "ζ {z}: {end}"); + // The bound holds after the settle time too, not only at it. + let late = 1.0 + s.response(-1.0, 0.0, 1.5 * s.settle_time()).0; + assert!((late - 1.0).abs() < 1.1e-3, "ζ {z} later: {late}"); + } +} + +/// An undamped or barely damped spring ease still arrives at 1 without a jump. +#[test] +fn a_spring_that_never_settles_still_ends_at_one() { + for (m, k, c) in [(1.0, 100.0, 0.0), (1.0, 100.0, 0.01), (10.0, 0.5, 0.0)] { + let e = Easing::Spring(SpringEase { mass: m, stiffness: k, damping: c }); + assert!((e.apply(1.0 - 1e-9) - 1.0).abs() < 1e-6, "{m} {k} {c}: {}", e.apply(1.0 - 1e-9)); + assert!((1..1000).all(|i| e.apply(i as f64 / 1000.0).is_finite())); + } +} + +/// Stepping a spring from rest toward 1 frame by frame traces its ease. +#[test] +fn stepping_from_rest_traces_the_spring_ease() { + // Springs that settle within 10 seconds (the others have their ease adjusted to end at 1). + for (m, k, c) in PRESETS.into_iter().filter(|&(m, k, c)| Spring::from_physical(m, k, c).unwrap().settle_time() < 10.0) { + let s = Spring::from_physical(m, k, c).unwrap(); + let ease = Easing::Spring(SpringEase { mass: m, stiffness: k, damping: c }); + let (settle, frames) = (s.settle_time(), 600); + let mut st = SpringState::at(0.0); + for f in 1..frames { + let v = st.step(&s, 1.0, settle / frames as f64).unwrap(); + let want = ease.apply(f as f64 / frames as f64); + assert!((v - want).abs() < 1e-9, "{m} {k} {c} frame {f}: {v} vs {want}"); + } + } +} + +/// The spring equation integrated with small fourth-order Runge-Kutta steps, from 0 at rest +/// toward 1: value and velocity after `t` seconds. +fn integrated(w: f64, z: f64, t: f64) -> (f64, f64) { + let n = 100_000; + let h = t / n as f64; + let f = |x: f64, v: f64| (v, -w * w * (x - 1.0) - 2.0 * z * w * v); + let (mut x, mut v) = (0.0, 0.0); + for _ in 0..n { + let (a1, b1) = f(x, v); + let (a2, b2) = f(x + 0.5 * h * a1, v + 0.5 * h * b1); + let (a3, b3) = f(x + 0.5 * h * a2, v + 0.5 * h * b2); + let (a4, b4) = f(x + h * a3, v + h * b3); + x += h / 6.0 * (a1 + 2.0 * a2 + 2.0 * a3 + a4); + v += h / 6.0 * (b1 + 2.0 * b2 + 2.0 * b3 + b4); + } + (x, v) +} + +/// Damping ratios just off 1 are solved with the ratio given, not the critical one. +#[test] +fn a_nearly_critical_spring_steps_with_its_own_damping_ratio() { + let w = 10.0; + for t in [0.1, 0.3, 1.0] { + let crit = released(w, 1.0, t); + for z in [1.0 - 5e-5, 1.0 + 5e-5, 1.0 - 1e-9, 1.0 + 1e-9] { + let s = Spring::new(w / std::f64::consts::TAU, z).unwrap(); + let mut st = SpringState::at(0.0); + st.step(&s, 1.0, t).unwrap(); + let (x, v) = integrated(w, z, t); + assert!((st.value - x).abs() < 1e-10 && (st.velocity - v).abs() < 1e-9, "ζ {z} at {t}: {st:?} vs {x}, {v}"); + if (z - 1.0).abs() > 1e-6 { + // The two differ by far more than the tolerance above. + assert!((x - crit).abs() > 1e-7, "ζ {z} at {t}: {x} vs {crit}"); + } + } + } +} + +/// A critically damped step keeps the velocity a tiny step leaves, beside a huge offset. +#[test] +fn a_critical_step_keeps_its_velocity_beside_a_huge_offset() { + let s = Spring::from_physical(1.0, 1.0, 2.0).unwrap(); + assert_eq!(s.damping(), 1.0); + let mut st = SpringState { value: 1e20, velocity: 1.0 }; + st.step(&s, 0.0, 1e-22).unwrap(); + assert!((st.velocity - 0.99).abs() < 1e-12, "{st:?}"); +} + +/// A spring whose damped frequency rounds to 0 moves at its velocity over a step. +#[test] +fn a_spring_whose_damped_frequency_rounds_to_zero_still_steps() { + let s = Spring::new(f64::from_bits(1), 0.9998).unwrap(); + let mut st = SpringState { value: 0.0, velocity: 1.0 }; + let v = st.step(&s, 0.0, 1.0).unwrap(); + assert!((v - 1.0).abs() < 1e-12 && (st.velocity - 1.0).abs() < 1e-12, "{st:?}"); +} + +/// A spring whose damped frequency is above 0 but whose phase over a short step rounds to 0 +/// still moves at its velocity over the step. +#[test] +fn a_step_whose_phase_rounds_to_zero_still_moves() { + let s = Spring::new(1e-320, 0.99995).unwrap(); + let mut st = SpringState { value: 0.0, velocity: 1.0 }; + let v = st.step(&s, 0.0, 0.001).unwrap(); + assert!((v - 0.001).abs() < 1e-15 && (st.velocity - 1.0).abs() < 1e-12, "{st:?}"); +} + +/// A state that is not finite is refused at every step length and in every damping regime, +/// and stays as it is. +#[test] +fn a_state_that_is_not_finite_is_refused_at_any_step_length() { + for z in [0.5, 1.0, 2.0] { + let s = Spring::new(1.0, z).unwrap(); + for start in [SpringState::at(f64::NAN), SpringState { value: 0.0, velocity: f64::INFINITY }] { + for dt in [0.0, 0.1, 200.0, 1e300] { + let mut st = start; + assert_eq!(st.step(&s, 1.0, dt), Err(EaseError::Overflow), "ζ {z}, {dt}"); + assert_eq!((st.value.to_bits(), st.velocity.to_bits()), (start.value.to_bits(), start.velocity.to_bits())); + } + } + } +} + +#[test] +fn the_three_damping_regimes_agree_near_critical_damping() { + // Either side of critical damping, the solutions meet the critically damped one. + let w = 10.0; + for t in [0.01, 0.1, 0.3, 1.0] { + let crit = released(w, 1.0, t); + for z in [1.0 - 2e-4, 1.0 - 5e-5, 1.0, 1.0 + 5e-5, 1.0 + 2e-4] { + let s = Spring::new(w / std::f64::consts::TAU, z).unwrap(); + let mut st = SpringState::at(0.0); + let v = st.step(&s, 1.0, t).unwrap(); + assert!((v - crit).abs() < 1e-3, "ζ {z} at {t}: {v} vs {crit}"); + } + } +} + +#[test] +fn a_spring_settles_on_its_target() { + for (f, z) in [(2.0, 0.2), (1.0, 1.0), (0.5, 3.0), (8.0, 0.05)] { + let s = Spring::new(f, z).unwrap(); + let mut st = SpringState::at(0.0); + for _ in 0..60 * 120 { + st.step(&s, 10.0, 1.0 / 60.0).unwrap(); + } + assert!(st.settled(10.0, 1e-6), "{f} Hz ζ {z}: {st:?}"); + } + // An undamped spring keeps swinging, its energy kept. + let s = Spring::new(1.0, 0.0).unwrap(); + let mut st = SpringState::at(0.0); + for _ in 0..60 * 100 { + st.step(&s, 1.0, 1.0 / 60.0).unwrap(); + } + let w = s.omega(); + let energy = (st.value - 1.0).powi(2) + (st.velocity / w).powi(2); + assert!((energy - 1.0).abs() < 1e-9, "{energy}"); +} + +/// Many short steps land where one long step does: the step is exact, not an integrator. +#[test] +fn many_small_steps_equal_one_long_step() { + for (f, z) in [(3.0, 0.3), (1.0, 1.0), (1.0, 4.0), (0.7, 0.0)] { + let s = Spring::new(f, z).unwrap(); + let mut one = SpringState { value: -2.0, velocity: 5.0 }; + let mut many = one; + one.step(&s, 1.0, 2.0).unwrap(); + for _ in 0..240 { + many.step(&s, 1.0, 2.0 / 240.0).unwrap(); + } + assert!((one.value - many.value).abs() < 1e-9 && (one.velocity - many.velocity).abs() < 1e-8, "{f} {z}: {one:?} {many:?}"); + } + // Variable frame lengths too. + let s = Spring::new(2.0, 0.4).unwrap(); + let (mut a, mut b) = (SpringState::at(0.0), SpringState::at(0.0)); + a.step(&s, 1.0, 0.5).unwrap(); + for dt in [0.1, 0.016, 0.05, 0.034, 0.2, 0.1] { + b.step(&s, 1.0, dt).unwrap(); + } + assert!((a.value - b.value).abs() < 1e-9); +} + +#[test] +fn huge_steps_land_on_the_target() { + for (f, z) in [(MAX_SPRING_HZ, 0.0001), (1e-6, 0.5), (1.0, MAX_DAMPING_RATIO), (5.0, 1.0)] { + let s = Spring::new(f, z).unwrap(); + for dt in [1e6, 1e300, f64::MAX] { + let mut st = SpringState { value: 5.0, velocity: -3.0 }; + let v = st.step(&s, 2.0, dt).unwrap(); + assert!(v.is_finite() && st.velocity.is_finite(), "{f} {z} {dt}"); + } + } + let s = Spring::new(4.0, 0.5).unwrap(); + let mut st = SpringState { value: 5.0, velocity: -3.0 }; + assert_eq!(st.step(&s, 2.0, 1e300).unwrap(), 2.0); + assert_eq!(st.velocity, 0.0); + // An undamped spring keeps its energy over any finite step, the longest included. + let s = Spring::new(MAX_SPRING_HZ, 0.0).unwrap(); + let w = s.omega(); + for dt in [1e300, f64::MAX] { + let mut st = SpringState { value: 5.0, velocity: -3.0 }; + st.step(&s, 2.0, dt).unwrap(); + let energy = (st.value - 2.0).powi(2) + (st.velocity / w).powi(2); + assert!((energy - (9.0 + (3.0 / w).powi(2))).abs() < 1e-9, "{dt}: {st:?}"); + } + let s = Spring::new(4.0, 0.5).unwrap(); + // A zero step changes nothing. + let mut st = SpringState { value: 5.0, velocity: -3.0 }; + assert_eq!(st.step(&s, 2.0, 0.0).unwrap(), 5.0); + assert_eq!(st.velocity, -3.0); +} + +#[test] +fn bad_inputs_are_refused_and_leave_the_state_alone() { + assert_eq!(Spring::new(f64::NAN, 0.5), Err(EaseError::NotFinite("frequency"))); + assert!(matches!(Spring::new(0.0, 0.5), Err(EaseError::OutOfRange { what: "frequency", .. }))); + assert!(matches!(Spring::new(MAX_SPRING_HZ * 2.0, 0.5), Err(EaseError::OutOfRange { what: "frequency", .. }))); + assert!(matches!(Spring::new(1.0, -0.1), Err(EaseError::OutOfRange { what: "damping", .. }))); + assert_eq!(Spring::new(1.0, f64::INFINITY), Err(EaseError::NotFinite("damping"))); + assert!(matches!(Spring::from_controls(1.5, 0.5), Err(EaseError::OutOfRange { what: "strength", .. }))); + assert!(matches!(Spring::from_physical(1.0, 0.0, 1.0), Err(EaseError::OutOfRange { what: "stiffness", .. }))); + let s = Spring::new(1.0, 0.5).unwrap(); + let start = SpringState { value: 1.0, velocity: 2.0 }; + for (target, dt, err) in [ + (f64::NAN, 0.1, EaseError::NotFinite("target")), + (f64::INFINITY, 0.1, EaseError::NotFinite("target")), + (0.0, f64::NAN, EaseError::NotFinite("step")), + (0.0, f64::INFINITY, EaseError::NotFinite("step")), + ] { + let mut st = start; + assert_eq!(st.step(&s, target, dt), Err(err)); + assert_eq!(st, start); + } + let mut st = start; + assert!(matches!(st.step(&s, 0.0, -0.1), Err(EaseError::OutOfRange { what: "step", .. }))); + assert_eq!(st, start); + // A value too far from the target to measure is refused, not turned into NaN. + let mut far = SpringState { value: f64::MAX, velocity: 0.0 }; + assert_eq!(far.step(&s, -f64::MAX, 0.1), Err(EaseError::Overflow)); + assert_eq!(far, SpringState { value: f64::MAX, velocity: 0.0 }); +} + +#[test] +fn the_controls_map_onto_frequency_and_damping() { + let s = Spring::from_controls(0.0, 0.0).unwrap(); + assert!((s.omega() - std::f64::consts::TAU * 0.5).abs() < 1e-12 && s.damping() == 0.0); + let s = Spring::from_controls(1.0, 2.0 / 3.0).unwrap(); + assert!((s.omega() - std::f64::consts::TAU * 10.0).abs() < 1e-9 && (s.damping() - 1.0).abs() < 1e-12); + assert_eq!(Spring::from_controls(0.5, 1.0).unwrap().damping(), MAX_DAMPING_RATIO); +} diff --git a/crates/ease/src/tests/track_tests.rs b/crates/ease/src/tests/track_tests.rs new file mode 100644 index 0000000000..d39ae5a830 --- /dev/null +++ b/crates/ease/src/tests/track_tests.rs @@ -0,0 +1,162 @@ +use crate::*; + +fn key(time: f64, value: T, ease: Easing) -> Key { + Key { time, value, ease } +} + +#[test] +fn a_track_eases_between_its_keys_and_holds_outside_them() { + let t = Track::from_keys(vec![ + key(2.0, 10.0f64, Easing::QuadIn), + key(0.0, 0.0, Easing::Linear), + key(4.0, 0.0, Easing::Hold), + key(6.0, 50.0, Easing::Linear), + ]) + .unwrap(); + assert_eq!(t.keys().iter().map(|k| k.time).collect::>(), [0.0, 2.0, 4.0, 6.0]); + assert_eq!(t.sample(-1.0), Ok(0.0)); + assert_eq!(t.sample(1.0), Ok(5.0)); + assert_eq!(t.sample(2.0), Ok(10.0)); + // Quad in: a quarter of the way at half time. + assert_eq!(t.sample(3.0), Ok(7.5)); + // Hold keeps the value until the next key. + assert_eq!(t.sample(4.0), Ok(0.0)); + assert_eq!(t.sample(5.999), Ok(0.0)); + assert_eq!(t.sample(6.0), Ok(50.0)); + assert_eq!(t.sample(1e300), Ok(50.0)); +} + +#[test] +fn an_overshooting_ease_carries_the_value_past_its_keys() { + let t = Track::from_keys(vec![key(0.0, 0.0f64, Easing::BackOut), key(1.0, 100.0, Easing::Linear)]).unwrap(); + let peak = (1..100).map(|i| t.sample(i as f64 / 100.0).unwrap()).fold(f64::MIN, f64::max); + assert!(peak > 105.0 && peak < 115.0, "{peak}"); +} + +#[test] +fn tracks_hold_any_animatable_value() { + let p = Track::from_keys(vec![key(0.0, Vec2::new(0.0, 0.0), Easing::Linear), key(1.0, Vec2::new(10.0, -20.0), Easing::Linear)]).unwrap(); + assert_eq!(p.sample(0.5), Ok(Vec2::new(5.0, -10.0))); + let c = Track::from_keys(vec![key(0.0, [0.0f32, 1.0, 0.5, 1.0], Easing::Linear), key(2.0, [1.0, 0.0, 0.5, 0.0], Easing::Linear)]).unwrap(); + assert_eq!(c.sample(1.0), Ok([0.5, 0.5, 0.5, 0.5])); + let s = Track::from_keys(vec![key(0.0, 1.0f32, Easing::Linear), key(1.0, 3.0, Easing::Linear)]).unwrap(); + assert_eq!(s.sample(0.25), Ok(1.5)); + let d = Track::from_keys(vec![key(0.0, [0.0f64; 3], Easing::Linear), key(1.0, [3.0, 6.0, 9.0], Easing::Linear)]).unwrap(); + assert_eq!(d.sample(1.0 / 3.0).map(|v| v.map(|x| (x * 1e9).round() / 1e9)), Ok([1.0, 2.0, 3.0])); +} + +#[test] +fn bad_keys_and_times_are_refused() { + assert_eq!(Track::::new().sample(0.0), Err(EaseError::Empty)); + let t = Track::from_keys(vec![key(0.0, 1.0f64, Easing::Linear)]).unwrap(); + assert_eq!(t.sample(f64::NAN), Err(EaseError::NotFinite("time"))); + assert_eq!(t.sample(f64::INFINITY), Err(EaseError::NotFinite("time"))); + assert_eq!(t.sample(5.0), Ok(1.0)); + assert_eq!(Track::from_keys(vec![key(f64::NAN, 1.0f64, Easing::Linear)]), Err(EaseError::NotFinite("time"))); + assert_eq!(Track::from_keys(vec![key(0.0, f64::NAN, Easing::Linear)]), Err(EaseError::NotFinite("value"))); + assert_eq!(Track::from_keys(vec![key(0.0, Vec2::new(0.0, f64::INFINITY), Easing::Linear)]), Err(EaseError::NotFinite("value"))); + assert_eq!(Track::from_keys(vec![key(1.0, 1.0f64, Easing::Linear), key(1.0, 2.0, Easing::Linear)]), Err(EaseError::SameTime(1.0))); + // −0 and +0 are one time. + assert_eq!(Track::from_keys(vec![key(-0.0, 1.0f64, Easing::Linear), key(0.0, 2.0, Easing::Linear)]), Err(EaseError::SameTime(0.0))); + let mut z = Track::from_keys(vec![key(-0.0, 1.0f64, Easing::Linear), key(1.0, 2.0, Easing::Linear)]).unwrap(); + assert_eq!(z.key_at(0.0), Some(0)); + assert_eq!(z.key_at(-0.0), Some(0)); + assert_eq!(z.insert(0.0, 5.0), Ok(0)); + assert_eq!(z.len(), 2); + let too_many: Vec> = (0..=MAX_TRACK_KEYS).map(|i| key(i as f64, 0.0, Easing::Linear)).collect(); + assert_eq!(Track::from_keys(too_many), Err(EaseError::Full(MAX_TRACK_KEYS))); +} + +#[test] +fn inserting_splits_a_segment_with_its_ease() { + let mut t = Track::from_keys(vec![key(0.0, 0.0f64, Easing::CubicIn), key(2.0, 8.0, Easing::Linear)]).unwrap(); + assert_eq!(t.insert(1.0, 1.0), Ok(1)); + assert_eq!(t.keys()[1].ease, Easing::CubicIn); + // Setting an existing key keeps its ease. + t.set_ease(1, Easing::Hold).unwrap(); + assert_eq!(t.insert(1.0, 3.0), Ok(1)); + assert_eq!((t.keys()[1].value, &t.keys()[1].ease), (3.0, &Easing::Hold)); + assert_eq!(t.insert(-0.0, 7.0), Ok(0)); + assert_eq!(t.len(), 3); + assert_eq!(t.key_at(0.0), Some(0)); + assert_eq!(t.insert(5.0, f64::NAN), Err(EaseError::NotFinite("value"))); + assert_eq!(t.insert(f64::NEG_INFINITY, 1.0), Err(EaseError::NotFinite("time"))); + assert_eq!(t.remove(1).map(|k| k.value), Some(3.0)); + assert!(t.remove(9).is_none() && t.set_ease(9, Easing::Linear).is_none()); + // Before the first key, a new key eases linearly. + assert_eq!(t.insert(-1.0, 0.0), Ok(0)); + assert_eq!(t.keys()[0].ease, Easing::Linear); +} + +#[test] +fn keys_at_the_ends_of_the_number_range_sample_without_overflow() { + let t = Track::from_keys(vec![key(-f64::MAX, -1.0f64, Easing::Linear), key(f64::MAX, 1.0, Easing::Linear)]).unwrap(); + assert_eq!(t.sample(0.0), Ok(0.0)); + let v = t.sample(f64::MAX / 2.0).unwrap(); + assert!((v - 0.5).abs() < 1e-12, "{v}"); + // Keys a hair apart. + let near = Track::from_keys(vec![key(1.0, 0.0f64, Easing::Linear), key(1.0 + f64::EPSILON, 1.0, Easing::Linear)]).unwrap(); + assert!(near.sample(1.0 + f64::EPSILON / 2.0).unwrap().is_finite()); + // Values at opposite ends of the range interpolate without overflowing their difference. + let wide = Track::from_keys(vec![key(0.0, f64::MAX, Easing::Linear), key(1.0, -f64::MAX, Easing::Linear)]).unwrap(); + assert_eq!(wide.sample(0.5), Ok(0.0)); + let v = + Track::from_keys(vec![key(0.0, Vec2::new(-f64::MAX, 1e308), Easing::Linear), key(1.0, Vec2::new(f64::MAX, -1e308), Easing::Linear)]).unwrap(); + assert_eq!(v.sample(0.5), Ok(Vec2::ZERO)); + let a = Track::from_keys(vec![key(0.0, [f64::MAX; 2], Easing::Linear), key(1.0, [-f64::MAX; 2], Easing::Linear)]).unwrap(); + assert!(a.sample(0.25).unwrap().iter().all(|x| x.is_finite())); + // Keys a subnormal step either side of 0 still interpolate between them. + let tiny = Track::from_keys(vec![key(-f64::from_bits(1), 0.0f64, Easing::Linear), key(f64::from_bits(1), 1.0, Easing::Linear)]).unwrap(); + assert_eq!(tiny.sample(0.0), Ok(0.5)); + // An overshoot past the largest f32 is refused, not returned as infinity. + let over = Track::from_keys(vec![key(0.0, -f32::MAX, Easing::BackOut), key(1.0, f32::MAX, Easing::Linear)]).unwrap(); + assert_eq!(over.sample(0.6), Err(EaseError::Overflow)); + // An overshoot whose step past the far key is too large to represent, with a result that + // is not. + let r = crate::lerp(-1e308, 5e307, 1.25); + assert!((r / 8.75e307 - 1.0).abs() < 1e-12, "{r}"); + let back = Track::from_keys(vec![key(0.0, -f64::MAX, Easing::BackOut), key(1.0, -1e300, Easing::Linear)]).unwrap(); + assert!(back.sample(0.6).unwrap() > 0.0); +} + +#[cfg(feature = "serde")] +#[test] +fn tracks_round_trip_through_files_and_bad_files_are_refused() { + let t = Track::from_keys(vec![key(0.0, 1.0f64, Easing::Linear), key(1.5, 2.0, Easing::Hold), key(3.0, 0.5, Easing::QuadOut)]).unwrap(); + let text = serde_json::to_string(&t).unwrap(); + assert_eq!( + text, + r#"{"keys":[{"time":0.0,"value":1.0,"ease":"Linear"},{"time":1.5,"value":2.0,"ease":"Hold"},{"time":3.0,"value":0.5,"ease":"QuadOut"}]}"# + ); + assert_eq!(serde_json::from_str::>(&text).unwrap(), t); + // Keys out of order are sorted; a missing ease is linear. + let r: Track = serde_json::from_str(r#"{"keys":[{"time":2,"value":1},{"time":1,"value":0}]}"#).unwrap(); + assert_eq!((r.keys()[0].time, &r.keys()[1].ease), (1.0, &Easing::Linear)); + // Two keys at one time, or a time that is not a number, are a broken file. + assert!(serde_json::from_str::>(r#"{"keys":[{"time":1,"value":1},{"time":1,"value":0}]}"#).is_err()); + assert!(serde_json::from_str::>(r#"{"keys":[{"time":"x","value":1}]}"#).is_err()); + // More keys than a track holds are refused while reading, before the rest are read. + let mut big = String::from(r#"{"keys":["#); + for i in 0..=MAX_TRACK_KEYS { + if i > 0 { + big.push(','); + } + big.push_str(&format!(r#"{{"time":{i},"value":0}}"#)); + } + big.push_str("]}"); + let err = serde_json::from_str::>(&big).unwrap_err().to_string(); + assert!(err.contains("more than 100000 keys"), "{err}"); +} + +/// Formats that write a struct as its fields in order (rather than by name) read a track too, +/// through the same checks. +#[cfg(feature = "serde")] +#[test] +fn tracks_read_from_formats_that_write_fields_in_order() { + let t: Track = serde_json::from_str(r#"[[{"time":2,"value":1},{"time":1,"value":0,"ease":"QuadIn"}]]"#).unwrap(); + assert_eq!(t.keys().iter().map(|k| (k.time, k.value)).collect::>(), [(1.0, 0.0), (2.0, 1.0)]); + assert_eq!(t.keys()[0].ease, Easing::QuadIn); + assert!(serde_json::from_str::>(r#"[[{"time":1,"value":1},{"time":1,"value":0}]]"#).is_err()); + assert!(serde_json::from_str::>("[]").is_err()); + assert!(serde_json::from_str::>("[[], 1]").is_err()); +} diff --git a/crates/ease/src/track.rs b/crates/ease/src/track.rs new file mode 100644 index 0000000000..c2c139ddc2 --- /dev/null +++ b/crates/ease/src/track.rs @@ -0,0 +1,269 @@ +//! [`Track`]: keyed values with an ease between each key and the next. + +use crate::{EaseError, Easing, Vec2, finite}; + +/// Most keys one track holds. +pub const MAX_TRACK_KEYS: usize = 100_000; + +/// A value a track can animate: interpolated in a straight line between keys, the ease giving +/// how far along. Eases that overshoot pass `t` outside `0..=1`, which extrapolates. +pub trait Animatable: Clone { + /// The value `t` of the way from `self` to `to`. + fn lerp(&self, to: &Self, t: f64) -> Self; + /// Whether every component is finite. + fn is_finite(&self) -> bool; +} + +impl Animatable for f32 { + fn lerp(&self, to: &f32, t: f64) -> f32 { + crate::lerp(f64::from(*self), f64::from(*to), t) as f32 + } + fn is_finite(&self) -> bool { + f32::is_finite(*self) + } +} + +impl Animatable for f64 { + fn lerp(&self, to: &f64, t: f64) -> f64 { + crate::lerp(*self, *to, t) + } + fn is_finite(&self) -> bool { + f64::is_finite(*self) + } +} + +impl Animatable for Vec2 { + fn lerp(&self, to: &Vec2, t: f64) -> Vec2 { + Vec2::lerp(*self, *to, t) + } + fn is_finite(&self) -> bool { + Vec2::is_finite(*self) + } +} + +impl Animatable for [f32; N] { + fn lerp(&self, to: &[f32; N], t: f64) -> [f32; N] { + let mut out = *self; + for (o, b) in out.iter_mut().zip(to) { + *o = Animatable::lerp(&*o, b, t); + } + out + } + fn is_finite(&self) -> bool { + self.iter().all(|v| v.is_finite()) + } +} + +impl Animatable for [f64; N] { + fn lerp(&self, to: &[f64; N], t: f64) -> [f64; N] { + let mut out = *self; + for (o, b) in out.iter_mut().zip(to) { + *o = crate::lerp(*o, *b, t); + } + out + } + fn is_finite(&self) -> bool { + self.iter().all(|v| v.is_finite()) + } +} + +/// A key: a value at a time (seconds), and the ease to the next key ([`Easing::Hold`] keeps the +/// value until the next key). +#[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Key { + pub time: f64, + pub value: T, + #[cfg_attr(feature = "serde", serde(default))] + pub ease: Easing, +} + +/// Keys sorted by time, one per time, at most [`MAX_TRACK_KEYS`], every time and value finite. +/// +/// Before the first key a track gives the first key's value, after the last key the last's. +#[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct Track { + keys: Vec>, +} + +impl Default for Track { + fn default() -> Self { + Track { keys: Vec::new() } + } +} + +impl Track { + pub fn new() -> Self { + Track::default() + } + + /// A track from keys a caller or a file supplies: an error for a time or value that is not + /// finite, two keys at one time, or more than [`MAX_TRACK_KEYS`]. The keys may come in any + /// order. + pub fn from_keys(mut keys: Vec>) -> Result { + if keys.len() > MAX_TRACK_KEYS { + return Err(EaseError::Full(MAX_TRACK_KEYS)); + } + for k in &mut keys { + check(k.time, &k.value)?; + // -0.0 and 0.0 are one time. + if k.time == 0.0 { + k.time = 0.0; + } + } + keys.sort_by(|a, b| a.time.total_cmp(&b.time)); + if let Some(w) = keys.windows(2).find(|w| matches!(w, [a, b] if a.time == b.time)) { + return Err(EaseError::SameTime(w.first().map_or(0.0, |k| k.time))); + } + Ok(Track { keys }) + } + + pub fn keys(&self) -> &[Key] { + &self.keys + } + + pub fn is_empty(&self) -> bool { + self.keys.is_empty() + } + + pub fn len(&self) -> usize { + self.keys.len() + } + + /// Sets the value at `time`, keeping that key's ease, or adds a key there that eases like + /// the segment it splits. Returns the key's index. An error for a time or value that is not + /// finite, or a full track. + pub fn insert(&mut self, time: f64, value: T) -> Result { + check(time, &value)?; + // -0.0 and 0.0 are one time. + let time = if time == 0.0 { 0.0 } else { time }; + match self.keys.binary_search_by(|k| k.time.total_cmp(&time)) { + Ok(i) => { + if let Some(k) = self.keys.get_mut(i) { + k.value = value; + } + Ok(i) + } + Err(i) => { + if self.keys.len() >= MAX_TRACK_KEYS { + return Err(EaseError::Full(MAX_TRACK_KEYS)); + } + let ease = i.checked_sub(1).and_then(|p| self.keys.get(p)).map_or_else(Easing::default, |k| k.ease.clone()); + self.keys.insert(i, Key { time, value, ease }); + Ok(i) + } + } + } + + /// Sets the ease from key `i` to the next one. `None` for a missing key. + pub fn set_ease(&mut self, i: usize, ease: Easing) -> Option<()> { + self.keys.get_mut(i)?.ease = ease; + Some(()) + } + + /// Removes key `i`, returning it. + pub fn remove(&mut self, i: usize) -> Option> { + (i < self.keys.len()).then(|| self.keys.remove(i)) + } + + /// The index of the key at exactly `time` (−0 and +0 are one time). + pub fn key_at(&self, time: f64) -> Option { + let time = if time == 0.0 { 0.0 } else { time }; + self.keys.binary_search_by(|k| k.time.total_cmp(&time)).ok() + } + + /// The value at `time`. An error for an empty track, a `time` that is not finite, or an + /// overshooting ease that carries the value past what the type can hold. + pub fn sample(&self, time: f64) -> Result { + let time = finite(time, "time")?; + let (Some(first), Some(last)) = (self.keys.first(), self.keys.last()) else { return Err(EaseError::Empty) }; + if time <= first.time { + return Ok(first.value.clone()); + } + if time >= last.time { + return Ok(last.value.clone()); + } + let i = self.keys.partition_point(|k| k.time <= time); + let (Some(a), Some(b)) = (i.checked_sub(1).and_then(|j| self.keys.get(j)), self.keys.get(i)) else { return Ok(last.value.clone()) }; + if a.ease == Easing::Hold { + return Ok(a.value.clone()); + } + // Keys at opposite ends of the f64 range overflow the span; halving both sides keeps it. + let span = b.time - a.time; + let t = if span.is_finite() { (time - a.time) / span } else { (time * 0.5 - a.time * 0.5) / (b.time * 0.5 - a.time * 0.5) }; + let v = a.value.lerp(&b.value, a.ease.apply(t.clamp(0.0, 1.0))); + if v.is_finite() { Ok(v) } else { Err(EaseError::Overflow) } + } +} + +fn check(time: f64, value: &T) -> Result<(), EaseError> { + finite(time, "time")?; + if value.is_finite() { Ok(()) } else { Err(EaseError::NotFinite("value")) } +} + +#[cfg(feature = "serde")] +mod serde_impl { + use super::{Animatable, Key, MAX_TRACK_KEYS, Track}; + use serde::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor}; + use std::marker::PhantomData; + + /// The key list, read one key at a time and refused once it passes [`MAX_TRACK_KEYS`], so a + /// hostile file cannot make it allocate more. + struct Keys(Vec>); + + impl<'de, T: Deserialize<'de>> Deserialize<'de> for Keys { + fn deserialize>(d: D) -> Result { + struct V(PhantomData); + impl<'de, T: Deserialize<'de>> Visitor<'de> for V { + type Value = Keys; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "a list of at most {MAX_TRACK_KEYS} keys") + } + fn visit_seq>(self, mut seq: A) -> Result, A::Error> { + let mut keys = Vec::with_capacity(seq.size_hint().unwrap_or(0).min(1024)); + while let Some(k) = seq.next_element()? { + if keys.len() >= MAX_TRACK_KEYS { + return Err(A::Error::custom(format!("more than {MAX_TRACK_KEYS} keys"))); + } + keys.push(k); + } + Ok(Keys(keys)) + } + } + d.deserialize_seq(V(PhantomData)) + } + } + + impl<'de, T: Animatable + Deserialize<'de>> Deserialize<'de> for Track { + fn deserialize>(d: D) -> Result { + struct V(PhantomData); + impl<'de, T: Animatable + Deserialize<'de>> Visitor<'de> for V { + type Value = Track; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "a track") + } + fn visit_map>(self, mut map: A) -> Result, A::Error> { + let mut keys: Option>> = None; + while let Some(name) = map.next_key::()? { + if name == "keys" { + keys = Some(map.next_value::>()?.0); + } else { + map.next_value::()?; + } + } + Track::from_keys(keys.unwrap_or_default()).map_err(A::Error::custom) + } + /// Formats that write a struct as its fields in order. + fn visit_seq>(self, mut seq: A) -> Result, A::Error> { + let keys = seq.next_element::>()?.ok_or_else(|| A::Error::invalid_length(0, &self))?.0; + if seq.next_element::()?.is_some() { + return Err(A::Error::invalid_length(2, &self)); + } + Track::from_keys(keys).map_err(A::Error::custom) + } + } + d.deserialize_struct("Track", &["keys"], V(PhantomData)) + } + } +} diff --git a/crates/ease/src/vec2.rs b/crates/ease/src/vec2.rs new file mode 100644 index 0000000000..60a1b6896a --- /dev/null +++ b/crates/ease/src/vec2.rs @@ -0,0 +1,83 @@ +//! A 2D point or vector, for ease curve points and motion paths. + +use std::ops::{Add, Mul, Neg, Sub}; + +/// A 2D point or vector. In files it is `{"x": …, "y": …}`. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Vec2 { + pub x: f64, + pub y: f64, +} + +impl Vec2 { + pub const ZERO: Vec2 = Vec2 { x: 0.0, y: 0.0 }; + + pub const fn new(x: f64, y: f64) -> Self { + Vec2 { x, y } + } + + pub fn dot(self, o: Vec2) -> f64 { + self.x * o.x + self.y * o.y + } + + /// The length. Large components do not overflow on the way, so the length is finite whenever + /// it is at most `f64::MAX`; a longer vector, such as `(f64::MAX, f64::MAX)`, has an infinite + /// length. [`Vec2::normalized`] still gives such a vector's direction. + pub fn length(self) -> f64 { + self.x.hypot(self.y) + } + + /// The vector scaled to length 1, or zero for a zero (or non-finite) vector. The components + /// are divided by the larger one first, so a vector near the largest or smallest `f64` still + /// gives a unit vector. + pub fn normalized(self) -> Vec2 { + let m = self.x.abs().max(self.y.abs()); + if !(self.is_finite() && m > 0.0) { + return Vec2::ZERO; + } + let (x, y) = (self.x / m, self.y / m); + let l = x.hypot(y); + Vec2::new(x / l, y / l) + } + + pub fn lerp(self, o: Vec2, t: f64) -> Vec2 { + Vec2::new(crate::lerp(self.x, o.x, t), crate::lerp(self.y, o.y, t)) + } + + pub fn distance(self, o: Vec2) -> f64 { + (o - self).length() + } + + pub fn is_finite(self) -> bool { + self.x.is_finite() && self.y.is_finite() + } +} + +impl Add for Vec2 { + type Output = Vec2; + fn add(self, o: Vec2) -> Vec2 { + Vec2::new(self.x + o.x, self.y + o.y) + } +} + +impl Sub for Vec2 { + type Output = Vec2; + fn sub(self, o: Vec2) -> Vec2 { + Vec2::new(self.x - o.x, self.y - o.y) + } +} + +impl Mul for Vec2 { + type Output = Vec2; + fn mul(self, s: f64) -> Vec2 { + Vec2::new(self.x * s, self.y * s) + } +} + +impl Neg for Vec2 { + type Output = Vec2; + fn neg(self) -> Vec2 { + Vec2::new(-self.x, -self.y) + } +} diff --git a/crates/exr/src/decode.rs b/crates/exr/src/decode.rs index 1ec050565f..6a8e3b0c32 100644 --- a/crates/exr/src/decode.rs +++ b/crates/exr/src/decode.rs @@ -12,8 +12,9 @@ //! //! The `exr` crate sizes buffers from headers before it reads pixels, so everything that reaches //! it is checked first: preview attributes against their own size, each part's samples against -//! [`Limits`], all parts together against the budget, and the samples against what a file of -//! this size can decompress to. +//! [`Limits`], all parts together against the budget, the samples against what a file of this +//! size can decompress to, and the packed length of each chunk of the part being read against the +//! rest of the file and the budget. use std::io::Cursor; @@ -456,7 +457,11 @@ pub fn decode_display_part( if pixels > limits.max_pixels { return Err(Error::LimitExceeded(format!("display window of {pixels} pixels exceeds {}", limits.max_pixels))); } - let kept = info.channels.iter().filter(|channel| keep(&part_channel_name(info.name.as_deref(), &channel.name))).count(); + let header = meta.headers.get(index).ok_or_else(|| malformed(format!("part {index}")))?; + let prefix = header.own_attributes.layer_name.as_ref().map(|name| name.to_string()).filter(|name| !name.is_empty()); + let kept_names = kept_channel_names(header, prefix.as_deref(), keep); + let kept = + header.channels.list.iter().filter(|channel| kept_names.contains(&part_channel_name(prefix.as_deref(), &channel.name.to_string()))).count(); let bytes_needed = pixels .checked_mul(4) .and_then(|bytes_per_channel| bytes_per_channel.checked_mul(kept as u64)) @@ -464,16 +469,18 @@ pub fn decode_display_part( if bytes_needed > limits.max_bytes || usize::try_from(bytes_needed).is_err() { return Err(Error::LimitExceeded(format!("{bytes_needed} display-window bytes exceed {}", limits.max_bytes))); } + let recorded = |name: &str| kept_names.contains(name); + let keep: &dyn Fn(&str) -> bool = &recorded; let block_limit = std::cell::Cell::new(None); let select = DisplaySelect { index, keep, fill, limits, seen: std::cell::Cell::new(0), block_limit: &block_limit }; let exr_error = |error| block_limit.take().map(Error::LimitExceeded).unwrap_or_else(|| map_exr(error)); let planes = if meta.headers.iter().any(|header| header.deep) { - let header = meta.headers.get(index).ok_or_else(|| malformed(format!("part {index}")))?; select.seen.set(index); let mut reader = select.create_channels_reader(header).map_err(exr_error)?; read_flat_part_chunks(bytes, &meta, index, &mut reader, limits)?; reader.into_channels() } else { + check_flat_packed_lengths(bytes, &meta, index, kept > 0, limits)?; ReadImage::new(ReadAllLayers { read_channels: select }, |_| {}) .from_buffered(Cursor::new(bytes)) .map_err(exr_error)? @@ -822,6 +829,104 @@ pub(super) fn flat_block_ordinal(header: &Header, tile: TileCoordinates) -> Resu Err(malformed("flat tile names a missing level")) } +/// Part `index`'s offset table (one `u64` per chunk) and where the last offset table ends. The +/// tables follow the headers, one per part in header order, and must all lie inside the file. +fn part_offset_table<'a>(bytes: &'a [u8], meta: &MetaData, index: usize) -> Result<(&'a [u8], u64)> { + let header = meta.headers.get(index).ok_or_else(|| malformed(format!("part {index}")))?; + let truncated = || malformed("the offset tables run past the end of the file"); + let (mut table, mut tables_end) = (0u64, tables_start(bytes)?); + for (i, h) in meta.headers.iter().enumerate() { + if i == index { + table = tables_end; + } + let len = u64::try_from(h.chunk_count).ok().and_then(|n| n.checked_mul(8)).ok_or_else(truncated)?; + tables_end = tables_end.checked_add(len).filter(|end| *end <= bytes.len() as u64).ok_or_else(truncated)?; + } + let offsets = usize::try_from(table) + .ok() + .and_then(|start| bytes.get(start..start.checked_add(header.chunk_count.checked_mul(8)?)?)) + .ok_or_else(truncated)?; + Ok((offsets, tables_end)) +} + +/// The bytes from `offset` to the end of the file, and the packed length the flat chunk there +/// declares. The chunk must start past the last offset table and inside the file, carry part +/// number `index` in a multipart file, and declare no more bytes than the file has left after its +/// length field. +fn flat_chunk_at<'a>(bytes: &'a [u8], header: &Header, multipart: bool, index: usize, offset: u64, tables_end: u64) -> Result<(&'a [u8], usize)> { + let chunk = usize::try_from(offset) + .ok() + .filter(|_| offset >= tables_end) + .and_then(|start| bytes.get(start..)) + .filter(|rest| !rest.is_empty()) + .ok_or_else(|| malformed(format!("chunk offset {offset} is outside the chunk area of the file")))?; + if multipart { + let part = chunk.get(..4).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(i32::from_le_bytes); + let part = part.ok_or_else(|| malformed(format!("the chunk at offset {offset} is cut off")))?; + if usize::try_from(part).ok() != Some(index) { + return Err(malformed(format!("the chunk at offset {offset} belongs to part {part}, not part {index}"))); + } + } + // The crate allocates a chunk's declared payload before it reads it, so the payload must + // fit in the rest of the file. The length follows the part number and the block's y, or + // its four tile coordinates. + let fields = if matches!(header.blocks, exr::meta::BlockDescription::Tiles(_)) { 16 } else { 4 }; + let size_at = if multipart { 4 } else { 0 } + fields; + let size = chunk.get(size_at..size_at + 4).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(i32::from_le_bytes); + let size = size.ok_or_else(|| malformed(format!("the chunk at offset {offset} is cut off")))?; + let left = chunk.len() - (size_at + 4); + if usize::try_from(size).is_ok_and(|size| size > left) { + return Err(malformed(format!("the chunk at offset {offset} declares {size} bytes, but {left} remain in the file"))); + } + let size = usize::try_from(size).map_err(|_| malformed("negative packed chunk length"))?; + Ok((chunk, size)) +} + +/// The names of `header`'s channels that `keep` accepts, named as the channel readers name them +/// (behind `prefix`, the part's name, when there is one). `keep` is asked once per channel, and +/// the readers and the packed-length check use this one answer. +fn kept_channel_names(header: &Header, prefix: Option<&str>, keep: &dyn Fn(&str) -> bool) -> std::collections::HashSet { + let names = header.channels.list.iter().map(|channel| part_channel_name(prefix, &channel.name.to_string())); + names.filter(|name| keep(name)).collect() +} + +/// Checks every chunk of flat part `index` before the `exr` crate's image reader reads the part. +/// That reader reserves a chunk's declared packed length, up to the part's nominal block size, +/// before it reads the payload, so each chunk is checked as [`flat_chunk_at`] describes. The +/// reader picks the chunks it reads by their place in the offset table, which follows the +/// part's blocks in increasing y order, and reads only the blocks of the largest resolution +/// level, and none when the decode keeps no channel (`reads_any` false). The packed length of +/// each chunk the reader reads must also fit in [`Limits::max_bytes`]. +/// +/// The table has one entry per block (`header.chunk_count`). Every block of a scan-line part is +/// at the largest level. In a tiled part the largest level's tiles come first, so an entry is at +/// that level when its place is below that level's tile count. The check works from these counts +/// and does not list the blocks, so its memory does not grow with the size of the offset table. +fn check_flat_packed_lengths(bytes: &[u8], meta: &MetaData, index: usize, reads_any: bool, limits: &Limits) -> Result<()> { + let header = meta.headers.get(index).ok_or_else(|| malformed(format!("part {index}")))?; + let multipart = meta.requirements.is_multilayer(); + let (offsets, tables_end) = part_offset_table(bytes, meta, index)?; + let largest_level_blocks = match &header.blocks { + exr::meta::BlockDescription::Tiles(tiles) => { + let (tile_w, tile_h) = (tiles.tile_size.width(), tiles.tile_size.height()); + if tile_w == 0 || tile_h == 0 { + return Err(malformed("flat block has a zero dimension")); + } + header.layer_size.width().div_ceil(tile_w).saturating_mul(header.layer_size.height().div_ceil(tile_h)) + } + exr::meta::BlockDescription::ScanLines => header.chunk_count, + }; + let read_count = if reads_any { largest_level_blocks } else { 0 }; + for (place, &entry) in offsets.as_chunks::<8>().0.iter().enumerate() { + let (_, size) = flat_chunk_at(bytes, header, multipart, index, u64::from_le_bytes(entry), tables_end)?; + let read = place < read_count; + if read && size as u64 > limits.max_bytes { + return Err(Error::LimitExceeded("packed flat block exceeds the byte budget".into())); + } + } + Ok(()) +} + /// Reads the chunks of flat part `index` of a file that also holds deep parts into `reader`. /// /// The `exr` crate's image reader validates every header before it reads a chunk and refuses @@ -839,19 +944,7 @@ fn read_flat_part_chunks(bytes: &[u8], meta: &MetaData, index: usize, reader: &m for flat in meta.headers.iter().filter(|h| !h.deep) { flat.validate(multipart, &mut long_names, false).map_err(map_exr)?; } - let truncated = || malformed("the offset tables run past the end of the file"); - let (mut table, mut tables_end) = (0u64, tables_start(bytes)?); - for (i, h) in meta.headers.iter().enumerate() { - if i == index { - table = tables_end; - } - let len = u64::try_from(h.chunk_count).ok().and_then(|n| n.checked_mul(8)).ok_or_else(truncated)?; - tables_end = tables_end.checked_add(len).filter(|end| *end <= bytes.len() as u64).ok_or_else(truncated)?; - } - let offsets = usize::try_from(table) - .ok() - .and_then(|start| bytes.get(start..start.checked_add(header.chunk_count.checked_mul(8)?)?)) - .ok_or_else(truncated)?; + let (offsets, tables_end) = part_offset_table(bytes, meta, index)?; // One bit per block, not a Vec/HashSet of every coordinate. A cropped display must not // permit unbounded bookkeeping for an enormous data window of tiny tiles. let tracking_bytes = header.chunk_count.div_ceil(8); @@ -863,31 +956,7 @@ fn read_flat_part_chunks(bytes: &[u8], meta: &MetaData, index: usize, reader: &m seen.resize(tracking_bytes, 0u8); for &entry in offsets.as_chunks::<8>().0 { let offset = u64::from_le_bytes(entry); - let chunk = usize::try_from(offset) - .ok() - .filter(|_| offset >= tables_end) - .and_then(|start| bytes.get(start..)) - .filter(|rest| !rest.is_empty()) - .ok_or_else(|| malformed(format!("chunk offset {offset} is outside the chunk area of the file")))?; - if multipart { - let part = chunk.get(..4).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(i32::from_le_bytes); - let part = part.ok_or_else(|| malformed(format!("the chunk at offset {offset} is cut off")))?; - if usize::try_from(part).ok() != Some(index) { - return Err(malformed(format!("the chunk at offset {offset} belongs to part {part}, not part {index}"))); - } - } - // The crate allocates a chunk's declared payload before it reads it, so the payload must - // fit in the rest of the file. The length follows the part number and the block's y, or - // its four tile coordinates. - let fields = if matches!(header.blocks, exr::meta::BlockDescription::Tiles(_)) { 16 } else { 4 }; - let size_at = if multipart { 4 } else { 0 } + fields; - let size = chunk.get(size_at..size_at + 4).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(i32::from_le_bytes); - let size = size.ok_or_else(|| malformed(format!("the chunk at offset {offset} is cut off")))?; - let left = chunk.len() - (size_at + 4); - if usize::try_from(size).is_ok_and(|size| size > left) { - return Err(malformed(format!("the chunk at offset {offset} declares {size} bytes, but {left} remain in the file"))); - } - let size = usize::try_from(size).map_err(|_| malformed("negative packed chunk length"))?; + let (chunk, size) = flat_chunk_at(bytes, header, multipart, index, offset, tables_end)?; // Read coordinates without allocating the payload. Validate their real clipped block // and budgets before Chunk::read uses the nominal (possibly huge) tile dimensions. let coordinate_at = if multipart { 4 } else { 0 }; @@ -959,6 +1028,10 @@ pub fn decode_part(bytes: &[u8], index: usize, keep: &dyn Fn(&str) -> bool, limi return Err(Error::Unsupported("HTJ2K compression".into())); } let info = part_info(index, header); + let kept_names = kept_channel_names(header, None, keep); + let keeps_any = !kept_names.is_empty(); + let recorded = |name: &str| kept_names.contains(name); + let keep: &dyn Fn(&str) -> bool = &recorded; let select = Select { index, keep, seen: std::cell::Cell::new(0) }; let planes = if meta.headers.iter().any(|header| header.deep) { select.seen.set(index); @@ -966,6 +1039,7 @@ pub fn decode_part(bytes: &[u8], index: usize, keep: &dyn Fn(&str) -> bool, limi read_flat_part_chunks(bytes, &meta, index, &mut reader, limits)?; reader.into_channels() } else { + check_flat_packed_lengths(bytes, &meta, index, keeps_any, limits)?; let image = ReadImage::new(ReadAllLayers { read_channels: select }, |_| {}).from_buffered(Cursor::new(bytes)).map_err(map_exr)?; image.layer_data.into_iter().nth(index).map(|l| l.channel_data).ok_or_else(|| malformed("the part was not read"))? }; diff --git a/crates/exr/src/decode_tests.rs b/crates/exr/src/decode_tests.rs index 32fefa029f..3a20d7b7ef 100644 --- a/crates/exr/src/decode_tests.rs +++ b/crates/exr/src/decode_tests.rs @@ -179,6 +179,133 @@ fn decoded_display_part_rejects_kept_subsampled_channels() { assert!(matches!(decode_display_part(&bytes, 0, &|name| name == "R", &|_| 0.0, &Limits::default()), Err(Error::Unsupported(_)))); } +#[test] +fn a_flat_chunk_s_packed_length_is_checked_before_the_crate_reads_it() { + // One 9 × 7 tile of a 1024 × 1024 tile size: the crate would reserve up to the nominal tile + // (1024 × 1024 pixels of three f32 channels, 12 MiB) for the chunk's declared length. + let list = ["B", "G", "R"].iter().map(|n| AnyChannel::new(*n, FlatSamples::F32(ramp(63, 1.0)))).collect(); + let encoding = Encoding { + compression: exr::prelude::Compression::Uncompressed, + blocks: Blocks::Tiles(exr::math::Vec2(1024, 1024)), + line_order: LineOrder::Increasing, + }; + let mut bytes = file(vec![Layer::new((9, 7), LayerAttributes::default(), encoding, AnyChannels::sort(list))], (9, 7)); + assert_eq!(decode_part(&bytes, 0, &all, &Limits::default()).unwrap().channels.len(), 3); + let mut cursor = std::io::Cursor::new(&bytes[..]); + exr::meta::MetaData::read_from_buffered(&mut cursor, false).unwrap(); + let table = cursor.position() as usize; + let chunk = u64::from_le_bytes(bytes[table..table + 8].try_into().unwrap()) as usize; + // The packed length follows the four tile coordinates. + let size_at = chunk + 16; + bytes.extend_from_slice(&[0; 2000]); + let limits = Limits { max_bytes: 1000, ..Limits::default() }; + let r = |name: &str| name == "R"; + // More bytes than the file has left after the length. + bytes[size_at..size_at + 4].copy_from_slice(&i32::MAX.to_le_bytes()); + assert!(matches!(decode_part(&bytes, 0, &all, &limits), Err(Error::Malformed(m)) if m.contains("remain in the file"))); + assert!(matches!(decode_display_part(&bytes, 0, &r, &|_| 0.0, &limits), Err(Error::Malformed(m)) if m.contains("remain in the file"))); + // Inside the file, but over the byte budget. + bytes[size_at..size_at + 4].copy_from_slice(&1001i32.to_le_bytes()); + assert!(matches!(decode_part(&bytes, 0, &all, &limits), Err(Error::LimitExceeded(_)))); + assert!(matches!(decode_display_part(&bytes, 0, &r, &|_| 0.0, &limits), Err(Error::LimitExceeded(_)))); + // A decode that keeps no channel reads no chunk. + let none = |_: &str| false; + assert!(decode_part(&bytes, 0, &none, &limits).unwrap().channels.is_empty()); + assert!(decode_display_part(&bytes, 0, &none, &|_| 0.0, &limits).unwrap().channels.is_empty()); +} + +#[test] +fn a_skipped_flat_chunk_s_packed_length_is_not_held_to_the_budget() { + use exr::math::RoundingMode; + use exr::prelude::Levels; + // 9 × 7 in 4 × 4 tiles with mip levels. The reader reads only the six tiles of level 0, so a + // smaller level's chunk may declare more than the budget while it fits in the file. + let sizes: Vec = exr::meta::mip_map_levels(RoundingMode::Down, exr::math::Vec2(9, 7)).map(|(_, size)| size.area()).collect(); + let levels = Levels::Mip { rounding_mode: RoundingMode::Down, level_data: sizes.iter().map(|n| FlatSamples::F32(ramp(*n, 1.0))).collect() }; + let encoding = Encoding { + compression: exr::prelude::Compression::Uncompressed, + blocks: Blocks::Tiles(exr::math::Vec2(4, 4)), + line_order: LineOrder::Increasing, + }; + let channels = AnyChannels::sort(vec![AnyChannel::new("R", levels)].into()); + let layers = vec![Layer::new((9, 7), LayerAttributes::default(), encoding, channels)]; + let image = exr::image::Image::from_layers(ImageAttributes::new(IntegerBounds::new((0, 0), (9, 7))), layers); + let mut out = std::io::Cursor::new(Vec::new()); + image.write().to_buffered(&mut out).unwrap(); + let mut bytes = out.into_inner(); + let mut cursor = std::io::Cursor::new(&bytes[..]); + let meta = exr::meta::MetaData::read_from_buffered(&mut cursor, false).unwrap(); + let table = cursor.position() as usize; + let count = meta.headers[0].chunk_count; + assert!(count > 6, "the part has chunks beyond level 0"); + // The last chunk in the table holds the smallest level: its tile coordinates, then its level. + let last = table + (count - 1) * 8; + let chunk = u64::from_le_bytes(bytes[last..last + 8].try_into().unwrap()) as usize; + let level_x = i32::from_le_bytes(bytes[chunk + 8..chunk + 12].try_into().unwrap()); + let level_y = i32::from_le_bytes(bytes[chunk + 12..chunk + 16].try_into().unwrap()); + assert_ne!((level_x, level_y), (0, 0)); + bytes.extend_from_slice(&[0; 2000]); + bytes[chunk + 16..chunk + 20].copy_from_slice(&1500i32.to_le_bytes()); + let limits = Limits { max_bytes: 1000, ..Limits::default() }; + let r = |name: &str| name == "R"; + assert_eq!(decode_part(&bytes, 0, &all, &limits).unwrap().channels.len(), 1); + assert_eq!(decode_display_part(&bytes, 0, &r, &|_| 0.0, &limits).unwrap().channels.len(), 1); + // The reader picks chunks by their place in the table, so a level-0 entry that points at the + // smaller level's chunk is read, and that chunk's length is held to the budget. + let entry = bytes[last..last + 8].to_vec(); + bytes[table..table + 8].copy_from_slice(&entry); + assert!(matches!(decode_part(&bytes, 0, &all, &limits), Err(Error::LimitExceeded(_)))); + assert!(matches!(decode_display_part(&bytes, 0, &r, &|_| 0.0, &limits), Err(Error::LimitExceeded(_)))); +} + +#[test] +fn the_packed_length_check_finds_the_end_of_level_0_among_many_small_tiles() { + use exr::math::RoundingMode; + use exr::prelude::Levels; + // 64 × 48 in 1 × 1 tiles with mip levels: the 3,072 tiles of level 0 fill the first places of + // the offset table, and the smaller levels follow. + let (w, h) = (64, 48); + let sizes: Vec = exr::meta::mip_map_levels(RoundingMode::Down, exr::math::Vec2(w, h)).map(|(_, size)| size.area()).collect(); + let levels = Levels::Mip { rounding_mode: RoundingMode::Down, level_data: sizes.iter().map(|n| FlatSamples::F32(ramp(*n, 1.0))).collect() }; + let encoding = Encoding { + compression: exr::prelude::Compression::Uncompressed, + blocks: Blocks::Tiles(exr::math::Vec2(1, 1)), + line_order: LineOrder::Increasing, + }; + let channels = AnyChannels::sort(vec![AnyChannel::new("R", levels)].into()); + let layers = vec![Layer::new((w, h), LayerAttributes::default(), encoding, channels)]; + let image = exr::image::Image::from_layers(ImageAttributes::new(IntegerBounds::new((0, 0), (w, h))), layers); + let mut out = std::io::Cursor::new(Vec::new()); + image.write().to_buffered(&mut out).unwrap(); + let mut bytes = out.into_inner(); + let mut cursor = std::io::Cursor::new(&bytes[..]); + let meta = exr::meta::MetaData::read_from_buffered(&mut cursor, false).unwrap(); + let table = cursor.position() as usize; + let level_0 = w * h; + assert!(meta.headers[0].chunk_count > level_0, "the part has chunks beyond level 0"); + let chunk_at = |bytes: &[u8], place: usize| u64::from_le_bytes(bytes[table + place * 8..table + place * 8 + 8].try_into().unwrap()) as usize; + let level_of = |bytes: &[u8], chunk: usize| { + let x = i32::from_le_bytes(bytes[chunk + 8..chunk + 12].try_into().unwrap()); + let y = i32::from_le_bytes(bytes[chunk + 12..chunk + 16].try_into().unwrap()); + (x, y) + }; + let (last_read, first_skipped) = (chunk_at(&bytes, level_0 - 1), chunk_at(&bytes, level_0)); + assert_eq!(level_of(&bytes, last_read), (0, 0)); + assert_ne!(level_of(&bytes, first_skipped), (0, 0)); + // The decoded part takes 12,288 bytes, inside the budget; a declared length of 30,000 is not. + bytes.extend_from_slice(&[0; 40_000]); + let limits = Limits { max_bytes: 20_000, ..Limits::default() }; + let r = |name: &str| name == "R"; + // The first chunk past level 0 is not read, so its length is not held to the budget. + bytes[first_skipped + 16..first_skipped + 20].copy_from_slice(&30_000i32.to_le_bytes()); + assert_eq!(decode_part(&bytes, 0, &all, &limits).unwrap().channels.len(), 1); + assert_eq!(decode_display_part(&bytes, 0, &r, &|_| 0.0, &limits).unwrap().channels.len(), 1); + // The last chunk of level 0 is read, so its length is. + bytes[last_read + 16..last_read + 20].copy_from_slice(&30_000i32.to_le_bytes()); + assert!(matches!(decode_part(&bytes, 0, &all, &limits), Err(Error::LimitExceeded(_)))); + assert!(matches!(decode_display_part(&bytes, 0, &r, &|_| 0.0, &limits), Err(Error::LimitExceeded(_)))); +} + /// A 2x2 single-part file whose layer carries a 2x1 preview. fn with_preview() -> Vec { let mut attrs = LayerAttributes::named("rgb"); diff --git a/crates/font-manager/src/panel/browse/cards.rs b/crates/font-manager/src/panel/browse/cards.rs index 8f7042d3cd..d145fc6493 100644 --- a/crates/font-manager/src/panel/browse/cards.rs +++ b/crates/font-manager/src/panel/browse/cards.rs @@ -1,7 +1,7 @@ //! The family card and the collection of cards the panel lists. use craft_ui::buttons::{SplitButton, SplitOutput}; -use craft_ui::contract::{Entry, Props as _, Styled as _, clicked}; +use craft_ui::contract::{ActivateOn, Entry, Props as _, Styled as _, clicked}; use super::{ Access, Badge, Button, Collection, CollectionProps, CollectionResponse, Common, Component, ComponentStyle, ContainerProps, Cow, Cx, DisplayOrder, @@ -440,7 +440,7 @@ pub struct FamilyCardsStyle { metrics: Metrics, } -/// The family cards of one list: one Tab stop, Up and Down move the lead, Enter or a double click activates a card. +/// The family cards of one list: one Tab stop, Up and Down move the lead, Enter or a click activates a card. #[derive(craft_ui::contract::Component)] #[component(collection)] pub struct FamilyCards { @@ -457,7 +457,7 @@ impl FamilyCards { FamilyCards { common: Common::new(), props: ContainerProps::new().sizing(Sizing::Fill), - items: CollectionProps::new().select(SelectMode::Single), + items: CollectionProps::new().select(SelectMode::Single).activate(ActivateOn::Click), } .label(label) } diff --git a/crates/font-manager/tests/it/panel.rs b/crates/font-manager/tests/it/panel.rs index 8bc99c1c69..b321381712 100644 --- a/crates/font-manager/tests/it/panel.rs +++ b/crates/font-manager/tests/it/panel.rs @@ -193,11 +193,11 @@ impl Rig { self.panel.borrow().installed().iter().any(|f| f.name == family) } - /// Opens the details of the card named `family`: the card takes the focus, Enter opens it. + /// Opens the details of the card named `family` with a click. fn open(&mut self, family: &str) { let card = self.named(Role::LIST_ITEM, family); self.fx.click_at(Pos2::new(card.rect.left() + 4.0, card.rect.top() + 4.0)); - self.key(Key::Enter); + self.fx.settle(); assert_eq!(self.panel.borrow().details_family().as_deref(), Some(family)); } } @@ -335,6 +335,20 @@ fn each_family_keeps_its_system_fonts_choice_across_starts() { assert_eq!(again.store.calls().len(), 2); } +/// A single click on a card's name area opens its details; a click on its Install control does only its own thing. +#[trial] +fn a_single_click_on_a_card_opens_its_details() { + let mut rig = setup("card-click"); + rig.allow(); + rig.type_into("Search", "Hack"); + rig.click("Install"); + assert_eq!(rig.panel.borrow().details_family(), None, "a press on a card's control opens no details"); + let card = rig.named(Role::LIST_ITEM, "Hack"); + rig.fx.click_at(Pos2::new(card.rect.left() + 4.0, card.rect.top() + 4.0)); + rig.fx.settle(); + assert_eq!(rig.panel.borrow().details_family().as_deref(), Some("Hack")); +} + /// A card's Install menu installs for the choice picked, and the press on it opens no details. #[trial] fn a_cards_install_menu_chooses_where_the_fonts_go() { diff --git a/crates/image-codecs/src/codecs/png.rs b/crates/image-codecs/src/codecs/png.rs index 6523d56474..e68c9acefe 100644 --- a/crates/image-codecs/src/codecs/png.rs +++ b/crates/image-codecs/src/codecs/png.rs @@ -1390,12 +1390,12 @@ fn start( if opts.embed_icc && let Some(icc) = icc { - info.icc_profile = Some(icc.clone().into()); + info.icc_profile = Some(std::borrow::Cow::Borrowed(icc.as_slice())); } if opts.embed_metadata { if let Some(exif) = &meta.exif { // The pixels are written as they are shown: never let a viewer rotate them again. - info.exif_metadata = Some(crate::resolution::export_exif(exif, meta.dpi).into_owned().into()); + info.exif_metadata = Some(crate::resolution::export_exif(exif, meta.dpi)); } if let Some((x, y)) = meta.dpi && x > 0.0 diff --git a/crates/java-class/src/java_class.rs b/crates/java-class/src/java_class.rs index 4b751ec3ee..47fd0ef67a 100644 --- a/crates/java-class/src/java_class.rs +++ b/crates/java-class/src/java_class.rs @@ -11,6 +11,7 @@ use crate::bytes::Reader; use crate::java_ops::{self, Insn}; use crate::{FormatError, descriptor as dex}; use serde::Serialize; +use std::collections::HashMap; /// Most constant-pool entries, fields, methods, attributes or interfaces we read from one file. const MAX_ITEMS: usize = 1 << 20; @@ -18,6 +19,9 @@ const MAX_ITEMS: usize = 1 << 20; const MAX_ATTRS: usize = 64 * 1024; /// Deepest annotation/element-value nesting we walk. const MAX_ANNO_DEPTH: usize = 32; +/// Most bytes of constant-pool text copied into one parsed class. Many entries can name the same +/// long `Utf8`; once the limit is reached, further names are kept as pool-index placeholders. +pub(crate) const MAX_COPIED_TEXT: usize = 64 << 20; /// One constant-pool entry. Index 0 and the slot after a `Long`/`Double` are `Unusable`. #[derive(Debug, Clone, PartialEq)] @@ -347,6 +351,76 @@ fn utf8_of(pool: &[Const], idx: u16) -> &str { } } +/// Copies constant-pool text into the parse result within `MAX_COPIED_TEXT` bytes in total. +pub(crate) struct Names<'p> { + pool: &'p [Const], + left: usize, + exhausted: bool, + /// The length of each text `keep` has built, by kind and pool index. + built: HashMap<(&'static str, u16), usize>, +} + +impl<'p> Names<'p> { + pub(crate) fn new(pool: &'p [Const]) -> Self { + Names { pool, left: MAX_COPIED_TEXT, exhausted: false, built: HashMap::new() } + } + + /// Charge `len` bytes; false once the budget cannot cover them. + fn admit(&mut self, len: usize) -> bool { + match self.left.checked_sub(len) { + Some(left) => { + self.left = left; + true + } + None => { + self.exhausted = true; + false + } + } + } + + /// `render(pool, idx)` when the budget covers it, otherwise the placeholder ``. + /// The length of each rendered text is kept by kind and index, so a text over the budget is + /// built at most once however many entries name it. + pub(crate) fn keep(&mut self, kind: &'static str, idx: u16, render: fn(&[Const], u16) -> String) -> String { + self.keep_as((kind, idx), kind, idx, render) + } + + /// Like `keep` for a loadable constant. Constants that copy the same Utf8 the same way share + /// one kept length, so many `String` entries over one long Utf8 build its text at most once + /// past the budget. + pub(crate) fn constant(&mut self, idx: u16, render: fn(&[Const], u16) -> String) -> String { + let key = const_text_key(self.pool, idx); + self.keep_as(key, "const", idx, render) + } + + fn keep_as(&mut self, key: (&'static str, u16), kind: &'static str, idx: u16, render: fn(&[Const], u16) -> String) -> String { + if let Some(&len) = self.built.get(&key) { + return if self.admit(len) { render(self.pool, idx) } else { format!("<{kind}#{idx}>") }; + } + let text = render(self.pool, idx); + self.built.insert(key, text.len()); + if self.admit(text.len()) { text } else { format!("<{kind}#{idx}>") } + } + + /// The Utf8 at `idx` (empty when it is not a Utf8), or `` once the budget is spent. + fn utf8(&mut self, idx: u16) -> String { + let text = utf8_of(self.pool, idx); + if self.admit(text.len()) { text.to_string() } else { format!("") } + } + + /// Like `class_name_at`, or `` once the budget is spent. + fn class(&mut self, idx: u16) -> String { + match self.pool.get(idx as usize) { + Some(Const::Class(name_idx)) => { + let text = utf8_of(self.pool, *name_idx); + if self.admit(text.len()) { text.to_string() } else { format!("") } + } + _ => format!(""), + } + } +} + /// Parse a class file. pub fn parse(data: &[u8]) -> Result { if !data.starts_with(&[0xca, 0xfe, 0xba, 0xbe]) { @@ -369,8 +443,9 @@ pub fn parse(data: &[u8]) -> Result { let access = c.u16().ok_or_else(|| FormatError::Truncated("access flags".into()))?; let this_idx = c.u16().ok_or_else(|| FormatError::Truncated("this_class".into()))?; let super_idx = c.u16().ok_or_else(|| FormatError::Truncated("super_class".into()))?; - let this_class = class_name_at(&pool, this_idx); - let super_class = if super_idx == 0 { None } else { Some(class_name_at(&pool, super_idx)) }; + let mut names = Names::new(&pool); + let this_class = names.class(this_idx); + let super_class = if super_idx == 0 { None } else { Some(names.class(super_idx)) }; // Interfaces let n_iface = c.u16().ok_or_else(|| FormatError::Truncated("interfaces count".into()))? as usize; let mut interfaces = Vec::new(); @@ -379,12 +454,12 @@ pub fn parse(data: &[u8]) -> Result { warnings.push("interface list ended early".into()); break; }; - interfaces.push(class_name_at(&pool, i)); + interfaces.push(names.class(i)); } // Fields - let fields = parse_members(&mut c, &pool, &mut warnings, "field")?; + let fields = parse_members(&mut c, &mut names, &mut warnings, "field")?; // Methods - let methods = parse_members(&mut c, &pool, &mut warnings, "method")?; + let methods = parse_members(&mut c, &mut names, &mut warnings, "method")?; // Class attributes let (attrs, complete) = read_attrs(&mut c, &pool); if !complete { @@ -399,24 +474,27 @@ pub fn parse(data: &[u8]) -> Result { match a.name { "SourceFile" => { if let Some(i) = Reader::new(a.info).u16_be(0) { - source_file = Some(utf8_of(&pool, i).to_string()); + source_file = Some(names.utf8(i)); } } "Signature" => { if let Some(i) = Reader::new(a.info).u16_be(0) { - signature = Some(utf8_of(&pool, i).to_string()); + signature = Some(names.utf8(i)); } } "BootstrapMethods" => match bootstrap_table(a.info) { Some(table) => bootstrap_methods = table, None => warnings.push("invalid BootstrapMethods table".into()), }, - "InnerClasses" => inner_classes = parse_inner_classes(a.info, &pool), - "RuntimeVisibleAnnotations" => annotations.extend(parse_annotation_types(a.info, &pool, "runtime")), - "RuntimeInvisibleAnnotations" => annotations.extend(parse_annotation_types(a.info, &pool, "class")), + "InnerClasses" => inner_classes = parse_inner_classes(a.info, &mut names), + "RuntimeVisibleAnnotations" => annotations.extend(parse_annotation_types(a.info, &mut names, "runtime")), + "RuntimeInvisibleAnnotations" => annotations.extend(parse_annotation_types(a.info, &mut names, "class")), _ => {} } } + if names.exhausted { + warnings.push(format!("names exceed {} MiB of copied text; later ones are shown as pool indices", MAX_COPIED_TEXT >> 20)); + } Ok(ClassFile { version, access, @@ -518,7 +596,8 @@ fn bootstrap_table(data: &[u8]) -> Option)>> { (cursor.pos == data.len()).then_some(table) } -fn parse_members(c: &mut Cursor<'_>, pool: &[Const], warnings: &mut Vec, what: &str) -> Result, FormatError> { +fn parse_members(c: &mut Cursor<'_>, names: &mut Names<'_>, warnings: &mut Vec, what: &str) -> Result, FormatError> { + let pool = names.pool; let n = c.u16().ok_or_else(|| FormatError::Truncated(format!("{what} count")))? as usize; let mut out = Vec::new(); for _ in 0..n.min(MAX_ITEMS) { @@ -526,21 +605,20 @@ fn parse_members(c: &mut Cursor<'_>, pool: &[Const], warnings: &mut Vec, warnings.push(format!("{what} table ended early")); break; }; - let mut m = - Member { access, name: utf8_of(pool, name_idx).to_string(), descriptor: utf8_of(pool, desc_idx).to_string(), ..Default::default() }; + let mut m = Member { access, name: names.utf8(name_idx), descriptor: names.utf8(desc_idx), ..Default::default() }; let (attrs, _) = read_attrs(c, pool); for a in attrs { match a.name { - "Code" => m.code = parse_code(a.info, pool), + "Code" => m.code = parse_code(a.info, names), "ConstantValue" => { if let Some(i) = Reader::new(a.info).u16_be(0) { - m.constant_value = Some(const_display(pool, i)); + m.constant_value = Some(names.constant(i, const_display)); } } - "Exceptions" => m.exceptions = parse_exceptions_attr(a.info, pool), + "Exceptions" => m.exceptions = parse_exceptions_attr(a.info, names), "Signature" => { if let Some(i) = Reader::new(a.info).u16_be(0) { - m.signature = Some(utf8_of(pool, i).to_string()); + m.signature = Some(names.utf8(i)); } } "Deprecated" => m.deprecated = true, @@ -553,7 +631,8 @@ fn parse_members(c: &mut Cursor<'_>, pool: &[Const], warnings: &mut Vec, Ok(out) } -fn parse_code(info: &[u8], pool: &[Const]) -> Option { +fn parse_code(info: &[u8], names: &mut Names<'_>) -> Option { + let pool = names.pool; let mut c = Cursor::new(info); let max_stack = c.u16()?; let max_locals = c.u16()?; @@ -563,7 +642,7 @@ fn parse_code(info: &[u8], pool: &[Const]) -> Option { let mut exceptions = Vec::new(); for _ in 0..n_exc.min(MAX_ITEMS) { let (Some(start_pc), Some(end_pc), Some(handler_pc), Some(catch)) = (c.u16(), c.u16(), c.u16(), c.u16()) else { break }; - exceptions.push(ExceptionEntry { start_pc, end_pc, handler_pc, catch_type: (catch != 0).then(|| class_name_at(pool, catch)) }); + exceptions.push(ExceptionEntry { start_pc, end_pc, handler_pc, catch_type: (catch != 0).then(|| names.class(catch)) }); } let mut line_numbers = Vec::new(); let (attrs, _) = read_attrs(&mut c, pool); @@ -580,27 +659,27 @@ fn parse_code(info: &[u8], pool: &[Const]) -> Option { Some(Code { max_stack, max_locals, bytecode, exceptions, line_numbers }) } -fn parse_exceptions_attr(info: &[u8], pool: &[Const]) -> Vec { +fn parse_exceptions_attr(info: &[u8], names: &mut Names<'_>) -> Vec { let mut c = Cursor::new(info); let n = c.u16().unwrap_or(0) as usize; let mut out = Vec::new(); for _ in 0..n.min(MAX_ITEMS) { let Some(i) = c.u16() else { break }; - out.push(class_name_at(pool, i)); + out.push(names.class(i)); } out } -fn parse_inner_classes(info: &[u8], pool: &[Const]) -> Vec { +fn parse_inner_classes(info: &[u8], names: &mut Names<'_>) -> Vec { let mut c = Cursor::new(info); let n = c.u16().unwrap_or(0) as usize; let mut out = Vec::new(); for _ in 0..n.min(MAX_ITEMS) { let (Some(inner), Some(outer), Some(name), Some(access)) = (c.u16(), c.u16(), c.u16(), c.u16()) else { break }; out.push(InnerClass { - inner: (inner != 0).then(|| class_name_at(pool, inner)), - outer: (outer != 0).then(|| class_name_at(pool, outer)), - name: (name != 0).then(|| utf8_of(pool, name).to_string()), + inner: (inner != 0).then(|| names.class(inner)), + outer: (outer != 0).then(|| names.class(outer)), + name: (name != 0).then(|| names.utf8(name)), access, }); } @@ -608,32 +687,35 @@ fn parse_inner_classes(info: &[u8], pool: &[Const]) -> Vec { } /// Extract annotation type names (dotted) from a `Runtime*Annotations` attribute, best-effort. -fn parse_annotation_types(info: &[u8], pool: &[Const], visibility: &str) -> Vec { +fn parse_annotation_types(info: &[u8], names: &mut Names<'_>, visibility: &str) -> Vec { let mut c = Cursor::new(info); let n = c.u16().unwrap_or(0) as usize; let mut out = Vec::new(); for _ in 0..n.min(MAX_ITEMS) { - match read_annotation(&mut c, pool, 0) { - Some(t) => out.push(format!("{t} ({visibility})")), + match read_annotation(&mut c, names.pool, 0) { + Some(idx) => { + let t = names.keep("utf8", idx, |pool, idx| field_type(utf8_of(pool, idx))); + out.push(format!("{t} ({visibility})")); + } None => break, } } out } -/// Read one `annotation` structure, returning its (dotted) type name; advances past its values. -fn read_annotation(c: &mut Cursor<'_>, pool: &[Const], depth: usize) -> Option { +/// Read one `annotation` structure, returning the pool index of its type descriptor; advances past +/// its values. +fn read_annotation(c: &mut Cursor<'_>, pool: &[Const], depth: usize) -> Option { if depth > MAX_ANNO_DEPTH { return None; } let type_idx = c.u16()?; let n_pairs = c.u16()? as usize; - let type_name = field_type(utf8_of(pool, type_idx)); for _ in 0..n_pairs.min(MAX_ITEMS) { let _name_idx = c.u16()?; skip_element_value(c, pool, depth + 1)?; } - Some(type_name) + Some(type_idx) } fn skip_element_value(c: &mut Cursor<'_>, pool: &[Const], depth: usize) -> Option<()> { @@ -686,6 +768,17 @@ fn const_display(pool: &[Const], idx: u16) -> String { } } +/// The key under which `Names` keeps the length of `const_display(pool, idx)`: the Utf8 a +/// `String`, `Class` or `MethodType` constant copies, otherwise the constant itself. +fn const_text_key(pool: &[Const], idx: u16) -> (&'static str, u16) { + match pool.get(idx as usize) { + Some(Const::String(s)) => ("const-string", *s), + Some(Const::Class(n)) => ("const-class", *n), + Some(Const::MethodType(d)) => ("const-method-type", *d), + _ => ("const", idx), + } +} + // --------------------------------------------------------------------------------------------- // Resolution and formatting on a parsed class diff --git a/crates/java-class/src/lib.rs b/crates/java-class/src/lib.rs index 4d135e16b2..7e54dd258f 100644 --- a/crates/java-class/src/lib.rs +++ b/crates/java-class/src/lib.rs @@ -33,6 +33,10 @@ mod java_attribute_names; #[path = "regressions/java_constant_pool_slots.rs"] mod java_constant_pool_slots; +#[cfg(test)] +#[path = "regressions/java_copied_names.rs"] +mod java_copied_names; + #[cfg(test)] #[path = "regressions/java_invoke_operands.rs"] mod java_invoke_operands; diff --git a/crates/java-class/src/regressions/java_copied_names.rs b/crates/java-class/src/regressions/java_copied_names.rs new file mode 100644 index 0000000000..2279807c17 --- /dev/null +++ b/crates/java-class/src/regressions/java_copied_names.rs @@ -0,0 +1,248 @@ +use crate::java_class::{self, ClassFile, Const, MAX_COPIED_TEXT, Names}; +use std::cell::Cell; + +const BIG: usize = u16::MAX as usize; +// Each repeat names the 65,535-byte Utf8 at least once, so 1,100 repeats exceed the limit. +const REPEATS: u16 = 1100; + +#[derive(Clone, Copy, Debug)] +enum Scope { + Interfaces, + Fields, + Methods, + Throws, + Catches, + InnerClasses, + Constants, +} + +fn u16b(out: &mut Vec, n: u16) { + out.extend_from_slice(&n.to_be_bytes()); +} + +fn utf8(out: &mut Vec, text: &str) { + out.push(1); + u16b(out, text.len() as u16); + out.extend_from_slice(text.as_bytes()); +} + +fn attr(out: &mut Vec, name: u16, info: &[u8]) { + u16b(out, name); + out.extend_from_slice(&(info.len() as u32).to_be_bytes()); + out.extend_from_slice(info); +} + +// Every repeated entry names pool entry 1 (a 65,535-byte Utf8) directly or through the +// `Class` at entry 2 or the `String` at entry 11. The file stays well under 100 KiB. +fn fixture(scope: Scope) -> Vec { + let mut out = vec![0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 52]; + u16b(&mut out, 12); + utf8(&mut out, &"A".repeat(BIG)); // 1 + out.extend_from_slice(&[7, 0, 1]); // 2 + utf8(&mut out, "java/lang/Object"); // 3 + out.extend_from_slice(&[7, 0, 3]); // 4 + utf8(&mut out, "Sample"); // 5 + out.extend_from_slice(&[7, 0, 5]); // 6 + for text in ["Exceptions", "InnerClasses", "Code", "ConstantValue"] { + utf8(&mut out, text); // 7..10 + } + out.extend_from_slice(&[8, 0, 1]); // 11 + for word in [0x0021, 6, 4] { + u16b(&mut out, word); + } + // Interfaces + if matches!(scope, Scope::Interfaces) { + u16b(&mut out, REPEATS); + for _ in 0..REPEATS { + u16b(&mut out, 2); + } + } else { + u16b(&mut out, 0); + } + // Fields and methods named and described by entry 1. + for table in [Scope::Fields, Scope::Methods] { + if std::mem::discriminant(&scope) == std::mem::discriminant(&table) { + u16b(&mut out, REPEATS); + for _ in 0..REPEATS { + for word in [0, 1, 1, 0] { + u16b(&mut out, word); + } + } + } else if matches!((scope, table), (Scope::Constants, Scope::Fields)) { + // Fields named `Sample` whose `ConstantValue` is the string at entry 11. + u16b(&mut out, REPEATS); + for _ in 0..REPEATS { + for word in [0x0018, 5, 5, 1] { + u16b(&mut out, word); + } + attr(&mut out, 10, &[0, 11]); + } + } else if matches!((scope, table), (Scope::Throws | Scope::Catches, Scope::Methods)) { + u16b(&mut out, 1); + for word in [0x0009, 5, 5, 1] { + u16b(&mut out, word); + } + let mut info = Vec::new(); + if matches!(scope, Scope::Throws) { + u16b(&mut info, REPEATS); + for _ in 0..REPEATS { + u16b(&mut info, 2); + } + attr(&mut out, 7, &info); + } else { + info.extend_from_slice(&[0, 0, 0, 0, 0, 0, 0, 1, 0xb1]); + u16b(&mut info, REPEATS); + for _ in 0..REPEATS { + for word in [0, 1, 0, 2] { + u16b(&mut info, word); + } + } + u16b(&mut info, 0); + attr(&mut out, 9, &info); + } + } else { + u16b(&mut out, 0); + } + } + // Class attributes + if matches!(scope, Scope::InnerClasses) { + u16b(&mut out, 1); + let mut info = Vec::new(); + u16b(&mut info, REPEATS); + for _ in 0..REPEATS { + for word in [2, 0, 1, 0] { + u16b(&mut info, word); + } + } + attr(&mut out, 8, &info); + } else { + u16b(&mut out, 0); + } + out +} + +/// The copied names of one scope's repeated entries. +fn names(parsed: &ClassFile, scope: Scope) -> Vec<&str> { + let mut out = Vec::new(); + match scope { + Scope::Interfaces => out.extend(parsed.interfaces.iter().map(String::as_str)), + Scope::Fields | Scope::Methods => { + let members = if matches!(scope, Scope::Fields) { &parsed.fields } else { &parsed.methods }; + for m in members { + out.extend([m.name.as_str(), m.descriptor.as_str()]); + } + } + Scope::Throws => out.extend(parsed.methods.iter().flat_map(|m| m.exceptions.iter().map(String::as_str))), + Scope::Catches => { + let codes = parsed.methods.iter().filter_map(|m| m.code.as_ref()); + out.extend(codes.flat_map(|c| c.exceptions.iter().filter_map(|e| e.catch_type.as_deref()))); + } + Scope::InnerClasses => { + for row in &parsed.inner_classes { + out.extend(row.inner.as_deref()); + out.extend(row.name.as_deref()); + } + } + Scope::Constants => out.extend(parsed.fields.iter().filter_map(|m| m.constant_value.as_deref())), + } + out +} + +fn check(scope: Scope) { + let bytes = fixture(scope); + assert!(bytes.len() < 100_000, "{scope:?}: {}", bytes.len()); + let parsed = java_class::parse(&bytes).unwrap(); + let names = names(&parsed, scope); + let per_entry = if matches!(scope, Scope::Fields | Scope::Methods | Scope::InnerClasses) { 2 } else { 1 }; + // Every entry is still listed; the budget replaces names, not rows. + assert_eq!(names.len(), usize::from(REPEATS) * per_entry, "{scope:?}"); + // A string constant is shown quoted, two bytes longer than its Utf8. + let full: Vec = names.iter().map(|n| n.len()).filter(|&n| n >= BIG).collect(); + assert!(!full.is_empty(), "{scope:?}: the first names are copied in full"); + let copied: usize = full.iter().sum(); + assert!(copied <= MAX_COPIED_TEXT, "{scope:?}: {copied} bytes of names copied"); + assert!(names.iter().any(|n| n.starts_with('<') && n.ends_with('>')), "{scope:?}: names past the budget are placeholders"); + assert!(parsed.warnings.iter().any(|w| w.contains("pool indices")), "{scope:?}: {:?}", parsed.warnings); + assert_eq!(parsed.this_class, "Sample"); + assert_eq!(parsed.super_class.as_deref(), Some("java/lang/Object")); +} + +#[test] +fn repeated_interface_names_stay_within_the_copy_budget() { + check(Scope::Interfaces); +} + +#[test] +fn repeated_field_names_stay_within_the_copy_budget() { + check(Scope::Fields); +} + +#[test] +fn repeated_method_names_stay_within_the_copy_budget() { + check(Scope::Methods); +} + +#[test] +fn repeated_thrown_type_names_stay_within_the_copy_budget() { + check(Scope::Throws); +} + +#[test] +fn repeated_caught_type_names_stay_within_the_copy_budget() { + check(Scope::Catches); +} + +#[test] +fn repeated_inner_class_names_stay_within_the_copy_budget() { + check(Scope::InnerClasses); +} + +#[test] +fn repeated_constant_values_stay_within_the_copy_budget() { + check(Scope::Constants); +} + +thread_local! { + static RENDERS: Cell = const { Cell::new(0) }; +} + +fn counted_render(pool: &[Const], idx: u16) -> String { + RENDERS.with(|n| n.set(n.get() + 1)); + match pool.get(usize::from(idx)) { + Some(Const::Utf8(s)) => format!("{s:?}"), + Some(Const::String(s)) => match pool.get(usize::from(*s)) { + Some(Const::Utf8(text)) => format!("{text:?}"), + _ => String::new(), + }, + _ => String::new(), + } +} + +#[test] +fn text_over_the_budget_is_rendered_once() { + let pool = vec![Const::Unusable, Const::Utf8("A".repeat(BIG))]; + let mut names = Names::new(&pool); + RENDERS.with(|n| n.set(0)); + let kept: Vec = (0..2 * MAX_COPIED_TEXT / BIG).map(|_| names.keep("const", 1, counted_render)).collect(); + let copied = kept.iter().filter(|t| t.len() == BIG + 2).count(); + assert!(copied >= 1 && copied < kept.len(), "{copied} of {} copied", kept.len()); + assert_eq!(kept.last().map(String::as_str), Some("")); + // Only the copied texts are rendered; the refusals reuse the length kept from the first one. + assert_eq!(RENDERS.with(Cell::get), copied); +} + +#[test] +fn string_constants_over_one_utf8_are_rendered_once_past_the_budget() { + let entries = 2 * MAX_COPIED_TEXT / BIG; + let mut pool = vec![Const::Unusable, Const::Utf8("A".repeat(BIG))]; + pool.extend((0..entries).map(|_| Const::String(1))); + let mut names = Names::new(&pool); + RENDERS.with(|n| n.set(0)); + let kept: Vec = (2..pool.len()).map(|i| names.constant(i as u16, counted_render)).collect(); + let copied = kept.iter().filter(|t| t.len() == BIG + 2).count(); + assert!(copied >= 1 && copied < kept.len(), "{copied} of {} copied", kept.len()); + assert_eq!(kept.last().map(String::as_str), Some(format!("", pool.len() - 1).as_str())); + // Each `String` entry is its own pool index, but all of them quote entry 1, so the refusals + // reuse the length kept for entry 1 instead of building the text again. + assert_eq!(RENDERS.with(Cell::get), copied); +} diff --git a/crates/media/src/ogg/tests.rs b/crates/media/src/ogg/tests.rs index 79d4a68be7..2b03f4c65f 100644 --- a/crates/media/src/ogg/tests.rs +++ b/crates/media/src/ogg/tests.rs @@ -24,6 +24,19 @@ fn recovery_charges_only_bytes_read_again() { assert_eq!(find_capture(&b"junk, no pattern".to_vec(), 0, 16, &mut r).unwrap(), Capture::End); } +/// A source that counts the bytes read from it. +struct Counted(Vec, std::cell::Cell); + +impl ByteSource for Counted { + fn len(&self) -> u64 { + self.0.len() as u64 + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + self.1.set(self.1.get() + buf.len() as u64); + self.0.read_at(offset, buf) + } +} + /// Write one page holding `segments` (lacing already computed by `lace`). fn page(out: &mut Vec, flags: u8, granule: i64, serial: u32, seq: u32, lacing: &[u8], body: &[u8]) { let start = out.len(); @@ -129,6 +142,22 @@ fn packets_spanning_pages() { assert_eq!(t.total, 1920); } +/// Opus header pages for `serial` (with the beginning-of-stream flag), then data pages of one +/// 960-sample packet of `pk_len` bytes each; sequence numbers continue from the header pages. +fn opus_pages(f: &mut Vec, serial: u32, npk: usize, pk_len: usize, eos: bool) { + let head = opus_head(0); + let (l, b) = lace(&[&head], false); + page(f, 0x02, 0, serial, 0, &l, &b); + let (l, b) = lace(&[b"OpusTags\x00\x00\x00\x00\x00\x00\x00\x00"], false); + page(f, 0, 0, serial, 1, &l, &b); + for i in 0..npk { + let p = pkt(i, pk_len); + let (l, b) = lace(&[&p], false); + let last = eos && i + 1 == npk; + page(f, if last { 0x04 } else { 0 }, (i as i64 + 1) * 960, serial, i as u32 + 2, &l, &b); + } +} + fn page_starts(f: &[u8]) -> Vec { f.windows(4).enumerate().filter(|(_, w)| *w == b"OggS").map(|(i, _)| i).collect() } diff --git a/crates/mesh/Cargo.toml b/crates/mesh/Cargo.toml index 17519cb07e..6a0d7d0294 100644 --- a/crates/mesh/Cargo.toml +++ b/crates/mesh/Cargo.toml @@ -15,14 +15,15 @@ default = ["stl", "obj", "ply", "gltf", "fbx", "threemf"] stl = [] obj = [] ply = [] -gltf = ["dep:serde_json"] +gltf = [] fbx = ["dep:miniz_oxide", "dep:craft-zip"] threemf = ["dep:craft-opc", "dep:craft-xml"] dae = ["dep:craft-xml"] abc = [] [dependencies] -serde_json = { workspace = true, optional = true } +# glTF reading and writing, and the `extensions` and `extras` values in the model. +serde_json = { workspace = true } # zlib-compressed arrays in binary FBX. miniz_oxide = { version = "0.9", optional = true } craft-zip = { workspace = true, optional = true } diff --git a/crates/mesh/README.md b/crates/mesh/README.md index 5d77168fc4..614cf85509 100644 --- a/crates/mesh/README.md +++ b/crates/mesh/README.md @@ -8,7 +8,7 @@ a `Scene` into bytes. One Cargo feature per format, all on by default. | `stl` | STL, binary and ASCII | yes | binary and ASCII | none | | `obj` | Wavefront OBJ with MTL | yes | OBJ and MTL | none | | `ply` | PLY, ASCII and both binary byte orders | yes | no (no app writes PLY) | none | -| `gltf` | glTF 2.0 (`.gltf`) and GLB | yes | GLB | `serde_json` | +| `gltf` | glTF 2.0 (`.gltf`) and GLB | yes | GLB | `serde_json` (a dependency with every feature) | | `threemf` | 3MF, core and materials extension | yes | no | `craft-opc`, `craft-xml` | | `fbx` | FBX 6.x and 7.x, binary and ASCII | yes | no | `miniz_oxide` | | `dae` | COLLADA (`.dae`), scenes, transforms, cameras | yes | no | `craft-xml` | @@ -22,7 +22,11 @@ USD is not here yet. `lights`, plus `external` (every other file the file names) and `warnings` (what was left out or repaired). - `Mesh`: a name, attribute pools (`positions` and `normals` as `f64`, `uv_sets`, per-position - `colors`, `joints` and `weights`) and `parts`. + `colors`, `joints` and `weights`) and `parts`, and glTF morph targets (`morph_targets`, each a + name and position, normal and tangent offsets, with their default `morph_weights`). +- glTF's `extensions` and `extras` of the file, nodes, meshes and materials are kept on + `Scene`, `Node`, `Mesh` and `Material` as `serde_json` values (re-exported as + `craft_mesh::serde_json`), whole, the ones the reader also reads into the model included. - `Part`: the faces of a mesh that share a group name, a material and a smoothing group. A face is a polygon of three or more `Corner`s; each corner indexes a position and optionally a normal and a UV. Formats with separate indices (OBJ) are kept exactly, and polygons stay whole. @@ -84,11 +88,26 @@ texture slots, UV set, sampler wrap modes and `KHR_texture_transform`, `KHR_mate `KHR_materials_unlit`, `KHR_materials_pbrSpecularGlossiness` (diffuse colour and texture, no metal, roughness from the glossiness); textures whose image is in `EXT_texture_webp`; images embedded in a buffer view or a `data:` URI, or named; skins; translation, rotation and scale animations; -cameras; `KHR_lights_punctual`. Primitives of a mesh that name the same accessors share their -vertices. `write_glb` writes nodes, meshes (positions, normals, UV sets, colours), materials with -their texture transforms and sampler wrap modes, and images; `write_glb_with_options` also writes -each sampler's `magFilter` and `minFilter` when its `GlbWriteOptions` set them. The other -formats' writers do not write texture transforms. +cameras; `KHR_lights_punctual`; morph targets (POSITION, NORMAL and TANGENT offsets, dense or +sparse, with the mesh's default `weights`, a node's own `weights` and names from +`extras.targetNames`). Primitives of a mesh that name the same accessors and morph targets share +their vertices. `write_glb` writes nodes, meshes (positions, normals, UV sets, colours, joints and +weights), skins with their inverse bind matrices, morph targets (POSITION and NORMAL offsets, the +mesh's and each node's `weights`, names in `extras.targetNames`; a target that moves fewer than +three quarters of the vertices as a sparse accessor), materials with their texture transforms and +sampler wrap modes, and images (with their `mimeType` when it is known); `write_glb_with_options` +also writes each sampler's `magFilter` and `minFilter` when its `GlbWriteOptions` set them. Parts +whose corners all have normals or UVs and parts whose corners do not are written as primitives over +separate vertices. The kept `extensions` and `extras` are written as +kept, except that the material extensions the reader reads into `Material` are written from its +fields and `KHR_lights_punctual` is not written; `extensionsUsed` lists every extension in the +file. The reader does not keep `extensionsRequired`; the writer requires only `EXT_texture_webp`, +which it uses for every texture of a WebP image. The file's textures (`texture_variants`) keep their indices, and so do nodes, materials and +skins, so kept extension data (a VRM file's, for example) still names the same things. Meshes +without triangles and images without bytes or a URI are left out, and later meshes and images +then move up; so do the textures after one the reader leaves out for want of an image, which it +names in a warning. Accessor and buffer view indices in kept extension data are not rewritten. The +other formats' writers do not write texture transforms. **3MF.** The package is opened with `craft-opc` and the model part found through its `3dmodel` relationship; `threemf::read_model_part` reads a model part's XML on its own. Mesh objects, @@ -115,10 +134,12 @@ FBX 6.x files (a `Model` holds its mesh, `Properties60`, objects connected by na geometry, transforms, the hierarchy and materials. Not read: FBX 5 and older, 6.x textures, animation, skin deformers, blend shapes, cameras, lights, NURBS. -Not read (glTF): required geometry extensions (Draco, meshopt) are `Error::Unsupported`. Points, -lines and morph targets are left out and counted in a warning; scenes other than the default are -named in one; other extensions are passed over. -Not written: skins, animations, cameras, lights, and `.gltf` with separate files. +Not read (glTF): required geometry extensions (Draco, meshopt) are `Error::Unsupported`. Points +and lines are left out and counted in a warning, as are the morph targets of a mesh with more than +`max_morph_targets`; scenes other than the default are named in one; animations of morph target +weights are passed over. +Not written: animations, cameras, lights, tangents (and so the tangent offsets of morph targets), +and `.gltf` with separate files. ## Hostile input @@ -137,8 +158,9 @@ mutations of every byte of good files. | `max_materials` | 100 000 | materials; images; OBJ material libraries; 3MF base materials and textures together | | `max_nodes` | 100 000 | nodes, and node visits when the hierarchy is walked (ends cycles); 3MF placed objects, build items and components | | `max_depth` | 64 | node nesting; 3MF component nesting (ends cycles) | -| `max_data_bytes` | 1 GiB | buffers and material libraries taken from the resolver; embedded image bytes; skin and animation values; the binary chunk `write_glb` builds; what a 3MF package inflates to, and its textures; an FBX file's meshes, image bytes and parsed values (binary: 8 bytes per array element, and other values are not counted; ASCII: `size_of::()` per value, each array element included, plus string bytes; record names and the overhead of records and their containers are not counted) | +| `max_data_bytes` | 1 GiB | buffers and material libraries taken from the resolver; embedded image bytes (in buffer views and `data:` URIs); skin and animation values; morph targets and their offsets (8 bytes per value); the binary chunk `write_glb` builds; what a 3MF package inflates to, and its textures; an FBX file's meshes, image bytes and parsed values (binary: 8 bytes per array element, and other values are not counted; ASCII: `size_of::()` per value, each array element included, plus string bytes; record names and the overhead of records and their containers are not counted) | | `max_extras` | 10 000 | skins, animations, cameras, lights, buffers (each); channels of one animation | +| `max_morph_targets` | 256 | morph targets of one glTF mesh; a mesh with more is read in its base shape with a warning, not refused | Fixed bounds: a PLY header of 1 MiB, 64 elements and 256 properties per element; 2^24 components for glTF accessors without a buffer view, over the whole file; 10 000 parts in a 3MF package; FBX diff --git a/crates/mesh/src/gltf.rs b/crates/mesh/src/gltf.rs index d43af5e999..984e1e6e9a 100644 --- a/crates/mesh/src/gltf.rs +++ b/crates/mesh/src/gltf.rs @@ -12,12 +12,26 @@ //! in a buffer view or a `data:` URI, or named), skins, animations of translation, rotation //! and scale, cameras and `KHR_lights_punctual` lights. A glTF mesh becomes one [`Mesh`] whose //! pools hold its primitives' vertices one after another (once for primitives that name the -//! same accessors), and each primitive a [`Part`]. +//! same accessors and morph targets), and each primitive a [`Part`]. +//! +//! Morph targets: each target's POSITION, NORMAL and TANGENT offsets (dense or sparse +//! accessors, any component type) become one [`MorphTarget`] of the mesh, with the mesh's +//! default `weights`, names from `extras.targetNames`, and a node's own `weights` in +//! [`Node::morph_weights`]. A mesh with more targets than [`Limits::max_morph_targets`] is read +//! in its base shape, and its targets are named in a warning. The offsets count against +//! [`Limits::max_data_bytes`] at 8 bytes per value, the zero offsets of vertices a target does +//! not move included, and so does each [`MorphTarget`] itself. The buffers count against the +//! same limit, and the offsets, images, skins and animations get what the buffers leave of it. +//! +//! The `extensions` and `extras` of the file, its nodes, meshes and materials are kept as +//! written ([`Scene::extensions`], [`Node::extensions`], …), for a caller that reads an +//! extension this module does not. They are kept whole: an extension that is also read into +//! the model's own fields (lights, the material extensions) stays in them as written. //! //! Not read: required extensions that change how geometry is stored (Draco, meshopt) are -//! [`Error::Unsupported`]; points, lines, morph targets, scenes other than the default and -//! other extensions are passed over (skipped primitives, primitives with morph targets and the -//! other scenes are named in warnings). +//! [`Error::Unsupported`]; points, lines, scenes other than the default and animations of +//! morph target weights are passed over (skipped primitives and the other scenes are named in +//! warnings). //! //! Buffers are needed to read anything, so an external buffer is asked of the resolver (by its //! percent-decoded URI) and is [`Error::Missing`] when declined. External images are only named @@ -27,16 +41,31 @@ //! A triangle that names a vertex that is not there, or one whose position is not finite, is //! left out and counted in a warning. //! -//! Written ([`write_glb`]): nodes, meshes (positions, normals, every UV set, colours), -//! materials and images. Skins, animations, cameras and lights are not written. +//! Written ([`write_glb`]): nodes, meshes (positions, normals, every UV set, colours, joints +//! and weights), skins, morph targets (POSITION and NORMAL offsets, the mesh's and each node's +//! weights, names in `extras.targetNames`), materials and images. A target that moves fewer +//! than three quarters of the vertices is written as a sparse accessor. The kept `extensions` +//! and `extras` of the file, nodes, meshes and materials are written as kept, except the +//! extensions the reader reads into the model's own fields: those are written from the fields +//! (the material extensions) or not at all (lights). `extensionsUsed` lists every extension the +//! written file names. The reader does not keep `extensionsRequired`; the writer requires only +//! `EXT_texture_webp`, which it uses for every texture of a WebP image (core glTF has no WebP). The file's textures ([`Scene::texture_variants`]) are written first and +//! in their order, so indices into nodes, materials and skins in kept extension data still name +//! the same things. Indices into textures, meshes and images do too, unless the reader left out +//! a texture without an image (named in a warning) or the writer leaves out a mesh without +//! triangles or an image without bytes or a URI: the later ones then move up. Indices into +//! accessors, buffer views and buffers are not rewritten. Animations, cameras, lights and +//! tangents (and so the tangent offsets of morph targets) are not written. use std::cell::Cell; +use std::collections::BTreeSet; use serde_json::{Map, Value, json}; use crate::{ AlphaMode, Animation, Camera, Channel, ChannelPath, Corner, Error, IDENTITY, Image, Interpolation, Light, LightKind, Limits, Material, Mesh, - NONE, Node, Part, Projection, Resolver, Result, Scene, Skin, TextureRef, Trs, UvTransform, Wrap, count_warning, malformed, too_large, + MorphTarget, NONE, Node, Part, Projection, Resolver, Result, Scene, Skin, TextureRef, Trs, Unified, UvTransform, Wrap, count_warning, malformed, + too_large, }; const KIND: &str = "glTF"; @@ -258,6 +287,11 @@ impl Doc<'_> { /// The accessor's values, `n` per element, at most `max` elements: every length is checked /// against the bytes that are there before anything is allocated from a count. fn rows(&self, a: usize, max: usize, what: &str) -> Result<(Vec, usize)> { + self.rows_with(a, max, what, &self.zero_left) + } + + /// [`Doc::rows`], taking the zeros of an accessor without a buffer view from `zeros`. + fn rows_with(&self, a: usize, max: usize, what: &str, zeros: &Cell) -> Result<(Vec, usize)> { let acc = self.accessor(a)?; let n = match acc.get("type").and_then(Value::as_str).unwrap_or("") { "SCALAR" => 1, @@ -287,7 +321,7 @@ impl Doc<'_> { let mut out = match idx(acc, "bufferView") { // No buffer view: all zeros. None => { - charge(&self.zero_left, total, "values without a buffer")?; + charge(zeros, total, "values without a buffer")?; vec![0.0; total] } Some(bv) => self.dense(acc, bv, (ct, csize, norm), n, count)?, @@ -364,7 +398,12 @@ impl Doc<'_> { struct Skipped { triangles: usize, primitives: usize, + /// Primitives of meshes with more morph targets than the limit allows. morphs: usize, + /// Primitives whose number of morph targets differs from their mesh's. + uneven: usize, + /// Morph target attributes that do not fit their primitive's vertices. + unfit: usize, } fn rows_of(v: &[f64]) -> impl Iterator + '_ { @@ -446,12 +485,95 @@ fn attributes(d: &Doc, attrs: &Value, pos: &[f64], mesh: &mut Mesh) -> Result<[u Ok([base, normal_base, uv_base, tangent_base]) } +/// Append the offsets of the primitive's morph targets (`list`) to the mesh's targets, from +/// where the primitive's vertices start in each pool. An attribute that does not have one +/// `VEC3` per vertex, or that moves a pool the primitive does not fill, is left out. +fn morph_targets( + d: &Doc, + list: &[Value], + mesh: &mut Mesh, + [base, normal_base, _, tangent_base]: [u32; 4], + nv: usize, + skipped: &mut Skipped, +) -> Result<()> { + // Every value is counted against the data limit before it is read, so the zeros of an + // accessor without a buffer view are not counted again. + let unbounded = Cell::new(usize::MAX); + for (target, t) in mesh.morph_targets.iter_mut().zip(list) { + for (start, key, offsets) in + [(base, "POSITION", &mut target.positions), (normal_base, "NORMAL", &mut target.normals), (tangent_base, "TANGENT", &mut target.tangents)] + { + let Some(a) = idx(t, key) else { continue }; + // An offset of a pool the primitive does not fill is left out before its accessor + // is looked up. + if start == NONE { + skipped.unfit += 1; + continue; + } + let vec3 = d.accessor(a)?.get("type").and_then(Value::as_str) == Some("VEC3"); + if !vec3 || d.count(a) != Some(nv) { + skipped.unfit += 1; + continue; + } + charge(&d.data_left, nv.saturating_mul(size_of::<[f64; 3]>()), "morph target bytes")?; + let (v, _) = d.rows_with(a, nv, "morph target offsets", &unbounded)?; + // Vertices of earlier primitives that this target does not move get no offset. + pad(&d.data_left, offsets, start as usize)?; + offsets.extend(rows_of::<3>(&v)); + } + } + Ok(()) +} + +/// Give `offsets` `len` entries, the new ones zero, counting their bytes against the data +/// limit. +fn pad(data_left: &Cell, offsets: &mut Vec<[f64; 3]>, len: usize) -> Result<()> { + let added = len.saturating_sub(offsets.len()); + charge(data_left, added.saturating_mul(size_of::<[f64; 3]>()), "morph target bytes")?; + offsets.resize(len.max(offsets.len()), [0.0; 3]); + Ok(()) +} + +/// Name the mesh's morph targets (`extras.targetNames`), set their default weights, and give +/// every list of offsets the length of the pool it moves. +fn finish_morph_targets(d: &Doc, m: &Value, mesh: &mut Mesh) -> Result<()> { + if mesh.morph_targets.is_empty() { + return Ok(()); + } + let names = m.get("extras").map_or(&[][..], |e| arr(e, "targetNames")); + let pools = [mesh.positions.len(), mesh.normals.len(), mesh.tangents.len()]; + for (k, t) in mesh.morph_targets.iter_mut().enumerate() { + t.name = names.get(k).and_then(Value::as_str).unwrap_or("").to_string(); + for (offsets, len) in [&mut t.positions, &mut t.normals, &mut t.tangents].into_iter().zip(pools) { + if !offsets.is_empty() { + pad(&d.data_left, offsets, len)?; + } + } + } + let weights = arr(m, "weights"); + mesh.morph_weights = (0..mesh.morph_targets.len()).map(|k| weights.get(k).map_or(0.0, finite_f32)).collect(); + Ok(()) +} + +/// A JSON number as `f32`; 0 when it is not a finite number. +fn finite_f32(v: &Value) -> f32 { + v.as_f64().map(|x| x as f32).filter(|x| x.is_finite()).unwrap_or(0.0) +} + +/// The object's `extensions` and `extras`, as written. Each is a part of the JSON chunk that is +/// kept once, so together they are never larger than it. +fn extension_data(v: &Value) -> (Map, Option) { + (v.get("extensions").and_then(Value::as_object).cloned().unwrap_or_default(), v.get("extras").cloned()) +} + /// Where the vertices of one set of attribute accessors start in the mesh's pools (positions, /// normals, UVs), and how many there are. Primitives of a mesh that name the same accessors /// (one vertex buffer, several materials) share the vertices. type Shared = std::collections::HashMap; -fn primitive(d: &Doc, p: &Value, mesh: &mut Mesh, shared: &mut Shared, materials: usize, skipped: &mut Skipped) -> Result<()> { +/// `targets` is the number of morph targets read for the mesh: 0 when it has none, or more +/// than the limit allows. +fn primitive(d: &Doc, p: &Value, mesh: &mut Mesh, shared: &mut Shared, materials: usize, targets: usize, skipped: &mut Skipped) -> Result<()> { let mode = idx(p, "mode").unwrap_or(4); let position = p.get("attributes").and_then(|a| idx(a, "POSITION")); let (Some(attrs), Some(pa), 4..=6) = (p.get("attributes"), position, mode) else { @@ -459,8 +581,15 @@ fn primitive(d: &Doc, p: &Value, mesh: &mut Mesh, shared: &mut Shared, materials return Ok(()); }; charge(&d.parts_left, 1, "primitives")?; - skipped.morphs += usize::from(!arr(p, "targets").is_empty()); - let key = attrs.to_string(); + let own = arr(p, "targets"); + if targets == 0 { + skipped.morphs += usize::from(!own.is_empty()); + } else { + skipped.uneven += usize::from(own.len() != targets); + } + // Primitives that name the same attributes but other morph targets move differently, so + // they do not share vertices. + let key = if targets == 0 { attrs.to_string() } else { json!([attrs, p.get("targets")]).to_string() }; let ([base, normal_base, uv_base, tangent_base], nv) = match shared.get(&key) { Some(known) => *known, None => { @@ -469,7 +598,11 @@ fn primitive(d: &Doc, p: &Value, mesh: &mut Mesh, shared: &mut Shared, materials return Err(malformed(KIND, "POSITION is not VEC3")); } charge(&d.vertices_left, pos.len() / 3, "vertices")?; - let placed = (attributes(d, attrs, &pos, mesh)?, pos.len() / 3); + let bases = attributes(d, attrs, &pos, mesh)?; + if targets > 0 { + morph_targets(d, own, mesh, bases, pos.len() / 3, skipped)?; + } + let placed = (bases, pos.len() / 3); shared.insert(key, placed); placed } @@ -554,6 +687,7 @@ fn images(d: &Doc, limits: &Limits, scene: &mut Scene) -> Result<()> { // An image that cannot be decoded is left without data, not an error. Some(data) => { if let Ok((mime, bytes)) = data { + charge(&d.data_left, bytes.len(), "image bytes")?; image.mime_type = image.mime_type.or(Some(mime).filter(|m| !m.is_empty())); image.data = Some(bytes); } @@ -597,6 +731,13 @@ fn materials(j: &Value, limits: &Limits, scene: &mut Scene) -> Result<()> { Some(TextureRef { image, wrap: [wrap(sampler, "wrapS"), wrap(sampler, "wrapT")], ..TextureRef::default() }) }) .collect(); + // The textures after one that is left out move up, so `extensions` data that names them by + // index no longer matches `texture_variants`. + count_warning( + &mut scene.warnings, + texture_list.len() - scene.texture_variants.len(), + "texture(s) have no image that is read and were left out; the textures after them are numbered from one less", + ); let tref = |v: Option<&Value>| -> Option { let v = v?; let texture = arr(j, "textures").get(idx(v, "index")?)?; @@ -621,6 +762,7 @@ fn materials(j: &Value, limits: &Limits, scene: &mut Scene) -> Result<()> { let strength = ext.and_then(|e| e.get("KHR_materials_emissive_strength")).map_or(1.0, |e| num(e, "emissiveStrength", 1.0)); let clearcoat = ext.and_then(|e| e.get("KHR_materials_clearcoat")); let sheen = ext.and_then(|e| e.get("KHR_materials_sheen")); + let (extensions, extras) = extension_data(m); scene.materials.push(Material { name: name(m), base_color: nums(pbr, "baseColorFactor", [1.0; 4]).map(|v| v as f32), @@ -649,6 +791,8 @@ fn materials(j: &Value, limits: &Limits, scene: &mut Scene) -> Result<()> { sheen_roughness: sheen.map_or(0.0, |s| num(s, "sheenRoughnessFactor", 0.0)) as f32, sheen_color_texture: sheen.and_then(|s| tref(s.get("sheenColorTexture"))), sheen_roughness_texture: sheen.and_then(|s| tref(s.get("sheenRoughnessTexture"))), + extensions, + extras, }); // The older specular-glossiness model, as the nearest metallic-roughness material: its // diffuse colour and texture, no metal, and roughness from the glossiness. @@ -669,6 +813,8 @@ fn nodes(j: &Value, limits: &Limits, scene: &mut Scene) -> Result<()> { return Err(too_large(KIND, format!("more than {} nodes", limits.max_nodes))); } let skins = arr(j, "skins").len().min(limits.max_extras); + let targets: Vec = scene.meshes.iter().map(|m| m.morph_targets.len()).collect(); + let targets_of = |mesh: Option| mesh.and_then(|m| targets.get(m)).copied().unwrap_or(0); for n in list { let matrix = n.get("matrix").and_then(Value::as_array).filter(|a| a.len() == 16).map(|_| nums(n, "matrix", IDENTITY)); let trs = Trs { @@ -676,6 +822,7 @@ fn nodes(j: &Value, limits: &Limits, scene: &mut Scene) -> Result<()> { rotation: nums(n, "rotation", [0.0, 0.0, 0.0, 1.0]), scale: nums(n, "scale", [1.0; 3]), }; + let (extensions, extras) = extension_data(n); scene.nodes.push(Node { name: name(n), transform: matrix.unwrap_or_else(|| trs.matrix()), @@ -685,6 +832,10 @@ fn nodes(j: &Value, limits: &Limits, scene: &mut Scene) -> Result<()> { camera: idx(n, "camera").filter(|c| *c < scene.cameras.len()), light: n.get("extensions").and_then(|e| e.get("KHR_lights_punctual")).and_then(|e| idx(e, "light")).filter(|l| *l < scene.lights.len()), children: indices(n, "children", list.len()), + // Only as many as the node's mesh has targets read: none when it has none. + morph_weights: arr(n, "weights").iter().take(targets_of(idx(n, "mesh"))).map(finite_f32).collect(), + extensions, + extras, }); } let scenes = arr(j, "scenes"); @@ -861,16 +1012,20 @@ pub fn read(bytes: &[u8], limits: &Limits, resolve: Resolver) -> Result { if version.split('.').next() != Some("2") { return Err(Error::Unsupported(format!("glTF: version `{}` (2.x is read)", version.chars().take(16).collect::()))); } - let mut scene = Scene::default(); + let (extensions, extras) = extension_data(&j); + let mut scene = Scene { extensions, extras, ..Scene::default() }; check_extensions(&j, &mut scene)?; + let buffers = buffers(&j, bin, limits, &mut scene, resolve)?; + // What is read out of the buffers shares one limit with the buffers themselves. + let data_left = limits.max_data_bytes.saturating_sub(buffers.iter().map(Vec::len).sum()); let d = Doc { j: &j, - buffers: buffers(&j, bin, limits, &mut scene, resolve)?, + buffers, vertices_left: Cell::new(limits.max_vertices), triangles_left: Cell::new(limits.max_triangles), parts_left: Cell::new(limits.max_parts), zero_left: Cell::new(MAX_ZERO_COMPONENTS), - data_left: Cell::new(limits.max_data_bytes), + data_left: Cell::new(data_left), }; images(&d, limits, &mut scene)?; materials(&j, limits, &mut scene)?; @@ -879,11 +1034,22 @@ pub fn read(bytes: &[u8], limits: &Limits, resolve: Resolver) -> Result { } let mut skipped = Skipped::default(); for m in arr(&j, "meshes") { - let mut mesh = Mesh { name: name(m), ..Mesh::default() }; + // glTF gives every primitive of a mesh the same number of morph targets; a primitive + // with fewer is not moved by the targets it lacks. + // Primitives that are left out (points, lines) do not count. + let read_primitive = + |p: &&Value| matches!(idx(p, "mode").unwrap_or(4), 4..=6) && p.get("attributes").and_then(|a| idx(a, "POSITION")).is_some(); + let targets = arr(m, "primitives").iter().filter(read_primitive).map(|p| arr(p, "targets").len()).max().unwrap_or(0); + let targets = if targets > limits.max_morph_targets { 0 } else { targets }; + // Targets without offsets still take memory, and across many meshes it adds up. + charge(&d.data_left, targets.saturating_mul(size_of::()), "morph target bytes")?; + let (extensions, extras) = extension_data(m); + let mut mesh = Mesh { name: name(m), morph_targets: vec![MorphTarget::default(); targets], extensions, extras, ..Mesh::default() }; let mut shared = Shared::new(); for p in arr(m, "primitives") { - primitive(&d, p, &mut mesh, &mut shared, scene.materials.len(), &mut skipped)?; + primitive(&d, p, &mut mesh, &mut shared, scene.materials.len(), targets, &mut skipped)?; } + finish_morph_targets(&d, m, &mut mesh)?; scene.meshes.push(mesh); } cameras_and_lights(&j, limits, &mut scene)?; @@ -892,22 +1058,44 @@ pub fn read(bytes: &[u8], limits: &Limits, resolve: Resolver) -> Result { animations(&d, limits, &mut scene)?; count_warning(&mut scene.warnings, skipped.primitives, "primitive(s) are points, lines or have no positions and were left out"); count_warning(&mut scene.warnings, skipped.triangles, "triangle(s) could not be read and were left out"); - count_warning(&mut scene.warnings, skipped.morphs, "primitive(s) have morph targets, which were left out (drawn in the base shape)"); + count_warning( + &mut scene.warnings, + skipped.morphs, + "primitive(s) have more morph targets than the limit allows, which were left out (drawn in the base shape)", + ); + count_warning(&mut scene.warnings, skipped.uneven, "primitive(s) have fewer morph targets than their mesh; the others do not move them"); + count_warning(&mut scene.warnings, skipped.unfit, "morph target attribute(s) do not fit their primitive's vertices and were left out"); // A hierarchy with a cycle, or one too deep to walk, is refused here rather than by every caller. scene.instances(limits)?; Ok(scene) } /// The binary chunk and the buffer views and accessors over it, as they are written. -#[derive(Default)] -struct Writer { - bin: Vec, +pub(crate) struct Writer { + pub(crate) bin: Vec, views: Vec, - accessors: Vec, + pub(crate) accessors: Vec, + /// Most bytes the binary chunk may hold ([`Limits::max_data_bytes`]). + max_bytes: usize, + /// Most morph targets of one mesh ([`Limits::max_morph_targets`]). + max_targets: usize, } impl Writer { - fn view(&mut self, bytes: &[u8], target: Option) -> usize { + pub(crate) fn new(limits: &Limits) -> Writer { + Writer { bin: Vec::new(), views: Vec::new(), accessors: Vec::new(), max_bytes: limits.max_data_bytes, max_targets: limits.max_morph_targets } + } + + /// [`Error::TooLarge`] when `bytes` more would take the binary chunk past its limit. + fn room(&self, bytes: usize) -> Result<()> { + match self.bin.len().next_multiple_of(4).checked_add(bytes) { + Some(total) if total <= self.max_bytes => Ok(()), + _ => Err(too_large("GLB", format!("more than {} bytes of data", self.max_bytes))), + } + } + + fn view(&mut self, bytes: &[u8], target: Option) -> Result { + self.room(bytes.len())?; self.bin.resize(self.bin.len().next_multiple_of(4), 0); let mut view = json!({ "buffer": 0, "byteOffset": self.bin.len(), "byteLength": bytes.len() }); if let (Some(t), Some(v)) = (target, view.as_object_mut()) { @@ -915,15 +1103,23 @@ impl Writer { } self.bin.extend_from_slice(bytes); self.views.push(view); - self.views.len() - 1 + Ok(self.views.len() - 1) } - /// A float accessor of `N` components per row; with the bounds glTF wants for positions. - fn floats(&mut self, rows: impl Iterator, kind: &str, bounds: bool) -> usize { + /// A float accessor of `N` components per row of vertex data; with the bounds glTF wants + /// for positions. + fn floats(&mut self, rows: impl Iterator, kind: &str, bounds: bool) -> Result { + self.floats_in(rows, kind, bounds, Some(34962)) + } + + /// [`Writer::floats`] in a buffer view with the given `target` (`None` for data that is not + /// per vertex). + fn floats_in(&mut self, rows: impl Iterator, kind: &str, bounds: bool, target: Option) -> Result { let mut bytes = Vec::new(); let (mut lo, mut hi, mut count) = ([f32::INFINITY; N], [f32::NEG_INFINITY; N], 0usize); for row in rows { count += 1; + self.room(bytes.len() + 4 * N)?; for (k, x) in row.iter().enumerate() { bytes.extend_from_slice(&x.to_le_bytes()); if let (Some(l), Some(h)) = (lo.get_mut(k), hi.get_mut(k)) { @@ -932,86 +1128,344 @@ impl Writer { } } } - let view = self.view(&bytes, Some(34962)); + let view = self.view(&bytes, target)?; let mut acc = json!({ "bufferView": view, "componentType": 5126, "count": count, "type": kind }); if let (true, Some(a)) = (bounds && count > 0, acc.as_object_mut()) { a.insert("min".into(), json!(lo.to_vec())); a.insert("max".into(), json!(hi.to_vec())); } self.accessors.push(acc); - self.accessors.len() - 1 + Ok(self.accessors.len() - 1) } - fn indices(&mut self, triangles: &[[u32; 3]]) -> usize { + fn indices(&mut self, triangles: &[[u32; 3]]) -> Result { + self.room(triangles.len().saturating_mul(12))?; let bytes: Vec = triangles.iter().flatten().flat_map(|i| i.to_le_bytes()).collect(); - let view = self.view(&bytes, Some(34963)); + let view = self.view(&bytes, Some(34963))?; self.accessors.push(json!({ "bufferView": view, "componentType": 5125, "count": triangles.len() * 3, "type": "SCALAR" })); - self.accessors.len() - 1 + Ok(self.accessors.len() - 1) } - /// The glTF mesh of `mesh`, or `None` when it has no triangle. - fn mesh(&mut self, mesh: &Mesh) -> Option { - let u = mesh.unified(); - if u.parts.iter().all(Vec::is_empty) { - return None; + /// The glTF mesh of `mesh` and the highest joint its written vertices name, or `None` when + /// it has no triangle. + pub(crate) fn mesh(&mut self, mesh: &Mesh) -> Result)>> { + // Parts whose corners all have normals (or UVs) and parts whose corners do not are + // written over separate vertices, so the first keep their normals, UVs and the morph + // targets' normal offsets. + let layout = |p: &Part| { + let all = |f: &dyn Fn(&Corner) -> bool| p.corners.iter().all(f); + (!mesh.normals.is_empty() && all(&|c| c.normal != NONE), !mesh.uv_sets.is_empty() && all(&|c| c.uv != NONE)) + }; + let keys: Vec> = mesh.parts.iter().map(|p| (!p.corners.is_empty()).then(|| layout(p))).collect(); + let mut layouts = Vec::new(); + for key in keys.iter().flatten() { + if !layouts.contains(key) { + layouts.push(*key); + } } + let groups: Vec = if layouts.len() <= 1 { + vec![mesh.unified()] + } else { + layouts.iter().map(|l| mesh.unified_parts(|k| keys.get(k).copied().flatten() == Some(*l))).collect() + }; + if groups.iter().all(|u| u.parts.iter().all(Vec::is_empty)) { + return Ok(None); + } + let mut top = None; + let mut streams = Vec::with_capacity(groups.len()); + for u in &groups { + if u.parts.iter().all(Vec::is_empty) { + streams.push(None); + continue; + } + let (attrs, highest) = self.vertices(mesh, u)?; + top = top.max(highest); + streams.push(Some((attrs, self.targets(mesh, u)?))); + } + let mut primitives = Vec::new(); + for (k, part) in mesh.parts.iter().enumerate() { + for (u, stream) in groups.iter().zip(&streams) { + let (Some(triangles), Some((attrs, targets))) = (u.parts.get(k).filter(|t| !t.is_empty()), stream) else { continue }; + let mut p = + Map::from_iter([("attributes".to_string(), Value::Object(attrs.clone())), ("indices".into(), json!(self.indices(triangles)?))]); + if let Some(m) = part.material { + p.insert("material".into(), json!(m)); + } + // Every primitive of a mesh has the mesh's targets. + if !targets.is_empty() { + p.insert("targets".into(), Value::Array(targets.clone())); + } + primitives.push(Value::Object(p)); + } + } + let mut out = Map::from_iter([("primitives".to_string(), Value::Array(primitives))]); + if !mesh.name.is_empty() { + out.insert("name".into(), json!(mesh.name)); + } + if !mesh.morph_targets.is_empty() && !mesh.morph_weights.is_empty() { + out.insert("weights".into(), json!(mesh.morph_weights)); + } + if !mesh.extensions.is_empty() { + out.insert("extensions".into(), Value::Object(mesh.extensions.clone())); + } + if let Some(extras) = mesh_extras(mesh) { + out.insert("extras".into(), extras); + } + Ok(Some((Value::Object(out), top))) + } + + /// The vertex attributes of `u`, the mesh's vertices for some of its parts, and the highest + /// joint they name. + fn vertices(&mut self, mesh: &Mesh, u: &Unified) -> Result<(Map, Option)> { let mut attrs = Map::new(); - attrs.insert("POSITION".into(), json!(self.floats(u.positions.iter().map(|p| p.map(|x| x as f32)), "VEC3", true))); + attrs.insert("POSITION".into(), json!(self.floats(u.positions.iter().map(|p| p.map(|x| x as f32)), "VEC3", true)?)); if !u.normals.is_empty() { - attrs.insert("NORMAL".into(), json!(self.floats(u.normals.iter().map(|n| n.map(|x| x as f32)), "VEC3", false))); + attrs.insert("NORMAL".into(), json!(self.floats(u.normals.iter().map(|n| n.map(|x| x as f32)), "VEC3", false)?)); } if !u.uvs.is_empty() { for (k, set) in mesh.uv_sets.iter().enumerate() { let rows = u.corners.iter().map(|c| set.get(c.uv as usize).copied().unwrap_or_default()); - attrs.insert(format!("TEXCOORD_{k}"), json!(self.floats(rows, "VEC2", false))); + attrs.insert(format!("TEXCOORD_{k}"), json!(self.floats(rows, "VEC2", false)?)); } } if !u.colors.is_empty() { - attrs.insert("COLOR_0".into(), json!(self.floats(u.colors.iter().copied(), "VEC4", false))); + attrs.insert("COLOR_0".into(), json!(self.floats(u.colors.iter().copied(), "VEC4", false)?)); } - let mut primitives = Vec::new(); - for (part, triangles) in mesh.parts.iter().zip(&u.parts).filter(|(_, t)| !t.is_empty()) { - let mut p = json!({ "attributes": attrs, "indices": self.indices(triangles) }); - if let (Some(m), Some(o)) = (part.material, p.as_object_mut()) { - o.insert("material".into(), json!(m)); + let mut top = None; + if !mesh.joints.is_empty() && !mesh.weights.is_empty() { + let joints: Vec<[u16; 4]> = u.corners.iter().map(|c| mesh.joints.get(c.position as usize).copied().unwrap_or_default()).collect(); + top = joints.iter().flatten().max().copied(); + attrs.insert("JOINTS_0".into(), json!(self.joints(joints.into_iter())?)); + let weights = u.corners.iter().map(|c| mesh.weights.get(c.position as usize).copied().unwrap_or_default()); + attrs.insert("WEIGHTS_0".into(), json!(self.floats(weights, "VEC4", false)?)); + } + Ok((attrs, top)) + } + + /// `JOINTS_0`: four joint indices per vertex, as unsigned shorts. + fn joints(&mut self, rows: impl Iterator) -> Result { + let mut bytes = Vec::new(); + let mut count = 0usize; + for row in rows { + count += 1; + self.room(bytes.len() + 8)?; + bytes.extend(row.iter().flat_map(|j| j.to_le_bytes())); + } + let view = self.view(&bytes, Some(34962))?; + self.accessors.push(json!({ "bufferView": view, "componentType": 5123, "count": count, "type": "VEC4" })); + Ok(self.accessors.len() - 1) + } + + /// The mesh's morph targets over the vertices of `u`: a POSITION for each, and a NORMAL + /// where the target moves normals and the normals are written. glTF wants at least one + /// attribute in a target, so a target that moves nothing gets a POSITION of zeros. A mesh + /// with more targets than [`Limits::max_morph_targets`] is [`Error::TooLarge`]. + fn targets(&mut self, mesh: &Mesh, u: &Unified) -> Result> { + if mesh.morph_targets.len() > self.max_targets { + return Err(too_large("GLB", format!("mesh `{}` has more than {} morph targets", mesh.name, self.max_targets))); + } + let pick = |offsets: &[[f64; 3]], i: u32| offsets.get(i as usize).map_or([0.0; 3], |o| o.map(|x| x as f32)); + let mut out = Vec::with_capacity(mesh.morph_targets.len()); + for t in &mesh.morph_targets { + let rows: Vec<[f32; 3]> = u.corners.iter().map(|c| pick(&t.positions, c.position)).collect(); + let mut target = Map::from_iter([("POSITION".to_string(), json!(self.offsets(&rows)?))]); + if !t.normals.is_empty() && !u.normals.is_empty() { + let rows: Vec<[f32; 3]> = u.corners.iter().map(|c| pick(&t.normals, c.normal)).collect(); + target.insert("NORMAL".into(), json!(self.offsets(&rows)?)); } - primitives.push(p); + out.push(Value::Object(target)); } - let mut out = json!({ "primitives": primitives }); - if let (false, Some(o)) = (mesh.name.is_empty(), out.as_object_mut()) { - o.insert("name".into(), json!(mesh.name)); + Ok(out) + } + + /// The `VEC3` accessor of one attribute of a morph target, with the bounds glTF wants for a + /// target's POSITION. When fewer than three quarters of the rows move, only those are + /// written, as a sparse accessor over zeros (no buffer view), which takes fewer bytes. + fn offsets(&mut self, rows: &[[f32; 3]]) -> Result { + let moved: Vec = (0u32..).zip(rows).filter(|(_, r)| **r != [0.0; 3]).map(|(i, _)| i).collect(); + // A sparse row is a 4-byte index and 12 bytes of values; a dense one, 12 bytes. + if moved.len().saturating_mul(4) >= rows.len().saturating_mul(3) { + return self.floats(rows.iter().copied(), "VEC3", true); } - Some(out) + let (mut lo, mut hi) = ([f32::INFINITY; 3], [f32::NEG_INFINITY; 3]); + for row in rows { + for ((l, h), x) in lo.iter_mut().zip(hi.iter_mut()).zip(row) { + *l = l.min(*x); + *h = h.max(*x); + } + } + let mut acc = Map::from_iter([ + ("componentType".to_string(), json!(5126)), + ("count".into(), json!(rows.len())), + ("type".into(), json!("VEC3")), + ("min".into(), json!(lo)), + ("max".into(), json!(hi)), + ]); + if !moved.is_empty() { + // The index and value views, 16 bytes a row. The index view ends on a 4-byte + // boundary, so no padding goes between them. + self.room(moved.len().saturating_mul(16))?; + let indices: Vec = moved.iter().flat_map(|i| i.to_le_bytes()).collect(); + let values: Vec = moved.iter().filter_map(|i| rows.get(*i as usize)).flatten().flat_map(|x| x.to_le_bytes()).collect(); + let (indices, values) = (self.view(&indices, None)?, self.view(&values, None)?); + let sparse = + json!({ "count": moved.len(), "indices": { "bufferView": indices, "componentType": 5125 }, "values": { "bufferView": values } }); + acc.insert("sparse".into(), sparse); + } + self.accessors.push(Value::Object(acc)); + Ok(self.accessors.len() - 1) + } + + /// A skin: its joints, and its inverse bind matrices when it has them (none means identity). + fn skin(&mut self, s: &Skin) -> Result { + let mut out = Map::from_iter([("joints".to_string(), json!(s.joints))]); + if !s.name.is_empty() { + out.insert("name".into(), json!(s.name)); + } + if !s.inverse_bind.is_empty() { + let rows = s.inverse_bind.iter().map(|m| m.map(|x| x as f32)); + out.insert("inverseBindMatrices".into(), json!(self.floats_in(rows, "MAT4", false, None)?)); + } + Ok(Value::Object(out)) + } +} + +/// A node as written. `mesh` is its mesh's written index and the mesh, when the mesh is +/// written; glTF gives a node a skin and weights only with a mesh. +fn node_json(n: &Node, mesh: Option<(usize, &Mesh)>) -> Value { + let mut out = Map::new(); + if !n.name.is_empty() { + out.insert("name".into(), json!(n.name)); + } + if n.transform != IDENTITY { + out.insert("matrix".into(), json!(n.transform)); + } + if let Some((index, m)) = mesh { + out.insert("mesh".into(), json!(index)); + if let Some(skin) = n.skin { + out.insert("skin".into(), json!(skin)); + } + // One weight per target of the mesh: the mesh's own weights stand in for any the node + // leaves out. + if !n.morph_weights.is_empty() && !m.morph_targets.is_empty() { + let weight = |k: usize| n.morph_weights.get(k).or_else(|| m.morph_weights.get(k)).copied().unwrap_or(0.0); + out.insert("weights".into(), json!((0..m.morph_targets.len()).map(weight).collect::>())); + } + } + if !n.children.is_empty() { + out.insert("children".into(), json!(n.children)); + } + let extensions = kept(&n.extensions, &[LIGHTS]); + if !extensions.is_empty() { + out.insert("extensions".into(), Value::Object(extensions)); + } + if let Some(extras) = &n.extras { + out.insert("extras".into(), extras.clone()); + } + Value::Object(out) +} + +/// The mesh's `extras` as written: as kept, with `targetNames` set to the names of its morph +/// targets when one has a name. `extras` that are not an object are written as they are, and +/// the names are then not written. +fn mesh_extras(mesh: &Mesh) -> Option { + let named = mesh.morph_targets.iter().any(|t| !t.name.is_empty()); + let names = || json!(mesh.morph_targets.iter().map(|t| t.name.as_str()).collect::>()); + match mesh.extras.clone() { + Some(Value::Object(mut o)) => { + if named { + o.insert("targetNames".into(), names()); + } + Some(Value::Object(o)) + } + None if named => Some(json!({ "targetNames": names() })), + other => other, } } /// The media type of encoded image bytes, for the formats glTF allows. fn sniff(bytes: &[u8]) -> &'static str { - if bytes.starts_with(&[0xFF, 0xD8]) { "image/jpeg" } else { "image/png" } + if bytes.starts_with(&[0xFF, 0xD8]) { + "image/jpeg" + } else if bytes.starts_with(b"RIFF") && bytes.get(8..12) == Some(b"WEBP") { + "image/webp" + } else { + "image/png" + } } -/// Images, samplers and textures as written: one texture per image and wrap pair in use. +/// `EXT_texture_webp`: core glTF has no WebP, so a texture of a WebP image names it only through +/// the extension, which a file without another source then requires. +const WEBP: &str = "EXT_texture_webp"; + +/// Images, samplers and textures as written: the scene's [`Scene::texture_variants`] first, in +/// their order, then one texture per other image and wrap pair in use. #[derive(Default)] struct Textures { images: Vec, /// The written index of each image of the scene (`None`: no bytes and no name to write). image_map: Vec>, samplers: Vec<[Wrap; 2]>, - textures: Vec<(usize, usize)>, + /// The written image (`None`: a texture of the file whose image is not written) and sampler. + textures: Vec<(Option, usize)>, + /// The index of the first of `textures` with each image and sampler. + first: std::collections::HashMap<(Option, usize), usize>, + /// Whether each written image is WebP. + webp: Vec, } impl Textures { + /// The `textures` list, and whether a texture names its image only through `EXT_texture_webp`. + fn json(&self) -> (Vec, bool) { + let mut webp_only = false; + let list = self + .textures + .iter() + .map(|(image, sampler)| match image { + Some(image) if self.webp.get(*image).copied().unwrap_or(false) => { + webp_only = true; + json!({ "sampler": sampler, "extensions": { WEBP: { "source": image } } }) + } + Some(image) => json!({ "source": image, "sampler": sampler }), + // glTF allows a texture without a source; it keeps the index of the next ones. + None => json!({ "sampler": sampler }), + }) + .collect(); + (list, webp_only) + } + + fn sampler(&mut self, wrap: [Wrap; 2]) -> usize { + self.samplers.iter().position(|s| *s == wrap).unwrap_or_else(|| { + self.samplers.push(wrap); + self.samplers.len() - 1 + }) + } + + /// Keep the textures of the file at their indices, which `extensions` the writer keeps may + /// name. + fn variants(&mut self, variants: &[TextureRef]) { + for t in variants { + let image = self.image_map.get(t.image).copied().flatten(); + let sampler = self.sampler(t.wrap); + self.push((image, sampler)); + } + } + + /// Add a texture, and the index of the first texture with its image and sampler. + fn push(&mut self, texture: (Option, usize)) -> usize { + self.textures.push(texture); + *self.first.entry(texture).or_insert(self.textures.len() - 1) + } + fn slot(&mut self, t: Option) -> Option { let t = t?; let image = (*self.image_map.get(t.image)?)?; - let sampler = self.samplers.iter().position(|s| *s == t.wrap).unwrap_or_else(|| { - self.samplers.push(t.wrap); - self.samplers.len() - 1 - }); - let index = self.textures.iter().position(|x| *x == (image, sampler)).unwrap_or_else(|| { - self.textures.push((image, sampler)); - self.textures.len() - 1 - }); + let sampler = self.sampler(t.wrap); + let key = (Some(image), sampler); + let index = match self.first.get(&key) { + Some(index) => *index, + None => self.push(key), + }; let mut out = json!({ "index": index, "texCoord": t.uv_set }); if let (Some(tt), Some(o)) = (t.transform, out.as_object_mut()) { let ext = json!({ "offset": tt.offset, "rotation": tt.rotation, "scale": tt.scale }); @@ -1021,10 +1475,29 @@ impl Textures { } } -fn material_json(m: &Material, textures: &mut Textures, extensions: &mut Vec<&'static str>) -> Value { +/// Material extensions the reader reads into [`Material`]'s fields. The writer writes them from +/// the fields, or not at all, and never as kept. +const MATERIAL_FIELDS: [&str; 5] = [ + "KHR_materials_emissive_strength", + "KHR_materials_unlit", + "KHR_materials_clearcoat", + "KHR_materials_sheen", + "KHR_materials_pbrSpecularGlossiness", +]; + +/// Extensions of the file and its nodes that the reader reads into [`Scene::lights`] and +/// [`Node::light`], which the writer does not write. +const LIGHTS: &str = "KHR_lights_punctual"; + +/// The kept `extensions` of an object, without `skip`. +fn kept(extensions: &Map, skip: &[&str]) -> Map { + extensions.iter().filter(|(k, _)| !skip.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect() +} + +fn material_json(m: &Material, textures: &mut Textures) -> Value { let mut pbr = json!({ "baseColorFactor": m.base_color, "metallicFactor": m.metallic, "roughnessFactor": m.roughness }); let mut out = json!({ "name": m.name, "doubleSided": m.double_sided }); - let mut ext = Map::new(); + let mut ext = kept(&m.extensions, &MATERIAL_FIELDS); // glTF's emissive factor stops at 1; the rest is a strength. let peak = m.emissive.iter().copied().fold(1.0f32, f32::max); if peak > 1.0 { @@ -1057,25 +1530,6 @@ fn material_json(m: &Material, textures: &mut Textures, extensions: &mut Vec<&'s } ext.insert("KHR_materials_sheen".into(), Value::Object(sheen)); } - for name in ["KHR_materials_emissive_strength", "KHR_materials_unlit", "KHR_materials_clearcoat", "KHR_materials_sheen"] { - if ext.contains_key(name) && !extensions.contains(&name) { - extensions.push(name); - } - } - let slots = [ - m.base_color_texture, - m.metallic_roughness_texture, - m.normal_texture, - m.occlusion_texture, - m.emissive_texture, - m.clearcoat_texture, - m.clearcoat_roughness_texture, - m.sheen_color_texture, - m.sheen_roughness_texture, - ]; - if slots.iter().flatten().any(|t| t.transform.is_some()) && !extensions.contains(&TEXTURE_TRANSFORM) { - extensions.push(TEXTURE_TRANSFORM); - } let set = |o: &mut Value, key: &str, v: Option| { if let (Some(v), Some(o)) = (v, o.as_object_mut()) { o.insert(key.into(), v); @@ -1105,9 +1559,40 @@ fn material_json(m: &Material, textures: &mut Textures, extensions: &mut Vec<&'s } } set(&mut out, "extensions", (!ext.is_empty()).then_some(Value::Object(ext))); + set(&mut out, "extras", m.extras.clone()); out } +/// The names of the extensions the document uses (its `extensionsUsed`): the keys of every +/// `extensions` object in it, at any depth, sorted. The application's `extras` are not +/// searched. +fn extensions_used(root: &Map) -> Vec { + extension_names(root, |name| name).into_iter().map(|name| json!(name)).collect() +} + +/// The keys of every `extensions` object in `root`, at any depth, each made into a `K` by `key` +/// and kept once. Each name takes a number of comparisons logarithmic in the names found so far. +pub(crate) fn extension_names<'a, K: Ord>(root: &'a Map, key: impl Fn(&'a str) -> K) -> BTreeSet { + let mut used = BTreeSet::new(); + let mut stack: Vec<(&str, &Value)> = root.iter().map(|(k, v)| (k.as_str(), v)).collect(); + while let Some((name, v)) = stack.pop() { + match (name, v) { + ("extras", _) => {} + ("extensions", Value::Object(o)) => { + for (name, inner) in o { + used.insert(key(name)); + stack.push((name, inner)); + } + } + (_, Value::Object(o)) => stack.extend(o.iter().map(|(k, v)| (k.as_str(), v))), + // An array's items are not under any key. + (_, Value::Array(a)) => stack.extend(a.iter().map(|item| ("", item))), + _ => {} + } + } + used +} + /// JSON has no number for these, and a file with them is not glTF. fn check_finite(scene: &Scene) -> Result<()> { let positions = scene.meshes.iter().flat_map(|m| m.positions.iter().flatten()).all(|x| (*x as f32).is_finite()); @@ -1136,6 +1621,86 @@ fn check_finite(scene: &Scene) -> Result<()> { if positions && nodes && materials { Ok(()) } else { Err(malformed(KIND, "a position, transform or material value is not finite")) } } +/// Every joint a written vertex names is in the skin of each node that places the mesh, and a +/// node with a skin places only written meshes with joints and weights. `top` is the highest +/// joint of each mesh's written vertices, and `written` the written index of each mesh. +fn check_joints(scene: &Scene, top: &[Option], written: &[Option]) -> Result<()> { + for n in &scene.nodes { + let (Some(m), Some(s)) = (n.mesh, n.skin.and_then(|s| scene.skins.get(s))) else { continue }; + if written.get(m).copied().flatten().is_none() { + continue; + } + let Some(Some(j)) = top.get(m) else { + return Err(malformed(KIND, format!("node `{}` has skin `{}` and a mesh without joints and weights", n.name, s.name))); + }; + if usize::from(*j) >= s.joints.len() { + return Err(malformed(KIND, format!("node `{}` names joint {j} of skin `{}`, which has {}", n.name, s.name, s.joints.len()))); + } + } + Ok(()) +} + +/// Skins as glTF has them: a skin with joints, each node once, and with one inverse bind matrix +/// per joint when it has any, each with a last row of 0, 0, 0, 1; and a mesh with both joints +/// and weights or neither, whose vertices name each joint with a weight other than 0 once. +fn check_skins(scene: &Scene) -> Result<()> { + if let Some(m) = scene.meshes.iter().find(|m| m.joints.is_empty() != m.weights.is_empty()) { + return Err(malformed(KIND, format!("mesh `{}` has joints without weights or weights without joints", m.name))); + } + let repeated = |j: &[u16; 4], w: &[f32; 4]| (0..4).any(|a| (a + 1..4).any(|b| w[a] != 0.0 && w[b] != 0.0 && j[a] == j[b])); + if let Some(m) = scene.meshes.iter().find(|m| m.joints.iter().zip(&m.weights).any(|(j, w)| repeated(j, w))) { + return Err(malformed(KIND, format!("mesh `{}` has a vertex that names a joint with a weight twice", m.name))); + } + for s in &scene.skins { + if s.joints.is_empty() { + return Err(malformed(KIND, format!("skin `{}` has no joints", s.name))); + } + let mut seen = std::collections::HashSet::with_capacity(s.joints.len()); + if !s.joints.iter().all(|j| seen.insert(*j)) { + return Err(malformed(KIND, format!("skin `{}` names a joint node twice", s.name))); + } + // Column-major: the last row is entries 3, 7, 11 and 15, as written in `f32`. + if s.inverse_bind.iter().any(|m| [m[3], m[7], m[11], m[15]].map(|x| x as f32) != [0.0, 0.0, 0.0, 1.0]) { + return Err(malformed(KIND, format!("skin `{}` has an inverse bind matrix whose last row is not 0, 0, 0, 1", s.name))); + } + if !s.inverse_bind.is_empty() && s.inverse_bind.len() != s.joints.len() { + return Err(malformed( + KIND, + format!("skin `{}` has {} inverse bind matrices for {} joints", s.name, s.inverse_bind.len(), s.joints.len()), + )); + } + } + Ok(()) +} + +/// Skins ([`check_skins`]) and morph targets as glTF has them: every value finite, and no node +/// with more weights than its mesh has targets. +fn check_rigging(scene: &Scene) -> Result<()> { + check_skins(scene)?; + let targets = |n: &Node| n.mesh.and_then(|m| scene.meshes.get(m)).map_or(0, |m| m.morph_targets.len()); + if let Some(n) = scene.nodes.iter().find(|n| n.morph_weights.len() > targets(n)) { + return Err(malformed(KIND, format!("node `{}` has {} morph weights for {} targets", n.name, n.morph_weights.len(), targets(n)))); + } + // Morph target weights may be negative; skinning weights may not. + if let Some(m) = scene.meshes.iter().find(|m| m.weights.iter().flatten().any(|w| *w < 0.0)) { + return Err(malformed(KIND, format!("mesh `{}` has a negative skinning weight", m.name))); + } + let binds = scene.skins.iter().flat_map(|s| s.inverse_bind.iter().flatten()).all(|x| (*x as f32).is_finite()); + let offsets = scene + .meshes + .iter() + .flat_map(|m| &m.morph_targets) + .flat_map(|t| t.positions.iter().chain(&t.normals).flatten()) + .all(|x| (*x as f32).is_finite()); + let weights = scene.meshes.iter().flat_map(|m| m.morph_weights.iter().chain(m.weights.iter().flatten())); + let node_weights = scene.nodes.iter().flat_map(|n| &n.morph_weights); + if binds && offsets && weights.chain(node_weights).all(|x| x.is_finite()) { + Ok(()) + } else { + Err(malformed(KIND, "a skin or morph target value is not finite")) + } +} + /// Texture magnification filtering for a GLB sampler. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u16)] @@ -1166,9 +1731,18 @@ pub struct GlbWriteOptions { } /// The scene as a binary glTF file: its nodes, meshes (each part a primitive over the mesh's -/// [`Mesh::unified`] vertices: positions, normals, UV sets and colours) and materials, with -/// images that have bytes embedded and the others named by their URI. The binary chunk is -/// limited to `limits.max_data_bytes`. +/// [`Mesh::unified`] vertices: positions, normals, UV sets, colours, joints and weights, with +/// the mesh's morph targets), skins and materials, with images that have bytes embedded and +/// the others named by their URI, and the kept `extensions` and `extras` (see the module +/// documentation). The binary chunk is limited to `limits.max_data_bytes`, and each mesh to +/// `limits.max_morph_targets` morph targets; past either, the writer stops with +/// [`Error::TooLarge`] before it writes more. A value that is not +/// finite, a skin without joints, with a joint node named twice, or whose inverse bind matrices +/// do not match its joints or have a last row other than 0, 0, 0, 1, a mesh with joints but no +/// weights (or weights but no joints), a negative skinning weight, a vertex that names a joint +/// with a weight other than 0 twice, a joint of a written vertex outside the skin of a node that +/// places the mesh, a node with a skin that places a written mesh without joints and weights, +/// and a node with more morph weights than its mesh has targets are [`Error::Malformed`]. pub fn write_glb(scene: &Scene, limits: &Limits) -> Result> { write_glb_with_options(scene, limits, &GlbWriteOptions::default()) } @@ -1178,60 +1752,71 @@ pub fn write_glb_with_options(scene: &Scene, limits: &Limits, options: &GlbWrite scene.validate()?; scene.instances(limits)?; check_finite(scene)?; - let mut w = Writer::default(); + check_rigging(scene)?; + let mut w = Writer::new(limits); let mut meshes = Vec::new(); + let mut top = Vec::with_capacity(scene.meshes.len()); let mesh_map: Vec> = scene .meshes .iter() .map(|m| { - w.mesh(m).map(|v| { + let written = w.mesh(m)?; + top.push(written.as_ref().and_then(|(_, j)| *j)); + Ok(written.map(|(v, _)| { meshes.push(v); meshes.len() - 1 - }) + })) }) - .collect(); + .collect::>()?; + check_joints(scene, &top, &mesh_map)?; let mut textures = Textures::default(); for image in &scene.images { let mut out = Map::new(); if !image.name.is_empty() { out.insert("name".into(), json!(image.name)); } - match (&image.data, &image.uri) { + let mime = match (&image.data, &image.uri) { (Some(bytes), _) => { - out.insert("bufferView".into(), json!(w.view(bytes, None))); - out.insert("mimeType".into(), json!(image.mime_type.clone().unwrap_or_else(|| sniff(bytes).into()))); + let mime = image.mime_type.clone().unwrap_or_else(|| sniff(bytes).into()); + out.insert("bufferView".into(), json!(w.view(bytes, None)?)); + out.insert("mimeType".into(), json!(mime)); + mime + } + (None, Some(uri)) => { + out.insert("uri".into(), json!(uri)); + // The path's extension, without a query or fragment. + let path = uri.split(['?', '#']).next().unwrap_or(""); + let webp = path.rsplit_once('.').is_some_and(|(_, e)| e.eq_ignore_ascii_case("webp")); + match image.mime_type.clone().filter(|m| !m.is_empty()) { + // A URI without the format's extension keeps its media type for the next reader. + Some(mime) => { + out.insert("mimeType".into(), json!(mime)); + mime + } + None if webp => "image/webp".into(), + None => String::new(), + } } - (None, Some(uri)) => drop(out.insert("uri".into(), json!(uri))), (None, None) => { textures.image_map.push(None); continue; } - } + }; + textures.webp.push(mime == "image/webp"); textures.image_map.push(Some(textures.images.len())); textures.images.push(Value::Object(out)); } - let mut extensions = Vec::new(); - let materials: Vec = scene.materials.iter().map(|m| material_json(m, &mut textures, &mut extensions)).collect(); + textures.variants(&scene.texture_variants); + let materials: Vec = scene.materials.iter().map(|m| material_json(m, &mut textures)).collect(); let nodes: Vec = scene .nodes .iter() .map(|n| { - let mut out = Map::new(); - if !n.name.is_empty() { - out.insert("name".into(), json!(n.name)); - } - if n.transform != IDENTITY { - out.insert("matrix".into(), json!(n.transform)); - } - if let Some(m) = n.mesh.and_then(|m| mesh_map.get(m).copied().flatten()) { - out.insert("mesh".into(), json!(m)); - } - if !n.children.is_empty() { - out.insert("children".into(), json!(n.children)); - } - Value::Object(out) + let mesh = n.mesh.and_then(|m| Some((mesh_map.get(m).copied().flatten()?, scene.meshes.get(m)?))); + node_json(n, mesh) }) .collect(); + let skins: Vec = scene.skins.iter().map(|s| w.skin(s)).collect::>()?; if w.bin.len() > limits.max_data_bytes { return Err(too_large("GLB", format!("more than {} bytes of data", limits.max_data_bytes))); } @@ -1252,8 +1837,10 @@ pub fn write_glb_with_options(scene: &Scene, limits: &Limits, options: &GlbWrite }; list("nodes", nodes); list("meshes", meshes); + list("skins", skins); list("materials", materials); - list("textures", textures.textures.iter().map(|(image, sampler)| json!({ "source": image, "sampler": sampler })).collect()); + let (texture_list, webp_only) = textures.json(); + list("textures", texture_list); list( "samplers", textures @@ -1274,7 +1861,20 @@ pub fn write_glb_with_options(scene: &Scene, limits: &Limits, options: &GlbWrite list("images", textures.images); list("accessors", w.accessors); list("bufferViews", w.views); - list("extensionsUsed", extensions.iter().map(|e| json!(e)).collect()); + let extensions = kept(&scene.extensions, &[LIGHTS]); + if !extensions.is_empty() { + root.insert("extensions".into(), Value::Object(extensions)); + } + if let Some(extras) = &scene.extras { + root.insert("extras".into(), extras.clone()); + } + let used = extensions_used(&root); + if !used.is_empty() { + root.insert("extensionsUsed".into(), Value::Array(used)); + } + if webp_only { + root.insert("extensionsRequired".into(), json!([WEBP])); + } if !w.bin.is_empty() { root.insert("buffers".into(), json!([{ "byteLength": w.bin.len() }])); } diff --git a/crates/mesh/src/lib.rs b/crates/mesh/src/lib.rs index c1d2e1d4bd..5870aa5af9 100644 --- a/crates/mesh/src/lib.rs +++ b/crates/mesh/src/lib.rs @@ -26,7 +26,8 @@ //! of the caller's [`Resolver`], which may decline. //! //! Depends on no other Craft crate, except that `threemf` opens its package with `craft-opc` -//! and reads its XML with `craft-xml`. +//! and reads its XML with `craft-xml`. `serde_json` holds glTF's `extensions` and `extras` in +//! the model, so it is a dependency with every feature. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] // The helpers the formats share are not all used by every subset of them. @@ -65,6 +66,10 @@ mod triangulate; use std::collections::HashMap; use std::fmt; +/// The JSON types of the `extensions` and `extras` fields. +pub use serde_json; +use serde_json::{Map, Value}; + /// Why a file could not be read or a scene could not be written. #[derive(Clone, Debug, PartialEq)] pub enum Error { @@ -123,6 +128,9 @@ pub struct Limits { pub max_data_bytes: usize, /// Most skins, animations, cameras and lights (each), and most channels of one animation. pub max_extras: usize, + /// Most morph targets of one mesh. A mesh with more keeps its base shape, and its targets + /// are left out and counted in a warning. + pub max_morph_targets: usize, } impl Default for Limits { @@ -138,6 +146,7 @@ impl Default for Limits { max_depth: 64, max_data_bytes: 1 << 30, max_extras: 10_000, + max_morph_targets: 256, } } } @@ -255,6 +264,30 @@ pub struct Mesh { pub joints: Vec<[u16; 4]>, pub weights: Vec<[f32; 4]>, pub parts: Vec, + /// Morph targets (glTF): shapes whose offsets, times a weight, are added to the base shape. + pub morph_targets: Vec, + /// The weight of each morph target when nothing sets one (glTF `mesh.weights`); one per + /// target. + pub morph_weights: Vec, + /// The file's `extensions` object for the mesh (glTF), as written; empty when it has none. + pub extensions: Map, + /// The file's `extras` value for the mesh (glTF), as written. + pub extras: Option, +} + +/// One morph target of a [`Mesh`]: offsets added to the base shape, times the target's weight. +/// Each list is empty when the target does not move that attribute, or as long as the mesh's +/// pool it moves. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct MorphTarget { + /// The target's name, from the mesh's `extras.targetNames` (glTF); empty when it has none. + pub name: String, + /// One offset per entry of [`Mesh::positions`]. + pub positions: Vec<[f64; 3]>, + /// One offset per entry of [`Mesh::normals`]. + pub normals: Vec<[f64; 3]>, + /// One offset of `[x, y, z]` per entry of [`Mesh::tangents`]; the handedness does not move. + pub tangents: Vec<[f64; 3]>, } /// A triangle list with one index per vertex, as [`Mesh::unified`] builds it. @@ -297,6 +330,20 @@ impl Mesh { if self.parts.iter().any(|p| p.has_tangents) && self.tangents.len() != self.positions.len() { return bad("a part names tangents but the tangent array does not match the positions"); } + if !self.morph_weights.is_empty() && self.morph_weights.len() != self.morph_targets.len() { + return bad("the morph weights do not match the morph targets"); + } + for t in &self.morph_targets { + for (what, len, pool) in [ + ("positions", t.positions.len(), self.positions.len()), + ("normals", t.normals.len(), self.normals.len()), + ("tangents", t.tangents.len(), self.tangents.len()), + ] { + if len != 0 && len != pool { + return bad(&format!("morph target `{}`: its {what} do not match the mesh's", t.name)); + } + } + } for p in &self.parts { let total = if p.face_sizes.is_empty() { (p.corners.len() % 3 == 0).then_some(p.corners.len()) @@ -321,13 +368,24 @@ impl Mesh { /// The mesh as triangles ([`Part::triangles_in`]) with one vertex per distinct corner. /// Corners whose indices are out of range are dropped with their triangle. pub fn unified(&self) -> Unified { + self.unified_parts(|_| true) + } + + /// [`Mesh::unified`] over the parts that `keep` takes by index. The others get no triangles, + /// and their corners do not decide whether the vertices have normals and UVs. + pub(crate) fn unified_parts(&self, keep: impl Fn(usize) -> bool) -> Unified { let mut out = Unified::default(); - let all = |f: &dyn Fn(&Corner) -> bool| self.parts.iter().all(|p| p.corners.iter().all(f)); + let kept = || self.parts.iter().enumerate().filter(|(k, _)| keep(*k)).map(|(_, p)| p); + let all = |f: &dyn Fn(&Corner) -> bool| kept().all(|p| p.corners.iter().all(f)); let normals = !self.normals.is_empty() && all(&|c| c.normal != NONE); let uv_set = self.uv_sets.first().filter(|_| all(&|c| c.uv != NONE)); let colors = self.colors.len() == self.positions.len() && !self.colors.is_empty(); let mut ids: HashMap = HashMap::new(); - for part in &self.parts { + for (k, part) in self.parts.iter().enumerate() { + if !keep(k) { + out.parts.push(Vec::new()); + continue; + } let mut tris = Vec::with_capacity(part.triangle_count()); 'tri: for t in part.triangles_in(&self.positions) { let mut tri = [0u32; 3]; @@ -471,6 +529,11 @@ pub struct Material { pub sheen_roughness: f32, pub sheen_color_texture: Option, pub sheen_roughness_texture: Option, + /// The file's `extensions` object for the material (glTF), as written, the ones read into + /// the fields above included; empty when it has none. + pub extensions: Map, + /// The file's `extras` value for the material (glTF), as written. + pub extras: Option, } impl Default for Material { @@ -499,6 +562,8 @@ impl Default for Material { sheen_roughness: 0.0, sheen_color_texture: None, sheen_roughness_texture: None, + extensions: Map::new(), + extras: None, } } } @@ -615,11 +680,31 @@ pub struct Node { pub skin: Option, /// Indices into [`Scene::nodes`]. pub children: Vec, + /// Morph target weights for this node's mesh (glTF `node.weights`), in place of the mesh's + /// [`Mesh::morph_weights`]; at most one per target the mesh has, and empty when the node + /// sets none. + pub morph_weights: Vec, + /// The file's `extensions` object for the node (glTF), as written; empty when it has none. + pub extensions: Map, + /// The file's `extras` value for the node (glTF), as written. + pub extras: Option, } impl Default for Node { fn default() -> Self { - Node { name: String::new(), transform: IDENTITY, trs: None, camera: None, light: None, mesh: None, skin: None, children: Vec::new() } + Node { + name: String::new(), + transform: IDENTITY, + trs: None, + camera: None, + light: None, + mesh: None, + skin: None, + children: Vec::new(), + morph_weights: Vec::new(), + extensions: Map::new(), + extras: None, + } } } @@ -727,6 +812,11 @@ pub struct Scene { pub external: Vec, /// What was left out or repaired while reading. pub warnings: Vec, + /// The file's top-level `extensions` object (glTF), as written, the lights read into + /// [`Scene::lights`] included; empty when it has none. + pub extensions: Map, + /// The file's top-level `extras` value (glTF), as written. + pub extras: Option, } impl Scene { diff --git a/crates/mesh/src/tests.rs b/crates/mesh/src/tests.rs index 31b84d2eff..7be9dddf50 100644 --- a/crates/mesh/src/tests.rs +++ b/crates/mesh/src/tests.rs @@ -10,6 +10,8 @@ mod dae; mod fbx; #[cfg(feature = "gltf")] mod gltf; +#[cfg(feature = "gltf")] +mod gltf_write; #[cfg(feature = "obj")] mod obj; #[cfg(feature = "ply")] diff --git a/crates/mesh/src/tests/gltf.rs b/crates/mesh/src/tests/gltf.rs index 42eabc4028..62542cb36b 100644 --- a/crates/mesh/src/tests/gltf.rs +++ b/crates/mesh/src/tests/gltf.rs @@ -5,8 +5,8 @@ use crate::gltf::{ GlbWriteOptions, MAX_ZERO_COMPONENTS, MagFilter, MinFilter, glb_container, read, split_glb, uri_decode, write_glb, write_glb_with_options, }; use crate::{ - AlphaMode, ChannelPath, Corner, Error, IDENTITY, Image, Interpolation, LightKind, Limits, Material, Mesh, NONE, Node, Part, Projection, Scene, - TextureRef, UvTransform, Wrap, face_normal, no_external, transform_point, + AlphaMode, ChannelPath, Corner, Error, IDENTITY, Image, Interpolation, LightKind, Limits, Material, Mesh, MorphTarget, NONE, Node, Part, + Projection, Scene, TextureRef, UvTransform, Wrap, face_normal, no_external, transform_point, }; /// Builds the binary chunk with its buffer views and accessors. @@ -652,8 +652,11 @@ fn limits_count_shared_accessors_expansions_and_extras() { assert!(with(&glb, &|l| l.max_extras = 4).is_ok(), "{key}"); assert!(too(with(&glb, &|l| l.max_extras = 3)), "{key}"); } - let image_and_keys = with(&r, &|l| l.max_data_bytes = split_glb(&r).unwrap().1.unwrap().len()); - assert!(image_and_keys.is_ok()); + // The skin's 32 matrix values and the channel's 8 keys are charged on top of the buffer + // they are read from. + let bin = split_glb(&r).unwrap().1.unwrap().len(); + assert!(with(&r, &|l| l.max_data_bytes = bin + 40).is_ok()); + assert!(too(with(&r, &|l| l.max_data_bytes = bin + 39))); } #[test] @@ -770,7 +773,13 @@ fn written_files_read_back() { // The materials; the image without bytes or a name takes its texture slot with it. let mut wood = scene.materials[0].clone(); wood.occlusion_texture = None; - assert_eq!(back.materials, [wood, scene.materials[1].clone()]); + // The reader also keeps the extensions the writer wrote for the fields as they are written. + let mut read = back.materials.clone(); + assert_eq!( + Value::Object(std::mem::take(&mut read[0].extensions)), + json!({ "KHR_materials_emissive_strength": { "emissiveStrength": 2.0 }, "KHR_materials_unlit": {} }) + ); + assert_eq!(read, [wood, scene.materials[1].clone()]); assert_eq!(back.images.len(), 2); assert_eq!((back.images[0].data.as_deref(), back.images[0].mime_type.as_deref()), (Some(&b"\x89PNG wood"[..]), Some("image/png"))); assert_eq!(back.images[1].uri.as_deref(), Some("bump.png")); @@ -889,7 +898,7 @@ fn specular_glossiness_and_webp_textures() { } #[test] -fn morph_targets_and_other_scenes_are_named_in_warnings() { +fn other_scenes_are_named_in_warnings_and_read_morph_targets_are_not() { let mut b = B::default(); let p = b.f32s(&QUAD[..9], "VEC3", 3); let d = b.f32s(&[0.0; 9], "VEC3", 3); @@ -900,33 +909,253 @@ fn morph_targets_and_other_scenes_are_named_in_warnings() { "scene": scene, "scenes": scenes, "nodes": [{ "mesh": 0 }, { "mesh": 0 }], - "meshes": [{ "primitives": [plain, morphed, morphed] }], + "meshes": [{ "primitives": [morphed, morphed] }], })) }; let s = parse(&doc(json!(1), json!([{ "nodes": [0] }, { "nodes": [1] }, { "nodes": [] }]))).unwrap(); assert_eq!(s.roots, [1]); - assert_eq!( - s.warnings, - ["scene 1 of 3 was read; the others were left out", "2 primitive(s) have morph targets, which were left out (drawn in the base shape)",] - ); - // The morphed primitives are still drawn, in their base shape. - assert_eq!(s.meshes[0].parts.len(), 3); - let morphs = "2 primitive(s) have morph targets, which were left out (drawn in the base shape)"; + // The morph targets are read, so they are not named. + assert_eq!(s.warnings, ["scene 1 of 3 was read; the others were left out"]); + assert_eq!((s.meshes[0].parts.len(), s.meshes[0].morph_targets.len()), (2, 1)); // An out-of-range choice falls back to the first scene. let s = parse(&doc(json!(5), json!([{ "nodes": [1] }, { "nodes": [0] }]))).unwrap(); assert_eq!(s.roots, [1]); - assert_eq!(s.warnings, ["scene 0 of 2 was read; the others were left out", morphs]); + assert_eq!(s.warnings, ["scene 0 of 2 was read; the others were left out"]); // One scene, or none, is not a warning about scenes. let s = parse(&doc(json!(5), json!([{ "nodes": [0] }]))).unwrap(); assert_eq!(s.roots, [0]); - assert_eq!(s.warnings, [morphs]); + assert!(s.warnings.is_empty(), "{:?}", s.warnings); let s = parse(&doc(json!(null), json!(null))).unwrap(); assert_eq!(s.roots, [0, 1]); - assert_eq!(s.warnings, [morphs]); + assert!(s.warnings.is_empty(), "{:?}", s.warnings); let s = parse(&one_mesh(&b, plain.clone())).unwrap(); assert!(s.warnings.is_empty(), "{:?}", s.warnings); } +/// A quad with normals and tangents and two morph targets: "smile" moves every position, normal +/// and tangent by dense accessors, and "blink" moves two positions by a sparse accessor without +/// a buffer view. The mesh's default weights name only the first target; the node sets both. +fn morphed() -> Vec { + let mut b = B::default(); + let p = b.f32s(&QUAD, "VEC3", 3); + let n = b.f32s(&[0.0, 0.0, 1.0].repeat(4), "VEC3", 3); + let t = b.f32s(&[1.0, 0.0, 0.0, 1.0].repeat(4), "VEC4", 4); + let i = b.u16s(&[0, 1, 2, 0, 2, 3]); + let lift = b.f32s(&[0.0, 0.0, 1.0].repeat(4), "VEC3", 3); + let tilt = b.f32s(&[0.5, 0.0, 0.0].repeat(4), "VEC3", 3); + let turn = b.f32s(&[0.0, 1.0, 0.0].repeat(4), "VEC3", 3); + let which = b.view(&[1u8, 3]); + let moves = b.view(&[0.0f32, 2.0, 0.0, 0.0, 0.0, -1.0].iter().flat_map(|x| x.to_le_bytes()).collect::>()); + b.accessors.push(json!({ "componentType": 5126, "count": 4, "type": "VEC3", + "sparse": { "count": 2, "indices": { "bufferView": which, "componentType": 5121 }, "values": { "bufferView": moves } } })); + let blink = b.accessors.len() - 1; + b.glb(json!({ + "nodes": [{ "mesh": 0, "weights": [0.5, 1.0] }], + "meshes": [{ + "name": "Face", + "primitives": [{ + "attributes": { "POSITION": p, "NORMAL": n, "TANGENT": t }, + "indices": i, + "targets": [{ "POSITION": lift, "NORMAL": tilt, "TANGENT": turn }, { "POSITION": blink }], + }], + "weights": [0.25], + "extras": { "targetNames": ["smile", "blink"] }, + }], + })) +} + +#[test] +fn morph_targets_are_read_with_their_names_and_weights() { + let s = parse(&morphed()).unwrap(); + s.validate().unwrap(); + assert!(s.warnings.is_empty(), "{:?}", s.warnings); + let m = &s.meshes[0]; + let names: Vec<&str> = m.morph_targets.iter().map(|t| t.name.as_str()).collect(); + assert_eq!(names, ["smile", "blink"]); + // A weight the mesh leaves out is 0; the node's own weights stand in for the mesh's. + assert_eq!(m.morph_weights, [0.25, 0.0]); + assert_eq!(s.nodes[0].morph_weights, [0.5, 1.0]); + let (smile, blink) = (&m.morph_targets[0], &m.morph_targets[1]); + assert_eq!( + (smile.positions.clone(), smile.normals.clone(), smile.tangents.clone()), + (vec![[0.0, 0.0, 1.0]; 4], vec![[0.5, 0.0, 0.0]; 4], vec![[0.0, 1.0, 0.0]; 4]) + ); + // The sparse target moves only the positions it names, and no normals or tangents. + assert_eq!(blink.positions, [[0.0; 3], [0.0, 2.0, 0.0], [0.0; 3], [0.0, 0.0, -1.0]]); + assert!(blink.normals.is_empty() && blink.tangents.is_empty()); + // The glTF rule: each position is its base plus every target's offset times its weight. + // With the node's weights 0.5 and 1.0, worked out by hand from the offsets above: + let weights = &s.nodes[0].morph_weights; + let shaped: Vec<[f64; 3]> = m + .positions + .iter() + .enumerate() + .map(|(v, base)| { + let mut p = *base; + for (t, w) in m.morph_targets.iter().zip(weights) { + for (k, x) in p.iter_mut().enumerate() { + *x += f64::from(*w) * t.positions[v][k]; + } + } + p + }) + .collect(); + assert_eq!(shaped, [[0.0, 0.0, 0.5], [1.0, 2.0, 0.5], [1.0, 1.0, 0.5], [0.0, 1.0, -0.5]]); +} + +#[test] +fn morph_targets_follow_their_primitives_vertices() { + let mut b = B::default(); + let three = b.f32s(&QUAD[..9], "VEC3", 3); + let normals = b.f32s(&[0.0, 0.0, 1.0].repeat(3), "VEC3", 3); + let four = b.f32s(&QUAD, "VEC3", 3); + let up = b.f32s(&[0.0, 0.0, 1.0].repeat(3), "VEC3", 3); + let bend = b.f32s(&[0.0, 1.0, 0.0].repeat(3), "VEC3", 3); + let out = b.f32s(&[1.0, 0.0, 0.0].repeat(4), "VEC3", 3); + let i = b.u16s(&[0, 1, 2, 0, 2, 3]); + let a = json!({ "attributes": { "POSITION": three, "NORMAL": normals }, "targets": [{ "POSITION": up, "NORMAL": bend }] }); + // The second primitive has no normals, so its target's NORMAL has nothing to move. + let b2 = json!({ "attributes": { "POSITION": four }, "indices": i, "targets": [{ "POSITION": out, "NORMAL": out }] }); + // The fourth names the first one's positions without its targets: its own vertices, not + // moved. + let still = json!({ "attributes": { "POSITION": three, "NORMAL": normals } }); + let s = parse(&b.glb(json!({ "meshes": [{ "primitives": [a, b2, a, still] }] }))).unwrap(); + s.validate().unwrap(); + assert_eq!( + s.warnings, + [ + "1 primitive(s) have fewer morph targets than their mesh; the others do not move them", + "1 morph target attribute(s) do not fit their primitive's vertices and were left out", + ] + ); + let m = &s.meshes[0]; + // The third primitive shares the first one's vertices; the fourth has its own. + assert_eq!((m.positions.len(), m.normals.len(), m.parts.len()), (10, 6, 4)); + let t = &m.morph_targets[0]; + let mut positions = vec![[0.0, 0.0, 1.0]; 3]; + positions.extend([[1.0, 0.0, 0.0]; 4]); + positions.extend([[0.0; 3]; 3]); + assert_eq!(t.positions, positions); + let mut normals = vec![[0.0, 1.0, 0.0]; 3]; + normals.extend([[0.0; 3]; 3]); + assert_eq!(t.normals, normals); + // The NORMAL offsets of a primitive without normals are left out before their accessor is + // looked up, so offsets that name no accessor leave the primitive as it is. + let missing = json!({ "attributes": { "POSITION": four }, "indices": i, "targets": [{ "POSITION": out, "NORMAL": 99 }] }); + let s = parse(&b.glb(json!({ "meshes": [{ "primitives": [missing] }] }))).unwrap(); + assert_eq!(s.warnings, ["1 morph target attribute(s) do not fit their primitive's vertices and were left out"]); + assert_eq!((s.meshes[0].triangle_count(), s.meshes[0].morph_targets[0].positions.len()), (2, 4)); +} + +#[test] +fn images_in_data_uris_count_against_the_data_limit() { + // Six bytes of image, and no buffers. + let doc = json!({ "asset": { "version": "2.0" }, "images": [{ "uri": "data:image/png;base64,AAAAAAAA" }] }); + let glb = glb_container(&serde_json::to_vec(&doc).unwrap(), &[]).unwrap(); + assert_eq!(with(&glb, &|l| l.max_data_bytes = 6).unwrap().images[0].data.as_deref(), Some(&[0u8; 6][..])); + assert!(too(with(&glb, &|l| l.max_data_bytes = 5))); + assert!(too(with(&glb, &|l| l.max_data_bytes = 0))); +} + +#[test] +fn morph_target_limits() { + let glb = morphed(); + assert_eq!(with(&glb, &|l| l.max_morph_targets = 2).unwrap().meshes[0].morph_targets.len(), 2); + // Past the limit the mesh is read in its base shape, and its targets are named. + let s = with(&glb, &|l| l.max_morph_targets = 1).unwrap(); + s.validate().unwrap(); + let m = &s.meshes[0]; + assert!(m.morph_targets.is_empty() && m.morph_weights.is_empty()); + assert_eq!((m.positions.len(), m.triangle_count()), (4, 2)); + assert_eq!(s.warnings, ["1 primitive(s) have more morph targets than the limit allows, which were left out (drawn in the base shape)"]); + // The node's weights have no targets left to move, so they go too. + assert!(s.nodes[0].morph_weights.is_empty()); + + // The offsets count against the data limit, so targets that all name one accessor cannot + // multiply it without bound: 200 targets of 4 vertices are 2,400 values of 8 bytes. + let mut b = B::default(); + let p = b.f32s(&QUAD, "VEC3", 3); + let d = b.f32s(&[0.25; 12], "VEC3", 3); + let targets: Vec = (0..200).map(|_| json!({ "POSITION": d })).collect(); + let many = one_mesh(&b, json!({ "attributes": { "POSITION": p }, "targets": targets })); + assert!(b.bin.len() < 19_200); + // The buffer's own bytes come out of the same limit. + let bin = |glb: &[u8]| split_glb(glb).unwrap().1.unwrap().len(); + let structs = 200 * size_of::(); + let s = with(&many, &|l| l.max_data_bytes = bin(&many) + 19_200 + structs).unwrap(); + assert_eq!((s.meshes[0].morph_targets.len(), s.meshes[0].morph_targets[199].positions[3]), (200, [0.25; 3])); + assert!(too(with(&many, &|l| l.max_data_bytes = bin(&many) + 19_200 + structs - 1))); + // The zero offsets of vertices a target does not move count too: 200 targets that move + // only the second primitive's 3 vertices also hold zeros for the first one's 4, so + // 200 x 7 x 3 values of 8 bytes. + let three = b.f32s(&QUAD[..9], "VEC3", 3); + let d3 = b.f32s(&[0.25; 9], "VEC3", 3); + let unmoved = json!({ "attributes": { "POSITION": p }, "targets": vec![json!({}); 200] }); + let moved = json!({ "attributes": { "POSITION": three }, "targets": vec![json!({ "POSITION": d3 }); 200] }); + let padded = b.glb(json!({ "meshes": [{ "primitives": [unmoved, moved] }] })); + let s = with(&padded, &|l| l.max_data_bytes = bin(&padded) + 33_600 + structs).unwrap(); + assert_eq!(s.meshes[0].morph_targets[0].positions.len(), 7); + assert!(too(with(&padded, &|l| l.max_data_bytes = bin(&padded) + 33_600 + structs - 1))); + // So do the targets themselves, offsets or not: many meshes of empty targets cannot + // allocate without bound. + let empty = json!({ "primitives": [{ "attributes": { "POSITION": p }, "targets": vec![json!({}); 200] }] }); + let meshes = b.glb(json!({ "meshes": vec![empty; 50] })); + assert!(with(&meshes, &|l| l.max_data_bytes = bin(&meshes) + 50 * structs).is_ok()); + assert!(too(with(&meshes, &|l| l.max_data_bytes = bin(&meshes) + 50 * structs - 1))); + // One triangle: its positions and offsets take 72 bytes of buffer, and its target holds + // 9 offsets of 8 bytes, so it needs one target's size plus 144 bytes. + let mut t = B::default(); + let p3 = t.f32s(&QUAD[..9], "VEC3", 3); + let d3 = t.f32s(&[0.25; 9], "VEC3", 3); + let triangle = one_mesh(&t, json!({ "attributes": { "POSITION": p3 }, "targets": [{ "POSITION": d3 }] })); + assert_eq!(bin(&triangle), 72); + let one = size_of::(); + assert!(with(&triangle, &|l| l.max_data_bytes = one + 144).is_ok()); + assert!(too(with(&triangle, &|l| l.max_data_bytes = one + 143))); + // A primitive that is left out (points) does not count towards the mesh's targets. + let three: Vec = (0..3).map(|_| json!({ "POSITION": d })).collect(); + let points = json!({ "attributes": { "POSITION": p }, "mode": 0, "targets": three }); + let one = json!({ "attributes": { "POSITION": p }, "targets": [{ "POSITION": d }] }); + let mixed = b.glb(json!({ "meshes": [{ "primitives": [points, one] }] })); + let s = with(&mixed, &|l| l.max_morph_targets = 1).unwrap(); + assert_eq!(s.meshes[0].morph_targets.len(), 1); + assert_eq!( + s.warnings, + ["1 primitive(s) are points, lines or have no positions and were left out", "1 triangle(s) could not be read and were left out"] + ); + hammer(&glb, &parse); +} + +#[test] +fn extensions_and_extras_are_kept() { + let mut b = B::default(); + let p = b.f32s(&QUAD[..9], "VEC3", 3); + let root = json!({ "VENDOR_avatar": { "bones": [{ "node": 0, "bone": "head" }] }, "KHR_lights_punctual": { "lights": [{ "type": "point", "extras": 1 }] } }); + let node = json!({ "VENDOR_bone": { "stiff": 0.5 }, "KHR_lights_punctual": { "light": 0 } }); + let material = + json!({ "KHR_materials_unlit": {}, "KHR_materials_clearcoat": { "clearcoatFactor": 0.5 }, "VENDOR_toon": { "shade": [0.5, 0.5, 0.5] } }); + let s = parse(&b.glb(json!({ + "extensionsUsed": ["VENDOR_avatar", "KHR_lights_punctual", "KHR_materials_unlit", "KHR_materials_clearcoat", "VENDOR_toon"], + "extensions": root.clone(), + "extras": { "author": "test" }, + "nodes": [{ "mesh": 0, "extensions": node.clone(), "extras": 7 }], + "meshes": [{ "primitives": [{ "attributes": { "POSITION": p }, "material": 0 }], "extensions": { "VENDOR_mesh": {} }, "extras": [1, 2] }], + "materials": [{ "extensions": material.clone(), "extras": "x" }], + }))) + .unwrap(); + // Extensions the reader reads are kept whole as well, with what its fields do not hold + // (the light's extras). + assert_eq!((s.lights.len(), s.nodes[0].light, s.materials[0].unlit, s.materials[0].clearcoat), (1, Some(0), true, 0.5)); + assert_eq!((Value::Object(s.extensions.clone()), s.extras.clone()), (root, Some(json!({ "author": "test" })))); + assert_eq!((Value::Object(s.nodes[0].extensions.clone()), s.nodes[0].extras.clone()), (node, Some(json!(7)))); + assert_eq!((Value::Object(s.meshes[0].extensions.clone()), s.meshes[0].extras.clone()), (json!({ "VENDOR_mesh": {} }), Some(json!([1, 2])))); + let m = &s.materials[0]; + assert_eq!((Value::Object(m.extensions.clone()), m.extras.clone()), (material, Some(json!("x")))); + // An `extensions` that is not an object is passed over. + let s = parse(&b.glb(json!({ "extensions": [1], "meshes": [{ "primitives": [{ "attributes": { "POSITION": p } }] }] }))).unwrap(); + assert!(s.extensions.is_empty() && s.extras.is_none()); +} + #[test] fn strict_uri_decoding_preserves_exact_names_and_rejects_invalid_utf8() { use crate::gltf::uri_decode_strict; diff --git a/crates/mesh/src/tests/gltf_write.rs b/crates/mesh/src/tests/gltf_write.rs new file mode 100644 index 0000000000..cfb69a7e76 --- /dev/null +++ b/crates/mesh/src/tests/gltf_write.rs @@ -0,0 +1,553 @@ +//! The GLB writer's skins, morph targets and extension data, read back with the glTF reader and +//! checked against the rules of the Khronos glTF 2.0 specification. + +use std::cell::Cell; + +use serde_json::{Map, Value, json}; + +use crate::gltf::{Writer, extension_names, glb_container, read, split_glb, write_glb}; +use crate::{Corner, Error, IDENTITY, Image, Limits, Mat4, Material, Mesh, MorphTarget, Node, Part, Scene, Skin, TextureRef, Wrap, no_external}; + +fn parse(bytes: &[u8]) -> crate::Result { + read(bytes, &Limits::default(), &mut no_external) +} + +/// The JSON chunk of a GLB. +fn json_of(glb: &[u8]) -> Value { + serde_json::from_slice(split_glb(glb).unwrap().0).unwrap() +} + +fn object(v: Value) -> Map { + match v { + Value::Object(o) => o, + _ => panic!("not an object"), + } +} + +fn moved(x: f64, y: f64, z: f64) -> Mat4 { + let mut m = IDENTITY; + m[12..15].copy_from_slice(&[x, y, z]); + m +} + +/// A quad skinned to two joints, with three morph targets: `smile` moves every vertex and the +/// normal, `blink` one vertex, and `rest` nothing. +fn rig() -> Scene { + let mesh = Mesh { + name: "Face".into(), + positions: vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]], + normals: vec![[0.0, 0.0, 1.0]], + joints: vec![[0, 1, 0, 0], [0, 1, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]], + weights: vec![[0.75, 0.25, 0.0, 0.0], [0.5, 0.5, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0]], + parts: vec![Part { + material: Some(0), + face_sizes: vec![4], + corners: (0..4).map(|i| Corner { position: i, normal: 0, uv: crate::NONE }).collect(), + ..Part::default() + }], + morph_targets: vec![ + MorphTarget { name: "smile".into(), positions: vec![[0.0, 0.0, 1.0]; 4], normals: vec![[0.5, 0.0, 0.0]], tangents: vec![] }, + MorphTarget { name: "blink".into(), positions: vec![[0.0; 3], [0.0; 3], [0.0; 3], [0.0, -0.25, 0.0]], ..MorphTarget::default() }, + MorphTarget { name: "rest".into(), ..MorphTarget::default() }, + ], + morph_weights: vec![0.25, 0.75, 0.0], + ..Mesh::default() + }; + let mut scene = Scene::from_meshes(vec![mesh, Mesh { name: "empty".into(), ..Mesh::default() }], vec![Material::plain("Skin", [1.0; 4])]); + // 0: the face, skinned, with weights for its first target only. 1: a node whose mesh has no + // triangles, so it is written without a mesh, and so without its skin. + scene.nodes[0].skin = Some(0); + scene.nodes[0].morph_weights = vec![0.5]; + scene.nodes[1].skin = Some(0); + // 2 → 3: the joints. + scene.nodes.push(Node { name: "Hips".into(), transform: moved(0.0, 1.0, 0.0), children: vec![3], ..Node::default() }); + scene.nodes.push(Node { name: "Head".into(), transform: moved(0.0, 0.5, 0.0), ..Node::default() }); + scene.roots = vec![0, 1, 2]; + scene.skins = vec![Skin { name: "Body".into(), joints: vec![2, 3], inverse_bind: vec![moved(0.0, -1.0, 0.0), moved(0.0, -1.5, 0.0)] }]; + scene +} + +/// Every vertex of the mesh's [`Mesh::unified`] triangles, shaped by `weights` as glTF shapes +/// it: the base position and normal plus each target's offset times its weight. +fn shaped(mesh: &Mesh, weights: &[f32]) -> Vec<([f64; 3], [f64; 3])> { + let u = mesh.unified(); + u.corners + .iter() + .map(|c| { + let (mut p, mut n) = (mesh.positions[c.position as usize], mesh.normals[c.normal as usize]); + for (t, w) in mesh.morph_targets.iter().zip(weights) { + let w = f64::from(*w); + let dp = t.positions.get(c.position as usize).copied().unwrap_or_default(); + let dn = t.normals.get(c.normal as usize).copied().unwrap_or_default(); + for ((x, d), (y, e)) in p.iter_mut().zip(dp).zip(n.iter_mut().zip(dn)) { + *x += w * d; + *y += w * e; + } + } + (p, n) + }) + .collect() +} + +/// The joints and weights of every vertex of the mesh's [`Mesh::unified`] triangles. +fn skinning(mesh: &Mesh) -> Vec<([u16; 4], [f32; 4])> { + mesh.unified().corners.iter().map(|c| (mesh.joints[c.position as usize], mesh.weights[c.position as usize])).collect() +} + +#[test] +fn skins_and_morph_targets_read_back() { + let scene = rig(); + let back = parse(&write_glb(&scene, &Limits::default()).unwrap()).unwrap(); + back.validate().unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + assert_eq!(back.skins, scene.skins); + assert_eq!(back.nodes.iter().map(|n| (n.mesh, n.skin)).collect::>(), [(Some(0), Some(0)), (None, None), (None, None), (None, None)]); + let (face, read) = (&scene.meshes[0], &back.meshes[0]); + assert_eq!(skinning(read), skinning(face)); + let names: Vec<&str> = read.morph_targets.iter().map(|t| t.name.as_str()).collect(); + assert_eq!(names, ["smile", "blink", "rest"]); + assert_eq!(read.morph_weights, face.morph_weights); + // A node that sets fewer weights than its mesh has targets takes the mesh's for the rest. + assert_eq!(back.nodes[0].morph_weights, [0.5, 0.75, 0.0]); + assert!(back.nodes[1].morph_weights.is_empty()); + for weights in [&[1.0, 0.0, 0.0][..], &[0.0, 1.0, 0.0], &[0.5, 0.75, 1.0]] { + assert_eq!(shaped(read, weights), shaped(face, weights), "weights {weights:?}"); + } + // Worked out by hand from the offsets in `rig`, with the node's weights. + let p: Vec<[f64; 3]> = shaped(read, &back.nodes[0].morph_weights).into_iter().map(|(p, _)| p).collect(); + assert_eq!(p, [[0.0, 0.0, 0.5], [1.0, 0.0, 0.5], [1.0, 1.0, 0.5], [0.0, 0.8125, 0.5]]); +} + +#[test] +fn written_rigging_follows_the_specification() { + let j = json_of(&write_glb(&rig(), &Limits::default()).unwrap()); + let accessor = |a: &Value| j["accessors"][a.as_u64().unwrap() as usize].clone(); + let mesh = &j["meshes"][0]; + let targets = &mesh["primitives"][0]["targets"]; + assert_eq!(targets.as_array().unwrap().len(), 3); + // Every primitive of a mesh has as many targets as the mesh has weights. + assert!(mesh["primitives"].as_array().unwrap().iter().all(|p| p["targets"] == *targets)); + assert_eq!(mesh["weights"], json!([0.25, 0.75, 0.0])); + assert_eq!(mesh["extras"], json!({ "targetNames": ["smile", "blink", "rest"] })); + // A node's weights are one per target of its mesh; `skin` and `weights` need a `mesh`. + assert_eq!(j["nodes"][0]["weights"], json!([0.5, 0.75, 0.0])); + assert_eq!(j["nodes"][0]["skin"], json!(0)); + for n in j["nodes"].as_array().unwrap() { + assert!(n.get("mesh").is_some() || (n.get("skin").is_none() && n.get("weights").is_none()), "{n}"); + } + // Every target's POSITION accessor carries its bounds. + for t in targets.as_array().unwrap() { + let a = accessor(&t["POSITION"]); + assert!(a.get("min").is_some() && a.get("max").is_some(), "{a}"); + assert_eq!((a["type"].as_str(), a["count"].as_u64()), (Some("VEC3"), Some(4))); + } + let (smile, blink, rest) = (accessor(&targets[0]["POSITION"]), accessor(&targets[1]["POSITION"]), accessor(&targets[2]["POSITION"])); + // A target that moves every vertex is written whole. + assert!(smile.get("bufferView").is_some() && smile.get("sparse").is_none()); + assert!(targets[0].get("NORMAL").is_some() && targets[1].get("NORMAL").is_none()); + // One that moves one vertex names it over zeros; one that moves nothing is only zeros. + assert!(blink.get("bufferView").is_none()); + assert_eq!(blink["sparse"]["count"], json!(1)); + assert_eq!(blink["sparse"]["indices"]["componentType"], json!(5125)); + assert_eq!((blink["min"].clone(), blink["max"].clone()), (json!([0.0, -0.25, 0.0]), json!([0.0, 0.0, 0.0]))); + assert!(rest.get("bufferView").is_none() && rest.get("sparse").is_none()); + assert_eq!((rest["min"].clone(), rest["max"].clone()), (json!([0.0, 0.0, 0.0]), json!([0.0, 0.0, 0.0]))); + // Sparse indices and values have no buffer view target. + for key in ["indices", "values"] { + let view = &j["bufferViews"][blink["sparse"][key]["bufferView"].as_u64().unwrap() as usize]; + assert!(view.get("target").is_none(), "{view}"); + } + // Skinning attributes and the inverse bind matrices. + let attrs = &mesh["primitives"][0]["attributes"]; + let (joints, weights) = (accessor(&attrs["JOINTS_0"]), accessor(&attrs["WEIGHTS_0"])); + assert_eq!((joints["type"].as_str(), joints["componentType"].as_u64()), (Some("VEC4"), Some(5123))); + assert_eq!((weights["type"].as_str(), weights["componentType"].as_u64()), (Some("VEC4"), Some(5126))); + let skin = &j["skins"][0]; + assert_eq!((skin["joints"].clone(), skin["name"].clone()), (json!([2, 3]), json!("Body"))); + let ibm = accessor(&skin["inverseBindMatrices"]); + assert_eq!((ibm["type"].as_str(), ibm["count"].as_u64()), (Some("MAT4"), Some(2))); + let view = &j["bufferViews"][ibm["bufferView"].as_u64().unwrap() as usize]; + assert!(view.get("target").is_none(), "{view}"); +} + +/// [`rig`] with extension data on the file, nodes, meshes and materials, as a VRM file holds it. +fn rig_with_extensions() -> Scene { + let mut s = rig(); + s.extensions = object(json!({ + "VRMC_vrm": { "specVersion": "1.0", "humanoid": { "humanBones": { "hips": { "node": 2 }, "head": { "node": 3 } } } }, + // Lights are read into `Scene::lights`, which the writer does not write. + "KHR_lights_punctual": { "lights": [{ "type": "point" }] }, + })); + s.extras = Some(json!({ "author": "test" })); + s.nodes[3].extensions = object(json!({ "VRMC_node_constraint": { "specVersion": "1.0", "constraint": { "roll": { "source": 2 } } } })); + s.nodes[2].extensions = object(json!({ "KHR_lights_punctual": { "light": 0 } })); + s.nodes[2].extras = Some(json!(["kept"])); + s.meshes[0].extras = Some(json!({ "kind": "face", "targetNames": ["old"] })); + s.meshes[0].extensions = object(json!({ "EXAMPLE_mesh": { "level": 2 } })); + s.images = vec![ + Image { name: "skin".into(), data: Some(b"\x89PNG skin".to_vec()), ..Image::default() }, + Image { name: "shade".into(), data: Some(b"\x89PNG shade".to_vec()), ..Image::default() }, + ]; + // The file's textures, in its order: the extension data names them by index. + s.texture_variants = + vec![TextureRef { image: 0, wrap: [Wrap::Clamp; 2], ..TextureRef::default() }, TextureRef { image: 1, ..TextureRef::default() }]; + let m = &mut s.materials[0]; + m.base_color_texture = Some(TextureRef { image: 1, ..TextureRef::default() }); + // The unlit extension is read into `Material::unlit`, which says it is not unlit. + m.extensions = object(json!({ + "VRMC_materials_mtoon": { + "specVersion": "1.0", + "shadeMultiplyTexture": { "index": 0, "extensions": { "KHR_texture_transform": { "scale": [2.0, 2.0] } } }, + }, + "KHR_materials_unlit": {}, + })); + m.extras = Some(json!({ "note": 1 })); + s +} + +#[test] +fn extension_data_is_written_and_listed() { + let scene = rig_with_extensions(); + let glb = write_glb(&scene, &Limits::default()).unwrap(); + let j = json_of(&glb); + let used: Vec<&str> = j["extensionsUsed"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + for name in ["VRMC_vrm", "VRMC_node_constraint", "VRMC_materials_mtoon", "KHR_texture_transform", "EXAMPLE_mesh"] { + assert!(used.contains(&name), "{name} in {used:?}"); + } + for name in ["KHR_lights_punctual", "KHR_materials_unlit"] { + assert!(!used.contains(&name), "{name} in {used:?}"); + } + assert!(j["extensions"].get("KHR_lights_punctual").is_none() && j["nodes"][2].get("extensions").is_none()); + // The file's textures keep their indices, so the extension data still names the right + // ones, and a material slot that matches one of them uses it. + assert_eq!(j["textures"].as_array().unwrap().len(), 2); + assert_eq!((j["textures"][0]["source"].clone(), j["textures"][1]["source"].clone()), (json!(0), json!(1))); + assert_eq!(j["materials"][0]["pbrMetallicRoughness"]["baseColorTexture"]["index"], json!(1)); + let back = parse(&glb).unwrap(); + back.validate().unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + assert_eq!(Value::Object(back.extensions.clone()), json!({ "VRMC_vrm": scene.extensions["VRMC_vrm"] })); + assert_eq!(back.extras, scene.extras); + assert_eq!(back.nodes[3].extensions, scene.nodes[3].extensions); + assert_eq!((back.nodes[2].extensions.is_empty(), &back.nodes[2].extras), (true, &scene.nodes[2].extras)); + // The names of the targets replace the ones the mesh's extras held. + assert_eq!(back.meshes[0].extras, Some(json!({ "kind": "face", "targetNames": ["smile", "blink", "rest"] }))); + assert_eq!(back.meshes[0].extensions, scene.meshes[0].extensions); + let m = &back.materials[0]; + assert_eq!(Value::Object(m.extensions.clone()), json!({ "VRMC_materials_mtoon": scene.materials[0].extensions["VRMC_materials_mtoon"] })); + assert_eq!((m.unlit, &m.extras), (false, &scene.materials[0].extras)); + assert_eq!(back.texture_variants.iter().map(|t| (t.image, t.wrap)).collect::>(), [(0, [Wrap::Clamp; 2]), (1, [Wrap::Repeat; 2])]); + // Targets without names leave the kept `targetNames` as they are. + let mut s = rig_with_extensions(); + s.meshes[0].morph_targets.iter_mut().for_each(|t| t.name.clear()); + let j = json_of(&write_glb(&s, &Limits::default()).unwrap()); + assert_eq!(j["meshes"][0]["extras"], json!({ "kind": "face", "targetNames": ["old"] })); +} + +/// A name that counts how often it is compared. +struct Counted<'a> { + name: &'a str, + count: &'a Cell, +} + +impl PartialEq for Counted<'_> { + fn eq(&self, other: &Self) -> bool { + self.count.set(self.count.get() + 1); + self.name == other.name + } +} + +impl Eq for Counted<'_> {} + +impl PartialOrd for Counted<'_> { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Counted<'_> { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.count.set(self.count.get() + 1); + self.name.cmp(other.name) + } +} + +/// `n` extensions at the top of the file, each holding an object in an array that uses itself +/// again and one extension every one of them shares, so `3 * n` names are found and `n + 1` differ. +fn many_extensions(n: usize) -> Map { + (0..n) + .map(|i| { + let name = format!("EXT_{i:05}"); + let inner = json!({ "nested": [{ "extensions": { name.clone(): {}, "SHARED": {} } }] }); + (name, inner) + }) + .collect() +} + +// A `Counted` orders by its name only; its counter is not part of the key. +#[allow(clippy::mutable_key_type)] +#[test] +fn many_extension_names_are_listed_once_in_n_log_n_comparisons() { + const N: usize = 5000; + let mut scene = rig(); + scene.extensions = many_extensions(N); + // Extension keys inside the application's extras are not listed. + scene.extras = Some(json!({ "extensions": { "IN_EXTRAS": {} } })); + let j = json_of(&write_glb(&scene, &Limits::default()).unwrap()); + let mut expected: Vec = (0..N).map(|i| format!("EXT_{i:05}")).collect(); + expected.push("SHARED".into()); + assert_eq!(j["extensionsUsed"], json!(expected)); + + let root = Map::from_iter([("extensions".to_string(), Value::Object(many_extensions(N)))]); + let count = Cell::new(0); + let names = extension_names(&root, |name| Counted { name, count: &count }); + assert_eq!(names.len(), N + 1); + // 3 * N insertions into a set of at most N + 1 names: about 13 comparisons each. A search of + // every name found so far takes on the order of N * N. + let limit = 3 * N * 32; + assert!(count.get() <= limit, "{} comparisons for {} names (limit {limit})", count.get(), 3 * N); +} + +#[test] +fn a_texture_left_out_for_want_of_an_image_is_named() { + // The first texture has no image the reader reads, so the second one becomes the first. + let doc = json!({ + "asset": { "version": "2.0" }, + "images": [{ "uri": "a.png" }], + "textures": [{ "extensions": { "EXAMPLE_texture": { "source": 0 } } }, { "source": 0 }], + "extensions": { "EXAMPLE_root": { "texture": 1 } }, + }); + let s = parse(&glb_container(&serde_json::to_vec(&doc).unwrap(), &[]).unwrap()).unwrap(); + assert_eq!(s.texture_variants.len(), 1); + assert_eq!(s.warnings, ["1 texture(s) have no image that is read and were left out; the textures after them are numbered from one less"]); +} + +#[test] +fn a_texture_of_a_webp_image_names_it_through_the_extension() { + let webp = b"RIFF\x04\x00\x00\x00WEBPVP8 ".to_vec(); + let mut s = rig(); + s.images = vec![Image { data: Some(webp.clone()), ..Image::default() }, Image { uri: Some("b.WEBP?v=1#top".into()), ..Image::default() }]; + // The first texture is the file's and no material uses it; the second a material's. + s.texture_variants = vec![TextureRef::default()]; + s.materials[0].base_color_texture = Some(TextureRef { image: 1, ..TextureRef::default() }); + let glb = write_glb(&s, &Limits::default()).unwrap(); + let j = json_of(&glb); + assert_eq!(j["images"][0]["mimeType"], json!("image/webp")); + for (k, image) in [(0, 0), (1, 1)] { + let t = &j["textures"][k]; + assert!(t.get("source").is_none(), "{t}"); + assert_eq!(t["extensions"]["EXT_texture_webp"]["source"], json!(image)); + } + assert_eq!(j["extensionsRequired"], json!(["EXT_texture_webp"])); + assert!(j["extensionsUsed"].as_array().unwrap().contains(&json!("EXT_texture_webp"))); + let back = parse(&glb).unwrap(); + assert_eq!(back.texture_variants.iter().map(|t| t.image).collect::>(), [0, 1]); + assert_eq!(back.materials[0].base_color_texture.map(|t| t.image), Some(1)); + assert_eq!(back.images[0].data.as_deref(), Some(&webp[..])); + // Without a WebP image nothing is required. + assert!(json_of(&write_glb(&rig(), &Limits::default()).unwrap()).get("extensionsRequired").is_none()); +} + +#[test] +fn a_named_image_keeps_its_media_type() { + // The URI has no extension, so only the media type says the image is WebP. + let mut s = rig(); + s.images = vec![Image { uri: Some("asset?id=42".into()), mime_type: Some("image/webp".into()), ..Image::default() }]; + s.materials[0].base_color_texture = Some(TextureRef::default()); + let first = write_glb(&s, &Limits::default()).unwrap(); + let j = json_of(&first); + assert_eq!((j["images"][0]["uri"].clone(), j["images"][0]["mimeType"].clone()), (json!("asset?id=42"), json!("image/webp"))); + let back = parse(&first).unwrap(); + assert_eq!(back.images[0].mime_type.as_deref(), Some("image/webp")); + let second = json_of(&write_glb(&back, &Limits::default()).unwrap()); + assert_eq!(second["textures"][0]["extensions"]["EXT_texture_webp"]["source"], json!(0)); + assert_eq!(second, j); + // A named image of no known type is written without one. + s.images[0].mime_type = None; + assert!(json_of(&write_glb(&s, &Limits::default()).unwrap())["images"][0].get("mimeType").is_none()); +} + +#[test] +fn texture_slots_use_the_first_of_the_files_textures_that_match() { + let mut s = rig_with_extensions(); + // The file holds the same texture three times; a material slot that matches uses the first. + s.texture_variants = vec![TextureRef { image: 0, ..TextureRef::default() }, TextureRef { image: 1, ..TextureRef::default() }]; + s.texture_variants.extend([TextureRef { image: 1, ..TextureRef::default() }; 2]); + let j = json_of(&write_glb(&s, &Limits::default()).unwrap()); + assert_eq!(j["textures"].as_array().unwrap().len(), 4); + assert_eq!(j["materials"][0]["pbrMetallicRoughness"]["baseColorTexture"]["index"], json!(1)); + // A slot that matches none of them adds one texture, which the next such slot uses again. + s.materials[0].normal_texture = Some(TextureRef { image: 1, wrap: [Wrap::Mirror; 2], ..TextureRef::default() }); + s.materials[0].emissive_texture = s.materials[0].normal_texture; + let j = json_of(&write_glb(&s, &Limits::default()).unwrap()); + assert_eq!(j["textures"].as_array().unwrap().len(), 5); + assert_eq!((j["materials"][0]["normalTexture"]["index"].clone(), j["materials"][0]["emissiveTexture"]["index"].clone()), (json!(4), json!(4))); +} + +#[test] +fn parts_with_and_without_normals_are_written_over_their_own_vertices() { + // A triangle without normals next to the quad, which has normals and a target that moves them. + let mut s = rig(); + let corners = (0..3).map(|i| Corner { position: i, normal: crate::NONE, uv: crate::NONE }).collect(); + s.meshes[0].parts.push(Part { material: Some(0), face_sizes: vec![3], corners, ..Part::default() }); + let glb = write_glb(&s, &Limits::default()).unwrap(); + let j = json_of(&glb); + let primitives = j["meshes"][0]["primitives"].as_array().unwrap(); + assert_eq!(primitives.len(), 2); + assert!(primitives[0]["attributes"].get("NORMAL").is_some() && primitives[0]["targets"][0].get("NORMAL").is_some()); + assert!(primitives[1]["attributes"].get("NORMAL").is_none() && primitives[1]["targets"][0].get("NORMAL").is_none()); + let back = parse(&glb).unwrap(); + back.validate().unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + let read = &back.meshes[0]; + assert!(read.parts[0].corners.iter().all(|c| c.normal != crate::NONE)); + assert!(read.parts[1].corners.iter().all(|c| c.normal == crate::NONE)); + // The quad moves as it did without the triangle. + let quad = |m: &Mesh| Mesh { parts: vec![m.parts[0].clone()], ..m.clone() }; + assert_eq!(skinning(&quad(read)), skinning(&quad(&s.meshes[0]))); + for weights in [&[1.0, 0.0, 0.0][..], &[0.5, 0.75, 1.0]] { + assert_eq!(shaped(&quad(read), weights), shaped(&quad(&s.meshes[0]), weights), "weights {weights:?}"); + } +} + +#[test] +fn writing_a_written_file_again_gives_the_same_bytes() { + let first = write_glb(&rig_with_extensions(), &Limits::default()).unwrap(); + let second = write_glb(&parse(&first).unwrap(), &Limits::default()).unwrap(); + assert_eq!(json_of(&second), json_of(&first)); + assert_eq!(second, first); +} + +#[test] +fn writer_refuses_rigging_that_is_not_gltf() { + let limits = Limits::default(); + let refused = |s: &Scene| matches!(write_glb(s, &limits), Err(Error::Malformed(_))); + let mut s = rig(); + s.meshes[0].morph_targets[1].positions[3][1] = f64::NAN; + assert!(refused(&s), "an offset that is not finite"); + let mut s = rig(); + s.meshes[0].morph_targets[0].normals[0][0] = f64::INFINITY; + assert!(refused(&s), "a normal offset that is not finite"); + let mut s = rig(); + s.meshes[0].morph_weights[0] = f32::NAN; + assert!(refused(&s), "a mesh weight that is not finite"); + let mut s = rig(); + s.nodes[0].morph_weights[0] = f32::INFINITY; + assert!(refused(&s), "a node weight that is not finite"); + let mut s = rig(); + s.nodes[0].morph_weights = vec![0.5; 4]; + assert!(refused(&s), "more node weights than targets"); + let mut s = rig(); + s.nodes[1].morph_weights = vec![1.0]; + assert!(refused(&s), "node weights for a mesh without targets"); + let mut s = rig(); + s.meshes[0].weights[2][0] = f32::NAN; + assert!(refused(&s), "a skin weight that is not finite"); + let mut s = rig(); + s.skins[0].inverse_bind[1][13] = f64::NAN; + assert!(refused(&s), "an inverse bind matrix that is not finite"); + let mut s = rig(); + s.skins[0].inverse_bind.pop(); + assert!(refused(&s), "fewer inverse bind matrices than joints"); + let mut s = rig(); + s.skins[0].joints.clear(); + s.skins[0].inverse_bind.clear(); + assert!(refused(&s), "a skin without joints"); + let mut s = rig(); + s.meshes[0].weights.clear(); + assert!(refused(&s), "joints without weights"); + let mut s = rig(); + s.meshes[0].joints.clear(); + assert!(refused(&s), "weights without joints"); + let mut s = rig(); + s.meshes[0].weights[0] = [-0.25, 1.25, 0.0, 0.0]; + assert!(refused(&s), "a negative skinning weight"); + let mut s = rig(); + s.meshes[0].joints[0] = [0; 4]; + assert!(refused(&s), "a joint named twice with weights other than 0"); + let mut s = rig(); + s.meshes[0].joints[1] = [0, 1, 0, 1]; + s.meshes[0].weights[1] = [0.5, 0.25, 0.0, 0.25]; + assert!(refused(&s), "a joint named twice in slots that are not next to each other"); + let mut s = rig(); + s.skins[0].joints = vec![2, 2]; + assert!(refused(&s), "a joint node named twice in a skin"); + let mut s = rig(); + s.skins[0].inverse_bind[0][3] = 1.0; + assert!(refused(&s), "an inverse bind matrix whose last row is not 0, 0, 0, 1"); + let mut s = rig(); + s.meshes[0].joints.clear(); + s.meshes[0].weights.clear(); + assert!(refused(&s), "a skin on a written mesh without joints and weights"); + // `rig` names joint 0 again in the slots whose weight is 0, which glTF allows. + assert!(rig().meshes[0].joints[0][2..] == [0, 0] && write_glb(&rig(), &limits).is_ok()); + let mut s = rig(); + s.meshes[0].joints[3][1] = 2; + assert!(refused(&s), "a joint the node's skin does not have"); + // A position no triangle uses is not written, so its joints are not checked. + let mut u = rig(); + let face = &mut u.meshes[0]; + face.positions.push([5.0; 3]); + face.joints.push([7, 0, 0, 0]); + face.weights.push([1.0, 0.0, 0.0, 0.0]); + face.morph_targets[0].positions.push([0.0; 3]); + face.morph_targets[1].positions.push([0.0; 3]); + assert!(write_glb(&u, &limits).is_ok()); + // The same mesh under a node without a skin is not checked against one. + s.nodes[0].skin = None; + assert!(write_glb(&s, &limits).is_ok()); + // A skin without inverse bind matrices has identity ones, and none are written. + let mut s = rig(); + s.skins[0].inverse_bind.clear(); + let glb = write_glb(&s, &limits).unwrap(); + assert!(json_of(&glb)["skins"][0].get("inverseBindMatrices").is_none()); + assert_eq!(parse(&glb).unwrap().skins, s.skins); + // The skinning and morph target data count against the data limit like everything else in + // the binary chunk (which is padded to 4 bytes). + let glb = write_glb(&rig(), &limits).unwrap(); + let bin = split_glb(&glb).unwrap().1.unwrap().len(); + assert!(write_glb(&rig(), &Limits { max_data_bytes: bin, ..Limits::default() }).is_ok()); + assert!(matches!(write_glb(&rig(), &Limits { max_data_bytes: bin - 4, ..Limits::default() }), Err(Error::TooLarge(_)))); +} + +#[test] +fn the_data_limit_stops_the_writer_before_the_binary_chunk_passes_it() { + // 1,024 vertices and 64 targets that move each of them: 12 KiB of positions and 768 KiB of + // target offsets. + let mut mesh = rig().meshes.swap_remove(0); + let n = 1024u32; + mesh.positions = (0..n).map(|i| [f64::from(i), 0.0, 0.0]).collect(); + mesh.normals.clear(); + mesh.joints.clear(); + mesh.weights.clear(); + mesh.parts[0].face_sizes = vec![3; n as usize / 3]; + mesh.parts[0].corners = (0..n / 3 * 3).map(|i| Corner { position: i, normal: crate::NONE, uv: crate::NONE }).collect(); + mesh.morph_targets = (0..64).map(|_| MorphTarget { positions: vec![[0.0, 0.0, 1.0]; n as usize], ..MorphTarget::default() }).collect(); + mesh.morph_weights.clear(); + let limits = Limits { max_data_bytes: 64 * 1024, ..Limits::default() }; + let mut w = Writer::new(&limits); + assert!(matches!(w.mesh(&mesh), Err(Error::TooLarge(_)))); + assert!(w.bin.len() <= limits.max_data_bytes, "{} bytes written past a limit of {}", w.bin.len(), limits.max_data_bytes); + // The limit holds for sparse accessors too: each target now moves one vertex in four, 4 KiB + // of sparse indices and values a target. + for t in &mut mesh.morph_targets { + t.positions.iter_mut().enumerate().filter(|(i, _)| i % 4 != 0).for_each(|(_, p)| *p = [0.0; 3]); + } + let mut w = Writer::new(&limits); + assert!(matches!(w.mesh(&mesh), Err(Error::TooLarge(_)))); + assert!(w.bin.len() <= limits.max_data_bytes, "{} bytes written past a limit of {}", w.bin.len(), limits.max_data_bytes); + assert!(w.accessors.iter().any(|a| a.get("sparse").is_some())); + // A mesh with more morph targets than the reader reads is refused before any target is + // written: only the POSITION accessor is. + let limits = Limits { max_morph_targets: 63, ..Limits::default() }; + let mut w = Writer::new(&limits); + assert!(matches!(w.mesh(&mesh), Err(Error::TooLarge(_)))); + assert_eq!(w.accessors.len(), 1); + let mut scene = rig(); + scene.meshes[0] = mesh; + scene.nodes[0].morph_weights.clear(); + scene.nodes[0].skin = None; + scene.nodes[1].skin = None; + assert!(write_glb(&scene, &Limits { max_morph_targets: 64, ..Limits::default() }).is_ok()); + assert!(matches!(write_glb(&scene, &limits), Err(Error::TooLarge(_)))); +} diff --git a/crates/pbr/Cargo.toml b/crates/pbr/Cargo.toml index d76a902ce7..654a7c93b8 100644 --- a/crates/pbr/Cargo.toml +++ b/crates/pbr/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-pbr" -description = "Image-based lighting for physically based rendering: equirect environments, a GGX-prefiltered specular chain and SH9 diffuse irradiance" +description = "Image-based lighting for physically based rendering: equirect environments, a GGX-prefiltered specular chain, SH9 diffuse irradiance and the metallic-roughness BRDF" version.workspace = true edition.workspace = true license.workspace = true @@ -23,4 +23,6 @@ thiserror = { workspace = true } craft-pbr = { path = ".", features = ["parallel"] } # The differential tests run verbatim copies of the apps' previous code, which uses glam and rayon. glam = "0.30" +# Parses and validates the WGSL text of `SHADE_WGSL`. +naga = { version = "30.0.1", features = ["wgsl-in"] } rayon = { workspace = true } diff --git a/crates/pbr/README.md b/crates/pbr/README.md index 000df64468..6a531206d0 100644 --- a/crates/pbr/README.md +++ b/crates/pbr/README.md @@ -3,8 +3,9 @@ Image-based lighting for physically based rendering, computed on the CPU. An `EnvImage` is a linear RGB equirect (latitude-longitude) environment, row-major with the top row first. The crate turns it into a GGX-prefiltered chain for specular light and nine spherical-harmonics coefficients for -diffuse light, and renders six procedural environments with no image assets. It has no UI, does no -file or network I/O and has no `unsafe` code. +diffuse light, and renders six procedural environments with no image assets. It also evaluates the +glTF 2.0 metallic-roughness BRDF for direct light and the environment BRDF term of the split sum. +It has no UI, does no file or network I/O and has no `unsafe` code. - **Frame.** +Y is up. Column `u = φ / 2π` and row `v = θ / π` map to the direction `(sin θ cos φ, cos θ, sin θ sin φ)`: row 0 is straight up, `u = 0` points to +X and `u` increases @@ -34,8 +35,59 @@ file or network I/O and has no `unsafe` code. `ggx_distribution_between` evaluates it between a normal and a half vector, taking `(n·h)²` and `|n × h|²` from the vectors in `f64`, so it stays exact where `n·h` is close to 1. Samples read a box-filtered pyramid of the source at a level chosen from each sample's density plus `lod_bias` (default 1). `firefly_cap` caps source radiance before - filtering when set (default off); level 0 is never capped. The environment BRDF term of the - split sum is not in this crate. + filtering when set (default off); level 0 is never capped. +- **Environment BRDF.** `try_environment_brdf(n_dot_v, roughness)` returns the `[scale, bias]` of + the split sum's second term: specular light is a prefiltered level's radiance times + `f0 × scale + bias`. The values are Karis's analytic fit for mobile + (), with `scale` and + `bias` kept at least 0 and their sum at most 1. `n_dot_v` is clamped to `0..=1`. +- **Direct light.** `Material::try_new(base_color, metallic, roughness)` takes linear base color, + metallic and perceptual roughness, each from 0 to 1 as glTF 2.0 defines them, and + `try_with_weights(specular, diffuse)` sets two weights for direct light: `specular` (0 to + `MAX_SPECULAR`, 25) scales the dielectric reflectance at normal incidence, 0.04, and `diffuse` + (0 to 1) scales the diffuse lobe. Both are 1 for a glTF material. Other values, NaN and + infinity give `PbrError::BadMaterial`. `try_direct(n, v, l)` returns the BRDF times `n·l` times + π, the fraction of a light's irradiance reflected toward the viewer, per RGB channel. The BRDF + is the final form of glTF 2.0 section B.3.5 + (): + `f0` is 0.04 mixed toward the base color by metallic, `F` is Schlick's approximation at `v·h` + (section B.3.4), the diffuse lobe is `(1 − F) (1 − metallic) base / π`, and the specular lobe + is `F D V`, with the `D` of `ggx_distribution_between` from the normal and the half vector and + the visibility `V = G / (4 (n·v) (n·l))`. + - `Material::with_visibility` selects the geometry term, a `Visibility`: + - `SmithSchlick`, the default and EffectCraft's term: the Smith-Schlick `G` with + `k = (roughness + 1)² / 8`, which Karis gives for analytic lights in the 2013 notes above. + - `SmithSeparable`: the `V` of section B.3.2, from the separable form of the Smith + masking-shadowing function. + - `SmithHeightCorrelated`: the height-correlated Smith form for GGX of Heitz, *Understanding + the Masking-Shadowing Function in Microfacet-Based BRDFs* (JCGT 2014, + ), which section B.3.2 cites for its formulas. + TextureCraft's mesh shader uses this form. + + The Smith-Schlick term equals the separable form at roughness 1; on smoother surfaces it is + darker at grazing angles (below half of the separable form with roughness 0.25 and the view + and light both about 84 degrees from the normal). The height-correlated form is at least as + bright as the separable one. The visibility affects `try_direct` only. + - Roughness is shaded as at least `MIN_DIRECT_ROUGHNESS` (0.032, `α` = 0.001024). + - `n·v` is taken as at least `1e-4`, so a view at or below the surface sees it as at a + grazing angle. `D` is exact where `n·h` is close to 1, so the highlight peaks at its head-on + value. `D` is 0 where `n·h` is 0 or less, which happens when the view is at least as far + below the surface as the light is above it. + - With `SmithSchlick`, the specular denominator `4 (n·v) (n·l)` is taken as at least `1e-4`, + as in EffectCraft. Where the product is smaller, at grazing angles, the specular lobe is below + `F D G / (4 (n·v) (n·l))`: about 4% of it with `n·v` and `n·l` both 0.001. The other two + forms divide by no such product and have no floor. + - A light at or below the surface, or a view straight opposite the light, gives + 0. Directions are normalized; one that is not finite or has zero length gives + `PbrError::BadDirection`. + - A white metal reflects at most the light it receives, with each geometry term. As section + B.3.6.3 notes, the Fresnel coupling of the two lobes does not conserve energy: with + `SmithSchlick`, a smooth white dielectric seen about 80 degrees from the normal reflects about 9.8% more light than it + receives. +- **Default environment.** `default_environment()` is an 8 × 4 gray studio gradient for an + environment light that has no image: radiance proportional to `0.15 + 1.2 max(0, d·key)` with + the key `(0.66, 0.75, 0)`, up and toward +X, scaled to a mean of 0.3 over the pixels weighted + by `sin θ` at their centers. - **Diffuse.** `try_sh9` projects every pixel of the source onto the nine real SH basis functions of `sh_basis`, each integrated over the area of each pixel. The coefficients are convolved with the clamped cosine lobe (band factors `π`, `2π/3`, `π/4`, Ramamoorthi and Hanrahan 2001, @@ -61,6 +113,80 @@ file or network I/O and has no `unsafe` code. On a 256 × 128 source, the default `try_prefilter` evaluates 1,396,736 samples (10,912 output pixels in levels 1 to 5, 128 samples each). +## WGSL + +`SHADE_WGSL` is the WGSL text of the shading functions (`src/shade.wgsl`). It declares no +bindings and no entry points, and every name in it starts with `pbr_`, `PBR_` or `Pbr`. An app +joins its own declarations, the text and its entry points into one module: + +```rust +let source = [APP_BINDINGS, craft_pbr::SHADE_WGSL, APP_ENTRY_POINTS].join("\n"); +``` + +and passes `source` to its shader compiler (with wgpu, `wgpu::ShaderSource::Wgsl(source.into())`). +The crate does not depend on wgpu or naga in its build. + +- **Values.** `Material::gpu()` returns a `GpuMaterial`, laid out as the WGSL struct + `PbrMaterial` (32 bytes: `base_color` at 0, `metallic` at 12, `roughness` at 16, `specular` at + 20, `diffuse` at 24). `GpuSh9::try_new` takes the coefficients of `try_sh9` and lays them out as + `PbrSh9` (144 bytes, one `vec4` per coefficient). `to_bytes` on either returns the + little-endian bytes for a uniform or storage buffer. `GpuSh9::try_new` returns + `PbrError::BadOption` for a coefficient that is not finite or whose magnitude is over + `GpuSh9::MAX_COEFFICIENT` (1e30), which keeps the `f32` sum of `pbr_irradiance` finite. Every + result of `try_sh9` is accepted. +- **Bounds.** No function loops or recurses. The GPU cannot return an error, so where the Rust + function returns one, the WGSL function returns a defined value: `pbr_direct` and + `pbr_environment_light` clamp material values to the ranges `Material::try_new` and + `try_with_weights` accept, a zero-length direction gives 0, and `pbr_environment_brdf` clamps + roughness to 0 to 1. WGSL implementations may assume that values are finite, so an app uploads + only checked values: a `GpuMaterial` comes from a checked `Material`. +- **Output.** Colors are linear. The text has no display encoding. + +| Rust | WGSL | Notes | +|------|------|-------| +| `Material::try_new` | `pbr_material_clamped` | Clamps to the ranges the Rust constructors check, including `try_with_weights`. | +| `Material::f0` | `pbr_f0` | Same formula. | +| `Material::try_direct` | `pbr_direct` | Same floors: roughness at least 0.032, `n·v` at least `1e-4`, `n·h` at most 1 and `4 (n·v) (n·l)` at least `1e-4`. A light at or below the surface or a view straight opposite the light gives 0 in both. A zero-length direction gives 0 instead of an error, material values are clamped instead of checked, and `D` is evaluated in `f32` by `pbr_ggx_distribution`. | +| `fresnel_schlick` | `pbr_fresnel_schlick` | Same formula. | +| `smith_schlick_ggx` | `pbr_smith_schlick_ggx` | Same formula. | +| `ggx_distribution` | `pbr_ggx_distribution` | Same `α` floor, in `f32`; `(n·h)² (α² − 1) + 1` is computed as `(1 − n·h)(1 + n·h) + (n·h)² α²`. | +| `try_environment_brdf` | `pbr_environment_brdf` | Same fit and clamps; roughness is clamped instead of checked. | +| `dir_of` | `pbr_dir_of` | Same frame. | +| `uv_of` | `pbr_uv_of` | Same frame; a direction straight up or down has `u = 0`, as `atan2(0, 0)` gives in Rust. | +| `sh_basis` | `pbr_sh_basis` | Same basis; a zero-length direction gives nine zeros. | +| `irradiance` | `pbr_irradiance` | Sums in `f32` instead of `f64`. | +| `unit` | `pbr_unit` | Scales by the largest component first, as the Rust helper does; a zero-length direction gives the zero vector. | + +Two WGSL functions have no Rust counterpart in this crate. `pbr_specular_levels(roughness, +levels)` returns the two levels of a `try_prefilter` chain to blend and the weight of the second. +`pbr_environment_light` combines irradiance, prefiltered radiance and `pbr_environment_brdf` by +the split sum, as EffectCraft's `shade.rs` does on the CPU. + +The functions come from EffectCraft's `crates/gpu/src/shaders/advanced3d.wgsl` (at EffectCraft +`f4d45dfe`), which ports `shade.rs`. Changes from that shader: + +- The direct roughness floor is 0.032 instead of 0.03, a view straight opposite the light gives 0 + instead of a fallback half vector, `n·h` is taken as at most 1 as well as at least 0, and the + environment BRDF keeps `scale` and `bias` at least 0 with a sum of at most 1, as in the Rust + functions (see Origin). +- A zero-length direction gives 0. EffectCraft's `norm3` replaced it with `(0, 0, −1)`. +- Material values are clamped to the Rust ranges. EffectCraft clamped roughness to 0.03 to 1 and + read base color, metallic, specular and diffuse unchecked. +- `D` computes its inner term as `(1 − n·h)(1 + n·h) + (n·h)² α²` with an `α` floor of 0.001 and + a denominator of at least `f32::MIN_POSITIVE`. EffectCraft computed `(n·h)² (α² − 1) + 1`, + which loses precision in `f32` near `n·h = 1` for small `α`, with a denominator of at least + `1e-12` and no `α` floor. +- Fresnel raises `1 − v·h` to the fifth power by multiplication instead of `pow`. +- The equirect mapping is in this crate's frame. For EffectCraft's frame, a direction + `(x, y, z)` there is `(−z, −y, −x)` here, which gives the same `v` and the same `u` before + EffectCraft adds its rotation. +- EffectCraft's `srgb_to_linear` is not carried: the shader does not call it. + +Texture sampling, shadow maps, light attenuation and the unpacking of EffectCraft's buffers stay +in EffectCraft: they read its own bindings and packed layouts. The tests parse and validate the +text with naga, alone and with app bindings and `vs` and `fs` entry points, and check the +`PbrMaterial` and `PbrSh9` layouts against `to_bytes`. They do not run the WGSL on a GPU. + ## Origin The algorithms come from the `crates/render/src/ibl.rs` files of TextureCraft and MaterialCraft, @@ -85,6 +211,31 @@ they are tall. Changes from those files: rows (3.2e-4 on 64). - Rows run on several threads only with the `parallel` feature. +The BRDF, the environment BRDF and the default environment come from EffectCraft's +`crates/render/src/three_d/adv/shade.rs` and `adv/scene.rs`. Changes from those files: + +- Material values, weights and directions are checked; NaN, infinity, values out of range and + zero-length directions give an error instead of a NaN or negative color. Directions are + normalized. +- The distribution is `ggx_distribution_between`, evaluated in `f64` from the normal and the half + vector. EffectCraft evaluated it in `f32` from `n·h`, which loses the narrow peak of smooth + surfaces. From roughness 0.25 up, with the view and the light above the surface, the direct + light matches within `1e-4` of `max(1, value)`. +- Roughness is shaded as at least 0.032 instead of 0.03, so `α` stays above the 0.001 floor of + `ggx_distribution`. +- A view straight opposite the light gives 0 instead of using a fallback half vector. +- `D` is 0 where `n·h` is 0 or less, a view at least as far below the surface as the light is + above it, so such a view sees no specular lobe. EffectCraft took `n·h` as at least 0 there and + gave `D` its value at `n·h` = 0, `α² / π`. EffectCraft also did not keep `n·h` at most 1, so + rounding after normalization could put `D` above its peak. +- The environment BRDF keeps `scale` and `bias` at least 0 with a sum of at most 1. The fit gives + a negative scale for smooth surfaces at grazing angles (-0.044 with a bias of 1.044 at + `n·v` = 0 and roughness 0), which made `f0 × scale + bias` greater than 1 and the diffuse + weight `1 − fs` negative, and a negative bias of -0.0024 for rough surfaces at grazing angles. +- The default environment is in this crate's frame. An EffectCraft direction `(x, y, z)`, with +Y + down and the image center at +Z, is `(−z, −y, −x)` here, so the key `(0, −0.75, −0.66)` + becomes `(0.66, 0.75, 0)` and the pixels are the same within `1e-6`. + ## Migration - **TextureCraft.** Replace `texturecraft_render::ibl` with `craft_pbr`. Pass @@ -99,3 +250,8 @@ they are tall. Changes from those files: - **MaterialCraft.** Replace `materialcraft_render::ibl` with `craft_pbr`, with the same `firefly_cap`. `by_id` stays in the app and maps view ids to `Environment::from_name`. `hammersley` returns `None` when `i` is not below `n`. +- **EffectCraft.** Replace `shade::brdf` with `Material::try_new(...)?.try_with_weights(specular_k, + diffuse_k)?.try_direct(n, v, l)`, and `shade::env_brdf` with `try_environment_brdf`. The + adapter keeps layer policy, texture sampling, lights, shadows and its box-filtered environment + chain, and maps a material error to a render failure. `default_environment` replaces + `scene::default_environment` once the adapter converts directions to this crate's frame. diff --git a/crates/pbr/src/brdf.rs b/crates/pbr/src/brdf.rs new file mode 100644 index 0000000000..44efb9fae4 --- /dev/null +++ b/crates/pbr/src/brdf.rs @@ -0,0 +1,232 @@ +//! The metallic-roughness BRDF for direct light and the environment BRDF term of the split sum. + +use std::f32::consts::PI; + +use crate::PbrError; +use crate::prefilter::ggx_distribution_between; +use crate::vec3::unit; + +/// The smallest roughness direct light is shaded with. Smaller values, 0 included, are shaded as +/// this one, so a point light keeps a highlight of finite height. Its `α = roughness²` of +/// 0.001024 is above the `α` floor of [`ggx_distribution`](crate::ggx_distribution). +pub const MIN_DIRECT_ROUGHNESS: f32 = 0.032; + +/// Largest [`Material::specular`] weight: at 25 the dielectric reflectance at normal incidence, +/// `0.04 × specular`, is 1. +pub const MAX_SPECULAR: f32 = 25.0; + +/// The smallest `n·v` the direct BRDF divides by. A view at or below the surface is shaded as +/// a view at this cosine. +const MIN_N_DOT_V: f32 = 1e-4; + +/// The geometry term of the specular lobe in [`Material::try_direct`]. Each form uses +/// `α = roughness²` with roughness at least [`MIN_DIRECT_ROUGHNESS`]. The environment BRDF of +/// [`try_environment_brdf`] does not depend on it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum Visibility { + /// EffectCraft's term, the default: the Smith-Schlick `G` with `k = (roughness + 1)² / 8` + /// that Karis gives for analytic lights in *Real Shading in Unreal Engine 4* + /// (), + /// divided by `4 (n·v) (n·l)` taken as at least `1e-4`. It equals + /// [`SmithSeparable`](Visibility::SmithSeparable) at roughness 1 and is darker at grazing + /// angles on smoother surfaces. + #[default] + SmithSchlick, + /// The visibility of glTF 2.0 section B.3.2 + /// (), from the + /// separable form of the Smith masking-shadowing function: + /// `V = 1 / ((n·l + √(α² + (1 − α²) (n·l)²)) (n·v + √(α² + (1 − α²) (n·v)²)))`. + SmithSeparable, + /// The height-correlated Smith masking-shadowing function for GGX of Heitz, *Understanding + /// the Masking-Shadowing Function in Microfacet-Based BRDFs* (JCGT 2014, + /// ), which section B.3.2 cites for the derivation: + /// `V = 0.5 / (n·l √((n·v)² (1 − α²) + α²) + n·v √((n·l)² (1 − α²) + α²))`. TextureCraft's + /// mesh shader uses this form. + SmithHeightCorrelated, +} + +/// A metallic-roughness material: linear base color, metallic and perceptual roughness, each in +/// `0..=1` as glTF 2.0 defines them, and two weights for direct light. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Material { + base_color: [f32; 3], + metallic: f32, + roughness: f32, + specular: f32, + diffuse: f32, + visibility: Visibility, +} + +/// Checks that `v` is finite and in `lo..=hi`. +fn in_range(v: f32, lo: f32, hi: f32, what: &'static str) -> Result { + if v.is_finite() && (lo..=hi).contains(&v) { Ok(v) } else { Err(PbrError::BadMaterial(what)) } +} + +impl Material { + /// A material with specular and diffuse weights of 1 and the default [`Visibility`], + /// [`Visibility::SmithSchlick`]. Returns [`PbrError::BadMaterial`] when a base color channel, + /// `metallic` or `roughness` is not a number in `0..=1`. + pub fn try_new(base_color: [f32; 3], metallic: f32, roughness: f32) -> Result { + for c in base_color { + in_range(c, 0.0, 1.0, "a base color channel is not a number from 0 to 1")?; + } + Ok(Material { + base_color, + metallic: in_range(metallic, 0.0, 1.0, "the metallic value is not a number from 0 to 1")?, + roughness: in_range(roughness, 0.0, 1.0, "the roughness is not a number from 0 to 1")?, + specular: 1.0, + diffuse: 1.0, + visibility: Visibility::default(), + }) + } + + /// The material with this geometry term for direct light. + pub fn with_visibility(self, visibility: Visibility) -> Material { + Material { visibility, ..self } + } + + /// The material with these weights. `specular` scales the dielectric reflectance at normal + /// incidence, 0.04 at 1, and is a number from 0 to [`MAX_SPECULAR`]. `diffuse` scales the + /// diffuse lobe and is a number from 0 to 1. Returns [`PbrError::BadMaterial`] otherwise. + /// glTF 2.0 has neither weight; both are 1 for a glTF material. + pub fn try_with_weights(self, specular: f32, diffuse: f32) -> Result { + Ok(Material { + specular: in_range(specular, 0.0, MAX_SPECULAR, "the specular weight is not a number from 0 to 25")?, + diffuse: in_range(diffuse, 0.0, 1.0, "the diffuse weight is not a number from 0 to 1")?, + ..self + }) + } + + /// The linear base color. + pub fn base_color(&self) -> [f32; 3] { + self.base_color + } + + /// The metallic value. + pub fn metallic(&self) -> f32 { + self.metallic + } + + /// The perceptual roughness. + pub fn roughness(&self) -> f32 { + self.roughness + } + + /// The specular weight. + pub fn specular(&self) -> f32 { + self.specular + } + + /// The diffuse weight. + pub fn diffuse(&self) -> f32 { + self.diffuse + } + + /// The geometry term for direct light. + pub fn visibility(&self) -> Visibility { + self.visibility + } + + /// The reflectance at normal incidence: `0.04 × specular` mixed toward the base color by + /// `metallic`. Each channel is in `0..=1`. + pub fn f0(&self) -> [f32; 3] { + let d = 0.04 * self.specular; + self.base_color.map(|c| d + (c - d) * self.metallic) + } + + /// The light one light reflects toward the viewer: the BRDF times `n·l` times π, per RGB + /// channel, for a light whose color is the irradiance on a surface facing it. A white light + /// on a white rough dielectric lit and seen head-on gives about 1. + /// + /// `n`, `v` and `l` are the surface normal, the direction to the viewer and the direction to + /// the light; they are normalized here. The BRDF is the final form of glTF 2.0 section + /// B.3.5: a Lambert lobe `(1 − F) (1 − metallic) base / π` plus `F D V`, with Schlick's `F` + /// (section B.3.4) at `v·h`, the GGX `D` of [`ggx_distribution_between`] from `n` and the + /// half vector, and the visibility `V = G / (4 (n·v) (n·l))` that [`Material::visibility`] + /// selects. By default `G` is the Smith-Schlick term with `k = (roughness + 1)² / 8` that + /// Karis gives for analytic lights, where section B.3.2 writes the separable Smith form + /// ([`Visibility::SmithSeparable`]). Roughness is shaded as at least + /// [`MIN_DIRECT_ROUGHNESS`]. A light at or below the surface gives 0, and so does a view + /// straight opposite the light, which has no half vector. `n·v` is taken as at least `1e-4`, + /// so a view at or below the surface sees the surface as at a grazing angle. `D` is exact + /// where `n·h` is close to 1, so the highlight peaks at its head-on value. `D` is 0 where + /// `n·h` is 0 or less, which happens when the view is at least as far below the surface as + /// the light is above it. With [`Visibility::SmithSchlick`] the specular denominator + /// `4 (n·v) (n·l)` is taken as at least `1e-4`, as in EffectCraft, so where it is smaller the + /// specular lobe is below `F D G / (4 (n·v) (n·l))`. The other two forms divide by no such + /// product and have no floor. + /// + /// Returns [`PbrError::BadDirection`] when a direction is not finite or has zero length. + pub fn try_direct(&self, n: [f32; 3], v: [f32; 3], l: [f32; 3]) -> Result<[f32; 3], PbrError> { + let n = unit(n).ok_or(PbrError::BadDirection)?; + let v = unit(v).ok_or(PbrError::BadDirection)?; + let l = unit(l).ok_or(PbrError::BadDirection)?; + let n_l = n.dot(l); + if n_l <= 0.0 { + return Ok([0.0; 3]); + } + let Some(h) = unit((v + l).to_array()) else { return Ok([0.0; 3]) }; + let n_v = n.dot(v).max(MIN_N_DOT_V); + let v_h = v.dot(h).max(0.0); + let r = self.roughness.max(MIN_DIRECT_ROUGHNESS); + let f = fresnel_schlick(self.f0(), v_h); + let d = ggx_distribution_between(n.to_array(), h.to_array(), r)?; + let spec = d * visibility(self.visibility, n_v, n_l, r); + let mut out = [0.0; 3]; + for c in 0..3 { + let kd = (1.0 - f[c]) * (1.0 - self.metallic); + out[c] = (kd * self.base_color[c] / PI * self.diffuse + f[c] * spec) * n_l * PI; + } + Ok(out) + } +} + +/// Schlick's Fresnel `f0 + (1 − f0) (1 − v·h)⁵`, with `1 − v·h` kept in `0..=1`. +fn fresnel_schlick(f0: [f32; 3], v_h: f32) -> [f32; 3] { + let k = (1.0 - v_h).clamp(0.0, 1.0).powi(5); + f0.map(|c| c + (1.0 - c) * k) +} + +/// The Smith-Schlick-GGX geometry term for direct light, `k = (roughness + 1)² / 8`. +fn smith_schlick_ggx(n_v: f32, n_l: f32, roughness: f32) -> f32 { + let k = (roughness + 1.0) * (roughness + 1.0) / 8.0; + let g1 = |x: f32| x / (x * (1.0 - k) + k); + g1(n_v) * g1(n_l) +} + +/// The visibility `G / (4 (n·v) (n·l))` of `kind` for `n_v` and `n_l` in `(0, 1]` and perceptual +/// `roughness`. `χ⁺(h·l)` and `χ⁺(h·v)` of section B.3.2 are 1: with `h` the normalized `v + l`, +/// `h·l` and `h·v` are equal and positive whenever `h` exists. +fn visibility(kind: Visibility, n_v: f32, n_l: f32, roughness: f32) -> f32 { + let a2 = (roughness * roughness) * (roughness * roughness); + let root = |x: f32| (a2 + (1.0 - a2) * x * x).sqrt(); + match kind { + Visibility::SmithSchlick => smith_schlick_ggx(n_v, n_l, roughness) / (4.0 * n_v * n_l).max(1e-4), + Visibility::SmithSeparable => 1.0 / ((n_l + root(n_l)) * (n_v + root(n_v))), + Visibility::SmithHeightCorrelated => 0.5 / (n_l * root(n_v) + n_v * root(n_l)), + } +} + +/// The environment BRDF term of the split sum for `n_dot_v` and perceptual `roughness`, as +/// `[scale, bias]`: the specular light of a prefiltered environment is its radiance times +/// `f0 × scale + bias`. The values are Karis's analytic fit for mobile +/// (), kept so that +/// `scale` and `bias` are at least 0 and their sum is at most 1, which keeps `f0 × scale + bias` +/// in `0..=1` for every `f0` in `0..=1`. `n_dot_v` is clamped to `0..=1`. +/// +/// Returns [`PbrError::BadDirection`] when `n_dot_v` is not finite, and +/// [`PbrError::BadMaterial`] when `roughness` is not a number in `0..=1`. +pub fn try_environment_brdf(n_dot_v: f32, roughness: f32) -> Result<[f32; 2], PbrError> { + if !n_dot_v.is_finite() { + return Err(PbrError::BadDirection); + } + let rough = in_range(roughness, 0.0, 1.0, "the roughness is not a number from 0 to 1")?; + let n_v = n_dot_v.clamp(0.0, 1.0); + let c0 = [-1.0, -0.0275, -0.572, 0.022]; + let c1 = [1.0, 0.0425, 1.04, -0.04]; + let r = [rough * c0[0] + c1[0], rough * c0[1] + c1[1], rough * c0[2] + c1[2], rough * c0[3] + c1[3]]; + let a004 = (r[0] * r[0]).min((-9.28 * n_v).exp2()) * r[0] + r[1]; + let scale = (-1.04 * a004 + r[2]).clamp(0.0, 1.0); + let bias = (1.04 * a004 + r[3]).clamp(0.0, 1.0 - scale); + Ok([scale, bias]) +} diff --git a/crates/pbr/src/environment.rs b/crates/pbr/src/environment.rs index 85b680ef6b..6658941466 100644 --- a/crates/pbr/src/environment.rs +++ b/crates/pbr/src/environment.rs @@ -328,3 +328,27 @@ impl Environment { Ok(EnvImage { width, height, data }) } } + +/// A dim studio environment of 8 × 4 pixels for an environment light that has no image: a gray +/// gradient whose radiance in direction `d` is proportional to `0.15 + 1.2 max(0, d·key)`, with +/// the key direction `(0.66, 0.75, 0)` up and toward +X. It is scaled so that the mean of its +/// pixels, each weighted by `sin θ` at its center, is 0.3. +pub fn default_environment() -> Result { + let key = V3::new(0.66, 0.75, 0.0); + let (w, h) = (8usize, 4usize); + let mut data = try_pixels(w * h)?; + let (mut mean, mut weight) = (0.0f32, 0.0f32); + for (i, px) in data.iter_mut().enumerate() { + let (x, y) = (i % w, i / w); + let sa = ((y as f32 + 0.5) / h as f32 * PI).sin(); + let l = 0.15 + 1.2 * pixel_dir(x, y, w, h).dot(key).max(0.0); + *px = [l; 3]; + mean += l * sa; + weight += sa; + } + let k = if mean.is_finite() && mean > 1e-6 { 0.3 * weight / mean } else { 1.0 }; + for px in &mut data { + *px = px.map(|c| c * k); + } + Ok(EnvImage { width: w as u32, height: h as u32, data }) +} diff --git a/crates/pbr/src/lib.rs b/crates/pbr/src/lib.rs index b6c7a9b68d..9413f9c0b2 100644 --- a/crates/pbr/src/lib.rs +++ b/crates/pbr/src/lib.rs @@ -22,8 +22,19 @@ //! distribution D is the one section B.3.2 writes //! (). //! Samples are importance-sampled from Hammersley points and read from a box-filtered pyramid -//! of the source at a level chosen from each sample's density. The environment BRDF term of the -//! split sum is not in this crate. +//! of the source at a level chosen from each sample's density. [`try_environment_brdf`] gives +//! the other term of the split sum, the scale and bias of `f0`. +//! +//! [`Material`] holds a glTF 2.0 metallic-roughness material, and [`Material::try_direct`] +//! evaluates its BRDF for one light in the final form of section B.3.5 +//! (), +//! with the Smith-Schlick geometry term Karis gives for analytic lights by default. [`Visibility`] +//! selects section B.3.2's separable Smith form or the height-correlated Smith form instead. +//! [`default_environment`] +//! is a small studio environment for an environment light without an image. +//! +//! [`SHADE_WGSL`] is the WGSL text of the same shading functions for an app's own shaders, and +//! [`GpuMaterial`] and [`GpuSh9`] lay out the values it reads. //! //! The diffuse coefficients are the nine real SH coefficients of the radiance, convolved with the //! clamped cosine lobe (band factors `π`, `2π/3` and `π/4`, Ramamoorthi and Hanrahan 2001, @@ -39,19 +50,23 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod brdf; mod environment; mod prefilter; mod sh; mod vec3; +mod wgsl; #[cfg(feature = "parallel")] use rayon::prelude::*; -pub use environment::{ColorEncoding, ENVIRONMENTS, EnvImage, Environment, MAX_RADIANCE, dir_of, uv_of}; +pub use brdf::{MAX_SPECULAR, MIN_DIRECT_ROUGHNESS, Material, Visibility, try_environment_brdf}; +pub use environment::{ColorEncoding, ENVIRONMENTS, EnvImage, Environment, MAX_RADIANCE, default_environment, dir_of, uv_of}; pub use prefilter::{PrefilterOptions, ggx_distribution, ggx_distribution_between, hammersley, try_prefilter}; pub use sh::{irradiance, sh_basis, try_sh9}; +pub use wgsl::{GpuMaterial, GpuSh9, SHADE_WGSL}; -/// Why an environment could not be made, filtered or read. +/// Why an environment could not be made, filtered or read, or a material could not be shaded. #[derive(Debug, Clone, PartialEq, thiserror::Error)] #[non_exhaustive] pub enum PbrError { @@ -74,6 +89,9 @@ pub enum PbrError { /// An option is out of its range; the text names it. #[error("{0}")] BadOption(&'static str), + /// A material value is not a number or is out of its range; the text names it. + #[error("{0}")] + BadMaterial(&'static str), /// The filtering would take more sample evaluations than [`Limits::max_work`]. #[error("the filtering needs {needed} sample evaluations, over the limit of {limit}")] TooMuchWork { needed: u64, limit: u64 }, diff --git a/crates/pbr/src/shade.wgsl b/crates/pbr/src/shade.wgsl new file mode 100644 index 0000000000..01a3a20a92 --- /dev/null +++ b/crates/pbr/src/shade.wgsl @@ -0,0 +1,205 @@ +// craft-pbr shading functions in WGSL: the metallic-roughness BRDF for direct light, the +// environment BRDF of the split sum, the equirect mapping, SH9 irradiance and the light of an +// environment. Each function computes the terms of the Rust function the crate README lists +// next to it. The text declares no bindings and no entry points. An app makes one module of +// its own declarations, this text and its entry points. Every name here starts with `pbr_`, +// `PBR_` or `Pbr`. Colors are linear, and nothing here encodes them for display. No function +// loops or recurses. + +const PBR_PI: f32 = 3.14159265358979; +const PBR_TAU: f32 = 6.28318530717959; +// MIN_DIRECT_ROUGHNESS +const PBR_MIN_DIRECT_ROUGHNESS: f32 = 0.032; +// MAX_SPECULAR +const PBR_MAX_SPECULAR: f32 = 25.0; +// The smallest n·v the direct BRDF divides by. +const PBR_MIN_N_DOT_V: f32 = 1e-4; +// The α floor of ggx_distribution. +const PBR_MIN_ALPHA: f32 = 1e-3; +// f32::MIN_POSITIVE +const PBR_F32_MIN_POSITIVE: f32 = 1.17549435e-38; + +// A material as GpuMaterial lays it out: 32 bytes, base_color at 0, metallic at 12, roughness +// at 16, specular at 20 and diffuse at 24. +struct PbrMaterial { + base_color: vec3, + metallic: f32, + roughness: f32, + specular: f32, + diffuse: f32, +}; + +// Nine SH coefficients as GpuSh9 lays them out, in the order of pbr_sh_basis: red, green and +// blue in x, y and z, 16 bytes each. +struct PbrSh9 { + c: array, 9>, +}; + +// The material with each value clamped to the range Material::try_new and try_with_weights +// accept: base color, metallic, roughness and diffuse from 0 to 1, specular from 0 to 25. +fn pbr_material_clamped(m: PbrMaterial) -> PbrMaterial { + return PbrMaterial( + clamp(m.base_color, vec3(0.0), vec3(1.0)), + clamp(m.metallic, 0.0, 1.0), + clamp(m.roughness, 0.0, 1.0), + clamp(m.specular, 0.0, PBR_MAX_SPECULAR), + clamp(m.diffuse, 0.0, 1.0), + ); +} + +// `d` scaled to unit length, or the zero vector when `d` has zero length. `d` is divided by its +// largest component first, which keeps the squared length in range. +fn pbr_unit(d: vec3) -> vec3 { + let big = max(abs(d.x), max(abs(d.y), abs(d.z))); + if (!(big > 0.0)) { + return vec3(0.0); + } + let s = d / big; + return s * inverseSqrt(dot(s, s)); +} + +// The reflectance at normal incidence: 0.04 × specular mixed toward the base color by metallic. +fn pbr_f0(m: PbrMaterial) -> vec3 { + let d = vec3(0.04 * m.specular); + return d + (m.base_color - d) * m.metallic; +} + +// The GGX distribution D at n_dot_h for perceptual roughness, with α = max(roughness², 0.001): +// α² / (π ((n·h)² (α² − 1) + 1)²). The inner term is computed as (1 − n·h)(1 + n·h) + (n·h)² α², +// the same value, which keeps the peak 1 / (π α²) of small α in f32. +fn pbr_ggx_distribution(n_dot_h: f32, roughness: f32) -> f32 { + let a = max(roughness * roughness, PBR_MIN_ALPHA); + let a2 = a * a; + let k = (1.0 - n_dot_h) * (1.0 + n_dot_h) + n_dot_h * n_dot_h * a2; + return a2 / max(PBR_PI * k * k, PBR_F32_MIN_POSITIVE); +} + +// Schlick's Fresnel f0 + (1 − f0) (1 − v·h)⁵, with 1 − v·h kept in 0..=1. +fn pbr_fresnel_schlick(f0: vec3, v_dot_h: f32) -> vec3 { + let x = clamp(1.0 - v_dot_h, 0.0, 1.0); + let x2 = x * x; + return f0 + (vec3(1.0) - f0) * (x2 * x2 * x); +} + +// The Smith-Schlick-GGX geometry term for direct light, k = (roughness + 1)² / 8. +fn pbr_smith_schlick_ggx(n_dot_v: f32, n_dot_l: f32, roughness: f32) -> f32 { + let k = (roughness + 1.0) * (roughness + 1.0) / 8.0; + let gv = n_dot_v / (n_dot_v * (1.0 - k) + k); + let gl = n_dot_l / (n_dot_l * (1.0 - k) + k); + return gv * gl; +} + +// The light one light reflects toward the viewer: the BRDF times n·l times π, per channel, for +// a light whose color is the irradiance on a surface facing it. `n`, `v` and `l` are the +// normal, the direction to the viewer and the direction to the light; they are normalized here. +// The material is clamped with pbr_material_clamped and roughness is shaded as at least +// PBR_MIN_DIRECT_ROUGHNESS. A light at or below the surface, a view straight opposite the light +// and a zero-length direction give 0. n·v is taken as at least 1e-4, n·h as at most 1, and the +// specular denominator 4 (n·v) (n·l) as at least 1e-4. +fn pbr_direct(material: PbrMaterial, n_in: vec3, v_in: vec3, l_in: vec3) -> vec3 { + let m = pbr_material_clamped(material); + let n = pbr_unit(n_in); + let v = pbr_unit(v_in); + let l = pbr_unit(l_in); + let n_l = dot(n, l); + if (n_l <= 0.0 || dot(v, v) == 0.0) { + return vec3(0.0); + } + let h = pbr_unit(v + l); + if (dot(h, h) == 0.0) { + return vec3(0.0); + } + let n_v = max(dot(n, v), PBR_MIN_N_DOT_V); + let n_h = clamp(dot(n, h), 0.0, 1.0); + let v_h = max(dot(v, h), 0.0); + let r = max(m.roughness, PBR_MIN_DIRECT_ROUGHNESS); + let f = pbr_fresnel_schlick(pbr_f0(m), v_h); + let spec = pbr_ggx_distribution(n_h, r) * pbr_smith_schlick_ggx(n_v, n_l, r) / max(4.0 * n_v * n_l, 1e-4); + let kd = (vec3(1.0) - f) * (1.0 - m.metallic); + return (kd * m.base_color / PBR_PI * m.diffuse + f * spec) * n_l * PBR_PI; +} + +// The environment BRDF term of the split sum for n_dot_v and perceptual roughness, as +// (scale, bias): specular light is prefiltered radiance times f0 × scale + bias. Karis's analytic +// fit for mobile, with scale and bias at least 0 and their sum at most 1. n_dot_v and roughness +// are clamped to 0..=1. +fn pbr_environment_brdf(n_dot_v: f32, roughness: f32) -> vec2 { + let n_v = clamp(n_dot_v, 0.0, 1.0); + let rough = clamp(roughness, 0.0, 1.0); + let r = rough * vec4(-1.0, -0.0275, -0.572, 0.022) + vec4(1.0, 0.0425, 1.04, -0.04); + let a004 = min(r.x * r.x, exp2(-9.28 * n_v)) * r.x + r.y; + let scale = clamp(-1.04 * a004 + r.z, 0.0, 1.0); + let bias = clamp(1.04 * a004 + r.w, 0.0, 1.0 - scale); + return vec2(scale, bias); +} + +// The direction of equirect coordinates (u, v) in the crate's frame: +Y up, row 0 straight up, +// u = 0 toward +X and u increasing toward +Z. +fn pbr_dir_of(u: f32, v: f32) -> vec3 { + let theta = v * PBR_PI; + let phi = u * PBR_TAU; + return vec3(sin(theta) * cos(phi), cos(theta), sin(theta) * sin(phi)); +} + +// The equirect coordinates (u, v) of a unit direction, u in 0..=1 and v in 0..=1. A direction +// straight up or down has u = 0. +fn pbr_uv_of(d: vec3) -> vec2 { + var phi = 0.0; + if (d.x != 0.0 || d.z != 0.0) { + phi = atan2(d.z, d.x); + } + let u = phi / PBR_TAU; + return vec2(u - floor(u), acos(clamp(d.y, -1.0, 1.0)) / PBR_PI); +} + +// The nine real SH basis functions at direction `d`, bands 0 to 2 in the order +// Y00, Y1-1 (y), Y10 (z), Y11 (x), Y2-2 (xy), Y2-1 (yz), Y20, Y21 (xz), Y22. `d` is normalized +// first; a zero-length direction gives nine zeros. +fn pbr_sh_basis(d_in: vec3) -> array { + let d = pbr_unit(d_in); + if (dot(d, d) == 0.0) { + return array(); + } + return array( + 0.282095, + 0.488603 * d.y, + 0.488603 * d.z, + 0.488603 * d.x, + 1.092548 * d.x * d.y, + 1.092548 * d.y * d.z, + 0.315392 * (3.0 * d.z * d.z - 1.0), + 1.092548 * d.x * d.z, + 0.546274 * (d.x * d.x - d.y * d.y), + ); +} + +// Σ c_k Y_k(n): the diffuse radiance a white surface with normal `n` reflects. Negative results, +// which ringing can give, are kept. A zero-length normal gives 0. +fn pbr_irradiance(sh: PbrSh9, n: vec3) -> vec3 { + let b = pbr_sh_basis(n); + return sh.c[0].xyz * b[0] + sh.c[1].xyz * b[1] + sh.c[2].xyz * b[2] + sh.c[3].xyz * b[3] + sh.c[4].xyz * b[4] + + sh.c[5].xyz * b[5] + sh.c[6].xyz * b[6] + sh.c[7].xyz * b[7] + sh.c[8].xyz * b[8]; +} + +// The two prefiltered levels to blend for perceptual roughness, and the weight of the second, as +// (low, high, weight). Level l of `levels` from try_prefilter is filtered for roughness +// l / (levels − 1). Roughness is clamped to 0..=1; 0 or 1 levels give (0, 0, 0). +fn pbr_specular_levels(roughness: f32, levels: u32) -> vec3 { + let last = f32(max(levels, 1u) - 1u); + let lv = clamp(roughness, 0.0, 1.0) * last; + let lo = floor(lv); + let hi = min(lo + 1.0, last); + return vec3(lo, hi, lv - lo); +} + +// The light an environment reflects toward the viewer, by the split sum. `irradiance` is the +// diffuse radiance a white surface with this normal reflects (pbr_irradiance, or the app's own +// lookup), and `prefiltered` is the radiance of the prefiltered levels along the reflection of +// the view about the normal, blended as pbr_specular_levels gives. The diffuse part is weighted +// by 1 − (f0 × scale + bias) and 1 − metallic. The material is clamped with pbr_material_clamped. +fn pbr_environment_light(material: PbrMaterial, n_dot_v: f32, irradiance: vec3, prefiltered: vec3) -> vec3 { + let m = pbr_material_clamped(material); + let ab = pbr_environment_brdf(n_dot_v, m.roughness); + let fs = pbr_f0(m) * ab.x + vec3(ab.y); + return irradiance * m.base_color * (vec3(1.0) - fs) * (1.0 - m.metallic) * m.diffuse + prefiltered * fs; +} diff --git a/crates/pbr/src/wgsl.rs b/crates/pbr/src/wgsl.rs new file mode 100644 index 0000000000..71a979d210 --- /dev/null +++ b/crates/pbr/src/wgsl.rs @@ -0,0 +1,110 @@ +//! The WGSL text of the shading functions and the GPU layouts of the values it reads. + +use std::mem::offset_of; + +use crate::{Material, PbrError}; + +/// WGSL source of the shading functions: `pbr_direct`, `pbr_environment_brdf`, +/// `pbr_environment_light`, `pbr_irradiance` and the helpers they call, with the structs +/// `PbrMaterial` and `PbrSh9`. The crate README lists each function next to its Rust +/// counterpart. +/// +/// The text declares no bindings and no entry points, and every name in it starts with `pbr_`, +/// `PBR_` or `Pbr`. An app joins its own declarations, this text and its entry points with +/// newlines into one module and passes that to its shader compiler. No function loops or +/// recurses. Colors are linear. +pub const SHADE_WGSL: &str = include_str!("shade.wgsl"); + +/// A [`Material`] laid out as the WGSL struct `PbrMaterial`, 32 bytes. Made by [`Material::gpu`]. +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GpuMaterial { + base_color: [f32; 3], + metallic: f32, + roughness: f32, + specular: f32, + diffuse: f32, + pad: f32, +} + +impl GpuMaterial { + /// Bytes of one `PbrMaterial`, which is also its array stride. + pub const SIZE: usize = size_of::(); + + /// The little-endian bytes of `PbrMaterial`, for a uniform or storage buffer. + pub fn to_bytes(&self) -> [u8; GpuMaterial::SIZE] { + let mut out = [0u8; GpuMaterial::SIZE]; + let fields = [ + (offset_of!(GpuMaterial, base_color), self.base_color[0]), + (offset_of!(GpuMaterial, base_color) + 4, self.base_color[1]), + (offset_of!(GpuMaterial, base_color) + 8, self.base_color[2]), + (offset_of!(GpuMaterial, metallic), self.metallic), + (offset_of!(GpuMaterial, roughness), self.roughness), + (offset_of!(GpuMaterial, specular), self.specular), + (offset_of!(GpuMaterial, diffuse), self.diffuse), + (offset_of!(GpuMaterial, pad), self.pad), + ]; + for (at, v) in fields { + if let Some(dst) = out.get_mut(at..at + 4) { + dst.copy_from_slice(&v.to_le_bytes()); + } + } + out + } +} + +impl Material { + /// The material in the layout of the WGSL struct `PbrMaterial`. + pub fn gpu(&self) -> GpuMaterial { + GpuMaterial { + base_color: self.base_color(), + metallic: self.metallic(), + roughness: self.roughness(), + specular: self.specular(), + diffuse: self.diffuse(), + pad: 0.0, + } + } +} + +/// Nine SH coefficients from [`try_sh9`](crate::try_sh9) laid out as the WGSL struct `PbrSh9`, +/// 144 bytes: one `vec4` per coefficient with red, green and blue in `x`, `y` and `z` and 0 +/// in `w`. +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GpuSh9 { + c: [[f32; 4]; 9], +} + +impl GpuSh9 { + /// Bytes of one `PbrSh9`. + pub const SIZE: usize = size_of::(); + + /// The largest magnitude of a coefficient. The coefficients of [`try_sh9`](crate::try_sh9) + /// for radiance up to [`MAX_RADIANCE`](crate::MAX_RADIANCE) stay under 4e28. The basis + /// functions sum to less than 5 in magnitude in every direction, so `pbr_irradiance` sums + /// to less than 5e30 in `f32`. + pub const MAX_COEFFICIENT: f32 = 1e30; + + /// The coefficients in the layout of `PbrSh9`. Returns [`PbrError::BadOption`] when a + /// coefficient is not finite or its magnitude is over [`GpuSh9::MAX_COEFFICIENT`]. + pub fn try_new(coefficients: &[[f32; 3]; 9]) -> Result { + if coefficients.iter().flatten().any(|c| !c.is_finite() || c.abs() > GpuSh9::MAX_COEFFICIENT) { + return Err(PbrError::BadOption("an SH coefficient is not finite or its magnitude is over 1e30")); + } + Ok(GpuSh9 { c: coefficients.map(|[r, g, b]| [r, g, b, 0.0]) }) + } + + /// The little-endian bytes of `PbrSh9`, for a uniform or storage buffer. + pub fn to_bytes(&self) -> [u8; GpuSh9::SIZE] { + let mut out = [0u8; GpuSh9::SIZE]; + let base = offset_of!(GpuSh9, c); + for (i, v) in self.c.iter().flatten().enumerate() { + let at = base + 4 * i; + if let Some(dst) = out.get_mut(at..at + 4) { + dst.copy_from_slice(&v.to_le_bytes()); + } + } + out + } +} diff --git a/crates/pbr/tests/it/brdf.rs b/crates/pbr/tests/it/brdf.rs new file mode 100644 index 0000000000..d150803e79 --- /dev/null +++ b/crates/pbr/tests/it/brdf.rs @@ -0,0 +1,597 @@ +//! The direct-light BRDF, the environment BRDF and the default environment: EffectCraft's tests on +//! this crate's API, a comparison with EffectCraft's code, glTF 2.0's closed forms and numeric +//! properties. + +use std::f32::consts::PI; + +use craft_pbr::{ + EnvImage, MIN_DIRECT_ROUGHNESS, Material, PbrError, Visibility, default_environment, ggx_distribution, ggx_distribution_between, hammersley, + try_environment_brdf, +}; + +const VISIBILITIES: [Visibility; 3] = [Visibility::SmithSchlick, Visibility::SmithSeparable, Visibility::SmithHeightCorrelated]; + +use crate::reference::effectcraft as ec; + +fn dot(a: [f32; 3], b: [f32; 3]) -> f32 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +fn norm(a: [f32; 3]) -> [f32; 3] { + let l = dot(a, a).sqrt(); + [a[0] / l, a[1] / l, a[2] / l] +} + +fn material(base: [f32; 3], metallic: f32, roughness: f32) -> Material { + Material::try_new(base, metallic, roughness).unwrap() +} + +/// Unit directions spread over the upper hemisphere of +Z, from Hammersley points, with `n·d` at +/// least `min_cos`. +fn hemisphere(count: u32, min_cos: f32) -> Vec<[f32; 3]> { + (0..count) + .filter_map(|i| { + let [a, b] = hammersley(i, count)?; + let z = min_cos + (1.0 - min_cos) * b; + let s = (1.0 - z * z).max(0.0).sqrt(); + Some([s * (2.0 * PI * a).cos(), s * (2.0 * PI * a).sin(), z]) + }) + .collect() +} + +// ------------------------------------------------------------------ moved from EffectCraft + +#[test] +fn brdf_matches_cook_torrance_formula() { + // Reference: f = kd·c/π + D·G·F/(4·NV·NL), returned × NL × π. + let n = [0.0, 0.0, 1.0]; + let v = norm([0.3, 0.1, 1.0]); + let l = norm([-0.4, 0.2, 1.0]); + let (base, metal, rough) = ([0.8, 0.4, 0.2], 0.3f32, 0.45f32); + let got = material(base, metal, rough).try_direct(n, v, l).unwrap(); + let h = norm([v[0] + l[0], v[1] + l[1], v[2] + l[2]]); + let (nv, nl, nh, vh) = (dot(n, v), dot(n, l), dot(n, h), dot(v, h)); + let a2 = (rough * rough).powi(2); + let d = a2 / (PI * ((nh * nh) * (a2 - 1.0) + 1.0).powi(2)); + let k = (rough + 1.0).powi(2) / 8.0; + let g = nv / (nv * (1.0 - k) + k) * nl / (nl * (1.0 - k) + k); + for c in 0..3 { + let f0 = 0.04 + (base[c] - 0.04) * metal; + let f = f0 + (1.0 - f0) * (1.0 - vh).powi(5); + let expect = ((1.0 - f) * (1.0 - metal) * base[c] / PI + d * g * f / (4.0 * nv * nl)) * nl * PI; + assert!((got[c] - expect).abs() < 1e-5, "channel {c}: {} vs {expect}", got[c]); + } + // No light from behind the surface. + assert_eq!(material(base, metal, rough).try_direct(n, v, [0.0, 0.0, -1.0]).unwrap(), [0.0; 3]); + // A white rough dielectric lit head-on reflects about its base color (π folded in). + let w = material([1.0; 3], 0.0, 1.0).try_direct(n, n, n).unwrap(); + assert!(w[0] > 0.95 && w[0] < 1.05, "{w:?}"); +} + +#[test] +fn env_brdf_endpoints() { + let [a, b] = try_environment_brdf(1.0, 0.0).unwrap(); + assert!(a + b > 0.9 && a + b <= 1.05); + let [a, b] = try_environment_brdf(0.1, 1.0).unwrap(); + assert!(a >= 0.0 && b > -0.01 && a + b < 1.0); +} + +/// The default environment is a dim studio with a mean of 0.3, lit from up and toward +X, and +/// symmetric about the XY plane. +#[test] +fn default_environment_keeps_the_level_and_points_up() { + let env = default_environment().unwrap(); + let (w, h) = (env.width(), env.height()); + assert_eq!((w, h), (8, 4)); + let (mut mean, mut weight) = (0.0f32, 0.0f32); + let mut toward = [0.0f32; 3]; + for (i, p) in env.pixels().iter().enumerate() { + let (x, y) = (i % w as usize, i / w as usize); + let v = (y as f32 + 0.5) / h as f32; + let sa = (v * PI).sin(); + let lum = (p[0] + p[1] + p[2]) / 3.0; + mean += lum * sa; + weight += sa; + let d = craft_pbr::dir_of((x as f32 + 0.5) / w as f32, v); + for c in 0..3 { + toward[c] += d[c] * lum * sa; + } + } + assert!((mean / weight - 0.3).abs() < 0.01, "dim studio mean: {}", mean / weight); + let t = norm(toward); + assert!(t[1] > 0.5, "the key is up: {t:?}"); + assert!(t[0] > 0.3, "the key is toward +X: {t:?}"); + assert!(t[2].abs() < 0.1, "symmetric about the XY plane: {t:?}"); + // No texel clips past white at the default intensity. + assert!(env.pixels().iter().all(|p| p[0] <= 1.0 && p[0] > 0.0), "0 < radiance <= 1"); +} + +// ------------------------------------------------------------------ against EffectCraft's code + +/// EffectCraft's environment direction `(x, y, z)`, with +Y down and the image center at +Z, is +/// `(−z, −y, −x)` in this crate's frame, and the same pixels hold the same light. +#[test] +fn default_environment_matches_effectcraft_in_this_crate_frame() { + let ours = default_environment().unwrap(); + let (w, h, theirs) = ec::default_environment(); + assert_eq!((ours.width(), ours.height()), (w, h)); + for (a, b) in ours.pixels().iter().zip(&theirs) { + for c in 0..3 { + assert!((a[c] - b[c]).abs() < 1e-6, "{a:?} vs {b:?}"); + } + } + for (u, v) in [(0.1f32, 0.2f32), (0.5, 0.5), (0.8, 0.9)] { + let e = ec::equirect_dir(u, v, 0.0); + let d = craft_pbr::dir_of(u, v); + for (x, y) in [(d[0], -e[2]), (d[1], -e[1]), (d[2], -e[0])] { + assert!((x - y).abs() < 1e-5, "{d:?} vs {e:?}"); + } + } +} + +/// From roughness 0.25 up, the direct light matches EffectCraft's `brdf` within `1e-4` of +/// `max(1, value)`. Below it, this crate's distribution is evaluated in `f64` and EffectCraft's +/// in `f32`, which loses the narrow peak, and roughness is shaded as at least 0.032 where +/// EffectCraft used 0.03. +#[test] +fn direct_light_matches_effectcraft_for_valid_inputs() { + let n = [0.0, 0.0, 1.0]; + let dirs = hemisphere(24, 0.05); + for base in [[0.8, 0.4, 0.2], [1.0, 1.0, 1.0], [0.0, 0.1, 0.9]] { + for metallic in [0.0, 0.3, 1.0] { + for roughness in [0.25, 0.5, 0.8, 1.0] { + for (specular, diffuse) in [(1.0, 1.0), (2.0, 0.5), (0.0, 0.0)] { + let m = material(base, metallic, roughness).try_with_weights(specular, diffuse).unwrap(); + let s = ec::BrdfSurface { base, metallic, roughness, specular, diffuse }; + for &v in &dirs { + for &l in &dirs { + let a = m.try_direct(n, v, l).unwrap(); + let b = ec::brdf(s, n, v, l); + for c in 0..3 { + assert!((a[c] - b[c]).abs() <= 1e-4 * 1f32.max(b[c].abs()), "{a:?} vs {b:?} at {v:?} {l:?}"); + } + } + } + } + } + } + } +} + +/// The environment BRDF matches EffectCraft's `env_brdf` wherever that gives a scale and bias of +/// at least 0 with a sum of at most 1. +#[test] +fn environment_brdf_matches_effectcraft_inside_its_valid_range() { + for i in 0..=50 { + for j in 0..=50 { + let (n_v, rough) = (i as f32 / 50.0, j as f32 / 50.0); + let (a, b) = ec::env_brdf(n_v, rough); + if a >= 0.0 && b >= 0.0 && a + b <= 1.0 { + let [x, y] = try_environment_brdf(n_v, rough).unwrap(); + assert!((x - a).abs() <= 1e-6 && (y - b).abs() <= 1e-6, "{x}, {y} vs {a}, {b} at {n_v}, {rough}"); + } + } + } +} + +// ------------------------------------------------------------------ glTF 2.0 and numeric properties + +/// glTF 2.0 section B.3.5's metal and dielectric BRDFs, with `vd` the specular BRDF `V D`. +fn gltf_metal(base: f32, vh: f32, vd: f32) -> f32 { + vd * (base + (1.0 - base) * (1.0 - vh.abs()).powi(5)) +} + +fn gltf_dielectric(base: f32, vh: f32, vd: f32) -> f32 { + let fr = 0.04 + (1.0 - 0.04) * (1.0 - vh.abs()).powi(5); + base / PI + (vd - base / PI) * fr +} + +/// At metallic 0 and 1 the BRDF is glTF 2.0's dielectric and metal BRDF of section B.3.5, with +/// the specular BRDF `V D` taken from this crate's geometry term and distribution. +#[test] +fn metallic_endpoints_are_the_gltf_closed_forms() { + let n = [0.0, 0.0, 1.0]; + let dirs = hemisphere(16, 0.05); + for base in [[0.9, 0.5, 0.1], [1.0, 1.0, 1.0], [0.0, 0.0, 0.0]] { + for roughness in [0.1f32, 0.4, 1.0] { + let r = roughness.max(MIN_DIRECT_ROUGHNESS); + let k = (r + 1.0) * (r + 1.0) / 8.0; + for &v in &dirs { + for &l in &dirs { + let h = norm([v[0] + l[0], v[1] + l[1], v[2] + l[2]]); + let (nv, nl, nh, vh) = (dot(n, v), dot(n, l), dot(n, h), dot(v, h)); + let g = nv / (nv * (1.0 - k) + k) * nl / (nl * (1.0 - k) + k); + let vd = g / (4.0 * nv * nl) * ggx_distribution(nh, r); + let metal = material(base, 1.0, roughness).try_direct(n, v, l).unwrap(); + let dielectric = material(base, 0.0, roughness).try_direct(n, v, l).unwrap(); + for c in 0..3 { + let (want_m, want_d) = (gltf_metal(base[c], vh, vd), gltf_dielectric(base[c], vh, vd)); + let (got_m, got_d) = (metal[c] / (nl * PI), dielectric[c] / (nl * PI)); + // `try_direct` normalizes the directions again, which moves the half vector + // of the narrow lobes by a few units in the last place. + assert!((got_m - want_m).abs() <= 1e-3 * 1f32.max(want_m), "metal {got_m} vs {want_m}"); + assert!((got_d - want_d).abs() <= 1e-3 * 1f32.max(want_d), "dielectric {got_d} vs {want_d}"); + } + } + } + } + } +} + +/// glTF 2.0 section B.3.2's separable Smith masking for one direction. +fn gltf_g1(x: f32, a: f32) -> f32 { + 2.0 * x / (x + (a * a + (1.0 - a * a) * x * x).sqrt()) +} + +/// The Smith-Schlick geometry term with `k = (r + 1)² / 8` is glTF's separable Smith term at +/// roughness 1, and darker than it at grazing angles on smoother surfaces. +#[test] +fn the_geometry_term_against_the_gltf_separable_smith_form() { + let n = [0.0, 0.0, 1.0]; + let spec = |roughness: f32, v: [f32; 3], l: [f32; 3]| { + // A white metal reflects only its specular lobe, with F = 1. + material([1.0; 3], 1.0, roughness).try_direct(n, v, l).unwrap()[0] + }; + for &v in &hemisphere(16, 0.05) { + for &l in &hemisphere(16, 0.05) { + let h = norm([v[0] + l[0], v[1] + l[1], v[2] + l[2]]); + let (nv, nl) = (dot(n, v), dot(n, l)); + let want = gltf_g1(nv, 1.0) * gltf_g1(nl, 1.0) * ggx_distribution(dot(n, h), 1.0) / (4.0 * nv * nl) * nl * PI; + let got = spec(1.0, v, l); + assert!((got - want).abs() <= 1e-4 * want.max(1.0), "{got} vs {want}"); + } + } + let r = 0.25f32; + let (v, l) = (norm([0.995, 0.0, 0.1]), norm([-0.995, 0.0, 0.1])); + let karis = spec(r, v, l); + let ggx = gltf_g1(0.1, r * r) * gltf_g1(0.1, r * r) * ggx_distribution(1.0, r) / (4.0 * 0.1 * 0.1) * 0.1 * PI; + assert!(karis < 0.5 * ggx, "{karis} vs {ggx}"); +} + +/// `n·v`, `n·l` and `n·h` in `f64` for the normal +Z. +fn cosines64(v: [f32; 3], l: [f32; 3]) -> (f64, f64, f64) { + let unit = |d: [f64; 3]| { + let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); + [d[0] / len, d[1] / len, d[2] / len] + }; + let (v, l) = (unit(v.map(f64::from)), unit(l.map(f64::from))); + let h = unit([v[0] + l[0], v[1] + l[1], v[2] + l[2]]); + (v[2], l[2], h[2]) +} + +/// glTF 2.0 section B.3.2's GGX `D` in `f64`, with `α = roughness²`. +fn gltf_d64(nh: f64, roughness: f64) -> f64 { + let a2 = roughness.powi(4); + a2 / (std::f64::consts::PI * (nh * nh * (a2 - 1.0) + 1.0).powi(2)) +} + +/// Views and lights for the visibility tests: a spread over the hemisphere and grazing pairs at +/// 89 and 89.9 degrees from the normal, mirrored and side by side. +fn visibility_pairs() -> Vec<([f32; 3], [f32; 3])> { + let mut pairs = Vec::new(); + for &v in &hemisphere(12, 0.05) { + for &l in &hemisphere(12, 0.05) { + pairs.push((v, l)); + } + } + for deg in [89.0f32, 89.9] { + let (s, c) = (deg.to_radians().sin(), deg.to_radians().cos()); + let head_on = [0.0, 0.0, 1.0]; + pairs.extend([([s, 0.0, c], [-s, 0.0, c]), ([s, 0.0, c], [0.0, s, c]), ([s, 0.0, c], head_on), (head_on, [s, 0.0, c])]); + } + pairs +} + +/// The specular light of a white metal, whose `F` is 1 and whose diffuse lobe is 0, against +/// `want(n·v, n·l, α)`, a visibility computed in `f64` from a published formula. +fn check_visibility(kind: Visibility, want: impl Fn(f64, f64, f64) -> f64) { + let n = [0.0, 0.0, 1.0]; + for roughness in [0.0f32, 0.1, 0.25, 0.5, 1.0] { + let r = f64::from(roughness.max(MIN_DIRECT_ROUGHNESS)); + let m = material([1.0; 3], 1.0, roughness).with_visibility(kind); + for (v, l) in visibility_pairs() { + let (nv, nl, nh) = cosines64(v, l); + let expect = want(nv, nl, r * r) * gltf_d64(nh, r) * nl * std::f64::consts::PI; + let got = f64::from(m.try_direct(n, v, l).unwrap()[0]); + assert!((got - expect).abs() <= 1e-3 * expect + 1e-6, "{kind:?} roughness {roughness} at {v:?} {l:?}: {got} vs {expect}"); + } + } +} + +/// `Visibility::SmithSeparable` is the `V` of glTF 2.0 section B.3.2, written here as the +/// section writes it, at roughness 0 (shaded at the floor) to 1 and at grazing angles. +#[test] +fn the_separable_visibility_is_gltf_section_b_3_2() { + check_visibility(Visibility::SmithSeparable, |nv, nl, a| { + let a2 = a * a; + 1.0 / (nl.abs() + (a2 + (1.0 - a2) * nl * nl).sqrt()) / (nv.abs() + (a2 + (1.0 - a2) * nv * nv).sqrt()) + }); +} + +/// `Visibility::SmithHeightCorrelated` is Heitz's height-correlated masking-shadowing +/// `G₂ = 1 / (1 + Λ(v) + Λ(l))` with the GGX `Λ = (√(1 + α² tan² θ) − 1) / 2`, divided by +/// `4 (n·v) (n·l)`, computed here from the tangents rather than in the crate's form. +#[test] +fn the_height_correlated_visibility_is_heitzs_smith_form() { + check_visibility(Visibility::SmithHeightCorrelated, |nv, nl, a| { + let lambda = |c: f64| ((1.0 + a * a * (1.0 - c * c) / (c * c)).sqrt() - 1.0) / 2.0; + 1.0 / (1.0 + lambda(nv) + lambda(nl)) / (4.0 * nv * nl) + }); +} + +/// A material uses EffectCraft's Smith-Schlick term unless a host selects another, and the two +/// Smith forms are brighter than it at grazing angles on a smooth surface. +#[test] +fn the_default_visibility_is_effectcrafts_smith_schlick() { + let n = [0.0, 0.0, 1.0]; + assert_eq!(Visibility::default(), Visibility::SmithSchlick); + let m = material([0.8, 0.4, 0.2], 0.3, 0.45); + assert_eq!(m.visibility(), Visibility::SmithSchlick); + assert_eq!(m.try_with_weights(2.0, 0.5).unwrap().visibility(), Visibility::SmithSchlick); + let schlick = m.with_visibility(Visibility::SmithSchlick); + for (v, l) in visibility_pairs() { + assert_eq!(m.try_direct(n, v, l).unwrap(), schlick.try_direct(n, v, l).unwrap()); + } + let (v, l) = (norm([0.995, 0.0, 0.1]), norm([-0.995, 0.0, 0.1])); + let at = |kind| material([1.0; 3], 1.0, 0.25).with_visibility(kind).try_direct(n, v, l).unwrap()[0]; + assert!(at(Visibility::SmithSeparable) > 2.0 * at(Visibility::SmithSchlick)); + assert!(at(Visibility::SmithHeightCorrelated) > at(Visibility::SmithSeparable)); +} + +/// A unit vector along `d`, computed in the same steps and order as the crate normalizes +/// directions: divided by its largest component, then multiplied by the reciprocal length. +fn crate_unit(d: [f32; 3]) -> [f32; 3] { + let big = d[0].abs().max(d[1].abs()).max(d[2].abs()); + let s = [d[0] / big, d[1] / big, d[2] / big]; + let r = 1.0 / ((s[0] * s[0]) + (s[1] * s[1]) + (s[2] * s[2])).sqrt(); + [s[0] * r, s[1] * r, s[2] * r] +} + +/// The light a material reflects from a uniform white sky onto a surface seen at `theta`: the +/// specular lobe by GGX importance sampling of the half vector, and the diffuse lobe by cosine +/// sampling of the light. +fn albedo(m: &Material, theta: f32, steps: u32) -> f64 { + let n = [0.0, 0.0, 1.0]; + let v = [theta.sin(), 0.0, theta.cos()]; + let spec_only = m.try_with_weights(m.specular(), 0.0).unwrap(); + let a = m.roughness().max(MIN_DIRECT_ROUGHNESS).powi(2); + let (mut spec, mut diff) = (0.0f64, 0.0f64); + for i in 0..steps { + let xi = (i as f32 + 0.5) / steps as f32; + for j in 0..steps { + let phi = 2.0 * PI * (j as f32 + 0.5) / steps as f32; + // Specular: a half vector drawn from D (n·h), a light reflected about it. + let ct = ((1.0 - xi) / (1.0 + (a * a - 1.0) * xi)).sqrt(); + let st = (1.0 - ct * ct).max(0.0).sqrt(); + let hv = [st * phi.cos(), st * phi.sin(), ct]; + let vh = dot(v, hv); + if vh > 0.0 { + let l = [2.0 * vh * hv[0] - v[0], 2.0 * vh * hv[1] - v[1], 2.0 * vh * hv[2] - v[2]]; + if l[2] > 0.0 { + // The density at the half vector `try_direct` finds again from `v` and `l`, + // rounded the same way and with `D` taken from the same vectors. + let (uv, ul) = (crate_unit(v), crate_unit(l)); + let h = crate_unit([uv[0] + ul[0], uv[1] + ul[1], uv[2] + ul[2]]); + let d = ggx_distribution_between(n, h, m.roughness().max(MIN_DIRECT_ROUGHNESS)).unwrap(); + let pdf = d * h[2] / (4.0 * dot(uv, h)); + spec += f64::from(spec_only.try_direct(n, v, l).unwrap()[0] / PI / pdf); + } + } + // Diffuse: a light drawn from n·l / π. + let (cl, sl) = ((1.0 - xi).sqrt(), xi.sqrt()); + let l = [sl * phi.cos(), sl * phi.sin(), cl]; + let d = m.try_direct(n, v, l).unwrap()[0] - spec_only.try_direct(n, v, l).unwrap()[0]; + diff += f64::from(d / cl); + } + } + (spec + diff) / f64::from(steps * steps) +} + +const ANGLES: [f32; 8] = [0.0, 30.0, 60.0, 75.0, 80.0, 85.0, 89.0, 89.9]; +const ROUGHNESS: [f32; 9] = [0.0, 0.01, 0.032, 0.05, 0.1, 0.25, 0.5, 0.75, 1.0]; + +/// A white furnace: a white metal, whose BRDF is the specular lobe alone with `F = 1`, reflects +/// at most the light it receives at every roughness and view angle, with each geometry term. +#[test] +fn a_white_metal_reflects_at_most_the_light_it_receives() { + for kind in VISIBILITIES { + for roughness in ROUGHNESS { + for deg in ANGLES { + let e = albedo(&material([1.0; 3], 1.0, roughness).with_visibility(kind), deg.to_radians(), 96); + assert!(e <= 1.0 + 1e-3, "{kind:?} roughness {roughness} at {deg}°: {e}"); + assert!(e > 0.0, "{kind:?} roughness {roughness} at {deg}°: {e}"); + } + } + } +} + +/// glTF 2.0 section B.3.6.3 notes that the Fresnel coupling of the diffuse and specular lobes in +/// section B.3.5 does not conserve energy. For a white dielectric the excess is largest on smooth +/// surfaces seen about 80 degrees from the normal, where it is about 9.8%. +#[test] +fn a_white_dielectric_reflects_at_most_ten_percent_more_than_it_receives() { + for roughness in ROUGHNESS { + for deg in ANGLES { + let e = albedo(&material([1.0; 3], 0.0, roughness), deg.to_radians(), 96); + assert!(e <= 1.1, "roughness {roughness} at {deg}°: {e}"); + } + } + assert!(albedo(&material([1.0; 3], 0.0, 0.5), 0.0, 96) <= 1.0, "head-on the lobes conserve energy"); +} + +#[test] +fn the_brdf_is_reciprocal() { + let n = norm([0.1, -0.2, 1.0]); + let dirs: Vec<[f32; 3]> = hemisphere(20, 0.2).into_iter().map(|d| norm([d[0] + 0.1, d[1] - 0.2, d[2]])).collect(); + for (base, metallic) in [([0.7, 0.3, 0.1], 0.0), ([0.9, 0.8, 0.2], 1.0), ([0.5; 3], 0.4)] { + for (roughness, kind) in [0.05, 0.3, 0.9].into_iter().flat_map(|r| VISIBILITIES.map(|k| (r, k))) { + let m = material(base, metallic, roughness).with_visibility(kind); + for &v in &dirs { + for &l in &dirs { + let (nv, nl) = (dot(n, v), dot(n, l)); + if nv < 1e-2 || nl < 1e-2 { + continue; + } + let a = m.try_direct(n, v, l).unwrap(); + let b = m.try_direct(n, l, v).unwrap(); + for c in 0..3 { + let (x, y) = (a[c] / nl, b[c] / nv); + assert!((x - y).abs() <= 1e-4 * x.abs().max(1.0), "{x} vs {y}"); + } + } + } + } + } +} + +/// Roughness below `MIN_DIRECT_ROUGHNESS` is shaded as that roughness, and its highlight peak is +/// finite. +#[test] +fn roughness_is_clamped_at_the_documented_floor() { + let n = [0.0, 0.0, 1.0]; + let (v, l) = (norm([0.2, 0.0, 1.0]), norm([-0.2, 0.0, 1.0])); + let at = |r: f32| material([0.8; 3], 1.0, r).try_direct(n, v, l).unwrap(); + let floor = at(MIN_DIRECT_ROUGHNESS); + assert!(floor.iter().all(|c| c.is_finite() && *c > 0.0), "{floor:?}"); + for r in [0.0, 1e-6, 0.01, 0.03, MIN_DIRECT_ROUGHNESS] { + assert_eq!(at(r), floor, "roughness {r}"); + } + assert!(at(MIN_DIRECT_ROUGHNESS + 0.01)[0] < floor[0], "a rougher surface has a lower peak"); +} + +/// When rounding after normalization gives a dot product slightly over 1, the highlight is not +/// above the head-on peak. +#[test] +fn the_highlight_is_never_above_the_head_on_peak() { + let m = material([1.0; 3], 1.0, 0.0); + let head_on = m.try_direct([0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0]).unwrap()[0]; + for d in [[1.0, 1.0, 0.5], [0.3, -0.7, 0.2], [2.0, 3.0, 7.0], [-1.0, 0.1, 0.9], [0.6, 0.6, 0.6]] { + let got = m.try_direct(d, d, d).unwrap()[0]; + assert!(got <= head_on * (1.0 + 1e-4), "{d:?}: {got} vs {head_on}"); + } +} + +/// With `n`, `v` and `l` all along one direction off the axes, the highlight at the roughness +/// floor reaches the head-on peak. An `n·h` rounded to `f32` can be one step below 1 there, which +/// gives a `D` about 20% low. +#[test] +fn the_highlight_reaches_the_head_on_peak_off_the_axes() { + let m = material([1.0; 3], 1.0, MIN_DIRECT_ROUGHNESS); + let head_on = m.try_direct([0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0]).unwrap()[0]; + let d = norm([0.6, 0.6, 0.6]); + let got = m.try_direct(d, d, d).unwrap()[0]; + assert!((got - head_on).abs() <= 1e-4 * head_on, "{got} vs {head_on}"); +} + +/// A view at least as far below the surface as the light is above it has `n·h` of 0 or less, +/// where `D` is 0: a white metal, which reflects only its specular lobe, reflects nothing. +/// EffectCraft took `n·h` as at least 0 and gave `D` its value at 0. +#[test] +fn a_view_with_no_half_vector_above_the_surface_sees_no_specular_lobe() { + let n = [0.0, 0.0, 1.0]; + let m = material([1.0; 3], 1.0, 0.5); + let s = ec::BrdfSurface { base: [1.0; 3], metallic: 1.0, roughness: 0.5, specular: 1.0, diffuse: 1.0 }; + for (v, l) in [([-1.0, 0.0, -0.5], [1.0, 0.0, 0.2]), ([0.0, 1.0, -0.4], [0.0, 1.0, 0.3]), ([0.2, -1.0, -0.9], [0.5, 0.5, 0.1])] { + let (v, l) = (norm(v), norm(l)); + assert!(dot(n, v) + dot(n, l) <= 0.0, "{v:?} {l:?}"); + assert_eq!(m.try_direct(n, v, l).unwrap(), [0.0; 3], "{v:?} {l:?}"); + assert!(ec::brdf(s, n, v, l)[0] > 0.0, "{v:?} {l:?}"); + } +} + +/// The specular lobe divides by `4 (n·v) (n·l)` taken as at least `1e-4`, as EffectCraft does, +/// so at grazing angles it is lower than the expression without that floor. +#[test] +fn the_specular_denominator_is_floored_at_grazing_angles() { + let n = [0.0, 0.0, 1.0]; + let v = norm([1.0, 0.0, 0.001]); + let r = 0.5f32; + // A white metal: F is 1 and the diffuse lobe is 0. + let got = material([1.0; 3], 1.0, r).try_direct(n, v, v).unwrap()[0]; + let nv = dot(n, v); + let k = (r + 1.0).powi(2) / 8.0; + let g = (nv / (nv * (1.0 - k) + k)).powi(2); + let d = ggx_distribution(nv, r); + let floored = d * g / (4.0 * nv * nv).max(1e-4) * nv * PI; + let unfloored = d * g / (4.0 * nv * nv) * nv * PI; + assert!((got - floored).abs() <= 1e-3 * floored, "{got} vs {floored}"); + assert!(got < 0.05 * unfloored, "{got} vs {unfloored}"); +} + +#[test] +fn the_environment_brdf_keeps_reflectance_between_0_and_1() { + for i in 0..=60 { + for j in 0..=40 { + let (n_v, rough) = (i as f32 / 40.0 - 0.25, j as f32 / 40.0); + let [scale, bias] = try_environment_brdf(n_v, rough).unwrap(); + assert!(scale >= 0.0 && bias >= 0.0 && scale + bias <= 1.0, "{scale}, {bias} at {n_v}, {rough}"); + } + } + // A smooth surface seen at a grazing angle reflects all the light, whatever its f0. + assert_eq!(try_environment_brdf(0.0, 0.0).unwrap(), [0.0, 1.0]); +} + +#[test] +fn valid_inputs_give_finite_non_negative_light() { + let n = [0.0, 0.0, 1.0]; + let all: Vec<[f32; 3]> = hemisphere(32, -1.0); + for base in [[0.0; 3], [1.0; 3]] { + for metallic in [0.0, 1.0] { + for roughness in [0.0, 1.0] { + for (specular, diffuse, kind) in + [(0.0, 0.0), (craft_pbr::MAX_SPECULAR, 1.0)].into_iter().flat_map(|(s, d)| VISIBILITIES.map(|k| (s, d, k))) + { + let m = material(base, metallic, roughness).try_with_weights(specular, diffuse).unwrap().with_visibility(kind); + for &v in &all { + for &l in &all { + let out = m.try_direct(n, v, l).unwrap(); + assert!(out.iter().all(|c| c.is_finite() && *c >= 0.0), "{out:?} at {v:?} {l:?}"); + } + let huge = m.try_direct([0.0, 0.0, 1e30], v, [1e-30, 0.0, 1e-30]).unwrap(); + assert!(huge.iter().all(|c| c.is_finite() && *c >= 0.0), "{huge:?}"); + } + // A view straight opposite the light has no half vector. + assert_eq!(m.try_direct(n, [0.0, 0.6, -0.8], [0.0, -0.6, 0.8]).unwrap(), [0.0; 3]); + } + } + } + } +} + +#[test] +fn values_that_are_not_finite_or_out_of_range_are_refused() { + let bad = [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.01, 1.01]; + for x in bad { + assert!(matches!(Material::try_new([x, 0.5, 0.5], 0.0, 0.5), Err(PbrError::BadMaterial(_))), "base {x}"); + assert!(matches!(Material::try_new([0.5; 3], x, 0.5), Err(PbrError::BadMaterial(_))), "metallic {x}"); + assert!(matches!(Material::try_new([0.5; 3], 0.0, x), Err(PbrError::BadMaterial(_))), "roughness {x}"); + assert!(matches!(material([0.5; 3], 0.0, 0.5).try_with_weights(1.0, x), Err(PbrError::BadMaterial(_))), "diffuse {x}"); + assert!(matches!(try_environment_brdf(0.5, x), Err(PbrError::BadMaterial(_))), "environment roughness {x}"); + } + for x in [f32::NAN, f32::INFINITY, -0.01, craft_pbr::MAX_SPECULAR + 0.01] { + assert!(matches!(material([0.5; 3], 0.0, 0.5).try_with_weights(x, 1.0), Err(PbrError::BadMaterial(_))), "specular {x}"); + } + for x in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + assert_eq!(try_environment_brdf(x, 0.5), Err(PbrError::BadDirection), "n·v {x}"); + } + let m = material([0.5; 3], 0.0, 0.5); + let ok = [0.0, 0.0, 1.0]; + for d in [[0.0; 3], [f32::NAN, 0.0, 1.0], [0.0, f32::INFINITY, 1.0], [f32::NEG_INFINITY, 0.0, 0.0]] { + assert_eq!(m.try_direct(d, ok, ok), Err(PbrError::BadDirection), "normal {d:?}"); + assert_eq!(m.try_direct(ok, d, ok), Err(PbrError::BadDirection), "view {d:?}"); + assert_eq!(m.try_direct(ok, ok, d), Err(PbrError::BadDirection), "light {d:?}"); + } +} + +/// The default environment is a valid environment for the rest of the crate. +#[test] +fn the_default_environment_prefilters_and_projects() { + let env: EnvImage = default_environment().unwrap(); + let limits = craft_pbr::Limits::default(); + let mips = craft_pbr::try_prefilter(&env, &craft_pbr::PrefilterOptions::default(), &limits).unwrap(); + assert!(mips.iter().all(|m| m.pixels().iter().all(|p| p.iter().all(|c| c.is_finite() && *c >= 0.0)))); + let sh = craft_pbr::try_sh9(&env, &limits).unwrap(); + let up = craft_pbr::irradiance(&sh, [0.66, 0.75, 0.0]).unwrap()[0]; + let down = craft_pbr::irradiance(&sh, [-0.66, -0.75, 0.0]).unwrap()[0]; + assert!(up > down, "the key side is brighter: {up} vs {down}"); +} diff --git a/crates/pbr/tests/it/main.rs b/crates/pbr/tests/it/main.rs index ea24171e56..af2668dee1 100644 --- a/crates/pbr/tests/it/main.rs +++ b/crates/pbr/tests/it/main.rs @@ -4,12 +4,15 @@ mod bench; mod bounds; +mod brdf; mod differential; mod moved; mod numeric; +mod wgsl; -/// Verbatim copies of the apps' previous code, run by `differential`. +/// Verbatim copies of the apps' previous code, run by `differential` and `brdf`. mod reference { + pub mod effectcraft; pub mod materialcraft; pub mod texturecraft; } diff --git a/crates/pbr/tests/it/reference/effectcraft.rs b/crates/pbr/tests/it/reference/effectcraft.rs new file mode 100644 index 0000000000..16a1fc777e --- /dev/null +++ b/crates/pbr/tests/it/reference/effectcraft.rs @@ -0,0 +1,128 @@ +//! The shading functions of EffectCraft's `crates/render/src/three_d/adv/shade.rs` and its +//! `default_environment` from `adv/scene.rs`, at 41da144555, copied as they are apart from +//! visibility and the scaling loop of `default_environment`, which iterates over the channels +//! instead of indexing them. + +pub const PI: f32 = std::f32::consts::PI; + +#[inline] +pub fn dot(a: [f32; 3], b: [f32; 3]) -> f32 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} +#[inline] +pub fn norm(a: [f32; 3]) -> [f32; 3] { + let l = dot(a, a).sqrt(); + if l > 1e-20 { [a[0] / l, a[1] / l, a[2] / l] } else { [0.0, 0.0, -1.0] } +} +#[inline] +fn add(a: [f32; 3], b: [f32; 3]) -> [f32; 3] { + [a[0] + b[0], a[1] + b[1], a[2] + b[2]] +} +#[inline] +fn mix(a: f32, b: f32, t: f32) -> f32 { + a + (b - a) * t +} + +/// GGX / Trowbridge–Reitz normal distribution, `a = roughness²`. +#[inline] +pub fn d_ggx(n_h: f32, a: f32) -> f32 { + let a2 = a * a; + let d = n_h * n_h * (a2 - 1.0) + 1.0; + a2 / (PI * d * d).max(1e-12) +} + +/// Smith–Schlick-GGX geometry term for direct light (`k = (r + 1)² / 8`). +#[inline] +pub fn g_smith(n_v: f32, n_l: f32, rough: f32) -> f32 { + let k = (rough + 1.0) * (rough + 1.0) / 8.0; + let g1 = |x: f32| x / (x * (1.0 - k) + k); + g1(n_v) * g1(n_l) +} + +/// Schlick's Fresnel approximation. +#[inline] +pub fn f_schlick(f0: [f32; 3], v_h: f32) -> [f32; 3] { + let k = (1.0 - v_h).clamp(0.0, 1.0).powi(5); + [f0[0] + (1.0 - f0[0]) * k, f0[1] + (1.0 - f0[1]) * k, f0[2] + (1.0 - f0[2]) * k] +} + +/// Surface parameters used by the direct-light BRDF after texture sampling. +#[derive(Clone, Copy)] +pub struct BrdfSurface { + pub base: [f32; 3], + pub metallic: f32, + pub roughness: f32, + pub specular: f32, + pub diffuse: f32, +} + +/// Cook–Torrance BRDF × N·L × π for one light: (diffuse colour factor, specular colour). +/// Returned as the reflected fraction of the light's irradiance. +pub fn brdf(surface: BrdfSurface, n: [f32; 3], v: [f32; 3], l: [f32; 3]) -> [f32; 3] { + let BrdfSurface { base, metallic, roughness: rough, specular: spec_k, diffuse: diff_k } = surface; + let n_l = dot(n, l); + if n_l <= 0.0 { + return [0.0; 3]; + } + let n_v = dot(n, v).max(1e-4); + let h = norm(add(v, l)); + let n_h = dot(n, h).max(0.0); + let v_h = dot(v, h).max(0.0); + let r = rough.clamp(0.03, 1.0); + let f0 = [mix(0.04 * spec_k, base[0], metallic), mix(0.04 * spec_k, base[1], metallic), mix(0.04 * spec_k, base[2], metallic)]; + let f = f_schlick(f0, v_h); + let d = d_ggx(n_h, r * r); + let g = g_smith(n_v, n_l, r); + let spec = d * g / (4.0 * n_v * n_l).max(1e-4); + let mut out = [0.0; 3]; + for c in 0..3 { + let kd = (1.0 - f[c]) * (1.0 - metallic); + out[c] = (kd * base[c] / PI * diff_k + f[c] * spec) * n_l * PI; + } + out +} + +/// Split-sum environment BRDF (scale, bias) for `F0·A + B` (analytic fit). +#[inline] +pub fn env_brdf(n_v: f32, rough: f32) -> (f32, f32) { + let c0 = [-1.0, -0.0275, -0.572, 0.022]; + let c1 = [1.0, 0.0425, 1.04, -0.04]; + let r = [rough * c0[0] + c1[0], rough * c0[1] + c1[1], rough * c0[2] + c1[2], rough * c0[3] + c1[3]]; + let a004 = (r[0] * r[0]).min((-9.28 * n_v).exp2()) * r[0] + r[1]; + (-1.04 * a004 + r[2], 1.04 * a004 + r[3]) +} + +/// Inverse of `equirect_uv` (texel centre → direction). +pub fn equirect_dir(u: f32, v: f32, rot: f32) -> [f32; 3] { + let phi = (u - 0.5) * 2.0 * PI - rot; + let th = v * PI; + [th.sin() * phi.sin(), -th.cos(), th.sin() * phi.cos()] +} + +pub fn default_environment() -> (u32, u32, Vec<[f32; 4]>) { + // The key region's centre: three quarters up, two thirds toward the viewer (the default + // camera looks +z from -z). + let key = [0.0f32, -0.75, -0.66]; + let (w, h) = (8u32, 4u32); + let mut data = Vec::with_capacity((w * h) as usize); + let (mut mean, mut weight) = (0.0f32, 0.0f32); + for y in 0..h { + let v = (y as f32 + 0.5) / h as f32; + let sa = (v * std::f32::consts::PI).sin(); + for x in 0..w { + let u = (x as f32 + 0.5) / w as f32; + let l = 0.15 + 1.2 * dot(equirect_dir(u, v, 0.0), key).max(0.0); + data.push([l, l, l, 1.0]); + mean += l * sa; + weight += sa; + } + } + // A dim studio: scale the gradient to a weighted mean of exactly 0.3. + let k = if mean.is_finite() && mean > 1e-6 { 0.3 * weight / mean } else { 1.0 }; + for p in &mut data { + for c in p.iter_mut().take(3) { + *c *= k; + } + } + (w, h, data) +} diff --git a/crates/pbr/tests/it/wgsl.rs b/crates/pbr/tests/it/wgsl.rs new file mode 100644 index 0000000000..a2bdfcebd7 --- /dev/null +++ b/crates/pbr/tests/it/wgsl.rs @@ -0,0 +1,224 @@ +//! The WGSL text of the shading functions: it parses and validates, alone and joined with an app's +//! bindings and entry points; every Rust shading function has its WGSL counterpart; and the GPU +//! layouts write the bytes where the WGSL structs read them. + +use craft_pbr::{GpuMaterial, GpuSh9, Limits, MAX_RADIANCE, Material, PbrError, SHADE_WGSL, sh_basis, try_sh9}; +use naga::valid::{Capabilities, ValidationFlags, Validator}; +use naga::{Block, Module, Statement, TypeInner}; + +/// Each Rust shading function and its WGSL counterpart. The README's table lists the same pairs. +const COUNTERPARTS: [(&str, &str); 12] = [ + ("Material::try_new", "pbr_material_clamped"), + ("Material::f0", "pbr_f0"), + ("Material::try_direct", "pbr_direct"), + ("fresnel_schlick", "pbr_fresnel_schlick"), + ("smith_schlick_ggx", "pbr_smith_schlick_ggx"), + ("ggx_distribution", "pbr_ggx_distribution"), + ("try_environment_brdf", "pbr_environment_brdf"), + ("dir_of", "pbr_dir_of"), + ("uv_of", "pbr_uv_of"), + ("sh_basis", "pbr_sh_basis"), + ("irradiance", "pbr_irradiance"), + ("unit", "pbr_unit"), +]; + +/// App-side declarations and entry points in the shape EffectCraft's Advanced 3D shader has: a +/// uniform block, material and SH buffers, an environment texture, and `vs` and `fs` that shade +/// one light and the environment with the shared functions. +const APP_DECLARATIONS: &str = " +struct Globals { + clip: mat4x4, + eye: vec4, + light: vec4, + env: vec4, +}; +@group(0) @binding(0) var g: Globals; +@group(0) @binding(1) var materials: array; +@group(0) @binding(2) var sh: PbrSh9; +@group(0) @binding(3) var env_tex: texture_2d; +@group(0) @binding(4) var env_smp: sampler; +"; + +const APP_ENTRY_POINTS: &str = " +struct VIn { + @location(0) pos: vec3, + @location(1) normal: vec3, + @location(2) material: u32, +}; +struct VOut { + @builtin(position) clip: vec4, + @location(0) pos: vec3, + @location(1) normal: vec3, + @location(2) @interpolate(flat) material: u32, +}; +@vertex +fn vs(v: VIn) -> VOut { + var o: VOut; + o.clip = g.clip * vec4(v.pos, 1.0); + o.pos = v.pos; + o.normal = v.normal; + o.material = v.material; + return o; +} +@fragment +fn fs(i: VOut) -> @location(0) vec4 { + let m = materials[i.material]; + let n = pbr_unit(i.normal); + let v = pbr_unit(g.eye.xyz - i.pos); + var c = pbr_direct(m, n, v, g.light.xyz); + let lv = pbr_specular_levels(m.roughness, u32(g.env.x)); + let uv = pbr_uv_of(reflect(-v, n)); + let a = textureSampleLevel(env_tex, env_smp, uv, lv.x).rgb; + let b = textureSampleLevel(env_tex, env_smp, uv, lv.y).rgb; + c = c + pbr_environment_light(m, dot(n, v), pbr_irradiance(sh, n), mix(a, b, lv.z)); + return vec4(c, 1.0); +} +"; + +/// Parses and validates `source`, failing the test with naga's report. +fn module(source: &str) -> Module { + let module = naga::front::wgsl::parse_str(source).unwrap_or_else(|e| panic!("{}", e.emit_to_string(source))); + if let Err(e) = Validator::new(ValidationFlags::all(), Capabilities::default()).validate(&module) { + panic!("{}", e.emit_to_string(source)); + } + module +} + +fn function_names(m: &Module) -> Vec<&str> { + m.functions.iter().filter_map(|(_, f)| f.name.as_deref()).collect() +} + +fn has_loop(block: &Block) -> bool { + block.iter().any(|s| match s { + Statement::Loop { .. } => true, + Statement::Block(b) => has_loop(b), + Statement::If { accept, reject, .. } => has_loop(accept) || has_loop(reject), + Statement::Switch { cases, .. } => cases.iter().any(|c| has_loop(&c.body)), + _ => false, + }) +} + +/// The members of the struct named `name` as (member name, offset, type), and its size. +fn struct_layout<'m>(m: &'m Module, name: &str) -> (Vec<(&'m str, u32, &'m TypeInner)>, u32) { + let ty = m.types.iter().find(|(_, t)| t.name.as_deref() == Some(name)).unwrap_or_else(|| panic!("no struct {name}")).1; + let TypeInner::Struct { members, span } = &ty.inner else { panic!("{name} is not a struct") }; + let fields = members.iter().map(|mb| (mb.name.as_deref().unwrap_or(""), mb.offset, &m.types[mb.ty].inner)).collect(); + (fields, *span) +} + +fn f32_at(bytes: &[u8], at: u32) -> f32 { + let at = at as usize; + f32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()) +} + +#[test] +fn shading_text_validates_with_an_apps_bindings_and_entry_points() { + let source = [APP_DECLARATIONS, SHADE_WGSL, APP_ENTRY_POINTS].join("\n"); + let m = module(&source); + let entry: Vec<&str> = m.entry_points.iter().map(|e| e.name.as_str()).collect(); + assert_eq!(entry, ["vs", "fs"]); +} + +#[test] +fn shading_text_alone_has_no_bindings_entry_points_or_loops() { + let m = module(SHADE_WGSL); + assert!(m.global_variables.is_empty(), "the text declares a binding"); + assert!(m.entry_points.is_empty(), "the text declares an entry point"); + for (_, f) in m.functions.iter() { + assert!(!has_loop(&f.body), "{:?} loops", f.name); + } + let names = m + .functions + .iter() + .filter_map(|(_, f)| f.name.clone()) + .chain(m.constants.iter().filter_map(|(_, c)| c.name.clone())) + .chain(m.types.iter().filter_map(|(_, t)| t.name.clone()).filter(|n| n.chars().next().is_some_and(char::is_uppercase))); + for name in names { + assert!(name.starts_with("pbr_") || name.starts_with("PBR_") || name.starts_with("Pbr"), "{name} has no pbr prefix"); + } +} + +#[test] +fn every_rust_shading_function_has_a_wgsl_counterpart_listed_in_the_readme() { + let m = module(SHADE_WGSL); + let names = function_names(&m); + let readme = include_str!("../../README.md"); + for (rust, wgsl) in COUNTERPARTS { + assert!(names.contains(&wgsl), "{wgsl}, the counterpart of {rust}, is missing from SHADE_WGSL"); + let row = format!("| `{rust}` | `{wgsl}` |"); + assert!(readme.lines().any(|l| l.starts_with(&row)), "the README has no row for {rust} and {wgsl}"); + } +} + +#[test] +fn gpu_material_bytes_sit_where_pbr_material_reads_them() { + let m = module(SHADE_WGSL); + let (fields, span) = struct_layout(&m, "PbrMaterial"); + assert_eq!(span as usize, GpuMaterial::SIZE); + let mat = Material::try_new([0.1, 0.2, 0.3], 0.4, 0.5).unwrap().try_with_weights(6.0, 0.7).unwrap(); + let bytes = mat.gpu().to_bytes(); + assert_eq!(bytes.len(), span as usize); + let names: Vec<&str> = fields.iter().map(|f| f.0).collect(); + assert_eq!(names, ["base_color", "metallic", "roughness", "specular", "diffuse"]); + for (name, offset, _) in fields { + let read = match name { + "base_color" => vec![f32_at(&bytes, offset), f32_at(&bytes, offset + 4), f32_at(&bytes, offset + 8)], + _ => vec![f32_at(&bytes, offset)], + }; + let want = match name { + "base_color" => mat.base_color().to_vec(), + "metallic" => vec![mat.metallic()], + "roughness" => vec![mat.roughness()], + "specular" => vec![mat.specular()], + _ => vec![mat.diffuse()], + }; + assert_eq!(read, want, "{name} at byte {offset}"); + } +} + +#[test] +fn gpu_sh9_bytes_sit_where_pbr_sh9_reads_them() { + let m = module(SHADE_WGSL); + let (fields, span) = struct_layout(&m, "PbrSh9"); + assert_eq!(span as usize, GpuSh9::SIZE); + let &[(_, offset, &TypeInner::Array { stride, .. })] = fields.as_slice() else { panic!("PbrSh9 is not one array") }; + let coefficients: [[f32; 3]; 9] = std::array::from_fn(|k| std::array::from_fn(|c| (k * 3 + c) as f32 - 4.5)); + let bytes = GpuSh9::try_new(&coefficients).unwrap().to_bytes(); + assert_eq!(bytes.len(), span as usize); + for (k, rgb) in coefficients.iter().enumerate() { + for (c, want) in rgb.iter().enumerate() { + assert_eq!(f32_at(&bytes, offset + stride * k as u32 + 4 * c as u32), *want, "coefficient {k} channel {c}"); + } + } +} + +#[test] +fn gpu_sh9_rejects_coefficients_that_are_not_finite_or_too_large() { + for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX, -1.5 * GpuSh9::MAX_COEFFICIENT] { + let mut c = [[0.5f32; 3]; 9]; + c[8][2] = bad; + assert!(matches!(GpuSh9::try_new(&c), Err(PbrError::BadOption(_))), "{bad}"); + } + let mut c = [[0.5f32; 3]; 9]; + c[0][0] = -GpuSh9::MAX_COEFFICIENT; + assert!(GpuSh9::try_new(&c).is_ok()); +} + +#[test] +fn gpu_sh9_accepts_the_brightest_environments_and_keeps_the_wgsl_sum_finite() { + // A uniform environment and one lit only above the horizon, at the largest radiance. + for lit_rows in [8, 4] { + let env = crate::env_from(16, 8, |_, y| if y < lit_rows { [MAX_RADIANCE; 3] } else { [0.0; 3] }); + let sh = try_sh9(&env, &Limits::default()).unwrap(); + assert!(GpuSh9::try_new(&sh).is_ok(), "{lit_rows} lit rows: {sh:?}"); + } + // pbr_irradiance sums nine coefficients of at most MAX_COEFFICIENT times the basis values. + let mut largest = 0.0f32; + for i in 0..4096u32 { + let [u, v] = craft_pbr::hammersley(i, 4096).unwrap(); + let b = sh_basis(craft_pbr::dir_of(u, v)).unwrap(); + largest = largest.max(b.iter().map(|y| y.abs()).sum()); + } + assert!(largest < 5.0, "basis sum {largest}"); + assert!((5.0 * GpuSh9::MAX_COEFFICIENT).is_finite()); +} diff --git a/crates/pdf/tests/image_default_spaces.rs b/crates/pdf/tests/image_default_spaces.rs new file mode 100644 index 0000000000..b2040e9703 --- /dev/null +++ b/crates/pdf/tests/image_default_spaces.rs @@ -0,0 +1,102 @@ +#![cfg(feature = "read")] +#![allow(clippy::unwrap_used, clippy::panic)] + +//! `RasterImage::default_color_space` answers each draw of an image by the `/DefaultCMYK` in +//! scope at that draw (ISO 32000-2 §8.6.5.6). + +#[cfg(feature = "interpret")] +mod draws { + use craft_pdf::interpret::{ + BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache, InterpreterSettings, Paint, PathDrawMode, SoftMask, + TransformExt, font::Glyph, + }; + use kurbo::{Affine, BezPath, Rect}; + + const CGATS: &[u8] = include_bytes!("../../../vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc"); + + /// Whether each raster image drawn was drawn in a default color space. + #[derive(Default)] + struct Defaults(Vec); + + impl Device<'_> for Defaults { + fn set_soft_mask(&mut self, _: Option>) {} + fn set_blend_mode(&mut self, _: BlendMode) {} + fn draw_path(&mut self, _: &BezPath, _: Affine, _: &Paint<'_>, _: &PathDrawMode) {} + fn push_clip_path(&mut self, _: &ClipPath) {} + fn push_transparency_group(&mut self, _: f32, _: Option>, _: BlendMode) {} + fn draw_glyph(&mut self, _: &Glyph<'_>, _: Affine, _: Affine, _: &Paint<'_>, _: &GlyphDrawMode) {} + fn draw_image(&mut self, image: Image<'_, '_>, _: Affine) { + if let Image::Raster(r) = image { + self.0.push(r.default_color_space().is_some()); + } + } + fn pop_clip_path(&mut self) {} + fn pop_transparency_group(&mut self) {} + } + + /// A page that draws `page`, whose `/Fm0` form draws `form` with a `/DefaultCMYK` in its + /// resources. Both have `/Im0`, a 1 × 1 DeviceCMYK image XObject, and `/CS0`, a `/ColorSpace` + /// resource that is DeviceCMYK. + fn draw(page: &str, form: &str) -> Vec { + let mut objects: Vec> = vec![ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 4 2] /Contents 4 0 R /Resources << /XObject << /Im0 5 0 R /Fm0 7 0 R >> /ColorSpace << /CS0 /DeviceCMYK >> >> >>" + .to_vec(), + ]; + let stream = |dict: &str, data: &[u8]| { + let mut s = format!("<< {dict} /Length {} >> stream\n", data.len()).into_bytes(); + s.extend_from_slice(data); + s.extend_from_slice(b"\nendstream"); + s + }; + objects.push(stream("", page.as_bytes())); + objects.push(stream("/Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceCMYK /BitsPerComponent 8", &[0, 0, 0, 255])); + objects.push(stream("/N 4", CGATS)); + objects.push(stream( + "/Type /XObject /Subtype /Form /BBox [0 0 4 2] /Resources << /XObject << /Im0 5 0 R >> /ColorSpace << /DefaultCMYK [/ICCBased 6 0 R] /CS0 /DeviceCMYK >> >>", + form.as_bytes(), + )); + let mut bytes = b"%PDF-1.7\n".to_vec(); + let mut offsets = vec![]; + for (i, object) in objects.iter().enumerate() { + offsets.push(bytes.len()); + bytes.extend_from_slice(format!("{} 0 obj ", i + 1).as_bytes()); + bytes.extend_from_slice(object); + bytes.extend_from_slice(b" endobj\n"); + } + let xref = bytes.len(); + bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes()); + for offset in offsets { + bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes()); + } + bytes.extend_from_slice(format!("trailer << /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF", objects.len() + 1).as_bytes()); + + let pdf = craft_pdf::open_slice(&bytes, None).unwrap(); + let page = &pdf.pages()[0]; + let cache = InterpreterCache::new(); + let mut context = + Context::new(page.initial_transform(true).to_kurbo(), Rect::new(0.0, 0.0, 4.0, 2.0), &cache, page.xref(), InterpreterSettings::default()); + let mut defaults = Defaults::default(); + craft_pdf::interpret_page(page, &mut context, &mut defaults).unwrap(); + defaults.0 + } + + const INLINE: &str = "BI /W 1 /H 1 /CS /CMYK /BPC 8 /F /AHx ID 000000FF> EI"; + const INLINE_CS0: &str = "BI /W 1 /H 1 /CS /CS0 /BPC 8 /F /AHx ID 000000FF> EI"; + + #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] + #[cfg_attr(not(target_arch = "wasm32"), test)] + fn an_image_xobject_reports_the_default_of_each_draw() { + assert_eq!(draw("/Im0 Do /Fm0 Do /Im0 Do", "/Im0 Do"), [false, true, false]); + } + + #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] + #[cfg_attr(not(target_arch = "wasm32"), test)] + fn inline_images_report_the_default_of_each_draw() { + // A device space named directly, and one named by a `/ColorSpace` resource. + for inline in [INLINE, INLINE_CS0] { + assert_eq!(draw(&format!("{inline} /Fm0 Do {inline}"), inline), [false, true, false], "{inline}"); + } + } +} diff --git a/crates/ui-contract/src/contract/body/regions.rs b/crates/ui-contract/src/contract/body/regions.rs index 5b4025a61e..de994c9ea4 100644 --- a/crates/ui-contract/src/contract/body/regions.rs +++ b/crates/ui-contract/src/contract/body/regions.rs @@ -283,11 +283,12 @@ impl BodyHooks<'_> { regions.footer.max.y = bottom + self.measured_footer.y; } let mut footer_rect = regions.footer; + // The footer's start edge moves to the control column's, never past its own end edge. if props.label.is_some() { if rtl { - footer_rect.max.x = body_rect.max.x.clamp(footer_rect.min.x, footer_rect.max.x); + footer_rect.max.x = body_rect.max.x.min(footer_rect.max.x).max(footer_rect.min.x); } else { - footer_rect.min.x = body_rect.min.x.clamp(footer_rect.min.x, footer_rect.max.x); + footer_rect.min.x = body_rect.min.x.max(footer_rect.min.x).min(footer_rect.max.x); } } let offset = if rtl { regions.footer.max.x - footer_rect.max.x } else { footer_rect.min.x - regions.footer.min.x }; @@ -473,7 +474,9 @@ impl<'b> BodyHooks<'b> { } else if !self.given.0 { self.shared_width(room.x, props).max(inner.width()) } else { - inner.width() + // A container given less width than its padding has an inverted inner rect: its regions take no width, + // at their start edge. + inner.width().max(0.0) }; // A measure with no room limit along x offers an unbounded width. Left to right the body runs from its start // edge to +inf as egui allows; right to left its start edge is the right one, and an unbounded width would put diff --git a/crates/ui-contract/tests/it/layout/body.rs b/crates/ui-contract/tests/it/layout/body.rs index 3cea18b400..4d3b5e9864 100644 --- a/crates/ui-contract/tests/it/layout/body.rs +++ b/crates/ui-contract/tests/it/layout/body.rs @@ -564,3 +564,24 @@ fn a_scrolling_container_in_a_right_to_left_row_measures_and_shows_finite() { assert!(panel.min.x > beside.max.x - SLACK, "under RTL the container is right of the probe after it: {dump}"); } } + +/// A labelled container with a footer, shown in a rect narrower than its padding, in either direction: its measuring +/// run places the footer under the control column of a line with no room, and the container shows. +#[trial] +fn a_labelled_container_narrower_than_its_padding_places_its_footer() { + use craft_ui::contract::{FooterRegion, Pad, SideLabel}; + use craft_ui_test_kit::body::Slab; + for direction in [Direction::Ltr, Direction::Rtl] { + let (_, rects) = lay_out(Some(direction), |ui| { + let at = Rect::from_min_size(ui.available_rect_before_wrap().min, Vec2::new(4.0, 60.0)); + let props = ContainerProps::new().label(SideLabel::new()).footer(FooterRegion::new()).pad(Pad::Regular).sizing(Sizing::FillWidth); + let narrow = ui.scope_builder(egui::UiBuilder::new().max_rect(at), |ui| { + Slab::new(props).label("Balance").id_salt("field").show(ui, |ui, _| { + Block::new(ITEM).show(ui); + }) + }); + vec![narrow.inner.output.rect] + }); + assert!(rects[0].min.is_finite() && rects[0].max.is_finite(), "{direction:?}: the container shows at {:?}", rects[0]); + } +} diff --git a/crates/update/src/process.rs b/crates/update/src/process.rs index 29e5841871..df20ada97e 100644 --- a/crates/update/src/process.rs +++ b/crates/update/src/process.rs @@ -716,11 +716,11 @@ pub(crate) mod inherited_pipe_tests { }); // The output is more than 8 MB, so a failure shows only its length. assert_eq!(result.map(|output| output.len()), Err(HelperFailure::Unfinished("the fixture didn't finish within 5 seconds".into()))); - // Lets the descendant go and waits until it has closed its end. The read time limit only - // stops a broken test. + // Lets the descendant go and waits until it has closed its end. The read time limit set when + // it connected only stops a broken test. macOS refuses socket options once both directions + // are shut, which happens as soon as the descendant closes its end after this shutdown. let mut holder = holder.expect("the direct child didn't exit while the descendant held its output"); holder.shutdown(std::net::Shutdown::Write).unwrap(); - holder.set_read_timeout(Some(HOLD)).unwrap(); assert_eq!(holder.read_to_end(&mut Vec::new()).unwrap(), 0); } } diff --git a/crates/xls/src/read.rs b/crates/xls/src/read.rs index 8fdf5e473e..3820352e4b 100644 --- a/crates/xls/src/read.rs +++ b/crates/xls/src/read.rs @@ -16,7 +16,7 @@ use crate::records::{Cursor, Record, Records}; use crate::{Error, Limits, Read, Warning, cond, drawing, notes, styles}; const MAX_STRINGS: usize = 4_000_000; -const MAX_SHEETS: usize = 4096; +pub(crate) const MAX_SHEETS: usize = 4096; const MAX_NAMES: usize = 65_536; const MAX_XFS: usize = 65_536; const MAX_MERGES: usize = 100_000; diff --git a/crates/xls/src/testing.rs b/crates/xls/src/testing.rs index 1aaaf347e0..d57a5ee56f 100644 --- a/crates/xls/src/testing.rs +++ b/crates/xls/src/testing.rs @@ -54,13 +54,24 @@ fn number(cell: &str) -> Option<(u16, f64)> { /// Number records, a cell `date:` is a Number with the date format `m/d/yyyy` (built-in /// format 14), an empty cell is left out, and everything else, including a `date:` cell whose /// serial is not a number, goes through the shared-string table (as UTF-16 when it isn't -/// Latin-1). A nonempty cell past row 65,535 or column 255 (zero-based) returns -/// [`craft_cfb::Error::Invalid`] naming its sheet, row and column, and a compound file that cannot -/// be written returns the writer's error. +/// Latin-1). No sheets, or more than the 4,096 sheets [`crate::read()`] accepts, returns +/// [`craft_cfb::Error::Invalid`] naming the count. A nonempty cell past row 65,535 or column 255 +/// (zero-based) returns [`craft_cfb::Error::Invalid`] naming its sheet, row and column, and a +/// compound file that cannot be written returns the writer's error. /// /// shortcut: characters outside the Basic Multilingual Plane are dropped, sheet names are cut at /// 255 characters and strings at 4,000 (so each fits one record); lift when a fixture needs more. pub fn workbook(sheets: &[(&str, Vec>)]) -> Result, craft_cfb::Error> { + if sheets.is_empty() { + return Err(craft_cfb::Error::Invalid("fixture has no sheets; craft-xls reads a workbook only when it has a worksheet".into())); + } + if sheets.len() > crate::read::MAX_SHEETS { + return Err(craft_cfb::Error::Invalid(format!( + "fixture has {} sheets; craft-xls can read at most {}", + sheets.len(), + crate::read::MAX_SHEETS + ))); + } let mut sst: Vec<&str> = Vec::new(); let mut references = 0usize; for (name, rows) in sheets { diff --git a/crates/xls/tests/it/read.rs b/crates/xls/tests/it/read.rs index 0c5e91eb82..93cc4c484b 100644 --- a/crates/xls/tests/it/read.rs +++ b/crates/xls/tests/it/read.rs @@ -634,6 +634,25 @@ fn the_fixture_writer_reads_back() { assert_eq!(v(&wb, 1, "A1"), text("Name")); } +/// A fixture holds 1 to 4,096 sheets, the counts the reader accepts; any other count is an error +/// naming it, returned before anything is written. +#[test] +fn the_fixture_writer_rejects_a_sheet_count_the_reader_refuses() { + let names: Vec = (0..4097).map(|i| format!("S{i}")).collect(); + let sheets: Vec<(&str, Vec>)> = names.iter().map(|n| (n.as_str(), Vec::new())).collect(); + match craft_xls::testing::workbook(&sheets) { + Err(craft_cfb::Error::Invalid(m)) => assert!(m.contains("4097 sheets") && m.contains("at most 4096"), "{m}"), + other => panic!("{:?}", other.map(|b| b.len())), + } + match craft_xls::testing::workbook(&[]) { + Err(craft_cfb::Error::Invalid(m)) => assert!(m.contains("no sheets"), "{m}"), + other => panic!("{:?}", other.map(|b| b.len())), + } + let read = craft_xls::read(&craft_xls::testing::workbook(&sheets[..4096]).unwrap()).unwrap(); + assert_eq!(read.warnings, []); + assert!(read.workbook.sheets.iter().map(|s| s.name.as_str()).eq(names[..4096].iter().map(String::as_str))); +} + #[test] fn a_fixture_that_cannot_be_written_returns_the_writer_error() { assert_eq!(craft_xls::testing::compound("", b"x"), Err(craft_cfb::Error::BadName(String::new()))); diff --git a/vendor/README.craft-reader.md b/vendor/README.craft-reader.md index 405799ceb6..173e1a66b8 100644 --- a/vendor/README.craft-reader.md +++ b/vendor/README.craft-reader.md @@ -114,7 +114,8 @@ the last filter of an image of known size may produce (1 GiB by default), and `with_max_image_pixels` sets the most pixels an image or mask may have for the interpreter to decode it (2^28 by default, at most 2^32), before and after its codec decodes it. With 64-bit pointers a caller may raise either one; elsewhere a raise is clamped to the default. -`image_size_ok` keeps the 2^28 default. An 8-bit `DeviceRGB` image with the default or inverted `/Decode` and no transfer function keeps its decoded samples as its +The CCITT and JPEG 2000 decoders hold an image to the document's pixel limit; JBIG2 keeps +its own 2^28. `image_size_ok` and `ccitt_size_ok` keep the 2^28 default. An 8-bit `DeviceRGB` image with the default or inverted `/Decode` and no transfer function keeps its decoded samples as its RGB data instead of copying them into a second buffer. Tests: `decode_limits_tests::image_limits_default_and_caller_figures` in hayro-syntax and `image_limits` in `crates/pdf/tests/interpretation.rs`. @@ -167,7 +168,8 @@ Hostile-input bounds (CodeRabbit findings): - A CID font's `/W2` run that starts past CID 65535 is skipped as in `/W`, instead of overflowing and discarding the whole table. - CCITT images: `ccitt_size_ok` (inherited PdfCraft ledger item 2) allows at most 2^20 - columns and 2^28 pixels (columns × rows) before the decoder allocates. A `/Columns` past + columns and 2^28 pixels (columns × rows) before the decoder allocates; the decoder applies + the document's pixel limit in place of 2^28. A `/Columns` past `u32::MAX` is refused rather than wrapped to a small width. `/Rows` follows PdfCraft (17) and (19): `/Rows 0` or a value below `/Height` decodes to the image height, and decoding still stops where the data ends. @@ -201,9 +203,10 @@ raster tests are adapted in `tests/upstream_raster.rs` and the text contracts in `tests/upstream_text.rs`. (P8)'s PdfCraft test needs a Japanese substitute font and is not ported. - A CCITT image with `/Rows 0` (unknown height) decodes at most the rows that fit the stream's - output limit (counted in 1-bit rows) and 2^28 pixels; a known height is clamped the same way. - Before, it decoded to the end of the data, and a bit of 2D code can repeat a whole row. -- A JPEG 2000 image over 2^28 pixels, or over its output limit (at least 64 MiB), by the + output limit (counted in 1-bit rows) and the document's pixel limit (2^28 by default); a + known height is clamped the same way. Before, it decoded to the end of the data, and a bit of + 2D code can repeat a whole row. +- A JPEG 2000 image over the document's pixel limit (2^28 by default), or over its output limit (at least 64 MiB), by the codestream's own dimensions is refused before decoding, and its buffer is reserved fallibly: the image dictionary's smaller size no longer stands in for the size the decoder allocates. @@ -301,6 +304,15 @@ or DefaultGray profile and the CMYK simulation of patch 36. PdfCraft's eight ras adapted in `tests/upstream_raster.rs` (`default_color_spaces`); the plate case is `default_color_spaces_leave_device_color_on_its_plates` in `tests/plates.rs`. +A craft-libs patch on top of it, labeled `Craft patch (default spaces)` in code comments: +`RasterImage::default_color_space` returns the default color space that one draw of an image +uses in place of its device space, with the cache key of the object it was read from, or `None` +when the draw uses the image's own space. The same image XObject drawn inside and outside a +default's scope reports each draw by its own scope. An inline image that names a `/ColorSpace` +resource that is a device space reports the default substituted for it too +(`named_color_space_and_default` in hayro-interpret `interpret/mod.rs`). Tests: +`crates/pdf/tests/image_default_spaces.rs`. + A rendering speedup from the [PdfCraft revision 0b670caf4a090e9d83a7f41a84b4cb2144a2d33e ledger](https://github.com/storytold/pdfcraft/blob/0b670caf4a090e9d83a7f41a84b4cb2144a2d33e/vendor/README.md), hayro-interpret (35) with hayro (19), PdfCraft #3296, marked `PdfCraft patch (#3296)` because the plate-mode code uses (35) for #2770's own numbers. `EncodedShadingPattern::extent` is the diff --git a/vendor/hayro-interpret/SOURCE.json b/vendor/hayro-interpret/SOURCE.json index bffa37b555..18f3363dd4 100644 --- a/vendor/hayro-interpret/SOURCE.json +++ b/vendor/hayro-interpret/SOURCE.json @@ -20,13 +20,13 @@ "path": "Cargo.lock", "source_sha256": "a8a0e3460e43e7305385c01c3060ed34e4fdf13495d61b8a6bd1314d8a1c91a1", "source_git_blob": "c10e1749882fc27c11322f338b7e7f9568643b3c", - "sha256": "a8a0e3460e43e7305385c01c3060ed34e4fdf13495d61b8a6bd1314d8a1c91a1" + "sha256": "c9109a3318b0ae9bd674ef44244725d11c8cd7733ee0993396a4af8051b3ca5c" }, { "path": "Cargo.toml", "source_sha256": "cdb6fc309585747b98c029d2e2d48f31bc06595871aa3cce041786e5f78f61bf", "source_git_blob": "8141e63df329caeebd66392643848cdbdae5fb4e", - "sha256": "cdb6fc309585747b98c029d2e2d48f31bc06595871aa3cce041786e5f78f61bf" + "sha256": "fada6f6980bb507802ebb15a743e233af5ace27ec04cd1fa2226d62df219676b" }, { "path": "Cargo.toml.orig", @@ -176,49 +176,49 @@ "path": "src/cache.rs", "source_sha256": "76b5dc066330666a50a32124856306b72c98e646346263bd8a269bc99e5a0d42", "source_git_blob": "e253a7b8c7dbfbfa2f7dc1f6c582559962060b94", - "sha256": "c63ed890ead39cc6205746063f90689b7a617e8c14a35e6ee1b955550d1230a5" + "sha256": "de57929a3207a0a19f0ed7827ec040ef79364507094f41848bd6cfa9ace26874" }, { "path": "src/color.rs", "source_sha256": "799ce29bb5e59c8fc94db202873e48c2047dd35962e6f26efd215156c47158c1", "source_git_blob": "56bb04f24c04ba33ab6bf99c02a24735670959ad", - "sha256": "72935834f00f5f04f1baa418e12040b5a413e8620be7356337605a0ab63f5c7a" + "sha256": "00b8c834f3a70ea06bbd89e78e4668ce490129906fb9a9757b128296c0a2c5bc" }, { "path": "src/context.rs", "source_sha256": "dc2be553958ee3f5e5e644a77a0301723bae9ca027a352c13b9caaf549cc0e56", "source_git_blob": "d6772baa15ebb95d3ba2d1f54ce5c250ad1e8137", - "sha256": "221174b2b65824e1489e8d0f61ac5c81b828caf7f5c7053e27c84a6657857f4c" + "sha256": "3beef4bd55188e042c6eea83aa77ebeca259f9c503deab671352a479d575eb61" }, { "path": "src/convert.rs", "source_sha256": "a361962285ef6153b4c10f75c8c7e31a2267b12481f85e5ff520915e79a6f0ba", "source_git_blob": "e768911415945256824d9759b4aa0490e0c80377", - "sha256": "a361962285ef6153b4c10f75c8c7e31a2267b12481f85e5ff520915e79a6f0ba" + "sha256": "e42c82eb291fd02261a2b93aebeb7d8c9c95f0a1d733263f9658c72921ddb56b" }, { "path": "src/device.rs", "source_sha256": "6f0c1203d1e60724cdd11e9a230249247a70f578c4a7ccb9bf39a23411b32db6", "source_git_blob": "36c64a23fd23f6c4abad941077cf93296a67841f", - "sha256": "8fff824fd81c36dc20a194697b10cd752928b09301f9287b0bb6ed00978ac723" + "sha256": "2b227f7feb2a75baaea325a043efa3a27c276ba2cfbd7e61a1ae55375c219d0a" }, { "path": "src/encode.rs", "source_sha256": "674a97c48cc62e9a218f843246776528173c36c00aa96a1e4c291c1d912c29c6", "source_git_blob": "b3f830ba2dcdb7069ea73706be43c55be398f670", - "sha256": "46c9773f05c329cad20f3126394f89a551ee393569c58911b0a921be8c020376" + "sha256": "66e5a22c1125e8918f2f2a0b84324fcf3b0ad25e6b182d4277e90fc5163cee06" }, { "path": "src/font/blob.rs", "source_sha256": "30a9dadf498829ee03eb1ddc6deaeb09a06ee42415f288d46f4a67640582c575", "source_git_blob": "6eabc26b9bc30bdc51f0b5fdd5e4b556d7583ec5", - "sha256": "8c39f3ef95c48054d4aacaeb17189193c075df42fc767eee596bc4dbf2453d5f" + "sha256": "831e96f92127faa7225d5cde341e9308ddf0f440b6a20280c14bbc712bc4f72e" }, { "path": "src/font/cid.rs", "source_sha256": "c1dbe7fe5b7f7092d97b84063008df54aebf87db4ba1fdb3a179fab9fe6674b8", "source_git_blob": "b99dcbc116ca1169df3a229eafd05ee5b9204626", - "sha256": "6c9927c47893edacab4a3258d4ec72b4d3cc2dd25c518e308884321110847ab6" + "sha256": "a2e240a3ca36da75c9e353cbbf9db873d446f263d21c6c252ff01559bf9f83e1" }, { "path": "src/font/generated/glyph_names.rs", @@ -290,7 +290,7 @@ "path": "src/font/mod.rs", "source_sha256": "7e6411927d91205ca76c6b59f9d737cd1104d066f8cfcc0a87f481016ef30313", "source_git_blob": "7c8c8d086d59139df791cdb6952506473ec4b5a7", - "sha256": "c0c903cb8a33ab863412c407ad10181adec0d22b81c899fc5225de14d8878091" + "sha256": "b58ee45b8c4a4d1de36eadc11363a8620ac56202646c937c1a012539372883bc" }, { "path": "src/font/outline.rs", @@ -302,25 +302,25 @@ "path": "src/font/standard_font.rs", "source_sha256": "af3c51592c086671cb127745d4351d1380ef1212aee325099f1e933607995d7d", "source_git_blob": "139454a0b21eb992e9e52bf73c85e965c0f86cda", - "sha256": "01241c51fe85d94fa1bc3963e16a45be7c292104b204c37704e636ba2c0b0c5d" + "sha256": "03c8e9ffd3726e13713a6e8f5e25ef246939e52d77fcaa412a72344d2eb41790" }, { "path": "src/font/true_type.rs", "source_sha256": "278fed0cddcc43cc7d616200dcefb45720db9d560f54e41a82c281c3163b411d", "source_git_blob": "b36266985942b4d7e2970f9edf7329c4edbcfa11", - "sha256": "a1262fd7efcf358b85b7863c97733a40e5df4295a9d1b54f66b1bada5898f600" + "sha256": "8ba289682e9835fb9b6b7983eb1192c7eaa80e6467eed64b90d387682bee9776" }, { "path": "src/font/type1.rs", "source_sha256": "431b1fe86ca51bd993e81084a64c3e8ed8b90a67385a30eb4ffedfdd98c6f96b", "source_git_blob": "02f76bfb8095041e3d54df014190047de46be4c5", - "sha256": "af73de5038ee590bb062ee1e610a60e5e4f51d109ae765922ce9669b4e36ce95" + "sha256": "5df2d753500f0e52ee33c05ab1027185a7f2d8a56227dd58cb1a3da7a253fc85" }, { "path": "src/font/type3.rs", "source_sha256": "bc33784f0dd3e599028b28b3696b9e4380cbff08f4c4e6299dee51f8df5eb08f", "source_git_blob": "c0e0d0b2df8f38183b8e23e9e8f644c0b81d0529", - "sha256": "1778362c6c4a5cb015e756fd3f36afd7482f20a230dde0206f4339da922eaca4" + "sha256": "ab13ed284836e01bed3fb28cdbe3c44e63195d06157e9c6505c8a12ca740527c" }, { "path": "src/function/mod.rs", @@ -362,31 +362,31 @@ "path": "src/interpret/mod.rs", "source_sha256": "2b002323055bc19aa497e92c81ad8e06dc60ee03686cad89366df4ac7c7a06b2", "source_git_blob": "fe08fc284ba7c914d1414b68a5a346674a6f910f", - "sha256": "3f8958e8d234f00b24478acb8081aa1aaffdca6b8a12b24c4abc6f534ce09a05" + "sha256": "13620d8610850181f5e59b172b4d97ea4210c70b123ba2a98325e1fb794236bc" }, { "path": "src/interpret/path.rs", "source_sha256": "a5defbc4b883b262662f7e7474a00ec1f97dbef8c03b8669859f624f5d02344b", "source_git_blob": "838ea099f11d918d6e333e32503368be864689f8", - "sha256": "0e4d2dc0a2d5a2c5cdc0d1d9358fcf3b0854e8d24d002ce1830a1b4def786bc8" + "sha256": "a334e71b6ea0b2a3014b865b8b48e7b558033fe310effc202ca03e06926b0572" }, { "path": "src/interpret/state.rs", "source_sha256": "dce778291b13f6df83c8c13aee22f60edd033ec9f7d89309ef148d46d3ba9814", "source_git_blob": "95b773fb5cc434ab8db362d00e4e5180a8b740c9", - "sha256": "bc5e73c3b29cdfe9d5f5036ea82beb2cf5a12ccd8a8c93277c15670b5f81ec08" + "sha256": "e48f5874edd4db8db4453dfc1f3b13fe23801d2534f8aabfb132694ef87be68f" }, { "path": "src/interpret/text.rs", "source_sha256": "35eafa80147aea635bdef127c33ace20e1695e11e87c7bfe1e035c886806ff30", "source_git_blob": "ddec0400ea7a639c14769ac9ee7e137d000b3efd", - "sha256": "b34117d28ca7987833626f2e938abe4dd5d02ea869db7b0bdc1b8a264d775f9c" + "sha256": "ef5c39c97b54d08837763ca597f70d27f2dc2865cec11fb411400509d9fffe8c" }, { "path": "src/lib.rs", "source_sha256": "ea3fa23b74f99b5382798f90b7e9f0e3edca354ee26ea92fe26a91ee5c0195c9", "source_git_blob": "24c3be295783d7a53ac6bc39d93e539883480cd4", - "sha256": "ea3fa23b74f99b5382798f90b7e9f0e3edca354ee26ea92fe26a91ee5c0195c9" + "sha256": "3473d9640da637f95252611d1edb601efa9327c117d5580913c670dda696dd6e" }, { "path": "src/log.rs", @@ -398,13 +398,13 @@ "path": "src/ocg.rs", "source_sha256": "439455f65b8ad6ed9b0306536c2f75fa5f3fdda42ed4ca351ec3d340c38dc330", "source_git_blob": "c59b70df4be6a83485360dacd76bead9f80c7f94", - "sha256": "35dadd9fc07e3e5754e208fc5c0c588776ff6bff249aa0eee9848a8fde8b4f08" + "sha256": "0d1ebb4ce39088e3959096ff100383e3c5aca7b5164d582842339c9fb05cc9d1" }, { "path": "src/pattern.rs", "source_sha256": "17b49a465275c20e6645dea9443f2cb3a64c594925fd860e74b80b44d5344e37", "source_git_blob": "9295f51709f8915951d7b9afca9411651d65a1f8", - "sha256": "e57d4de60126eafa0da2113af12bbbde1aabd15554f1ee26f6551b8219f4ede5" + "sha256": "1ee9705afa285ddeb4c287e83e86906bdcc525a738b41d17164d1f751e2c01b6" }, { "path": "src/shading.rs", @@ -416,13 +416,13 @@ "path": "src/soft_mask.rs", "source_sha256": "6cd9c59c0cff580879c1f06ff40f3537c04b719bdb3ea59008fa1ab7559db5dd", "source_git_blob": "4d97d565b53c820fa927fbba8c3dda6acead7f34", - "sha256": "fe3da157602bf5b16a452ecbe1d8d554af992a5b9dfaa771dd23c2e2e66d730b" + "sha256": "b019e76429285f0e4b56217374ae15889902fa90fc432a84545efc5d380a4985" }, { "path": "src/types.rs", "source_sha256": "0e66569b8a7dc243b0a384cf1d3615ca62bf660b5324236f2594609bdfddfd46", "source_git_blob": "64d2b849bdd3fdcd4ebfd76845edcef77b625fbd", - "sha256": "669fb4a9427193a962b7cda70656b688795ea691f67ae52333124807ba88006c" + "sha256": "955b933c9372ecff5ad6e136cc3c42cec4fe8d9b0b5439513a560ca4189a8ca4" }, { "path": "src/util.rs", @@ -434,7 +434,7 @@ "path": "src/x_object.rs", "source_sha256": "e1c51e96a335c32c122011b2d05c5020c36a33c2c73342ba173c28a3e2fe0219", "source_git_blob": "21b134ce8cd9604399cd0776febf923d69c02673", - "sha256": "d752a8c44c0a3918e9fc130c4e59a1708ae7bfa2a3c95b700dfe77da15f43f66" + "sha256": "b430f23bfe5399c43eeb3fffb14b4fb2995c5b1137df61d1c647f7b0209f5eec" } ], "compatibility_reference": { diff --git a/vendor/hayro-interpret/src/interpret/mod.rs b/vendor/hayro-interpret/src/interpret/mod.rs index fd80f27ede..8b29008d8f 100644 --- a/vendor/hayro-interpret/src/interpret/mod.rs +++ b/vendor/hayro-interpret/src/interpret/mod.rs @@ -550,19 +550,30 @@ fn named_color_space<'a>( defaults: &DefaultColorSpaces<'_, '_>, context: &mut Context<'a>, ) -> Option { + named_color_space_and_default(name, resources, defaults, context).map(|(space, _)| space) +} + +/// Craft patch (default spaces): [`named_color_space`], with the cache key of the default it +/// substituted for a device space, if it did. +fn named_color_space_and_default<'a>( + name: &hayro_syntax::object::Name<'_>, + resources: &Resources<'a>, + defaults: &DefaultColorSpaces<'_, '_>, + context: &mut Context<'a>, +) -> Option<(ColorSpace, Option)> { if let Some(named) = ColorSpace::new_from_name(name) { let default = DeviceFamily::of_name(name).and_then(|family| defaults.get(family)); - return Some(default.map_or(named, |(space, _)| space)); + return Some(default.map_or((named, None), |(space, key)| (space, Some(key)))); } let resource = resources.get_color_space(name); - if let Some((space, _)) = resource + if let Some((space, key)) = resource .as_ref() .and_then(DeviceFamily::of_object) .and_then(|family| defaults.get(family)) { - return Some(space); + return Some((space, Some(key))); } - context.get_color_space(resources, name) + context.get_color_space(resources, name).map(|space| (space, None)) } /// Interprets the instructions that `ops` yields, until they run out or the caller cancels. It runs @@ -1100,7 +1111,7 @@ fn interpret_window<'a>( // resource, draws in its default. if let Some(x_object) = ImageXObject::new( i.0, - |name| named_color_space(name, resources, &defaults, context), + |name| named_color_space_and_default(name, resources, &defaults, context), &warning_sink, Some(&extended_warning_sink), &cache, diff --git a/vendor/hayro-interpret/src/types.rs b/vendor/hayro-interpret/src/types.rs index ecd42d584f..2630652783 100644 --- a/vendor/hayro-interpret/src/types.rs +++ b/vendor/hayro-interpret/src/types.rs @@ -118,6 +118,15 @@ impl RasterImage<'_> { func(image); } } + + /// Craft patch (default spaces): the default color space (`/DefaultGray`, `/DefaultRGB` or + /// `/DefaultCMYK` of the resources in scope, ISO 32000-2 §8.6.5.6) that this draw of the + /// image uses in place of its device space, with the cache key of the object it was read + /// from. `None` when the image is drawn in its own color space. The same image drawn where a + /// default is in scope and where none is answers each draw by its own scope. + pub fn default_color_space(&self) -> Option<(&crate::color::ColorSpace, u128)> { + self.0.default_color_space() + } } /// Craft patch (flatten): a raster image decoded into inks rather than RGB. diff --git a/vendor/hayro-interpret/src/x_object.rs b/vendor/hayro-interpret/src/x_object.rs index e127674004..44d5c6a417 100644 --- a/vendor/hayro-interpret/src/x_object.rs +++ b/vendor/hayro-interpret/src/x_object.rs @@ -574,10 +574,11 @@ impl<'a> ImageXObject<'a> { /// PdfCraft patch (#3018): an image in a device space is drawn in its default color space /// from `defaults`. Masks have none to replace, and `resolve_cs` (an inline image's named - /// color space) substitutes its own. + /// color space) substitutes its own. Craft patch (default spaces): `resolve_cs` also gives the + /// cache key of the default it substituted, if it did (see `default_color_space`). pub(crate) fn new( stream: &Stream<'a>, - resolve_cs: impl FnOnce(&Name<'_>) -> Option, + resolve_cs: impl FnOnce(&Name<'_>) -> Option<(ColorSpace, Option)>, warning_sink: &WarningSinkFn, extended_warning_sink: Option<&ExtendedWarningSinkFn>, cache: &Cache, @@ -624,9 +625,11 @@ impl<'a> ImageXObject<'a> { .and_then(|c| ColorSpace::new_allowing_tableless(c, cache)) // Inline images can also refer to color spaces by name. .or_else(|| { - cs_obj + let (space, key) = cs_obj .and_then(|c| c.into_name()) - .and_then(|n| resolve_cs(&n)) + .and_then(|n| resolve_cs(&n))?; + default_space = key; + Some(space) }) } }; @@ -870,6 +873,13 @@ impl<'a> ImageXObject<'a> { &self.stream } + /// Craft patch (default spaces): the default color space this draw uses in place of the + /// image's device space (PdfCraft patch #3018), if one is, with the cache key of the object + /// it was read from. + pub(crate) fn default_color_space(&self) -> Option<(&ColorSpace, u128)> { + Some((self.color_space.as_ref()?, self.default_space?)) + } + /// PdfCraft patch (review on #3884): whether `resolve_alpha` takes this image's alpha from /// a colour-key `/Mask` array: no `/SMaskInData 1` and no `/SMask` stream before it. fn has_colour_key_mask(&self) -> bool { diff --git a/vendor/hayro-syntax/src/decode_limits_tests.rs b/vendor/hayro-syntax/src/decode_limits_tests.rs index 5d2585c07d..1d9d3c118e 100644 --- a/vendor/hayro-syntax/src/decode_limits_tests.rs +++ b/vendor/hayro-syntax/src/decode_limits_tests.rs @@ -206,6 +206,30 @@ fn image_limits_default_and_caller_figures() { assert_eq!(crate::filter::decode_limit(&small, true, limits.with_max_decoded_image(100)), 100); } +/// A document's pixel limit reaches the CCITT decoder: an 8 × 4 Group 4 image decodes with the +/// default limit and with one of 32 pixels, and is refused with one of 31. +#[cfg(feature = "images")] +#[test] +fn a_documents_pixel_limit_reaches_the_ccitt_decoder() { + // One horizontal-mode row, three V0 rows, then EOFB: all black. + const ALL_BLACK_8X4: [u8; 6] = [0x26, 0xa2, 0xfe, 0x00, 0x20, 0x02]; + let (mut out, mut offsets) = base(); + let mut image = format!("<< /Length {} /Filter /CCITTFaxDecode /DecodeParms << /K -1 /Columns 8 >> >>\nstream\n", ALL_BLACK_8X4.len()).into_bytes(); + image.extend_from_slice(&ALL_BLACK_8X4); + image.extend_from_slice(b"\nendstream"); + object(&mut out, &mut offsets, 4, &image); + table(&mut out, &offsets, ""); + let params = ImageDecodeParams { width: 8, height: 4, ..Default::default() }; + let decoded = |limits: DecodeLimits| { + let pdf = Pdf::new_with_limits(out.clone(), limits).unwrap(); + let stream = pdf.xref().get::>(ObjectIdentifier::new(4, 0)).unwrap(); + stream.decoded_image(¶ms).map(|r| r.data.len()).ok() + }; + assert_eq!(decoded(DecodeLimits::default()), Some(32)); + assert_eq!(decoded(DecodeLimits::default().with_max_image_pixels(32)), Some(32)); + assert_eq!(decoded(DecodeLimits::default().with_max_image_pixels(31)), None); +} + #[test] fn object_stream_limit_applies_after_successful_root_xref() { let (bytes, _, _) = object_stream_pdf(false); diff --git a/vendor/hayro-syntax/src/filter/ccitt.rs b/vendor/hayro-syntax/src/filter/ccitt.rs index 29a3da40e6..c8597c7f5a 100644 --- a/vendor/hayro-syntax/src/filter/ccitt.rs +++ b/vendor/hayro-syntax/src/filter/ccitt.rs @@ -8,12 +8,14 @@ use alloc::vec::Vec; use core::iter; use hayro_ccitt::{DecodeSettings, Decoder, DecoderContext, EncodingMode}; -/// PdfCraft patch: `limit` is the most bytes the filter may produce (see `decode_limit`). +/// PdfCraft patch: `limit` is the most bytes the filter may produce (see `decode_limit`), and +/// `max_pixels` the most pixels (columns × rows) the image may decode to. pub(crate) fn decode( data: &[u8], params: &Dict<'_>, image_params: &ImageDecodeParams, limit: usize, + max_pixels: u64, ) -> Option> { let k = params.get::(K).unwrap_or(0); @@ -32,7 +34,7 @@ pub(crate) fn decode( }; let end_of_block = params.get::(END_OF_BLOCK).unwrap_or(true); // A `/Columns` past `u32::MAX` is refused: truncated, it would wrap to a small width that - // passes `ccitt_size_ok` and decode the image at the wrong width. + // passes `ccitt_size_within` and decode the image at the wrong width. let columns = match params.get::(COLUMNS) { Some(columns) => u32::try_from(columns).ok()?, None => 1728, @@ -55,15 +57,15 @@ pub(crate) fn decode( }; // PdfCraft patch: refuse absurd sizes before the decoder allocates for them. - if !super::ccitt_size_ok(settings.columns, settings.rows) { + if !super::ccitt_size_within(settings.columns, settings.rows, max_pixels) { return None; } // PdfCraft patch: the decoder stops after `rows` rows; with `/Rows 0` (unknown) it ran to the // end of the data, and a bit of 2D code can repeat a whole row, so a small stream produced - // gigabytes. Decode at most the rows that fit the output limit and the pixel cap. The limit + // gigabytes. Decode at most the rows that fit the output limit and the pixel limit. The limit // counts the stream's own 1-bit rows (`decode_limit`), whatever depth the rows are widened to. let mut settings = settings; - let fit = super::ccitt_max_rows(settings.columns, settings.columns.div_ceil(8), limit); + let fit = super::ccitt_max_rows(settings.columns, settings.columns.div_ceil(8), limit, max_pixels); settings.rows = if settings.rows == 0 { fit } else { settings.rows.min(fit) }; if settings.rows == 0 { return None; @@ -197,9 +199,19 @@ mod tests { #[test] fn columns_past_u32_max_are_refused_not_wrapped() { let params = ImageDecodeParams { width: 8, height: 4, ..Default::default() }; - let decoded = |dict: &[u8]| decode(&ALL_BLACK_8X4, &Dict::from_bytes(dict).unwrap(), ¶ms, 1 << 20); + let decoded = |dict: &[u8]| decode(&ALL_BLACK_8X4, &Dict::from_bytes(dict).unwrap(), ¶ms, 1 << 20, 1 << 28); assert!(decoded(b"<< /K -1 /Columns 8 >>").is_some()); // 2^32 + 8 would wrap to 8 columns. assert!(decoded(b"<< /K -1 /Columns 4294967304 >>").is_none()); } + + /// The image's 32 pixels are decoded with a pixel limit of 32 and refused with one of 31. + #[test] + fn the_pixel_limit_given_is_the_one_applied() { + let params = ImageDecodeParams { width: 8, height: 4, ..Default::default() }; + let dict = Dict::from_bytes(b"<< /K -1 /Columns 8 >>").unwrap(); + let decoded = |max_pixels| decode(&ALL_BLACK_8X4, &dict, ¶ms, 1 << 20, max_pixels); + assert_eq!(decoded(32).map(|r| r.data.len()), Some(32)); + assert!(decoded(31).is_none()); + } } diff --git a/vendor/hayro-syntax/src/filter/jpx.rs b/vendor/hayro-syntax/src/filter/jpx.rs index 2b24622426..fc169fb449 100644 --- a/vendor/hayro-syntax/src/filter/jpx.rs +++ b/vendor/hayro-syntax/src/filter/jpx.rs @@ -16,35 +16,20 @@ impl ImageColorSpace { } } -/// PdfCraft patch (47): the most pixels a codestream may decode to (2^28, the renderer's -/// `MAX_IMAGE_PIXELS` and hayro-interpret's `image_size_ok`). Its size comes from the SIZ marker, -/// not the image dictionary, and the decoder allocates it infallibly: a tiny file could ask for -/// tens of gigabytes and abort the process (#5078). -/// -/// It is checked against `Image::width()` x `height()` at full resolution: the SIZ image area, -/// divided by a component subsampling (`XRsiz`, `YRsiz`) that every component shares, the size the -/// decoder allocates each channel and component tile at. Components sampled differently leave the -/// area undivided. So a 2x2-subsampled 32768 x 32768 area decodes to, and counts as, 2^28. -const MAX_PIXELS: u64 = 1 << 28; - /// PdfCraft patch: the least output `limit` a JPEG 2000 image is held to: the limit comes from the /// image dictionary's size, which a decoder may round differently from the codestream's. const MIN_LIMIT: usize = 64 << 20; -/// Decode a JPEG 2000 image (JP2 file or raw codestream) for an image XObject described by -/// `params`, refusing codestreams over [`MAX_PIXELS`] or `limit` bytes; `None` when it can't be decoded. -pub(crate) fn decode(data: &[u8], params: &ImageDecodeParams, limit: usize) -> Option> { - decode_with_pixel_limit(data, params, limit, MAX_PIXELS) -} - -/// [`decode`] with `max_pixels` in place of [`MAX_PIXELS`], so a test can exercise the -/// full-resolution size check on a small image without an attacker-sized allocation. -fn decode_with_pixel_limit( - data: &[u8], - params: &ImageDecodeParams, - limit: usize, - max_pixels: u64, -) -> Option> { +/// PdfCraft patch: `limit` is the most bytes the filter may produce (see `decode_limit`), and +/// `max_pixels` the most pixels the codestream may decode to. A codestream's size comes from the +/// SIZ marker, not the image dictionary, and the decoder allocates it infallibly, so a tiny file +/// could ask for tens of gigabytes and abort the process (#5078). +/// +/// The count is checked against `Image::width()` x `height()` at full resolution: the SIZ image +/// area, divided by a component subsampling (`XRsiz`, `YRsiz`) that every component shares, the +/// size the decoder allocates each channel and component tile at. Components sampled differently +/// leave the area undivided. +pub(crate) fn decode(data: &[u8], params: &ImageDecodeParams, limit: usize, max_pixels: u64) -> Option> { use crate::object::stream::ImageColorSpace; let settings = DecodeSettings { @@ -71,7 +56,7 @@ fn decode_with_pixel_limit( // // PdfCraft patch (47): the header is read at full resolution first, because // `target_resolution` shrinks `width()` and `height()` but each tile's coefficients are still - // allocated at full size (review on #5086); see `MAX_PIXELS`. + // allocated at full size (review on #5086); see `decode`. let full_resolution = DecodeSettings { target_resolution: None, ..settings @@ -123,7 +108,7 @@ fn decode_with_pixel_limit( }; let has_alpha = image.has_alpha(); // PdfCraft patch: the decoder sizes its output from the codestream's own dimensions, not the - // image dictionary's, and allocates it infallibly. Refuse more than `MAX_PIXELS` pixels or + // image dictionary's, and allocates it infallibly. Refuse more than `max_pixels` pixels or // more than `limit` bytes before decoding, and reserve the buffer fallibly. if u64::from(width) * u64::from(height) > max_pixels { return None; @@ -339,7 +324,7 @@ fn scale( #[cfg(test)] mod tests { - use super::{decode, decode_with_pixel_limit, image_area_offset, scale, without_refused_enumerated_colour}; + use super::{decode, image_area_offset, scale, without_refused_enumerated_colour}; use crate::bit_reader::{BitReader, bit_mask}; use crate::object::stream::{ImageColorSpace, ImageDecodeParams}; use alloc::vec::Vec; @@ -510,7 +495,7 @@ mod tests { height: 2, ..ImageDecodeParams::default() }; - let result = decode(PALETTE_JP2, ¶ms, usize::MAX).unwrap(); + let result = decode(PALETTE_JP2, ¶ms, usize::MAX, 1 << 28).unwrap(); let image = result.image_data.unwrap(); assert!(matches!(image.color_space, Some(ImageColorSpace::Rgb))); let red = [255, 0, 0]; @@ -530,10 +515,18 @@ mod tests { height: 2, ..ImageDecodeParams::default() }; - let result = decode(PALETTE_JP2, ¶ms, usize::MAX).unwrap(); + let result = decode(PALETTE_JP2, ¶ms, usize::MAX, 1 << 28).unwrap(); assert_eq!(&*result.data, &[0, 1, 0, 1, 1, 0, 1, 0][..]); } + /// The codestream's 8 pixels are decoded with a pixel limit of 8 and refused with one of 7. + #[test] + fn the_pixel_limit_given_is_the_one_applied() { + let params = ImageDecodeParams { is_indexed: true, num_components: Some(1), width: 4, height: 2, ..ImageDecodeParams::default() }; + assert_eq!(decode(PALETTE_JP2, ¶ms, usize::MAX, 8).map(|r| r.data.len()), Some(8)); + assert!(decode(PALETTE_JP2, ¶ms, usize::MAX, 7).is_none()); + } + /// A 1x1, 1-bit codestream (one empty packet, so its sample is the midpoint 1) as a JP2 file /// whose header holds `extra` boxes after `ihdr` and `colr`. fn one_bit_jp2(extra: &[u8]) -> Vec { @@ -566,8 +559,16 @@ mod tests { /// precision; an image without a palette keeps its own (1 bit here). #[test] fn palette_colours_are_eight_bit_and_other_samples_keep_their_precision() { - let params = ImageDecodeParams { width: 1, height: 1, ..ImageDecodeParams::default() }; - let bpc = |data: &[u8]| decode(data, ¶ms, usize::MAX).and_then(|r| r.image_data).map(|d| d.bits_per_component); + let params = ImageDecodeParams { + width: 1, + height: 1, + ..ImageDecodeParams::default() + }; + let bpc = |data: &[u8]| { + decode(data, ¶ms, usize::MAX, 1 << 28) + .and_then(|r| r.image_data) + .map(|d| d.bits_per_component) + }; let mut palette = Vec::new(); for (kind, body) in [(&b"pclr"[..], &[0, 2, 3, 7, 7, 7, 255, 0, 0, 64, 128, 192][..]), (b"cmap", &[0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 2])] { palette.extend_from_slice(&((8 + body.len()) as u32).to_be_bytes()); @@ -620,7 +621,7 @@ mod tests { target_dimension: Some((2, 2)), ..ImageDecodeParams::default() }; - let result = decode(&one_level_codestream(x, y), ¶ms, usize::MAX).unwrap(); + let result = decode(&one_level_codestream(x, y), ¶ms, usize::MAX, 1 << 28).unwrap(); let image = result.image_data.unwrap(); assert_eq!((image.width, image.height), (expected, expected), "offset ({x}, {y})"); assert_eq!(result.data.as_ref(), alloc::vec![128; (expected * expected) as usize], "offset ({x}, {y})"); @@ -680,10 +681,10 @@ mod tests { #[test] fn a_codestream_over_the_pixel_cap_is_refused() { let params = ImageDecodeParams { width: 1, height: 1, ..ImageDecodeParams::default() }; - assert!(decode(&jp2_with_size(1, 1, 0), ¶ms, usize::MAX).is_some()); - assert!(decode(&jp2_with_size(65536, 65536, 0), ¶ms, usize::MAX).is_none()); + assert!(decode(&jp2_with_size(1, 1, 0), ¶ms, usize::MAX, 1 << 28).is_some()); + assert!(decode(&jp2_with_size(65536, 65536, 0), ¶ms, usize::MAX, 1 << 28).is_none()); let small_target = ImageDecodeParams { target_dimension: Some((1, 1)), ..params }; - assert!(decode(&jp2_with_size(65536, 65536, 4), &small_target, usize::MAX).is_none()); + assert!(decode(&jp2_with_size(65536, 65536, 4), &small_target, usize::MAX, 1 << 28).is_none()); } /// The size check uses the full-resolution size, not the target's. With four decomposition @@ -702,12 +703,12 @@ mod tests { target_dimension: Some((1, 1)), ..ImageDecodeParams::default() }; - let reduced = decode(&image, &small_target, usize::MAX).expect("a 64x64 image decodes at a 1x1 target"); + let reduced = decode(&image, &small_target, usize::MAX, 1 << 28).expect("a 64x64 image decodes at a 1x1 target"); let size = reduced.image_data.as_ref().map(|d| (d.width, d.height)); assert!( size.is_some_and(|(w, h)| u64::from(w) * u64::from(h) <= 1024), "the target shrinks the image under the limit: {size:?}" ); - assert!(decode_with_pixel_limit(&image, &small_target, usize::MAX, 1024).is_none()); + assert!(decode(&image, &small_target, usize::MAX, 1024).is_none()); } } diff --git a/vendor/hayro-syntax/src/filter/mod.rs b/vendor/hayro-syntax/src/filter/mod.rs index 833268506d..cf3a9250bb 100644 --- a/vendor/hayro-syntax/src/filter/mod.rs +++ b/vendor/hayro-syntax/src/filter/mod.rs @@ -94,6 +94,8 @@ impl Filter { } /// PdfCraft patch: `limit` is the most bytes the filter may produce (see `decode_limit`), and + /// `max_pixels` the most pixels a CCITT or JPEG 2000 image may decode to (the document's + /// [`DecodeLimits::max_image_pixels`](crate::DecodeLimits::max_image_pixels)), and /// `rows` the `/Height` of the image whose samples it produces, when it is an image's last /// filter. pub(crate) fn apply( @@ -102,6 +104,7 @@ impl Filter { params: &Dict<'_>, #[cfg_attr(not(feature = "images"), allow(unused))] image_params: &ImageDecodeParams, limit: usize, + #[cfg_attr(not(feature = "images"), allow(unused))] max_pixels: u64, control: Option<&crate::cancel::Control>, rows: Option, ) -> Result, DecodeFailure> { @@ -129,11 +132,11 @@ impl Filter { #[cfg(feature = "images")] Self::DctDecode => dct::decode(data, params, image_params).ok_or(DecodeFailure::ImageDecode), #[cfg(feature = "images")] - Self::CcittFaxDecode => ccitt::decode(data, params, image_params, limit).ok_or(DecodeFailure::ImageDecode), + Self::CcittFaxDecode => ccitt::decode(data, params, image_params, limit, max_pixels).ok_or(DecodeFailure::ImageDecode), #[cfg(feature = "images")] Self::Jbig2Decode => jbig2::decode(data, params, image_params, limit).ok_or(DecodeFailure::ImageDecode), #[cfg(feature = "images")] - Self::JpxDecode => jpx::decode(data, image_params, limit).ok_or(DecodeFailure::ImageDecode), + Self::JpxDecode => jpx::decode(data, image_params, limit, max_pixels).ok_or(DecodeFailure::ImageDecode), #[cfg(not(feature = "images"))] Self::DctDecode | Self::CcittFaxDecode | Self::Jbig2Decode | Self::JpxDecode => { warn!("image decoding is not supported (enable the `images` feature)"); @@ -190,34 +193,48 @@ pub(crate) fn decode_limit(params: &ImageDecodeParams, last: bool, limits: crate /// PdfCraft patch: whether a CCITT image of `columns` × `rows` may be decoded. The decoder sizes /// its line buffers from `/Columns`, which a fuzzed file set to 4294967295 (a 4 GiB allocation); -/// real fax lines are a few thousand pixels wide. +/// real fax lines are a few thousand pixels wide. At most [`MAX_IMAGE_PIXELS`] pixels, the +/// default of [`DecodeLimits::max_image_pixels`](crate::DecodeLimits::max_image_pixels). pub fn ccitt_size_ok(columns: u32, rows: u32) -> bool { - const MAX_COLUMNS: u32 = 1 << 20; - columns > 0 && columns <= MAX_COLUMNS && u64::from(columns) * u64::from(rows.max(1)) <= MAX_CCITT_PIXELS + ccitt_size_within(columns, rows, MAX_IMAGE_PIXELS) } -/// PdfCraft patch: the most pixels a CCITT image may decode to. -const MAX_CCITT_PIXELS: u64 = 1 << 28; +/// PdfCraft patch: [`ccitt_size_ok`] with at most `max_pixels` pixels (columns × rows). +pub(crate) fn ccitt_size_within(columns: u32, rows: u32, max_pixels: u64) -> bool { + const MAX_COLUMNS: u32 = 1 << 20; + columns > 0 && columns <= MAX_COLUMNS && u64::from(columns) * u64::from(rows.max(1)) <= max_pixels +} /// PdfCraft patch: the most rows of `columns` pixels, `row_bytes` bytes each once decoded, that fit -/// both `limit` bytes and the pixel cap; at least one when one row fits. +/// both `limit` bytes and `max_pixels` pixels; at least one when one row fits. #[cfg(feature = "images")] -pub(crate) fn ccitt_max_rows(columns: u32, row_bytes: u32, limit: usize) -> u32 { - let by_pixels = MAX_CCITT_PIXELS / u64::from(columns.max(1)); +pub(crate) fn ccitt_max_rows(columns: u32, row_bytes: u32, limit: usize, max_pixels: u64) -> u32 { + let by_pixels = max_pixels / u64::from(columns.max(1)); let by_bytes = u64::try_from(limit).unwrap_or(u64::MAX) / u64::from(row_bytes.max(1)); u32::try_from(by_pixels.min(by_bytes)).unwrap_or(u32::MAX) } #[cfg(all(test, feature = "images"))] mod ccitt_tests { - use super::ccitt_max_rows; + use super::{MAX_IMAGE_PIXELS, ccitt_max_rows, ccitt_size_ok, ccitt_size_within}; /// PdfCraft patch: an image of unknown height decodes at most the rows that fit both the output - /// limit (in 1-bit rows) and the 2^28-pixel cap. + /// limit (in 1-bit rows) and the pixel limit. #[test] fn unknown_ccitt_rows_fit_the_limit_and_the_pixel_cap() { - assert_eq!(ccitt_max_rows(1728, 216, 216 * 100), 100); - assert_eq!(ccitt_max_rows(1 << 20, 1 << 17, usize::MAX), 1 << 8); - assert_eq!(ccitt_max_rows(1728, 216, 100), 0); + assert_eq!(ccitt_max_rows(1728, 216, 216 * 100, MAX_IMAGE_PIXELS), 100); + assert_eq!(ccitt_max_rows(1 << 20, 1 << 17, usize::MAX, MAX_IMAGE_PIXELS), 1 << 8); + assert_eq!(ccitt_max_rows(1728, 216, 100, MAX_IMAGE_PIXELS), 0); + assert_eq!(ccitt_max_rows(1 << 20, 1 << 17, usize::MAX, 1 << 30), 1 << 10); + } + + /// A 32768 × 16384 image (2^29 pixels) is past the default limit and within a limit of 2^30. + #[test] + fn ccitt_size_follows_the_pixel_limit() { + assert!(!ccitt_size_ok(32_768, 16_384)); + assert!(!ccitt_size_within(32_768, 16_384, MAX_IMAGE_PIXELS)); + assert!(ccitt_size_within(32_768, 16_384, 1 << 30)); + assert!(ccitt_size_ok(16_384, 16_384)); + assert!(!ccitt_size_within(16_384, 16_384, (1 << 28) - 1)); } } diff --git a/vendor/hayro-syntax/src/object/stream.rs b/vendor/hayro-syntax/src/object/stream.rs index f464110bec..8f5ac7af92 100644 --- a/vendor/hayro-syntax/src/object/stream.rs +++ b/vendor/hayro-syntax/src/object/stream.rs @@ -279,7 +279,8 @@ impl<'a> Stream<'a> { continue; } // PdfCraft patch: see `filter::decode_limit`. - let limit = crate::filter::decode_limit(image_params, i + 1 == count, self.dict.ctx().decode_limits()).min(max); + let limits = self.dict.ctx().decode_limits(); + let limit = crate::filter::decode_limit(image_params, i + 1 == count, limits).min(max); // PdfCraft patch: the last filter of an image produces its rows. let rows = (i + 1 == count && image_params.height > 0) .then(|| usize::try_from(image_params.height).ok()) @@ -289,6 +290,7 @@ impl<'a> Stream<'a> { params, image_params, limit, + limits.max_image_pixels(), self.dict.ctx().control(), rows, )?; diff --git a/vendor/linesweeper/README.craft.md b/vendor/linesweeper/README.craft.md index 1b567dee30..7b6b2c3d7f 100644 --- a/vendor/linesweeper/README.craft.md +++ b/vendor/linesweeper/README.craft.md @@ -16,8 +16,11 @@ holds `upstream_revision`. `local_patches` describes each local patch. ## Local patches +`src/sweep/sweep_line.rs` also differs from the archive, in one doc comment. + | File | Change | |---|---| +| `src/sweep/sweep_line.rs` | The touch branch of `Sweeper::handle_intersection` runs its scan right from a segment, or left from a segment, at most once per sweep line until the sweep-line order changes. Exact copies of a shape queue a touch event for every pair of coincident segments, and each event used to scan the whole bundle in both directions, so sweeping `n` copies took time growing faster than `n^3`. The skipped scans would only push events already queued, so the output does not change. The `coincident_copies_scan_once_per_order` test counts the scans for 60 copies of two shapes, and `coincident_copies_keep_the_fill` compares the output fill with the input's nonzero fill for 200 inputs with exact, reversed and split copies. | | `src/sweep/sweep_line.rs` | The doc comment of `SweepLine::line_segment` says it can return a segment that has exited, which `segment_range` leaves out. Code comments label the change `Craft patch (exited slots)`. | | `src/curve/transverse.rs` | `transversal_after` returns `false` when either dy/dt bound it divides by is zero, negative or nan. It compared the two slope bounds by cross-multiplying, which reverses the comparison when a bound is negative. Two curves that leave a shared start point in opposite directions, with their first control points one ulp below the start, were reported as keeping their left-to-right order although they cross. `transversal_before` reflects its curves and calls `transversal_after`, so it returned the same wrong answer. The `crossing_with_negative_start_dy` test checks both functions. | | `src/curve/mod.rs` | When the chord that `fit_quadratic` takes for a very short curve gives a constant term that is not finite, `fit_quadratic` takes the line through the curve's start point with the chord's slope instead. Before, a curve near x = 1e305 with heights near 1e4 and less than about 3e-12 tall gave a product of an x coordinate and a height above `f64::MAX`, and the chord's constant term was NaN. The `short_curve_chord_with_huge_x` test fits vertical curves one ulp tall at y = 1e4 and x = 1e305, -1e305 and 5e307. Code comments label the change `Craft patch (huge chord)`. | @@ -27,6 +30,15 @@ holds `upstream_revision`. `local_patches` describes each local patch. | `docs/sweep.typ` | The lemma for the intersection scan to the left asks for the ordering invariant on `(alpha^1, ..., alpha^(i+1))` and the crossing invariant on `(alpha^1, ..., alpha^i)`, which is how the bidirectional lemma uses it. The argument for the order invariant cites the crossing invariant instead of a "third invariant"; the document defines two. | | `src/sweep/sweep_line.rs`, `src/topology.rs` | Clippy 1.100.0 with `-D warnings` and every feature passes on the library, its unit tests and the `regression` test: the `slow-asserts` invariant check in `sweep_line.rs` passes `self.line` to `assert!` without a `&` (`useless_borrows_in_formatting`), and `Contours::grouped` iterates over the contours with `enumerate` instead of indexing them (`needless_range_loop`). The behavior does not change. Code comments label the change `Craft patch (clippy lints)`. | +`docs/sweep.typ` has one more change: + +- `docs/sweep.typ`: the crossing-height lemma (`lem-intersection-height-error`) and its proof divide + the starting gap `beta(y_0) - alpha(y_0)` by the sum of both gaps. With the ending gap + `alpha(y_1) - beta(y_1)` as the numerator, gaps of 1 and 3 gave `t = 0.75`, while the segments + cross at `t = 0.25`. The proof's inverse-slope difference is `d/(y_1 - y_0)`; the package has + `d/(y_1 - y_1)`, whose denominator is zero. The lemma's bound and the later bound on the crossing + height use the absolute values of `1/m_alpha` and `1/m_beta`, because the slopes can be negative. + `omitted_files` lists the 43 files of the package left out here, with their hashes: - `tests/fonts/Inconsolata-Regular.ttf`: font files live in craft-fonts. diff --git a/vendor/linesweeper/SOURCE.json b/vendor/linesweeper/SOURCE.json index 3b88550a9e..b56664d40b 100644 --- a/vendor/linesweeper/SOURCE.json +++ b/vendor/linesweeper/SOURCE.json @@ -8,12 +8,14 @@ "upstream_revision": "824b0791a750f7b27b8edcbb6c6244d0e629875e", "upstream_directory": "", "local_patches": [ + "In `src/sweep/sweep_line.rs`, the touch branch of `Sweeper::handle_intersection` runs each scan from a segment in a direction at most once per sweep line until the sweep-line order changes, so exact copies of a shape no longer rescan the whole coincident bundle for every touch event.", "In `src/sweep/sweep_line.rs`, the doc comment of `SweepLine::line_segment` says it can return a segment that has exited, which `segment_range` leaves out.", "In `src/curve/transverse.rs`, `transversal_after` (and `transversal_before`, which calls it) returns `false` when either dy/dt bound is not positive, instead of cross-multiplying the slope bounds, which reverses the comparison for a negative bound.", "In `src/curve/mod.rs`, when the chord that `fit_quadratic` takes for a very short curve gives a constant term that is not finite, `fit_quadratic` takes the line through the curve's start point with the chord's slope, so a curve near x = 1e305 with heights near 1e4 no longer gives a NaN coefficient. In `src/curve/line.rs`, `line_at_ys` scales the x coordinates by 2^600 before the weighted sum and back after it when both have a magnitude below 2^-500, so a subnormal x coordinate no longer rounds to 0. Both files add tests for it.", "In `docs/sweep.typ`, the intersection scan to the left compares each segment with `alpha^(i+1)`, the segment the lemma after it is stated for, instead of `alpha^i`.", "In `docs/sweep.typ`, the typo \"condi0.2tions\" reads \"conditions\", and `q(i+i)` reads `q(i+1)`, the first index for which `q` is false.", "In `docs/sweep.typ`, the lemma for the intersection scan to the left asks for the ordering invariant on `(alpha^1, ..., alpha^(i+1))` and the crossing invariant on `(alpha^1, ..., alpha^i)`, as the bidirectional lemma uses it, and the argument for the order invariant cites the crossing invariant instead of a \"third invariant\".", + "In `docs/sweep.typ`, the crossing-height lemma and its proof use the starting gap `beta(y_0) - alpha(y_0)` as the numerator of `t`, instead of the ending gap `alpha(y_1) - beta(y_1)`, so that `y_0 + t(y_1 - y_0)` is the height where the segments cross, and the proof's inverse-slope difference is `d/(y_1 - y_0)` instead of `d/(y_1 - y_1)`. The lemma's bound and the later bound on the crossing height use the absolute values of the inverse slopes, because the slopes can be negative.", "In `src/sweep/sweep_line.rs` and `src/topology.rs`, two changes make clippy 1.100.0 with `-D warnings` and every feature pass on the library, its unit tests and the `regression` test: the `slow-asserts` invariant check passes `self.line` to `assert!` without a `&`, and `Contours::grouped` iterates over the contours with `enumerate` instead of indexing them. The behavior does not change." ], "files": [ @@ -29,7 +31,7 @@ { "path": "benches/linebender_logo.rs", "source_sha256": "d10867f43439d37f0e1da5d30eaed9ab3bfbe655ed47212f65dc20ab4db65cb3", "source_git_blob": null, "sha256": "d10867f43439d37f0e1da5d30eaed9ab3bfbe655ed47212f65dc20ab4db65cb3" }, { "path": "benches/painted_dreams.rs", "source_sha256": "073008db93840d380710e13ed3ae38e08cb823f10c12e5f838dac1ccf37eaecf", "source_git_blob": null, "sha256": "073008db93840d380710e13ed3ae38e08cb823f10c12e5f838dac1ccf37eaecf" }, { "path": "benches/synthetic.rs", "source_sha256": "7ce59bef2e1c4f28b00cb89feb15bc71ca4b098a8d27e7b02ea699aca9bcc810", "source_git_blob": null, "sha256": "7ce59bef2e1c4f28b00cb89feb15bc71ca4b098a8d27e7b02ea699aca9bcc810" }, - { "path": "docs/sweep.typ", "source_sha256": "4766082c8672a7bb4356b5581043489c13b4e3fb8931ba3a5f0a473fab0172f3", "source_git_blob": null, "sha256": "c151c2c47032eca41914139b105177d10996b6ece9c93622aaeb31a371cfe17b" }, + { "path": "docs/sweep.typ", "source_sha256": "4766082c8672a7bb4356b5581043489c13b4e3fb8931ba3a5f0a473fab0172f3", "source_git_blob": null, "sha256": "392f538b00cc4823d4fcec533de062c3315413498c4892cb6140ed6d476a4f47" }, { "path": "examples/boolean_op.rs", "source_sha256": "3b38a1ccda7e736cce4b191a3a45ab4824c4c365190e3eb637b2fb39b5996c9f", "source_git_blob": null, "sha256": "3b38a1ccda7e736cce4b191a3a45ab4824c4c365190e3eb637b2fb39b5996c9f" }, { "path": "examples/bus.rs", "source_sha256": "e206a08be73899f564188052c8ecc15526b54606e52ee2935a64ce6b5723da33", "source_git_blob": null, "sha256": "e206a08be73899f564188052c8ecc15526b54606e52ee2935a64ce6b5723da33" }, { "path": "examples/curve_metrics.rs", "source_sha256": "0db6a5327fd2119a03a9a66624fea3e04b6bbb519655667ad30487aee6c787d2", "source_git_blob": null, "sha256": "0db6a5327fd2119a03a9a66624fea3e04b6bbb519655667ad30487aee6c787d2" }, @@ -70,7 +72,7 @@ { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__square.snap", "source_sha256": "b35c3e6a38d5ecdd8acf315ba0b0bd6485cd8b40193fdd76bd446bdfdb6eda77", "source_git_blob": null, "sha256": "b35c3e6a38d5ecdd8acf315ba0b0bd6485cd8b40193fdd76bd446bdfdb6eda77" }, { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__square_and_diamond.snap", "source_sha256": "3f01a76fb7ff4aef0fd55fd869602d4a2b69fff1bd65632f406b275b5d6af600", "source_git_blob": null, "sha256": "3f01a76fb7ff4aef0fd55fd869602d4a2b69fff1bd65632f406b275b5d6af600" }, { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__two_squares.snap", "source_sha256": "79e3c95e563a66c0ce244125470a106a18dfe29f276b732defd305406c873c7e", "source_git_blob": null, "sha256": "79e3c95e563a66c0ce244125470a106a18dfe29f276b732defd305406c873c7e" }, - { "path": "src/sweep/sweep_line.rs", "source_sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3", "source_git_blob": null, "sha256": "44a585c1feb525b6616c6ee4b82c6d12d7de597e7d9287a44c1075417afb270a" }, + { "path": "src/sweep/sweep_line.rs", "source_sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3", "source_git_blob": null, "sha256": "3fba1bd6c41361cc8cf1736406396ecf4a05464599867a4dae77fff03ddac8e6" }, { "path": "src/topology.rs", "source_sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b", "source_git_blob": null, "sha256": "8729c2dd5941668f3d2805b6562d2d144d4e5156836b894b887394d9d2961aa7" }, { "path": "src/treevec.rs", "source_sha256": "d88b9fbf02fa9f318560e1d483d465555f2b696ae12c00f8e4f5b71ea6779445", "source_git_blob": null, "sha256": "d88b9fbf02fa9f318560e1d483d465555f2b696ae12c00f8e4f5b71ea6779445" }, { "path": "src/typed_vec.rs", "source_sha256": "3e9a2675b8a40d8fc4df0575bd9d0d16b5604d18e9b78638dd5a612b28fc4c30", "source_git_blob": null, "sha256": "3e9a2675b8a40d8fc4df0575bd9d0d16b5604d18e9b78638dd5a612b28fc4c30" }, diff --git a/vendor/linesweeper/docs/sweep.typ b/vendor/linesweeper/docs/sweep.typ index c77f6cdc62..838ac03016 100644 --- a/vendor/linesweeper/docs/sweep.typ +++ b/vendor/linesweeper/docs/sweep.typ @@ -719,10 +719,10 @@ and assume that $beta(y_0) - alpha(y_0) >= 0$ and $ alpha(y_1) - beta(y_1) > 16/3 (epsilon + 2 epsilon_0 M). $ -Define $t = (alpha(y_1) - beta(y_1)) / (alpha(y_1) - beta(y_1) + beta(y_0) - alpha(y_0)$ and set $y = y_0 + t(y_1 - y_0)$. The +Define $t = (beta(y_0) - alpha(y_0)) / (beta(y_0) - alpha(y_0) + alpha(y_1) - beta(y_1))$ and set $y = y_0 + t(y_1 - y_0)$. The natural way to compute $y$ produces an approximation $hat(y)$ satisfying $ -|alpha(hat(y)) - beta(hat(y))| <= 4(epsilon + 2 epsilon_0 M) (1 + max(1/m_alpha, 1/m_beta)), +|alpha(hat(y)) - beta(hat(y))| <= 4(epsilon + 2 epsilon_0 M) (1 + max(1/abs(m_alpha), 1/abs(m_beta))), $ where $m_alpha$ and $m_beta$ are the slopes of $alpha$ and $beta$. ] @@ -731,18 +731,18 @@ Basically, this says we can find a good approximate crossing height as long as t #proof[ First, note that at least one of $alpha(y_0)$ or $beta(y_0)$ is calculated exactly; similarly for $alpha(y_1)$ and $beta(y_1)$. -Therefore the absolute error in calculating $alpha(y_1) - beta(y_1)$ is at most $epsilon + epsilon_0 M$ (where the $epsilon_0 M$ comes +Therefore the absolute error in calculating $beta(y_0) - alpha(y_0)$ is at most $epsilon + epsilon_0 M$ (where the $epsilon_0 M$ comes from rounding after the summation) and the absolute error in calculating -$(alpha(y_1) - beta(y_1)) + (beta(y_0) - alpha(y_0))$ is at most $2 epsilon + 3 epsilon_0 M$. -These errors aren't independent, though, since both terms involve a computation of $alpha(y_1) - beta(y_1)$. -Specifically, let $c = alpha(y_1) - beta(y_1)$ and let $d = (alpha(y_1) - beta(y_1)) + (beta(y_0) - alpha(y_0))$; suppose +$(beta(y_0) - alpha(y_0)) + (alpha(y_1) - beta(y_1))$ is at most $2 epsilon + 3 epsilon_0 M$. +These errors aren't independent, though, since both terms involve a computation of $beta(y_0) - alpha(y_0)$. +Specifically, let $c = beta(y_0) - alpha(y_0)$ and let $d = (beta(y_0) - alpha(y_0)) + (alpha(y_1) - beta(y_1))$; suppose our calculation of $c$ has error $epsilon_c$ and our calculation of $d$ has error $epsilon_d$. Then $ |epsilon_c - epsilon_d| <= epsilon + 2 epsilon_0 M, $ -because this is the *additional* error introduced into $d$ by computing $beta(y_0) - alpha(y_0)$ and adding it to the other term. +because this is the *additional* error introduced into $d$ by computing $alpha(y_1) - beta(y_1)$ and adding it to the other term. Now we consider the quotient @@ -789,8 +789,8 @@ abs(alpha(hat(y)) - beta(hat(y))) <= (2 epsilon_0 + epsilon_t) d + (epsilon_0 M) $ If we assume that $16 (epsilon + 2 epsilon_0 M) / d <= 3$ then $epsilon_t d <= 4 epsilon + 8 epsilon_0 M$. -Since $d/(y_1 - y_1)$ is the difference of the inverse-slopes of $alpha$ and $beta$, it's bounded by twice -the maximum of these inverse-slopes. +Since $d/(y_1 - y_0)$ is the difference of the inverse-slopes of $alpha$ and $beta$, it's bounded by twice +the maximum absolute value of these inverse-slopes. ] Putting all this together (and handling the "chamfers" yet): @@ -802,7 +802,7 @@ and take $delta = 64 epsilon_0 M$. If $epsilon_0 <= 1/4$ then - If $alpha$ $(3 delta)/4$-crosses $beta$, we can compute a crossing height $hat(y)$ such that $ - |alpha(hat(y)) - beta(hat(y))| <= (9 delta) /16 (1 + max(1/m_alpha, 1/m_beta)). + |alpha(hat(y)) - beta(hat(y))| <= (9 delta) /16 (1 + max(1/abs(m_alpha), 1/abs(m_beta))). $ ] diff --git a/vendor/linesweeper/src/sweep/sweep_line.rs b/vendor/linesweeper/src/sweep/sweep_line.rs index 41e07d88c3..1d66ec7745 100644 --- a/vendor/linesweeper/src/sweep/sweep_line.rs +++ b/vendor/linesweeper/src/sweep/sweep_line.rs @@ -350,6 +350,17 @@ pub struct Sweeper<'a> { comparisons: RefCell, conservative_comparisons: RefCell, + + // Craft patch (coincident touch rescan): the (segment, scans right) pairs + // whose touch-event scan in `handle_intersection` already ran at the + // current `y` with the current sweep-line order. A scan reads only the + // order, `y` and the segments, so running it again before the order + // changes pushes only events it already pushed. Exact copies of a shape + // queue a touch event for every pair of coincident segments, and each one + // used to scan the whole bundle in both directions. + touch_scans: rustc_hash::FxHashSet<(SegIdx, bool)>, + #[cfg(test)] + touch_scan_count: usize, } impl<'segs> Sweeper<'segs> { @@ -377,6 +388,9 @@ impl<'segs> Sweeper<'segs> { horizontals: Vec::new(), comparisons: RefCell::new(ComparisonCache::new(eps, eps / 2.0)), conservative_comparisons: RefCell::new(ComparisonCache::new(4.0 * eps, eps / 2.0)), + touch_scans: rustc_hash::FxHashSet::default(), + #[cfg(test)] + touch_scan_count: 0, } } @@ -469,6 +483,7 @@ impl<'segs> Sweeper<'segs> { self.y = y; self.segs_needing_positions.clear(); self.horizontals.clear(); + self.touch_scans.clear(); } fn intersection_scan_right(&mut self, start_idx: usize, which: WhichTouch) { @@ -785,6 +800,9 @@ impl<'segs> Sweeper<'segs> { } } + // The order changes below, so earlier touch scans no longer stand. + self.touch_scans.clear(); + // Remove them in reverse to make indexing easier. let mut removed = Vec::with_capacity(to_move.len()); for &j in to_move.iter().rev() { @@ -830,9 +848,21 @@ impl<'segs> Sweeper<'segs> { // We haven't changed the order of any segments, but the "touch" event // we just processed might have been a witness for the crossing invariant. - // So we need to scan. - self.intersection_scan_right(right_idx, WhichTouch::Mid); - self.intersection_scan_left(left_idx, WhichTouch::Mid); + // So we need to scan, unless the same scan already ran with this order. + if self.touch_scans.insert((right, true)) { + #[cfg(test)] + { + self.touch_scan_count += 1; + } + self.intersection_scan_right(right_idx, WhichTouch::Mid); + } + if self.touch_scans.insert((left, false)) { + #[cfg(test)] + { + self.touch_scan_count += 1; + } + self.intersection_scan_left(left_idx, WhichTouch::Mid); + } } } @@ -2089,6 +2119,135 @@ mod tests { insta::assert_ron_snapshot!(snapshot_outputs(segs, 0.25)); } + fn closed_polyline(points: &[(f64, f64)]) -> BezPath { + let mut path = BezPath::new(); + path.move_to(points[0]); + for &p in &points[1..] { + path.line_to(p); + } + path.close_path(); + path + } + + fn copies(shape: &BezPath, n: usize) -> BezPath { + (0..n).flat_map(|_| shape.iter()).collect() + } + + // Exact copies of a shape queue a touch event for every pair of coincident + // segments. Each touch-event scan runs at most once per segment and + // direction for each sweep-line order, so the number of scans stays + // linear in the number of segments, and the output is the output for one + // copy. + #[test] + fn coincident_copies_scan_once_per_order() { + use crate::topology::Topology; + + let quad = closed_polyline(&[(0.0, 0.0), (100.0, 37.0), (60.0, 90.0), (10.0, 70.0)]); + let rect = closed_polyline(&[(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)]); + for shape in [quad, rect] { + let path = copies(&shape, 60); + let mut segs = Segments::default(); + segs.add_bez_path(&path).unwrap(); + let mut sweep = Sweeper::new(&segs, 1e-6); + let mut bufs = SweepLineBuffers::default(); + let mut lines = 0; + while sweep.next_line(&mut bufs).is_some() { + lines += 1; + } + assert!( + sweep.touch_scan_count <= 2 * segs.len() * lines, + "{} touch scans for {} segments on {lines} sweep lines", + sweep.touch_scan_count, + segs.len() + ); + + let contour_paths = |path: &BezPath| -> Vec { + Topology::from_path(path, 1e-6) + .unwrap() + .contours(|w| *w != 0) + .contours() + .map(|c| c.path.clone()) + .collect() + }; + assert_eq!(contour_paths(&path), contour_paths(&shape)); + } + } + + // Small polygons on an integer grid, with exact, reversed and + // midpoint-split copies of some of them. The nonzero fill of the output + // contours matches the nonzero fill of the input. + #[test] + fn coincident_copies_keep_the_fill() { + use crate::topology::Topology; + use kurbo::{ParamCurve, ParamCurveNearest, Shape}; + + let mut state = 0x9e37_79b9_7f4a_7c15_u64; + let mut next = |n: u64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % n + }; + for case in 0..200 { + let mut polygons: Vec> = Vec::new(); + for _ in 0..1 + next(3) { + let len = 3 + next(3); + let polygon = (0..len).map(|_| (next(9) as f64, next(9) as f64)).collect(); + polygons.push(polygon); + } + for _ in 0..1 + next(3) { + let source = polygons[next(polygons.len() as u64) as usize].clone(); + let copy = match next(3) { + 0 => source, + 1 => source.into_iter().rev().collect(), + _ => { + let mut split = Vec::new(); + for (i, &(x0, y0)) in source.iter().enumerate() { + let (x1, y1) = source[(i + 1) % source.len()]; + split.push((x0, y0)); + split.push(((x0 + x1) / 2.0, (y0 + y1) / 2.0)); + } + split + } + }; + polygons.push(copy); + } + let input: BezPath = polygons + .iter() + .flat_map(|p| closed_polyline(p).into_iter()) + .collect(); + + let top = Topology::from_path(&input, 1e-6).unwrap(); + let contours = top.contours(|w| *w != 0); + for i in 0..64 { + for j in 0..64 { + let p = kurbo::Point::new(i as f64 / 8.0 + 0.0137, j as f64 / 8.0 + 0.0291); + // Skip points too close to an input edge to say which + // side they are on. + let near_edge = input.segments().any(|seg| { + let line = kurbo::Line::new(seg.start(), seg.end()); + let t = line.nearest(p, 0.0).t; + line.eval(t).distance(p) < 1e-3 + }); + if near_edge { + continue; + } + let expected = input.winding(p) != 0; + let output_winding: i32 = contours + .contours() + .map(|c| c.path.winding(p)) + .sum(); + assert_eq!( + output_winding != 0, + expected, + "case {case} at {p:?}: {}", + input.to_svg() + ); + } + } + } + } + #[test] fn empty_sweep_line() { let segs = Segments::default();