All files / player-browser/src/skins/synesthesia space.ts

97.63% Statements 330/338
92.47% Branches 86/93
100% Functions 40/40
97.81% Lines 314/321

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809                                                        272x 272x 2x   270x 270x                           154x 154x 154x 154x 154x 154x 154x                                   104x 104x 104x 104x   104x 104x 104x 104x 104x 104x 1x 1x 1x 1x 1x   103x 103x 103x 103x 103x 103x         505x                                           230x 230x 230x 230x 230x 230x 230x 230x 230x 230x 230x                                       201x 201x 201x 201x 201x 201x 201x 133x 133x 133x   201x 201x 201x 201x 101x 101x 1x 1x 1x 1x 1x   100x 100x 100x 100x 100x 100x       377x 377x 377x       246x 246x 246x                                         60x 60x 22811x   22811x 22811x 22811x 22811x             22811x 22811x 22811x 22811x 22811x 22811x 22811x 22811x   60x 60x                             64x 64x 64x 64x 64x 64x                                   65x 65x 65x 65x 1x 1x 1x 1x 1x   64x 64x 64x 64x 64x 64x       66x 66x 66x                                   3x 3x 3x 3x 3x 3x               55x 55x 55x 55x                       6x 6x 18x 18x   6x         83x 83x 83x 83x 83x 83x 83x 83x         83x   1x 1x 1x 1x   1x 1x 1x 1x             80x 80x 80x 80x   1x 1x 1x 1x           83x                 30x                         30x 30x 33x 30x 30x 30x 30x 30x 30x 30x               149x 149x           149x 149x 87360x 87360x 87360x 87360x 87360x 87360x   35444x 35444x 35444x 35444x     51916x 51916x 51916x 26724x 26724x   51916x             149x                 256x                                       306x     306x 306x   306x 306x 306x 306x 306x 306x 306x       35444x                             30x       7525x 1505x                           109x 109x 109x         3x 3x 3x                         8316x   3064x 2079x                             1504x 1504x 1504x 1504x 1504x 1504x 1504x 1504x 1504x 1504x 6016x   1504x                                               19202x 57606x         57606x 19202x                                                       5x 5x   5x 5x 5x           5x 19x 5x 1x 1x 1x   4x   14x 14x 7x   5x 1x 1x   4x 4x 3x 3x   4x 2x 2x   4x       30x 7680x 30x 7650x 7650x   30x 15360x 30x         18620x   1934x   1827x   1982x   1841x   2367x   2133x   2212x   4324x           4655x 4655x 4655x 4655x 4655x 4655x 4655x 4655x 4655x 4655x 4655x 4655x 4655x 4655x 4655x 4655x 4655x 4655x       30x               2077x 2076x 2076x 2076x 2076x   2076x 2076x       30x                             6x 6x 6x 6x 6x   1x 1x 1x 1x   6x 6x 6x              
import { hash01 } from '@be-music/player-skin-sdk';
 
/**
 * Pure 3D helpers for the Synesthesia skin: a pinhole projection, deterministic particle bursts, a looping starfield,
 * point-cloud shapes (pyramids), orbiting particles for the audio orb, particle rivers, and ember / hue-based colour. Everything is a
 * function of (seed, time) so the pooled per-frame redraw needs no particle state and never shimmers.
 */
 
export interface Vec3 {
  x: number;
  y: number;
  z: number;
}
 
export interface Projected {
  x: number;
  y: number;
  /** Perspective scale at this depth (1 at `z = 0`). */
  scale: number;
  /** False when the point is behind the camera. */
  visible: boolean;
}
 
/**
 * Pinhole projection. The camera sits at `z = -focal` looking down +z, so a point at `z = 0` projects 1:1 around the
 * origin `(cx, cy)`; larger `z` recedes toward the vanishing point and shrinks.
 */
export function projectPoint(point: Vec3, cx: number, cy: number, focal: number): Projected {
  const depth = focal + point.z;
  if (depth <= 1e-3) {
    return { x: cx, y: cy, scale: 0, visible: false };
  }
  const scale = focal / depth;
  return { x: cx + point.x * scale, y: cy + point.y * scale, scale, visible: true };
}
 
/** A camera's yaw / pitch sines and cosines, worked out once per frame for {@link projectViewInto}. */
export interface CameraBasis {
  camera: CameraPose;
  cosYaw: number;
  sinYaw: number;
  cosPitch: number;
  sinPitch: number;
}
 
