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

53.24% Statements 123/231
27.27% Branches 30/110
72.22% Functions 13/18
53.65% Lines 110/205

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                                                  29x           29x 29x 29x 145x 145x 145x 145x   29x                 4x 4x 4x 4x 4x 4x                               29x 29x     29x     29x                         6x 6x 6x 6x 6x 6x 6x 6x 6x                                 34x         34x 34x 34x 34x     20x 20x 7x 7x 7x   20x       9x 9x 8x                   8x 8x 8x 6x 6x   8x                                           2x 2x 2x                               2x                                 2x 2x 1x                         3x 3x 3x 3x 3x             3x   3x       6x 7x 7x 7x 7x 8x   7x 7x   6x 3x 3x 3x 3x 3x   3x 3x     6x 6x 6x                     29x                       11x         9x                                   11x 11x 11x 11x 11x 11x                                       11x 3x 3x 3x 3x   3x 3x 3x                                                                                       29x 29x 29x                                                                                                                                                                                                                                                                                                                                                   29x 29x 29x 29x 29x 29x 29x 29x 29x                  
import type { Graphics } from 'pixi.js';
import { drawGlassSurface } from './glass.ts';
import type { Flock } from './boids.ts';
import { createMantaShape, mantaShapeInto } from './manta.ts';
import {
  cameraBasis,
  cloudBasis,
  emberColor,
  projectCloudPointInto,
  scratchProjected,
  type CameraPose,
  type CloudPoint,
  type Projected,
  type Vec3,
} from './space.ts';
import { SYN_CYAN, SYN_MAGENTA, SYN_WHITE, synGlowTexture } from './style.ts';
import { hash01 } from '@be-music/player-skin-sdk';
import { pointLayerFor } from '../pixi-kit/index.ts';
 
/**
 * Shared Synesthesia drawing: hairline frames with lock-on corners (a rhythm-shooter targeting reticle) and projected point
 * clouds. Callers own the `Graphics`; these only append geometry.
 */
 
/** Most grains one square point breaks into. */
const MAX_GRAINS = 5;
 
/**
 * Where the grains of a point sit, as fractions of the point's size: a golden-angle spiral, so a cluster of any count
 * fills the point's square evenly without lining up into a pattern.
 */
export const GRAIN_OFFSETS: Float32Array = (() => {
  const offsets = new Float32Array(MAX_GRAINS * 2);
  for (let index = 0; index < MAX_GRAINS; index += 1) {
    const radius = index === 0 ? 0 : 0.42 * Math.sqrt(index / (MAX_GRAINS - 1));
    const angle = index * 2.39996;
    offsets[index * 2] = Math.cos(angle) * radius;
    offsets[index * 2 + 1] = Math.sin(angle) * radius;
  }
  return offsets;
})();
 
/**
 * How a square point of `size` px and `alpha` breaks into fine grains: each grain is about half the point's size
 * (0.6–1.1 px), there are as many as it takes to cover a share of the point (1–5), and their alpha is set so the
 * cluster gives off about the light the point did. Pure.
 */
export function grainsFor(size: number, alpha: number, out: Grains = { count: 0, size: 0, alpha: 0 }): Grains {
  const grain = Math.max(0.6, Math.min(1.1, size * 0.5));
  const count = Math.max(1, Math.min(MAX_GRAINS, Math.round((size / grain) ** 2 * 0.45)));
  out.count = count;
  out.size = grain;
  out.alpha = Math.min(1, (alpha * size * size * 0.8) / (count * grain * grain));
  return out;
}
 
/** How a mark breaks into grains: their count, size and alpha. */
export interface Grains {
  count: number;
  size: number;
  alpha: number;
}
 
/** How a segment breaks into grains: {@link Grains} laid in `lanes` parallel lanes. */
export interface TrailGrains extends Grains {
  lanes: number;
}
 
/** Scratch results the batch's hot paths write grains into, so a frame of thousands of points allocates none. */
const SCRATCH_GRAINS: Grains = { count: 0, size: 0, alpha: 0 };
const SCRATCH_TRAIL: TrailGrains = { count: 0, size: 0, alpha: 0, lanes: 0 };
 
/** Most grains one segment breaks into. */
const MAX_TRAIL_GRAINS = 32;
 
/** Most parallel lanes a wide segment's grains spread over. */
const MAX_TRAIL_LANES = 3;
 
