All files / player-browser/src/view/beatoraja/play markers.ts

92.94% Statements 79/85
78.57% Branches 66/84
100% Functions 7/7
95.83% Lines 69/72

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                                                                                                                                                                                                            22x                 22x 22x     22x 22x                                                                                       19x 11x 11x       11x 11x 11x                           11x 44x                     9x 44x 44x 44x 10x 10x 25x 25x 25x 6x 5x 19x     23x               25x 25x         22x 22x 25x 21x 21x         21x 21x 21x 21x 21x 21x 21x 21x       11x 11x 9x   9x                           13x 13x                                   88x 9x 9x 9x 10x 10x   10x     10x           10x     10x 10x         10x   10x 10x   9x       21x 21x 21x 21x 21x       21x       11x          
// Lane markers rendered alongside notes on the gameplay scene.
//
// Beatoraja's `note.group` / `note.bpm` / `note.stop` / `note.time` arrays describe how to draw
// per-event chart-time markers — section lines at every measure boundary, BPM-change indicator
// bars, STOP markers, and timed grid lines. Each entry is a destination-shaped record (`id`,
// `dst[]`, optional `op` / `r` / `g` / `b`) referencing an `image[]` for the visual.
//
// The renderer paints one sprite per (marker kind × event) at the matching beat, scrolled to the
// judgement line by the same hispeed math the note layer uses. Markers outside the visible lane
// area are culled.
 
import { Container, Sprite, type Texture } from 'pixi.js';
import { findFirstIndexNumberAtOrAfter } from '@be-music/shared-utils/core';
import {
  normalizeBeatorajaDestinations,
  type BeatorajaImageElement,
  type BeatorajaImageId,
} from '@be-music/skin-beatoraja';
import { createCroppedBeatorajaTexture, flipRectToPixi } from '../../../skin/beatoraja/render.ts';
import type { BeatorajaTextureCache } from '../../../skin/beatoraja/textures.ts';
import {
  isDrawnAtTime,
  isPastDrawWindow,
  resolveDrawBottom,
  resolveDrawY,
  type NoteDrawWindow,
} from '../../../chart/note-draw-window.ts';
import type { BeatorajaMarkerBeats } from '../../../chart/beatoraja/markers.ts';
 
interface MarkerKindData {
  /** Image element resolved from the destination's id. */
  image: BeatorajaImageElement | undefined;
  /** Texture cropped to the image's source-rect, ready for sprite assignment. */
  texture: Texture | undefined;
  /** Authored display rect — `dst[0]` of the destination. Position is replaced per-marker. */
  rect: { x: number; y: number; w: number; h: number };
  /** Authored tint / alpha (from `dst[0]`) — applied to every painted instance. */
  tint: number;
  alpha: number;
  /**
   * Pixi-Y offset between the marker's authored BOTTOM and the lane's authored BOTTOM, both
   * computed in Pixi-Y-DOWN screen coordinates. Mirrors upstream's `line.draw(sprite, time,
   * main, 0, (int) (y - hl))` pattern (`LaneRenderer.java:373, 387, 400, 414`):
   *
   *   - upstream `y` is the libGDX-Y-UP scroll position of the timeline.
   *   - `hl` is the lane's authored Y-UP bottom (= judge-line position).
   *   - the offset added to the line's authored Y-UP position is `y - hl`.
   *   - so the rendered line Y-UP bottom = `authored_line_y + (y - hl)`.
   *
   * Re-derived in Pixi: `rendered_pixi_bottom = scroll_pixi + (M_authored - L_authored)`,
   * where `M_authored` / `L_authored` are the Pixi-Y bottoms of the marker / lane in their
   * authored positions. This `bottomOffsetFromLaneBottomPixi` field stores
   * `M_authored - L_authored` so the per-frame update can add it to `y` directly.
   *
   * For ModernChic the barline is authored at `y = NOTES_JUDGE_Y, h = 3` while the lane is
   * authored at `y = NOTES_JUDGE_Y - 12, h = LANE_LENGTH - 12`. After Y-flip the offset
   * resolves to `-12` (the barline sits 12 px above the lane bottom in Pixi). Without
   * honoring this, every barline painted at the lane's bottom edge instead of crossing
   * through the note head's middle, which is exactly the user-reported symptom of section
   * lines visually misaligning with note heads.
   */
  bottomOffsetFromLaneBottomPixi: number;
}
 