/** The basis for `camera`, written into `out` (a fresh object when omitted). */
export function cameraBasis(camera: CameraPose, out?: CameraBasis): CameraBasis {
  const basis = out ?? { camera, cosYaw: 1, sinYaw: 0, cosPitch: 1, sinPitch: 0 };
  basis.camera = camera;
  basis.cosYaw = Math.cos(camera.yaw);
  basis.sinYaw = Math.sin(camera.yaw);
  basis.cosPitch = Math.cos(camera.pitch);
  basis.sinPitch = Math.sin(camera.pitch);
  return basis;
}
 
/**
 * `projectPoint(viewPoint({ x, y, z }, camera, orbit), cx, cy, focal)` without allocating: the result is written into
 * `out`. For the hot loops that project thousands of points a frame.
 */
export function projectViewInto(
  out: Projected,
  x: number,
  y: number,
  z: number,
  basis: CameraBasis,
  cx: number,
  cy: number,
  focal: number,
  orbit = 0,
): Projected {
  const camera = basis.camera;
  const lx = x - camera.x;
  const ly = y - camera.y;
  const lz = z - camera.z - orbit;
  // rotateY by -yaw, then rotateX by pitch (see `viewPoint`).
  const x1 = lx * basis.cosYaw - lz * basis.sinYaw;
  const z1 = lx * basis.sinYaw + lz * basis.cosYaw;
  const y2 = ly * basis.cosPitch - z1 * basis.sinPitch;
  const z2 = ly * basis.sinPitch + z1 * basis.cosPitch + orbit;
  const depth = focal + z2;
  if (depth <= 1e-3) {
    out.x = cx;
    out.y = cy;
    out.scale = 0;
    out.visible = false;
    return out;
  }
  const scale = focal / depth;
  out.x = cx + x1 * scale;
  out.y = cy + y2 * scale;
  out.scale = scale;
  out.visible = true;
  return out;
}
 
/** A blank {@link Projected} to reuse with {@link projectViewInto}. */
export function scratchProjected(): Projected {
  return { x: 0, y: 0, scale: 0, visible: false };
}
 
/** A point-cloud transform (scale → yaw → pitch → offset) with its sines and cosines worked out once per cloud. */
export interface CloudBasis {
  scale: number;
  cosYaw: number;
  sinYaw: number;
  /** Whether the transform pitches at all (a zero pitch skips the turn, as `drawPointCloud` always did). */
  pitched: boolean;
  cosPitch: number;
  sinPitch: number;
  x: number;
  y: number;
  z: number;
}
 
/** The basis of a cloud transform, written into `out` (a fresh object when omitted). */
export function cloudBasis(
  transform: { scale: number; x: number; y: number; z: number; yaw: number; pitch?: number },
  out?: CloudBasis,
): CloudBasis {
  const basis = out ?? { scale: 1, cosYaw: 1, sinYaw: 0, pitched: false, cosPitch: 1, sinPitch: 0, x: 0, y: 0, z: 0 };
  basis.scale = transform.scale;
  basis.cosYaw = Math.cos(transform.yaw);
  basis.sinYaw = Math.sin(transform.yaw);
  basis.pitched = Boolean(transform.pitch);
  basis.cosPitch = basis.pitched ? Math.cos(transform.pitch!) : 1;
  basis.sinPitch = basis.pitched ? Math.sin(transform.pitch!) : 0;
  basis.x = transform.x;
  basis.y = transform.y;
  basis.z = transform.z;
  return basis;
}
 
/**
 * A unit-shape point placed by `cloud` and projected, seen from `camera` when given, written into `out` without
 * allocating: the same arithmetic, in the same order, as `projectPoint(viewPoint(placed, camera, orbit))` over
 * `rotateX(rotateY(scaled, yaw), pitch)` plus the offset.
 */
