> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# TileFalling — data-driven performance flow

How the engine's game state and the falling-tile lane exchange data, and why it is cheap:
JS only publishes _what happened_; the UI runtime reads _plain numbers_ and derives everything else.

Sources: `packages/rhythm-engine/src/driver/game-state.ts`, `src/components/TileFalling.tsx`,
`src/components/tile-pool.worklet.ts`, `src/components/tile-note-status.ts`, `src/components/tile-chart-soa.ts`.

## 1. Threads and data ownership

```mermaid
flowchart LR
  subgraph JS["JS thread (judgement, React)"]
    J["Judgement / input"]
    H["TileFallingHandle<br/>consumeTile / pinHold / releaseHold"]
    SW["TileStatusWriter<br/>mirror + queue"]
    L["layoutsRef + consumedRef<br/>immutable SharedTileLayout"]
  end

  subgraph SHARED["Lock-free shared memory"]
    RING["Status ring<br/>head / tail / N slots (numbers)"]
    GS["GameState Float64Array [8]<br/>isRunning, ticksPerSecond, holdAtTick,<br/>tick, rate, epoch, multiplier, stamp"]
  end

  subgraph UI["UI runtime (frame callback)"]
    LANE["Lane frame callback<br/>single writer of GameState"]
    POOL["TilePoolState (slot pool)"]
    SOA["TileChartSoA<br/>columns by chartIndex"]
    REC["reconcileTiles"]
    SYS["Beam system then Body system<br/>putSprite(velocity x dt)"]
  end

  GPU["WebGPU sprite plane"]

  J --> H
  H -->|"setStatus / setPress"| SW
  H -.->|"synchronous geometry for FX"| J
  L --> H
  SW -->|"pump once per JS turn"| RING
  LANE -->|"writeGameState / freezeGameState"| GS
  GS -->|"readGameState (no alloc)"| REC
  RING -->|"drainStatusRing"| REC
  SOA --> REC
  REC <--> POOL
  POOL --> SYS
  SYS --> GPU
```

## 2. One frame on the UI runtime

```mermaid
sequenceDiagram
  autonumber
  participant LF as Lane frame callback
  participant GS as GameState block
  participant TS as Tile systems (beams, bodies)
  participant RT as reconcileTiles
  participant RG as Status ring
  participant SP as putSprite

  LF->>GS: writeGameState(isRunning, tick, rate, epoch, multiplier, stamp)
  TS->>GS: readGameState(out) - reused view
  TS->>RT: tick, now, tempo, rate, epoch, fresh
  RT->>RT: dt = min(now - pool.now, MAX_FRAME_DT)
  RT->>RT: pool.tick = fresh ? tick : tick + rate*dt
  RT->>RT: laneV = laneSpeedPx(rate, ticksPerPixel, tempo)
  alt tempo changed
    RT->>RT: rescaleForTempo
  end
  RT->>RT: advanceTiles (headY += v*dt)
  RT->>RT: advanceTileCursorWorklet (window start/end)
  RT->>RT: sweep culled range, release non-pinned slots
  alt epoch changed or lane parked while tick moved
    RT->>RT: anchorAllSlots (re-seat from chart)
  end
  RT->>RG: readHead (one cell while idle)
  RG-->>RT: new entries (status / press)
  RT->>RT: bindWindow if cursor moved
  RT->>RT: wakeVisibleSlots
  TS->>SP: write only awake slots
```

## 3. Status ring — the only JS to UI channel per note

```mermaid
flowchart TD
  A["Judgement event"] --> B{"status changed<br/>vs mirror?"}
  B -- no --> X["drop (no write)"]
  B -- yes --> C["encode entry<br/>chartId + chartIndex + status"]
  C --> Q["queue[]"]
  Q --> D["schedule pump<br/>once per JS turn"]
  D --> E{"head - tail <<br/>RING_SLOTS?"}
  E -- yes --> F["write slot cells first"]
  F --> G["publish head last"]
  E -- no, ring full --> R["retry(pump) later"]
  R --> E
  G --> H["UI: drainStatusRing"]
  H --> I{"entry chartId ==<br/>current chart?"}
  I -- no --> S["skip stale entry"]
  I -- yes --> U["apply status to slot<br/>CONSUMED / HOLDING / ENDING_FADE / ENDED"]
  U --> W["writeTail(consumed)"]
```

## 4. Slot lifecycle

```mermaid
stateDiagram-v2
  [*] --> Free
  Free --> Bound: bindWindow (cursor reaches chartIndex)
  Bound --> Awake: headY > -WAKE_MARGIN or pinned or fading
  Awake --> Falling: advanceTiles
  Falling --> Consumed: status CONSUMED
  Falling --> Holding: pinHold (press tick + tempo)
  Holding --> Fading: releaseHold fadeOut
  Holding --> Ended: releaseHold instant
  Fading --> Ended: finishFades
  Consumed --> Free: releaseSlot
  Falling --> Free: culled below startIndex
  Ended --> Free: releaseSlot
  Free --> Free: pool full, steal lowest non-pinned
```

## 5. Performance cost map (what is data, what is work)