/**
 * How a segment `length` px long and `width` px thick breaks into a trail of fine grains: grains about a pixel across,
 * spaced about 1.6 px apart (up to MAX_TRAIL_GRAINS per lane), laid in 1–3 parallel lanes across the stroke's width,
 * with their alpha set so the trail gives off about the light the stroke did. Pure.
 */
export function trailGrainsFor(
  length: number,
  width: number,
  alpha: number,
  out: TrailGrains = { count: 0, size: 0, alpha: 0, lanes: 0 },
): TrailGrains {
  const grain = Math.max(0.6, Math.min(1.1, width * 0.6));
  const count = Math.max(1, Math.min(MAX_TRAIL_GRAINS, Math.round(length / 1.6) + 1));
  const lanes = Math.max(1, Math.min(MAX_TRAIL_LANES, Math.round(width / 1.5)));
  const area = Math.max(grain * grain, length * width);
  out.count = count;
  out.lanes = lanes;
  out.size = grain;
  out.alpha = Math.min(1, (alpha * area * 0.8) / (count * lanes * grain * grain));
  return out;
}
 
/**
 * Batches thousands of tiny additive shapes into a handful of draw instructions: rects and line segments are bucketed
 * by (target graphics, colour quantized to 4 bits per channel, alpha quantized to eighths, stroke width) and emitted as
 * one `fill` / `stroke` per bucket on {@link flush}. Emission order is bucket order, so only use it where overlap order does not matter
 * (additive light).
 */
export class ShapeBatch {
  /**
   * @param points When true, square rects are drawn as particles on the target's {@link pointLayerFor point layer}
   *   instead of `Graphics` geometry. Off for tests and for targets outside the scene graph.
   */
  private readonly points: boolean;
 
  public constructor(points = false) {
    this.points = points;
  }
 
  // Buckets are keyed by a packed integer and kept across flushes (only their data is reset), so a steady frame
  // allocates no keys, buckets, or arrays.
  private readonly rects = new Map<number, ShapeBucket>();
  private readonly lines = new Map<number, ShapeBucket>();
  private readonly ids = new Map<Graphics, number>();
  private readonly targets: Graphics[] = [];
 
  private id(graphics: Graphics): number {
    let id = this.ids.get(graphics);
    if (id === undefined) {
      id = this.targets.length;
      this.ids.set(graphics, id);
      this.targets.push(graphics);
    }
    return id;
  }
 
  public rect(graphics: Graphics, rawColor: number, alpha: number, x: number, y: number, w: number, h: number): void {
    const eighths = Math.round(Math.min(1, alpha) * 8);
    if (eighths <= 0) return;
    Iif (this.points && w === h) {
      // Square points become GPU particles (exact colour and alpha, no geometry rebuild), broken into fine grains so
      // every particle in the skin shares the audio orb's fine, dusty texture.
      const layer = pointLayerFor(graphics);
      const grains = grainsFor(w, Math.min(1, alpha), SCRATCH_GRAINS);
      const cx = x + w / 2;
      const cy = y + h / 2;
      layer.cluster(cx, cy, GRAIN_OFFSETS, grains.count, w, grains.size, rawColor, grains.alpha);
      return;
    }
    const key = (this.id(graphics) * 9 + eighths) * 4096 + colorIndex(rawColor);
    let bucket = this.rects.get(key);
    if (!bucket) {
      bucket = { target: this.id(graphics), color: quantizeColor(rawColor), alpha: eighths / 8, width: 0, data: [] };
      this.rects.set(key, bucket);
    }
    bucket.data.push(x, y, w, h);
  }
 
  /**
   * A soft glow sprite `size` px across centred on `(cx, cy)`, on its own particle layer next to `graphics`. Only drawn
   * in points mode; elsewhere (tests, targets outside the scene graph) it is skipped.
   */
  public glow(graphics: Graphics, color: number, alpha: number, cx: number, cy: number, size: number): void {
    if (!this.points || alpha <= 0.004 || size <= 0) return;
    pointLayerFor(graphics, synGlowTexture()).point(cx, cy, size, color, Math.min(1, alpha));
  }
 