export interface BeatorajaMarkerLayerOptions {
  group: ReadonlyArray<Readonly<Record<string, unknown>>>;
  bpm: ReadonlyArray<Readonly<Record<string, unknown>>>;
  stop: ReadonlyArray<Readonly<Record<string, unknown>>>;
  time: ReadonlyArray<Readonly<Record<string, unknown>>>;
  /** `image[]` lookup for resolving destination ids → image elements. */
  images: ReadonlyMap<BeatorajaImageId, BeatorajaImageElement>;
  textures: BeatorajaTextureCache;
  /**
   * Skin canvas height in skin-pixel units. Used to flip the prototype rect's Y from libGDX
   * Y-UP into Pixi Y-DOWN, matching the note layer's lane rects and the play view's chrome.
   */
  canvasHeight: number;
  /**
   * Authored Pixi-Y of the lane's bottom edge (= upstream's `hl` after Y-flip into Pixi).
   * Computed once from `noteSection.dst[0]`'s flipped lane rects: `max(rect.y + rect.h)`.
   *
   * Used to compute each marker's bottom-offset-from-lane-bottom in Pixi space. Mirrors
   * upstream's barline draw pattern (`line.draw(sprite, ..., 0, y - hl)` in
   * `LaneRenderer.java:373`) where the line is offset relative to the lane bottom — markers
   * whose authored Y differs from the lane's bottom paint with that constant pixel gap so
   * they cross the lane at the authored offset (e.g., ModernChic's barlines cross through
   * the note head's MIDDLE rather than the note's bottom edge).
   *
   * `undefined` falls back to "treat marker bottom = scroll position", which is the previous
   * behaviour that misaligned ModernChic barlines by 12 px.
   */
  laneAuthoredBottomY?: number;
}
 
// `BEATORAJA_MARKER_PIXELS_PER_BEAT` (a fixed 72) used to live here for parity with the
// note layer's old constant. It was removed alongside the upstream-faithful scroll switch
// in `view/beatoraja/play/notes.ts` — the scroll distance per beat is now `laneHeight / 4 *
// hispeed` per upstream `LaneRenderer.java:271-276`. The gameplay caller computes the
// matching value via `beatorajaPixelsPerBeat()` and passes it through `update.args` so the
// marker layer stays in lock-step with the note layer.
 
export class BeatorajaMarkerLayer {
  readonly container: Container = new Container();
  /** Resolved per-kind prototype data. `[]` means the skin didn't author markers of that kind. */
  private readonly kindData: {
    group: MarkerKindData[];
    bpm: MarkerKindData[];
    stop: MarkerKindData[];
    time: MarkerKindData[];
  };
  /** Sprite pool — one entry per visible marker, reused across frames. */
  private readonly spritePool: Sprite[] = [];
  private firstFrameLogged = false;
 
  constructor(options: BeatorajaMarkerLayerOptions) {
    const laneBottom = options.laneAuthoredBottomY;
    this.kindData = {
      group: this.resolveKind(options.group, options.images, options.textures, options.canvasHeight, laneBottom),
      bpm: this.resolveKind(options.bpm, options.images, options.textures, options.canvasHeight, laneBottom),
      stop: this.resolveKind(options.stop, options.images, options.textures, options.canvasHeight, laneBottom),
      time: this.resolveKind(options.time, options.images, options.textures, options.canvasHeight, laneBottom),
    };
  }
 
