From 5f4207b6fd9f6574206cb49543fb17131843f278 Mon Sep 17 00:00:00 2001 From: supersurviveur Date: Wed, 30 Sep 2026 18:50:15 +0200 Subject: [PATCH] perf: Add BLA rendering for other fractals --- CLAUDE.md | 44 +- src/app.rs | 3 + src/fractal/bla.rs | 876 ++++++++++++++++++++++++++++-------- src/shaders/mandelbrot.wgsl | 51 ++- tests/shader_valid.rs | 4 +- 5 files changed, 756 insertions(+), 222 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index dc4652a..e2f1b6b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -246,24 +246,36 @@ pixel is a handful of `f32` complex multiplies. the input scale. Lambda set mode's reference sits at the origin, so it never reaches deep zooms anyway. - `src/fractal/bla.rs` — **bivariate linear approximation**: a table of - merged linear steps `e' = A·e + B·dc` (valid while `|e| < R`) built on - the CPU from the reference orbit, so the shader's `bla_lookup` jumps each - pixel over whole runs of steps. Plain Mandelbrot only (set + Julia, no - morph; `bla::applies`, the `BLA` override). This is what makes deep zoom - fast: every pixel follows the reference for tens of thousands of steps - before diverging (1e-200: 12.7 s → 0.7 s at 960×540). Level `l` node `i` - covers steps `1 + i·2^l ..`, and only levels ≥ 3 are uploaded (bindings 4/5, - `bla_meta` = `[min_level, levels, offsets…]`). Coefficients are - floatexp (f32 mantissa + i32 exponent), so a jump in the deep prologue - lands straight at its output scale. `R` depends on the view's largest - `|dc|` (`dc_max_log2`), so `FractalApp::bla_table` rebuilds on reference - change or when the dc range grows (or shrinks by `BLA_DC_SLACK` binades); - exports/headless build per frame via `bla::for_uniforms`. The table stops + merged linear steps `e' = M·e + N·dc` (real 2×2 matrices; valid while + `|e| < R`) built on the CPU from the reference orbit, so the shader's + `bla_lookup` jumps each pixel over whole runs of steps. Every kind but + Phoenix (two-term map), no morph (`bla::applies`, the `BLA` override). + `M` is the map's Jacobian at `X`: `C(f'(X))` for the holomorphic kinds, a + sign fold of `C(2X)` for the abs/conjugate ones. Each kind's `M` and + radius live in `Node::step`, which must match `advance_delta_kind`. The + abs kinds' radius also keeps the delta off their fold lines (where + `diffabs` switches branch), and Complex Multibrot's keeps it off the + branch cut. So Burning Ship / Perpendicular / Buffalo can't jump along the + real axis (their fold), where their orbits often sit. Merges use the exact + 2×2 spectral norm (Frobenius would lose √2 of radius per level). This is + what makes deep zoom fast: every pixel follows the reference for tens of + thousands of steps before diverging (Mandelbrot 1e-200: 12.7 s → 0.7 s + at 960×540). Level `l` node `i` covers steps `1 + i·2^l ..`, and only + levels ≥ 3 are uploaded (bindings 4/5, 48 B nodes, `bla_meta` = + `[min_level, levels, offsets…]`). Coefficients are floatexp (f32 + mantissas + i32 exponent), so a jump in the deep prologue lands straight + at its output scale. `R` depends on the view's largest `|dc|` + (`dc_max_log2`), so `FractalApp::bla_table` rebuilds on reference or kind + change or when the dc range grows (or shrinks by `BLA_DC_SLACK` binades). + Exports/headless build per frame via `bla::for_uniforms`. The table stops before the reference crosses the pixel bailout, so a jump never skips an escape. Measure `|e|` with `log2_mag`, never `log2(dot(e, e))`: a 2^-100 delta squares to 0 in f32 and passed every radius test. `--no-bla` / the "Skip iterations (BLA)" checkbox upload an empty table - for A/B checks (it must render like `--no-bla` up to f32 noise). + for A/B checks. BLA must render like `--no-bla` up to f32 noise; on + chaotic views, compare against a `--no-bla` render nudged by ~0.01 px, + which differs by more. `escape_counts_match_all_kinds` checks every + kind on the CPU against the plain loop with f32 rounding. - `src/fractal/renderer.rs` — `FractalRenderer` (wgpu pipelines, uniform + storage buffers, bind groups), `Uniforms` (repr(C) layout that must match the WGSL `Uniforms` struct field-for-field, including padding; it includes @@ -305,7 +317,9 @@ arms), `reference.rs` (CPU iteration formula arm, and a test comparing against a naive `f64` iteration), `common.wgsl` (matching `KIND_*` const), `mandelbrot.wgsl` (matching `advance_delta`/`fprime` arms, plus the deep path's `advance_delta_scaled_kind` arm, its degree in `deep_step_kind` and, -if not z²-like, a `deep_fprime` arm), `buddhabrot.wgsl` +if not z²-like, a `deep_fprime` arm), `bla.rs` (a `Node::step` arm: the +step's Jacobian and linearity radius, plus a case in +`escape_counts_match_all_kinds`; or exclude the kind in `applies`), `buddhabrot.wgsl` (matching arm in `advance()`, if the kind makes sense as a Buddhabrot), `renderer.rs` `Uniforms` (only if the kind needs a new per-kind constant, e.g. Phoenix's `phoenix_p`), `app.rs` (`JULIA_PRESETS`/`SET_PRESETS` slot, diff --git a/src/app.rs b/src/app.rs index e482efc..ea3e9f7 100644 --- a/src/app.rs +++ b/src/app.rs @@ -56,6 +56,7 @@ const BLA_DC_SLACK: i32 = 2; #[derive(Clone, Copy, PartialEq)] struct BlaKey { generation: u64, + kind: u32, on: bool, julia: bool, dc_log2: i32, @@ -1304,12 +1305,14 @@ impl FractalApp { fn bla_table(&mut self, u: &Uniforms) -> Arc { let want = BlaKey { generation: self.generation, + kind: u.kind, on: self.use_bla && bla::applies(u), julia: u.is_julia != 0, dc_log2: bla::dc_max_log2(u), }; let fresh = self.bla_key.as_ref().is_some_and(|k| { k.generation == want.generation + && k.kind == want.kind && k.on == want.on && k.julia == want.julia && (!want.on diff --git a/src/fractal/bla.rs b/src/fractal/bla.rs index 30143d7..3a293f9 100644 --- a/src/fractal/bla.rs +++ b/src/fractal/bla.rs @@ -1,55 +1,66 @@ //! Bivariate linear approximation (BLA): skipping many perturbation steps at //! once. //! -//! Near the reference, a Mandelbrot delta step `e ← 2·X_m·e + e² + dc` is -//! linear in `(e, dc)` as long as `e²` is negligible next to `2·X_m·e`, i.e. -//! `|e| < R = ε·|X_m|`. Composing such steps gives `e_{m+k} = A·e_m + B·dc` -//! for whole runs of steps. This module builds a binary table of those -//! compositions from the reference orbit (level `l` merges `2^l` steps). The -//! shader (`bla_lookup` in `mandelbrot.wgsl`) then jumps each pixel over the -//! longest run whose validity radius its delta is inside. At deep zoom every -//! pixel follows the reference for tens of thousands of iterations before -//! its orbit diverges, so most of that turns into a few table lookups. +//! Near the reference, a delta step `e ← f(X_m + e) − f(X_m) + dc` is linear +//! in `(e, dc)` as long as its non-linear part is negligible: +//! `e' ≈ M_m·e + dc`, with `M_m` the real 2×2 Jacobian of the map at `X_m`. +//! Composing such steps gives `e_{m+k} = M·e_m + N·dc` for whole runs of +//! steps. This module builds a binary table of those compositions from the +//! reference orbit (level `l` merges `2^l` steps). The shader (`bla_lookup` +//! in `mandelbrot.wgsl`) then jumps each pixel over the longest run whose +//! validity radius `R` its delta is inside. At deep zoom every pixel follows +//! the reference for tens of thousands of iterations before its orbit +//! diverges, so most of that turns into a few table lookups. +//! +//! Real matrices rather than complex coefficients, so one shader path covers +//! every kind: `M` is complex multiplication by `f'(X)` for the holomorphic +//! kinds, and a sign fold of `C(2X)` for the abs / conjugate ones (see +//! [`Node::step`], which also holds each kind's radius). The folds are exact +//! while the delta doesn't cross the fold line, so their radius also keeps +//! it on one side. Phoenix's two-term map would need a 4×4 state matrix and +//! isn't covered; neither are kind-switch morphs. //! //! Merging steps `x` then `y`: -//! `A = A_y·A_x`, `B = A_y·B_x + B_y`, -//! `R = min(R_x, max(0, (R_y − |B_x|·dc_max) / |A_x|))`. +//! `M = M_y·M_x`, `N = M_y·N_x + N_y`, +//! `R = min(R_x, max(0, (R_y − ‖N_x‖·dc_max) / ‖M_x‖))`, with `‖·‖` the +//! spectral norm (exact for 2×2: the Frobenius norm would overestimate +//! conformal maps by √2, and shrink R by that at every level). //! `R` depends on the largest pixel offset `dc_max`, so a table is only valid //! for views whose `|dc|` stays below the one it was built with (see //! [`dc_max_log2`]). Coefficients span far more than f64's exponent range at -//! deep zoom (`|A|` ~ 1/pixel size), so they're built as [`Fx`] (f64 mantissa -//! with its own exponent) and uploaded as f32 mantissa + i32 exponent. -//! -//! Only the plain Mandelbrot map (set plane and Julia) uses it for now. +//! deep zoom (`‖M‖` ~ 1/pixel size), so they're built as floatexp ([`Fx`], +//! [`Mx`]: f64 mantissas with their own exponent) and uploaded as f32 +//! mantissas + i32 exponent. use super::FractalKind; use super::reference::RefOrbit; use super::renderer::Uniforms; -/// Relative size of the dropped `e²` term that a step may have. f32's own -/// precision (2^-24) already renders indistinguishably from plain stepping, -/// but a chaotic seahorse pixel then escaped 7 iterations late against an -/// f64 emulation (`escape_counts_match`). 2^-28 fixes that at the same -/// render speed on deep views. +/// Relative size of the dropped non-linear term that a step may have. f32's +/// own precision (2^-24) already renders indistinguishably from plain +/// stepping, but a chaotic seahorse pixel then escaped 7 iterations late +/// against an f64 emulation (`escape_counts_match`). 2^-28 fixes that at the +/// same render speed on deep views. const EPSILON_LOG2: i32 = -28; /// Lowest level uploaded. Lower levels are still merged, just not stored: /// a 1..4-step jump doesn't pay for its lookup, and skipping them keeps the -/// table at 8 bytes per orbit point. +/// table at 12 bytes per orbit point. const MIN_LEVEL: u32 = 3; /// Upload budget (bytes): the WebGPU default storage binding size limit. const MAX_TABLE_BYTES: usize = 128 << 20; -/// One table node, as the shader's `Bla` struct: `A = a·2^a_exp`, -/// `B = b·2^b_exp`, valid while `log2|e| < r_log2`. +/// One table node, as the shader's `Bla` struct: `M = m·2^m_exp`, +/// `N = n·2^n_exp` (row-major 2×2: `[m00, m01, m10, m11]`), valid while +/// `log2|e| < r_log2`. #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)] pub struct GpuBla { - pub a: [f32; 2], - pub b: [f32; 2], - pub a_exp: i32, - pub b_exp: i32, + pub m: [f32; 4], + pub n: [f32; 4], + pub m_exp: i32, + pub n_exp: i32, pub r_log2: f32, pub _pad: u32, } @@ -91,24 +102,50 @@ impl Default for BlaTable { } /// Whether the shader's BLA path applies to these uniforms' kind / morph -/// (the `BLA` pipeline override, see `PipelineKey`). +/// (the `BLA` pipeline override, see `PipelineKey`): every kind but Phoenix. pub fn applies(u: &Uniforms) -> bool { - u.kind == FractalKind::Mandelbrot as u32 && u.morph_w <= 0.0 + u.kind != FractalKind::Phoenix as u32 && u.morph_w <= 0.0 +} + +/// The iteration map a table linearizes, with the same (f32) constants the +/// shader's delta step uses. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct StepMap { + pub kind: FractalKind, + /// Multibrot exponent, clamped like the shader's. + pub power: u32, + pub lambda: (f64, f64), + pub complex_power: (f64, f64), + /// Julia plane: c is fixed, so no `dc` is added per step (`N = 0`). + pub julia: bool, +} + +impl StepMap { + pub fn from_uniforms(u: &Uniforms) -> Option { + let kind = *FractalKind::ALL.get(u.kind as usize)?; + Some(Self { + kind, + power: u.power.clamp(2, 20), + lambda: (u.lambda_l[0] as f64, u.lambda_l[1] as f64), + complex_power: (u.complex_power[0] as f64, u.complex_power[1] as f64), + julia: u.is_julia != 0, + }) + } } /// The table for rendering `u` from `orbit` (empty when BLA doesn't apply /// or is switched off). pub fn for_uniforms(orbit: &RefOrbit, u: &Uniforms, enabled: bool) -> BlaTable { - if !enabled || !applies(u) { - return BlaTable::empty(); + match StepMap::from_uniforms(u) { + Some(map) if enabled && applies(u) => build( + orbit, + u.ref_len as usize, + dc_max_log2(u), + u.bailout_sq as f64, + &map, + ), + _ => BlaTable::empty(), } - build( - orbit, - u.ref_len as usize, - dc_max_log2(u), - u.is_julia != 0, - u.bailout_sq as f64, - ) } /// Largest `log2|dc|` a pixel sample of this view can have, rounded up with @@ -222,6 +259,17 @@ impl Fx { } } + /// `self·2^k` (exact). + fn shl(self, k: i32) -> Fx { + if self.is_zero() { + return self; + } + Fx { + e: self.e + k, + ..self + } + } + /// `|self|` as a scalar. fn abs(self) -> Fx { Fx::scalar(self.re.hypot(self.im), self.e) @@ -232,9 +280,9 @@ impl Fx { Fx::scalar(self.re / o.re, self.e - o.e) } - /// Scalar comparison (both scalars). - fn lt(self, o: Fx) -> bool { - self.log2() < o.log2() + /// Scalar minimum (both scalars, non-negative). + fn min(self, o: Fx) -> Fx { + if self.log2() < o.log2() { self } else { o } } /// `log2|self|` (`-inf` for zero). @@ -244,54 +292,241 @@ impl Fx { } self.re.hypot(self.im).log2() + self.e as f64 } + + /// `self^k` for an integer `k >= 0`. + fn powi(self, k: u32) -> Fx { + (0..k).fold(Fx::scalar(1.0, 0), |acc, _| acc.mul(self)) + } + + /// Principal `self^p` for a complex `p` (the branch `cpow` and the + /// reference use: arg in (-π, π]). 0 for 0, like `cpow`. + fn cpow(self, p: (f64, f64)) -> Fx { + if self.is_zero() { + return Fx::ZERO; + } + let ln_r = self.re.hypot(self.im).ln() + self.e as f64 * std::f64::consts::LN_2; + let theta = self.im.atan2(self.re); + let lr = p.0 * ln_r - p.1 * theta; + let li = p.0 * theta + p.1 * ln_r; + let k = (lr / std::f64::consts::LN_2).floor(); + let mag = (lr - k * std::f64::consts::LN_2).exp(); + let (sin, cos) = li.sin_cos(); + Fx::new(mag * cos, mag * sin, k as i32) + } +} + +/// Extended-range real 2×2 matrix `[[a, b], [c, d]]·2^e` (row-major `m`), +/// normalized so its largest entry is in `[0.5, 1)` (or all zero, `e = 0`). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Mx { + m: [f64; 4], + e: i32, +} + +impl Mx { + const ZERO: Mx = Mx { m: [0.0; 4], e: 0 }; + const IDENTITY: Mx = Mx { + m: [0.5, 0.0, 0.0, 0.5], + e: 1, + }; + + fn new(m: [f64; 4], e: i32) -> Mx { + let a = m.iter().fold(0.0f64, |a, v| a.max(v.abs())); + if a == 0.0 || !a.is_finite() { + return Mx::ZERO; + } + let k = exponent(a); + Mx { + m: m.map(|v| scale(v, -k)), + e: e + k, + } + } + + /// Complex multiplication by `a`. + fn complex(a: Fx) -> Mx { + Mx::new([a.re, -a.im, a.im, a.re], a.e) + } + + /// `diag(s0, s1)·self`: flip the sign of rows (the abs folds). + fn fold(self, s0: f64, s1: f64) -> Mx { + let [a, b, c, d] = self.m; + Mx { + m: [s0 * a, s0 * b, s1 * c, s1 * d], + e: self.e, + } + } + + fn is_zero(self) -> bool { + self.m == [0.0; 4] + } + + /// `self·o`. + fn mul(self, o: Mx) -> Mx { + if self.is_zero() || o.is_zero() { + return Mx::ZERO; + } + let [a, b, c, d] = self.m; + let [p, q, r, s] = o.m; + Mx::new( + [a * p + b * r, a * q + b * s, c * p + d * r, c * q + d * s], + self.e + o.e, + ) + } + + fn add(self, o: Mx) -> Mx { + if self.is_zero() { + return o; + } + if o.is_zero() { + return self; + } + let e = self.e.max(o.e); + let (da, db) = (self.e - e, o.e - e); + if da < -80 { + return o; + } + if db < -80 { + return self; + } + let mut m = [0.0; 4]; + for (k, v) in m.iter_mut().enumerate() { + *v = scale(self.m[k], da) + scale(o.m[k], db); + } + Mx::new(m, e) + } + + /// Largest singular value (the operator norm), as a scalar. + fn norm(self) -> Fx { + let [a, b, c, d] = self.m; + let f2 = a * a + b * b + c * c + d * d; + let det = a * d - b * c; + let disc = (f2 * f2 - 4.0 * det * det).max(0.0).sqrt(); + Fx::scalar(((f2 + disc) / 2.0).sqrt(), self.e) + } } #[derive(Clone, Copy)] struct Node { - a: Fx, - b: Fx, + m: Mx, + n: Mx, r: Fx, } +/// Sign of a mantissa, as the fold factor (+1 at 0: the radius is 0 there +/// anyway, so the node is never used). +fn sign(x: f64) -> f64 { + if x < 0.0 { -1.0 } else { 1.0 } +} + impl Node { - /// Step at reference point `x`: `A = 2x`, `B = 1` (0 for Julia, where no - /// dc is added), `R = ε·|x|`. - fn step(x: Fx, julia: bool) -> Node { + /// One step of `map` at reference point `x`: its Jacobian `M`, `N = I` + /// (0 for Julia, where no dc is added) and the radius within which the + /// step is linear to ε. Must match `advance_delta_kind` in the shader + /// (the same maps as `reference.rs::step_f64`). + /// + /// ε bounds: the dropped second-order term relative to the linear one + /// (|e|/(2|X|) for z², (p−1)|e|/(2|X|) for z^p, |e|/|1−2X| for Lambda) + /// is kept at ε/2. The folds (abs kinds) are isometries, so their M + /// has both singular values 2|X|, like Mandelbrot's; their fold bounds + /// keep the delta from crossing the line where the abs switches branch + /// (with a factor ½ for the dropped e² there). Complex Multibrot must also + /// not cross the principal branch cut (the negative real axis), like + /// `complex_multibrot_delta`. + fn step(map: &StepMap, x: Fx) -> Node { + let eps = |r: Fx| r.shl(EPSILON_LOG2); + let c2x = Mx::complex(x.shl(1)); + let (re, im) = (x.re, x.im); // x's components, in units of 2^x.e + let hyp = re.hypot(im); + // Fold bounds, as scalars at x's scale: + // |xy|/(|x|+|y|) (sign of xy), |x²−y²|/(2|X|) (sign of x²−y²), |y|. + let fold_xy = || Fx::scalar(0.5 * (re * im).abs() / (re.abs() + im.abs()), x.e); + let fold_sq = || Fx::scalar(0.5 * (re * re - im * im).abs() / (2.0 * hyp), x.e); + let (m, r) = if x.is_zero() { + (Mx::ZERO, Fx::ZERO) + } else { + match map.kind { + FractalKind::Mandelbrot => (c2x, eps(x.abs())), + FractalKind::Tricorn => (c2x.fold(1.0, -1.0), eps(x.abs())), + FractalKind::BurningShip => { + (c2x.fold(1.0, sign(re * im)), eps(x.abs()).min(fold_xy())) + } + FractalKind::Celtic => ( + c2x.fold(sign(re * re - im * im), 1.0), + eps(x.abs()).min(fold_sq()), + ), + FractalKind::Buffalo => ( + c2x.fold(sign(re * re - im * im), -sign(re * im)), + eps(x.abs()).min(fold_xy()).min(fold_sq()), + ), + FractalKind::Perpendicular => ( + c2x.fold(1.0, -sign(im)), + eps(x.abs()).min(Fx::scalar(0.5 * im.abs(), x.e)), + ), + FractalKind::Multibrot => { + let p = map.power; + let a = x.powi(p - 1).mul(Fx::scalar(p as f64, 0)); + ( + Mx::complex(a), + eps(x.abs().div(Fx::scalar((p - 1) as f64, 0))), + ) + } + FractalKind::Lambda => { + let (lr, li) = map.lambda; + let one_2x = Fx::scalar(1.0, 0).add(x.shl(1).neg()); + let a = Fx::new(lr, li, 0).mul(one_2x); + (Mx::complex(a), eps(one_2x.abs().shl(-1))) + } + FractalKind::ComplexMultibrot => { + let (pr, pi) = map.complex_power; + let a = x.cpow((pr - 1.0, pi)).mul(Fx::new(pr, pi, 0)); + let cut = if re < 0.0 { + Fx::scalar(0.5 * im.abs(), x.e) + } else { + Fx::scalar(0.5 * hyp, x.e) + }; + let q = (pr - 1.0).hypot(pi); + let r = if q > 1e-12 { + eps(x.abs().div(Fx::scalar(q, 0))).min(cut) + } else { + cut // p = 1: the map is linear + }; + (Mx::complex(a), r) + } + // Not linearized (see `applies`). + FractalKind::Phoenix => (Mx::ZERO, Fx::ZERO), + } + }; Node { - a: Fx { e: x.e + 1, ..x }, - b: if julia { Fx::ZERO } else { Fx::scalar(1.0, 0) }, - r: Fx { - e: x.e + EPSILON_LOG2, - ..x.abs() - }, + m, + n: if map.julia { Mx::ZERO } else { Mx::IDENTITY }, + r, } } /// `self` then `y`. fn then(self, y: Node, dc_max: Fx) -> Node { - let a = y.a.mul(self.a); - let b = y.a.mul(self.b).add(y.b); - let r = if self.r.is_zero() || self.a.is_zero() { + let m = y.m.mul(self.m); + let n = y.m.mul(self.n).add(y.n); + let r = if self.r.is_zero() || self.m.is_zero() { Fx::ZERO } else { - let rem = y.r.add(self.b.abs().mul(dc_max).neg()); + let rem = y.r.add(self.n.norm().mul(dc_max).neg()); if rem.re <= 0.0 { Fx::ZERO } else { - let ry = rem.div(self.a.abs()); - if ry.lt(self.r) { ry } else { self.r } + rem.div(self.m.norm()).min(self.r) } }; - Node { a, b, r } + Node { m, n, r } } fn gpu(self) -> GpuBla { let r_log2 = self.r.log2(); GpuBla { - a: [self.a.re as f32, self.a.im as f32], - b: [self.b.re as f32, self.b.im as f32], - a_exp: self.a.e, - b_exp: self.b.e, + m: self.m.m.map(|v| v as f32), + n: self.n.m.map(|v| v as f32), + m_exp: self.m.e, + n_exp: self.n.e, r_log2: if r_log2.is_finite() { r_log2 as f32 } else { @@ -314,12 +549,13 @@ pub fn build( orbit: &RefOrbit, len: usize, dc_max_log2: i32, - julia: bool, bailout_sq: f64, + map: &StepMap, ) -> BlaTable { let len = len.min(orbit.len()); // Steps 1..=len-2 (step m reads X_m and lands on X_{m+1}, which must - // exist). Step 0 (X_0 = 0, e ← e² + dc) is never linear. + // exist). Step 0 (X_0 = 0 in the set plane, where e ← e² + dc) is never + // linear for the z² kinds, so it's never approximated. let limit = bailout_sq * (1.0 - 1e-3); let escape = (1..len).find(|&m| { let [re, im] = orbit.points[m]; @@ -337,7 +573,7 @@ pub fn build( if steps >> min_level == 0 { return BlaTable::empty(); } - let dc_max = if julia { + let dc_max = if map.julia { Fx::ZERO } else { Fx::scalar(1.0, dc_max_log2) @@ -352,8 +588,8 @@ pub fn build( let mut level: Vec = (0..steps >> min_level) .map(|i| { let start = 1 + i * run; - (1..run).fold(Node::step(point(start), julia), |acc, k| { - acc.then(Node::step(point(start + k), julia), dc_max) + (1..run).fold(Node::step(map, point(start)), |acc, k| { + acc.then(Node::step(map, point(start + k)), dc_max) }) }) .collect(); @@ -378,10 +614,42 @@ pub fn build( #[cfg(test)] mod tests { use super::*; - use crate::fractal::compute_set_reference; + use crate::fractal::{compute_reference, compute_set_reference}; use crate::view::Big; - fn orbit(cr: f64, ci: f64, iters: u32) -> RefOrbit { + const LAMBDA: (f64, f64) = (1.0, 0.0); + const CPOW: (f64, f64) = (2.5, 0.3); + + fn map(kind: FractalKind, julia: bool) -> StepMap { + StepMap { + kind, + power: 3, + lambda: LAMBDA, + complex_power: CPOW, + julia, + } + } + + /// Reference orbit from `z0` with parameter `c` (`z0 = 0`: set plane). + fn orbit(map: &StepMap, z0: (f64, f64), c: (f64, f64), iters: u32) -> RefOrbit { + let b = |v: f64| Big::from_f64(v, 128); + compute_reference( + &b(z0.0), + &b(z0.1), + &b(c.0), + &b(c.1), + iters, + 128, + map.kind, + map.power, + (0.0, 0.0), + map.lambda, + map.complex_power, + None, + ) + } + + fn mandel_orbit(cr: f64, ci: f64, iters: u32) -> RefOrbit { compute_set_reference( &Big::from_f64(cr, 128), &Big::from_f64(ci, 128), @@ -396,13 +664,123 @@ mod tests { ) } - fn fx_to_f64(v: [f32; 2], e: i32) -> (f64, f64) { - let s = 2f64.powi(e); - (v[0] as f64 * s, v[1] as f64 * s) + type C = (f64, f64); + + fn cmul(a: C, b: C) -> C { + (a.0 * b.0 - a.1 * b.1, a.0 * b.1 + a.1 * b.0) } - /// Replay the shader's lookup: the longest valid aligned node at `m`. - fn lookup(t: &BlaTable, m: usize, e_log2: f64) -> Option<(usize, usize)> { + fn add(a: C, b: C) -> C { + (a.0 + b.0, a.1 + b.1) + } + + fn mag2(a: C) -> f64 { + a.0 * a.0 + a.1 * a.1 + } + + /// `M·e + N·dc` for a node, in f64. + fn apply(nd: &GpuBla, e: C, dc: C) -> C { + let mv = |m: [f32; 4], k: i32, v: C| { + let s = 2f64.powi(k); + ( + (m[0] as f64 * v.0 + m[1] as f64 * v.1) * s, + (m[2] as f64 * v.0 + m[3] as f64 * v.1) * s, + ) + }; + add(mv(nd.m, nd.m_exp, e), mv(nd.n, nd.n_exp, dc)) + } + + /// The shader's `diffabs`: |c + d| − |c| without cancellation. + fn diffabs(c: f64, d: f64) -> f64 { + let cd = c + d; + if c >= 0.0 { + if cd >= 0.0 { d } else { -(2.0 * c + d) } + } else if cd > 0.0 { + 2.0 * c + d + } else { + -d + } + } + + fn cpow(z: C, p: C) -> C { + if z == (0.0, 0.0) { + return (0.0, 0.0); + } + let ln_r = 0.5 * mag2(z).ln(); + let th = z.1.atan2(z.0); + let mag = (p.0 * ln_r - p.1 * th).exp(); + let (s, c) = (p.0 * th + p.1 * ln_r).sin_cos(); + (mag * c, mag * s) + } + + /// f64 port of the shader's `advance_delta_kind`: f(X + e) − f(X). + fn delta(map: &StepMap, z: C, e: C) -> C { + let sq = add(cmul((2.0 * z.0, 2.0 * z.1), e), cmul(e, e)); + match map.kind { + FractalKind::Mandelbrot => sq, + FractalKind::Tricorn => { + let (cz, ce) = ((z.0, -z.1), (e.0, -e.1)); + add(cmul((2.0 * cz.0, 2.0 * cz.1), ce), cmul(ce, ce)) + } + FractalKind::BurningShip => { + let dp = z.0 * e.1 + z.1 * e.0 + e.0 * e.1; + (sq.0, 2.0 * diffabs(z.0 * z.1, dp)) + } + FractalKind::Celtic => (diffabs(z.0 * z.0 - z.1 * z.1, sq.0), sq.1), + FractalKind::Buffalo => ( + diffabs(z.0 * z.0 - z.1 * z.1, sq.0), + -diffabs(2.0 * z.0 * z.1, sq.1), + ), + FractalKind::Perpendicular => { + let da = diffabs(z.1, e.1); + let ay = z.1.abs() + da; + (sq.0, -2.0 * (z.0 * da + e.0 * ay)) + } + FractalKind::Multibrot => { + // (Z+e)^p − Z^p = e·Σ_k (Z+e)^k Z^(p−1−k), Horner-style. + let y = add(z, e); + let (mut s, mut zj) = ((1.0, 0.0), (1.0, 0.0)); + for _ in 1..map.power { + zj = cmul(zj, z); + s = add(cmul(s, y), zj); + } + cmul(e, s) + } + FractalKind::Lambda => { + let t = (1.0 - 2.0 * z.0 - e.0, -2.0 * z.1 - e.1); + cmul(map.lambda, cmul(e, t)) + } + FractalKind::ComplexMultibrot => { + let p = map.complex_power; + let y = add(z, e); + let crosses = z.0 < 0.0 && ((z.1 < 0.0) != (y.1 < 0.0)); + let w2 = mag2(e) / mag2(z); + if w2 < 0.25 && !crosses { + let zz = mag2(z); + let w = cmul(e, (z.0 / zz, -z.1 / zz)); + let (mut wk, mut acc, mut coef) = (w, (0.0, 0.0), (1.0, 0.0)); + for k in 1..=40 { + coef = cmul(coef, (p.0 - (k - 1) as f64, p.1)); + coef = (coef.0 / k as f64, coef.1 / k as f64); + acc = add(acc, cmul(coef, wk)); + wk = cmul(wk, w); + if mag2(wk) < 1e-36 * mag2(acc) { + break; + } + } + cmul(cpow(z, p), acc) + } else { + let (a, b) = (cpow(y, p), cpow(z, p)); + (a.0 - b.0, a.1 - b.1) + } + } + FractalKind::Phoenix => unreachable!(), + } + } + + /// Replay the shader's lookup: the longest valid aligned node at `m`, + /// of at most `budget` steps. + fn lookup(t: &BlaTable, m: usize, e_log2: f64, budget: usize) -> Option<(usize, usize)> { let (lmin, levels) = (t.meta[0], t.meta[1]); if m == 0 || levels == 0 { return None; @@ -418,7 +796,7 @@ mod tests { let base = t.meta[2 + k as usize] as usize; let count = t.meta[3 + k as usize] as usize - base; let local = j >> l; - if local >= count { + if (1usize << l) > budget || local >= count { break; } let node = &t.nodes[base + local]; @@ -430,149 +808,275 @@ mod tests { best } + struct Escape { + smooth: f64, + jumped: usize, + } + + /// The shader's f32 loop (rebasing, bailout, smooth count), in f64, with + /// or without the table. `off` is the pixel's dc (set plane) or z + /// offset (Julia). `None` when the pixel didn't escape. `round_f32` + /// rounds the delta to f32 after every plain step, like the GPU does. + fn emulate( + orb: &RefOrbit, + t: Option<&BlaTable>, + map: &StepMap, + off: C, + max_iter: usize, + round_f32: bool, + ) -> Option { + let x = |m: usize| (orb.points[m][0] as f64, orb.points[m][1] as f64); + let (step_add, mut e) = if map.julia { + ((0.0, 0.0), off) + } else { + (off, (0.0, 0.0)) + }; + let (mut m, mut n, mut jumped) = (0usize, 0usize, 0usize); + let x0 = x(0); + loop { + let z = add(x(m), e); + if mag2(z) > 1e6 { + let smooth = n as f64 - (0.5 * mag2(z).ln()).log2(); + return Some(Escape { smooth, jumped }); + } + if n >= max_iter { + return None; + } + let hit = t.filter(|_| m != 0).and_then(|t| { + let budget = (max_iter - n).min(orb.len() - 1 - m); + lookup(t, m, 0.5 * mag2(e).log2(), budget) + }); + if let Some((idx, k)) = hit { + e = apply(&t.unwrap().nodes[idx], e, step_add); + m += k; + n += k; + jumped += k; + } else { + e = add(delta(map, x(m), e), step_add); + if round_f32 { + e = (e.0 as f32 as f64, e.1 as f32 as f64); + } + m += 1; + n += 1; + } + if m >= orb.len() { + return Some(Escape { + smooth: n as f64, + jumped, + }); + } + let z = add(x(m), e); + if mag2(z) < mag2(e) { + e = (z.0 - x0.0, z.1 - x0.1); + m = 0; + } + } + } + + /// Escape iteration of `c` from `z0` iterated directly (in f64). + fn escape_time(map: &StepMap, z0: C, c: C, max: usize) -> usize { + let mut z = z0; + for n in 0..max { + if mag2(z) > 1e6 { + return n; + } + z = add(delta(map, (0.0, 0.0), z), c); // f(0) = 0 for every kind + } + max + } + + /// A boundary point of `map`'s default view (escaping late, i.e. + /// chaotic nearby): the most iterations under `max / 2`. + fn boundary_point(map: &StepMap, julia_c: Option, max: usize) -> C { + let (cx, cy, hh) = map.kind.default_set_view(); + let (cx, cy, hh) = if julia_c.is_some() { + (0.0, 0.0, 1.5) + } else { + (cx, cy, hh) + }; + let mut best = ((cx, cy), 0); + let k = 97; + for i in 0..k { + for j in 0..k { + let p = ( + cx + hh * (2.0 * i as f64 / k as f64 - 1.0) * 1.3, + cy + hh * (2.0 * j as f64 / k as f64 - 1.0), + ); + let n = match julia_c { + Some(c) => escape_time(map, p, c, max), + None => escape_time(map, (0.0, 0.0), p, max), + }; + if n < max / 2 && n > best.1 { + best = (p, n); + } + } + } + assert!(best.1 > 50, "{:?}: no boundary point found", map.kind); + best.0 + } + + /// Compare jumping against plain f64 stepping on 40 pixels around the + /// reference. Chaotic pixels amplify any error, so a few escape counts + /// differ whatever the method; BLA passes if it mismatches no more + /// pixels than plain stepping with the GPU's f32 rounding does (and + /// actually jumps). Returns the steps jumped. + fn check_pixels(orb: &RefOrbit, t: &BlaTable, m: &StepMap, half: f64, max: usize) -> usize { + let (mut jumped, mut bad_bla, mut bad_f32) = (0, 0, 0); + let mut worst = String::new(); + for i in 0..40 { + let a = i as f64 * 0.37; + let off = (half * a.cos(), half * (1.3 * a).sin()); + let plain = emulate(orb, None, m, off, max, false).map(|e| e.smooth); + let f32ish = emulate(orb, None, m, off, max, true).map(|e| e.smooth); + let fast = emulate(orb, Some(t), m, off, max, false); + if let Some(f) = &fast { + jumped += f.jumped; + } + let fast = fast.map(|e| e.smooth); + let differs = |x: Option| match (plain, x) { + (Some(a), Some(b)) => (a - b).abs() >= 0.05, + (a, b) => a.is_some() != b.is_some(), + }; + if differs(fast) { + bad_bla += 1; + worst = format!("off {off:?}: plain {plain:?}, bla {fast:?}"); + } + bad_f32 += differs(f32ish) as usize; + } + assert!( + bad_bla <= bad_f32.max(1), + "{:?} julia={}: {bad_bla} pixels differ with BLA, {bad_f32} with f32 \ + rounding (last: {worst})", + m.kind, + m.julia + ); + jumped + } + + /// For every kind BLA covers: jumping must reproduce the plain + /// perturbation loop's smooth escape counts on a chaotic view, and must + /// actually jump. + #[test] + fn escape_counts_match_all_kinds() { + let max = 4000; + let mut cases: Vec<(StepMap, Option)> = FractalKind::ALL + .iter() + .filter(|&&k| k != FractalKind::Phoenix) + .map(|&k| (map(k, false), None)) + .collect(); + cases.push((map(FractalKind::Mandelbrot, true), Some((-0.8, 0.156)))); + cases.push((map(FractalKind::BurningShip, true), Some((-0.6, -0.9)))); + for (m, julia_c) in cases { + let p = boundary_point(&m, julia_c, max); + let orb = match julia_c { + Some(c) => orbit(&m, p, c, max as u32), + None => orbit(&m, (0.0, 0.0), p, max as u32), + }; + let half = 1e-15f64; + let t = build( + &orb, + orb.len(), + (2.0 * half).log2().ceil() as i32 + 1, + 1e6, + &m, + ); + let jumped = check_pixels(&orb, &t, &m, half, max); + assert!(jumped > 0, "{:?} julia={}: never jumped", m.kind, m.julia); + } + } + /// Jumping with the table must track the plain perturbation iteration. #[test] fn jumps_match_stepping() { // A point inside the main cardioid: the orbit never escapes, so the // reference is long and smooth, and the deltas stay small. - let orb = orbit(-0.1, 0.2, 5000); + let m = map(FractalKind::Mandelbrot, false); + let orb = mandel_orbit(-0.1, 0.2, 5000); assert_eq!(orb.len(), 5001); let dc_max_log2 = -40; - let t = build(&orb, orb.len(), dc_max_log2, false, 1e6); + let t = build(&orb, orb.len(), dc_max_log2, 1e6, &m); assert!(t.levels() > 3); - let x = |m: usize| (orb.points[m][0] as f64, orb.points[m][1] as f64); + let x = |k: usize| (orb.points[k][0] as f64, orb.points[k][1] as f64); let mut jumped = 0; for &(dr, di) in &[(0.7, 0.1), (-0.3, 0.9), (0.0, -1.0)] { let dc = (dr * 2f64.powi(dc_max_log2), di * 2f64.powi(dc_max_log2)); - // Reference: plain perturbation steps. let mut e_ref = (0.0, 0.0); let mut plain = vec![e_ref]; - for m in 0..orb.len() - 1 { - let (xr, xi) = x(m); - let (er, ei) = e_ref; - e_ref = ( - 2.0 * (xr * er - xi * ei) + er * er - ei * ei + dc.0, - 2.0 * (xr * ei + xi * er) + 2.0 * er * ei + dc.1, - ); + for k in 0..orb.len() - 1 { + e_ref = add(delta(&m, x(k), e_ref), dc); plain.push(e_ref); } - // With jumps. - let (mut m, mut e) = (0usize, (0.0f64, 0.0f64)); - while m < orb.len() - 1 { - let e_log2 = e.0.hypot(e.1).log2(); - if let Some((idx, n)) = lookup(&t, m, e_log2) { - let nd = &t.nodes[idx]; - let (ar, ai) = fx_to_f64(nd.a, nd.a_exp); - let (br, bi) = fx_to_f64(nd.b, nd.b_exp); - e = ( - ar * e.0 - ai * e.1 + br * dc.0 - bi * dc.1, - ar * e.1 + ai * e.0 + br * dc.1 + bi * dc.0, - ); - m += n; + let (mut k, mut e) = (0usize, (0.0f64, 0.0f64)); + while k < orb.len() - 1 { + let budget = orb.len() - 1 - k; + if let Some((idx, n)) = lookup(&t, k, 0.5 * mag2(e).log2(), budget) { + e = apply(&t.nodes[idx], e, dc); + k += n; jumped += n; } else { - let (xr, xi) = x(m); - let (er, ei) = e; - e = ( - 2.0 * (xr * er - xi * ei) + er * er - ei * ei + dc.0, - 2.0 * (xr * ei + xi * er) + 2.0 * er * ei + dc.1, - ); - m += 1; + e = add(delta(&m, x(k), e), dc); + k += 1; } - let want = plain[m]; - let err = (e.0 - want.0).hypot(e.1 - want.1); - let mag = want.0.hypot(want.1); - assert!(err <= 1e-4 * mag + 1e-300, "m={m}: {e:?} vs {want:?}"); + let want = plain[k]; + let err = mag2((e.0 - want.0, e.1 - want.1)).sqrt(); + assert!( + err <= 1e-4 * mag2(want).sqrt() + 1e-300, + "k={k}: {e:?} vs {want:?}" + ); } } assert!(jumped > (orb.len() - 1) / 2, "only {jumped} steps jumped"); } - /// The shader's f32 loop (rebasing, escape, smooth count) with and - /// without jumps, on a chaotic seahorse view: escape iteration counts and - /// smooth values must agree. + /// The seahorse case that set ε: the smooth counts with and without + /// jumps must agree. #[test] fn escape_counts_match() { - let (cr, ci) = (-0.743_643_887_037_151, 0.131_825_904_205_330); - let orb = orbit(cr, ci, 20_000); - let half = 1e-9f64; - let dc_max_log2 = (2.0 * half).log2().ceil() as i32 + 1; - let t = build(&orb, orb.len(), dc_max_log2, false, 1e6); - let x = |m: usize| (orb.points[m][0] as f64, orb.points[m][1] as f64); - let run = |dc: (f64, f64), bla: bool| -> (u32, f64) { - let (mut m, mut n, mut e) = (0usize, 0u32, (0.0f64, 0.0f64)); - loop { - let xm = x(m); - let z = (xm.0 + e.0, xm.1 + e.1); - let z2 = z.0 * z.0 + z.1 * z.1; - if z2 > 1e6 || n >= 20_000 { - return (n, z2); - } - let hit = if bla && m != 0 { - lookup(&t, m, e.0.hypot(e.1).log2()) - } else { - None - }; - if let Some((idx, k)) = hit { - let nd = &t.nodes[idx]; - let (ar, ai) = fx_to_f64(nd.a, nd.a_exp); - let (br, bi) = fx_to_f64(nd.b, nd.b_exp); - e = ( - ar * e.0 - ai * e.1 + br * dc.0 - bi * dc.1, - ar * e.1 + ai * e.0 + br * dc.1 + bi * dc.0, - ); - m += k; - n += k as u32; - } else { - let (er, ei) = e; - e = ( - 2.0 * (xm.0 * er - xm.1 * ei) + er * er - ei * ei + dc.0, - 2.0 * (xm.0 * ei + xm.1 * er) + 2.0 * er * ei + dc.1, - ); - m += 1; - n += 1; - } - if m >= orb.len() { - return (u32::MAX, 0.0); - } - let xm = x(m); - let z = (xm.0 + e.0, xm.1 + e.1); - if z.0 * z.0 + z.1 * z.1 < e.0 * e.0 + e.1 * e.1 { - e = z; - m = 0; - } - } - }; - let mut jumped_any = false; - for i in 0..40 { - let a = i as f64 * 0.37; - let dc = (half * a.cos(), half * (1.3 * a).sin()); - let (n0, z0) = run(dc, false); - let (n1, z1) = run(dc, true); - jumped_any |= n0 > 1000; - let smooth = |n: u32, z2: f64| n as f64 - (0.5 * z2.ln()).log2(); - assert!( - (smooth(n0, z0) - smooth(n1, z1)).abs() < 0.05, - "dc {dc:?}: plain {n0} ({z0}), bla {n1} ({z1})" - ); + let m = map(FractalKind::Mandelbrot, false); + let orb = mandel_orbit(-0.743_643_887_037_151, 0.131_825_904_205_330, 20_000); + let half = 1e-15f64; + let t = build( + &orb, + orb.len(), + (2.0 * half).log2().ceil() as i32 + 1, + 1e6, + &m, + ); + let jumped = check_pixels(&orb, &t, &m, half, 20_000); + assert!(jumped > 0); + } + + /// The spectral norm is exact on conformal maps and folds of them. + #[test] + fn norm_is_exact() { + let a = Fx::new(0.3, -0.8, 5); + let want = a.abs().log2(); + for m in [ + Mx::complex(a), + Mx::complex(a).fold(1.0, -1.0), + Mx::complex(a).fold(-1.0, 1.0), + ] { + assert!((m.norm().log2() - want).abs() < 1e-12); } - assert!(jumped_any); + let diag = Mx::new([4.0, 0.0, 0.0, 0.25], 0); + assert!((diag.norm().log2() - 2.0).abs() < 1e-12); } /// A table built for a small dc_max must reject deltas it can't cover. #[test] fn radius_shrinks_with_dc_max() { - let orb = orbit(-0.1, 0.2, 2000); - let small = build(&orb, orb.len(), -40, false, 1e6); - let big = build(&orb, orb.len(), -4, false, 1e6); - let top = |t: &BlaTable| t.nodes[t.meta[2 + t.levels() as usize - 1] as usize].r_log2; - assert!(top(&big) < top(&small)); + let m = map(FractalKind::Mandelbrot, false); + let orb = mandel_orbit(-0.1, 0.2, 2000); + let small = build(&orb, orb.len(), -60, 1e6, &m); + let big = build(&orb, orb.len(), -30, 1e6, &m); // dc above the ~2^-30.5 step radius + assert!(big.nodes[0].r_log2 < small.nodes[0].r_log2); } #[test] fn layout() { - let orb = orbit(-0.1, 0.2, 1000); - let t = build(&orb, orb.len(), -30, false, 1e6); + let m = map(FractalKind::Mandelbrot, false); + let orb = mandel_orbit(-0.1, 0.2, 1000); + let t = build(&orb, orb.len(), -30, 1e6, &m); let steps = orb.len() - 2; assert_eq!(t.meta[0], MIN_LEVEL); for k in 0..t.levels() as usize { @@ -580,7 +1084,7 @@ mod tests { assert_eq!(count as usize, steps >> (MIN_LEVEL as usize + k)); } assert_eq!(*t.meta.last().unwrap() as usize, t.nodes.len()); - let tiny = orbit(-3.0, 0.0, 1000); // escapes at once - assert_eq!(build(&tiny, tiny.len(), -30, false, 1e6).levels(), 0); + let tiny = mandel_orbit(-3.0, 0.0, 1000); // escapes at once + assert_eq!(build(&tiny, tiny.len(), -30, 1e6, &m).levels(), 0); } } diff --git a/src/shaders/mandelbrot.wgsl b/src/shaders/mandelbrot.wgsl index fc8b999..8830331 100644 --- a/src/shaders/mandelbrot.wgsl +++ b/src/shaders/mandelbrot.wgsl @@ -32,14 +32,16 @@ @group(0) @binding(3) var ref_exp: array; // Bivariate linear approximation table (`fractal::bla`): node i of level l // maps the delta at reference step 1 + i·2^l to the one 2^l steps later as -// e' = A·e + B·dc, valid while log2|e| < r_log2. `bla_meta` is +// e' = M·e + N·dc, valid while log2|e| < r_log2. M = m·2^m_exp and +// N = n·2^n_exp are real 2x2 matrices, row-major (the Jacobian of the map, +// so the abs/conjugate kinds are covered too). `bla_meta` is // [min_level, level_count, off_0, ..., off_{level_count}]; only `BLA` // pipelines read either. struct Bla { - a: vec2, - b: vec2, - a_exp: i32, - b_exp: i32, + m: vec4, + n: vec4, + m_exp: i32, + n_exp: i32, r_log2: f32, _pad: u32, }; @@ -64,8 +66,8 @@ override MORPH: bool = false; // and `u.span` / `u.dc_offset` are all in units of 2^scale_exp, and each pixel // starts in the rescaled deep phase (see `iterate_sample`). override DEEP: bool = false; -// Jump over runs of reference steps with the BLA table (plain Mandelbrot, -// no morph; see `bla_lookup`). +// Jump over runs of reference steps with the BLA table (every kind but +// Phoenix, no morph; see `bla_lookup`). override BLA: bool = false; struct VsOut { @@ -596,6 +598,11 @@ const DEEP_RENORM_LOG2: i32 = 16; // binades above the delta's scale (|w| < 2^DEEP_RENORM_LOG2). const DEEP_NEAR_LOG2: i32 = 24; +// Row-major 2x2 matrix times vector (a BLA node's M or N). +fn mat2v(m: vec4, v: vec2) -> vec2 { + return vec2(dot(m.xy, v), dot(m.zw, v)); +} + // log2|v|, from above (|v| <= sqrt(2)·max component). Not via dot(v, v): // a delta ~2^-100 (a pixel offset at 1e-30 zoom) squares below f32's range, // and log2(0) = -inf passed every radius test, jumping pixels far too early. @@ -862,9 +869,9 @@ fn iterate_sample(offset: vec2, px: f32) -> Sample { if hit.y != 0u { let nd = bla_nodes[hit.x]; if DE { - var accv = fe_make(cmul(nd.a, v), nd.a_exp + sv); + var accv = fe_make(mat2v(nd.m, v), nd.m_exp + sv); if !IS_JULIA { - accv = fe_add(accv, fe_make(nd.b * px, nd.b_exp + scale_e)); + accv = fe_add(accv, fe_make(mat2v(nd.n, vec2(px, 0.0)), nd.n_exp + scale_e)); } v = accv.m; if accv.m.x != 0.0 || accv.m.y != 0.0 { @@ -874,9 +881,9 @@ fn iterate_sample(offset: vec2, px: f32) -> Sample { } } } - var acc = fe_make(cmul(nd.a, w), nd.a_exp + sx); + var acc = fe_make(mat2v(nd.m, w), nd.m_exp + sx); if !IS_JULIA { - acc = fe_add(acc, fe_make(cmul(nd.b, offset), nd.b_exp + scale_e)); + acc = fe_add(acc, fe_make(mat2v(nd.n, offset), nd.n_exp + scale_e)); } w = acc.m; if acc.m.x != 0.0 || acc.m.y != 0.0 { @@ -1099,9 +1106,14 @@ fn iterate_sample(offset: vec2, px: f32) -> Sample { // f'(z) of this step, shared by DE and the periodicity multiplier. // BLA jump (see the deep phase). dc and px are taken unscaled from // `offset`/`px`: at depth `step_add`/`px_t` have flushed to 0, but - // B·dc hasn't. The skipped steps' |f'|^2 product is |A|^2. No - // skipped iterate can be the window's closest to the critical point: - // a run's radius is below ε·|X| for every X in it. + // N·dc hasn't. The skipped steps' |f'|^2 product is |det M| (the + // steps are conformal, or folds of conformal maps). No skipped + // iterate can be the window's closest to the critical point: a run's + // radius is below ε·|X| for every X in it. + // + // With DE, dzs goes through M, the map's true Jacobian, where the + // plain loop multiplies by `fprime` (|2Z| for the abs kinds): same + // magnitude, since the folds are isometries. let e_old = e; let z_old = z; var jumped = false; @@ -1111,20 +1123,21 @@ fn iterate_sample(offset: vec2, px: f32) -> Sample { let nd = bla_nodes[hit.x]; let se = select(0, u.scale_exp, DEEP); if periodic { - let a2 = ldexp_sat(dot(nd.a, nd.a), 2 * nd.a_exp); + let det = abs(nd.m.x * nd.m.w - nd.m.y * nd.m.z); + let a2 = ldexp_sat(det, 2 * nd.m_exp); mult2 = mult2 * a2; mult2_cand = mult2_cand * a2; } if DE { - var dn = ldexp2_sat(cmul(nd.a, dzs), nd.a_exp); + var dn = ldexp2_sat(mat2v(nd.m, dzs), nd.m_exp); if !IS_JULIA { - dn = dn + ldexp2_sat(nd.b * px, nd.b_exp + se); + dn = dn + ldexp2_sat(mat2v(nd.n, vec2(px, 0.0)), nd.n_exp + se); } dzs = dn; } - var en = ldexp2_sat(cmul(nd.a, e), nd.a_exp); + var en = ldexp2_sat(mat2v(nd.m, e), nd.m_exp); if !IS_JULIA { - en = en + ldexp2_sat(cmul(nd.b, offset), nd.b_exp + se); + en = en + ldexp2_sat(mat2v(nd.n, offset), nd.n_exp + se); } e = en; m = m + hit.y; diff --git a/tests/shader_valid.rs b/tests/shader_valid.rs index 58bc688..cfcbb2c 100644 --- a/tests/shader_valid.rs +++ b/tests/shader_valid.rs @@ -86,8 +86,8 @@ fn mandelbrot_shader_specializations_compile() { for de in [0.0, 1.0] { for morph in [0.0, 1.0] { for deep in [0.0, 1.0] { - // BLA only exists for plain Mandelbrot (`bla::supported`). - let blas: &[f64] = if kind == 0 && morph == 0.0 { + // BLA: every kind but Phoenix (7), no morph (`bla::applies`). + let blas: &[f64] = if kind != 7 && morph == 0.0 { &[0.0, 1.0] } else { &[0.0]