  public line(
    graphics: Graphics,
    rawColor: number,
    alpha: number,
    width: number,
    x0: number,
    y0: number,
    x1: number,
    y1: number,
  ): void {
    const eighths = Math.round(Math.min(1, alpha) * 8);
    Iif (eighths <= 0) return;
    Iif (this.points) {
      // Segments break into a trail of fine grains too, so trails, fish and sparks share the dusty texture.
      const dx = x1 - x0;
      const dy = y1 - y0;
      const length = Math.sqrt(dx * dx + dy * dy);
      const grains = trailGrainsFor(length, width, Math.min(1, alpha), SCRATCH_TRAIL);
      const layer = pointLayerFor(graphics);
      // Wide strokes lay their grains in parallel lanes across the width, so a fatter stroke reads wider, not brighter.
      const nx = length > 0 ? -dy / length : 0;
      const ny = length > 0 ? dx / length : 0;
      for (let lane = 0; lane < grains.lanes; lane += 1) {
        const across = (lane - (grains.lanes - 1) / 2) * (width / grains.lanes);
        layer.trail(x0 + nx * across, y0 + ny * across, dx, dy, grains.count, grains.size, rawColor, grains.alpha);
      }
      return;
    }
    this.strokeLine(graphics, rawColor, eighths, width, x0, y0, x1, y1);
  }
 
  /**
   * A solid stroked segment, never broken into grains: for motion streaks such as the warp's speed lines, which have
   * to read as continuous light.
   */
  public streak(
    graphics: Graphics,
    rawColor: number,
    alpha: number,
    width: number,
    x0: number,
    y0: number,
    x1: number,
    y1: number,
  ): void {
    const eighths = Math.round(Math.min(1, alpha) * 8);
    if (eighths <= 0) return;
    this.strokeLine(graphics, rawColor, eighths, width, x0, y0, x1, y1);
  }
 
  private strokeLine(
    graphics: Graphics,
    rawColor: number,
    eighths: number,
    width: number,
    x0: number,
    y0: number,
    x1: number,
    y1: number,
  ): void {
    const halfSteps = Math.min(63, Math.max(1, Math.round(width * 2)));
    const key = ((this.id(graphics) * 9 + eighths) * 64 + halfSteps) * 4096 + colorIndex(rawColor);
    let bucket = this.lines.get(key);
    Eif (!bucket) {
      bucket = {
        target: this.id(graphics),
        color: quantizeColor(rawColor),
        alpha: eighths / 8,
        width: halfSteps / 2,
        data: [],
      };
      this.lines.set(key, bucket);
    }
    bucket.data.push(x0, y0, x1, y1);
  }
 
  public flush(): void {
    for (const bucket of this.rects.values()) {
      const { data } = bucket;
      Iif (data.length === 0) continue;
      const graphics = this.targets[bucket.target]!;
      for (let index = 0; index < data.length; index += 4) {
        graphics.rect(data[index]!, data[index + 1]!, data[index + 2]!, data[index + 3]!);
      }
      graphics.fill({ color: bucket.color, alpha: bucket.alpha });
      data.length = 0;
    }
    for (const bucket of this.lines.values()) {
      const { data } = bucket;
      Iif (data.length === 0) continue;
      const graphics = this.targets[bucket.target]!;
      for (let index = 0; index < data.length; index += 4) {
        graphics.moveTo(data[index]!, data[index + 1]!).lineTo(data[index + 2]!, data[index + 3]!);
      }
      graphics.stroke({ color: bucket.color, width: bucket.width, alpha: bucket.alpha });
      data.length = 0;
    }
    // Pooled graphics can be handed out in a different order next frame; re-learn the targets each flush.
    this.ids.clear();
    this.targets.length = 0;
    Iif (this.rects.size + this.lines.size > 4096) {
      this.rects.clear();
      this.lines.clear();
    }
  }
}
 
/**
 * One batch shared by every Synesthesia renderer. Renderers draw synchronously and flush before returning, so sharing
 * is safe and lets steady frames reuse its buckets instead of allocating a batch per call.
 */
export const sharedShapeBatch: ShapeBatch = new ShapeBatch(true);
 
interface ShapeBucket {
  target: number;
  color: number;
  alpha: number;
  width: number;
  data: number[];
}
 
/** 12-bit index of a colour's {@link quantizeColor} bucket (the top nibble of each channel). */
function colorIndex(color: number): number {
  return ((color >> 12) & 0xf00) | ((color >> 8) & 0xf0) | ((color >> 4) & 0xf);
}
 
/** `color` snapped to 16 levels per channel (bucket-friendly, visually identical for light). */
function quantizeColor(color: number): number {
  return (color & 0xf0f0f0) | 0x080808;
}
 