export function projectCloudPointInto(
  out: Projected,
  x: number,
  y: number,
  z: number,
  cloud: CloudBasis,
  camera: CameraBasis | undefined,
  cx: number,
  cy: number,
  focal: number,
  orbit = 0,
): Projected {
  const sx = x * cloud.scale;
  const sy = y * cloud.scale;
  const sz = z * cloud.scale;
  const rx = sx * cloud.cosYaw + sz * cloud.sinYaw;
  let ry = sy;
  let rz = -sx * cloud.sinYaw + sz * cloud.cosYaw;
  if (cloud.pitched) {
    const py = ry * cloud.cosPitch - rz * cloud.sinPitch;
    rz = ry * cloud.sinPitch + rz * cloud.cosPitch;
    ry = py;
  }
  const px = rx + cloud.x;
  const py = ry + cloud.y;
  const pz = rz + cloud.z;
  if (camera) return projectViewInto(out, px, py, pz, camera, cx, cy, focal, orbit);
  const depth = focal + pz;
  if (depth <= 1e-3) {
    out.x = cx;
    out.y = cy;
    out.scale = 0;
    out.visible = false;
    return out;
  }
  const scale = focal / depth;
  out.x = cx + px * scale;
  out.y = cy + py * scale;
  out.scale = scale;
  out.visible = true;
  return out;
}
 
export function rotateY(point: Vec3, angle: number): Vec3 {
  const cos = Math.cos(angle);
  const sin = Math.sin(angle);
  return { x: point.x * cos + point.z * sin, y: point.y, z: -point.x * sin + point.z * cos };
}
 
export function rotateX(point: Vec3, angle: number): Vec3 {
  const cos = Math.cos(angle);
  const sin = Math.sin(angle);
  return { x: point.x, y: point.y * cos - point.z * sin, z: point.y * sin + point.z * cos };
}
 
export interface BurstParticle {
  /** Unit-ish launch direction (upper hemisphere biased). */
  direction: Vec3;
  /** Launch speed multiplier in [0.35, 1]. */
  speed: number;
  /** Size multiplier in [0.4, 1]. */
  size: number;
  /** Hue offset in [-0.08, 0.08] around the burst's base hue. */
  hueShift: number;
  /** Lifetime fraction in [0.55, 1] — some sparks burn out early. */
  life: number;
}
 
/**
 * `count` burst particles on a sphere, deterministic for `seed`. Directions are biased upward (screen −y) so a hit
 * reads as sparks thrown off the judgement line rather than a symmetric puff.
 */
export function burstParticles(seed: number, count: number, particles: BurstParticle[] = []): BurstParticle[] {
  let used = 0;
  for (let index = 0; index < count; index += 1) {
    const base = seed * 97 + index * 13;
    // Uniform sphere sampling via (cos θ, φ), then squash the lower hemisphere.
    const cosTheta = 1 - 2 * hash01(base + 1);
    const sinTheta = Math.sqrt(Math.max(0, 1 - cosTheta * cosTheta));
    const phi = Math.PI * 2 * hash01(base + 2);
    const particle = (particles[index] ??= {
      direction: { x: 0, y: 0, z: 0 },
      speed: 0,
      size: 0,
      hueShift: 0,
      life: 0,
    });
    particle.direction.x = sinTheta * Math.cos(phi);
    particle.direction.y = cosTheta > 0 ? -cosTheta : cosTheta * -0.35;
    particle.direction.z = sinTheta * Math.sin(phi);
    particle.speed = 0.35 + 0.65 * hash01(base + 3);
    particle.size = 0.4 + 0.6 * hash01(base + 4);
    particle.hueShift = (hash01(base + 5) - 0.5) * 0.16;
    particle.life = 0.55 + 0.45 * hash01(base + 6);
    used++;
  }
  particles.length = used;
  return particles;
}
 
/**
 * Position of burst particle `particle` at normalized time `t` (0..1): ease-out launch with drag, plus a little
 * gravity pulling sparks back down late in their life.
 */
/** {@link burstParticlePosition} written into `out` without allocating. */
export function burstParticlePositionInto(
  out: Vec3,
  particle: BurstParticle,
  t: number,
  radius: number,
  gravity: number,
): Vec3 {
  const clamped = Math.max(0, Math.min(1, t));
  const travel = (1 - (1 - clamped) ** 3) * radius * particle.speed;
  out.x = particle.direction.x * travel;
  out.y = particle.direction.y * travel + gravity * clamped * clamped;
  out.z = particle.direction.z * travel;
  return out;
}
 
/**
 * `projectPoint(rotateY({ x, y, z }, angle), cx, cy, focal)` without allocating, for an angle whose cosine and sine
 * are worked out once: the same arithmetic in the same order, written into `out`.
 */
