From d587a0a9e746b970855677471e9b19dba67e0aff Mon Sep 17 00:00:00 2001 From: fkDead Date: Wed, 11 Nov 2026 20:20:49 +0100 Subject: [PATCH] capri-ui: add teleport module --- crates/capri-ui/src/teleport.rs | 608 ++++++++++++++++++++++++++++++++ 1 file changed, 608 insertions(+) create mode 100644 crates/capri-ui/src/teleport.rs diff --git a/crates/capri-ui/src/teleport.rs b/crates/capri-ui/src/teleport.rs new file mode 100644 index 0000000..de1dffa --- /dev/null +++ b/crates/capri-ui/src/teleport.rs @@ -0,0 +1,608 @@ +//! Red lightning teleport choreography (Capri's `avatar-teleport-motion.mjs`) and the +//! drag tether (`avatar-drag-tether.mjs`), ported literally. Coordinates are logical px. +use eframe::egui::{Color32, Painter, Pos2, Rect, Shape, Stroke}; + +use crate::geom; + +pub const FPS: f32 = 24.0; +pub const FRAMES: f32 = 28.0; +pub const TRANSIT_START: f32 = 6.0; +pub const ARRIVAL_START: f32 = 15.0; +const SETTLE_FRAME: f32 = FRAMES - 1.0; +const HEAD_POSITIONS: [f32; 9] = [0.11, 0.19, 0.3, 0.42, 0.55, 0.67, 0.79, 0.9, 1.0]; +const STRIKE_REACH: [f32; 6] = [0.15, 0.34, 0.26, 0.19, 0.11, 0.055]; +const RED: Color32 = Color32::from_rgb(0xff, 0x00, 0x3d); +const FILAMENT: Color32 = Color32::from_rgb(0xcc, 0x12, 0x3c); + +fn sample(values: &[f32], at: f32) -> f32 { + let index = at.clamp(0.0, (values.len() - 1) as f32); + let first = index.floor() as usize; + values[first] + (values[(first + 1).min(values.len() - 1)] - values[first]) * (index - first as f32) +} + +/// Capri's LCG (`randomSource`, `signalRandom`). +pub struct Lcg(u32); +impl Lcg { + pub fn new(seed: u32) -> Self { + Self(seed) + } + pub fn next(&mut self) -> f32 { + self.0 = self.0.wrapping_mul(1664525).wrapping_add(1013904223); + (self.0 as f64 / 4294967296.0) as f32 + } +} + +#[derive(Clone, Copy)] +struct Axis { + x: f32, + y: f32, + length: f32, +} + +fn line_between(a: Pos2, b: Pos2) -> Axis { + let (dx, dy) = (b.x - a.x, b.y - a.y); + let length = match dx.hypot(dy) { + 0.0 => 1.0, + l => l, + }; + Axis { x: dx / length, y: dy / length, length } +} + +fn along(at: Pos2, axis: Axis, forward: f32, across: f32) -> Pos2 { + Pos2::new(at.x + axis.x * forward - axis.y * across, at.y + axis.y * forward + axis.x * across) +} + +fn between(a: Pos2, b: Pos2, t: f32) -> Pos2 { + a + (b - a) * t +} + +/// What the choreography draws on: ink polygons and the (optionally clipped, tinted) sprite. +pub trait Ink { + fn fill(&mut self, points: &[Pos2], color: Color32, alpha: f32); + /// Draws Capri at `spot`; `clip` is a union of polygons, `tint` the red overlay amount. + fn capri(&mut self, arriving: bool, tint: f32, clip: Option<&[Vec]>); +} + +fn notch(edge: &mut Vec, start: Pos2, end: Pos2, side: f32, radius: f32, jaggedness: f32) { + let axis = line_between(start, end); + if axis.length < 15.0 || radius < 2.0 { + return; + } + let depth = (radius * 0.42).min(8.0) * jaggedness; + edge.extend([ + between(start, end, 0.21), + along(between(start, end, 0.25), axis, 0.0, -side * depth), + along(between(start, end, 0.34), axis, 0.0, -side * depth * 0.74), + between(start, end, 0.37), + ]); + if jaggedness > 0.65 && axis.length > 26.0 { + edge.extend([ + between(start, end, 0.61), + along(between(start, end, 0.65), axis, 0.0, -side * depth * 0.68), + along(between(start, end, 0.76), axis, 0.0, -side * depth * 0.48), + between(start, end, 0.78), + ]); + } +} + +fn ribbon(ink: &mut dyn Ink, alpha: f32, points: &[(Pos2, f32)], width: impl Fn(f32, usize) -> f32, color: Color32, jaggedness: f32) { + let mut upper: Vec = Vec::new(); + let mut lower: Vec = Vec::new(); + for (index, &(point, t)) in points.iter().enumerate() { + let left = points[index.saturating_sub(1)].0; + let right = points[(index + 1).min(points.len() - 1)].0; + let axis = line_between(left, right); + let radius = width(t, index); + let odd = index % 2 == 1; + let high = along(point, axis, 0.0, radius * if odd { 0.63 } else { 1.12 }); + let low = along(point, axis, 0.0, -radius * if odd { 1.06 } else { 0.59 }); + if jaggedness > 0.25 && index > 0 { + if odd { + let last = *upper.last().unwrap(); + notch(&mut upper, last, high, 1.0, radius, jaggedness); + } else { + let last = *lower.last().unwrap(); + notch(&mut lower, last, low, -1.0, radius, jaggedness); + } + } + upper.push(high); + lower.push(low); + } + lower.reverse(); + upper.extend(lower); + ink.fill(&upper, color, alpha); +} + +fn plain(points: &[Pos2]) -> Vec<(Pos2, f32)> { + points.iter().map(|&p| (p, 0.0)).collect() +} + +#[derive(Clone, Copy, Debug)] +pub struct Profile { + pub intensity: f32, + pub jaggedness: f32, + pub branches: f32, + pub reduced_flash: bool, + pub seed: u32, +} + +/// One end of a flight: contact point, sprite square size and the focus (bolt end, HUD anchor). +#[derive(Clone, Copy, Debug)] +pub struct Spot { + pub at: Pos2, + pub scale: f32, + pub focus: Option, + /// Sprite square in logical px (needed by `assemble`). + pub rect: Rect, +} + +pub struct Motion { + departure_scale: f32, + arrival_scale: f32, + start: Pos2, + end: Pos2, + axis: Axis, + energy: f32, + bolt_scale: f32, + profile: Profile, + points: Vec<(Pos2, f32)>, +} + +fn make_route(from: Pos2, axis: Axis, to: Pos2, amplitude: f32, profile: &Profile, bounds: Option<(f32, f32)>) -> Vec<(Pos2, f32)> { + let mut random = Lcg::new(profile.seed); + let jag = profile.jaggedness; + let mut points = vec![(from, 0.0)]; + let corners = [(0.15, -0.28, 0.25), (0.29, 0.62, 0.0), (0.4, -0.59, 0.4), (0.56, 0.76, 0.0), (0.69, 0.24, 0.52), (0.79, -0.7, 0.0), (0.9, 0.15, 0.27)]; + let mirror = if random.next() < 0.5 { -1.0 } else { 1.0 }; + let add = |points: &mut Vec<(Pos2, f32)>, mut p: Pos2, t: f32| { + if let Some((w, h)) = bounds { + p.x = p.x.min(w - 12.0).max(12.0); + p.y = p.y.min(h - 12.0).max(12.0); + } + points.push((p, t)); + }; + for (base, offset, minimum) in corners { + let t = base + (random.next() - 0.5) * (0.025 + jag * 0.035); + let bend = offset * amplitude * mirror * (0.73 + random.next() * 0.45); + let crack = (0.18 + random.next() * 0.16) * amplitude * jag; + if jag < minimum { + continue; + } + let corner = along(from, axis, t * axis.length, bend); + if jag > 0.55 && crack > 2.0 { + let (previous, pt) = *points.last().unwrap(); + let side = bend.signum(); + add(&mut points, along(between(previous, corner, 0.58), axis, 0.0, side * crack), pt + (t - pt) * 0.58); + add(&mut points, along(between(previous, corner, 0.76), axis, 0.0, -side * crack * 0.44), pt + (t - pt) * 0.76); + } + add(&mut points, corner, t); + } + points.push((to, 1.0)); + points +} + +fn point_at(points: &[(Pos2, f32)], t: f32) -> (Pos2, f32) { + let index = points.iter().position(|p| p.1 >= t).unwrap_or(0).max(1); + let (a, at) = points[index - 1]; + let (b, bt) = points[index]; + let u = if bt == at { 0.0 } else { (t - at) / (bt - at) }; + (a + (b - a) * u, t) +} + +fn drop(ink: &mut dyn Ink, alpha: f32, at: Pos2, radius: f32, color: Color32) { + let (s, c) = (-0.35f32).sin_cos(); + let pts: Vec = (0..16) + .map(|i| { + let a = i as f32 / 16.0 * std::f32::consts::TAU; + let (x, y) = (radius * a.cos(), radius * 0.83 * a.sin()); + Pos2::new(at.x + x * c - y * s, at.y + x * s + y * c) + }) + .collect(); + ink.fill(&pts, color, alpha); +} + +impl Motion { + pub fn new(from: &Spot, to: &Spot, profile: Profile, bounds: Option<(f32, f32)>) -> Self { + let scale = from.scale.max(to.scale); + let start = from.focus.unwrap_or(Pos2::new(from.at.x, from.at.y - from.scale * 0.52)); + let end = to.focus.unwrap_or(Pos2::new(to.at.x, to.at.y - to.scale * 0.52)); + let axis = line_between(start, end); + let travel = (axis.length / (2.0 * scale)).min(1.0); + let energy = 0.38 + profile.intensity * 0.88; + let amplitude = (scale * 0.53).min(axis.length * 0.31) * travel * (0.18 + profile.jaggedness * 1.13); + let points = make_route(start, axis, end, amplitude, &profile, bounds); + Self { departure_scale: from.scale, arrival_scale: to.scale, start, end, axis, energy, bolt_scale: scale * travel * energy, profile, points } + } + + fn branches(&self, ink: &mut dyn Ink, head: f32, tail: f32, scale: f32) { + let Profile { branches, intensity, jaggedness, reduced_flash, seed } = self.profile; + let count = (branches * if reduced_flash { 2.0 } else { 6.0 }).ceil() as usize; + let mut random = Lcg::new(seed ^ 0xf27a64b5); + for index in 0..count { + let t = 0.12 + ((index as f32 + 0.14 + random.next() * 0.68) / count as f32) * 0.8; + let side = if index % 2 == 1 { 1.0 } else { -1.0 }; + let variation = 0.78 + random.next() * 0.44; + if t <= tail || t >= head { + continue; + } + let origin = point_at(&self.points, t).0; + let axis = line_between(point_at(&self.points, t - 0.055).0, point_at(&self.points, t + 0.055).0); + let growth = ((t - tail) / 0.07).min((head - t) / 0.08).min(1.0); + let reach = scale * (0.13 + 0.25 * branches) * growth * variation; + if reach < 2.0 { + continue; + } + let fork = |f: f32, a: f32| along(origin, axis, reach * f, side * reach * a); + let stem = [origin, fork(-0.16, 0.22), fork(-0.12, 0.4), fork(-0.49, 0.48), fork(-0.39, 0.68), fork(-0.86, 0.88), fork(-1.15, 1.04)]; + let thickness = growth * (0.48 + intensity * 0.66) * if reduced_flash { 0.65 } else { 1.0 }; + const W: [f32; 7] = [1.45, 2.05, 1.65, 1.2, 0.8, 0.55, 0.12]; + ribbon(ink, 1.0, &plain(&stem), |_, i| W[i] * thickness, FILAMENT, 0.0); + if !reduced_flash && branches > 0.5 && jaggedness > 0.38 && index % 2 == 0 { + let tip = fork(-0.35, 1.19); + const T: [f32; 4] = [0.8, 0.56, 0.35, 0.12]; + ribbon(ink, 1.0, &plain(&[stem[3], fork(-0.23, 0.63), fork(-0.27, 0.86), tip]), |_, i| T[i] * growth, RED, 0.0); + drop(ink, 1.0, along(tip, axis, reach * 0.06, side * reach * 0.08), 1.25 * growth, RED); + } + } + } + + fn bolt(&self, ink: &mut dyn Ink, head: f32, tail: f32, scale: f32) { + if head <= tail { + return; + } + let Profile { jaggedness, reduced_flash, .. } = self.profile; + let travelled = head - tail; + let shoulder = head - travelled * 0.17; + let mut segment = vec![point_at(&self.points, tail)]; + segment.extend(self.points.iter().filter(|p| p.1 > tail && p.1 < shoulder).copied()); + segment.push(point_at(&self.points, shoulder)); + segment.push(point_at(&self.points, head)); + let radius = (scale * if reduced_flash { 0.065 } else { 0.125 }).max(1.0); + let last = segment.len() - 1; + let width = |t: f32, index: usize| { + if index == 0 || index == last { + return 0.55; + } + let stagger = if index % 2 == 1 { 0.19 } else { -0.16 }; + radius * (0.46 + 0.47 * (t - tail) / travelled + stagger * jaggedness) + }; + if travelled > 0.1 { + self.branches(ink, head, tail, scale); + } + ribbon(ink, 1.0, &segment, width, RED, if reduced_flash { 0.0 } else { jaggedness }); + } + + fn brk(&self, ink: &mut dyn Ink, scale: f32, strength: f32, spread: f32) { + if strength <= 0.0 { + return; + } + let Profile { branches, intensity, jaggedness, reduced_flash, seed } = self.profile; + let (focus, axis) = (self.start, self.axis); + let mut random = Lcg::new(seed); + let shards = (if reduced_flash { 2.0 + intensity * 3.0 } else { 4.0 + intensity * 10.0 }).round() as usize; + let extent = scale * spread; + for index in 0..shards { + let direction = index as f32 * 2.39996 + random.next() * (0.34 + jaggedness * 0.48); + let radial = Axis { x: direction.cos(), y: direction.sin(), length: 1.0 }; + let arm = (0.13 + random.next() * 0.85) * extent; + let start = along(focus, axis, radial.x * arm * 0.7, radial.y * arm); + let thickness = (scale * (0.004 + random.next() * 0.014)).max(1.0); + let length = scale * (0.026 + random.next() * 0.077); + if index % 3 == 0 { + drop(ink, strength, start, thickness * 1.15, RED); + continue; + } + let pts = [along(start, radial, -length * 0.48, -thickness), along(start, radial, length, 0.0), along(start, radial, -length * 0.1, thickness), along(start, radial, length * 0.16, 0.0)]; + ink.fill(&pts, RED, strength); + } + let lash = [ + along(focus, axis, -extent * 0.95, -extent * 1.13), + along(focus, axis, -extent * 0.52, -extent * 0.33), + along(focus, axis, -extent * 0.64, -extent * 0.16), + along(focus, axis, extent * 0.25, extent * 0.22), + along(focus, axis, extent * 0.02, extent * 0.39), + along(focus, axis, extent * 0.89, extent * 1.16), + ]; + let peak = scale * if reduced_flash { 0.023 } else { 0.059 }; + let w = [0.2, peak, peak * 0.42, peak, peak * 0.67, 0.2]; + ribbon(ink, strength, &plain(&lash), |_, i| w[i], RED, if reduced_flash { 0.0 } else { jaggedness }); + if !reduced_flash && branches > 0.0 { + let echo = [lash[1], along(focus, axis, -extent * 0.18, -extent * 0.64), along(focus, axis, extent * 0.16, -extent * 0.53), along(focus, axis, extent * 0.95, -extent * 1.15)]; + const E: [f32; 4] = [1.75, 1.4, 0.9, 0.16]; + ribbon(ink, strength, &plain(&echo), |_, i| E[i] * branches, FILAMENT, 0.0); + } + } + + fn retract(&self, ink: &mut dyn Ink, scale: f32, age: f32) { + let cuts: [&[f32]; 5] = [ + &[if self.profile.reduced_flash { 0.61 } else { 0.49 }, 0.86], + &[0.73, 0.65, 0.57, 0.66], + &[0.84, 0.45, 0.71, 0.76], + &[0.93, 0.25, 0.81, 0.84], + &[0.977, 0.14], + ]; + let i = age.floor() as usize; + if i >= cuts.len() { + return; + } + let from = cuts[i]; + let (to_tail, to_width) = cuts.get(i + 1).map_or((1.0, 0.0), |c| (c[0], c[1])); + let f = age.fract(); + let tail = from[0] + (to_tail - from[0]) * f; + let width = from[1] + (to_width - from[1]) * f; + self.bolt(ink, 1.0, tail, scale * width); + if from.len() == 4 { + self.bolt(ink, from[3], from[2], scale * width * 0.65); + } + } + + fn reveal(&self, ink: &mut dyn Ink, amount: f32, tint: f32) { + if amount <= 0.0 { + return; + } + if amount >= 1.0 { + return ink.capri(false, tint, None); + } + let rows = [(-0.54, -0.28, 0.49), (-0.32, -0.65, 0.77), (-0.14, -0.89, 0.5), (0.03, -0.48, 0.73), (0.18, -0.75, 0.44), (0.29, -0.4, 0.58), (0.56, -0.22, 0.31)]; + let (focus, scale) = (self.start, self.departure_scale); + let point = |y: f32, x: f32| Pos2::new(focus.x + scale * amount * x, focus.y + scale * y * (0.42 + amount * 0.58)); + let mut poly: Vec = rows.iter().map(|&(y, x, _)| point(y, x)).collect(); + poly.extend(rows.iter().rev().map(|&(y, _, x)| point(y, x))); + ink.capri(false, tint, Some(&[poly])); + } + + fn assemble(&self, ink: &mut dyn Ink, to: &Spot, age: f32) { + if age == 0.0 { + return; + } + if age >= 8.0 { + return ink.capri(true, 0.0, None); + } + let Profile { intensity, jaggedness, reduced_flash, .. } = self.profile; + let area = to.rect; + let apertures = [0.0, 0.21, 0.42, 0.66, 0.85, 1.0]; + let bands = [(0.0, 0.38), (0.35, 0.61), (0.58, 0.83), (0.8, 1.0)]; + let mut plates = Vec::new(); + let mut seams = Vec::new(); + for (index, (start, end)) in bands.into_iter().enumerate() { + let progress = sample(&apertures, age - index as f32); + if progress == 0.0 { + continue; + } + let side = if index % 2 == 1 { 1.0 } else { -1.0 }; + let center = area.min.x + area.width() * (0.5 + side * 0.13 * (1.0 - progress)); + let left = center + (area.min.x - center) * progress; + let right = center + (area.max.x - center) * progress; + let top = area.min.y + area.height() * start; + let height = area.height() * (end - start); + let bottom = top + height; + let tooth = (right - left) * (0.065 + jaggedness * 0.15) * (1.0 - progress); + let plate = vec![ + Pos2::new(left + tooth, top), + Pos2::new(right, top), + Pos2::new(right - tooth, top + height * 0.29), + Pos2::new(right - tooth, top + height * 0.5), + Pos2::new(right, top + height * 0.64), + Pos2::new(right - tooth, bottom), + Pos2::new(left, bottom), + Pos2::new(left + tooth, top + height * 0.59), + Pos2::new(left + tooth, top + height * 0.32), + Pos2::new(left, top + height * 0.2), + ]; + if progress < 1.0 { + let edge: Vec = if side > 0.0 { plate[1..6].to_vec() } else { plate[6..].iter().copied().chain([plate[0]]).collect() }; + let width = area.width().min(area.height()) * (1.0 - progress) * (0.46 + intensity * 0.72) * if reduced_flash { 0.009 } else { 0.018 }; + seams.push((edge, width)); + } + plates.push(plate); + } + ink.capri(true, 0.0, Some(&plates)); + for (edge, width) in seams { + let last = edge.len() - 1; + ribbon(ink, 1.0, &plain(&edge), |_, i| if i == 0 || i == last { 0.2 } else { width }, RED, 0.0); + } + } + + fn strike(&self, ink: &mut dyn Ink, scale: f32, age: f32) { + let Profile { branches, jaggedness, reduced_flash, .. } = self.profile; + let reach = if age < STRIKE_REACH.len() as f32 { scale * sample(&[STRIKE_REACH.as_slice(), &[0.0]].concat(), age) } else { 0.0 }; + if reach == 0.0 { + return; + } + let (focus, axis) = (self.end, self.axis); + let slash = [ + along(focus, axis, -reach * 0.73, -reach), + along(focus, axis, -reach * 0.28, -reach * 0.43), + along(focus, axis, reach * 0.12, -reach * 0.45), + focus, + along(focus, axis, reach * 0.28, reach * 0.42), + along(focus, axis, reach * 0.7, reach * 0.86), + ]; + let width = reach * if reduced_flash { 0.04 } else { 0.09 }; + let w = [0.15, width, width * 0.68, width, width * 0.62, 0.15]; + ribbon(ink, 1.0, &plain(&slash), |_, i| w[i], RED, if reduced_flash { 0.0 } else { jaggedness }); + if branches > 0.5 && age < 4.0 { + let side = reach * branches; + let echo = [slash[1], along(focus, axis, side * 0.34, -side * 0.55), along(focus, axis, side * 0.28, -side * 0.74), along(focus, axis, side * 0.69, -side * 1.02)]; + const E: [f32; 4] = [0.8, 1.4, 0.72, 0.1]; + let k = if reduced_flash { 0.5 } else { 1.0 }; + ribbon(ink, 1.0, &plain(&echo), |_, i| E[i] * k, FILAMENT, 0.0); + } + if !reduced_flash && age > 0.0 { + let chip = along(focus, axis, reach * 0.72, -reach * 0.69); + let size = reach * 0.15; + ink.fill(&[along(chip, axis, -size, 0.0), along(chip, axis, size, -size * 0.26), along(chip, axis, size * 0.55, size * 0.27)], RED, 1.0); + } + } + + /// Draws frame `frame` (fractional, 24 fps). Returns false once the flight is over. + pub fn draw(&self, ink: &mut dyn Ink, frame: f32, to: &Spot) -> bool { + let time = frame.max(0.0); + if time >= SETTLE_FRAME { + ink.capri(true, 0.0, None); + return false; + } + let p = self.profile; + if time < TRANSIT_START { + let reveal = sample(&[1.0, 1.0, 1.0, 0.74, 0.37, 0.0], time); + let strength = sample(&[0.0, 0.25, 0.37, 0.7, 0.87, 1.0, 0.0], time); + let tint = sample(&[0.0, 0.0, 0.13, 0.57, 0.93, 1.0], time) * if p.reduced_flash { 0.5 } else { 1.0 }; + self.reveal(ink, reveal, tint); + self.brk(ink, self.departure_scale * self.energy, strength, 0.49 - time * 0.045); + if time >= TRANSIT_START - 2.0 { + self.bolt(ink, sample(&[0.0, 0.09, HEAD_POSITIONS[0]], time - TRANSIT_START + 2.0), 0.0, self.bolt_scale); + } + } else if time < ARRIVAL_START { + let head = sample(&HEAD_POSITIONS, time - TRANSIT_START); + let tail = (head - if p.reduced_flash { 0.44 } else { 0.61 }).max(0.0); + self.bolt(ink, head, tail, self.bolt_scale); + } else { + let age = time - ARRIVAL_START; + self.retract(ink, self.bolt_scale, age); + self.assemble(ink, to, age); + self.strike(ink, (self.arrival_scale * self.energy).min(self.bolt_scale * 2.0), age); + } + true + } +} + +/// Drag lightning drawn as Capri's six-stroke stack. +/// `look` is (intensity, chaos) in percent. +pub fn draw_tether(painter: &Painter, from: Pos2, to: Pos2, look: (f32, f32), seed: u32, now_ms: f64, reduced: bool) { + let (intensity, chaos) = look; + let noise = |i: u32| -> f32 { + let mixed = (seed ^ i.wrapping_mul(0x9e3779b1)).wrapping_mul(0x85ebca6b); + ((mixed ^ (mixed >> 13)) as f64 / 4294967296.0) as f32 + }; + let mix = |a: f32, b: f32, t: f32| a + (b - a) * t; + let (dx, dy) = (to.x - from.x, to.y - from.y); + let distance = dx.hypot(dy); + if !distance.is_finite() || distance < 1.0 || intensity <= 0.0 { + return; + } + let density = (intensity / 100.0).clamp(0.0, 1.0); + let disorder = (chaos / 100.0).clamp(0.0, 1.0); + let time = if reduced { 0.0 } else { (now_ms / 1000.0) as f32 }; + let pieces = (distance / 24.0).ceil().clamp(4.0, 42.0) as u32; + let spread = (distance * 0.14).min(19.0) * mix(0.15, 1.0, disorder); + let (nx, ny) = (-dy / distance, dx / distance); + let point = |t: f32, o: f32| Pos2::new(from.x + dx * t + nx * o, from.y + dy * t + ny * o); + let mut nodes = vec![from]; + for i in 1..pieces { + let t = i as f32 / pieces as f32; + let wobble = if reduced { 0.0 } else { 0.23 * (time * 11.0 + i as f32 * 1.92).sin() }; + nodes.push(point(t, (noise(i) * 1.6 - 0.8 + wobble) * spread * (t * std::f32::consts::PI).sin())); + } + nodes.push(to); + let spine = |t: f32, o: f32| { + let i = ((t * pieces as f32).floor() as usize).min(pieces as usize - 1); + let phase = t * pieces as f32 - i as f32; + Pos2::new(mix(nodes[i].x, nodes[i + 1].x, phase) + nx * o, mix(nodes[i].y, nodes[i + 1].y, phase) + ny * o) + }; + let mut branches = Vec::new(); + let branch_count = (((1.0 + distance / 115.0) * density * if reduced { 1.0 } else { 2.0 }).ceil() as u32).min(19); + for i in 0..branch_count { + let o = 100 + i * 7; + let t = mix(0.05, 0.94, noise(o)); + let side = if noise(o + 1) < 0.5 { -1.0 } else { 1.0 }; + let reach = ((1.0 - t) * 0.8).min(mix(8.0, 37.0, noise(o + 2)) / distance); + let width = mix(3.0, 20.0, disorder * noise(o + 3)); + branches.push(vec![spine(t, 0.0), spine(t + reach * 0.38, width * side * 0.7), spine(t + reach * 0.65, width * side * 0.53), spine(t + reach, width * side)]); + } + let (mut embers, mut sparks) = (Vec::new(), Vec::new()); + let spark_count = (((6.0 + distance / 12.0) * density * if reduced { 0.3 } else { 1.0 }).ceil() as u32).min(72); + for i in 0..spark_count { + let o = 500 + i * 11; + let t = mix(0.045, 0.95, noise(o)); + let side = if noise(o + 1) < 0.5 { -1.0 } else { 1.0 }; + let duration = mix(0.19, 0.68, noise(o + 2)); + let life = (time / duration + noise(o + 3)) % 1.0; + let drift = mix(4.0, 33.0, disorder * noise(o + 4)); + let tip = spine((t + life * (11.0 / distance).min(0.04)).min(1.0), (0.15 + life * 0.85) * drift * side); + let length = (if reduced { 1.5 } else { 0.7 + (life * std::f32::consts::PI).sin() * 3.8 }) * (1.0 - life * 0.55); + let end = Pos2::new(tip.x - dx / distance * length - nx * side * length * 0.42, tip.y - dy / distance * length - ny * side * length * 0.42); + if i % 4 == 0 { sparks.push(vec![tip, end]) } else { embers.push(vec![tip, end]) } + } + let line = |pts: &[Pos2], color: Color32, width: f32, opacity: f32| { + painter.add(Shape::line(pts.to_vec(), Stroke::new(width, color.gamma_multiply(opacity)))); + }; + let bolt = |color, width, opacity| line(&nodes, color, width, opacity); + bolt(Color32::from_rgb(0xff, 0x16, 0x4b), 8.0, 0.13); + bolt(Color32::from_rgb(0xfa, 0x17, 0x4a), 4.0, 0.29); + for b in &branches { + line(b, Color32::from_rgb(0xff, 0x19, 0x46), 1.0, 0.64); + } + bolt(Color32::from_rgb(0xff, 0x3e, 0x5c), 1.45, 0.98); + for e in &embers { + line(e, Color32::from_rgb(0xfa, 0x23, 0x4b), 1.5, 0.63); + } + for s in &sparks { + line(s, Color32::from_rgb(0xff, 0x75, 0x87), 1.7, 0.95); + } +} + +/// Paints ink polygons directly; used by the overlay. +pub struct PainterInk<'a, F: FnMut(&Painter, bool, f32, Option<&[Vec]>)> { + pub painter: &'a Painter, + pub capri: F, +} + +impl]>)> Ink for PainterInk<'_, F> { + fn fill(&mut self, points: &[Pos2], color: Color32, alpha: f32) { + geom::fill(self.painter, points, color.gamma_multiply(alpha.clamp(0.0, 1.0))); + } + fn capri(&mut self, arriving: bool, tint: f32, clip: Option<&[Vec]>) { + (self.capri)(self.painter, arriving, tint, clip); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Default)] + struct Count { + fills: usize, + capri: Vec<(bool, Option)>, + } + impl Ink for Count { + fn fill(&mut self, points: &[Pos2], _: Color32, _: f32) { + assert!(points.iter().all(|p| p.x.is_finite() && p.y.is_finite())); + self.fills += 1; + } + fn capri(&mut self, arriving: bool, _: f32, clip: Option<&[Vec]>) { + self.capri.push((arriving, clip.map(|c| c.len()))); + } + } + + fn spot(x: f32, y: f32) -> Spot { + let scale = 200.0; + Spot { at: Pos2::new(x, y), scale, focus: None, rect: Rect::from_min_size(Pos2::new(x - 100.0, y - 186.0), [scale, scale].into()) } + } + + #[test] + fn lcg_matches_capri() { + // signalRandom(2078)() in Capri: (2078*1664525+1013904223) mod 2^32 / 2^32. + let expected = ((2078u64 * 1664525 + 1013904223) % (1 << 32)) as f64 / 4294967296.0; + assert!((Lcg::new(2078).next() as f64 - expected).abs() < 1e-6); + } + + #[test] + fn choreography_phases() { + let (from, to) = (spot(300.0, 800.0), spot(1400.0, 500.0)); + let profile = Profile { intensity: 0.75, jaggedness: 0.78, branches: 0.75, reduced_flash: false, seed: 42 }; + let motion = Motion::new(&from, &to, profile, Some((1920.0, 1200.0))); + assert!(motion.points.windows(2).all(|w| w[0].1 <= w[1].1), "route times increase"); + let mut ink = Count::default(); + assert!(motion.draw(&mut ink, 0.0, &to)); + assert_eq!(ink.capri, [(false, None)], "departure starts with the full sprite"); + let mut ink = Count::default(); + motion.draw(&mut ink, 10.0, &to); + assert!(ink.capri.is_empty() && ink.fills > 0, "transit draws only the bolt"); + let mut ink = Count::default(); + motion.draw(&mut ink, 17.0, &to); + assert_eq!(ink.capri, [(true, Some(2))], "arrival assembles in bands"); + let mut ink = Count::default(); + assert!(!motion.draw(&mut ink, 27.0, &to)); + } +}