/**
 * Lock-on reticle: four rounded corner brackets around `(x, y, w, h)` and an optional centre cross. `arm` is the
 * bracket length. `crossAngle` turns the cross about the centre in radians, in screen space (y points down), so a
 * positive angle turns it clockwise on screen and a negative one counter-clockwise.
 */
export function drawReticle(
  graphics: Graphics,
  x: number,
  y: number,
  w: number,
  h: number,
  color: number,
  alpha: number,
  options: { arm?: number; width?: number; cross?: boolean; crossAngle?: number } = {},
): void {
  const arm = Math.min(options.arm ?? 10, w / 2, h / 2);
  const width = options.width ?? 1.5;
  const right = x + w;
  const bottom = y + h;
  const bend = Math.min(3, arm / 2);
  graphics
    .moveTo(x, y + arm)
    .lineTo(x, y + bend)
    .quadraticCurveTo(x, y, x + bend, y)
    .lineTo(x + arm, y)
    .moveTo(right - arm, y)
    .lineTo(right - bend, y)
    .quadraticCurveTo(right, y, right, y + bend)
    .lineTo(right, y + arm)
    .moveTo(right, bottom - arm)
    .lineTo(right, bottom - bend)
    .quadraticCurveTo(right, bottom, right - bend, bottom)
    .lineTo(right - arm, bottom)
    .moveTo(x + arm, bottom)
    .lineTo(x + bend, bottom)
    .quadraticCurveTo(x, bottom, x, bottom - bend)
    .lineTo(x, bottom - arm)
    // Square caps reach as far as round ones would; at these hairline widths the rounding is under a pixel, and Pixi
    // builds a round cap from a fan of segments for every arm end of every reticle, every frame.
    .stroke({ color, width, alpha, cap: 'square' });
  if (options.cross) {
    const cx = x + w / 2;
    const cy = y + h / 2;
    const size = Math.min(w, h) * 0.08 + 2;
    const angle = options.crossAngle ?? 0;
    // One arm runs along (dx, dy), the other along its perpendicular (-dy, dx).
    const dx = size * Math.cos(angle);
    const dy = size * Math.sin(angle);
    graphics
      .moveTo(cx - dx, cy - dy)
      .lineTo(cx + dx, cy + dy)
      .moveTo(cx + dy, cy - dx)
      .lineTo(cx - dy, cy + dx)
      .stroke({ color, width: 1, alpha });
  }
}
 
/** A near-black frame with a warm hairline rim and bright lock-on corners — a targeting-HUD take on a panel. */
export function drawFrame(
  graphics: Graphics,
  x: number,
  y: number,
  w: number,
  h: number,
  rim: number,
  options: { fill?: number; arm?: number; emphasis?: boolean } = {},
): void {
  drawGlassSurface(graphics, x, y, w, h, options.fill ?? 0.96);
  graphics.rect(x, y, w, h).stroke({ color: rim, width: 1, alpha: options.emphasis ? 0.65 : 0.22 });
  drawReticle(graphics, x - 1, y - 1, w + 2, h + 2, SYN_WHITE, options.emphasis ? 0.9 : 0.3, {
    arm: options.arm ?? 9,
    width: 1.25,
  });
}
 
export interface CloudTransform {
  /** Uniform scale applied to the unit shape. */
  scale: number;
  /** World offset after rotation. */
  x: number;
  y: number;
  z: number;
  yaw: number;
  pitch?: number;
}
 
/**
 * Projects `points` through (scale → yaw / pitch → offset) into screen space and draws each as a tiny additive-ready
 * square — nearer and heavier points are bigger and brighter. `colorOf` picks a colour per point; `shimmer` (0..1)
 * flickers individual points over time so the cloud looks alive. `skip` lets the caller drop points (e.g. inside a
 * live BGA).
 */
const CLOUD_BASIS = cloudBasis({ scale: 1, x: 0, y: 0, z: 0, yaw: 0 });
const CLOUD_CAMERA = cameraBasis({ x: 0, y: 0, z: 0, yaw: 0, pitch: 0 });
const CLOUD_PROJECTED = scratchProjected();
 