export function projectYawedInto(
  out: Projected,
  x: number,
  y: number,
  z: number,
  cos: number,
  sin: number,
  cx: number,
  cy: number,
  focal: number,
): Projected {
  const rx = x * cos + z * sin;
  const rz = -x * sin + z * cos;
  const depth = focal + rz;
  if (depth <= 1e-3) {
    out.x = cx;
    out.y = cy;
    out.scale = 0;
    out.visible = false;
    return out;
  }
  const scale = focal / depth;
  out.x = cx + rx * scale;
  out.y = cy + y * scale;
  out.scale = scale;
  out.visible = true;
  return out;
}
 
export function burstParticlePosition(particle: BurstParticle, t: number, radius: number, gravity: number): Vec3 {
  const clamped = Math.max(0, Math.min(1, t));
  const travel = (1 - (1 - clamped) ** 3) * radius * particle.speed;
  return {
    x: particle.direction.x * travel,
    y: particle.direction.y * travel + gravity * clamped * clamped,
    z: particle.direction.z * travel,
  };
}
 
/**
 * Star `index` of a looping starfield flying toward the camera. Depth cycles over `[near, far]` at `speed` units/s;
 * lateral position is a fixed per-star spread in `[-spread, spread]`.
 */
/** {@link starfieldPoint} written into `out` instead of a fresh object. */
export function starfieldInto(
  out: Vec3,
  index: number,
  seconds: number,
  options: { spread: number; near: number; far: number; speed: number },
): Vec3 {
  const span = options.far - options.near;
  const phase = hash01(index * 7 + 3) * span;
  out.x = (hash01(index * 7 + 1) * 2 - 1) * options.spread;
  out.y = (hash01(index * 7 + 2) * 2 - 1) * options.spread * 0.62;
  out.z = options.far - ((seconds * options.speed + phase) % span);
  return out;
}
 
export function starfieldPoint(
  index: number,
  seconds: number,
  options: { spread: number; near: number; far: number; speed: number },
): Vec3 {
  const span = options.far - options.near;
  const phase = hash01(index * 7 + 3) * span;
  const z = options.far - ((seconds * options.speed + phase) % span);
  return {
    x: (hash01(index * 7 + 1) * 2 - 1) * options.spread,
    y: (hash01(index * 7 + 2) * 2 - 1) * options.spread * 0.62,
    z,
  };
}
 
/**
 * `over` painted at `alpha` (clamped to 0..1) over an opaque `base`, both 0xRRGGBB: what a normal-blended flat fill
 * leaves on a flat one, so the two can be drawn as one fill. Pure.
 */
export function mixColor(base: number, over: number, alpha: number): number {
  const t = Math.max(0, Math.min(1, alpha));
  const channel = (shift: number): number => {
    const from = (base >> shift) & 0xff;
    return Math.round(from + (((over >> shift) & 0xff) - from) * t);
  };
  return (channel(16) << 16) | (channel(8) << 8) | channel(0);
}
 
/** HSV (all in 0..1, hue wrapping) to a 0xRRGGBB number. */
export function hsvToHex(hue: number, saturation: number, value: number): number {
  const h = (((hue % 1) + 1) % 1) * 6;
  const s = Math.max(0, Math.min(1, saturation));
  const v = Math.max(0, Math.min(1, value));
  const sector = Math.floor(h);
  const fraction = h - sector;
  const p = v * (1 - s);
  const q = v * (1 - s * fraction);
  const t = v * (1 - s * (1 - fraction));
  // Allocation-free sector switch: this runs for thousands of particles per frame.
  let r: number;
  let g: number;
  let b: number;
  switch (sector % 6) {
    case 0:
      r = v;
      g = t;
      b = p;
      break;
    case 1:
      r = q;
      g = v;
      b = p;
      break;
    case 2:
      r = p;
      g = v;
      b = t;
      break;
    case 3:
      r = p;
      g = q;
      b = v;
      break;
    case 4:
      r = t;
      g = p;
      b = v;
      break;
    default:
      r = v;
      g = p;
      b = q;
  }
  return (Math.round(r * 255) << 16) | (Math.round(g * 255) << 8) | Math.round(b * 255);
}
 
/** One point of a point-cloud shape: a position plus a per-point size / brightness weight in [0.3, 1]. */
export interface CloudPoint extends Vec3 {
  weight: number;
}
 
/** {@link emberColor}'s ramp: `[t, r, g, b]` stops, hoisted so the hot path allocates nothing. */
const EMBER_STOPS: ReadonlyArray<readonly [number, number, number, number]> = [
  [0, 0xb8, 0x2c, 0x08],
  [0.35, 0xff, 0x66, 0x12],
  [0.65, 0xff, 0xaa, 0x30],
  [0.85, 0xff, 0xd8, 0x86],
  [1, 0xff, 0xf6, 0xe2],
];
 
