| 1 | //! Fusion BezierSpline, PolyPath, LUTBezier, and Gradient animation data & evaluators. |
| 2 | |
| 3 | use crate::lua_value::{LuaKey, LuaTable, LuaValue}; |
| 4 | |
| 5 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 6 | pub enum HandleMode { |
| 7 | #[default] |
| 8 | Free, |
| 9 | Aligned, |
| 10 | Vector, |
| 11 | Auto, |
| 12 | } |
| 13 | |
| 14 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 15 | pub struct KeyFlags { |
| 16 | pub linear: bool, |
| 17 | pub step_in: bool, |
| 18 | pub step_out: bool, |
| 19 | pub loop_after: bool, |
| 20 | pub loop_rel: bool, |
| 21 | pub ping_pong: bool, |
| 22 | pub locked_y: bool, |
| 23 | } |
| 24 | |
| 25 | #[derive(Clone, Debug, PartialEq)] |
| 26 | pub struct Keyframe { |
| 27 | pub time: f64, |
| 28 | pub value: f64, |
| 29 | /// Left tangent handle in absolute `(time, value)` coordinates (Fusion convention). |
| 30 | pub lh: Option<[f64; 2]>, |
| 31 | /// Right tangent handle in absolute `(time, value)` coordinates (Fusion convention). |
| 32 | pub rh: Option<[f64; 2]>, |
| 33 | pub flags: KeyFlags, |
| 34 | pub handle_mode: HandleMode, |
| 35 | } |
| 36 | |
| 37 | impl Keyframe { |
| 38 | pub fn new(time: f64, value: f64) -> Self { |
| 39 | Self { |
| 40 | time, |
| 41 | value, |
| 42 | lh: None, |
| 43 | rh: None, |
| 44 | flags: KeyFlags { linear: true, ..Default::default() }, |
| 45 | handle_mode: HandleMode::Aligned, |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | #[derive(Clone, Debug, PartialEq)] |
| 51 | pub struct BezierSpline { |
| 52 | pub name: String, |
| 53 | pub color: [u8; 3], |
| 54 | pub keyframes: Vec<Keyframe>, |
| 55 | } |
| 56 | |
| 57 | impl BezierSpline { |
| 58 | pub fn from_lua(name: String, table: &LuaTable) -> Self { |
| 59 | let color = table |
| 60 | .get_table("SplineColor") |
| 61 | .map(|c| { |
| 62 | [ |
| 63 | c.get_f64("Red").unwrap_or(200.0) as u8, |
| 64 | c.get_f64("Green").unwrap_or(140.0) as u8, |
| 65 | c.get_f64("Blue").unwrap_or(255.0) as u8, |
| 66 | ] |
| 67 | }) |
| 68 | .unwrap_or([210, 140, 255]); |
| 69 | |
| 70 | let mut keyframes = Vec::new(); |
| 71 | // BezierSpline uses `KeyFrames`; LUTBezier uses `KeyColorSplines[0]` |
| 72 | let kf_table = table.get_table("KeyFrames").or_else(|| { |
| 73 | table |
| 74 | .get_table("KeyColorSplines") |
| 75 | .and_then(|kc| kc.get_index(0)) |
| 76 | .and_then(LuaValue::as_table) |
| 77 | }); |
| 78 | |
| 79 | if let Some(kfs) = kf_table { |
| 80 | for (k, v) in &kfs.entries { |
| 81 | let time = match k { |
| 82 | LuaKey::Index(i) => *i as f64, |
| 83 | LuaKey::Number(n) => *n, |
| 84 | _ => continue, |
| 85 | }; |
| 86 | if !time.is_finite() { |
| 87 | continue; |
| 88 | } |
| 89 | let Some(kt) = v.as_table() else { continue }; |
| 90 | let value = kt.get_index(1).and_then(LuaValue::as_f64).unwrap_or(0.0); |
| 91 | if !value.is_finite() { |
| 92 | continue; |
| 93 | } |
| 94 | let finite_vec2 = |t: &LuaTable| { |
| 95 | read_vec2(t).filter(|[x, y]| x.is_finite() && y.is_finite()) |
| 96 | }; |
| 97 | let lh = kt.get_table("LH").and_then(finite_vec2); |
| 98 | let rh = kt.get_table("RH").and_then(finite_vec2); |
| 99 | let mut flags = KeyFlags::default(); |
| 100 | if let Some(ft) = kt.get_table("Flags") { |
| 101 | flags.linear = ft.get_bool("Linear").unwrap_or(false); |
| 102 | flags.step_in = ft.get_bool("StepIn").unwrap_or(false); |
| 103 | flags.step_out = ft.get_bool("StepOut").unwrap_or(false); |
| 104 | flags.loop_after = ft.get_bool("Loop").unwrap_or(false); |
| 105 | flags.loop_rel = ft.get_bool("LoopRel").unwrap_or(false); |
| 106 | flags.ping_pong = ft.get_bool("PingPong").unwrap_or(false); |
| 107 | flags.locked_y = ft.get_bool("LockedY").unwrap_or(false); |
| 108 | } |
| 109 | let handle_mode = if flags.linear { |
| 110 | HandleMode::Vector |
| 111 | } else { |
| 112 | HandleMode::Free |
| 113 | }; |
| 114 | keyframes.push(Keyframe { |
| 115 | time, |
| 116 | value, |
| 117 | lh, |
| 118 | rh, |
| 119 | flags, |
| 120 | handle_mode, |
| 121 | }); |
| 122 | } |
| 123 | } |
| 124 | keyframes.sort_by(|a, b| a.time.total_cmp(&b.time)); |
| 125 | Self { name, color, keyframes } |
| 126 | } |
| 127 | |
| 128 | pub fn sort(&mut self) { |
| 129 | self.keyframes.sort_by(|a, b| a.time.total_cmp(&b.time)); |
| 130 | } |
| 131 | |
| 132 | /// Evaluates the spline at arbitrary continuous time `t`. |
| 133 | pub fn eval(&self, t: f64) -> f64 { |
| 134 | let kfs = &self.keyframes; |
| 135 | if kfs.is_empty() { |
| 136 | return 0.0; |
| 137 | } |
| 138 | if kfs.len() == 1 { |
| 139 | return kfs[0].value; |
| 140 | } |
| 141 | let first = &kfs[0]; |
| 142 | let last = &kfs[kfs.len() - 1]; |
| 143 | |
| 144 | // Fusion never loops backwards before the first keyframe (`Loop` / `LoopRel` / `PingPong` all clamp). |
| 145 | if t.is_nan() || t <= first.time { |
| 146 | return first.value; |
| 147 | } |
| 148 | |
| 149 | // In Fusion, `Loop` / `LoopRel` requires at least two loop-flagged keyframes (`loop_start < loop_end`). |
| 150 | // The loop repeats `[loop_start, loop_end]` for `t >= loop_end.time` up to the next keyframe (if any). |
| 151 | let is_loop_key = |k: &Keyframe| k.flags.loop_after || k.flags.loop_rel; |
| 152 | let loop_pair = t.is_finite().then(|| { |
| 153 | kfs.iter().position(is_loop_key).and_then(|s| { |
| 154 | let e = kfs.iter().rposition(is_loop_key)?; |
| 155 | (s < e).then_some((s, e)) |
| 156 | }) |
| 157 | }).flatten(); |
| 158 | |
| 159 | let mut t = t; |
| 160 | let mut value_offset = 0.0_f64; |
| 161 | if let Some((ls_idx, le_idx)) = loop_pair { |
| 162 | let ls = &kfs[ls_idx]; |
| 163 | let le = &kfs[le_idx]; |
| 164 | let next_after_time = kfs.get(le_idx + 1).map(|k| k.time); |
| 165 | let span = le.time - ls.time; |
| 166 | if span > 1e-9 && t >= le.time && next_after_time.is_none_or(|nt| t < nt) { |
| 167 | let offset = t - ls.time; |
| 168 | let cycle = (offset / span).floor(); |
| 169 | let rem = offset - cycle * span; |
| 170 | t = ls.time + rem; |
| 171 | if ls.flags.loop_rel || le.flags.loop_rel { |
| 172 | value_offset = cycle * (le.value - ls.value); |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | if t <= first.time { |
| 178 | return first.value + value_offset; |
| 179 | } |
| 180 | if t >= last.time { |
| 181 | return last.value + value_offset; |
| 182 | } |
| 183 | |
| 184 | // Binary search segment [k0, k1] with k0.time <= t <= k1.time |
| 185 | let idx = kfs.partition_point(|k| k.time <= t).saturating_sub(1); |
| 186 | let k0 = &kfs[idx]; |
| 187 | let k1 = &kfs[(idx + 1).min(kfs.len() - 1)]; |
| 188 | eval_segment(k0, k1, t) + value_offset |
| 189 | } |
| 190 | |
| 191 | /// Applies Fusion `HueCurves` cyclic `[0..6]` endpoint continuity when tangent handles are omitted. |
| 192 | pub fn apply_hue_curves_cyclic_ends(&mut self) { |
| 193 | let kfs = &mut self.keyframes; |
| 194 | if kfs.len() < 2 { |
| 195 | return; |
| 196 | } |
| 197 | let first_t = kfs[0].time; |
| 198 | let last_t = kfs[kfs.len() - 1].time; |
| 199 | if (first_t - 0.0).abs() > 1e-6 || (last_t - 6.0).abs() > 1e-6 { |
| 200 | return; |
| 201 | } |
| 202 | let n = kfs.len(); |
| 203 | let first_v = kfs[0].value; |
| 204 | let last = &kfs[n - 1]; |
| 205 | if last.flags.linear || kfs[0].flags.step_out || last.flags.step_in { |
| 206 | if last.flags.linear && (last.value - first_v).abs() > 1e-9 { |
| 207 | kfs[n - 1].value = first_v; |
| 208 | } |
| 209 | return; |
| 210 | } |
| 211 | if kfs[0].rh.is_some() || last.lh.is_some() { |
| 212 | return; |
| 213 | } |
| 214 | let dt0 = kfs[1].time - first_t; |
| 215 | let dv0 = kfs[1].value - first_v; |
| 216 | let rh0 = [first_t + dt0 / 3.0, first_v + dv0 / 3.0]; |
| 217 | // Preserve the 2-keyframe initial chord slope in `RH` before snapping `last.value`. |
| 218 | if n == 2 { |
| 219 | kfs[0].rh = Some(rh0); |
| 220 | } |
| 221 | let dt_last = last_t - kfs[n - 2].time; |
| 222 | let dx_last = dt_last / 3.0; |
| 223 | let slope0 = if dt0.abs() > 1e-12 { dv0 / dt0 } else { 0.0 }; |
| 224 | kfs[n - 1].value = first_v; |
| 225 | kfs[n - 1].lh = Some([ |
| 226 | last_t - dx_last, |
| 227 | first_v - slope0 * dx_last, |
| 228 | ]); |
| 229 | } |
| 230 | |
| 231 | /// Returns the effective cubic Bezier control points `[p0, p1, p2, p3]` for segment `idx -> idx+1`. |
| 232 | pub fn segment_points(&self, idx: usize) -> Option<[[f64; 2]; 4]> { |
| 233 | let k0 = self.keyframes.get(idx)?; |
| 234 | let k1 = self.keyframes.get(idx + 1)?; |
| 235 | Some(segment_control_points(k0, k1)) |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | pub fn segment_control_points(k0: &Keyframe, k1: &Keyframe) -> [[f64; 2]; 4] { |
| 240 | let p0 = [k0.time, k0.value]; |
| 241 | let p3 = [k1.time, k1.value]; |
| 242 | let dt = k1.time - k0.time; |
| 243 | let dv = k1.value - k0.value; |
| 244 | // Keys can be transiently unsorted mid-drag; `f64::clamp` would panic on `lo > hi` or `NaN`. |
| 245 | let (t_lo, t_hi) = (k0.time.min(k1.time), k0.time.max(k1.time)); |
| 246 | let clamp_t = |x: f64| if t_lo <= t_hi { x.clamp(t_lo, t_hi) } else { x }; |
| 247 | |
| 248 | let p1 = if k1.flags.linear && k0.rh.is_none() { |
| 249 | [k0.time + dt / 3.0, k0.value + dv / 3.0] |
| 250 | } else if let Some(rh) = k0.rh { |
| 251 | [clamp_t(rh[0]), rh[1]] |
| 252 | } else { |
| 253 | [k0.time + dt / 3.0, k0.value + dv / 3.0] |
| 254 | }; |
| 255 | |
| 256 | let p2 = if k1.flags.linear && k1.lh.is_none() { |
| 257 | [k1.time - dt / 3.0, k1.value - dv / 3.0] |
| 258 | } else if let Some(lh) = k1.lh { |
| 259 | [clamp_t(lh[0]), lh[1]] |
| 260 | } else { |
| 261 | [k1.time - dt / 3.0, k1.value - dv / 3.0] |
| 262 | }; |
| 263 | |
| 264 | [p0, p1, p2, p3] |
| 265 | } |
| 266 | |
| 267 | fn eval_segment(k0: &Keyframe, k1: &Keyframe, t: f64) -> f64 { |
| 268 | let dt = k1.time - k0.time; |
| 269 | if dt.abs() < 1e-12 { |
| 270 | return k1.value; |
| 271 | } |
| 272 | if k0.flags.step_out { |
| 273 | return k1.value; |
| 274 | } |
| 275 | if k1.flags.step_in { |
| 276 | return k0.value; |
| 277 | } |
| 278 | if k1.flags.linear && k0.rh.is_none() && k1.lh.is_none() { |
| 279 | let u = (t - k0.time) / dt; |
| 280 | return k0.value + (k1.value - k0.value) * u; |
| 281 | } |
| 282 | |
| 283 | let [p0, p1, p2, p3] = segment_control_points(k0, k1); |
| 284 | |
| 285 | // Solve cubic X(u) = t for u in [0, 1] using Newton-Raphson + bisection guard. |
| 286 | let mut lo = 0.0_f64; |
| 287 | let mut hi = 1.0_f64; |
| 288 | let mut u = ((t - p0[0]) / dt).clamp(0.0, 1.0); |
| 289 | for _ in 0..12 { |
| 290 | let x = cubic(p0[0], p1[0], p2[0], p3[0], u); |
| 291 | let err = x - t; |
| 292 | if err.abs() < 1e-7 { |
| 293 | break; |
| 294 | } |
| 295 | if err < 0.0 { |
| 296 | lo = u; |
| 297 | } else { |
| 298 | hi = u; |
| 299 | } |
| 300 | let dx = cubic_deriv(p0[0], p1[0], p2[0], p3[0], u); |
| 301 | let next = if dx.abs() > 1e-9 { u - err / dx } else { 0.5 * (lo + hi) }; |
| 302 | u = if next > lo && next < hi { next } else { 0.5 * (lo + hi) }; |
| 303 | } |
| 304 | cubic(p0[1], p1[1], p2[1], p3[1], u) |
| 305 | } |
| 306 | |
| 307 | #[inline] |
| 308 | pub fn cubic(a: f64, b: f64, c: f64, d: f64, u: f64) -> f64 { |
| 309 | let inv = 1.0 - u; |
| 310 | inv * inv * inv * a + 3.0 * inv * inv * u * b + 3.0 * inv * u * u * c + u * u * u * d |
| 311 | } |
| 312 | |
| 313 | #[inline] |
| 314 | fn cubic_deriv(a: f64, b: f64, c: f64, d: f64, u: f64) -> f64 { |
| 315 | let inv = 1.0 - u; |
| 316 | 3.0 * inv * inv * (b - a) + 6.0 * inv * u * (c - b) + 3.0 * u * u * (d - c) |
| 317 | } |
| 318 | |
| 319 | /// 2D Bezier path used by Fusion `PolyPath` (Point animation) and `PolylineMask`. |
| 320 | #[derive(Clone, Debug, PartialEq)] |
| 321 | pub struct PolyPoint { |
| 322 | pub x: f64, |
| 323 | pub y: f64, |
| 324 | /// Relative left tangent handle `(lx, ly)` from `(x, y)`. |
| 325 | pub lx: f64, |
| 326 | pub ly: f64, |
| 327 | /// Relative right tangent handle `(rx, ry)` from `(x, y)`. |
| 328 | pub rx: f64, |
| 329 | pub ry: f64, |
| 330 | pub linear: bool, |
| 331 | } |
| 332 | |
| 333 | #[derive(Clone, Debug, PartialEq)] |
| 334 | pub struct PolyPath { |
| 335 | pub name: String, |
| 336 | pub displacement_op: Option<String>, |
| 337 | pub displacement_value: f64, |
| 338 | pub closed: bool, |
| 339 | pub points: Vec<PolyPoint>, |
| 340 | } |
| 341 | |
| 342 | impl PolyPath { |
| 343 | pub fn parse_polyline_table(pl: &LuaTable) -> (bool, Vec<PolyPoint>) { |
| 344 | let closed = pl.get_bool("Closed").unwrap_or(false); |
| 345 | let mut points = Vec::new(); |
| 346 | if let Some(pts) = pl.get_table("Points") { |
| 347 | for (_, v) in &pts.entries { |
| 348 | if let Some(pt) = v.as_table() { |
| 349 | points.push(PolyPoint { |
| 350 | x: pt.get_f64("X").unwrap_or(0.0), |
| 351 | y: pt.get_f64("Y").unwrap_or(0.0), |
| 352 | lx: pt.get_f64("LX").unwrap_or(0.0), |
| 353 | ly: pt.get_f64("LY").unwrap_or(0.0), |
| 354 | rx: pt.get_f64("RX").unwrap_or(0.0), |
| 355 | ry: pt.get_f64("RY").unwrap_or(0.0), |
| 356 | linear: pt.get_bool("Linear").unwrap_or(false), |
| 357 | }); |
| 358 | } |
| 359 | } |
| 360 | } |
| 361 | (closed, points) |
| 362 | } |
| 363 | |
| 364 | pub fn from_lua(name: String, table: &LuaTable) -> Self { |
| 365 | let mut displacement_op = None; |
| 366 | let mut displacement_value = 0.0; |
| 367 | let mut closed = false; |
| 368 | let mut points = Vec::new(); |
| 369 | |
| 370 | if let Some(inputs) = table.get_table("Inputs") { |
| 371 | if let Some(disp) = inputs.get_table("Displacement") { |
| 372 | displacement_op = disp.get_str("SourceOp").map(str::to_owned); |
| 373 | displacement_value = disp.get_f64("Value").unwrap_or(0.0); |
| 374 | } |
| 375 | if let Some(pl_in) = inputs.get_table("PolyLine").or_else(|| inputs.get_table("Polyline")) { |
| 376 | if let Some(pl) = pl_in.get_table("Value") { |
| 377 | let (c, pts) = Self::parse_polyline_table(pl); |
| 378 | closed = c; |
| 379 | points = pts; |
| 380 | } |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | Self { |
| 385 | name, |
| 386 | displacement_op, |
| 387 | displacement_value, |
| 388 | closed, |
| 389 | points, |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | /// Evaluates the PolyPath at normalized arc-length `displacement ∈ [0, 1]`, |
| 394 | /// returning Fusion normalized `[x, y]` coordinates (with `(0.5, 0.5)` origin!). |
| 395 | pub fn eval_center(&self, displacement: f64) -> [f64; 2] { |
| 396 | let p = self.eval_raw(displacement); |
| 397 | [0.5 + p[0], 0.5 + p[1]] |
| 398 | } |
| 399 | |
| 400 | /// Evaluates raw Polyline coordinates centered around `(0, 0)`. |
| 401 | /// Supports extrapolation when `displacement` is outside `[0, 1]` (e.g. from `LoopRel`!). |
| 402 | pub fn eval_raw(&self, displacement: f64) -> [f64; 2] { |
| 403 | if self.points.is_empty() { |
| 404 | return [0.0, 0.0]; |
| 405 | } |
| 406 | if self.points.len() == 1 { |
| 407 | return [self.points[0].x, self.points[0].y]; |
| 408 | } |
| 409 | let seg_count = if self.closed { self.points.len() } else { self.points.len() - 1 }; |
| 410 | |
| 411 | // Sample arc lengths along segments for accurate constant-speed displacement. |
| 412 | const SUBS: usize = 16; |
| 413 | let mut samples = Vec::with_capacity(seg_count * SUBS + 1); |
| 414 | let mut cum_len = 0.0_f64; |
| 415 | let mut prev = [self.points[0].x, self.points[0].y]; |
| 416 | samples.push((0.0_f64, prev)); |
| 417 | |
| 418 | for s in 0..seg_count { |
| 419 | let a = &self.points[s]; |
| 420 | let b = &self.points[(s + 1) % self.points.len()]; |
| 421 | let p0 = [a.x, a.y]; |
| 422 | let p3 = [b.x, b.y]; |
| 423 | let p1 = [a.x + a.rx, a.y + a.ry]; |
| 424 | let p2 = [b.x + b.lx, b.y + b.ly]; |
| 425 | for step in 1..=SUBS { |
| 426 | let u = step as f64 / SUBS as f64; |
| 427 | let cur = if a.linear && b.linear { |
| 428 | [p0[0] + (p3[0] - p0[0]) * u, p0[1] + (p3[1] - p0[1]) * u] |
| 429 | } else { |
| 430 | [ |
| 431 | cubic(p0[0], p1[0], p2[0], p3[0], u), |
| 432 | cubic(p0[1], p1[1], p2[1], p3[1], u), |
| 433 | ] |
| 434 | }; |
| 435 | let dx = cur[0] - prev[0]; |
| 436 | let dy = cur[1] - prev[1]; |
| 437 | cum_len += (dx * dx + dy * dy).sqrt(); |
| 438 | samples.push((cum_len, cur)); |
| 439 | prev = cur; |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | if cum_len <= 1e-12 || displacement.is_nan() { |
| 444 | return samples[0].1; |
| 445 | } |
| 446 | if !displacement.is_finite() { |
| 447 | return if displacement.is_sign_positive() { |
| 448 | samples[samples.len() - 1].1 |
| 449 | } else { |
| 450 | samples[0].1 |
| 451 | }; |
| 452 | } |
| 453 | // Extrapolate smoothly along end/start tangent when displacement is outside [0, 1] |
| 454 | if displacement > 1.0 && samples.len() >= 2 { |
| 455 | let (l0, v0) = samples[samples.len() - 2]; |
| 456 | let (l1, v1) = samples[samples.len() - 1]; |
| 457 | let seg = (l1 - l0).max(1e-12); |
| 458 | let extra = (displacement - 1.0) * cum_len; |
| 459 | return [ |
| 460 | v1[0] + (v1[0] - v0[0]) / seg * extra, |
| 461 | v1[1] + (v1[1] - v0[1]) / seg * extra, |
| 462 | ]; |
| 463 | } |
| 464 | if displacement < 0.0 && samples.len() >= 2 { |
| 465 | let (l0, v0) = samples[0]; |
| 466 | let (l1, v1) = samples[1]; |
| 467 | let seg = (l1 - l0).max(1e-12); |
| 468 | let extra = displacement * cum_len; |
| 469 | return [ |
| 470 | v0[0] + (v1[0] - v0[0]) / seg * extra, |
| 471 | v0[1] + (v1[1] - v0[1]) / seg * extra, |
| 472 | ]; |
| 473 | } |
| 474 | |
| 475 | let d = displacement.clamp(0.0, 1.0); |
| 476 | let target = d * cum_len; |
| 477 | let idx = samples.partition_point(|(l, _)| *l < target); |
| 478 | if idx == 0 { |
| 479 | return samples[0].1; |
| 480 | } |
| 481 | if idx >= samples.len() { |
| 482 | return samples[samples.len() - 1].1; |
| 483 | } |
| 484 | let (l0, v0) = samples[idx - 1]; |
| 485 | let (l1, v1) = samples[idx]; |
| 486 | let span = (l1 - l0).max(1e-12); |
| 487 | let frac = (target - l0) / span; |
| 488 | [v0[0] + (v1[0] - v0[0]) * frac, v0[1] + (v1[1] - v0[1]) * frac] |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | #[derive(Clone, Debug, PartialEq)] |
| 493 | pub struct GradientStop { |
| 494 | pub pos: f64, |
| 495 | pub rgba: [f32; 4], |
| 496 | } |
| 497 | |
| 498 | #[derive(Clone, Debug, Default, PartialEq)] |
| 499 | pub struct Gradient { |
| 500 | pub stops: Vec<GradientStop>, |
| 501 | } |
| 502 | |
| 503 | impl Gradient { |
| 504 | pub fn from_lua(table: &LuaTable) -> Self { |
| 505 | let mut stops = Vec::new(); |
| 506 | if let Some(colors) = table.get_table("Colors") { |
| 507 | for (k, v) in &colors.entries { |
| 508 | let pos = match k { |
| 509 | LuaKey::Index(i) => *i as f64, |
| 510 | LuaKey::Number(n) => *n, |
| 511 | _ => continue, |
| 512 | }; |
| 513 | if let Some(ct) = v.as_table() { |
| 514 | let r = ct.get_index(1).and_then(LuaValue::as_f64).unwrap_or(0.0) as f32; |
| 515 | let g = ct.get_index(2).and_then(LuaValue::as_f64).unwrap_or(0.0) as f32; |
| 516 | let b = ct.get_index(3).and_then(LuaValue::as_f64).unwrap_or(0.0) as f32; |
| 517 | let a = ct.get_index(4).and_then(LuaValue::as_f64).unwrap_or(1.0) as f32; |
| 518 | stops.push(GradientStop { pos, rgba: [r, g, b, a] }); |
| 519 | } |
| 520 | } |
| 521 | } |
| 522 | stops.sort_by(|a, b| a.pos.total_cmp(&b.pos)); |
| 523 | Self { stops } |
| 524 | } |
| 525 | |
| 526 | pub fn sample(&self, t: f64) -> [f32; 4] { |
| 527 | if self.stops.is_empty() { |
| 528 | return [0.0, 0.0, 0.0, 1.0]; |
| 529 | } |
| 530 | if self.stops.len() == 1 || t <= self.stops[0].pos { |
| 531 | return self.stops[0].rgba; |
| 532 | } |
| 533 | let last = &self.stops[self.stops.len() - 1]; |
| 534 | if t >= last.pos { |
| 535 | return last.rgba; |
| 536 | } |
| 537 | let idx = self.stops.partition_point(|s| s.pos <= t).saturating_sub(1); |
| 538 | let a = &self.stops[idx]; |
| 539 | let b = &self.stops[(idx + 1).min(self.stops.len() - 1)]; |
| 540 | let span = (b.pos - a.pos).max(1e-9); |
| 541 | let f = ((t - a.pos) / span) as f32; |
| 542 | [ |
| 543 | a.rgba[0] + (b.rgba[0] - a.rgba[0]) * f, |
| 544 | a.rgba[1] + (b.rgba[1] - a.rgba[1]) * f, |
| 545 | a.rgba[2] + (b.rgba[2] - a.rgba[2]) * f, |
| 546 | a.rgba[3] + (b.rgba[3] - a.rgba[3]) * f, |
| 547 | ] |
| 548 | } |
| 549 | } |
| 550 | |
| 551 | pub fn read_vec2(t: &LuaTable) -> Option<[f64; 2]> { |
| 552 | let x = t.get_index(1)?.as_f64()?; |
| 553 | let y = t.get_index(2)?.as_f64()?; |
| 554 | Some([x, y]) |
| 555 | } |
| 556 | |
| 557 | #[cfg(test)] |
| 558 | mod tests { |
| 559 | use super::*; |
| 560 | |
| 561 | fn kf(time: f64, value: f64, flags: KeyFlags) -> Keyframe { |
| 562 | Keyframe { |
| 563 | time, |
| 564 | value, |
| 565 | lh: None, |
| 566 | rh: None, |
| 567 | flags, |
| 568 | handle_mode: if flags.linear { HandleMode::Vector } else { HandleMode::Free }, |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | fn spline(keyframes: Vec<Keyframe>) -> BezierSpline { |
| 573 | BezierSpline { |
| 574 | name: "test".to_owned(), |
| 575 | color: [255, 255, 255], |
| 576 | keyframes, |
| 577 | } |
| 578 | } |
| 579 | |
| 580 | #[test] |
| 581 | fn segment_control_points_survive_unsorted_keys() { |
| 582 | let mut a = Keyframe::new(10.0, 0.0); |
| 583 | a.rh = Some([5.0, 1.0]); |
| 584 | let mut b = Keyframe::new(4.0, 1.0); |
| 585 | b.lh = Some([20.0, 0.5]); |
| 586 | let [_, p1, p2, _] = segment_control_points(&a, &b); |
| 587 | assert_eq!(p1, [5.0, 1.0]); |
| 588 | assert_eq!(p2, [10.0, 0.5]); |
| 589 | } |
| 590 | |
| 591 | #[test] |
| 592 | fn loop_clamps_before_first_keyframe_and_loops_after_last() { |
| 593 | let loop_flags = KeyFlags { linear: true, loop_after: true, ..Default::default() }; |
| 594 | let sp = spline(vec![ |
| 595 | kf(4129.0, 0.0, loop_flags), |
| 596 | kf(4155.0, 1.0, loop_flags), |
| 597 | ]); |
| 598 | // Pre-first keyframe must clamp to first.value (54_underwater ColorGain1HighHue @ 3933). |
| 599 | assert!((sp.eval(3933.0) - 0.0).abs() < 1e-9); |
| 600 | assert!((sp.eval(4129.0) - 0.0).abs() < 1e-9); |
| 601 | assert!((sp.eval(4142.0) - 0.5).abs() < 1e-9); |
| 602 | // At and after last.time, Loop wraps to first.time. |
| 603 | assert!((sp.eval(4155.0) - 0.0).abs() < 1e-9); |
| 604 | assert!((sp.eval(4168.0) - 0.5).abs() < 1e-9); |
| 605 | assert!((sp.eval(4181.0) - 0.0).abs() < 1e-9); |
| 606 | } |
| 607 | |
| 608 | #[test] |
| 609 | fn loop_requires_both_endpoints_flagged() { |
| 610 | let lin = KeyFlags { linear: true, ..Default::default() }; |
| 611 | let loop_f = KeyFlags { linear: true, loop_after: true, ..Default::default() }; |
| 612 | |
| 613 | let first_only = spline(vec![kf(10.0, 0.2, loop_f), kf(20.0, 0.8, lin)]); |
| 614 | assert!((first_only.eval(0.0) - 0.2).abs() < 1e-9); |
| 615 | assert!((first_only.eval(25.0) - 0.8).abs() < 1e-9); |
| 616 | |
| 617 | let last_only = spline(vec![kf(10.0, 0.2, lin), kf(20.0, 0.8, loop_f)]); |
| 618 | assert!((last_only.eval(0.0) - 0.2).abs() < 1e-9); |
| 619 | assert!((last_only.eval(25.0) - 0.8).abs() < 1e-9); |
| 620 | } |
| 621 | |
| 622 | #[test] |
| 623 | fn loop_rel_clamps_before_first_and_accumulates_after_last() { |
| 624 | let lin = KeyFlags { linear: true, ..Default::default() }; |
| 625 | let rel_both = KeyFlags { linear: true, loop_after: true, loop_rel: true, ..Default::default() }; |
| 626 | let sp = spline(vec![ |
| 627 | kf(10.0, 0.4, rel_both), |
| 628 | kf(20.0, 0.6, rel_both), |
| 629 | ]); |
| 630 | assert!((sp.eval(0.0) - 0.4).abs() < 1e-9); |
| 631 | assert!((sp.eval(15.0) - 0.5).abs() < 1e-9); |
| 632 | assert!((sp.eval(20.0) - 0.6).abs() < 1e-9); |
| 633 | assert!((sp.eval(25.0) - 0.7).abs() < 1e-9); |
| 634 | assert!((sp.eval(35.0) - 0.9).abs() < 1e-9); |
| 635 | |
| 636 | // LoopRel without Loop flag still loops relatively when both endpoints are marked. |
| 637 | let rel_only = KeyFlags { linear: true, loop_rel: true, ..Default::default() }; |
| 638 | let sp2 = spline(vec![kf(10.0, 0.4, rel_only), kf(20.0, 0.6, rel_only)]); |
| 639 | assert!((sp2.eval(0.0) - 0.4).abs() < 1e-9); |
| 640 | assert!((sp2.eval(25.0) - 0.7).abs() < 1e-9); |
| 641 | |
| 642 | // Single-endpoint LoopRel does not loop. |
| 643 | let single = spline(vec![kf(10.0, 0.4, lin), kf(20.0, 0.6, rel_both)]); |
| 644 | assert!((single.eval(25.0) - 0.6).abs() < 1e-9); |
| 645 | } |
| 646 | |
| 647 | #[test] |
| 648 | fn ping_pong_flag_semantics_match_fusion_21() { |
| 649 | let pp = KeyFlags { linear: true, ping_pong: true, ..Default::default() }; |
| 650 | let sp_pp = spline(vec![kf(10.0, 0.2, pp), kf(20.0, 0.8, pp)]); |
| 651 | assert!((sp_pp.eval(0.0) - 0.2).abs() < 1e-9); |
| 652 | assert!((sp_pp.eval(15.0) - 0.5).abs() < 1e-9); |
| 653 | assert!((sp_pp.eval(25.0) - 0.8).abs() < 1e-9); |
| 654 | |
| 655 | let loop_pp = KeyFlags { linear: true, loop_after: true, ping_pong: true, ..Default::default() }; |
| 656 | let sp_lpp = spline(vec![kf(10.0, 0.2, loop_pp), kf(20.0, 0.8, loop_pp)]); |
| 657 | assert!((sp_lpp.eval(0.0) - 0.2).abs() < 1e-9); |
| 658 | assert!((sp_lpp.eval(20.0) - 0.2).abs() < 1e-9); |
| 659 | assert!((sp_lpp.eval(25.0) - 0.5).abs() < 1e-9); |
| 660 | } |
| 661 | |
| 662 | #[test] |
| 663 | fn subrange_loop_repeats_between_flagged_keyframes_until_next_key() { |
| 664 | let lin = KeyFlags { linear: true, ..Default::default() }; |
| 665 | let lp = KeyFlags { linear: true, loop_after: true, ..Default::default() }; |
| 666 | let sp = spline(vec![ |
| 667 | kf(10.0, 0.2, lp), |
| 668 | kf(15.0, 0.7, lp), |
| 669 | kf(25.0, 0.9, lin), |
| 670 | ]); |
| 671 | assert!((sp.eval(5.0) - 0.2).abs() < 1e-9); |
| 672 | assert!((sp.eval(13.0) - 0.5).abs() < 1e-9); |
| 673 | assert!((sp.eval(15.0) - 0.2).abs() < 1e-9); |
| 674 | assert!((sp.eval(18.0) - 0.5).abs() < 1e-9); |
| 675 | assert!((sp.eval(23.0) - 0.5).abs() < 1e-9); |
| 676 | assert!((sp.eval(25.0) - 0.9).abs() < 1e-9); |
| 677 | assert!((sp.eval(27.0) - 0.9).abs() < 1e-9); |
| 678 | |
| 679 | let tail_loop = spline(vec![ |
| 680 | kf(10.0, 0.2, lin), |
| 681 | kf(15.0, 0.9, lp), |
| 682 | kf(20.0, 0.5, lp), |
| 683 | ]); |
| 684 | assert!((tail_loop.eval(0.0) - 0.2).abs() < 1e-9); |
| 685 | assert!((tail_loop.eval(13.0) - 0.62).abs() < 1e-9); |
| 686 | assert!((tail_loop.eval(20.0) - 0.9).abs() < 1e-9); |
| 687 | assert!((tail_loop.eval(23.0) - 0.66).abs() < 1e-9); |
| 688 | assert!((tail_loop.eval(33.0) - 0.66).abs() < 1e-9); |
| 689 | } |
| 690 | |
| 691 | #[test] |
| 692 | fn apply_hue_curves_cyclic_ends_wraps_last_handle_and_preserves_explicit_handles() { |
| 693 | // [0]=0.5, [2]=1.0, [6]=0.5 (HueCurves RedSuppress curve): |
| 694 | // slope0 = (1.0 - 0.5)/2 = +0.25, dt_last = 4 -> dx_last = 4/3, dy = 1/3 -> lh = (14/3, 1/6) |
| 695 | let smooth = KeyFlags::default(); |
| 696 | let mut rsup = spline(vec![ |
| 697 | kf(0.0, 0.5, smooth), |
| 698 | kf(2.0, 1.0, smooth), |
| 699 | kf(6.0, 0.5, smooth), |
| 700 | ]); |
| 701 | rsup.apply_hue_curves_cyclic_ends(); |
| 702 | let last_lh = rsup.keyframes[2].lh.expect("cyclic last.lh"); |
| 703 | assert!((last_lh[0] - (6.0 - 4.0 / 3.0)).abs() < 1e-9); |
| 704 | assert!((last_lh[1] - (0.5 - 1.0 / 3.0)).abs() < 1e-9); |
| 705 | // At h=5.0 (u=0.75 on [2..6]), cubic evaluates to ~0.414 instead of linear 0.625. |
| 706 | assert!((rsup.eval(5.0) - 0.4140625).abs() < 1e-3, "got {}", rsup.eval(5.0)); |
| 707 | |
| 708 | // 2-keyframe cyclic curve [0]=0.5, [6]=1.0 snaps last.value to 0.5 and mirrors chord RH->LH. |
| 709 | let mut two = spline(vec![kf(0.0, 0.5, smooth), kf(6.0, 1.0, smooth)]); |
| 710 | two.apply_hue_curves_cyclic_ends(); |
| 711 | assert!((two.eval(0.0) - 0.5).abs() < 1e-9); |
| 712 | assert!((two.eval(1.5) - 0.546875).abs() < 1e-6); |
| 713 | assert!((two.eval(3.0) - 0.5).abs() < 1e-9); |
| 714 | assert!((two.eval(4.5) - 0.453125).abs() < 1e-6); |
| 715 | assert!((two.eval(6.0) - 0.5).abs() < 1e-9); |
| 716 | |
| 717 | // Explicit LH/RH handles must not be overwritten. |
| 718 | let mut explicit = spline(vec![ |
| 719 | Keyframe { rh: Some([0.5, 0.9]), ..kf(0.0, 0.5, smooth) }, |
| 720 | Keyframe { lh: Some([5.5, 0.8]), ..kf(6.0, 0.5, smooth) }, |
| 721 | ]); |
| 722 | explicit.apply_hue_curves_cyclic_ends(); |
| 723 | assert_eq!(explicit.keyframes[0].rh, Some([0.5, 0.9])); |
| 724 | assert_eq!(explicit.keyframes[1].lh, Some([5.5, 0.8])); |
| 725 | } |
| 726 | } |