export function drawPointCloud(
  graphics: Graphics,
  points: readonly CloudPoint[],
  transform: CloudTransform,
  view: { cx: number; cy: number; focal: number; camera?: CameraPose; orbit?: number },
  style: {
    colorOf: (point: CloudPoint, index: number) => number;
    alpha: number;
    size: number;
    seconds?: number;
    shimmer?: number;
    /** Perspective scale at which `size` / `alpha` apply 1:1 (default 1) — set it near the cloud's depth. */
    referenceScale?: number;
    /** Heavy points also get a faint square halo this many times their size. */
    bokeh?: number;
    skip?: (x: number, y: number) => boolean;
  },
): void {
  const reference = style.referenceScale ?? 1;
  const seconds = style.seconds ?? 0;
  const shimmer = style.shimmer ?? 0;
  const batch = sharedShapeBatch;
  // The transform's and the camera's sines and cosines once per cloud, and one scratch result for every point.
  const cloud = cloudBasis(transform, CLOUD_BASIS);
  const camera = view.camera ? cameraBasis(view.camera, CLOUD_CAMERA) : undefined;
  const projected = CLOUD_PROJECTED;
  for (let index = 0; index < points.length; index += 1) {
    const point = points[index]!;
    projectCloudPointInto(
      projected,
      point.x,
      point.y,
      point.z,
      cloud,
      camera,
      view.cx,
      view.cy,
      view.focal,
      view.orbit,
    );
    if (!projected.visible) continue;
    if (style.skip?.(projected.x, projected.y)) continue;
    const flicker = shimmer > 0 ? 1 - shimmer * (0.5 + 0.5 * Math.sin(seconds * 7 + index * 2.39)) : 1;
    const depth = projected.scale / reference;
    const alpha = style.alpha * point.weight * flicker * Math.min(1.4, depth);
    if (alpha < 0.02) continue;
    const size = Math.max(0.6, style.size * (0.5 + point.weight) * depth);
    const color = style.colorOf(point, index);
    if (style.bokeh && point.weight > 0.75) {
      const halo = size * style.bokeh;
      batch.rect(
        graphics,
        color,
        Math.min(1, alpha) * 0.12,
        projected.x - halo / 2,
        projected.y - halo / 2,
        halo,
        halo,
      );
    }
    batch.rect(graphics, color, Math.min(1, alpha), projected.x - size / 2, projected.y - size / 2, size, size);
  }
  batch.flush();
}
 
/**
 * Draws a school of boids as fish of light: a tapering streak trailing each boid along its heading with a hot head,
 * nearer fish larger and brighter. `project` maps a world point to screen (camera + perspective); `skip` drops fish
 * (e.g. over a live BGA). `palette` picks the school's light: ember (with the odd blue fish), electric blue, or magenta.
 */