/**
 * Ember → gold → white-hot ramp for `t` in 0..1 (clamped) — the warm light that dominates a cosmic particle
 * worlds. Low `t` is a deep red-orange ember, high `t` a pale gold flare.
 */
export function emberColor(t: number): number {
  const clamped = Math.max(0, Math.min(1, Number.isFinite(t) ? t : 0));
  let index = 1;
  while (index < EMBER_STOPS.length - 1 && clamped > EMBER_STOPS[index]![0]) index += 1;
  const from = EMBER_STOPS[index - 1]!;
  const to = EMBER_STOPS[index]!;
  const f = (clamped - from[0]) / (to[0] - from[0]);
  const r = Math.round(from[1] + (to[1] - from[1]) * f);
  const g = Math.round(from[2] + (to[2] - from[2]) * f);
  const b = Math.round(from[3] + (to[3] - from[3]) * f);
  return (r << 16) | (g << 8) | b;
}
 
/**
 * Square pyramid as a point cloud: base half-width 1 on `y = 0`, apex at `y = -1.3` (screen up). Four in ten points
 * sit on the edges so the silhouette reads crisply; the rest scatter over the four faces. Deterministic for `seed`.
 */
export function pointCloudPyramid(seed: number, count: number): CloudPoint[] {
  const apex: Vec3 = { x: 0, y: -1.3, z: 0 };
  const corners: Vec3[] = [
    { x: -1, y: 0, z: -1 },
    { x: 1, y: 0, z: -1 },
    { x: 1, y: 0, z: 1 },
    { x: -1, y: 0, z: 1 },
  ];
  const points: CloudPoint[] = [];
  for (let index = 0; index < count; index += 1) {
    const base = seed * 131 + index * 17;
    const face = Math.floor(hash01(base + 1) * 4) % 4;
    const a = corners[face]!;
    const b = corners[(face + 1) % 4]!;
    const weight = 0.3 + 0.7 * hash01(base + 4);
    if (hash01(base + 2) < 0.4) {
      // Edge point: either a side edge (corner → apex) or a base edge.
      const along = hash01(base + 3);
      const from = hash01(base + 5) < 0.7 ? apex : b;
      points.push({ ...lerp3(a, from, along), weight: Math.min(1, weight + 0.25) });
      continue;
    }
    // Face point via uniform barycentric sampling of the triangle (a, b, apex).
    let u = hash01(base + 3);
    let v = hash01(base + 5);
    if (u + v > 1) {
      u = 1 - u;
      v = 1 - v;
    }
    points.push({
      x: a.x + (b.x - a.x) * u + (apex.x - a.x) * v,
      y: a.y + (b.y - a.y) * u + (apex.y - a.y) * v,
      z: a.z + (b.z - a.z) * u + (apex.z - a.z) * v,
      weight,
    });
  }
  return points;
}
 
/**
 * Particle `index` of a flowing river of light, in river-local space: it travels along `x` from `-length / 2` to
 * `length / 2` at `speed` units/s (looping), weaving on a slow sine, with a fixed per-particle offset across the
 * stream so the river has body. Deterministic for (`index`, `seconds`).
 */
export function particleRiverPoint(index: number, seconds: number, options: RiverOptions, distance?: number): Vec3 {
  return particleRiverPointInto({ x: 0, y: 0, z: 0 }, index, seconds, options, distance);
}
 
/** The flow {@link particleRiverPoint} follows. */
export interface RiverOptions {
  length: number;
  speed: number;
  amplitude: number;
  width: number;
  seed?: number;
}
 
/** {@link particleRiverPoint} written into `out`, for the per-frame loops. */
export function particleRiverPointInto(
  out: Vec3,
  index: number,
  seconds: number,
  options: RiverOptions,
  distance?: number,
): Vec3 {
  const base = (options.seed ?? 0) * 211 + index * 23;
  // `distance` (world units travelled, accumulated by the caller) lets the river's speed change without the particles
  // jumping; without it the flow is `seconds × speed`.
  const travelled = distance ?? seconds * options.speed;
  const along = (hash01(base + 1) + travelled / options.length) % 1;
  // Sum of two uniforms ≈ triangular spread: dense core, feathered edges.
  const across = (hash01(base + 2) + hash01(base + 3) - 1) * options.width;
  const depth = (hash01(base + 4) + hash01(base + 5) - 1) * options.width;
  const wave = Math.sin(along * Math.PI * 2 * 1.5 + seconds * 0.6 + (options.seed ?? 0)) * options.amplitude;
  out.x = (along - 0.5) * options.length;
  out.y = wave + across;
  out.z = depth;
  return out;
}
 
