@inventure71/paddockjs 1.0.0 → 2.0.1
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 +58 -0
- package/INSTALL_AND_UPDATE.md +4 -3
- package/README.md +219 -12
- package/docs/architecture.md +126 -45
- package/docs/concepts.md +9 -5
- package/docs/custom_model_controller.md +329 -0
- package/docs/data_contract.md +317 -22
- package/docs/data_model.md +1 -1
- package/docs/index.md +10 -0
- package/docs/learnings.md +22 -0
- package/docs/rules.md +71 -14
- package/docs/sense_contract.md +59 -0
- package/docs/system_specs.md +75 -13
- package/docs/training.md +280 -32
- package/examples/python/README.md +62 -0
- package/examples/python/base_policy_server.py +191 -0
- package/examples/python/requirements.txt +2 -0
- package/package.json +12 -4
- package/src/api/PaddockSimulatorController.js +6 -33
- package/src/app/BrowserExpertAdapter.js +76 -9
- package/src/app/BrowserExpertExternalRenderer.js +303 -0
- package/src/app/F1SimulatorApp.js +291 -1630
- package/src/app/banners/bannerFormatters.js +55 -0
- package/src/app/banners/raceDataBannerController.js +141 -0
- package/src/app/banners/stewardMessageController.js +99 -0
- package/src/app/camera/cameraConstants.js +21 -0
- package/src/app/camera/cameraController.js +265 -0
- package/src/app/camera/cameraGeometry.js +176 -0
- package/src/app/domBindings.js +4 -0
- package/src/app/readouts/carOverviewRenderer.js +109 -0
- package/src/app/readouts/controlStateRenderer.js +37 -0
- package/src/app/readouts/raceStatusRenderer.js +133 -0
- package/src/app/readouts/readoutFormatters.js +58 -0
- package/src/app/readouts/telemetryRenderer.js +113 -0
- package/src/app/readouts/timingTowerRenderer.js +177 -0
- package/src/app/rendering/appAssets.js +38 -0
- package/src/app/rendering/carRenderer.js +286 -0
- package/src/app/rendering/displayUtils.js +22 -0
- package/src/app/rendering/drsTrailRenderer.js +90 -0
- package/src/app/rendering/expertSensorRenderer.js +126 -0
- package/src/app/rendering/pitLaneStatusRenderer.js +50 -0
- package/src/app/rendering/replayGhostRenderer.js +124 -0
- package/src/app/rendering/trackRenderer.js +25 -0
- package/src/app/runtime/frameLoop.js +66 -0
- package/src/app/runtime/runtimeTiming.js +34 -0
- package/src/app/runtime/runtimeVisibility.js +45 -0
- package/src/config/defaultOptions.js +20 -0
- package/src/config/restartOptions.js +34 -0
- package/src/environment/actions.js +13 -5
- package/src/environment/controllerLoop.js +261 -0
- package/src/environment/episode.js +98 -2
- package/src/environment/evaluation.js +54 -32
- package/src/environment/index.d.ts +376 -10
- package/src/environment/index.js +1 -0
- package/src/environment/metrics.js +159 -0
- package/src/environment/observationOptions.js +22 -1
- package/src/environment/observationVector.js +200 -0
- package/src/environment/observations.js +199 -141
- package/src/environment/options.js +37 -5
- package/src/environment/recorder.js +13 -6
- package/src/environment/rewards.js +13 -2
- package/src/environment/runtime.js +272 -23
- package/src/environment/scenarios.js +57 -9
- package/src/environment/sensors/bodySenses.js +23 -0
- package/src/environment/sensors/boundarySenses.js +17 -0
- package/src/environment/sensors/carRays.js +75 -0
- package/src/environment/sensors/contactSenses.js +32 -0
- package/src/environment/sensors/index.js +157 -0
- package/src/environment/sensors/indexedRayBands.js +103 -0
- package/src/environment/sensors/nearbyCars.js +52 -0
- package/src/environment/sensors/opponentRadar.js +75 -0
- package/src/environment/sensors/rayConfig.js +110 -0
- package/src/environment/sensors/rayDefaults.js +6 -0
- package/src/environment/sensors/rayGeometry.js +60 -0
- package/src/environment/sensors/rayGuards.js +19 -0
- package/src/environment/sensors/sensorTargets.js +66 -0
- package/src/environment/sensors/surfaceRays.js +360 -0
- package/src/environment/sensors/trackRays.js +424 -0
- package/src/environment/sensors.js +1 -367
- package/src/environment/specs.js +159 -26
- package/src/environment/workerProtocol.js +13 -1
- package/src/index.d.ts +171 -6
- package/src/index.js +6 -32
- package/src/rendering/proceduralTrackAsset.js +20 -823
- package/src/rendering/renderSnapshot.js +38 -12
- package/src/rendering/track/finishLineRenderer.js +34 -0
- package/src/rendering/track/gridRenderer.js +47 -0
- package/src/rendering/track/offsetStrokeSafety.js +136 -0
- package/src/rendering/track/pitLaneRenderer.js +248 -0
- package/src/rendering/track/trackMaterialRenderer.js +326 -0
- package/src/rendering/track/trackRenderConstants.js +38 -0
- package/src/rendering/track/trackRenderGeometry.js +94 -0
- package/src/simulation/collisionGeometry.js +1 -1
- package/src/simulation/driver/driverControlConstants.js +28 -0
- package/src/simulation/driver/driverController.js +47 -0
- package/src/simulation/driver/driverInput.js +28 -0
- package/src/simulation/driver/driverMath.js +6 -0
- package/src/simulation/driver/driverPersonality.js +25 -0
- package/src/simulation/driver/edgeRecovery.js +48 -0
- package/src/simulation/driver/racingControls.js +399 -0
- package/src/simulation/driver/racingLinePlan.js +166 -0
- package/src/simulation/driver/recoveryDynamics.js +38 -0
- package/src/simulation/driver/rejoinControls.js +213 -0
- package/src/simulation/driver/safetyCarControls.js +35 -0
- package/src/simulation/driver/trafficScan.js +51 -0
- package/src/simulation/driverController.js +4 -619
- package/src/simulation/participants/participantInteractions.js +120 -0
- package/src/simulation/pit/pitFlow.js +239 -0
- package/src/simulation/pit/pitIntent.js +92 -0
- package/src/simulation/pit/pitKinematics.js +24 -0
- package/src/simulation/pit/pitOccupancy.js +47 -0
- package/src/simulation/pit/pitPenaltyService.js +71 -0
- package/src/simulation/pit/pitQueue.js +60 -0
- package/src/simulation/pit/pitRouteMovement.js +167 -0
- package/src/simulation/pit/pitRouting.js +319 -0
- package/src/simulation/pit/pitService.js +43 -0
- package/src/simulation/pit/pitServiceConstants.js +21 -0
- package/src/simulation/pit/pitServiceProfile.js +45 -0
- package/src/simulation/pit/pitSnapshots.js +61 -0
- package/src/simulation/pit/pitState.js +113 -0
- package/src/simulation/pit/pitTireService.js +94 -0
- package/src/simulation/race/classification.js +104 -0
- package/src/simulation/race/gridPenalties.js +37 -0
- package/src/simulation/race/raceControlState.js +38 -0
- package/src/simulation/race/raceDistance.js +32 -0
- package/src/simulation/race/raceFinish.js +65 -0
- package/src/simulation/race/raceLifecycle.js +67 -0
- package/src/simulation/race/raceOrder.js +113 -0
- package/src/simulation/race/raceProgress.js +129 -0
- package/src/simulation/race/raceSetup.js +93 -0
- package/src/simulation/race/raceStep.js +80 -0
- package/src/simulation/race/redFlag.js +15 -0
- package/src/simulation/race/retirements.js +44 -0
- package/src/simulation/race/safetyCar.js +92 -0
- package/src/simulation/race/stalledDnf.js +77 -0
- package/src/simulation/raceSimulation.js +231 -2817
- package/src/simulation/replay/replayGhosts.js +128 -0
- package/src/simulation/rules/moduleConfig.js +72 -0
- package/src/simulation/rules/penaltyConfig.js +99 -0
- package/src/simulation/rules/penaltyEvents.js +18 -0
- package/src/simulation/rules/penaltyStats.js +26 -0
- package/src/simulation/rules/ruleConfigMerge.js +41 -0
- package/src/simulation/rules/ruleDefaults.js +85 -0
- package/src/simulation/rules/rulesReview.js +144 -0
- package/src/simulation/rules/rulesetPresets.js +47 -0
- package/src/simulation/rules/trackLimitsSteward.js +1 -1
- package/src/simulation/rulesConfig.js +5 -323
- package/src/simulation/snapshots/raceSnapshots.js +193 -0
- package/src/simulation/timing/drsTiming.js +87 -0
- package/src/simulation/timing/gapEstimation.js +38 -0
- package/src/simulation/timing/lapTelemetry.js +182 -0
- package/src/simulation/timing/raceTiming.js +15 -0
- package/src/simulation/timing/sectorPerformance.js +60 -0
- package/src/simulation/timing/timingConstants.js +5 -0
- package/src/simulation/timing/timingHistory.js +46 -0
- package/src/simulation/timing/timingLines.js +79 -0
- package/src/simulation/track/centerlineSpline.js +59 -0
- package/src/simulation/track/drsZones.js +67 -0
- package/src/simulation/track/pitLaneAccess.js +103 -0
- package/src/simulation/track/pitLaneLayout.js +395 -0
- package/src/simulation/track/pitLaneState.js +160 -0
- package/src/simulation/track/proceduralCenterline.js +237 -0
- package/src/simulation/track/sampleGeometry.js +49 -0
- package/src/simulation/track/spatialQueries.js +154 -0
- package/src/simulation/track/startStraight.js +141 -0
- package/src/simulation/track/trackConstants.js +109 -0
- package/src/simulation/track/trackGenerationOptions.js +283 -0
- package/src/simulation/track/trackMath.js +241 -0
- package/src/simulation/track/trackModel.js +240 -0
- package/src/simulation/track/trackQueryGrid.js +94 -0
- package/src/simulation/track/trackQueryIndex.js +659 -0
- 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/trackSectors.js +19 -0
- package/src/simulation/track/trackStatePolicy.js +24 -0
- package/src/simulation/track/trackValidation.js +98 -0
- package/src/simulation/trackModel.js +1 -1706
- package/src/simulation/vehicle/contactResolution.js +181 -0
- package/src/simulation/vehicle/mainTrackWheelSurface.js +82 -0
- package/src/simulation/vehicle/pitWheelSurface.js +69 -0
- package/src/simulation/vehicle/runoffResponse.js +87 -0
- package/src/simulation/vehicle/surfacePriority.js +28 -0
- package/src/simulation/vehicle/vehicleGeometry.js +247 -0
- package/src/simulation/vehicle/vehicleKinematics.js +37 -0
- package/src/simulation/vehicle/vehiclePhysics.js +364 -0
- package/src/simulation/vehicle/vehicleSnapshots.js +327 -0
- package/src/simulation/vehicle/vehicleState.js +220 -0
- package/src/simulation/vehicle/wheelSurface.js +152 -0
- package/src/simulation/vehicleGeometry.js +1 -247
- package/src/simulation/vehiclePhysics.js +1 -136
- package/src/simulation/warmup/runtimeWarmup.js +224 -0
- package/src/simulation/wheelSurface.js +1 -338
- package/src/styles.css +42 -0
- package/src/ui/cameraControlsTemplate.js +20 -0
- package/src/ui/carOverviewTemplate.js +33 -0
- package/src/ui/componentTemplates.js +14 -360
- package/src/ui/raceCanvasTemplate.js +69 -0
- package/src/ui/raceControlsTemplate.js +36 -0
- package/src/ui/shellTemplate.js +5 -4
- package/src/ui/telemetryDrawerTemplate.js +55 -0
- package/src/ui/telemetryTemplates.js +136 -0
- package/src/ui/timingTowerTemplate.js +34 -0
package/docs/index.md
CHANGED
|
@@ -9,8 +9,18 @@ Use these docs as the package source of truth:
|
|
|
9
9
|
- [Concepts](concepts.md): vocabulary used by the simulator.
|
|
10
10
|
- [Data Contract](data_contract.md): shape of host-provided drivers, car pairings, ratings, assets, and callbacks.
|
|
11
11
|
- [Bring Your Own Model](training.md): environment contract, policy convention, and visual playback loop.
|
|
12
|
+
- [Model Sense Contract](sense_contract.md): executable proof boundary for policy-facing observation senses.
|
|
13
|
+
- [Custom Model Controller Guide](custom_model_controller.md): how to wrap a trained model as a batched driver controller for browser playback or headless loops.
|
|
12
14
|
- [Architecture](architecture.md): module ownership and data/control flow.
|
|
13
15
|
- [Data Model Notes](data_model.md): lower-level simulator data model notes kept with package docs.
|
|
14
16
|
- [Learnings](learnings.md): implementation lessons and layout verification rules learned from simulator integration issues.
|
|
15
17
|
|
|
18
|
+
Common paths:
|
|
19
|
+
|
|
20
|
+
- Installing PaddockJS into a browser host: read [System Specs](system_specs.md), then [Data Contract](data_contract.md), then [INSTALL_AND_UPDATE.md](../INSTALL_AND_UPDATE.md).
|
|
21
|
+
- Building a package-owned composable layout: read the public API and returned-controller sections in [System Specs](system_specs.md), then the sizing and UI options in [Data Contract](data_contract.md).
|
|
22
|
+
- Enabling pits, penalties, tire requirements, safety car, or stalled off-track DNF: read [Rules](rules.md) first. Pit stops require `rules.modules.pitStops.enabled`; `tireStrategy` alone only controls compounds, tire-requirement stewarding, and pit target choices.
|
|
23
|
+
- Connecting a trained model: read [Bring Your Own Model](training.md), then [Custom Model Controller Guide](custom_model_controller.md). PaddockJS owns observations, actions, specs, scenarios, and browser playback; the host owns the model, reward, storage, and training framework.
|
|
24
|
+
- Changing internals: read [Architecture](architecture.md) before editing source so new code lands in the feature-owned module instead of a facade or compatibility barrel.
|
|
25
|
+
|
|
16
26
|
When simulator behavior changes, update the relevant doc in this folder in the same change.
|
package/docs/learnings.md
CHANGED
|
@@ -45,3 +45,25 @@ For visual layout changes, verify more than the happy path screenshot:
|
|
|
45
45
|
- Browser smoke against an installed/bundled host, not only string-based unit tests.
|
|
46
46
|
|
|
47
47
|
Unit tests should cover the contract, but browser geometry checks catch CSS interactions that tests can miss.
|
|
48
|
+
|
|
49
|
+
## Indexed Track Queries Must Reach Every Runtime Path
|
|
50
|
+
|
|
51
|
+
The track query index is internal performance infrastructure, not a separate sensor contract. When a runtime opts into it, every simulation instance used by that runtime must receive the same option:
|
|
52
|
+
|
|
53
|
+
- Headless environments created by `createPaddockEnvironment()`.
|
|
54
|
+
- Browser expert mode through `F1SimulatorApp.createRaceSimulation()`.
|
|
55
|
+
- Policy Runner controller-debug configurations.
|
|
56
|
+
- Local preview remount/restart paths.
|
|
57
|
+
- Any benchmark or smoke path used to validate training behavior.
|
|
58
|
+
|
|
59
|
+
Do not assume that setting `trackQueryIndex: true` on a high-level preview or environment config is enough. Trace the option all the way into `createRaceSimulation()` and verify that the live simulation owns a non-enumerable `track.queryIndex`. The index must stay out of public JSON contracts: it may exist on the in-memory track object, but `Object.keys(snapshot.track)` must not expose `queryIndex`.
|
|
60
|
+
|
|
61
|
+
The failure mode to avoid: headless training uses indexed queries and looks fast, while the browser visual/expert simulation silently drops the option and falls back to legacy `nearestSampleInRange()` scans near barriers, recovery starts, or far-off-track positions. This can make the Policy Runner lag even when the model, heuristic controller, and ray contract are correct.
|
|
62
|
+
|
|
63
|
+
Verification for index-related changes should include both layers:
|
|
64
|
+
|
|
65
|
+
- A focused unit test proving the app or environment path forwards `trackQueryIndex` into the created simulation.
|
|
66
|
+
- A browser reproduction or smoke check against the Policy Runner or relevant visual runtime, especially near barrier/recovery geometry where legacy nearest-sample scans are most expensive.
|
|
67
|
+
- A profile or timing check when the bug is performance-related. If `nearestSampleInRange()` is still hot in an indexed browser path, the option did not reach the live simulation or another code path is bypassing the index.
|
|
68
|
+
|
|
69
|
+
Do not fix browser performance by changing model-facing sensor precision, hiding observations, or showing debug-only values. The active observation contract remains the source of truth: policies receive it, Policy Runner visualizes it, and the index only changes how the same values are computed.
|
package/docs/rules.md
CHANGED
|
@@ -4,7 +4,7 @@ This file documents the rules currently implemented by the simulator. If the rac
|
|
|
4
4
|
|
|
5
5
|
## Default Race Rules
|
|
6
6
|
|
|
7
|
-
Default rules are defined in `src/simulation/
|
|
7
|
+
Default rules are defined in `src/simulation/rules/ruleDefaults.js` and re-exported through `src/simulation/rulesConfig.js` as `DEFAULT_RULES`:
|
|
8
8
|
|
|
9
9
|
- DRS detection gap: `1` second.
|
|
10
10
|
- Safety car speed: `166 km/h`.
|
|
@@ -25,6 +25,28 @@ Race rules are normalized before the simulation starts. Hosts can choose a packa
|
|
|
25
25
|
|
|
26
26
|
The preset only chooses defaults. Explicit `rules.modules` values override the preset.
|
|
27
27
|
|
|
28
|
+
Default module state:
|
|
29
|
+
|
|
30
|
+
| Module | Package default | Important default options |
|
|
31
|
+
| --- | --- | --- |
|
|
32
|
+
| `pitStops` | disabled | `pitLaneSpeedLimitKph: 80`, `defaultStopSeconds: 2.8`, `maxConcurrentPitLaneCars: 3`, `minimumPitLaneGapMeters: 20`, `doubleStacking: false`, tire pit thresholds `50%` request / `30%` commit |
|
|
33
|
+
| `tireStrategy` | disabled | `compounds: ['S', 'M', 'H']`, `mandatoryDistinctDryCompounds: null` |
|
|
34
|
+
| `tireDegradation` | enabled | tire energy updates from throttle, braking, and lateral load unless disabled |
|
|
35
|
+
| `stalledDnf` | disabled | `maxStoppedSeconds: 12`, `speedThresholdKph: 5` |
|
|
36
|
+
| `penalties` | disabled | `stewardStrictness: 1`; track-limit, collision, tire-requirement, and pit-lane-speeding subsections default to `strictness: 0` |
|
|
37
|
+
| `weather` | disabled | reserved; no current grip or visibility effect |
|
|
38
|
+
| `reliability` | disabled | reserved; no current failure-risk effect |
|
|
39
|
+
| `fuelLoad` | disabled | reserved; no current mass or pace effect |
|
|
40
|
+
|
|
41
|
+
Ruleset preset deltas:
|
|
42
|
+
|
|
43
|
+
| Ruleset | Module changes from package defaults |
|
|
44
|
+
| --- | --- |
|
|
45
|
+
| `paddock` | no module changes; uses the package defaults above |
|
|
46
|
+
| `custom` | no module changes before explicit host overrides |
|
|
47
|
+
| `grandPrix2025` | enables `pitStops`, enables `tireStrategy` with `mandatoryDistinctDryCompounds: 2`, enables `penalties` with `stewardStrictness: 0.85`, track-limit strictness `0.85`, collision strictness `0.65`, tire-requirement strictness `1`, and pit-lane-speeding strictness `1` |
|
|
48
|
+
| `fia2025` | alias for `grandPrix2025` |
|
|
49
|
+
|
|
28
50
|
## Rule Modules
|
|
29
51
|
|
|
30
52
|
Advanced race behavior is organized under `rules.modules` so hosts can enable, disable, or tune each system independently:
|
|
@@ -48,6 +70,14 @@ rules: {
|
|
|
48
70
|
compounds: ['S', 'M', 'H'],
|
|
49
71
|
mandatoryDistinctDryCompounds: 2,
|
|
50
72
|
},
|
|
73
|
+
tireDegradation: {
|
|
74
|
+
enabled: true,
|
|
75
|
+
},
|
|
76
|
+
stalledDnf: {
|
|
77
|
+
enabled: true,
|
|
78
|
+
maxStoppedSeconds: 12,
|
|
79
|
+
speedThresholdKph: 5,
|
|
80
|
+
},
|
|
51
81
|
penalties: {
|
|
52
82
|
enabled: true,
|
|
53
83
|
stewardStrictness: 0.85,
|
|
@@ -58,12 +88,22 @@ rules: {
|
|
|
58
88
|
},
|
|
59
89
|
weather: { enabled: false },
|
|
60
90
|
reliability: { enabled: false },
|
|
61
|
-
fuelLoad: { enabled:
|
|
91
|
+
fuelLoad: { enabled: false },
|
|
62
92
|
},
|
|
63
93
|
}
|
|
64
94
|
```
|
|
65
95
|
|
|
66
|
-
The current implementation normalizes and exposes all module config, records a penalty ledger, enforces collision penalties, track-limit penalties, tire-requirement penalties,
|
|
96
|
+
The current implementation normalizes and exposes all module config, records a penalty ledger, enforces collision penalties, track-limit penalties, tire-requirement penalties, pit-lane speeding penalties, and opt-in stalled off-track DNFs, creates/renders pit-lane geometry when the resolved track generation options enable it, treats pit-lane asphalt, working-lane service areas, and garage boxes as legal drivable surfaces, applies nonlinear tire-energy degradation when `tireDegradation.enabled` is not `false`, and runs automated pit stops when `pitStops.enabled` is true. Weather effects, reliability failures, and fuel-load performance effects are reserved future modules only; the simulation does not change grip, power, retirement risk, mass, or pace from those module keys.
|
|
97
|
+
|
|
98
|
+
`tireStrategy` does not enable automatic pit stops. Enable `rules.modules.pitStops.enabled` separately, or use `ruleset: 'fia2025'` / `ruleset: 'grandPrix2025'`, when cars should use the automatic pit-entry, queue, service, and exit route. `tireStrategy.enabled` controls compounds, tire-requirement stewarding, and pit-stop tire choices.
|
|
99
|
+
|
|
100
|
+
`tireDegradation.enabled: false` freezes each car's current `tireEnergy` instead of updating wear from throttle, braking, and lateral load. This is separate from `tireStrategy.enabled`: tire strategy controls compounds, tire-requirement stewarding, and pit-stop tire choices, while tire degradation controls the physics wear curve.
|
|
101
|
+
|
|
102
|
+
`stalledDnf` defaults to `enabled: false`. When a host sets `rules.modules.stalledDnf.enabled: true`, a car that is off legal racing or pit surfaces and remains below `speedThresholdKph` for `maxStoppedSeconds` is marked out of race with `dnfReason: 'stalled-off-track'`, emits a `car-dnf` event, freezes controls/motion, and leaves active collision, sensor, pit-blocking, and race-order participation. The freeze clears simulator velocity, acceleration, slip, grip, and manual controls together, so a retired car cannot keep a stale motion vector in snapshots or model observations. The timer does not run during pre-start, red flag, after race completion, for already-finished cars, or while pit entry/queue/service/exit owns the car. Returning to legal surface or moving above the threshold resets the timer.
|
|
103
|
+
|
|
104
|
+
Participant interaction profiles can opt real cars out of specific interaction systems without turning them into replay ghosts. A non-colliding profile skips vehicle collision resolution and collision stewarding for that car pair, but the car still uses normal steering/throttle/brake physics. A non-blocking pit profile is ignored by pit service occupancy and queue-blocking checks. A car with `affectsRaceOrder: false` remains in `snapshot.cars` but is excluded from ranking, DRS references, finish order, and final classification. Replay ghosts are separate trajectory overlays in `snapshot.replayGhosts`; they never participate in rules, collisions, timing, pit stops, or penalties.
|
|
105
|
+
|
|
106
|
+
Automatic pit routing owns car motion while a car is entering, queued, servicing, or exiting. During those phases the route/service logic keeps scalar speed, throttle/brake, `appliedControls`, and simulator telemetry synchronized so simulator-mode observations and the next physics-owned step do not inherit stale pre-pit motion, grip, slip, or instability state. `velocityX/Y` is synchronized in simulator mode and cleared from arcade snapshots because arcade physics does not own a world-velocity state.
|
|
67
107
|
|
|
68
108
|
## Steward Strictness
|
|
69
109
|
|
|
@@ -86,10 +126,12 @@ Track-limit enforcement uses the white line as the legal edge. The steward check
|
|
|
86
126
|
|
|
87
127
|
The built-in driver AI is expected to respect that same white-line rule through normal control inputs. Its racing-line planner keeps a centerline comfort margin for the car footprint, and the controller progressively lifts, applies mild braking when needed, and steers back inward when the car approaches the legal edge. This does not let the car defy physics; it only changes when the default AI chooses to brake, coast, and steer. Kerbs still allow normal recovery speed rather than gravel-style stopping behavior.
|
|
88
128
|
|
|
89
|
-
Pit-lane surfaces are legal road for track-limit purposes. `pit-entry`, `pit-lane`, `pit-exit`, and `pit-box` track states set `inPitLane: true`, so ray sensors, runoff response, and the track-limit steward do not treat normal pit entry, service, or exit as off-track excursions.
|
|
129
|
+
Pit-lane surfaces are legal road for track-limit purposes. `pit-entry`, `pit-lane`, `pit-exit`, and `pit-box` track states set `inPitLane: true`, so ray sensors, runoff response, and the track-limit steward do not treat normal pit entry, service, or exit as off-track excursions. Environment-controlled cars only receive this pit-lane override when pit routing is active or pit intent is committed; otherwise they stay on main-track classification even near pit connectors. Hard barrier destruction remains based on main-track geometry and does not depend on pit classification.
|
|
90
130
|
|
|
91
131
|
Penalty decisions are recorded in `snapshot.penalties` and emitted as `penalty` events in the same step. Each entry includes the penalty type, driver id, strictness, status, penalty seconds, pending service conversion seconds, lap, timestamp, and rule-specific context. Multiple time penalties for the same driver are additive: two separate +5s entries produce `penaltySeconds: 10` on that car's snapshot and classification adjustment.
|
|
92
132
|
|
|
133
|
+
Collision response and collision-steward impact speed use simulator `velocityX/Y` when available. In simulator mode this keeps slip, sideways recovery, pit-adjacent motion, and post-contact damping aligned with actual physical motion instead of assuming every car moves exactly in its heading direction. If a collision pushes against a pit-route-owned car, the pit-owned car stays fixed and the movable car's scalar speed and velocity vector are damped together so the next physics step and model-facing speed senses remain consistent.
|
|
134
|
+
|
|
93
135
|
Each penalty subsection can define `consequences`. Supported consequences are:
|
|
94
136
|
|
|
95
137
|
- `{ type: 'warning' }`
|
|
@@ -148,15 +190,23 @@ Seconds gaps are the difference between when two cars crossed the same timing li
|
|
|
148
190
|
|
|
149
191
|
The race engine uses simulator units internally. `src/simulation/units.js` converts simulator distance and speed to public meter and km/h values. Public timer, lap-time, sector-time, gap-time, penalty-time, and service-countdown values are seconds. Public distance values with a `Meters` suffix are meters. The current speed calibration maps the simulation maximum speed to an F1-like `330 km/h`; rendered car sprite dimensions are a visual scale and are not used as the physical distance scale.
|
|
150
192
|
|
|
193
|
+
## Physics Modes
|
|
194
|
+
|
|
195
|
+
The default `physicsMode` is `'arcade'`, which preserves the existing forgiving vehicle behavior for current browser hosts and demos.
|
|
196
|
+
|
|
197
|
+
`physicsMode: 'simulator'` is opt-in for more believable F1-style limits. It still accepts only normal steering, throttle, brake, and pit-intent inputs, but the vehicle integrator keeps a real 2D world velocity, derives speed from that velocity, and applies a traction budget between longitudinal and lateral demand. Steering changes yaw through a rate-limited response, while body slip is derived from the difference between the car heading and actual velocity direction instead of being an artificial movement offset. External state placement through simulator APIs rejects non-finite numeric values and resynchronizes `velocityX/Y` whenever speed or heading is changed without an explicit velocity vector, so scenario/reset placement cannot leave stale simulator velocity behind. Kerbs remain legal racing surface, but high-load kerb use is less stable and slower than track asphalt. Gravel and grass are averaged per wheel so one wheel over the edge creates partial grip/drag loss, while all-wheel runoff still costs major time. The rendered barrier wall is the hard outer runoff boundary in both physics modes; cars whose footprint reaches the wall's inner face are marked `destroyed`, stopped, removed from active collision and sensor participation, and placed in DNF timing order. Barrier destruction, stalled DNF, pre-start grid hold, red-flag hold, and pit-queue hold freeze scalar speed and simulator velocity together; clearing a red flag resynchronizes active cars to the release speed and heading before the next observation while DNF/out-of-race cars remain frozen. `physicsMode` changes vehicle integration and grip behavior, not barrier consequences. Simulator mode does not teleport cars, magnetize them to the track, or bypass physics with hidden pose correction.
|
|
198
|
+
|
|
199
|
+
Simulator snapshots and environment observations expose additional vehicle telemetry: `lateralG`, `longitudinalG`, `gripUsage`, `slipAngleRadians`, `tractionLimited`, and `stabilityState`. These fields are optional public telemetry; existing `speedKph`, wheel-surface, steering, throttle, and brake fields remain unchanged.
|
|
200
|
+
|
|
151
201
|
## Laps
|
|
152
202
|
|
|
153
203
|
Lap is computed from each car's cumulative race distance over the track length. Total laps are provided by mount options and default to `10`.
|
|
154
204
|
|
|
155
205
|
Each track is automatically divided into three equal sectors. Sector and lap telemetry is recorded when a car's cumulative race distance crosses a sector boundary or start/finish boundary. Completed current-lap sector split times before the active sector are exposed as `currentSectors`, while `liveSectors` keeps only the active sector's elapsed time updated before the boundary is crossed and clears any future-sector values. `sectorProgress` is recomputed every snapshot as the live S1/S2/S3 fill state for the current lap, so sector-map UI does not derive progress from completed split state or keep stale future sectors lit. Timing values are stored in seconds and exposed on each car snapshot as `lapTelemetry`.
|
|
156
206
|
|
|
157
|
-
Each car is marked `finished` when it reaches `track.length * totalLaps`. It receives a frozen provisional `finishRank`, exposes `raceStatus: 'waved-flag'` / `wavedFlag: true`, and emits a `car-finish` event. The first finisher becomes provisional `winner`, but the race keeps running until every
|
|
207
|
+
Each car is marked `finished` when it reaches `track.length * totalLaps`. It receives a frozen provisional `finishRank`, exposes `raceStatus: 'waved-flag'` / `wavedFlag: true`, and emits a `car-finish` event. The first finisher becomes provisional `winner`, but the race keeps running until every race participant has either crossed the finish distance or is currently DNF. While the field is still finishing, timing order keeps already-finished cars in provisional finish order ahead of cars still running, and DNF cars sit below active cars in the order they retired. A car that has already crossed the finish line keeps that result even if it later touches the barrier or satisfies stalled-off-track detection while the rest of the field is still finishing; post-finish retirement checks do not turn it into DNF. A DNF car restored before final classification re-enters the live order and must finish before the race can complete; restoring it after final classification does not reopen the race.
|
|
158
208
|
|
|
159
|
-
When all cars have finished, the simulator records `finishedAt` and final `classification`, emits a `race-finish` event, freezes order to the classified result after outstanding penalties and classification consequences, deploys the safety car, and switches race mode to `safety-car`. Finished cars keep circulating under safety-car behavior instead of hard-stopping. The current implementation does not yet implement championship scoring.
|
|
209
|
+
When all cars have finished or reached DNF, the simulator records `finishedAt` and final `classification`, emits a `race-finish` event, freezes order to the classified result after outstanding penalties and classification consequences, deploys the safety car, and switches race mode to `safety-car`. DNF classification entries appear after finishers with `finished: false`, no finish time, and DNF reason/time/order metadata. Finished cars keep circulating under safety-car behavior instead of hard-stopping. The current implementation does not yet implement championship scoring.
|
|
160
210
|
|
|
161
211
|
## DRS
|
|
162
212
|
|
|
@@ -166,12 +216,13 @@ DRS behavior:
|
|
|
166
216
|
- Each track has DRS zones.
|
|
167
217
|
- A car latches into a DRS zone when it crosses that zone start.
|
|
168
218
|
- A car becomes DRS eligible if it was close enough to the physically-ahead car at the relevant detection crossing, including lapped traffic.
|
|
219
|
+
- Finished, DNF/out-of-race, non-race-order, and active pit-stop cars are ignored when selecting the physically-ahead DRS reference.
|
|
169
220
|
- The current detection window is controlled by `drsDetectionSeconds`.
|
|
170
221
|
- When eligible inside the latched zone, `drsActive` becomes true.
|
|
171
222
|
|
|
172
223
|
Physics effect:
|
|
173
224
|
|
|
174
|
-
- Active DRS reduces drag through `src/simulation/vehiclePhysics.js
|
|
225
|
+
- Active DRS reduces drag through `src/simulation/vehicle/vehiclePhysics.js`; the root `src/simulation/vehiclePhysics.js` path is only a compatibility re-export.
|
|
175
226
|
- The current drag multiplier is `0.42`.
|
|
176
227
|
|
|
177
228
|
Visual effect:
|
|
@@ -199,7 +250,7 @@ When safety car is cleared:
|
|
|
199
250
|
|
|
200
251
|
## Driver AI
|
|
201
252
|
|
|
202
|
-
Driver control decisions
|
|
253
|
+
Driver control decisions are exported from `src/simulation/driverController.js`; canonical driver policy modules live under `src/simulation/driver/`.
|
|
203
254
|
|
|
204
255
|
The AI has separate behavior for:
|
|
205
256
|
|
|
@@ -221,17 +272,21 @@ Green-flag behavior uses:
|
|
|
221
272
|
- Nearby traffic.
|
|
222
273
|
- Preferred and available lane offsets.
|
|
223
274
|
|
|
224
|
-
The built-in racing controller still drives through normal vehicle inputs only. It chooses a forward racing target, blends steering from the target angle, upcoming track heading, lateral offset, edge recovery pressure, and a corner-apex racing-line offset, then sends clamped steering/throttle/brake values into the vehicle physics integrator. It is expected to use the available track width and kerbs on generated circuits, including sharp generated turns. When heading alignment
|
|
275
|
+
The built-in racing controller still drives through normal vehicle inputs only. It chooses a forward racing target, blends steering from the target angle, upcoming track heading, lateral offset, edge recovery pressure, outward edge motion, and a corner-apex racing-line offset, then sends clamped steering/throttle/brake values into the vehicle physics integrator. It is expected to use the available track width and kerbs on generated circuits, including sharp generated turns. When heading alignment, steering load, or outward edge motion shows the car cannot yet carry throttle through a corner, throttle is cut before braking is requested so the controller does not fight itself. It does not snap car position, override heading, or bypass steering-rate/yaw-rate limits.
|
|
276
|
+
|
|
277
|
+
In simulator mode, the built-in controller uses separate tuning: earlier lookahead for braking, smaller high-speed steering requests, stronger edge recovery before the legal limit, throttle reduction when grip and slip telemetry show the car is overloaded, a higher legal-road speed floor so the baseline AI does not crawl through generated bends, and lower rejoin targets from kerb, grass, or gravel states. Extra stability braking is applied only when upcoming corner load, edge pressure, outward drift, high straight speed, or near-target speed makes it useful; ordinary below-target straight-line correction should not trigger brake pulses. This is intentionally a baseline driver, not a trained policy.
|
|
225
278
|
|
|
226
279
|
Traffic decisions use real meter-scaled gaps and lateral spacing, not raw simulator-size constants. A trailing car inside the attack window commits toward a visible passing lane instead of sitting on the centerline. A leading car with a close rear threat can defend the threatened side before the rival is fully alongside. Side-by-side overlap still creates spacing pressure so defensive and attacking moves are expressed as target-line choices and normal steering/brake/throttle inputs, not as collision avoidance teleports or artificial position overrides.
|
|
227
280
|
|
|
228
|
-
Rejoin behavior also remains physics-driven. When a car leaves the legal racing surface, the controller enters a short recovery hold and keeps using rejoin controls after the center point first reaches track or kerb until heading and edge margin are stable. That prevents the car from immediately returning to full racing throttle while still pointed across the track. Recovery targets look forward along the racing surface, bias inward from the edge, and request bounded surface-specific speeds for track, kerb, grass, gravel, and
|
|
281
|
+
Rejoin behavior also remains physics-driven. When a car leaves the legal racing surface, the controller enters a short recovery hold and keeps using rejoin controls after the center point first reaches track or kerb until heading and edge margin are stable. That prevents the car from immediately returning to full racing throttle while still pointed across the track. Recovery targets look forward along the racing surface, bias inward from the edge, and request bounded surface-specific speeds for track, kerb, grass, and gravel states. In simulator mode, rejoin controls also watch signed outward velocity relative to the track normal: a car sliding farther into runoff cuts throttle or brakes before trying to accelerate out, while very low-speed gravel/grass recovery limits steering lock and caps throttle when the heading is still outward so steering scrub does not pin the car in place. Barrier contact is not a recovery state; it destroys the car.
|
|
282
|
+
|
|
283
|
+
Simulator-mode steering scrub is dissipative in both forward and reverse motion. It opposes the signed forward velocity instead of always applying negative forward acceleration, so a car sliding backward with zero throttle cannot gain speed from steering scrub.
|
|
229
284
|
|
|
230
285
|
Tire energy can degrade to 1%. The vehicle physics layer converts tire energy into a nonlinear grip factor, so degradation has a visible performance cost across the full 100% to 1% range while still leaving a damaged car controllable enough to return to the pits.
|
|
231
286
|
|
|
232
287
|
## Vehicle Physics
|
|
233
288
|
|
|
234
|
-
Vehicle physics live in `src/simulation/vehiclePhysics.js`.
|
|
289
|
+
Vehicle physics live in `src/simulation/vehicle/vehiclePhysics.js`.
|
|
235
290
|
|
|
236
291
|
The model includes:
|
|
237
292
|
|
|
@@ -264,7 +319,9 @@ Track state can classify a car as on:
|
|
|
264
319
|
|
|
265
320
|
Surface affects grip, drag, and rolling resistance.
|
|
266
321
|
|
|
267
|
-
Surface physics is wheel-based. `src/simulation/wheelSurface.js` classifies each wheel contact patch against the track model and the car uses the worst current surface for physics: `barrier > gravel > grass > kerb > pit-box > pit-lane > pit-entry/pit-exit > track`. Normal main-track running uses an analytic signed-offset fast path from cached wheel geometry, while pit-lane and pit-connector edge cases use full patch sampling. One wheel on gravel slows the car with gravel behavior even if the other three wheels are on asphalt. In addition, `vehiclePhysics.js` compares left-side and right-side wheel resistance and applies a small capped yaw-rate bias toward the slower side, so asymmetric gravel/grass/kerb contact can tug the car toward the dirty side without becoming a full tire-force simulation. One wheel on kerb reports `kerb` and applies kerb-level grip/drag without causing a track-limit violation by itself. Pit entry, pit lane, pit exit, and pit-box surfaces remain legal drivable surfaces.
|
|
322
|
+
Surface physics is wheel-based. `src/simulation/vehicle/wheelSurface.js` classifies each wheel contact patch against the track model and the car uses the worst current surface for physics: `barrier > gravel > grass > kerb > pit-box > pit-lane > pit-entry/pit-exit > track`. Normal main-track running uses an analytic signed-offset fast path from cached wheel geometry, while pit-lane and pit-connector edge cases use full patch sampling. One wheel on gravel slows the car with gravel behavior even if the other three wheels are on asphalt. In addition, `vehiclePhysics.js` compares left-side and right-side wheel resistance and applies a small capped yaw-rate bias toward the slower side, so asymmetric gravel/grass/kerb contact can tug the car toward the dirty side without becoming a full tire-force simulation. One wheel on kerb reports `kerb` and applies kerb-level grip/drag without causing a track-limit violation by itself. If the car footprint reaches the rendered barrier wall's inner face, every physics mode marks the car destroyed instead of treating the wall as recoverable low-grip road. Pit entry, pit lane, pit exit, and pit-box surfaces remain legal drivable surfaces and do not count toward stalled off-track DNF timing.
|
|
323
|
+
|
|
324
|
+
Rendered material bands use those same thresholds. The visible gravel band starts at the outer kerb edge and ends at the simulated gravel edge; the visible runoff band starts at the gravel edge and ends at the barrier centerline; the barrier wall is drawn from the same `track.barrierWidth` used by destruction. Rendering, ray surface hits, wheel-surface classification, and barrier destruction must stay on this shared geometry contract.
|
|
268
325
|
|
|
269
326
|
When pit stops are enabled, each team is assigned one shared service area in the working lane plus two garage boxes. Driver pairs share the service area, and the service area, queue slot, and garage boxes inherit the team color from `driver.team.color` when present, otherwise the lead driver's color. The current automatic stop plan distributes pit calls across available race laps as bounded pit trains, then lets opportunistic cars join the entry only when fewer than `pitStops.maxConcurrentPitLaneCars` are active and the nearest active pit-lane car is at least `pitStops.minimumPitLaneGapMeters` ahead; committed cars enter at the next pit-entry window and can queue in the working lane if their team service area is busy. Built-in AI cars also request stops from tire condition: below `pitStops.tirePitRequestThresholdPercent` they request `pitIntent: 1`, and below `pitStops.tirePitCommitThresholdPercent` they request `pitIntent: 2`. Expert-controlled cars do not receive those tire-threshold automatic calls; their model or host must request the stop with `pitIntent`. Hosts and expert actions can change a pending stop with `pitIntent`: `0` clears the pending call, `1` stays active until a free-enough pit-entry window appears, and `2` commits to entering at the next pit-entry window even if capacity or gap checks would block mode `1`. The same request may include a target compound, either through `setPitIntent(driverId, intent, targetCompound)` or expert action `pitCompound`; invalid compounds are rejected. Pit intent and target compound are locked while the car is entering, queued, servicing, or exiting, and intent resets to `0` after pit exit. Completed stops can be re-armed by later tire condition or host intent, so pit stops are not one-use per race. Safety-car mode does not block pit intent. Closed pit-lane race-control state keeps pending calls on track until `setPitLaneOpen(true)`, while red-flag state freezes cars and closes the effective pit lane until cleared. If the gap is too small for mode `1`, the following car stays on the main track and retries later rather than being forced to stop in the lane. Allowed cars steer through a forward main-track approach into the pit-entry road, slow to the configured limiter speed before the main pit-lane start, follow the main fast lane, pass through the team-colored queue point, hold for any pit-served penalties, hold for the resolved tire-service time, change to the requested compound or default alternate compound, add that compound to `usedTireCompounds`, then steer back to the racing surface through `pit-exit`. While a car is stationary in service, the browser renderer shows a small countdown above it: red `+Ns` for pit-served penalty hold time and yellow `Ns` for normal pit-service time. The queue point is a rolling gate when the active service area is free, so the car continues into service without a full stop. If a team-mate is already servicing or still exiting from the active service area, the arriving car targets the queue point behind that service area, holds a bounded approach speed until the final capture distance, waits without obstructing the main fast lane, then follows a short queue-release route only after the active service area is physically clear; this keeps both the queue stop and the move into service continuous instead of snapping the car between slots or crawling through the last several meters. Cars whose position is controlled by pit entry, queue, service, or exit logic are not laterally displaced by generic collision correction; if another car overlaps one, the movable car is corrected away while the pit-controlled car stays on its authored route or stop point. `pitStops.variability.enabled` optionally adjusts service time from `team.pitCrew.speed`, `team.pitCrew.consistency`, and `team.pitCrew.reliability`; `pitStops.variability.perfect: true` forces `pitStops.defaultStopSeconds` for training. The pit limiter applies only on the straight main pit lane and working lane between the lane start and lane end; the pit-entry connector road and pit-exit connector road are legal pit-lane surfaces but are not speed-limited by `pitStops.pitLaneSpeedLimitKph`, although automatic entry routing caps connector overspeed so worn-tire cars can still reach the limiter and assigned service area.
|
|
270
327
|
|
|
@@ -272,7 +329,7 @@ When pit stops are enabled, each team is assigned one shared service area in the
|
|
|
272
329
|
|
|
273
330
|
Collision handling uses:
|
|
274
331
|
|
|
275
|
-
- Shared vehicle geometry from `src/simulation/vehicleGeometry.js`.
|
|
332
|
+
- Shared vehicle geometry from `src/simulation/vehicle/vehicleGeometry.js`.
|
|
276
333
|
- A body collision hull for car-vs-car contact.
|
|
277
334
|
- Four wheel/contact-patch shapes for surface and track-limit state, not for car-vs-car contact.
|
|
278
335
|
- Track-progress candidate pruning before narrow-phase checks.
|
|
@@ -295,7 +352,7 @@ These are not currently implemented:
|
|
|
295
352
|
|
|
296
353
|
- Strategic pit-call timing beyond the current first automatic stop.
|
|
297
354
|
- Double stacking and pit-crew conflicts.
|
|
298
|
-
-
|
|
355
|
+
- Full race-strategy planning beyond the current automatic pit schedule and host/model pit intents.
|
|
299
356
|
- Fuel load strategy.
|
|
300
357
|
- Weather.
|
|
301
358
|
- Mechanical failures.
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# Model Sense Contract
|
|
2
|
+
|
|
3
|
+
This document defines the proof boundary for model-facing PaddockJS senses. The
|
|
4
|
+
active environment observation contract is the source of truth for policies,
|
|
5
|
+
Policy Runner inputs, expert visualization, and rollout recording.
|
|
6
|
+
|
|
7
|
+
## What Is Proven In Code
|
|
8
|
+
|
|
9
|
+
`src/__tests__/environmentSenseContract.test.js` is the executable contract for
|
|
10
|
+
core model-facing senses. It checks three layers:
|
|
11
|
+
|
|
12
|
+
1. Object observations are compared against independent formulas from the
|
|
13
|
+
returned simulator snapshot. This covers body telemetry, local track
|
|
14
|
+
relation, race state, lookahead samples, wheel contact patches, nearby-car
|
|
15
|
+
geometry, and opponent radar fields.
|
|
16
|
+
2. Vector observations are decoded by schema name and compared against the
|
|
17
|
+
object observation oracle. A vector entry is not accepted unless a matching
|
|
18
|
+
schema oracle exists.
|
|
19
|
+
3. Compact vector-only output is compared against full output for the same
|
|
20
|
+
deterministic state, and public per-driver observation specs are compared
|
|
21
|
+
against the schemas produced in observations.
|
|
22
|
+
|
|
23
|
+
This is intentionally stronger than testing current implementation against
|
|
24
|
+
itself: the object oracle uses simulator snapshot facts and unit conversions,
|
|
25
|
+
while the vector oracle uses schema names and object fields rather than calling
|
|
26
|
+
`buildObservationVector()`.
|
|
27
|
+
|
|
28
|
+
## Model-Facing Sense Rules
|
|
29
|
+
|
|
30
|
+
- Public distance fields with a `Meters` suffix are meters, not simulator
|
|
31
|
+
units.
|
|
32
|
+
- Public angle fields with a `Radians` suffix are radians.
|
|
33
|
+
- Speed is exposed both as `speedKph` and `speedMetersPerSecond`; the latter is
|
|
34
|
+
derived from the simulator speed unit conversion.
|
|
35
|
+
- `self.onTrack` and `trackRelation.onLegalSurface` follow wheel-level legal
|
|
36
|
+
surface rules when wheel contact patches exist.
|
|
37
|
+
- `contactPatches` always uses the stable order `front-left`, `front-right`,
|
|
38
|
+
`rear-left`, `rear-right`.
|
|
39
|
+
- `nearbyCars` are sorted by car-relative distance, with deterministic ordering
|
|
40
|
+
for equal distances.
|
|
41
|
+
- Opponent radar fields use actual simulator velocity vectors when present.
|
|
42
|
+
- Ray object values, vector values, schemas, and visualizations must describe
|
|
43
|
+
the same active observation values. Debug-only precision may exist only when
|
|
44
|
+
clearly labeled and must not be presented as model input.
|
|
45
|
+
- `getObservationSpec()` is the canonical schema for compact loops, including
|
|
46
|
+
per-driver sensor overrides.
|
|
47
|
+
|
|
48
|
+
## Remaining Formal Limits
|
|
49
|
+
|
|
50
|
+
The test suite proves conformance to the executable contract above for the
|
|
51
|
+
deterministic scenarios it enumerates. It is not a mathematical proof over every
|
|
52
|
+
possible JavaScript object a caller could construct or every physically possible
|
|
53
|
+
track state. Extending the proof boundary requires adding more oracle cases for
|
|
54
|
+
the specific state family, for example replay ghosts, pit-service movement, or a
|
|
55
|
+
new sensor channel.
|
|
56
|
+
|
|
57
|
+
Any new model-facing sense must add or extend an oracle in
|
|
58
|
+
`environmentSenseContract.test.js`. Adding a vector schema field without an
|
|
59
|
+
oracle must fail the test.
|
package/docs/system_specs.md
CHANGED
|
@@ -28,16 +28,42 @@ Headless expert environment import:
|
|
|
28
28
|
```js
|
|
29
29
|
import {
|
|
30
30
|
createPaddockEnvironment,
|
|
31
|
+
createPaddockDriverControllerLoop,
|
|
31
32
|
createRolloutRecorder,
|
|
32
33
|
runEnvironmentEvaluation,
|
|
33
34
|
} from '@inventure71/paddockjs/environment';
|
|
34
35
|
```
|
|
35
36
|
|
|
36
37
|
The environment subpath is the only public headless training import. It must stay free of DOM, PixiJS, CSS, and browser app dependencies.
|
|
37
|
-
|
|
38
|
-
|
|
38
|
+
|
|
39
|
+
Root package exports:
|
|
40
|
+
|
|
41
|
+
| Export group | Public exports | Use |
|
|
42
|
+
| --- | --- | --- |
|
|
43
|
+
| Browser mounts | `mountF1Simulator`, `createPaddockSimulator` | all-in-one shell or composable package-owned UI surfaces |
|
|
44
|
+
| Composable helper mounts | `mountRaceControls`, `mountCameraControls`, `mountSafetyCarControl`, `mountTimingTower`, `mountRaceCanvas`, `mountTelemetryPanel`, `mountTelemetryCore`, `mountTelemetrySectors`, `mountTelemetrySectorBanner`, `mountTelemetryLapTimes`, `mountTelemetrySectorTimes`, `mountRaceTelemetryDrawer`, `mountCarDriverOverview`, `mountRaceDataPanel` | function-call wrappers around a composable simulator controller |
|
|
45
|
+
| Data helpers | `DriverData`, `VehicleData`, `CHAMPIONSHIP_ENTRY_BLUEPRINTS`, `DEMO_PROJECT_DRIVERS`, `buildChampionshipDriverGrid`, `formatDriverNumber`, `normalizeSimulatorDrivers` | demo data, host entry normalization, and rating helper construction |
|
|
46
|
+
| Package constants | `DEFAULT_F1_SIMULATOR_ASSETS`, `PADDOCK_SIMULATOR_PRESETS` | inspect bundled asset mapping and UI preset defaults |
|
|
47
|
+
| Track and units | `createProceduralTrack`, `REAL_F1_CAR_LENGTH_METERS`, `VISUAL_CAR_LENGTH_METERS`, `SIM_UNITS_PER_METER`, `TARGET_F1_TOP_SPEED_KPH`, `metersToSimUnits`, `simUnitsToMeters`, `kphToSimSpeed`, `simSpeedToKph`, `simSpeedToMetersPerSecond` | generated track definitions and physical/display unit conversion |
|
|
48
|
+
| Controller loop | `createPaddockDriverControllerLoop` | shared browser/headless batched model-controller orchestration |
|
|
49
|
+
|
|
50
|
+
Environment subpath exports:
|
|
51
|
+
|
|
52
|
+
| Export | Use |
|
|
53
|
+
| --- | --- |
|
|
54
|
+
| `createPaddockEnvironment` | browser-free step/reset runtime for JavaScript training and evaluation loops |
|
|
55
|
+
| `createPaddockDriverControllerLoop` | shared controller-loop helper for browser expert mode or headless environments |
|
|
56
|
+
| `createProgressReward` | optional demo reward used by examples; not the package objective |
|
|
57
|
+
| `createRolloutRecorder`, `createRolloutTransition` | neutral rollout transition recording helpers |
|
|
58
|
+
| `DEFAULT_EVALUATION_CASES`, `createEvaluationTracker`, `runEnvironmentEvaluation` | deterministic evaluation cases and metric aggregation |
|
|
59
|
+
| `ENVIRONMENT_SCENARIO_PRESETS` | reset-only scenario placement presets |
|
|
60
|
+
| `createEnvironmentWorkerProtocol`, `handleEnvironmentMessage` | JSON-serializable worker bridge helpers |
|
|
61
|
+
|
|
62
|
+
`createProgressReward()` is published from the same subpath only as non-canonical demo reward code for examples and smoke tests. It must remain optional and replaceable; environment stepping must continue to work with a custom `reward(context)` callback or no reward callback. Reward callbacks are user-owned formulas over package-owned facts, including neutral per-driver `metrics` and `info.drivers[driverId]` episode state. They run only for `step(actions)` transition results; reset/read paths are reward-neutral. Non-finite or missing callback results are normalized to a neutral `0` reward for that controlled driver.
|
|
63
|
+
Ray observations expose track-transition distance and car distance per ray. Track transitions use `kind: 'exit'` when the ray starts on track and reaches the border, `kind: 'entry'` when the ray starts off track and reaches the road again, and `kind: null` with max distance when no transition is visible. Track-position, surface, pit-lane, and ray fallback queries can use an internal non-enumerable track query index built with the track model. Browser/expert mounts, headless environments, and direct race-simulation construction now default to the indexed path (opt-out with `trackQueryIndex: false`); compact training-style environment runs (including `batch-training` rays with full state output) still auto-enable it. This changes runtime cost, not public observation shapes.
|
|
39
64
|
The package must not own model training, model persistence, model registries, or trained policy behavior. The supported contract is: external code reads observations, returns normalized actions, and advances either the headless environment or browser expert mode.
|
|
40
65
|
The shared expert runtime exposes `getActionSpec()` and `getObservationSpec()` so external code can inspect controlled drivers, action ranges, sensor layout, nearby-car limits, track lookahead fields, and the versioned vector schema before connecting a model. Environment reset may apply deterministic scenario placement presets or explicit placement/traffic layouts; model steps may not mutate position and still use normalized actions only. Neutral rollout recording, deterministic evaluation metrics, and the JSON worker protocol are environment utilities, not training algorithms.
|
|
66
|
+
`createPaddockDriverControllerLoop({ runtime, controller, actionRepeat })` is the shared public controller orchestrator for browser playback and JavaScript training-style loops. `runtime` may be browser expert mode or a headless environment, and `controller.decideBatch(context)` is called once per policy step for all controlled drivers in stable spec order. The loop lazily resets when scheduled playback starts from a fresh instance, caches `actionSpec` and `observationSpec`, reuses the active observation payload, supports async controllers, forwards actions through the normal `step(actions)` API, and repeats each decision for `actionRepeat` runtime frames. Scheduled playback stops and records `stats.lastError` when controller initialization, decision, stepping, or `onStep` hooks fail. It does not load checkpoints, run neural networks, parse model formats, compute rewards, or mutate vehicle state.
|
|
41
67
|
|
|
42
68
|
All-in-one mount call:
|
|
43
69
|
|
|
@@ -48,7 +74,14 @@ const simulator = await mountF1Simulator(root, {
|
|
|
48
74
|
onDriverOpen,
|
|
49
75
|
seed,
|
|
50
76
|
trackSeed,
|
|
77
|
+
trackGeneration,
|
|
78
|
+
trackQueryIndex,
|
|
79
|
+
warmup,
|
|
51
80
|
totalLaps,
|
|
81
|
+
physicsMode,
|
|
82
|
+
rules,
|
|
83
|
+
participantInteractions,
|
|
84
|
+
replayGhosts,
|
|
52
85
|
initialCameraMode,
|
|
53
86
|
preset,
|
|
54
87
|
title,
|
|
@@ -58,6 +91,7 @@ const simulator = await mountF1Simulator(root, {
|
|
|
58
91
|
showBackLink,
|
|
59
92
|
ui,
|
|
60
93
|
theme,
|
|
94
|
+
debug,
|
|
61
95
|
assets,
|
|
62
96
|
onLoadingChange,
|
|
63
97
|
onReady,
|
|
@@ -79,8 +113,22 @@ const simulator = createPaddockSimulator({
|
|
|
79
113
|
onDriverOpen,
|
|
80
114
|
seed,
|
|
81
115
|
trackSeed,
|
|
116
|
+
trackGeneration,
|
|
117
|
+
trackQueryIndex,
|
|
118
|
+
warmup,
|
|
82
119
|
totalLaps,
|
|
120
|
+
physicsMode,
|
|
83
121
|
initialCameraMode,
|
|
122
|
+
participantInteractions,
|
|
123
|
+
replayGhosts,
|
|
124
|
+
rules: {
|
|
125
|
+
ruleset: 'custom',
|
|
126
|
+
modules: {
|
|
127
|
+
pitStops: { enabled: true },
|
|
128
|
+
stalledDnf: { enabled: true },
|
|
129
|
+
tireStrategy: { enabled: true, mandatoryDistinctDryCompounds: 2 },
|
|
130
|
+
},
|
|
131
|
+
},
|
|
84
132
|
});
|
|
85
133
|
|
|
86
134
|
simulator.mountRaceControls(controlsRoot);
|
|
@@ -111,6 +159,8 @@ simulator.setPitLaneOpen(false);
|
|
|
111
159
|
simulator.setRedFlagDeployed(true);
|
|
112
160
|
```
|
|
113
161
|
|
|
162
|
+
Pit APIs are rule-gated. `setPitIntent()` returns `false` until the active rules enable `rules.modules.pitStops.enabled` and the active track has pit-lane geometry. `tireStrategy` does not enable automatic pit routing by itself; it only controls available compounds, tire requirement stewarding, and pit target choices.
|
|
163
|
+
|
|
114
164
|
Standalone helper functions are also exported for host code that prefers function calls:
|
|
115
165
|
|
|
116
166
|
```js
|
|
@@ -153,7 +203,10 @@ Returned controller:
|
|
|
153
203
|
mountTelemetryLapTimes(root),
|
|
154
204
|
mountTelemetrySectorTimes(root),
|
|
155
205
|
mountRaceTelemetryDrawer(root, { timingTowerVerticalFit, drawerInitiallyOpen, raceDataTelemetryDetail }),
|
|
206
|
+
mountCarDriverOverview(root),
|
|
156
207
|
mountRaceDataPanel(root),
|
|
208
|
+
querySelector(selector),
|
|
209
|
+
querySelectorAll(selector),
|
|
157
210
|
start(),
|
|
158
211
|
|
|
159
212
|
// Included on both APIs:
|
|
@@ -166,6 +219,7 @@ Returned controller:
|
|
|
166
219
|
setPitIntent(driverId, intent, targetCompound),
|
|
167
220
|
getPitIntent(driverId),
|
|
168
221
|
getPitTargetCompound(driverId),
|
|
222
|
+
getSimulationSpeed(),
|
|
169
223
|
servePenalty(penaltyId),
|
|
170
224
|
cancelPenalty(penaltyId),
|
|
171
225
|
callSafetyCar(),
|
|
@@ -208,27 +262,35 @@ Returned controller:
|
|
|
208
262
|
- The host passes data, not internal DOM.
|
|
209
263
|
- Host driver IDs and entry `driverId` values must be unique. Entries may omit `driverNumber`; provided numbers must be unique.
|
|
210
264
|
- `totalLaps` is normalized to a finite positive integer before simulation so invalid input cannot produce zero-lap, negative-lap, or non-finite snapshots.
|
|
265
|
+
- `physicsMode` accepts `'arcade'` and `'simulator'`. The default is `'arcade'` to preserve existing hosts. `'simulator'` is opt-in and keeps cars controlled only through steering, throttle, brake, and pit intent while enabling traction-budget limits, steering scrub, velocity-heading slip, surface-specific grip/drag, and simulator telemetry. Snapshots expose `physicsMode` plus per-car `lateralG`, `longitudinalG`, `gripUsage`, `slipAngleRadians`, `tractionLimited`, `stabilityState`, and the latest `appliedControls`.
|
|
211
266
|
- `restart(nextOptions)` can change race data and deterministic seeds such as `trackSeed`, but it does not support changing asset URLs. Asset changes require `destroy()` and a fresh mount because PixiJS texture loading is an initialization boundary.
|
|
212
267
|
- `onDriverOpen(driver)` is the navigation boundary.
|
|
213
|
-
- Lifecycle callbacks are optional: `onLoadingChange`, `onReady`, `onError`, `onDriverSelect`, `onRaceEvent`, `onLapChange`, and `onRaceFinish`.
|
|
214
|
-
- Race completion is part of the simulation snapshot. Cars receive individual `finished`, `finishTime`, `finishRank`, `status: 'waved-flag'`, `raceStatus: 'waved-flag'`, `wavedFlag`, `penaltySeconds`, `adjustedFinishTime`, and `classifiedRank` values as they cross the finish distance. The first finisher sets a provisional `raceControl.winner`; already-finished cars remain frozen in provisional finish order while the remaining cars complete the distance. Final `raceControl.classification` and `raceControl.finished` are set only after every car
|
|
215
|
-
- Race rules support package presets and custom module config. Supported rulesets are `paddock`, `grandPrix2025`, `fia2025`, and `custom`.
|
|
268
|
+
- Lifecycle callbacks are optional: `onLoadingChange`, `onReady`, `onError`, `onDriverSelect`, `onRaceEvent`, `onLapChange`, and `onRaceFinish`. Lifecycle callback failures are routed to `onError` when possible and must not stop the simulator loop. `onDriverOpen(driver)` is host-owned navigation code and is not wrapped as a lifecycle callback.
|
|
269
|
+
- Race completion is part of the simulation snapshot. Cars receive individual `finished`, `finishTime`, `finishRank`, `status: 'waved-flag'`, `raceStatus: 'waved-flag'`, `wavedFlag`, `penaltySeconds`, `adjustedFinishTime`, and `classifiedRank` values as they cross the finish distance. Destroyed/out-of-race cars expose `dnf`, `dnfReason`, `dnfAt`, and `dnfOrder`, appear below active cars in timing, render faded/gray in the race canvas, and do not block race completion while they remain DNF. The first finisher sets a provisional `raceControl.winner`; already-finished cars remain frozen in provisional finish order while the remaining cars complete the distance. Final `raceControl.classification` and `raceControl.finished` are set only after every race participant has finished or is DNF. DNF entries are included after finishers with no finish time. A DNF car restored before final classification re-enters live timing and must finish; after final classification, resurrection does not reopen the race. Final classification converts unserved drive-through and stop-go penalties into configured time, sorts finishers by `finishTime + penaltySeconds`, applies position-drop and disqualification consequences, then race control switches to `safety-car`, the final order freezes to the classified result, and the field keeps circulating under safety-car behavior.
|
|
270
|
+
- Race rules support package presets and custom module config. Supported rulesets are `paddock`, `grandPrix2025`, `fia2025`, and `custom`. Active advanced modules include pit stops, tire strategy, tire degradation, stalled off-track DNF, and penalties. Weather, reliability, and fuel load are reserved module placeholders only; they do not currently change grip, power, retirement risk, mass, or pace. The current simulator normalizes all module config, creates/renders track-owned pit-lane geometry on tracks whose resolved generation options enable it, treats pit-lane asphalt, working-lane service areas, and garage boxes as legal drivable surfaces, runs automatic bounded pit-train entry/service/exit through the main fast lane and shared team service areas when pit stops are enabled, lets host/expert pit calls choose a target tire compound, uses the team queue point as a rolling gate when the service area is free, queues a second team car behind the active service area and moves it forward through a queue-release route only after the active service area is physically clear, keeps pit-route approach speed bounded until the final queue/service capture instead of crawling through open route, optionally varies pit-service time from team pit-crew stats with a perfect-training override, supports pit-lane open/closed state plus red flags, requests pit stops from configurable tire-energy thresholds, applies nonlinear tire-grip degradation down to 1% unless `rules.modules.tireDegradation.enabled` is `false`, can retire cars that remain off legal racing/pit surfaces below the configured stalled-DNF speed threshold for the configured duration when `rules.modules.stalledDnf.enabled` is `true`, applies the pit speed limiter only on the main pit lane/working lane, enforces pit-lane speeding on speed-limited pit-lane parts but not on entry/exit connectors, keeps the safety car about `55m` ahead of the leader with compact `22m` frozen-order queue slots, lets the built-in driver AI ride kerbs, attack, defend, and recover through normal steering/throttle/brake decisions with short controller-state commitments for rejoin and attack decisions, and enforces stewarded penalties for collisions, track limits, pit-lane speeding, and tire requirements. `tireStrategy` does not enable automatic pit stops; `pitStops.enabled` is required for pit routing and non-clear pit intent requests.
|
|
216
271
|
- Penalty subsections use `strictness` from `0` to `1`, not only boolean enablement. `strictness: 0` means the subsection is not enforced; `strictness: 1` applies the configured rule margin. Steward decisions are exposed as `penalty` events and as top-level `snapshot.penalties`. Penalty entries include normalized consequences and lifecycle status. Immediate consequences apply time, grid, position, or disqualification effects directly; drive-through and stop-go consequences remain issued until served, cancelled, or converted at final classification.
|
|
217
272
|
- The browser UI can opt into top steward messages with `ui.penaltyBanners` and timing-row penalty badges with `ui.timingPenaltyBadges`. Steward messages render track-limit warning events and penalty decisions from the simulation; time-penalty messages put the penalty seconds in a large left chip and use penalty-colored backgrounds, while warnings use warning-colored backgrounds. Timing-row `!` badges are rendered only from `snapshot.penalties`; warning events do not count. UI code must not recalculate steward decisions.
|
|
218
273
|
- The simulator must stay interactive after being installed through `npm install @inventure71/paddockjs`.
|
|
219
274
|
- The package must build correctly through a browser bundler that supports JavaScript modules, CSS imports, and image imports.
|
|
220
275
|
- The simulation should remain deterministic for the same seed, track seed, drivers, entries, and rules.
|
|
221
|
-
-
|
|
276
|
+
- Warmup is enabled by default for browser mounts, headless environments, and direct simulation creation. It runs on a disposable runtime and must not mutate the visible initial race state; under the default `warmup.policy: 'config-change'`, identical configuration fingerprints reuse cached warmup while seed/config changes rerun warmup automatically.
|
|
277
|
+
- When `trackSeed` is omitted in a browser mount, the simulator creates a fresh procedural circuit for that mount. Explicit `trackSeed` values are deterministic and cached by seed plus resolved generation options for repeated mounts. Cached procedural definitions are immutable; callers that import `createProceduralTrack(seed, options)` should treat the returned definition as read-only and clone it before custom mutation. `trackGeneration` forwards the same procedural options used by `createProceduralTrack(seed, options)`: `profile`, `length`, `startStraight`, `pitLane`, `shape`, `validation`, and `attempts`. The `race` profile preserves the default full circuit with pit lane; `training-short`, `training-medium`, and `training-technical` are smaller pitless presets intended for training or demos. Explicit option fields override profile defaults after the profile is resolved. Procedural generation traces seeded connected region boundaries, smooths and warps them into centerline controls, then rejects circuits with excessive local heading jumps, turn accumulation, self-intersections, poor clearance, invalid length, or weak shape variation.
|
|
222
278
|
- The renderer should target a paced 60 FPS simulation/render loop.
|
|
223
279
|
- The render loop should pause while the race canvas is offscreen or the document is hidden, then resume without catching up the elapsed hidden time. Layout measurements needed for overlay camera safe areas should be cached between resize/layout invalidations. Runtime DOM updates should skip unchanged text/markup so visible embeds do not rewrite stable readouts every frame.
|
|
224
280
|
- Restart and rerender paths must destroy replaced PixiJS display children while preserving shared loaded textures.
|
|
225
281
|
- Restart supports race/data/seed changes but does not support asset URL changes or browser expert mode changes. Texture loading and ticker ownership are mount-time boundaries; hosts must destroy and mount again to change either boundary.
|
|
226
|
-
- Expert environment code can create a headless `createPaddockEnvironment()` from the `@inventure71/paddockjs/environment` subpath. It requires explicit `controlledDrivers`, accepts normalized actions `{ steering, throttle, brake }` plus optional `pitIntent` and `pitCompound`, advances only through `step(actions)`, and returns environment-loop JavaScript results with `observation`, `reward`, `terminated`, `truncated`, `done`, `events`, `state`, and `info`. Controlled drivers do not receive tire-threshold automatic pit calls; they request automatic pit service through `pitIntent`, may choose the target tire through `pitCompound`, and observe pit-lane/service/race-control state in `observation[driverId].object.self` and `.race`. `pitIntent: 0` is a no-op clear request and does not fail when pit stops are disabled. `self.onTrack` follows wheel-level legality, so track, kerb, and legal pit-lane/box surfaces are on-track while gravel/grass/barrier are off-track. Environment scenarios may set reset positions with `preset`, `placements`, and relative `traffic`;
|
|
227
|
-
-
|
|
282
|
+
- Expert environment code can create a headless `createPaddockEnvironment()` from the `@inventure71/paddockjs/environment` subpath. It requires explicit `controlledDrivers`, accepts normalized actions `{ steering, throttle, brake }` plus optional `pitIntent` and `pitCompound`, advances only through `step(actions)`, and returns environment-loop JavaScript results with `observation`, `reward`, `metrics`, `terminated`, `truncated`, `done`, `events`, `state`, and `info`. `steering` is an absolute normalized steering target: `-1` points at maximum left, `0` points at center, `1` points at maximum right, and intermediate values are percentages of the maximum steering angle; the vehicle integrator rate-limits motion toward that target instead of snapping the wheel. `steering`, `throttle`, and `brake` are required for each controlled-driver action. Strict action policy throws on missing or non-finite vehicle controls, while report policy records the error and releases stale manual controls so the built-in driver owns that physics step. `info.drivers[driverId]` exposes per-driver `terminated`, `truncated`, `endReason`, `episodeStep`, and `episodeId` for batched loops; selected-driver resets clear only selected driver truncation/termination and do not rewind global `info.step`. For scoped reset results, `info.controlledDrivers` matches the drivers present in `observation` and `metrics`, while `info.drivers` preserves episode state for all configured controlled drivers. Controlled drivers do not receive tire-threshold automatic pit calls; they request automatic pit service through `pitIntent`, may choose the target tire through `pitCompound`, and observe pit-lane/service/race-control state in `observation[driverId].object.self` and `.race`. `pitIntent: 0` is a no-op clear request and does not fail when pit stops are disabled. `self.onTrack` follows wheel-level legality, so track, kerb, and legal pit-lane/box surfaces are on-track while gravel/grass/barrier are off-track. Barrier-wall contact in both physics modes is measured against the rendered wall's inner face; contact marks the car destroyed/DNF, removes it from active collision/sensor participation, emits a `car-destroyed` event, and terminates that driver's episode with `endReason: 'destroyed'`. Opt-in stalled off-track DNF removes the car from the same active participation systems while keeping `destroyed: false` and terminates controlled-driver episodes with `endReason: 'stalled-off-track'` when `rules.modules.stalledDnf.enabled` is `true`. Reset is still an episode-boundary `resetDrivers()` call. Environment scenarios may set reset positions with `preset`, `placements`, and relative `traffic`; `resetDrivers(placements)` may reset selected controlled drivers between episodes without recreating the whole simulation. Partial `reset(options)` calls preserve omitted nested option groups while replacing arrays and explicit scenario placement maps. After placement, selected cars are classified by the same runoff/barrier rules before observations are returned, so cars already inside terminal barrier space report destroyed metrics and stable miss-valued rays instead of doing alive-car far-out ray scans. Both scenario placement and `resetDrivers()` are setup data, not policy actions. `participantInteractions` may make real physics cars non-colliding, sensor-hidden, non-blocking for pit occupancy, or excluded from race order, but those cars still live in `snapshot.cars` and move only through normal physics/control APIs. The `batch-training` profile is non-colliding, sensor-hidden, pit-non-blocking, excluded from race order, and still rendered. `replayGhosts` are separate trajectory-driven entities in `snapshot.replayGhosts`; they are visual/reference overlays and never enter car physics, timing, pit, order, or penalty systems. Replay ghosts are sensor-hidden unless their own sensor flags explicitly opt them into ray or nearby observations.
|
|
283
|
+
- Headless environments also accept an optional `externalRenderer` observer hook. It receives `{ snapshot, observation, meta }` on `reset`, `step`, and `resetDrivers`, so external tooling can stream authoritative frames to visualizers without letting that transport mutate simulation state.
|
|
284
|
+
- Controller loop code should use `createPaddockDriverControllerLoop()` instead of duplicating browser/headless stepping. Its controller context groups observations by controlled driver id, includes `orderedObservations` for direct batch tensor assembly, exposes metrics, events, cached specs, and reset-driver ids, and keeps per-driver resets as controller reset hooks when the runtime supports `resetDrivers()`. `previousActions` is the last action map actually applied before the current `actions`; on the first controlled frame after reset it is empty, and after repeated frames it reflects the prior physics step rather than pre-copying the current decision.
|
|
285
|
+
- Expert ray sensors originate from the controlled car center. The default compact set is `[-135, -60, -20, 0, 20, 60, 135, 180]`, giving forward, side, and rear awareness while staying small. Rays detect track edges against the actual track geometry and detect car hits by ray-to-car-footprint intersection. Hosts may opt into per-ray lengths, predefined layouts such as `driver-front-heavy`, and surface-aware channels for kerb and illegal surface detection; those channels are computed only when requested. For normal driver interactions, `precision: 'driver'` road-edge, kerb, and illegal-surface channels keep the sampled model-facing distances whether the track query index is enabled or disabled. The `batch-training` participant profile keeps its indexed recovery-ray path as its high-throughput training contract; other indexed ray-boundary shortcuts are reserved for non-driver/debug diagnostics. Barrier walls are rendered/physical terminal boundaries, not model-facing ray targets; active ray objects, vectors, schemas, and visualizations must not expose a `barrier` ray channel. Ray `precision` defaults to `driver`, which is the active model-facing sensor contract; `debug` precision is only for explicitly labeled diagnostics. `observation.profile: 'physical-driver'` exposes local driver-like yaw, contact-patch, boundary, richer ray, and opponent-radar senses while omitting default lookahead samples unless explicitly configured. `observation.output` can be `full`, `vector`, or `object`, `includeSchema: false` omits repeated schema payloads, and `vectorType: 'float32'` returns typed vector buffers for high-throughput JavaScript loops. `result.stateOutput` can be `full`, `minimal`, or `none`; `none` returns `state: null` and is intended for loops that rely on observations, metrics, and info instead of full snapshots.
|
|
286
|
+
- Track surface bands are single-source geometry. Rendering derives visible gravel, runoff, and barrier offsets from the same track widths used by wheel surfaces and ray surface hits: road edge, kerb outer edge, gravel outer edge, runoff outer edge, and barrier wall width. New code must not add independent magic offsets for these bands.
|
|
228
287
|
- Browser expert mode is opt-in with `expert: { enabled: true, controlledDrivers, frameSkip }`. When enabled, the returned controller exposes `expert.reset()`, `expert.step(actions)`, `expert.getObservation()`, and `expert.getState()`.
|
|
288
|
+
- Browser expert mode also exposes `attachExternalRenderer(source)`, `detachExternalRenderer()`, and `getExternalRendererState()` for render-only external-frame playback. The `source` callback contract is `subscribe(onFrame) => unsubscribe`, where each frame is `{ snapshot, observation, meta? }`.
|
|
229
289
|
- Browser expert mode wraps the same `RaceSimulation` instance that the visual canvas renders. It must not create a parallel simulation for the same mount.
|
|
230
290
|
- Browser expert mode disables automatic ticker-driven simulation advancement. The visual canvas updates only after explicit expert `reset()` or `step(actions)` calls.
|
|
231
|
-
-
|
|
291
|
+
- While external renderer mode is attached, browser expert runtime is strict render-only and rejects local `step()`, `resetDrivers()`, and `reset()`. Hosts must detach before returning to local stepping; detach restores the current local simulation track surface if external frames had redrawn the shared track asset.
|
|
292
|
+
- Policy Runner `Live preview stream` mode accepts `ws://`/`wss://` push streams and `http://`/`https://` polling endpoints that return `preview:snapshot` frames.
|
|
293
|
+
- Browser expert mode may opt into `expert.visualizeSensors: true` or `expert.visualizeSensors: { rays: true }`. When enabled, ray sensors render in the race canvas world layer from the selected controlled car by default, using the same observation result produced by explicit expert steps. The overlay draws a separate colored marker for each detected active channel on each ray, including road-edge, kerb, illegal surface, and car hits. Barrier walls are visible track geometry, not ray-hit markers, and browser components must not reintroduce a barrier ray label. Hosts may request `visualizeSensors: { rays: true, drivers: 'all' }` for the heavier all-controlled-car overlay or pass an explicit driver id list. Every model-facing sense follows this rule: the model receives the active environment observation, and Policy Runner/expert visualization displays that same observation instead of recomputing a more precise or different browser-only value. Extra diagnostics must be clearly separated from model senses.
|
|
232
294
|
|
|
233
295
|
## Current Visible Features
|
|
234
296
|
|
|
@@ -236,8 +298,8 @@ Returned controller:
|
|
|
236
298
|
- Race canvas rendered with PixiJS.
|
|
237
299
|
- Procedural track rendering with asphalt texture and DRS overlays.
|
|
238
300
|
- Driver selection from cars and timing tower rows.
|
|
239
|
-
- Camera modes: overview, leader, selected, show all.
|
|
240
|
-
Overview
|
|
301
|
+
- Camera modes: overview, leader, selected, show all, and pit.
|
|
302
|
+
Overview frames the active generated track bounds with package-owned padding and pit-lane extent; show all dynamically fits the active pack; pit frames the operational pit-lane work area when the track has one.
|
|
241
303
|
- Zoom controls.
|
|
242
304
|
- FPS readout.
|
|
243
305
|
- Start lights.
|
|
@@ -270,11 +332,11 @@ npm run check
|
|
|
270
332
|
|
|
271
333
|
Expected:
|
|
272
334
|
|
|
273
|
-
-
|
|
335
|
+
- Fast Vitest tests pass in the normal local gate. Slow characterization tests run under `npm run check:release`.
|
|
274
336
|
- `npm pack --dry-run` succeeds and includes source files plus bundled assets.
|
|
275
337
|
- A packed tarball installs and builds inside a fresh temporary Vite consumer app.
|
|
276
338
|
- The tracked showcase host builds.
|
|
277
|
-
- Chromium browser smoke verifies
|
|
339
|
+
- The quick Chromium browser smoke verifies showcase canvas rendering, overflow constraints, and one public API action. The release browser smoke verifies the desktop/mobile matrix, package-panel overflow constraints, public API buttons, and visual policy-runner stepping across generation and race configurations.
|
|
278
340
|
|
|
279
341
|
Run from a browser host that consumes the published package:
|
|
280
342
|
|