| Stage              | Input data                            | Per-frame cost                     | Allocation             |
| ------------------ | ------------------------------------- | ---------------------------------- | ---------------------- |
| GameState write    | 8 numbers                             | 8 stores                           | none (positional args) |
| GameState read     | `Float64Array[8]`                     | 8 loads into reused view           | none                   |
| Status ring idle   | `head` cell                           | 1 lock-free read                   | none                   |
| Status ring active | new entries only                      | O(new entries)                     | none                   |
| `advanceTiles`     | pool columns, `laneV`, `dt`           | O(active slots)                    | none                   |
| Cursor advance     | `TileChartSoA` + `pool.tick`          | amortised O(1)                     | none                   |
| `bindWindow`       | only when cursor moved (`bindDirty`)  | O(entered tiles)                   | none                   |
| `anchorAllSlots`   | only on epoch bump / parked tick move | O(slots), rare                     | none                   |
| `wakeVisibleSlots` | `bodyAwake` flags                     | O(capacity) scan, early `continue` | none                   |
| Sprite writes      | awake slots only                      | O(visible)                         | none                   |

**Data-driven rules**

- `stamp` says which frame wrote the block, `isRunning` says whether to advance: no freshness guess.
- Tiles integrate `velocity x dt` and only re-anchor when `epoch` changes (seek, rewind, tempo jump).
- A stalled JS thread cannot delay a tile: the pool lives on the UI runtime and never reports back.
- Per-chart cost (`buildTileChartSoA`, layout) is paid once in `useEffect`, not per frame.

## 6. Metrics worth sampling

```mermaid
flowchart LR
  M1["frameDt, clamp hits<br/>(pool.frameDt)"] --> D["Perf overlay / DevTool"]
  M2["ring depth = head - tail<br/>+ retry count"] --> D
  M3["awake slots / bodyCapacity"] --> D
  M4["bindWindow calls per second"] --> D
  M5["anchorAllSlots calls (epoch bumps)"] --> D
  M6["stamp lag = now - GameState.stamp"] --> D
  M7["steal events (pool full)"] --> D
```

## 7. Cost per runtime — JS / Worklet (UI) / Worker / Native render

Qualitative budget from code reading, **not measured**. Fill the "measure" column from the sim
(`react-devtools-sim-profiling`, FX frame timer) before quoting numbers.

```mermaid
flowchart TB
  subgraph JSRT["JS thread (Hermes) — keep near idle during play"]
    direction TB
    JA["Judgement: consumeTile / pinHold / releaseHold<br/>binary search on layoutsRef, O(log n)"]
    JB["statusWriter.setStatus: mirror compare + queue push"]
    JC["pump once per JS turn:<br/>write slot cells, publish head"]
    JD["PER CHART only: buildTileSharedLayout + buildTileChartSoA<br/>then scheduleOnUI(installTileChartOnUI)"]
    JA --> JB --> JC
  end

  subgraph UIRT["UI runtime (worklets) — the per-frame hot path"]
    direction TB
    UA["Lane frame callback: writeGameState (8 stores)"]
    UB["readGameState into reused view"]
    UC["reconcileTiles:<br/>advanceTiles, cursor, cull, drainStatusRing,<br/>bindWindow if dirty, wakeVisibleSlots"]
    UD["Beam system then Body system:<br/>putSprite for awake slots"]
    UA --> UB --> UC --> UD
  end

  subgraph WORKER["Worker runtime 'sprite-atlas-pack'"]
    direction TB
    WA["packSpriteTexture<br/>about 550 MaxRects tries per sheet<br/>hundreds of ms, once per sheet"]
  end

  subgraph NATIVE["Native: render + audio"]
    direction TB
    NA["WebGPU sprite plane: upload dirty slots, draw"]
    NB["Native audio engine: noteOn fire-and-forget"]
  end

  JC -- "lock-free ring cells" --> UC
  JD -- "scheduleOnUI, once per chart" --> UC
  UD -- "queued sprite writes" --> NA
  JA -- "noteOn" --> NB
  WA -- "finished layout (async promise)" --> JD
```

| Runtime    | Work                            | Frequency                   | Scales with                | Risk if it grows                       | Measure                                     |
| ---------- | ------------------------------- | --------------------------- | -------------------------- | -------------------------------------- | ------------------------------------------- |
| JS         | judgement + status queue + pump | per tap / per JS turn       | taps per second            | blocks input, never delays tile motion | JS frame time during dense chord charts     |
| JS         | layout + SoA build              | per chart                   | note count                 | start-up hitch                         | ms in `useEffect` on song load              |
| UI worklet | GameState write/read            | every frame                 | constant (8 fields)        | negligible                             | none needed                                 |
| UI worklet | `reconcileTiles`                | every frame                 | active slots, ring entries | frame over budget drops lane FPS       | ms per frame, awake slots                   |
| UI worklet | `bindWindow` / `anchorAllSlots` | on cursor move / epoch bump | window size, capacity      | spike on seek or tempo jump            | calls per second, spike ms                  |
| UI worklet | sprite systems                  | every frame                 | awake slots                | dominates frame cost on dense charts   | sprites written per frame                   |
| Worker     | atlas pack                      | once per sheet              | sprite count               | none for gameplay if off-thread        | ms off-thread, fallback to JS if no runtime |
| Native     | GPU upload + draw               | every frame                 | dirty slots, sprite count  | GPU-bound frames                       | FX frame ms (about 3 ms in the sim)         |
| Native     | audio noteOn                    | per tap                     | polyphony                  | latency                                | tap to sound latency                        |

**Where the work moved in the new logic**

- Per note, JS now only writes one status entry. Slot binding, position and fade moved to the UI runtime.
- A stalled JS thread cannot delay a tile, because the pool is on the UI runtime and reads shared cells.
- The only heavy off-thread job is atlas packing, and it runs once per sheet, not per frame.
- Per-frame cost is therefore dominated by one place: the UI runtime (`reconcileTiles` plus sprite writes).

***

<small>Source: [`docs/tile-falling-performance-flow.md`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/docs/tile-falling-performance-flow.md)</small>