function lerp3(a: Vec3, b: Vec3, t: number): Vec3 {
  return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t, z: a.z + (b.z - a.z) * t };
}
 
/**
 * A camera pose for the background 3D space: an offset of the eye (`x` right, `y` down, `z` forward) plus `yaw`
 * (positive turns right) and `pitch` (positive looks down), in radians.
 */
export interface CameraPose {
  x: number;
  y: number;
  z: number;
  yaw: number;
  pitch: number;
}
 
export const REST_CAMERA: CameraPose = { x: 0, y: 0, z: 0, yaw: 0, pitch: 0 };
 
/** Blend between two poses (`t` = 0 → `from`, 1 → `to`); `mixCamera(REST_CAMERA, pose, 0.5)` halves a move. */
export function mixCamera(from: CameraPose, to: CameraPose, t: number): CameraPose {
  const mix = (a: number, b: number) => a + (b - a) * t;
  return {
    x: mix(from.x, to.x),
    y: mix(from.y, to.y),
    z: mix(from.z, to.z),
    yaw: mix(from.yaw, to.yaw),
    pitch: mix(from.pitch, to.pitch),
  };
}
 
/**
 * World `point` seen from `camera`: translate by the eye offset, then turn by yaw / pitch about a pivot `orbit` units
 * ahead (0 turns the camera in place; a positive value circles the camera around a subject at that depth).
 */
export function viewPoint(point: Vec3, camera: CameraPose, orbit = 0): Vec3 {
  const local = { x: point.x - camera.x, y: point.y - camera.y, z: point.z - camera.z - orbit };
  const turned = rotateX(rotateY(local, -camera.yaw), camera.pitch);
  return { x: turned.x, y: turned.y, z: turned.z + orbit };
}
 
/** Screen position of the direction straight ahead in world space (+z) — where the floor's horizon and warp meet. */
export function vanishingPoint(camera: CameraPose, cx: number, cy: number, focal: number): { x: number; y: number } {
  const direction = rotateX(rotateY({ x: 0, y: 0, z: 1 }, -camera.yaw), camera.pitch);
  Iif (direction.z <= 1e-6) return { x: cx, y: cy };
  return { x: cx + (direction.x / direction.z) * focal, y: cy + (direction.y / direction.z) * focal };
}
 
/** Per-axis extents a roaming camera may wander within (each axis spans `[-range, range]`). */
export interface CameraRange {
  x: number;
  y: number;
  yaw: number;
  pitch: number;
}
 
/** Shot `index` of a seeded random sequence: a pose inside `range`, deterministic for (`index`, `seed`). */
export function randomShot(index: number, seed: number, range: CameraRange): CameraPose {
  const roll = (offset: number) => hash01(seed * 977 + index * 31 + offset) * 2 - 1;
  // Shot 0 opens at rest so every scene starts on the composed default view.
  if (index === 0) return REST_CAMERA;
  return { x: roll(1) * range.x, y: roll(2) * range.y, z: 0, yaw: roll(3) * range.yaw, pitch: roll(4) * range.pitch };
}
 
/**
 * A roaming camera: every `cycleSeconds` a new random shot (see {@link randomShot}). Within each cycle the camera holds,
 * then flies to the next shot over a random 1–3.5 s — or, one cycle in five, hard-cuts to it — and a slow handheld
 * drift (incommensurate sines, `drift` × the range) keeps it breathing between moves.
 */
