Skip to content

Three.js playback ​

ReplayLayer adds travelers, utilization halos, and directional flows to your THREE.Scene. You own the canvas, renderer, camera, and rendering policy. A result contains recorded movement; stationary agents are represented by occupancy rather than an animated traveler mesh.

Install three, import the package stylesheet once, and pass a completed result:

ts
import type { RunResult } from '@grabm/abm'
import {
  PlaybackController,
  getPlaybackActivityIntervals,
  ReplayLayer,
  mountPlaybackControls,
  type PlaybackControlsHandle,
} from '@grabm/abm/playback'
import type { Scene } from 'three'
import '@grabm/abm/playback/styles.css'

export function mountPlayback(
  scene: Scene,
  controlsHost: HTMLElement,
  result: RunResult,
  render: () => void,
) {
  const layer = new ReplayLayer({ scene, result, onInvalidate: render })
  const { startMinute, durationMinutes } = result.input.run
  const handles: { controls?: PlaybackControlsHandle } = {}
  const controller = new PlaybackController({
    startMinute,
    activityIntervals: getPlaybackActivityIntervals(result),
    skipInactiveTime: false,
    endMinute: startMinute + durationMinutes,
    simulationMinutesPerSecond: 5,
    onFrame(minute) {
      layer.seek(minute)
      render()
    },
    onStateChange(state) {
      handles.controls?.update(state)
    },
  })
  handles.controls = mountPlaybackControls(controlsHost, {
    controller,
    startMinute,
    endMinute: startMinute + durationMinutes,
    rateDisplay: 'both',
  })
  function refreshTheme() {
    const root = document.documentElement
    const css = getComputedStyle(root)
    const color = (name: string) => css.getPropertyValue(name).trim()
    layer.setTheme(root.dataset['theme'] === 'light' ? 'light' : 'dark', {
      agents: Object.fromEntries(
        ['walk', 'bike', 'road', 'transit'].map((mode) => [
          mode,
          color(`--graph-agent-${mode}`),
        ]),
      ),
      utilization: color('--graph-utilization-normal'),
      overCapacity: color('--graph-utilization-over'),
      flow: color('--graph-flow-normal'),
    })
    layer.seek(controller.getState().minute)
    render()
  }
  refreshTheme()
  document.addEventListener('grabm:themechange', refreshTheme)
  return {
    controller,
    dispose() {
      document.removeEventListener('grabm:themechange', refreshTheme)
      controller.dispose()
      handles.controls?.dispose()
      layer.dispose()
      render()
    },
  }
}

Clock and controls ​

PlaybackController requires simulationMinutesPerSecond. The recipe uses 5; the speed selector multiplies that rate. seek(minute) is clamped to the run interval. onFrame fires during construction, so callbacks must not read an uninitialized controller. Controls receive subsequent state through controls.update(state).

For a clock or DOM controls without Three.js, import from @grabm/abm/playback/headless. In Node, inject frame scheduling callbacks before calling play(); default scheduling uses browser animation frames.

Skip inactive time ​

The controls include Skip inactive time, unchecked by default. Supply activityIntervals: getPlaybackActivityIntervals(result) when constructing the controller to enable the checkbox. Both APIs are exported from @grabm/abm/playback and @grabm/abm/playback/headless, so hosts such as PreFORM can use them without adopting this site's renderer or UI.

The helper builds the union of actual recorded edge-traversal intervals. A period is inactive when no agent is moving; stationary occupancy and dwell do not count as movement. For other kinds of visible activity, supply your own PlaybackActivityInterval[] using startMinute and endMinute in simulation minutes. Intervals are copied, sorted, and merged; zero-length intervals are ignored and invalid times throw. Do not use zero-length markers for instantaneous events; include an interval around events your renderer needs to display.

Set skipInactiveTime: true to opt in initially, or call controller.setSkipInactiveTime(true) at runtime. This only changes automatic playback: manual seek() remains exact, paused playback stays paused, and speed continues to apply within active intervals. Across a gap, the clock lands at the next active interval's start; unused frame time is discarded so a short upcoming interval is not skipped entirely. If no activity remains, playback goes to the end and pauses. Playing again restarts normally.

Use setActivityIntervals(intervals) when replacing a result. An empty array means the timeline is known to have no movement. Omitting intervals, or setting them to undefined, means activity is unknown: automatic skipping is disabled and the checkbox is unavailable. State exposes skipInactiveTime (the preference) and canSkipInactiveTime (whether activity information is available).

For streamed datasets, provide activity intervals covering the complete timeline from the host or a full run; a single loaded replay window cannot establish that later time is inactive. Skipped-to frames still go through prepareFrame, preserving buffering, cancellation, errors, and retry behavior. This feature does not add an activity index to the stored dataset format.

For a button presentation, pass skipInactiveControl: 'toggle' to mountPlaybackControls. It uses an outlined circle when off and a filled circle when on, with aria-pressed for assistive technology. The examples use this style; the default library presentation remains a checkbox.

Theme and lifetime ​

The recipe reads the shared grABM semantic tokens from the document root and calls setTheme on grabm:themechange. An external host can define the same semantic tokens or adapt the palette callback to its own theme. CSS alone cannot recolor GPU materials.

Dispose the clock, controls, layer, and theme listener when removing a result. The layer removes its own scene objects and disposes its geometry/materials. Your host must separately dispose its own renderer and other resources.

Your application provides the renderer and camera; see the application implementation. API reference includes custom geometry resolvers.

Compressed activity timelines ​

With Skip inactive enabled, the native controls allocate their scrubber width only to complete activity intervals. Tooltips and output times remain simulation clock times. Changing the toggle does not seek; direct controller.seek(minute) remains exact. Unknown coverage keeps the full axis, while known empty coverage disables seeking in the compressed scrubber.

Custom renderers can use controller.getTimelineScale() or import createPlaybackTimelineScale(startMinute, endMinute, activityIntervals?) from @grabm/abm/playback/headless. Omit intervals for a full axis. toPosition(minute) maps clock time to cumulative visible minutes; toMinute(position, bias?) maps back. At a removed gap, the default forward bias selects the next interval start; backward selects the preceding end. Use projectRange for buffered ranges, chart buckets and chapters so they share the same axis. The scale is immutable and can be cached between clock updates. PreFORM-specific chapter inference and visual styling remain host responsibilities.

Documentation for the grABM library.