@inventure71/paddockjs 2.0.0 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -1
- package/INSTALL_AND_UPDATE.md +10 -1
- package/README.md +92 -17
- package/docs/architecture.md +26 -16
- package/docs/component_inventory.md +72 -0
- package/docs/concepts.md +7 -5
- package/docs/custom_model_controller.md +2 -2
- package/docs/data_contract.md +121 -33
- package/docs/data_model.md +1 -1
- package/docs/index.md +10 -0
- package/docs/learnings.md +6 -6
- package/docs/rules.md +39 -9
- package/docs/sense_contract.md +59 -0
- package/docs/system_specs.md +76 -20
- package/docs/training.md +27 -20
- package/package.json +1 -1
- package/src/api/PaddockSimulatorController.js +75 -36
- package/src/app/BrowserExpertAdapter.js +9 -300
- package/src/app/BrowserExpertExternalRenderer.js +303 -0
- package/src/app/F1SimulatorApp.js +190 -68
- package/src/app/banners/raceDataBannerController.js +71 -36
- package/src/app/banners/stewardMessageController.js +5 -4
- package/src/app/camera/cameraConstants.js +2 -0
- package/src/app/camera/cameraController.js +86 -29
- package/src/app/camera/cameraGeometry.js +12 -1
- package/src/app/domBindings.js +89 -9
- package/src/app/layoutScheduler.js +27 -0
- package/src/app/layoutSupport.js +165 -0
- package/src/app/raceOverlayClearanceSupport.js +158 -0
- package/src/app/readouts/carOverviewRenderer.js +16 -8
- package/src/app/readouts/controlStateRenderer.js +1 -1
- package/src/app/readouts/raceStatusRenderer.js +30 -21
- package/src/app/readouts/readoutFormatters.js +2 -0
- package/src/app/readouts/telemetryRenderer.js +17 -8
- package/src/app/readouts/timingTowerRenderer.js +62 -10
- package/src/app/runtime/runtimeVisibility.js +66 -5
- package/src/config/cssValues.js +16 -0
- package/src/config/defaultOptions.js +51 -38
- package/src/config/restartOptions.js +34 -0
- package/src/config/themeOptions.js +825 -0
- package/src/config/timingGapMode.js +13 -0
- package/src/config/urlOptions.js +25 -0
- package/src/data/championship.js +14 -9
- package/src/environment/controllerLoop.js +34 -5
- package/src/environment/episode.js +14 -2
- package/src/environment/index.d.ts +17 -4
- package/src/environment/observationVector.js +200 -0
- package/src/environment/observations.js +58 -285
- package/src/environment/options.js +1 -1
- package/src/environment/recorder.js +13 -6
- package/src/environment/rewards.js +13 -2
- package/src/environment/runtime.js +65 -25
- package/src/environment/scenarios.js +22 -3
- package/src/environment/sensors/index.js +3 -3
- package/src/environment/sensors/opponentRadar.js +13 -3
- package/src/environment/sensors/sensorTargets.js +8 -2
- package/src/environment/sensors/surfaceRays.js +84 -12
- package/src/environment/sensors/trackRays.js +173 -15
- package/src/environment/specs.js +78 -40
- package/src/index.d.ts +112 -9
- package/src/index.js +26 -33
- package/src/simulation/driver/driverController.js +1 -1
- package/src/simulation/driver/edgeRecovery.js +1 -1
- package/src/simulation/driver/racingControls.js +2 -2
- package/src/simulation/driver/rejoinControls.js +2 -2
- package/src/simulation/pit/pitFlow.js +5 -0
- package/src/simulation/pit/pitKinematics.js +24 -0
- package/src/simulation/pit/pitQueue.js +5 -0
- package/src/simulation/pit/pitRouteMovement.js +7 -0
- package/src/simulation/pit/pitRouting.js +2 -4
- package/src/simulation/pit/pitService.js +2 -0
- package/src/simulation/pit/pitTireService.js +2 -0
- package/src/simulation/race/raceLifecycle.js +2 -6
- package/src/simulation/race/raceProgress.js +6 -1
- package/src/simulation/race/raceSetup.js +2 -6
- package/src/simulation/race/raceStep.js +2 -2
- package/src/simulation/race/redFlag.js +3 -3
- package/src/simulation/race/safetyCar.js +10 -4
- package/src/simulation/race/stalledDnf.js +8 -17
- package/src/simulation/raceSimulation.js +1 -0
- package/src/simulation/rules/rulesReview.js +3 -0
- package/src/simulation/snapshots/raceSnapshots.js +1 -0
- package/src/simulation/timing/lapTelemetry.js +28 -9
- package/src/simulation/track/pitLaneLayout.js +7 -3
- package/src/simulation/track/spatialQueries.js +5 -28
- package/src/simulation/track/trackQueryGrid.js +94 -0
- package/src/simulation/track/trackQueryIndex.js +193 -434
- package/src/simulation/track/trackQueryPitIndex.js +140 -0
- package/src/simulation/track/trackQueryScratch.js +46 -0
- package/src/simulation/track/trackQueryStats.js +28 -0
- package/src/simulation/track/trackStatePolicy.js +0 -1
- package/src/simulation/vehicle/contactResolution.js +67 -2
- package/src/simulation/vehicle/runoffResponse.js +11 -12
- package/src/simulation/vehicle/vehicleKinematics.js +37 -0
- package/src/simulation/vehicle/vehiclePhysics.js +5 -4
- package/src/simulation/vehicle/vehicleSnapshots.js +22 -0
- package/src/simulation/vehicle/vehicleState.js +36 -2
- package/src/simulation/vehicle/wheelSurface.js +3 -1
- package/src/simulation/warmup/runtimeWarmup.js +0 -1
- package/src/styles.css +1185 -136
- package/src/ui/bannerTemplates.js +38 -28
- package/src/ui/cameraControlsTemplate.js +16 -5
- package/src/ui/carOverviewTemplate.js +12 -5
- package/src/ui/raceCanvasTemplate.js +31 -8
- package/src/ui/raceControlsTemplate.js +27 -10
- package/src/ui/shellTemplate.js +3 -1
- package/src/ui/telemetryDrawerTemplate.js +23 -10
- package/src/ui/telemetryTemplates.js +58 -32
- package/src/ui/templateUtils.js +48 -0
- package/src/ui/timingTowerTemplate.js +29 -12
package/CHANGELOG.md
CHANGED
|
@@ -1,11 +1,47 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 3.0.0
|
|
4
|
+
|
|
5
|
+
### Major Changes
|
|
6
|
+
|
|
7
|
+
- Add the semantic theme customization system. Themes may be partial, but resolved themes are complete light/dark packages; one-sided light/dark token overrides generate and cache the opposite mode, derivative theme packages cannot invent unknown tokens, component/team theme selectors are supported, and theme plus driver/team colors are validated before becoming CSS variables.
|
|
8
|
+
- Make indexed track queries canonical and internal. Browser mounts, headless environments, Policy Runner, model-sense visualization, and hot simulation paths now use the package-owned index, while unsuitable edge cases stay behind focused internal fallback integrations. The public `trackQueryIndex` option is removed.
|
|
9
|
+
- Add the playable keyboard demo and pit controls. The local preview now exposes a playable route with steering/throttle/brake controls plus pit request, commit, clear, and target compound commands through the normal expert action fields.
|
|
10
|
+
- Finalize the opt-in `driver` camera. Hosts can enable the control with `ui.driverCamera: true` or start directly in it with `initialCameraMode: 'driver'`; the camera follows the selected car from a lower screen anchor, rotates the world around the car heading, respects zoom bounds, and falls back safely when no selected car or snapshot is available.
|
|
11
|
+
- Keep `car.trackState` as a documented public snapshot shape with stable car-center track classification fields, and make package readouts tolerate partial startup or external-renderer snapshots without throwing.
|
|
12
|
+
|
|
13
|
+
### Fixes And Hardening
|
|
14
|
+
|
|
15
|
+
- Sanitize public URL-like options such as `backLinkHref` so unsafe schemes cannot become clickable package-owned links.
|
|
16
|
+
- Sanitize runtime snapshot colors and escape package asset URLs before writing readout CSS values, so external-renderer or partial-snapshot data cannot inject inline style declarations.
|
|
17
|
+
- Harden track query correctness and performance with deterministic indexed lookup coverage, progress hints as optimization-only inputs, and benchmark coverage for hot query paths.
|
|
18
|
+
- Preserve scheduler cancellation behavior in `createPaddockDriverControllerLoop()` so stopped scheduled playback cancels package-owned and custom scheduler handles cleanly.
|
|
19
|
+
|
|
20
|
+
### Migration Notes
|
|
21
|
+
|
|
22
|
+
- Remove any host usage of `trackQueryIndex`; indexed queries are always canonical/internal in 3.0.0.
|
|
23
|
+
- Rename the strict physics mode from `physicsMode: 'simulator'` to `physicsMode: 'advanced'`. The old string is no longer accepted and falls back to the default `physicsMode: 'arcade'`.
|
|
24
|
+
- Prefer the semantic `theme` contract over one-off color aliases. Legacy aliases such as `accentColor`, `greenColor`, and `yellowColor` still map to semantic tokens for migration.
|
|
25
|
+
- Use `ui.driverCamera: true` when the generated camera controls should expose the Driver button, or `initialCameraMode: 'driver'` when the simulator should start in driver camera mode.
|
|
26
|
+
- `backLinkHref` now accepts only relative URLs, hash URLs, and absolute `http:` / `https:` URLs; unsafe or malformed values fall back to the package default.
|
|
27
|
+
|
|
28
|
+
### Verification Notes
|
|
29
|
+
|
|
30
|
+
- The normal package handoff gate is `npm run check`.
|
|
31
|
+
- The final release gate is `npm run check:release`, which adds slow characterization coverage and the full browser smoke matrix.
|
|
32
|
+
|
|
33
|
+
## 2.0.1
|
|
34
|
+
|
|
35
|
+
### Patch Changes
|
|
36
|
+
|
|
37
|
+
- Harden the simulator training environment and model-facing sense contract. This patch keeps vector-only observations aligned with full object observations, keeps indexed ray acceleration equivalent to the legacy ray contract for driver-facing senses, preserves stable terminal-car and pit-route state during training loops, and documents the stricter model-sense boundary.
|
|
38
|
+
|
|
3
39
|
## 2.0.0
|
|
4
40
|
|
|
5
41
|
### Major Changes
|
|
6
42
|
|
|
7
43
|
- Promote the `v6` simulator work as the next major PaddockJS release. This release keeps the package boundary focused on browser-mounted simulator components, composable simulator surfaces, and browser-free JavaScript environment/control APIs.
|
|
8
|
-
- Add the stricter opt-in `physicsMode: '
|
|
44
|
+
- Add the stricter opt-in `physicsMode: 'advanced'` vehicle model with 2D velocity/yaw dynamics, traction limits, speed-sensitive steering, steering scrub, slip telemetry, reduced off-road grip, and advanced-mode AI tuning. The default remains `physicsMode: 'arcade'` for existing hosts.
|
|
9
45
|
- Add richer procedural track generation with semantic profiles (`race`, `training-short`, `training-medium`, and `training-technical`), validated connected-region centerlines, profile-level generation controls, deterministic `trackGeneration` options, DRS zones, pit-lane access geometry, and cached track query indexes.
|
|
10
46
|
- Add hard barrier-wall consequences and opt-in stalled off-track DNF handling. Barrier contact now marks cars destroyed/DNF in both physics modes, while `rules.modules.stalledDnf` can retire cars that remain stopped off legal surfaces.
|
|
11
47
|
- Expand the headless environment contract for real training loops: compact vector/object/full observation output, optional `Float32Array` vectors, schema caching, no-state/minimal/full result output, per-driver episode info, selected-driver resets, reset-only scenario placements, reward normalization, evaluation helpers, rollout metrics, and a shared driver-controller loop.
|
package/INSTALL_AND_UPDATE.md
CHANGED
|
@@ -112,12 +112,21 @@ npm run check
|
|
|
112
112
|
Install a specific version when the host needs a controlled upgrade:
|
|
113
113
|
|
|
114
114
|
```bash
|
|
115
|
-
npm install @inventure71/paddockjs@
|
|
115
|
+
npm install @inventure71/paddockjs@3.0.0
|
|
116
116
|
npm run check
|
|
117
117
|
```
|
|
118
118
|
|
|
119
119
|
After updating, smoke-test the page that mounts the simulator. Browser behavior changes should be checked in the consuming host, because host CSS, container size, and route handling are outside the package.
|
|
120
120
|
|
|
121
|
+
### 3.0.0 Migration Notes
|
|
122
|
+
|
|
123
|
+
- Remove any `trackQueryIndex` host option. Indexed track queries are always canonical package internals in 3.0.0.
|
|
124
|
+
- Rename strict vehicle-physics usage from `physicsMode: 'simulator'` to `physicsMode: 'advanced'`. The old string is no longer accepted and will resolve to the default `physicsMode: 'arcade'`.
|
|
125
|
+
- Prefer the semantic `theme` contract for new customization. Partial themes are valid, resolved themes are complete, and one-sided light/dark token overrides generate and cache the opposite mode. Legacy aliases such as `accentColor`, `greenColor`, and `yellowColor` remain migration aliases.
|
|
126
|
+
- Use `ui.driverCamera: true` to show the generated Driver camera button, or `initialCameraMode: 'driver'` to start in that mode.
|
|
127
|
+
- `backLinkHref` is sanitized; relative URLs, hash URLs, and absolute `http:` / `https:` URLs are accepted, while unsafe schemes fall back to the package default.
|
|
128
|
+
- Full public snapshots include `car.trackState` for the stable car-center track classification shape.
|
|
129
|
+
|
|
121
130
|
## Package Release Workflow
|
|
122
131
|
|
|
123
132
|
The package repo owns its release process:
|
package/README.md
CHANGED
|
@@ -12,7 +12,7 @@ npm install @inventure71/paddockjs
|
|
|
12
12
|
|
|
13
13
|
## Documentation
|
|
14
14
|
|
|
15
|
-
Start with [docs/index.md](docs/index.md) for
|
|
15
|
+
Start with [docs/index.md](docs/index.md) for the full package map: what to install, which API to use, what data to pass, how rules modules work, how the browser and headless runtimes differ, and which verification commands prove a change. If you are integrating the package into a host site, read [System Specs](docs/system_specs.md), [Data Contract](docs/data_contract.md), and [Rules](docs/rules.md) first. If you already trained a driver model and want to run it in PaddockJS, use the [Custom Model Controller Guide](docs/custom_model_controller.md).
|
|
16
16
|
|
|
17
17
|
## Package Workflow
|
|
18
18
|
|
|
@@ -40,9 +40,11 @@ npm run changeset
|
|
|
40
40
|
|
|
41
41
|
Local development and showcase builds require Node `20.19.0` or newer. CI currently runs the package check on Node 22 and releases on Node 24.
|
|
42
42
|
|
|
43
|
-
##
|
|
43
|
+
## 3.0 Release Highlights
|
|
44
44
|
|
|
45
|
-
|
|
45
|
+
The `3.0.0` release line adds semantic theme customization with complete resolved light/dark themes, reusable derivative theme packages, component/team theme selectors, cached opposite-mode color generation, and validated color tokens. Indexed track queries are now canonical/internal, so hosts should remove any `trackQueryIndex` option usage. The local preview adds first-class Customization and playable keyboard routes, including theme package switching, selected-team theming, component overrides, pit request/commit/clear, and target-compound controls. The public camera contract includes the opt-in `driver` camera, and full public car snapshots document `car.trackState` as the stable car-center track classification shape.
|
|
46
|
+
|
|
47
|
+
The release also hardens public URL handling for options such as `backLinkHref`, keeps package readouts safe for partial startup or external-renderer snapshots, preserves scheduler cancellation behavior in `createPaddockDriverControllerLoop()`, and keeps the release workflow centered on `npm run check` plus the final `npm run check:release` gate.
|
|
46
48
|
|
|
47
49
|
The package still does not ship trained model weights, model storage, a Python Gymnasium/PettingZoo package, static obstacles, weather, reliability failures, fuel-load effects, or debug mutation APIs. Those remain host-owned or future scope.
|
|
48
50
|
|
|
@@ -57,7 +59,7 @@ import { createPaddockEnvironment } from '@inventure71/paddockjs/environment';
|
|
|
57
59
|
The package root remains the browser component API. The environment subpath is intentionally browser-free and does not import DOM, PixiJS, or package CSS.
|
|
58
60
|
PaddockJS is a bring-your-own-model environment. It does not choose an ML framework, store model weights, or ship a trained driver. The shared `createPaddockDriverControllerLoop()` helper lets a user-owned controller run against either browser expert mode or `createPaddockEnvironment()` with the same batched `decideBatch(context)` call shape.
|
|
59
61
|
|
|
60
|
-
Browser and headless environments default to `physicsMode: 'arcade'` for existing hosts. Opt into the stricter vehicle model with `physicsMode: '
|
|
62
|
+
Browser and headless environments default to `physicsMode: 'arcade'` for existing hosts. Opt into the stricter vehicle model with `physicsMode: 'advanced'` when you want 2D velocity/yaw dynamics, traction limits, steering scrub, derived slip telemetry, reduced off-road grip, and advanced-mode AI tuning:
|
|
61
63
|
|
|
62
64
|
```js
|
|
63
65
|
const env = createPaddockEnvironment({
|
|
@@ -65,7 +67,7 @@ const env = createPaddockEnvironment({
|
|
|
65
67
|
entries,
|
|
66
68
|
controlledDrivers: ['budget'],
|
|
67
69
|
frameSkip: 2,
|
|
68
|
-
physicsMode: '
|
|
70
|
+
physicsMode: 'advanced',
|
|
69
71
|
});
|
|
70
72
|
|
|
71
73
|
let result = env.reset();
|
|
@@ -104,7 +106,7 @@ The starter script imports the public `@inventure71/paddockjs/environment` subpa
|
|
|
104
106
|
|
|
105
107
|
Each default ray reports track-transition distance and car distance. A track hit uses `kind: 'exit'` when the ray leaves the road and `kind: 'entry'` when an off-track ray points back to the road. Richer sensor layouts are opt-in: rays can use per-ray lengths, predefined layouts such as `driver-front-heavy`, channels for `roadEdge`, `kerb`, `illegalSurface`, and `car`, and `precision: 'driver' | 'debug'`. Driver precision is the default model-facing contract; debug precision is only for clearly labeled diagnostics. Surface channels are computed only when requested. Barrier walls are rendered and enforced as hard destruction boundaries in both physics modes, but they are not model-facing ray targets. `observation.object.self.onTrack` follows the simulator's wheel-level legality rules, so track, kerb, and legal pit-lane/box surfaces are on-track for reward and observation purposes. `pitIntent: 0` is always accepted as the no-op clear value, including environments where pit stops are disabled.
|
|
106
108
|
|
|
107
|
-
For realistic local-perception policies, use `physicsMode: '
|
|
109
|
+
For realistic local-perception policies, use `physicsMode: 'advanced'` with `observation.profile: 'physical-driver'`. It exposes yaw rate, local boundary distances, contact-patch surface readings, richer opponent radar, and surface-aware ray fields in the versioned vector schema. The profile defaults track lookahead to `[]` so the policy does not receive privileged future curvature unless the host explicitly opts back in.
|
|
108
110
|
|
|
109
111
|
External training code can inspect the environment contract without guessing field ranges:
|
|
110
112
|
|
|
@@ -163,7 +165,7 @@ const env = createPaddockEnvironment({
|
|
|
163
165
|
drivers,
|
|
164
166
|
entries,
|
|
165
167
|
controlledDrivers: agentIds,
|
|
166
|
-
physicsMode: '
|
|
168
|
+
physicsMode: 'advanced',
|
|
167
169
|
participantInteractions: { defaultProfile: 'batch-training' },
|
|
168
170
|
observation: {
|
|
169
171
|
profile: 'physical-driver',
|
|
@@ -216,6 +218,7 @@ const env = createPaddockEnvironment({
|
|
|
216
218
|
`isolated-training` is the no-collision profile for real cars that should still remain in race order. `batch-training` is the preferred no-collision profile for same-environment learner batches because it is also excluded from race order. Both profiles hide the car from other cars' ray sensors and `nearbyCars` observations by default; use `phantom-race` or explicit `detectableByRays` / `detectableAsNearby` overrides only when sensor visibility is intentional.
|
|
217
219
|
|
|
218
220
|
Browser expert mode is opt-in through the normal mount API. When enabled, the visual simulator advances only when host code calls `simulator.expert.step(actions)`. Expert mode is a mount-time boundary; changing `expert` through `restart(nextOptions)` is rejected so ticker ownership cannot silently change under a mounted simulator.
|
|
221
|
+
Browser expert mode uses the same episode lifecycle as the headless environment. The default episode horizon is a high safety cap (`1_000_000` expert steps, roughly 4.6 hours at 60Hz with `frameSkip: 1`) so normal user-facing sessions should end by race finish, not by the safety cap. Training and evaluation loops should set a smaller explicit `expert.episode.maxSteps` or `episode.maxSteps` when they need bounded rollouts; `episode.endOnRaceFinish` keeps normal race completion as the terminal condition.
|
|
219
222
|
Set `expert.visualizeSensors` to draw expert sensor rays inside the actual race canvas for visual debugging:
|
|
220
223
|
|
|
221
224
|
```js
|
|
@@ -239,6 +242,8 @@ When multiple drivers are controlled, sensor visualization renders the selected
|
|
|
239
242
|
|
|
240
243
|
## API
|
|
241
244
|
|
|
245
|
+
The root package exports the browser mounts, composable helper mounts, data/rating helpers, bundled asset and preset constants, procedural-track helper, simulator unit converters, and `createPaddockDriverControllerLoop`. The browser-free training runtime lives under `@inventure71/paddockjs/environment`; see [docs/system_specs.md](docs/system_specs.md) for the full export catalog.
|
|
246
|
+
|
|
242
247
|
All-in-one mount:
|
|
243
248
|
|
|
244
249
|
```js
|
|
@@ -324,7 +329,24 @@ simulator.mountRaceTelemetryDrawer(document.getElementById('sim-race-workbench')
|
|
|
324
329
|
});
|
|
325
330
|
```
|
|
326
331
|
|
|
327
|
-
|
|
332
|
+
When a composable host intends to use pit APIs or automatic pit behavior, include the pit rules in the simulator options before mounting components:
|
|
333
|
+
|
|
334
|
+
```js
|
|
335
|
+
const simulator = createPaddockSimulator({
|
|
336
|
+
drivers,
|
|
337
|
+
entries,
|
|
338
|
+
rules: {
|
|
339
|
+
ruleset: 'custom',
|
|
340
|
+
modules: {
|
|
341
|
+
pitStops: { enabled: true },
|
|
342
|
+
stalledDnf: { enabled: true },
|
|
343
|
+
tireStrategy: { enabled: true, mandatoryDistinctDryCompounds: 2 },
|
|
344
|
+
},
|
|
345
|
+
},
|
|
346
|
+
});
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
`drivers` is the host-owned project/pilot list. `entries` is the optional driver/car/team pairing sheet. The car/driver overview uses the existing driver and vehicle rating components from each entry. Driver and vehicle entries can also include `customFields` as extra label/value metadata. Entries can include `team: { id, name, color, icon, theme, pitCrew }`; the timing tower uses the team icon, defaults team color to the car color when omitted, and can map `team.theme` into the semantic theme system. `team.pitCrew` accepts `speed`, `consistency`, and `reliability` values from `0` to `1` for optional pit-service variability. Assets, including the default car image and generic driver helmet, are bundled by default, so the host website does not need to provide simulator images or textures.
|
|
328
350
|
|
|
329
351
|
The returned object supports:
|
|
330
352
|
|
|
@@ -341,17 +363,39 @@ The returned object supports:
|
|
|
341
363
|
- `getPitIntent(driverId)`
|
|
342
364
|
- `getPitTargetCompound(driverId)`
|
|
343
365
|
- `getSimulationSpeed()`
|
|
366
|
+
- `setTimingGapMode(mode)`
|
|
367
|
+
- `getTimingGapMode()`
|
|
368
|
+
- `toggleTimingGapMode()`
|
|
344
369
|
- `servePenalty(penaltyId)`
|
|
345
370
|
- `cancelPenalty(penaltyId)`
|
|
346
371
|
- `getSnapshot()`
|
|
347
372
|
- `expert` when explicitly enabled, otherwise `null`
|
|
348
373
|
|
|
374
|
+
Timing gap mode is controller-owned, not tied to whether the manual tower toggle is visible. `setTimingGapMode('interval')` makes timing rows show interval to the car ahead, `setTimingGapMode('leader')` makes them show gap to P1, and `toggleTimingGapMode()` switches between those two values. These methods can be called after mounting or while the race is running; mounted timing towers update immediately and keep the same selected driver/order state.
|
|
375
|
+
|
|
349
376
|
Useful UI options:
|
|
350
377
|
|
|
351
378
|
```js
|
|
352
379
|
preset: 'timing-overlay',
|
|
353
380
|
theme: {
|
|
354
|
-
|
|
381
|
+
mode: 'system',
|
|
382
|
+
use: 'trackside',
|
|
383
|
+
tokens: {
|
|
384
|
+
primary: { light: '#008c55', dark: '#00ff84' },
|
|
385
|
+
pitLane: '#7c3aed',
|
|
386
|
+
},
|
|
387
|
+
themes: {
|
|
388
|
+
trackside: {
|
|
389
|
+
extends: 'default',
|
|
390
|
+
tokens: { yellowFlag: { dark: '#ffcc00' } },
|
|
391
|
+
components: {
|
|
392
|
+
button: { background: 'pitLane', text: 'primaryText', border: 'primary' },
|
|
393
|
+
},
|
|
394
|
+
},
|
|
395
|
+
},
|
|
396
|
+
componentThemes: {
|
|
397
|
+
'race-controls': 'trackside',
|
|
398
|
+
},
|
|
355
399
|
timingTowerMaxWidth: '360px',
|
|
356
400
|
raceViewMinHeight: '720px',
|
|
357
401
|
},
|
|
@@ -368,13 +412,31 @@ ui: {
|
|
|
368
412
|
raceDataBannerSize: 'auto',
|
|
369
413
|
raceDataTelemetryDetail: true,
|
|
370
414
|
timingTowerVerticalFit: 'expand-race-view',
|
|
415
|
+
timingGapMode: 'interval',
|
|
416
|
+
timingGapModeToggle: true,
|
|
417
|
+
timingEntryVerticalPadding: 5,
|
|
371
418
|
},
|
|
372
419
|
debug: {
|
|
373
420
|
physicsModeIndicator: false,
|
|
374
421
|
}
|
|
375
422
|
```
|
|
376
423
|
|
|
377
|
-
`preset` is resolved before explicit host options. Available presets are `dashboard`, `timing-overlay`, `compact-race`, and `full-dashboard`; hosts can start from a preset and override any `ui`, `debug`, or `theme` field. `debug.physicsModeIndicator: true` renders a small top-left race-canvas square: blue for arcade physics and red for
|
|
424
|
+
`preset` is resolved before explicit host options. Available presets are `dashboard`, `timing-overlay`, `compact-race`, and `full-dashboard`; hosts can start from a preset and override any `ui`, `debug`, or `theme` field. `debug.physicsModeIndicator: true` renders a small top-left race-canvas square: blue for arcade physics and red for advanced physics. It defaults to `false` for package consumers and is intended only for debug/development use. `theme` resolves semantic package tokens into complete light/dark themes, can define reusable named theme packages with `extends`, and can assign a named theme to component scopes such as `race-controls` through `componentThemes`. Component theme keys accept package `data-paddock-component` names and camelCase aliases such as `raceControls` or `timingTower`; `selectedDriverPanel` targets both selected-driver package surfaces. Selected-driver surfaces such as the car/driver overview and race-data panel use the selected team's theme by default when one is available. Unknown theme tokens or component slots are ignored, one-sided light/dark token overrides generate and cache the opposite mode, and theme plus driver/team colors are validated before they are written to CSS variables. Legacy aliases such as `accentColor`, `greenColor`, and `yellowColor` still map to the semantic token system for migration.
|
|
425
|
+
|
|
426
|
+
### Layout Support Contract
|
|
427
|
+
|
|
428
|
+
PaddockJS supports the all-in-one shell and host mount roots in containers at least `320px` wide. Hosts should size the outer mount root with normal responsive CSS, for example `width: 100%; min-width: 0;`, and avoid adding host rules that target package internals such as `.sim-grid`, `.sim-timing`, or `.race-data-panel`. The host owns page placement; PaddockJS owns the shell, timing-board width, camera safe area, lower-thirds, drawer behavior, focus styles, and touch target sizing. Package-owned subcomponents can have smaller internal widths when their own layout is designed for it; for example, the broadcast timing tower remains valid at its package-owned narrow width. Responsive narrow template variants are enabled by default and can be disabled with `ui.responsiveNarrowLayout: false` or the matching composable mount option when a host intentionally wants the older stacked timing/drawer behavior.
|
|
429
|
+
|
|
430
|
+
The package uses container-width density tiers:
|
|
431
|
+
|
|
432
|
+
- `320px` to `519px`: mobile density. Controls wrap, embedded timing towers stop reserving a side gutter and use the package timing reveal, telemetry drawers reveal over the race view, and lower-thirds compress inside the race view. The lower-third may cover empty timing-tower chrome, but if it would cover any timing entries the race view adds package-owned banner clearance to its minimum height. If the entries remain clear, no extra banner height is reserved.
|
|
433
|
+
- `520px` to `759px`: narrow tablet density. Race surfaces keep readable controls while standalone telemetry and overview modules collapse to single-column layouts.
|
|
434
|
+
- `760px` to `1119px`: tablet density. Side-by-side host sections may still give an individual component a narrow container, so package components use their own container width rather than viewport width.
|
|
435
|
+
- `1120px` and wider: desktop density. The broadcast timing tower can sit in the left race gutter at its package-owned width, and telemetry/drawer layouts use wider horizontal space.
|
|
436
|
+
|
|
437
|
+
If the shell/mount root receives less than `320px` inline size, or an individual package component is constrained below its component-specific minimum, PaddockJS marks it with `data-paddock-size-unsupported="true"` and shows an accessible `Unsupported size` placeholder. That is intentional: below the support envelope, the package prefers a clear placeholder over clipped controls, horizontal scrolling, or overlapping race UI. The placeholder is package-owned and uses `role="status"` with polite live-region behavior.
|
|
438
|
+
|
|
439
|
+
Package controls, drawer toggles, lower-third actions, and close buttons maintain practical `44px` touch targets. Timing rows are compact selectable broadcast entries with configurable vertical padding. Touch driving controls are not part of the package; the playable preview remains keyboard/expert-action driven and does not add a virtual joystick.
|
|
378
440
|
|
|
379
441
|
If `trackSeed` is omitted, each mounted browser simulator creates a fresh procedural circuit. Passing `trackSeed` makes the track deterministic so multiple embeds can share the same generated circuit; repeated procedural seeds are cached within the page runtime as immutable track definitions. Treat values returned by `createProceduralTrack()` as read-only and pass custom mutable copies when experimenting with track-definition edits. `restart({ trackSeed })` rebuilds the race on the deterministic circuit for the new seed. Asset URL changes are not restartable; destroy and mount a new simulator when changing assets.
|
|
380
442
|
|
|
@@ -439,6 +501,8 @@ Pit-lane asphalt, working-lane service areas, and garage boxes are legal drivabl
|
|
|
439
501
|
|
|
440
502
|
When `rules.modules.pitStops.enabled` is true, cars automatically form bounded pit trains when lane space is available. They brake to the limiter by the main pit-lane start, drive along the main fast lane, pass through the team queue spot as a rolling gate, roll into the team-colored working-lane service area when it is clear, stop, serve eligible penalties before tire work, show the remaining stationary service time above the car, change to the requested configured tire compound or the default alternate compound, and exit back to the race track.
|
|
441
503
|
|
|
504
|
+
`tireStrategy` does not enable automatic pit stops. It controls available compounds, pit-stop target compound choices, and tire-requirement stewarding. Use `rules.modules.pitStops.enabled: true` for automatic pit routing and pit APIs, or choose a preset such as `ruleset: 'fia2025'` / `ruleset: 'grandPrix2025'` that enables both pit stops and the two-compound tire strategy by default.
|
|
505
|
+
|
|
442
506
|
Team-mates share one service area. Every car enters through the queue spot first, but it only stops there when the active service spot is blocked. A second team car waits in the queue spot until the active service spot is physically clear, including the previous car's first movement out of the box, without blocking the main fast lane.
|
|
443
507
|
|
|
444
508
|
By default, built-in AI cars request an opportunistic `pitIntent: 1` below 50% tire energy and commit `pitIntent: 2` below 30%. Hosts can change those thresholds with `tirePitRequestThresholdPercent` and `tirePitCommitThresholdPercent`. Expert/headless controlled drivers do not receive those automatic tire-threshold calls and must request service with `pitIntent`.
|
|
@@ -473,6 +537,10 @@ const simulator = await mountF1Simulator(root, {
|
|
|
473
537
|
perfect: false,
|
|
474
538
|
},
|
|
475
539
|
},
|
|
540
|
+
tireStrategy: {
|
|
541
|
+
enabled: true,
|
|
542
|
+
mandatoryDistinctDryCompounds: 2,
|
|
543
|
+
},
|
|
476
544
|
tireDegradation: {
|
|
477
545
|
enabled: true,
|
|
478
546
|
},
|
|
@@ -498,12 +566,14 @@ const simulator = await mountF1Simulator(root, {
|
|
|
498
566
|
|
|
499
567
|
For deterministic single-skill training or visual checkpoint comparison, set `rules.modules.tireDegradation.enabled: false` so tyre energy remains fixed while the car still drives through normal steering, throttle, brake, and surface physics. `rules.modules.stalledDnf` defaults to `enabled: false` so base simulator and training environments keep stuck off-track cars live unless a host opts in. Set `enabled: true` to retire cars that are off legal racing or pit surfaces while below `speedThresholdKph` for `maxStoppedSeconds`.
|
|
500
568
|
|
|
501
|
-
Supported rulesets are `paddock`, `grandPrix2025`, `fia2025`, and `custom`. Presets only choose defaults; explicit module config wins. Weather, reliability, and fuel-load performance effects are reserved future modules and are not active
|
|
569
|
+
Supported rulesets are `paddock`, `grandPrix2025`, `fia2025`, and `custom`. Presets only choose defaults; explicit module config wins. Weather, reliability, and fuel-load performance effects are reserved future modules and are not active `3.0.0` behavior. Penalty subsections use `strictness` from `0` to `1` instead of plain booleans. Track limits use the white line as the legal edge and require all four wheel contact patches to be fully outside the same side of the line before recording a violation, so normal kerb riding is not punished. Per-car `surface` is resolved from the worst wheel surface, snapshots include `car.wheels` for per-wheel surface and white-line state, and asymmetric left/right wheel resistance adds a small capped yaw tug toward the slower side when only one side is on a worse surface. Collision stewarding is driven by a body collision hull, not transparent sprite bounds or wheel-only overlap, and contact events include shape ids, contact type, depth, and time of impact. It considers impact severity, closing speed, and whether one car clearly hit another from behind; clear rear contact penalizes only the physically trailing car, including lapped traffic cases, while unclear meaningful contact records shared-fault penalties for both cars. Stalled off-track DNFs emit `car-dnf` with `reason: 'stalled-off-track'`, freeze the car, remove it from active control/collision/sensor/pit participation, and classify it with the existing DNF metadata. Pit-lane speeding is enforced on the main fast lane, working lane, service areas, and garage boxes, but not on pit-entry or pit-exit connector roads. Track-limit warnings are emitted as `track-limits` events, while penalty decisions are exposed through `snapshot.penalties` plus `penalty` events. Penalty consequences support warning, time, drive-through, stop-go, position-drop, grid-drop, and disqualification payloads. Time consequences are additive, drive-through and stop-go penalties are service obligations, and unserved service penalties convert to configured time at final classification.
|
|
502
570
|
|
|
503
|
-
`initialCameraMode` accepts `'overview'`, `'leader'`, `'selected'`, `'show-all'`, or `'pit'`; invalid values fall back to `'leader'`. The overview camera frames the active generated track bounds, including package-owned track padding and pit-lane extent, instead of using a fixed world-center zoom. Camera mode changes ease from the current camera target to the next target after the initial frame, so switching between leader, selected, overview, show-all, and pit views does not snap the world view.
|
|
571
|
+
`initialCameraMode` accepts `'overview'`, `'leader'`, `'selected'`, `'driver'`, `'show-all'`, or `'pit'`; invalid values fall back to `'leader'`. The overview camera frames the active generated track bounds, including package-owned track padding and pit-lane extent, instead of using a fixed world-center zoom. Camera mode changes ease from the current camera target to the next target after the initial frame, so switching between leader, selected, driver, overview, show-all, and pit views does not snap the world view.
|
|
504
572
|
|
|
505
573
|
The pit camera targets the generated operational pit-lane geometry, including the lane, boxes, service areas, and queue areas, while excluding the longer entry/exit access roads. It zooms out as needed to fit that work area inside the active race-view safe area, and its control is hidden when the active track has no pit lane.
|
|
506
574
|
|
|
575
|
+
The driver camera follows the selected car from a lower screen anchor and rotates the world so the car's heading points upward. Its control is opt-in through `ui.driverCamera: true`, and setting `initialCameraMode: 'driver'` enables that control automatically.
|
|
576
|
+
|
|
507
577
|
Zoom buttons and wheel zoom apply to every camera mode. Zoom-out is bounded by the active generated track frame so the camera cannot pull far beyond the circuit. The renderer keeps grass coverage larger than the simulated world, and the transparent canvas host uses the same grass color as a fallback around the framed circuit.
|
|
508
578
|
|
|
509
579
|
`layoutPreset: 'left-tower-overlay'` creates a left broadcast gutter inside the race view, frames the camera around the remaining race area, and places the timing tower in that gutter without covering camera controls. The project/radio lower-third stays inside the race window and can intentionally render over the timing sidebar instead of shrinking around it.
|
|
@@ -512,9 +582,9 @@ Composable hosts should pass `{ includeRaceDataPanel: true }` to `mountRaceCanva
|
|
|
512
582
|
|
|
513
583
|
`raceDataTelemetryDetail: true` makes the project lower-third include a compact S1/S2/S3 sector strip with live sector elapsed time and per-sector progress. That telemetry project lower-third stays visible until dismissed, muted, or replaced, while radio mode keeps its normal schedule. The standalone `mountTelemetrySectorBanner()` surface remains available only when a host explicitly mounts it.
|
|
514
584
|
|
|
515
|
-
`includeTimingTower: true` embeds the timing tower directly inside the race canvas and reserves camera space from the measured tower gutter when the tower is a side overlay. In narrow
|
|
585
|
+
`includeTimingTower: true` embeds the timing tower directly inside the race canvas and reserves camera space from the measured tower gutter when the tower is a side overlay. In narrow hosts, the embedded timing tower becomes a package-owned left reveal panel opened by the race view's Timing control instead of taking permanent height above the track. The control updates `aria-expanded`, the closed tower is inert/hidden to assistive tech, and the renderer/camera keep resizing through the transition without remounting the simulator. This responsive narrow behavior is enabled by default; pass `responsiveNarrowLayout: false` to `mountRaceCanvas()` or set `ui.responsiveNarrowLayout: false` to opt out.
|
|
516
586
|
|
|
517
|
-
`mountRaceTelemetryDrawer()` is a higher-level template that mounts an external top control row, race canvas, embedded timing tower, lower-third, top steward message, safety-car control, and a
|
|
587
|
+
`mountRaceTelemetryDrawer()` is a higher-level template that mounts an external top control row, race canvas, embedded timing tower, lower-third, top steward message, safety-car control, and a telemetry drawer together. Pass `{ raceDataTelemetryDetail: true }` when the drawer lower-third should include compact sector detail. On narrow hosts the responsive template is enabled by default: the top workbench controls stack into full-width rows, the safety-car and telemetry actions become a two-column row, the telemetry drawer reveals over the race view instead of forcing the race canvas to reserve permanent drawer height, and the race view measures lower-third/timing-entry geometry before adding extra vertical clearance. Pass `{ responsiveNarrowLayout: false }` to opt out.
|
|
518
588
|
|
|
519
589
|
The drawer top row contains camera controls, a `1x` simulation-speed button that cycles through `2x`, `3x`, `4x`, `5x`, `10x`, and back to `1x`, a `Mute banners` toggle, safety car, and the telemetry toggle so those controls do not cover the race. For other camera-control placements the speed button is hidden by default and can be enabled with `ui.simulationSpeedControl: true`.
|
|
520
590
|
|
|
@@ -528,10 +598,15 @@ Banner and timing layout options:
|
|
|
528
598
|
- `raceDataBannerSize: 'custom'` preserves the default CSS-variable-driven lower-third size for hosts that want to tune their own banner geometry.
|
|
529
599
|
- `timingTowerVerticalFit: 'expand-race-view'` lets the race window grow tall enough for the tower.
|
|
530
600
|
- `timingTowerVerticalFit: 'scroll'` keeps the race window height and scrolls the timing list inside the cropped tower.
|
|
601
|
+
- `timingGapMode: 'interval'` starts the timing tower in `Int` mode, showing interval to the car ahead. Use `'leader'` to start in `Gap` mode, showing the total gap to P1.
|
|
602
|
+
- `timingGapModeToggle: true` shows the compact timing-tower header toggle by default. Set it to `false` when the host should own mode changes through `setTimingGapMode()`, `getTimingGapMode()`, or `toggleTimingGapMode()`.
|
|
603
|
+
- `timingEntryVerticalPadding: 5` adds `5px` above and below each timing entry. Set one non-negative number to change all entry rows together.
|
|
604
|
+
|
|
605
|
+
The same timing fit values can be passed to `mountRaceCanvas()` when `includeTimingTower` is enabled. Standalone timing towers are capped by `--timing-board-max-width` and fill their mount root height; placing the root in a fixed-height container makes only the timing entries scroll. Timing entries always stack from the top as compact content-sized rows, so P1/P2 occupy the same vertical positions whether the race has 2 cars or 20. Use `timingEntryVerticalPadding` when the tower needs looser or denser row spacing.
|
|
531
606
|
|
|
532
|
-
The
|
|
607
|
+
The timing tower defaults to `Int` mode and includes a single compact `Int`/`Gap` header toggle unless `ui.timingGapModeToggle: false` is set. The toggle lives in the timing header's gap column and is package-owned: it keeps the same header alignment as `POS`, `TEAM`, `PROJECT`, and `TYRE`, uses a practical `44px` hit target, and draws selected/focus states inside the tower header so the broadcast proportions do not shift. Hosts should not replace this with custom CSS against package internals. If a host needs a different control placement, hide the header toggle and call the controller methods from host-owned UI instead.
|
|
533
608
|
|
|
534
|
-
|
|
609
|
+
Hosts can set the initial mode with `ui.timingGapMode` and can change it at any time with `setTimingGapMode('interval' | 'leader')`, `getTimingGapMode()`, or `toggleTimingGapMode()`. `Int` shows the interval to the car ahead, while `Gap` shows total gap to the leader. Seconds gaps are measured from hidden fixed timing-line crossings on the track. If a car is one or more whole laps behind in the selected mode, the tower shows labels such as `+1` or `+2` instead of a seconds estimate.
|
|
535
610
|
|
|
536
611
|
Other UI switches:
|
|
537
612
|
|
|
@@ -553,7 +628,7 @@ Mounted package surfaces include a lightweight red start-light loading overlay.
|
|
|
553
628
|
|
|
554
629
|
The runtime also pauses its render ticker when the race canvas is offscreen or the browser tab is hidden. This keeps pages with multiple PaddockJS embeds responsive without requiring host code to manually start and stop each simulator. At `5x` and `10x` browser playback, noncritical timing/readout DOM refreshes run at a lower cadence while fixed-step simulation and race events keep using authoritative race state.
|
|
555
630
|
|
|
556
|
-
Lifecycle callbacks are optional and host-owned. PaddockJS emits `onLoadingChange`, `onReady`, `onError`, `onDriverSelect`, `onRaceEvent`, `onLapChange`, and `onRaceFinish`; callback errors are routed to `onError` when provided and do not stop the simulator loop. Race snapshots include per-car interval timing, leader-gap timing, whole-lap gap counts, calibrated `speedKph`, automatic `track.sectors`, hidden `track.timingLines`, per-car `lapTelemetry`, finish state, `raceControl.winner` after the first finisher, and final `raceControl.classification` only after the whole field is finished or DNF. Sector telemetry clears future-sector values so banners and sidebars show completed splits before the active sector plus the active live timer, not stale later-sector entries. Cars that have crossed the line before full race completion expose `raceStatus: 'waved-flag'` / `wavedFlag: true` and stay frozen in provisional finish order; later barrier contact or stalled-off-track detection does not turn that result into DNF. Destroyed/out-of-race cars expose DNF metadata, show `DNF` at the bottom of the timing tower, render faded/gray in the race canvas, and appear after finishers in final classification with no finish time. If a DNF car is restored before final classification, it re-enters live timing and the race waits for it again; once `raceControl.finished` is true, classification stays final. Final classification applies time penalties and unserved service conversions through `adjustedFinishTime`, then applies position-drop and disqualification consequences to finishers before DNF entries. The field then circulates in safety-car mode and the race canvas shows a package-owned winner banner.
|
|
631
|
+
Lifecycle callbacks are optional and host-owned. PaddockJS emits `onLoadingChange`, `onReady`, `onError`, `onDriverSelect`, `onRaceEvent`, `onLapChange`, and `onRaceFinish`; lifecycle callback errors are routed to `onError` when provided and do not stop the simulator loop. `onDriverOpen(driver)` is host-owned navigation code and is not wrapped as a lifecycle callback. Race snapshots include per-car interval timing, leader-gap timing, whole-lap gap counts, calibrated `speedKph`, automatic `track.sectors`, hidden `track.timingLines`, per-car `lapTelemetry`, finish state, `raceControl.winner` after the first finisher, and final `raceControl.classification` only after the whole field is finished or DNF. Sector telemetry clears future-sector values so banners and sidebars show completed splits before the active sector plus the active live timer, not stale later-sector entries. Cars that have crossed the line before full race completion expose `raceStatus: 'waved-flag'` / `wavedFlag: true` and stay frozen in provisional finish order; later barrier contact or stalled-off-track detection does not turn that result into DNF. Destroyed/out-of-race cars expose DNF metadata, show `DNF` at the bottom of the timing tower, render faded/gray in the race canvas, and appear after finishers in final classification with no finish time. If a DNF car is restored before final classification, it re-enters live timing and the race waits for it again; once `raceControl.finished` is true, classification stays final. Final classification applies time penalties and unserved service conversions through `adjustedFinishTime`, then applies position-drop and disqualification consequences to finishers before DNF entries. The field then circulates in safety-car mode and the race canvas shows a package-owned winner banner.
|
|
557
632
|
|
|
558
633
|
## License
|
|
559
634
|
|
package/docs/architecture.md
CHANGED
|
@@ -103,15 +103,15 @@ Responsibilities:
|
|
|
103
103
|
`src/environment/` owns the browser-free expert environment:
|
|
104
104
|
|
|
105
105
|
- `index.js` and `index.d.ts` expose the public subpath API.
|
|
106
|
-
- `runtime.js` owns environment-loop `reset()`, `step(actions)`, `resetDrivers(placements)`, `getObservation()`, and `getState()` around an injected race-simulation host. It also owns partial reset option merging, preserving omitted nested plain-object groups while replacing arrays and explicit scenario placement maps. It owns per-driver episode bookkeeping for batched environments and formats result state as `full`, `minimal`, or `none` without changing simulator stepping. `resetDrivers()` reapplies normal runoff/barrier classification to the selected cars after placement and before result construction, clears only selected driver episode terminal state, and does not rewind global `info.step`.
|
|
106
|
+
- `runtime.js` owns environment-loop `reset()`, `step(actions)`, `resetDrivers(placements)`, `getObservation()`, and `getState()` around an injected race-simulation host. It also owns partial reset option merging, preserving omitted nested plain-object groups while replacing arrays and explicit scenario placement maps. It owns per-driver episode bookkeeping for batched environments and formats result state as `full`, `minimal`, or `none` without changing simulator stepping. `resetDrivers()` reapplies normal runoff/barrier classification to the selected cars after placement and before result construction, clears only selected driver episode terminal state, and does not rewind global `info.step`. Reset-only observation scope affects the returned observation and metrics maps, while full `info.drivers` remains scoped to each controlled driver's own episode state. Reward callbacks are transition-only and run from `step(actions)`, not reset/read result construction.
|
|
107
107
|
- `race/stalledDnf.js` owns the optional stalled off-track retirement rule. It consumes current wheel/track surface state after vehicle physics, ignores pre-start/red-flag/finished/pit-controlled states, tracks per-car stopped time below the configured speed threshold, and converts eligible stuck cars into the existing DNF path with `reason: 'stalled-off-track'`. Other modules should consume the resulting `outOfRace`/`dnf` state instead of reimplementing stalled detection.
|
|
108
108
|
- `options.js` validates `controlledDrivers`, scenario participants, reset placement config, frame skip, action policy, sensor config, and episode limits.
|
|
109
109
|
- `actions.js` maps normalized public controls onto simulator steering/throttle/brake controls plus pit intent and optional target compound requests. It treats steering, throttle, and brake as required vehicle-control fields so broken model output is reported instead of silently becoming zeroed controls.
|
|
110
110
|
- `scenarios.js` owns environment reset placement presets, absolute placements, and relative traffic layouts. It applies them through simulator state APIs during environment creation/reset only; it must not create policy-time teleport or assisted-control paths.
|
|
111
|
-
- `observations.js`, `sensors.js`, and `events.js` build sensor-style observations, versioned fixed-schema vectors, track lookahead/curvature, ray/nearby-car readings, and global/per-driver events. Observation output formatting is separate from object/vector construction so compact training loops can request vector-only results while `getObservationSpec()` remains the schema source. Vector-only mode uses a direct vector path and can return `Float32Array` buffers without building the full public object observation. When a loop requests vector-only, schema-free, no-state output, `runtime.js` uses the internal `snapshotTraining()` path instead of the heavier public observation snapshot;
|
|
111
|
+
- `observations.js`, `observationVector.js`, `sensors.js`, and `events.js` build sensor-style observations, versioned fixed-schema vectors, track lookahead/curvature, ray/nearby-car readings, and global/per-driver events. `observations.js` owns object observation assembly and direct compact-source preparation, while `observationVector.js` is the single owner of model-facing vector order, schema entries, and typed-array formatting for both object-backed and direct vector paths. Observation output formatting is separate from object/vector construction so compact training loops can request vector-only results while `getObservationSpec()` remains the schema source. Vector-only mode uses a direct vector path and can return `Float32Array` buffers without building the full public object observation. When a loop requests vector-only, schema-free, no-state output, `runtime.js` uses the internal `snapshotTraining()` path instead of the heavier public observation snapshot; returned state still uses public snapshot shapes. Environment-owned simulations always use the internal track query index because repeated track/surface/ray queries otherwise dominate step cost. `sensors.js` is a compatibility barrel; nearby-car scans, ray defaults, ray config normalization, track rays, surface rays, indexed ray-band intersections, car rays, body senses, contact-patch senses, boundary senses, opponent radar, and ray geometry live under `src/environment/sensors/`. Expensive surface-ray channels are opt-in and appear in the vector schema whenever requested. Replay-ghost sensor type flags are also part of compact ray/nearby-car vectors so vector-only consumers can distinguish real cars from opt-in references. Driver rays use a precision-aware cached origin state and shared per-observation ray target context. Driver `precision: 'driver'` road-edge, kerb, and illegal-surface channels use the canonical indexed projection path with driver-precision validation. Destroyed/out-of-race cars keep the active ray schema but short-circuit to miss-valued rays before creating track ray contexts, which prevents terminal cars in batch training from repeatedly querying far-out geometry. Pit-connector and unusual cases can still use sampled validation internally. Ray precision defaults to the model-facing `driver` contract; `debug` precision is diagnostic-only and must not be silently substituted into policy inputs or model-sense visualization.
|
|
112
112
|
- `metrics.js` owns reward-neutral per-driver facts such as progress delta, legal progress delta, off-track/severe-cut state, destroyed state, low-speed state, spin/backwards/instability state, lap completion, lap time, and contact count. Contact metrics dedupe the identifiers on each normalized physical contact event so one event increments each involved driver once. It must not encode or choose rewards.
|
|
113
|
-
- `recorder.js` owns neutral rollout transition export. It
|
|
114
|
-
- `controllerLoop.js` owns browser/headless controller orchestration around an injected runtime. It may lazily reset a fresh runtime before scheduled playback, but public `reset()` remains an explicit playback stop. Controller contexts report current `actions` separately from `previousActions`, where previous means the last action map actually applied before the current physics step. Scheduled playback catches controller/runtime failures, stops the loop, and exposes the thrown value through loop stats.
|
|
113
|
+
- `recorder.js` owns neutral rollout transition export. It snapshots observations, actions, rewards, next observations, terminal flags, and info at record time and does not interpret rewards or policies.
|
|
114
|
+
- `controllerLoop.js` owns browser/headless controller orchestration around an injected runtime. It may lazily reset a fresh runtime before scheduled playback, but public `reset()` remains an explicit playback stop. Controller contexts report current `actions` separately from `previousActions`, where previous means the last action map actually applied before the current physics step. It maintains an observation cache so reset-only `resetDrivers()` results can stay small without handing null observations to the next batch decision for non-reset controlled drivers. Scheduled playback catches controller/runtime failures, stops the loop, and exposes the thrown value through loop stats.
|
|
115
115
|
- `evaluation.js` owns deterministic evaluation cases and metrics. It can run a supplied policy against fixed seeds/scenarios, internally requests the minimal snapshot needed when compact no-state base options are supplied, and reuses environment metric semantics for legal surfaces and contacts. It must not update models or define reward objectives.
|
|
116
116
|
- `workerProtocol.js` owns the JSON-serializable wrapper used by external bridges. It forwards reset/step/spec/state messages to an environment instance, including `getState` output selection, and does not choose Python, Gymnasium, PettingZoo, or storage infrastructure.
|
|
117
117
|
|
|
@@ -119,7 +119,7 @@ The environment subpath must not import `src/index.js`, package CSS, PixiJS, `F1
|
|
|
119
119
|
|
|
120
120
|
`src/simulation/rulesConfig.js` is the public rules normalization facade. Defaults live in `src/simulation/rules/ruleDefaults.js`, ruleset presets in `rulesetPresets.js`, merge/value helpers in `ruleConfigMerge.js`, module normalization in `moduleConfig.js`, and penalty consequence normalization in `penaltyConfig.js`. Race modules should be added through those focused files first, then consumed by simulation logic through the normalized `race.rules` object.
|
|
121
121
|
|
|
122
|
-
`src/simulation/track/trackModel.js` is the canonical track-model facade. Procedural centerline generation, validation, sample rebuilding, start-straight normalization, sectors, DRS zones, pit-lane layout/access/state, spatial query indexing, and spatial queries live in focused `src/simulation/track/*` modules. `src/simulation/trackModel.js` remains a compatibility re-export for tests or older internal imports, but new production code should import the canonical track module. `buildTrackModel()` attaches a non-enumerable internal `track.queryIndex` after samples, DRS, sectors, and pit-lane geometry are finalized, and cached built models freeze their static geometry so consumers cannot mutate shared pit-lane data between builds. Race simulations clone the built track to own mutable timing/pit state and
|
|
122
|
+
`src/simulation/track/trackModel.js` is the canonical track-model facade. Procedural centerline generation, validation, sample rebuilding, start-straight normalization, sectors, DRS zones, pit-lane layout/access/state, spatial query indexing, and spatial queries live in focused `src/simulation/track/*` modules. `src/simulation/trackModel.js` remains a compatibility re-export for tests or older internal imports, but new production code should import the canonical track module. `buildTrackModel()` attaches a non-enumerable internal `track.queryIndex` after samples, DRS, sectors, and pit-lane geometry are finalized, and cached built models freeze their static geometry so consumers cannot mutate shared pit-lane data between builds. Race simulations clone the built track to own mutable timing/pit state and always attach a fresh runtime index fork. `trackQueryIndex.js` owns the internal indexed-query orchestration over typed centerline segment data, arc-length buckets, surface band thresholds, and deterministic nearest/ray query selection. Generic uniform grid operations live in `trackQueryGrid.js`, scratch buffer/epoch reuse lives in `trackQueryScratch.js`, query diagnostics live in `trackQueryStats.js`, and pit-lane road/box grid construction plus pit candidate lookups live in `trackQueryPitIndex.js`. Public callers still use `nearestTrackState()` and the same snapshot shapes; the index is internal infrastructure and must not leak into JSON snapshots or host contracts. Indexed nearest lookup treats progress hints only as optimization bounds, resolves equal-distance centerline segment ties deterministically inside the index, and proves finite-point nearest projections through the tight segment grid before falling back to a deterministic global indexed segment scan only if the grid cannot produce candidates. Missing indexes are programmer errors on built runtime tracks. Ray-boundary queries walk the tight segment grid along the ray corridor instead of querying the expanded recovery grid, which keeps compact training-track profiles from producing thousands of false candidate segments per ray. The model explicitly straightens the start/finish window so the starting grid, pit-entry approach area, and immediate post-line exit area are geometrically straight instead of merely choosing the least-curved generated segment. The pit lane is generated next to that start straight for every built track and exposes entry/exit connectors, explicit procedural road centerlines that overlap the track surface, connect on the lane-facing side of the main track, are tangent to the track at merge points and to the main pit lane at pit-lane endpoints, a straight main fast lane sized from the team/box run plus bounded entry/exit buffers, a parallel working lane, one shared service area per team, queue geometry behind each service area, and two garage boxes per team. `src/rendering/proceduralTrackAsset.js` is now only the Pixi container lifecycle wrapper; main-circuit drawing, pit-lane drawing, grid rendering, finish-line rendering, material constants, render geometry, and offset-stroke safety live under `src/rendering/track/`. `F1SimulatorApp` overlays the dynamic pit-lane status light because open/closed/red-flag state belongs to race control, not the static track texture.
|
|
123
123
|
|
|
124
124
|
`src/simulation/rules/` owns focused rule calculation helpers. Each stewarded rule should have its own function and, once non-trivial, its own file. `raceSimulation.js` should orchestrate timing/state and call those helpers; rule modules should return events or penalty payloads rather than mutating the whole simulation directly.
|
|
125
125
|
|
|
@@ -149,7 +149,7 @@ Responsibilities:
|
|
|
149
149
|
- Restart behavior for race data, seed, and track changes. Asset URL changes and browser expert mode changes are intentionally outside restart because texture loading and ticker ownership are part of initialization.
|
|
150
150
|
- Lifecycle cleanup, including partial-init failure cleanup and destruction of replaced PixiJS display children without destroying shared textures.
|
|
151
151
|
|
|
152
|
-
`src/app/camera/` owns camera state, camera constants, camera-safe-area measurement, track/pit-lane bounds fitting, zoom limits, mode availability, and target/frame calculation for overview, leader, selected, show-all, and pit cameras.
|
|
152
|
+
`src/app/camera/` owns camera state, camera constants, camera-safe-area measurement, track/pit-lane bounds fitting, zoom limits, mode availability, rotation, and target/frame calculation for overview, leader, selected, driver, show-all, and pit cameras.
|
|
153
153
|
|
|
154
154
|
`src/app/rendering/` owns PixiJS rendering surfaces:
|
|
155
155
|
|
|
@@ -164,7 +164,7 @@ Responsibilities:
|
|
|
164
164
|
|
|
165
165
|
`src/app/readouts/` owns generated-DOM readout rendering:
|
|
166
166
|
|
|
167
|
-
- `timingTowerRenderer.js` owns timing tower rows, gap
|
|
167
|
+
- `timingTowerRenderer.js` owns timing tower rows, runtime gap-mode labels/toggle state, waved-flag labels, and timing penalty badges. A single simulator may mount more than one timing tower through standalone and embedded composable surfaces, so timing row rendering fans out through plural timing-list bindings while keeping row markup/caching in this focused renderer.
|
|
168
168
|
- `telemetryRenderer.js` owns selected-car telemetry and lap/sector readouts.
|
|
169
169
|
- `carOverviewRenderer.js` owns driver/vehicle overview field selection and rendering.
|
|
170
170
|
- `raceStatusRenderer.js` owns race mode/lap/DRS/contact/start-light/finish readouts.
|
|
@@ -178,15 +178,19 @@ Warmup ownership is split intentionally: `src/simulation/warmup/runtimeWarmup.js
|
|
|
178
178
|
|
|
179
179
|
When `options.expert.enabled` is true, `F1SimulatorApp` creates a narrow browser expert adapter around its existing `this.sim` race simulation. The adapter uses the same shared environment runtime as the headless API, but it must not create a second race simulation for the visual mount. Expert browser mounts disable automatic ticker-driven simulation advancement; the canvas updates only after `simulator.expert.reset()` or `simulator.expert.step(actions)` renders the new snapshot. External renderer mode may temporarily redraw the shared track asset from authoritative external snapshots; detach restores the local simulation track before local expert stepping resumes. The shared runtime owns controlled-driver pit intent defaults: controlled cars start with `pitIntent` set to `0`, tire-threshold automatic pit calls are disabled for them, and expert actions may request `0`, `1`, or `2` plus optional `pitCompound` through the simulation API instead of steering into the pit lane directly. Expert mode is a mount-time boundary; runtime restart rejects `expert` changes instead of attempting to rewire ticker ownership in place.
|
|
180
180
|
|
|
181
|
+
`src/app/BrowserExpertExternalRenderer.js` owns the external-renderer bridge used by browser expert mode: source subscription lifecycle, external-to-local driver-id mapping, external frame observation/event/penalty id rewriting, external track-surface redraws, local track restoration on detach, and external-renderer state reporting. `BrowserExpertAdapter.js` remains the local visual expert runtime adapter and should not grow those external-frame responsibilities again.
|
|
182
|
+
|
|
181
183
|
Expert sensor visualization belongs to the browser app layer, not the headless environment. The environment result owns the observation contract; `BrowserExpertAdapter` passes that observation into `F1SimulatorApp.renderExpertFrame()`, and `src/app/rendering/expertSensorRenderer.js` draws opt-in sensor rays in a Pixi world layer so they share the same camera transform as the track and cars. Multi-driver expert mounts visualize the selected controlled car by default, with an explicit `drivers: 'all'` opt-in for heavier all-controlled-car overlays. Ray visualization draws every detected model-facing channel as a separate marker rather than choosing only the nearest hit, which keeps road-edge, kerb, illegal-surface, and car detection debuggable. Barrier walls are track geometry and destruction boundaries, not model-facing ray hits; active ray objects, vectors, schemas, and visualizations must not expose a `barrier` ray channel. The Policy Runner senses panel follows the same boundary for all senses: it reads the active observation object/vector and may show separate diagnostics only when those are labeled as diagnostics, not as model input.
|
|
182
184
|
|
|
183
185
|
Track material rendering must use the same surface-band thresholds as simulation. `src/rendering/track/trackMaterialRenderer.js` exposes `getTrackMaterialBands(track)` as the rendering-side band contract derived from `track.width`, `track.kerbWidth`, `track.gravelWidth`, `track.runoffWidth`, and `track.barrierWidth`; gravel, runoff, visible barrier walls, ray surface hits, wheel surfaces, and barrier destruction must not invent independent offsets or hardcoded widths. Barrier contact uses the visible vehicle footprint against the rendered wall's inner face so visual contact, destruction, and the environment's terminal state agree.
|
|
184
186
|
|
|
185
|
-
Environment sensor target selection belongs to `src/environment/sensors/sensorTargets.js`. It adapts real cars and opt-in replay ghosts into a common sensor target shape while preserving the invariant that replay ghosts stay out of `snapshot.cars` and race systems.
|
|
187
|
+
Environment sensor target selection belongs to `src/environment/sensors/sensorTargets.js`. It adapts real cars and opt-in replay ghosts into a common sensor target shape while preserving the invariant that replay ghosts stay out of `snapshot.cars` and race systems. Radar enrichment keys targets by entity type plus id, so duplicate ids between real cars and replay ghosts do not cross-contaminate velocity-derived nearby-car facts.
|
|
186
188
|
|
|
187
189
|
`F1SimulatorApp.js` should stay a facade/orchestrator. New camera, rendering, readout, banner, or runtime behavior should usually land in the matching `src/app/*/` ownership module rather than expanding the app class.
|
|
188
190
|
|
|
189
|
-
`src/app/domBindings.js` owns DOM selector lookup
|
|
191
|
+
`src/app/domBindings.js` owns DOM selector lookup plus null-safe text and CSS custom-property writes for package-generated UI surfaces. It exposes both singular compatibility handles and plural collections for package-owned readouts that can appear more than once in the same simulator root, such as timing tower rows, lap counters, race-control status slots, and race-data panels. Shared helpers in this module resolve plural collections with singular fallbacks, skip duplicate node work, and avoid repeated identical text/style writes, so focused renderers do not each reimplement that control flow. Race-data panel bindings are grouped at lookup time so banner renderers and controls update embedded lower-thirds and standalone panels without repeated runtime DOM queries. Car/driver overview field label/value nodes are also grouped once at lookup time so overview renders update cached field bindings instead of rediscovering children on every changed overview render.
|
|
192
|
+
|
|
193
|
+
`src/app/layoutSupport.js` owns the package support-envelope observer for browser UI surfaces. It measures generated `data-paddock-component` surfaces and all-in-one shells, sets `data-paddock-size-unsupported` when a shell/mount is narrower than `320px`, when a component is below its component-specific inline minimum, or when a surface is below its minimum usable block size, and leaves CSS to show the accessible package-owned placeholder. Component-specific inline minima matter because package internals such as the broadcast timing tower are intentionally narrower than `320px` and must not self-report unsupported at their valid package-owned width. `src/app/raceOverlayClearanceSupport.js` owns the related narrow race-overlay measurement: it observes responsive embedded timing canvases, checks whether the lower-third would cover timing-row entries in the open reveal geometry, and sets a package CSS variable/class only when extra bottom clearance is required. The lower-third may cover timing-tower chrome/background that has no entries. These observers do not change simulation state, camera math, public API, or host layout; they only record whether the current package-owned surface can render safely.
|
|
190
194
|
|
|
191
195
|
## Simulation Core
|
|
192
196
|
|
|
@@ -245,13 +249,13 @@ Responsibilities:
|
|
|
245
249
|
|
|
246
250
|
`src/simulation/rules/penaltyStats.js` owns penalty-stat aggregation and lookup helpers.
|
|
247
251
|
|
|
248
|
-
`src/simulation/vehicle/contactResolution.js` owns physical collision resolution and contact velocity response. Stewarding remains separate from physical response.
|
|
252
|
+
`src/simulation/vehicle/contactResolution.js` owns physical collision resolution and contact velocity response. Stewarding remains separate from physical response. In advanced mode, every collision branch that changes speed also keeps `velocityX/Y` synchronized, including contacts where one car is fixed by pit entry, queue, service, or exit routing.
|
|
249
253
|
|
|
250
254
|
`src/simulation/vehicle/runoffResponse.js` owns non-penalty off-track vehicle correction.
|
|
251
255
|
|
|
252
256
|
`src/simulation/snapshots/raceSnapshots.js` owns public, render, and observation snapshot assembly.
|
|
253
257
|
|
|
254
|
-
Weather effects, reliability failures, and fuel-load performance effects are not active
|
|
258
|
+
Weather effects, reliability failures, and fuel-load performance effects are not active `3.0.0` behavior. Their future ownership should stay separate from the race orchestrator: weather belongs in a future `src/simulation/weather/` module that returns track/session condition modifiers, reliability belongs in a future `src/simulation/reliability/` module that emits deterministic failure/degradation events, and fuel-load effects belong in a future vehicle-adjacent performance module that adjusts mass/pace through explicit inputs rather than hidden mutation.
|
|
255
259
|
|
|
256
260
|
`snapshot()` is the full public data contract and must remain stable for host callbacks, environment state, and external callers. Internal browser/rendering paths use lean read models such as `snapshotRender()` so the 60 FPS loop does not serialize setup, wheels, penalties, and other non-render fields every frame. Environment and sensor code may use similarly narrow internal views, cache shared per-observation ray origin state, and broadphase car-ray checks before exact footprint intersection, but those must not change the public `RaceSnapshot` shape.
|
|
257
261
|
|
|
@@ -263,7 +267,9 @@ Weather effects, reliability failures, and fuel-load performance effects are not
|
|
|
263
267
|
|
|
264
268
|
`src/simulation/vehicle/wheelSurface.js` owns per-wheel track sampling and the effective car surface. Surface priority, analytic main-track classification, and pit-lane/connector classification are split into `surfacePriority.js`, `mainTrackWheelSurface.js`, and `pitWheelSurface.js`. On normal main-track running it uses the cached wheel geometry and the car center's track normal to analytically classify each wheel patch from signed offsets. It falls back to full patch sampling near pit connectors and inside pit-lane states. `vehiclePhysics.js` consumes that effective surface through the car track state, and separately compares left-side and right-side wheel resistance to add a small capped yaw bias toward the slower side.
|
|
265
269
|
|
|
266
|
-
`src/simulation/vehiclePhysics.js` owns vehicle integration using the already-resolved wheel surfaces and wheel-state resistance imbalance. It exposes the normalized `physicsMode` contract and routes between the compatibility arcade integrator and the opt-in
|
|
270
|
+
`src/simulation/vehicle/vehiclePhysics.js` owns vehicle integration using the already-resolved wheel surfaces and wheel-state resistance imbalance. It exposes the normalized `physicsMode` contract and routes between the compatibility arcade integrator and the opt-in advanced integrator. The advanced path owns 2D velocity integration, yaw response, traction-budget calculation, speed-sensitive steering, steering scrub, aero drag/downforce balance, per-wheel surface averaging, derived slip-angle telemetry, advanced surface coefficients, and telemetry fields; steering scrub opposes signed forward motion so reverse slides do not gain energy from steering loss. Driver AI and environment policies still provide only steering/throttle/brake/pit intent.
|
|
271
|
+
|
|
272
|
+
`src/simulation/vehicle/vehicleState.js` owns external state mutation from simulator and environment reset APIs. It rejects non-finite numeric partial state and resynchronizes advanced-mode velocity from speed/heading when callers do not provide an explicit velocity vector, so scenario placement and `resetDrivers()` cannot leave stale physics velocity behind.
|
|
267
273
|
|
|
268
274
|
`src/simulation/rules/pitLaneSpeedingSteward.js` owns pit-speed-limit review. `raceSimulation.js` calls it after authoritative race-state recalculation so it reads the same pit-lane part classification as snapshots and track-limit stewarding. The steward only checks speed-limited pit-lane parts (`fast-lane`, `working-lane`, service areas, and garage boxes), leaving pit-entry and pit-exit connector roads legal but not speed-limited.
|
|
269
275
|
|
|
@@ -273,7 +279,7 @@ Browser mounts generate a fresh procedural seed when `trackSeed` is omitted; exp
|
|
|
273
279
|
|
|
274
280
|
`src/rendering/renderSnapshot.js` owns interpolation for rendering. It accepts either the full public snapshot or the lean render snapshot; render-only callers should prefer the lean snapshot.
|
|
275
281
|
|
|
276
|
-
The app runtime pauses its PixiJS ticker when the race canvas is outside the viewport or the document is hidden, then resets the frame clock before resuming. This prevents host pages with several simulator embeds from running every race while only one is visible, and avoids a large simulation catch-up step when the canvas re-enters view. Camera safe-area layout measurements are cached and invalidated by resize observation so the 60 FPS render path does not force repeated DOM geometry reads. Camera framing derives a cached active-track bounds box from generated samples plus pit-lane extent; overview uses that frame directly, and every camera uses it as the zoom-out floor. The first camera frame is applied immediately, then later camera mode changes interpolate target position and scale so leader/selected/overview/show-all/pit switches do not jump the world view. Runtime readouts avoid redundant DOM writes for unchanged text, timing markup, finish classification, and static selected-car overview data, and `updateDom()` reuses its supplied full snapshot for camera-control availability instead of taking another public snapshot. Static pit-lane status graphics are redrawn only when their status/geometry key changes, and DRS trail histories are pruned in place. Startup marks the initial DOM refresh time so the first ticker frame does not immediately redo the same full readout update. At `5x` and `10x` browser playback, noncritical DOM/timing refreshes are throttled more aggressively while fixed-step simulation, event emission, and rendering continue from authoritative simulation state. Long project-radio delays are also treated as stale schedule state instead of replaying every missed lower-third transition.
|
|
282
|
+
The app runtime pauses its PixiJS ticker when the race canvas is outside the viewport or the document is hidden, then resets the frame clock before resuming. Runtime visibility uses `IntersectionObserver` plus a bounded canvas-geometry check on observer, scroll, resize, focus, and page-show events so a visible canvas cannot remain paused because of a stale observer result. Ticker synchronization also compares the intended runtime state with PixiJS' actual `ticker.started` state before deciding whether to call `start()` or `stop()`. This prevents host pages with several simulator embeds from running every race while only one is visible, and avoids a large simulation catch-up step when the canvas re-enters view. Camera safe-area layout measurements are cached and invalidated by resize observation so the 60 FPS render path does not force repeated DOM geometry reads. Camera framing derives a cached active-track bounds box from generated samples plus pit-lane extent; overview uses that frame directly, and every camera uses it as the zoom-out floor. The first camera frame is applied immediately, then later camera mode changes interpolate target position and scale so leader/selected/overview/show-all/pit switches do not jump the world view. Runtime readouts avoid redundant DOM writes for unchanged text, timing markup, finish classification, and static selected-car overview data, and `updateDom()` reuses its supplied full snapshot for camera-control availability instead of taking another public snapshot. Static pit-lane status graphics are redrawn only when their status/geometry key changes, and DRS trail histories are pruned in place. Startup marks the initial DOM refresh time so the first ticker frame does not immediately redo the same full readout update. At `5x` and `10x` browser playback, noncritical DOM/timing refreshes are throttled more aggressively while fixed-step simulation, event emission, and rendering continue from authoritative simulation state. Long project-radio delays are also treated as stale schedule state instead of replaying every missed lower-third transition.
|
|
277
283
|
|
|
278
284
|
## Data Layer
|
|
279
285
|
|
|
@@ -301,6 +307,8 @@ The app runtime pauses its PixiJS ticker when the race canvas is outside the vie
|
|
|
301
307
|
- Race telemetry drawer template.
|
|
302
308
|
- Car/driver overview panel.
|
|
303
309
|
|
|
310
|
+
The package-owned component inventory is maintained in [Component Inventory](component_inventory.md). Use it before changing templates, DOM bindings, readout renderers, layout observers, or local-preview component usage so shared component behavior stays in focused helpers instead of drifting across all-in-one, composable, and derived mixed variants.
|
|
311
|
+
|
|
304
312
|
`src/ui/bannerTemplates.js` owns package banner markup:
|
|
305
313
|
|
|
306
314
|
- Top steward message for warnings and penalties.
|
|
@@ -310,17 +318,19 @@ The app runtime pauses its PixiJS ticker when the race canvas is outside the vie
|
|
|
310
318
|
|
|
311
319
|
`src/ui/templateUtils.js` owns shared template helpers such as escaping and loading-state markup. Banner templates and non-banner component templates should share helpers through this module instead of importing from each other.
|
|
312
320
|
|
|
313
|
-
`src/ui/shellTemplate.js` composes those component templates into the default all-in-one simulator DOM and package-owned layout presets such as `left-tower-overlay`. Telemetry graph/table surfaces are independent package-owned components controlled by `ui.telemetryModules` when used through stack/drawer templates; app readout modules render them from `car.lapTelemetry` without requiring host-owned DOM. The telemetry stack can embed the car/driver overview, owns vertical scrolling when the host constrains its height, and is also embedded by the hide/show race telemetry drawer. The overview is also a separately mountable component. The project and radio lower-thirds share the same race-data panel markup; runtime state only swaps content and mode classes. The optional project telemetry detail lives inside that shared lower-third, while the broadcast sector banner remains a separate lower-third-style sector graph that can be mounted standalone or embedded inside the race canvas only when a host explicitly asks for that independent popup. Readout modules bind the selected car name/code/color to it through the same readout path as the other telemetry surfaces. The race telemetry drawer template composes an external top control row, race canvas with embedded timing tower, project/radio lower-third, top steward message, safety-car control, and the telemetry stack in a
|
|
321
|
+
`src/ui/shellTemplate.js` composes those component templates into the default all-in-one simulator DOM and package-owned layout presets such as `left-tower-overlay`. Telemetry graph/table surfaces are independent package-owned components controlled by `ui.telemetryModules` when used through stack/drawer templates; app readout modules render them from `car.lapTelemetry` without requiring host-owned DOM. The telemetry stack can embed the car/driver overview, owns vertical scrolling when the host constrains its height, and is also embedded by the hide/show race telemetry drawer. The overview is also a separately mountable component. The project and radio lower-thirds share the same race-data panel markup; runtime state only swaps content and mode classes. The optional project telemetry detail lives inside that shared lower-third, while the broadcast sector banner remains a separate lower-third-style sector graph that can be mounted standalone or embedded inside the race canvas only when a host explicitly asks for that independent popup. Readout modules bind the selected car name/code/color to it through the same readout path as the other telemetry surfaces. The race telemetry drawer template composes an external top control row, race canvas with embedded timing tower, project/radio lower-third, top steward message, safety-car control, and the telemetry stack in a drawer. Its open/close state is owned by `F1SimulatorApp`; the safety-car control, project/radio banner mute toggle, and telemetry toggle stay in the top row while telemetry is open. Wide drawer layouts reserve final race-view space with a stable margin while the sidebar itself animates with a compositor transform; responsive narrow drawer layouts are enabled by default, stack the top workbench controls by container width, and reveal over the race view so mobile canvas height does not permanently collapse. The drawer race area uses the configured workbench height so host embeds do not leave unused black space below the simulation. The left-tower overlay preset is responsible for internal component placement and package-owned proportions; the project/radio lower-third remains owned by the race canvas so it can either use the race space beside the timing tower in `auto` sizing mode or overlap the tower when space is constrained. Composable hosts can also ask the race-canvas template to embed the timing tower directly with `includeTimingTower`, using the same expand-vs-scroll vertical fit contract on wide containers and a package-owned left reveal panel on narrow containers. In responsive narrow mode, the race-canvas min-height is governed by the timing tower/race-view minimum until runtime measurement shows the lower-third would cover one or more timing rows; only then does CSS receive the measured clearance needed to move the banner below the entries. `F1SimulatorApp` owns the timing reveal state, keeps closed narrow timing panels inert/hidden, installs the overlay-clearance observer, and resizes the renderer/camera during open, close, and host resize transitions without remounting the simulator. `src/app/layoutScheduler.js` owns the shared RAF coalescing/cancellation primitive used by layout support and overlay-clearance measurement so resize and mutation observers do not duplicate scheduling state. `ui.responsiveNarrowLayout` and matching composable mount options only toggle package-owned narrow template classes; they do not change simulation state or require host-owned layout patches. `src/app/camera/` measures the resulting timing-tower gutter when framing the PixiJS camera, whether the tower comes from the prebuilt shell or from an embedded composable race canvas. It also owns camera mode availability, wheel/button zoom for every camera mode, opt-in driver-camera rotation, hiding the pit camera control when the active track has no pit-lane geometry, and fitting the pit camera from operational `track.pitLane` lane, box, service, and queue bounds instead of host-provided coordinates or long access-road endpoints. On narrow hosts, closed timing reveals are outside the canvas safe area and open reveals are measured continuously by resize observation. Hosts should not provide the internal simulator markup or tune preset internals with raw sizing options.
|
|
314
322
|
|
|
315
323
|
Penalty UI is display-only. `src/app/banners/stewardMessageController.js` may show track-limit warning events and `snapshot.penalties` in the top steward message, and `src/app/readouts/timingTowerRenderer.js` may show timing-row penalty badges when the host enables those UI options, but the UI must not infer, modify, or recalculate steward decisions.
|
|
316
324
|
|
|
317
|
-
`src/config/defaultOptions.js` owns preset resolution, telemetry module normalization, the public theme contract, and
|
|
325
|
+
`src/config/defaultOptions.js` owns preset resolution, telemetry module normalization, browser warmup option normalization defaults, and deriving team theme selectors from normalized entry team metadata. `src/config/themeOptions.js` owns the public theme contract: semantic token resolution, generated opposite-mode value caching, known-token filtering, safe CSS color/size token validation, named derivative theme packages, component slot maps, component/team theme selectors, and legacy alias mapping for the old small color API. Presets are merged before host options; resolved theme fields are applied as package CSS variables by the all-in-one app and composable controller. Runtime selected-team theme context is cached so theme variables are not recomputed during normal render loops. This keeps sizing/color customization explicit without turning internal layout ratios into public API.
|
|
326
|
+
|
|
327
|
+
`src/config/restartOptions.js` owns shared restart-option merging for both `mountF1Simulator().restart()` and `createPaddockSimulator().restart()`. It preserves omitted driver/entry data, merges nested UI banner and asset texture groups, and resets prior UI/theme state when a restart supplies a new preset so the two browser mount surfaces cannot drift.
|
|
318
328
|
|
|
319
329
|
Race completion is owned by `src/simulation/raceSimulation.js`. The simulation records provisional `finishOrder` / `finishRank` as each car crosses the line and uses that order for snapshots until final classification exists, so app code never has to re-sort finished cars by live distance. Race retirement state is owned by `src/simulation/race/retirements.js`; it defines DNF detection and ordering while vehicle code only marks the physical destruction event. The app layer reads `raceControl.finished`, `winner`, `classification`, and per-car `raceStatus`/DNF fields from snapshots, renders the timing/winner states, and emits lifecycle callbacks. Penalty lifecycle, pit-stop penalty service, service conversion, time adjustment, position drops, grid drops, disqualification effects, and DNF classification placement are applied inside the simulation, not in the UI. UI code may display countdowns from `pitStop.phase`, `serviceRemainingSeconds`, and `penaltyServiceRemainingSeconds`, but it must not infer, serve, or recalculate steward outcomes from lap text, timing rows, or car position.
|
|
320
330
|
|
|
321
331
|
Composable hosts may choose where each package-owned component root is placed, but they still receive package-generated markup through the public mount functions. The controller marks each mounted root as an `f1-sim-component` styling scope so standalone pieces receive the same package variables as the all-in-one shell.
|
|
322
332
|
|
|
323
|
-
`src/styles.css` styles the generated shell, imports package fonts, caps timing-tower width for readability, and owns the
|
|
333
|
+
`src/styles.css` styles the generated shell, imports package fonts, caps timing-tower width for readability, and owns the timing-list scroll behavior. Timing rows are compact content-sized grid rows stacked from the top, with `ui.timingEntryVerticalPadding` setting one shared pixel padding value above and below every entry, so rank positions do not stretch or redistribute when the number of entries changes. The timing tower owns its runtime interval-vs-leader-gap switch, while `F1SimulatorApp` reads both seconds and whole-lap gap values from the race snapshot and formats positive lap deficits as `+N` before seconds. The compact `Int`/`Gap` header toggle is a timing-tower style contract, not host CSS: the grid reserves a stable gap column, the header labels and toggle share one vertical center, the visible pill stays inside the header, and the clickable target remains `44px` without changing tower width. Fixed hidden timing-line creation, crossing timestamps, and seconds-gap calculation stay inside `src/simulation/timing/`. Sector-map surfaces read `lapTelemetry.sectorProgress` for bar fill and `lapTelemetry.liveSectors` for live active-sector time; the simulation owns those values so UI components do not infer active split state from DOM state. Future sectors are cleared by the simulation and ignored defensively by the renderer, so banner/sidebar sector nodes cannot keep stale timing text or yellow/purple/green performance classes after the active sector changes. Component templates include lightweight package-owned loading overlays; `F1SimulatorApp` removes them after startup initialization has completed.
|
|
324
334
|
|
|
325
335
|
The host page should only provide:
|
|
326
336
|
|