export function roamingCamera(
  seconds: number,
  seed: number,
  range: CameraRange,
  cycleSeconds: number,
  drift = 0.08,
): CameraPose {
  const time = Number.isFinite(seconds) ? seconds : 0;
  const step = Math.floor(time / cycleSeconds);
  const local = time - step * cycleSeconds;
  const from = randomShot(step, seed, range);
  const to = randomShot(step + 1, seed, range);
  const cut = hash01(seed * 53 + step * 7) < 0.2;
  const move = cut ? 0.18 : 1 + 2.5 * hash01(seed * 61 + step * 11);
  const hold = cycleSeconds - move;
  const raw = local <= hold ? 0 : Math.min(1, (local - hold) / move);
  const pose = mixCamera(from, to, raw * raw * (3 - 2 * raw));
  const wobble = (a: number, b: number, c: number) =>
    (Math.sin(time * a) + Math.sin(time * b + 1.3) * 0.6 + Math.sin(time * c + 2.1) * 0.3) / 1.9;
  return {
    x: pose.x + wobble(0.31, 0.53, 1.07) * range.x * drift,
    y: pose.y + wobble(0.27, 0.61, 0.97) * range.y * drift,
    z: pose.z,
    yaw: pose.yaw + wobble(0.23, 0.47, 1.13) * range.yaw * drift,
    pitch: pose.pitch + wobble(0.29, 0.43, 0.89) * range.pitch * drift,
  };
}
 
/** An axis-aligned box in world space. */
export interface Box3 {
  minX: number;
  maxX: number;
  minY: number;
  maxY: number;
  minZ: number;
  maxZ: number;
}
 
/**
 * A free-roaming position inside `bounds` at `seconds`: each axis sums two incommensurate sines (phases from `seed`),
 * so the path wanders smoothly and never visibly repeats. Always inside the box.
 */
export function wanderPoint(seconds: number, seed: number, bounds: Box3): Vec3 {
  const t = Number.isFinite(seconds) ? seconds : 0;
  const axis = (a: number, b: number, offset: number) =>
    (Math.sin(t * a + hash01(seed * 31 + offset) * 6.283) * 0.62 +
      Math.sin(t * b + hash01(seed * 37 + offset) * 6.283) * 0.38) *
      0.5 +
    0.5;
  const mix = (min: number, max: number, u: number) => min + (max - min) * u;
  return {
    x: mix(bounds.minX, bounds.maxX, axis(0.137, 0.311, 1)),
    y: mix(bounds.minY, bounds.maxY, axis(0.193, 0.427, 2)),
    z: mix(bounds.minZ, bounds.maxZ, axis(0.101, 0.263, 3)),
  };
}
 
/** Axis-aligned rectangle (x / y / w / h) for {@link clipSegmentOutsideRect}. */
export interface ClipRect {
  x: number;
  y: number;
  w: number;
  h: number;
}
 
/**
 * The parts of the segment (x0, y0) → (x1, y1) that lie outside `rect`, appended to `out` as `x0, y0, x1, y1` quads:
 * the whole segment when it misses the rect, one or two pieces when it crosses it, nothing when it lies inside. Lets
 * the space's floor lines run up to a live BGA without being drawn over it. Returns the number of pieces appended.
 */
export function clipSegmentOutsideRect(
  x0: number,
  y0: number,
  x1: number,
  y1: number,
  rect: ClipRect,
  out: number[],
): number {
  const dx = x1 - x0;
  const dy = y1 - y0;
  // Liang–Barsky: narrow [enter, exit] to the part of the segment inside the rect.
  let enter = 0;
  let exit = 1;
  const edges: ReadonlyArray<readonly [number, number]> = [
    [-dx, x0 - rect.x],
    [dx, rect.x + rect.w - x0],
    [-dy, y0 - rect.y],
    [dy, rect.y + rect.h - y0],
  ];
  for (const [p, q] of edges) {
    if (p === 0) {
      if (q < 0) {
        enter = 1;
        exit = 0;
        break;
      }
      continue;
    }
    const t = q / p;
    if (p < 0) enter = Math.max(enter, t);
    else exit = Math.min(exit, t);
  }
  if (enter >= exit) {
    out.push(x0, y0, x1, y1);
    return 1;
  }
  let pieces = 0;
  if (enter > 0) {
    out.push(x0, y0, x0 + dx * enter, y0 + dy * enter);
    pieces += 1;
  }
  if (exit < 1) {
    out.push(x0 + dx * exit, y0 + dy * exit, x1, y1);
    pieces += 1;
  }
  return pieces;
}
 
/** Shuffled 0..255 (doubled so lookups never wrap) for {@link perlin2}; fixed, so the terrain is the same every run. */
const PERLIN_PERM: Uint8Array = (() => {
  const base = Array.from({ length: 256 }, (_, index) => index);
  for (let index = 255; index > 0; index -= 1) {
    const swap = Math.floor(hash01(index * 13 + 7) * (index + 1));
    [base[index], base[swap]] = [base[swap]!, base[index]!];
  }
  const perm = new Uint8Array(512);
  for (let index = 0; index < 512; index += 1) perm[index] = base[index & 255]!;
  return perm;
})();
 