export function drawSchool(
  graphics: Graphics,
  flock: Flock,
  /** Projects `point` into `out` and returns it. */
  project: (out: Projected, point: Vec3) => Projected,
  style: {
    alpha: number;
    palette?: 'ember' | 'blue' | 'magenta';
    skip?: (x: number, y: number) => boolean;
    /** 0..1: how hard the latest kick is flicking every manta up, wings flung wide and white-hot (see stepKick). */
    swell?: number;
    /** 0..1: the level of the school's range of the music (bass, mids, or highs); the glow brightens and spreads with it. */
    glowLevel?: number;
    /** Scene clock (s) that beats the wings. */
    seconds?: number;
  },
): void {
  const palette = style.palette ?? 'ember';
  // On a kick each manta flicks up: wider, harder-beating wings, a thicker outline, flashing white.
  const swell = Math.max(0, Math.min(1, style.swell ?? 0));
  const girth = 1 + 1.2 * swell;
  const seconds = style.seconds ?? 0;
  // The glow follows the school's range of the music: a faint halo while it is quiet, bright and wide when it is loud —
  // while the kick drives the swell.
  const level = Math.max(0, Math.min(1, style.glowLevel ?? 0));
  const glowGain = (0.3 + 1.2 * level) * (1 + 0.7 * swell);
  const glowSpread = (1 + 0.4 * level) * (1 + 0.5 * swell);
  const { position: p, velocity: v } = flock;
  const batch = sharedShapeBatch;
  const at = SCHOOL_SCRATCH_POSITION;
  const heading = SCHOOL_SCRATCH_VELOCITY;
  for (let index = 0; index < flock.count; index += 1) {
    at.x = p[index * 3]!;
    at.y = p[index * 3 + 1]!;
    at.z = p[index * 3 + 2]!;
    const center = project(SCHOOL_CENTER, at);
    if (!center.visible) continue;
    if (style.skip?.(center.x, center.y)) continue;
    heading.x = v[index * 3]!;
    heading.y = v[index * 3 + 1]!;
    heading.z = v[index * 3 + 2]!;
    // Each manta beats its wings out of step with the rest of the school.
    const shape = mantaShapeInto(SCHOOL_MANTA, at, heading, seconds, hash01(index * 7 + 1) * Math.PI * 2, swell);
    const nose = project(SCHOOL_NOSE, shape.nose);
    const leftTip = project(SCHOOL_LEFT_TIP, shape.leftTip);
    const rightTip = project(SCHOOL_RIGHT_TIP, shape.rightTip);
    const tailRoot = project(SCHOOL_TAIL_ROOT, shape.tailRoot);
    const tailEnd = project(SCHOOL_TAIL_END, shape.tailEnd);
    if (!nose.visible || !leftTip.visible || !rightTip.visible || !tailRoot.visible) continue;
    const nearness = Math.min(1, center.scale * 2.4);
    const heat = hash01(index * 5 + 3);
    const color =
      palette === 'blue'
        ? heat > 0.75
          ? SYN_WHITE
          : SYN_CYAN
        : palette === 'magenta'
          ? heat > 0.8
            ? 0xffb3d9
            : SYN_MAGENTA
          : index % 7 === 0
            ? SYN_CYAN
            : emberColor(0.55 + 0.4 * heat);
    const alpha = style.alpha * (0.35 + 0.65 * nearness) * (1 + 0.8 * swell);
    const lit = swell > 0.01 ? mixColor(color, SYN_WHITE, Math.min(1, swell * 1.2)) : color;
    // Every manta carries a soft halo, swelling with its range of the music and blooming on a kick.
    batch.glow(
      graphics,
      lit,
      style.alpha * (0.1 + 0.25 * nearness) * glowGain,
      center.x,
      center.y,
      (12 + 26 * nearness) * glowSpread,
    );
    // The wings' outline: nose out to each wingtip and back in to the tail root, brighter along the leading edges.
    const edge = (0.8 + 1.4 * nearness) * girth;
    batch.line(graphics, lit, alpha, edge, nose.x, nose.y, leftTip.x, leftTip.y);
    batch.line(graphics, lit, alpha, edge, nose.x, nose.y, rightTip.x, rightTip.y);
    batch.line(graphics, lit, alpha * 0.55, edge * 0.7, leftTip.x, leftTip.y, tailRoot.x, tailRoot.y);
    batch.line(graphics, lit, alpha * 0.55, edge * 0.7, rightTip.x, rightTip.y, tailRoot.x, tailRoot.y);
    if (tailEnd.visible) {
      batch.line(graphics, lit, alpha * 0.35, edge * 0.5, tailRoot.x, tailRoot.y, tailEnd.x, tailEnd.y);
    }
    const size = (1.2 + 2 * nearness) * (1 + 1.2 * swell);
    batch.rect(
      graphics,
      heat > 0.8 ? SYN_WHITE : lit,
      Math.min(1, alpha * 1.3),
      nose.x - size / 2,
      nose.y - size / 2,
      size,
      size,
    );
  }
  batch.flush();
}
 
/** Scratch state for {@link drawSchool}, reused every frame. */
const SCHOOL_SCRATCH_POSITION: Vec3 = { x: 0, y: 0, z: 0 };
const SCHOOL_SCRATCH_VELOCITY: Vec3 = { x: 0, y: 0, z: 0 };
const SCHOOL_MANTA = createMantaShape();
const SCHOOL_CENTER = scratchProjected();
const SCHOOL_NOSE = scratchProjected();
const SCHOOL_LEFT_TIP = scratchProjected();
const SCHOOL_RIGHT_TIP = scratchProjected();
const SCHOOL_TAIL_ROOT = scratchProjected();
const SCHOOL_TAIL_END = scratchProjected();
 
/** `from` blended toward `to` by `t` (0..1), per RGB channel. */
function mixColor(from: number, to: number, t: number): number {
  const r = Math.round(((from >> 16) & 255) + (((to >> 16) & 255) - ((from >> 16) & 255)) * t);
  const g = Math.round(((from >> 8) & 255) + (((to >> 8) & 255) - ((from >> 8) & 255)) * t);
  const b = Math.round((from & 255) + ((to & 255) - (from & 255)) * t);
  return (r << 16) | (g << 8) | b;
}