  /**
   * Paint markers for the current frame. `judgementY` and `pixelsPerBeat` are passed in so the
   * marker layer stays in lockstep with the note layer's scroll math (avoids visual drift when
   * the host tweaks judgement line or hispeed mid-play).
   */
  update(args: {
    currentBeat: number;
    judgementY: number;
    laneTopY: number;
    pixelsPerBeat: number;
    markers: BeatorajaMarkerBeats;
    /** Source BPM GUIDE controls both BPM-change and STOP lines. */
    bpmGuide?: boolean;
    /** Which of BPM GUIDE's lines to show; both BPM-change and STOP lines by default. */
    bpmGuideKinds?: { readonly bpm: boolean; readonly stop: boolean };
    /**
     * Lane distance from the playhead to a beat, in beats at scroll rate 1 — the note layer's `#SCROLL` / `#SPEED`
     * integrator, so bar lines move with the notes. Defaults to the beat difference.
     */
    distance?: (beat: number) => number;
    /**
     * The note layer's draw window. On a chart that scrolls it is beatoraja's `LaneRenderer` window: markers stop after
     * the first timeline past the lane top, one whose time has come is gone, and one a negative rate puts below the line
     * while its time is ahead still draws, down to the stage bottom. Otherwise it is LR2's: a marker scrolls down to the
     * judgement line and goes once the playhead has passed it, so one under a STOP that began on it stays on the line.
     * Omitted: every marker in the lane draws.
     */
    window?: NoteDrawWindow;
    /** Chart time of a beat, in seconds; with `window`, hides a marker whose time has come. */
    secondsAt?: (beat: number) => number;
    /**
     * Visual CONSTANT's opacity of a timeline at its chart time (`resolveConstantAlpha`), read through `secondsAt`; a
     * marker it gives 0 is not drawn. Omitted: every marker keeps its authored alpha.
     */
    alphaAt?: (seconds: number) => number;
  }): void {
    const distance = args.distance ?? ((beat: number): number => beat - args.currentBeat);
    const { window, secondsAt } = args;
    const drawBottom = window ? resolveDrawBottom(window, args.judgementY) : args.judgementY;
    // Under LR2's rules a marker goes once the playhead has passed it; a pixel of slack keeps the one just crossed for a
    // frame, on the line.
    // Past an LR2 negative-BPM reversal one the playhead passed before it stays gone as the scroll runs back.
    const passedBeat = (window?.reachedBeat ?? args.currentBeat) - 1 / Math.max(1, args.pixelsPerBeat);
    let used = 0;
    const ranges: ReadonlyArray<{ kind: MarkerKindData[]; beats: ReadonlyArray<number>; timed?: boolean }> = [
      { kind: this.kindData.group, beats: args.markers.group },
      {
        kind: this.kindData.bpm,
        beats: args.bpmGuide && args.bpmGuideKinds?.bpm !== false ? args.markers.bpm : [],
        timed: true,
      },
      {
        kind: this.kindData.stop,
        beats: args.bpmGuide && args.bpmGuideKinds?.stop !== false ? args.markers.stop : [],
        timed: true,
      },
      { kind: this.kindData.time, beats: args.markers.time },
    ];
    for (const { kind, beats, timed } of ranges) {
      if (kind.length === 0 || beats.length === 0) continue;
      // Iterate EVERY prototype with a resolved texture per marker kind. DP skins author one
      // destination per side (1P-side x, 2P-side x) for `group` / `bpm` / `stop` / `time` —
      // upstream `LaneRenderer.java:412-416` mirrors this with a `for (SkinImage line :
      // skin.getLine())` loop that draws each registered image. A previous `kind.find(...)`
      // short-circuit picked only the FIRST prototype and painted it at every beat, so DP
      // 2P-side measure lines / BPM-change / STOP / time markers never rendered. The user-
      // reported symptom: "2P 側に小節線や BPM 変更線が表示されない" on DP charts.
      // Under LR2's rules the beats (each list ascending) before `passedBeat` are gone, and once one draws above the lane
      // top every later one does too: the walk starts past the first and stops at the second, instead of visiting every
      // marker of the chart each frame.
      const lr2 = window !== undefined && window.rules !== 'beatoraja';
      const firstIndex = lr2 ? findFirstIndexNumberAtOrAfter(beats, passedBeat) : 0;
      const stopsAtTop = lr2 && args.pixelsPerBeat > 0;
      for (const proto of kind) {
        Iif (proto.texture === undefined) continue;
        for (let beatIndex = firstIndex; beatIndex < beats.length; beatIndex += 1) {
          const beat = beats[beatIndex]!;
          Iif (timed && window && secondsAt && secondsAt(beat) < window.nowSeconds) continue;
          if (window?.rules === 'beatoraja') {
            if (isPastDrawWindow(window, beat)) break;
            if (secondsAt && !isDrawnAtTime(window, secondsAt(beat))) continue;
          } else Iif (window && beat < passedBeat) {
            continue;
          }
          const scrollY = window
            ? resolveDrawY(window, args.judgementY - distance(beat) * args.pixelsPerBeat, args.judgementY)
            : args.judgementY - distance(beat) * args.pixelsPerBeat;
          // Apply the authored bottom offset relative to the lane's authored bottom — mirrors
          // upstream's `line.draw(..., 0, y - hl)` (`LaneRenderer.java:373`). Without this the
          // barline lands at the lane's BOTTOM EDGE instead of the authored bar position
          // (which for ModernChic is 12 px above the lane bottom, crossing through the note
          // head's middle).
          const y = scrollY + proto.bottomOffsetFromLaneBottomPixi;
          if (stopsAtTop && y < args.laneTopY - 24) break;
          // Cull markers outside the lane area. Test against the OFFSET y so a marker that sits
          // well above the lane bottom (e.g., a hypothetical "ceiling marker") doesn't get
          // culled prematurely. 24-pixel slack matches the note layer's culling so markers
          // don't pop in/out at the edge.
          Iif (y < args.laneTopY - 24 || y > drawBottom + 24) continue;
          const alpha = args.alphaAt && secondsAt ? args.alphaAt(secondsAt(beat)) : 1;
          if (alpha <= 0) continue;
          const sprite = this.acquireSprite(used);
          sprite.texture = proto.texture;
          // Anchor at the rect's BOTTOM-LEFT so the marker's bottom edge sits exactly on `y`.
          // Combined with the offset above, this puts the marker bottom at `scrollY + offset`
          // — i.e., the offset relative to where the timeline's scroll position is at this
          // beat, exactly mirroring upstream's `authored_marker_y + (scroll_y - lane_bottom_y)`.
          sprite.anchor.set(0, 1);
          sprite.x = proto.rect.x;
          sprite.y = y;
          sprite.width = proto.rect.w;
          sprite.height = Math.max(1, proto.rect.h);
          sprite.tint = proto.tint;
          sprite.alpha = proto.alpha * alpha;
          used += 1;
        }
      }
    }
    this.shrinkPoolTo(used);
    if (!this.firstFrameLogged && used > 0) {
      this.firstFrameLogged = true;
      // eslint-disable-next-line no-console
      console.log(
        '[beatoraja-markers] first frame painted',
        JSON.stringify({
          group: args.markers.group.length,
          bpm: args.markers.bpm.length,
          stop: args.markers.stop.length,
          time: args.markers.time.length,
          painted: used,
        }),
      );
    }
  }
 