function perlinGrad(hash: number, x: number, y: number): number {
  // Eight gradient directions: the four axes and the four diagonals.
  switch (hash & 7) {
    case 0:
      return x + y;
    case 1:
      return -x + y;
    case 2:
      return x - y;
    case 3:
      return -x - y;
    case 4:
      return x;
    case 5:
      return -x;
    case 6:
      return y;
    default:
      return -y;
  }
}
 
/** Classic 2D Perlin gradient noise: smooth, zero on integer lattice points, roughly within -1..1. */
export function perlin2(x: number, y: number): number {
  const xf = Math.floor(x);
  const yf = Math.floor(y);
  const xi = xf & 255;
  const yi = yf & 255;
  const dx = x - xf;
  const dy = y - yf;
  const u = dx * dx * dx * (dx * (dx * 6 - 15) + 10);
  const v = dy * dy * dy * (dy * (dy * 6 - 15) + 10);
  const p = PERLIN_PERM;
  const aa = p[p[xi]! + yi]!;
  const ab = p[p[xi]! + yi + 1]!;
  const ba = p[p[xi + 1]! + yi]!;
  const bb = p[p[xi + 1]! + yi + 1]!;
  const lower = perlinGrad(aa, dx, dy);
  const x1 = lower + u * (perlinGrad(ba, dx - 1, dy) - lower);
  const upper = perlinGrad(ab, dx, dy - 1);
  const x2 = upper + u * (perlinGrad(bb, dx - 1, dy - 1) - upper);
  return x1 + v * (x2 - x1);
}
 
/** World units per noise cell of the floor's terrain; the second octave runs at 2.3x the frequency. */
const TERRAIN_CELL = 520;
 
/**
 * Height (world units, >= 0, upward) the floor rises at `(x, worldZ)`: two octaves of Perlin noise shaped into rounded
 * hills over flat valleys, drifting slowly with `seconds`. `worldZ` is the point's depth plus the distance travelled,
 * so the hills scroll with the floor. `amplitude` sets the tallest hill; the skins drive it with the music's level.
 */
export function floorRise(x: number, worldZ: number, seconds: number, amplitude: number): number {
  if (amplitude <= 0) return 0;
  const drift = seconds * 0.05;
  const nx = x / TERRAIN_CELL;
  const nz = worldZ / TERRAIN_CELL;
  const n = perlin2(nx + drift, nz) * 0.7 + perlin2(nx * 2.3 - drift, nz * 2.3 + 17.3) * 0.3;
  // Most of the noise swells into rounded hills (smoothstep over it); only its lowest stretches stay flat valley floor.
  const crest = Math.max(0, Math.min(1, n * 1.5 + 0.4));
  return amplitude * crest * crest * (3 - 2 * crest);
}
 
/** Nearest the fly-past pushes an object off the vanishing point (px), so one sitting on it still slides past. */
const FLY_PAST_MIN_OFFSET = 40;
 
/**
 * Where an object at `(x, y)` drawn at `scale` lands as the camera flies past it during the launch warp (`warp` 0..1):
 * it streams out from the vanishing point `(vpX, vpY)` like the stars, growing faster and faster (ease-in) until it
 * leaves the screen, and fades over the last quarter of the warp.
 */
export function flyPast(
  x: number,
  y: number,
  scale: number,
  vpX: number,
  vpY: number,
  warp: number,
): { x: number; y: number; scale: number; alpha: number } {
  const t = Math.max(0, Math.min(1, warp));
  let dx = x - vpX;
  let dy = y - vpY;
  const distance = Math.hypot(dx, dy);
  if (distance < FLY_PAST_MIN_OFFSET) {
    // Sitting on the vanishing point: slide off down and to the right, below the launch title.
    const ux = distance > 1e-6 ? dx / distance : 0.6;
    const uy = distance > 1e-6 ? dy / distance : 0.8;
    dx = ux * FLY_PAST_MIN_OFFSET;
    dy = uy * FLY_PAST_MIN_OFFSET;
  }
  const reach = 1 + 5 * t * t;
  const fade = Math.max(0, Math.min(1, (t - 0.75) / 0.25));
  return {
    x: t > 0 ? vpX + dx * reach : x,
    y: t > 0 ? vpY + dy * reach : y,
    scale: scale * reach,
    alpha: 1 - fade * fade * (3 - 2 * fade),
  };
}