  dispose(): void {
    Eif (!this.container.destroyed) this.container.destroy({ children: true });
    this.spritePool.length = 0;
  }
 
  // ─── Internals ────────────────────────────────────────────────────────────────────────────────
 
  /**
   * Resolve a marker-kind's authored destinations to a paintable prototype list. Each input
   * record is normalized through the standard destination pipeline (so `if[]` / `op[]` gates,
   * dst keyframes, etc. flow through), but only `dst[0]` is consumed — the marker's authored
   * appearance is the static rect; the renderer overrides Y per-beat anyway.
   */
  private resolveKind(
    inputs: ReadonlyArray<Readonly<Record<string, unknown>>>,
    images: ReadonlyMap<BeatorajaImageId, BeatorajaImageElement>,
    textures: BeatorajaTextureCache,
    canvasHeight: number,
    laneAuthoredBottomY: number | undefined,
  ): MarkerKindData[] {
    if (inputs.length === 0) return [];
    const groups = normalizeBeatorajaDestinations(inputs);
    const out: MarkerKindData[] = [];
    for (const group of groups) {
      const image = images.get(group.id);
      const baseTexture = image !== undefined ? textures.get(image.src) : undefined;
      const texture =
        image !== undefined && baseTexture !== undefined
          ? createCroppedBeatorajaTexture(baseTexture, { x: image.x, y: image.y, w: image.w, h: image.h })
          : undefined;
      const dst0 = group.dst[0];
      // beatoraja's `dst[]` is libGDX Y-UP; flip into Pixi Y-DOWN to match the rest of the
      // pipeline. The flipped rect's `y + h` is the marker's authored Pixi BOTTOM, which we
      // diff against the lane's authored Pixi bottom to mirror upstream's `(y - hl)` offset
      // (`LaneRenderer.java:373`).
      const rect =
        dst0 !== undefined
          ? flipRectToPixi({ x: dst0.x, y: dst0.y, w: dst0.w, h: dst0.h }, canvasHeight)
          : { x: 0, y: 0, w: 0, h: 0 };
      const tint = dst0 !== undefined ? ((dst0.r & 0xff) << 16) | ((dst0.g & 0xff) << 8) | (dst0.b & 0xff) : 0xffffff;
      const alpha = dst0 !== undefined ? Math.max(0, Math.min(1, dst0.a / 255)) : 1;
      // Compute the constant Pixi-Y delta between the marker's authored bottom and the lane's
      // authored bottom. Falls back to 0 when the caller didn't supply a lane bottom — that
      // preserves the previous "marker bottom = scroll position" behaviour for tests / hosts
      // that haven't wired the new arg yet.
      const markerAuthoredBottomPixi = rect.y + rect.h;
      const bottomOffsetFromLaneBottomPixi =
        laneAuthoredBottomY !== undefined ? markerAuthoredBottomPixi - laneAuthoredBottomY : 0;
      out.push({ image, texture, rect, tint, alpha, bottomOffsetFromLaneBottomPixi });
    }
    return out;
  }
 
  private acquireSprite(index: number): Sprite {
    let s = this.spritePool[index];
    if (s === undefined) {
      s = new Sprite();
      this.spritePool.push(s);
      this.container.addChild(s);
    } else E{
      s.visible = true;
    }
    return s;
  }
 
  private shrinkPoolTo(used: number): void {
    for (let i = used; i < this.spritePool.length; i += 1) {
      this.spritePool[i]!.visible = false;
    }
  }
}