Public release

This commit is contained in:
2026-10-06 18:28:45 +00:00
parent 1062542e62
commit 9944af66e7
220 changed files with 535 additions and 30319 deletions
+3 -3
View File
@@ -1,9 +1,9 @@
@echo off
cd /d "%~dp0"
"C:\Users\Nicholas\.cache\codex-runtimes\codex-primary-runtime\dependencies\native\powershell\pwsh.exe" -NoProfile -ExecutionPolicy Bypass -File "%~dp0native\forward_camera\setup.ps1" -Disable
"C:\Python314\python.exe" tools\retire_forward_camera.py --apply
if errorlevel 1 (
echo Disable failed or was cancelled. See diagnostics\forward-camera-setup.log.
echo Close ATS normally, then retry. Cab-screen framework remains installed.
) else (
echo SPF disabled. Restart ATS normally.
echo Camera inset removed. Start ATS normally; both cab screens remain available.
)
pause
-9
View File
@@ -1,9 +0,0 @@
@echo off
cd /d "%~dp0"
"C:\Users\Nicholas\.cache\codex-runtimes\codex-primary-runtime\dependencies\native\powershell\pwsh.exe" -NoProfile -ExecutionPolicy Bypass -File "%~dp0native\forward_camera\setup.ps1"
if errorlevel 1 (
echo Camera setup failed or was cancelled. See diagnostics\forward-camera-setup.log.
) else (
echo Passive camera prototype installed. Restart ATS and keep FSD disengaged for the first test.
)
pause
-9
View File
@@ -1,9 +0,0 @@
@echo off
cd /d "%~dp0"
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0tools\install_inset_top_right.ps1" -Projection pop-wide
if errorlevel 1 (
echo Installation failed. Keep ATS and the driving runtime closed; inspect the reported error.
) else (
echo Top-right Pop wide preview installed. Restart ATS for passive camera verification.
)
pause
-9
View File
@@ -1,9 +0,0 @@
@echo off
cd /d "%~dp0"
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0tools\install_inset_top_right.ps1"
if errorlevel 1 (
echo Installation failed. Keep ATS and the driving runtime closed; existing files are preserved or restored.
) else (
echo Top-right inset installed. Restart ATS; the first run is passive while the new placement is verified.
)
pause
-9
View File
@@ -1,9 +0,0 @@
@echo off
cd /d "%~dp0"
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0tools\install_pop_camera_rectification.ps1"
if errorlevel 1 (
echo Installation failed. Keep ATS and the driving runtime closed. Existing files are preserved or restored.
) else (
echo Asymmetric camera profile installed. No driving calibration is granted. Start ATS manually for passive verification.
)
pause
+36 -919
View File
@@ -1,950 +1,67 @@
# Tesla Semi ATS driving assistant
# ATS Native FSD
## Current runtime: ATS-native autopilot
Experimental simulator autopilot and Tesla Semi cab displays for American Truck Simulator. The controller follows the game's directed lanes and active GPS route, measures nearby vehicles and trailers, and drives through vJoy.
`Run-Tesla-FSD.bat` now starts the native ATS backend. It does not load
openpilot, WMI, Pop v2, ONNX, or camera inference for control. The backend
follows the active game GPS route over the mounted lane graph, reads simulator
traffic/trailer geometry and authored signal data, and drives through the
verified vJoy input path. The optional in-game SPF bridge (`native/input_bridge`)
is retained for explicit diagnostics, but its acknowledgement alone does not
prove that ATS has mapped the semantic device into the truck controls. With
`--input auto`, the runner therefore selects vJoy first and only tries ETS2LA
if vJoy is unavailable; `--input spf`, `--input ets2la`, and `--input vjoy`
select a transport explicitly. The Tesla Semi right and left screen surfaces
remain the native backend's display and diagnostics output.
## Run
The older WMI/Pop launchers remain available for passive comparison and
rollback only. They are not part of the native control path.
Cabin rendering runs on a separate worker with one pending frame; slow screen
updates cannot hold up fresh steering commands. Authored road coordinates are
immutable after verification, so detached driving scenes share those static
points while copying mutable observations. Lane association projects all
segments together. vJoy writes serialize with neutral/release separately from
the command mailbox, allowing the next command to be queued during a slow
device write. The 500 ms command watchdog remains active. The native actuator
worker neutralizes immediately on a failed focus check and latches a fault if
it persists for 100 ms; a brief window handoff can resume the existing lease
only with an unexpired command. The main loop still releases on focus loss,
Escape, or manual takeover. A confirmed fault requires a new human F8 press.
The control log records scene-copy, planning, SDK-to-control, command dispatch,
and cabin-render timings separately.
Road-profile handoffs use a fixed qualified bridge between both complete road
primitives. Its forward path does not shrink when the truck enters the bridge;
lane membership uses that same curve until it joins the next road centerline.
The bridge requires verified sources, consecutive GPS edges, an explicit
route-bound profile connection, and qualified geometry on both sides. Ordinary
off-path, height, heading, and freshness checks still apply.
Native automatic passing uses the mounted ordinary-road lane definitions and
measured actor bodies. When the set speed exceeds a verified lead's speed by
more than 5 MPH, the planner checks the adjacent left lane, signals, and follows
a road-anchored transition. It keeps the maneuver when the lead leaves the
forward view, follows the passing lane, and signals right to return only after
the passed consist clears the rear of the player's trailer and the return gap
is usable. A controlled junction queue does not trigger a pass. Shoulders and
opposing lanes are excluded. The cockpit status and bounded native control log
report the maneuver phase and reasons for waiting.
Lane-change steering and collision checking use the maneuver's chosen path;
the departure lane's center and old forward corridor no longer fight the pass.
Only a fresh permitted transition expands the lane-membership gate at the
midpoint. An occupied lane pauses the maneuver with braking. Lane permissions
are refreshed in the background after map expansion, using the current mounted
definition catalog rather than retaining an obsolete graph hash.
A measured parked vehicle blocking the route can trigger the same adjacent-lane
bypass. Authored construction-prefab paths remain part of native GPS following.
Random roadwork cones, barriers, and full-road detours are **not detected by the
vehicle actor reader**. Handling those events requires live event/obstacle
geometry and a route that excludes the closed corridor; an empty vehicle list
does not establish that a work zone is clear. SCS documents random road events
and lane-blocking behavior at
https://modding.scssoft.com/wiki/Documentation/Engine/Units/journey_events_road_event
and whole-road detours at
https://modding.scssoft.com/wiki/Documentation/Engine/Detours.
## Continuous WMI / Pop v2 gameplay
`Run-WMI-Drive.bat` selects the pinned stock openpilot 0.11.0 WMI model; `Run-Pop-v2-Drive.bat` retains Pop v2 as a fallback. The panel names the selected model. Both use the same verified split vision/policy tensor layout, decoder, paired narrow/wide camera input and temporal context. To select directly: `python tools/run_pop_gameplay.py --model wmi-v0.11.0` or `--model pop-v2`. Matching contracts do not establish equivalent ATS driving performance.
Continuous gameplay accepts the Peterbilt 579 and the Tesla Semi, reported by the SDK as `Semi truck 2019`. The installed forward inset and native camera checks remain in use. On October 3, 2026, the user reported that the inset remains fixed through the full camera look range in the Tesla Semi. This is a visual observation; the earlier 579 calibration evidence is preserved separately.
GPS is optional when fresh SDK telemetry reports zero route distance and the GPS reader explicitly reports no active route. The panel then shows model road following, and F8 can engage without a destination. Setting a destination restores GPS checks; missing or invalid data for an active route does not silently switch to model-only driving.
Use `Run-Pop-v2-Drive.bat` for continuous experimental driving with Pop v2, analog vJoy steering, and Chill speed hold at the saved target (35 MPH initially). Keep ATS in front, select a forward gear, release the parking brake, and press **F8** when the panel reports ready. F8 toggles driving; manual steering or braking and focus loss release controls. Camera looks remain available. Escape releases driving controls while leaving the panel open, so ATS menus work normally. Close the panel or press Q while it is focused to exit.
This mode has no trial timer or narrow engagement speed band. Model uncertainty and incomplete historical slots after initial warmup appear as warnings. Disengaging leaves the original model/GPS/traffic dashboard live, and a later F8 press can engage again. The model uses CPU inference; GPS is displayed as route guidance and does not yet steer navigation turns. With ATS focused, **Home raises MAX by 5 MPH; End lowers it by 5 MPH**, while engaged or disengaged. Range is 5–80 MPH. The panel updates immediately and the target is saved for the next launch. First launch defaults to 35 MPH; `python tools/run_pop_gameplay.py --speed 40` overrides the initial target.
Temporal warmup resamples the policy's historical feature timeline between real
recorded model features at the observed CPU cadence. Interpolation is bounded
to 250 ms and to normal local cadence; unsupported intervals remain incomplete.
Observed/interpolated slot counts and bracket widths are recorded explicitly.
Actual camera pairs retain their separate 100 ms sampling bound. A brief capture
interruption no longer erases all history; long pauses and projection changes
still reset it. An unqualified GPS first-node connection permits camera lane
assistance while automatic route execution remains pending. Matched route/model
disagreement and manual junction handoffs still retain their control gates.
Steering follows the actual model path with an 18 metre / 2.5 second lookahead, reducing correction strength when the forecast is shorter. Gameplay speed hold can ramp throttle to 100% for truck load and retains learned holding power near the target instead of repeatedly dropping to coast. Following uses native actor/trailer boxes and the measured truck front extent. Missing motion estimates do not erase a position hazard. A centered camera lead with probability at least 0.90 over three consecutive frames and at least 95 ms can provide a nearer rear estimate or a fallback; adjacent/single-frame detections cannot. Incomplete traffic coverage still requires manual following. SDK feedback from our own vJoy brake is not treated as a manual takeover; physical steering/brake keys still release control. Brief command gaps can recover with a unique model frame no older than 350 ms; a 500 ms command deadline still releases controls and requires a new F8 press.
Stopping-distance and time-to-contact estimates drive traffic braking, including 100% emergency brake instead of the earlier 20% cap. With fresh measured native motion, low-speed traffic following uses a 16-foot minimum buffer for a moving lead and follows its measured pace; stopped or uncertain leads retain the 26-foot buffer. A matching camera rear can tighten the gap without erasing measured departure motion. Close leads persist as explicitly estimated gaps for at most one second across read dropouts, without extending the last observation timestamp; held estimates cannot enable the reduced queue buffer. A traffic feed gap with no retained lead inhibits throttle while leaving steering engaged. Brief model/path gaps retain traffic braking instead of unconditionally clearing the pedals. The panel labels following/emergency braking and unknown-feed coasting. Native linked trailer chains are bounded to four; unverified or longer chains reject the snapshot, and coverage is still incomplete. These are experimental simulator heuristics, not guaranteed collision avoidance.
The experimental painted-lane blend is disabled after a reported lane-keeping regression; steering currently uses the previous model-path controller. The helper remains available for offline analysis. A rejected vJoy write gets one identical retry only if the SDK still confirms ownership. Persistent actuator or neutral-write failures leave the panel alive and passive, report the fault, and require a new human F8 press to retry.
The truck navigator's SDK posted speed limit can raise MAX. A valid limit must remain stable for 0.3 seconds; the first known limit or a change to a higher posted limit raises MAX only if it exceeds the current target, within the existing 80 MPH cap. The automatic offset is +5 MPH while a verified trailer is attached (or its state is still unknown) and +10 MPH when the verified own chain says the tractor is bobtail. Home/End still adjust MAX by 5 MPH. An unchanged or lower sign does not overwrite a manual setting; zero, missing, paused or stale limits are ignored. Target changes are saved and shown immediately. This increase-only mode does not reduce MAX for lower posted limits.
MAX is a ceiling. Predicted path curvature reduces the effective cruise target using a 2 m/s² lateral acceleration budget. Covered path points up to 100 m also provide bend anticipation with a 1.5 m/s² braking budget; the planner never extrapolates beyond the model path. Speed recovers at up to 3 MPH per second after a bend. The saved MAX stays unchanged by curve caps. This is a simulator heuristic, not validated rollover prevention; path branch selection and lane keeping remain incomplete.
A supervised simulator controller using the existing Supercombo model, ATS telemetry, and analog vJoy or keyboard controls. F8 selects the camera for the chosen mode, centers the cabin with NumPad 5, and engages after ten usable road frames. Steering tracks the detected lane center at distance-indexed lookahead points. The calibrated road inset supports a limited steering test with manual speed; the separate bumper mode also supports cruise.
## Finish setup
1. Close ATS and double-click `install_plugin.bat`. Approve the Windows administrator prompt. The installer copies and verifies the bundled RenCloud v1.12.1 64-bit plugin; results go to `install_log.txt`.
2. Restart ATS and enter the driving view. Start the engine, select a forward gear, and release the parking brake.
3. For keyboard fallback, leave ATS configured for A/D and W/S. For smoother analog control, finish the vJoy setup below. The assistant sends no mouse movement.
4. The **Tesla Semi FSD** desktop shortcut opens the calibrated inset steering test with CPU inference, vJoy and the original dashboard. Bring ATS to the foreground on a straight road with clear lane markings, drive at 10–15 MPH, then press **F8**. Control the pedals manually. Inset testing disengages above 20 MPH. `Run-Tesla-FSD-Passive.bat` opens observation without acquiring driving controls.
5. F8 again, Escape, physical driving keys, or camera keys take over. Focus loss, paused/stale telemetry, unclear lanes, and actuator errors also release controls.
The HUD shows engagement-blocking reasons. Tab belongs to ATS. Lane-change shortcuts are disabled during initial lane-keeping validation. The HUD moves to a second monitor when available; on a single monitor keep it behind ATS while driving.
The original dashboard panel is still the default. It shows the actual 512x256 model input, lanes, predicted path, speed, gear, status, selected model, driving mode, model provider, and inference timing. `--no-hud` hides it for diagnostic tests. `--hud-mode cockpit_screen` selects the compact visualization; with the panel focused, M switches layouts and Q exits. C cycles driving modes and N cycles compatible registered models, only with fresh stationary telemetry, the parking brake set and F8 off. Focusing the panel while driving releases control because ATS loses focus. The ordinary inset launcher retains manual pedals; C cannot bypass its restriction to steering-only control.
## IQ Pilot feature integration
The comparison uses only the requested [IQ.Pilot beta-radarless-pq branch](https://gitlvb.teallvbs.xyz/IQ.Lvbs/IQ.Pilot/src/branch/beta-radarless-pq/), pinned to commit `821597d28fba40a531c3e2afa02fb0c0198a8d04`. Public source was read through its Gitea contents API; file revisions are preserved in the ignored `reference/iqpilot-beta-radarless-pq/source.json`. The ATS code implements these concepts independently. The reviewed branch maps Stock ACC to factory longitudinal control, IQ.Chill to IQ longitudinal with relaxed personality, and IQ.Pilot to end-to-end model longitudinal control. Its signal lane-change modes include direct and timed activation, brake cancellation, a consumed state, and optional blind-spot waiting. IQ.Dynamic exists in the newer separate local checkout, but is outside this branch comparison.
| Feature | Available here | Work before active use |
| --- | --- | --- |
| Driving modes | `--driving-mode manual`, `cruise`, or `chill`; Chill limits throttle/ramp and increases following distance. Neither cruise mode is model-driven IQ.Pilot. | Tune the remaining speed error and test bends/lead following. End-to-end mode needs a validated model trajectory and speed planner. |
| Model selector | `--list-models`, `--model ID`, and parked panel N; every local entry has its own manifest, hash and decoder contract. The historical model and an experimental passive Pop v2 adapter are installed. | Validate Pop's camera, cadence and vehicle response before control. Its split vision/policy bundle has a separate runner and decoder; it cannot replace the historical ONNX directly. |
| Laneless path | `--dry-run --path-preview` evaluates model geometry without acquiring vJoy. Pop's passive assessor also checks predicted road edges, uncertainty and temporal coverage. | Validate camera pose, live cadence, obstacle handling and closed-loop response. Hypothesis weight is not road confidence. |
| Nudgeless turn signals | `--dry-run --signal-preview` reads actual SDK signal flags and issues one model-intent pulse per activation, with configurable delay and brake cancellation. This never commands a lane change. | Validate the model's maneuver response, adjacent-lane geometry and side traffic; add completion/abort states and trailer clearance. Nearby ATS vehicles can now be displayed, but blind-spot clearance logic is not validated. |
`Run-Tesla-FSD-Chill-Test.bat` opens a restricted 120-second, 15 MPH inset cruise test with the usual camera identity, telemetry, focus, takeover and watchdog checks. The desktop shortcut still opens manual-pedal lane keeping. Chill is an ATS speed controller inspired by the mode distinction; it is not the IQ.Pilot implementation or its complete driving stack.
`Run-Tesla-FSD-Feature-Preview.bat` opens passive path and signal evaluation with the original dashboard and paired input/output recording. You drive. The previews require `--dry-run` and cannot acquire vJoy or actuate the truck. Signals use active flags rather than flashing lamp states. The preview delay defaults to one second; `--signal-delay` accepts 0.05, 0.5, 1, 2 or 3 seconds. Preview cancellation does not establish that a neighboring lane is clear.
Assess a recording with `python -m tools.assess_path_recording diagnostics/RECORDING_DIRECTORY`. Existing moving calibration had usable path geometry in 253 of 266 frames, but a median 0.64 m offset from the detected lane center. The other 13 paths lacked usable forward extent. This is a geometry assessment, not validation of laneless driving; the saved frame review confirms that the path can be offset from lane center.
The implementation order is: clean camera input and comfortable speed control; paired passive path/signal recordings and model comparison; calibrated laneless tracking; then controlled turn-signal lane-change tests with explicit clearance and abort behavior. The current runner still uses CPU ONNX Runtime; this feature work does not enable ROCm.
## Cabin driving with a separate model camera
An experimental `--camera auxiliary` mode reads a dedicated 512x256 road inset while the main ATS view stays in the cabin. It uses [SCS custom multi-view rendering](https://eurotrucksimulator2.com/multimon_config.php), with cabin geometry disabled only in the inset. This is an additional rendered camera, not access to an invisible camera 6 feed. `Run-Tesla-FSD.bat` selects the calibrated inset steering test with CPU inference and opens the original dashboard. `Run-Tesla-FSD-Passive.bat` keeps observation available without driving commands. Running `python main.py` directly still defaults to the validated bumper mode with automatic provider selection.
Run `python -m vision.configure_auxiliary_camera` to generate a preview. Close ATS, then run it with `--apply` to back up `config.cfg` and any existing `multimon_config.sii` and install the layout. The initial camera offset is truck-dependent and needs live calibration. Restart ATS in cabin view (top-row 1), then run `python main.py --camera auxiliary --dry-run --record-calibration --inference-provider cpu`. The dashboard camera preview should show only the inset road image, with plausible lanes and stable confidence. Recording saves the exact input and matching live model outputs. Active auxiliary control requires a reviewed calibration matching the truck, layout, model, plugin and settings. Resolution/layout changes require recalibration. Physical steering and camera keys still take over. Mouse-look is permitted only in active inset mode with live camera correction; a short supervised road check passed.
On October 3 the inset was verified live at the top center, 32 pixels below the top of the 2560x1440 game screen. The original SCS layout followed cabin head movement. The installed ForwardCamera render integration compensates for that movement, and the Pinnacle calibration now permits restricted steering-only control. The original game configuration is preserved in `fsd-camera-backup-20261003-031258-083728` inside the ATS documents directory. Game notification overlays can obscure the inset because capture reads the rendered screen.
An independent truck-facing view requires a render integration that fixes the auxiliary camera to the truck while preserving the driver's camera. [SCS explains the main-camera dependency](https://forum.scssoft.com/viewtopic.php?p=375768). The inspected [ETS2LA capture plugin](https://github.com/ETS2LA/capture) captures already-rendered frames, and the [ETS2LA communication plugin](https://github.com/ETS2LA/plugin) exposes camera properties; neither documented interface creates the independent view.
A [ForwardCamera prototype](native/forward_camera/README.md) uses [SPF Framework v1.2.5](https://github.com/TrackAndTruckDevs/SPF-Framework/releases/tag/v1.2.5) to compensate for cabin head movement in the `road` inset. The direct per-monitor render hook retains truck rotation while removing head rotation. It requires exact loaded-code comparisons across five inspected ATS 1.61.2 functions, a signature/location check, and road rectangle/FOV checks. Version 0.2.3 also compensates for head translation using the existing read-only RenCloud telemetry mapping. All 117 parked look samples matched, with median/P95 feature shifts of zero pixels at detector precision. No different parked pose was held long enough for a settled result, and the user still reported very slight movement. Subsequent moving calibration found usable lanes in all 155 recorded look frames, with reviewed lane overlays following the paint. The original dashboard remains available. The installer backs up existing SPF files and preserves camera settings.
## GPS-guided driving
The target is a destination-to-destination simulator experience: the selected ATS GPS route guides lane selection, exits and turns; the road camera supplies local road/traffic observations; the controller applies steering and speed. This is a navigation-guided architecture. The existing historical Supercombo input contract has no GPS/navigation tensor, so GPS cannot be passed directly to that model without changing its interface or adding a planner.
The RenCloud reader now exposes SCS navigation distance (metres), ETA (seconds), speed limit (m/s), local map scale, and the truck's world position/rotation. The dashboard displays GPS distance and speed limit, and paired passive recordings preserve this metadata. These fields are observations; no driving behavior is changed by them. Invalid optional navigation metadata is marked unavailable without invalidating otherwise healthy steering telemetry.
Run `python -m tools.check_navigation` to inspect the live inputs without acquiring controls. The October 3 check found fresh ATS telemetry, 55.4 km remaining, 2324 seconds ETA, a 75 MPH reported limit and finite world pose. The independent `Local\\ETS2LARoute` feed was absent, matching the installed plugin inventory. Details are saved in `diagnostics/navigation-input-check.json`.
[ETS2LA's navigation reader](https://github.com/ETS2LA/ETS2LA/blob/main/ETS2LA.Game/SDK/Navigation.cs) documents a separate game-side feed of route node IDs with distances/times to the destination. Those IDs still require matching map geometry to produce turns, exits or an ego-relative path. The implemented read-only adapter opens only an existing route mapping, verifies snapshot consistency/format, and always marks it unsuitable for control. It does not create a mapping, open the ETS2LA input feed, or send steering commands.
The reviewed [route exporter](https://github.com/ETS2LA/plugin/blob/main/src/core.cpp) updates on a change in route node count and does not clear the previous route in its no-route branch. Its shared buffer has no heartbeat or route-generation ID. Identical node counts can therefore conceal reroutes; two matching reads do not establish freshness. Compatibility with this ATS 1.61 build also needs verification before installing or adapting a game-side exporter. A production bridge must publish its supported game/build and protocol version, heartbeat, route generation/hash, explicit route-active state, and bounded coordinate data. It must clear route guidance on cancellation, rerouting, pause, stale telemetry or map mismatch.
Next steps:
1. The first route connection is now implemented without a new plugin: `telemetry/gps_route_reader.py` reads the live GPS task through read-only process access. It requires the exact verified ATS executable SHA256 and compares both loaded GPS getters with that file before reading pointers. Route array bounds, repeated pointer/array/node snapshots and SDK distance/ETA agreement reject mismatched or changing data. Each snapshot re-reads all route points, including same-count reroutes. Pause, stale telemetry and zero GPS distance clear cached guidance immediately. This build-specific adapter will refuse an ATS update until reverified.
2. Run `Run-Tesla-FSD-Navigation-Preview.bat` for the original dashboard with the model camera, GPS map and next route bend. Leave F8 off and drive manually; F8 cannot enable driving in this mode. Route nodes are graph points, not a lane-center steering path; bends are not classified as exits or intersections. The preview matches world position, heading and advisor progress, then records coordinates and paired road/model frames. The first live parked check read a 52-point route and matched the truck to its current segment with 2.85 world metres cross-track error, 0.02 advisor metres progress error and heading dot product 0.9999998. All eight live snapshots matched. Next, record a manual bend, exit and intersection; verify rerouting and cancellation in the game. Use `python -m tools.check_gps_route --duration 2 --render` for a route-only diagnostic without any controller.
3. Add a navigation planner or a compatible model accepting route context. Keep route instructions, lane changes and intersection turns distinct; the current model's lane-change pulse is not a general navigation-turn command.
4. Validate supervised highway exits, then turns/intersections, speed changes, traffic lights, yielding and trailer clearance. A GPS route alone does not resolve obstacles, right-of-way or stop conditions.
The first manual navigation drive recorded 732 moving samples across 40.57 seconds. Route matching succeeded in 695 (94.95%), progressing through segments 3–6 with a minimum heading dot product of 0.99908. Median graph cross-track error was 2.91 world metres (maximum 7.01); graph offsets are not lane-center errors. Two SDK/GPS disagreement episodes hid guidance for 1.05 and 1.10 seconds. The reader now retains its verified read-only handle after snapshot disagreements and retries after 50 ms instead of forcing a one-second reconnect; strict data checks remain unchanged. This recovery change passes regression checks but still needs a moving retest. Only 575 of the 732 moving model frames passed the existing lane checks, so this run does not validate automatic navigation steering. Evidence is `diagnostics/inset-cal-20261003-060527-828098/navigation-assessment.json`. Reproduce the assessment with `python -m tools.assess_navigation_recording <recording-directory>`.
A subsequent run used the ordinary steering launcher (`dry_run=False`, manual pedals), without GPS route snapshots. Its first engagement lasted 0.480 seconds before a lane-confidence release; its second lasted 14.053 seconds before the existing 20 MPH limit released steering. The saved confidence-drop road image was unobstructed, so this release cannot be attributed to a HUD popup. That run does not validate the requested GPS bend/exit/reroute check. Evidence is `diagnostics/steering-review-20261003-061208.json`; the two release folders preserve exact model inputs. Use the Navigation Preview launcher for the next GPS recording.
### Bounded GPS driving and road scene
`Run-Tesla-FSD-GPS-Driving-Test.bat` runs GPS-assisted camera steering and
12 MPH Chill cruise for at most 120 seconds. F8 engages after the existing
camera/telemetry checks; F8 or physical driving inputs release control. The
ordinary `Run-Tesla-FSD.bat` still uses manual pedals and now shows/records GPS.
The GPS graph constrains camera-supported guidance; it is not a lane-center
path and does not establish right-of-way at exits or intersections.
The October 3 GPS trial recorded 777 engaged samples over 43.06 seconds, with
all 777 matched to the route. Measured steering and throttle followed the
commands. Control released when the gearbox entered neutral. The 12 MPH
setting had a remaining speed error on an uphill section. The Chill speed
loop now learns a bounded throttle offset to compensate for load, clearing
it on reset, stale telemetry, lower targets, overspeed and following limits.
Its existing throttle/brake caps remain unchanged; this adjustment needs a
moving retest. Evidence: `diagnostics/navigation-drive-20261003-061834-419967`.
The road scene preserves all four historical model lane-line outputs with
their individual probabilities. It displays only confident observations,
with brighter ego boundaries and dimmer adjacent boundaries. Four possible
lines do not prove four lanes, and uncertain road geometry is not filled in.
In the live parked exit-split check, the model confirmed only one boundary;
it cannot yet supply an accurate complete highway layout at that location.
Nearby vehicles now come from a separate, read-only ATS actor adapter. The
reader requires the exact verified ATS 1.61.2 executable, compares the loaded
traffic getter with that executable, validates bounded lists and repeated
snapshots, and checks the player's position against SDK telemetry. It
excludes the player's truck/trailer and reports measured vehicle positions,
dimensions and headings ahead, beside and behind the truck. The live parked
check verified vehicles queued behind the truck and on the opposite
carriageway. A game update disables this source until it is verified again.
The dashboard keeps its original camera preview and GPS map. Its surround
view shows actual loaded actors, with model-observed forward lane lines in
the same metric view. Coverage is incomplete: no displayed vehicle is not
proof of a clear lane. Traffic observations currently improve the display
and recordings; they do not authorize lane changes or select a traffic-aware
route. Lane selection needs verified lane geometry, tracked gaps and an
abort-capable planner before it can control the truck.
A local read-only map cache now supplies lane counts independently of the
camera model. Seven nearby map sectors were completely decoded in format 907;
the nearby highway's `us_tmpl12` definition explicitly contains two lanes in
the truck's travel direction. Both road endpoint IDs and coordinates matched
the live GPS route. The current parked pose is just before that road, so the
panel labels this **nearby map** information and does not claim lane membership.
The dashed green curve is a sampled road reference; lane widths and template
boundaries remain unverified. It is never used as a steering target.
`telemetry/road_geometry.py` verifies the game executable, archive hashes,
loaded version and active mod order; it rejects stale/paused SDK poses,
ambiguous matches and locations outside the local cache. The active Tesla mod
has no map or lane-definition overrides. The cache and extraction evidence
are under `diagnostics/map-cache`; rebuild it after game/map changes. Road
definitions are matched read-only, and no game files or DLLs were changed.
The measured reader startup was 0.76 seconds and median snapshot time 2.47 ms.
Road-template PMD/PMG lane semantics still need a supported decoder before the
map can supply physically accurate lane boundaries.
The original camera, GPS map
and both dashboard layouts are retained. `Run-Tesla-FSD-Passive.bat` opens the
combined scene with driving disabled and paired recording enabled. Use
`python -m tools.render_recorded_scene RECORDING_DIRECTORY --sequence N` to
review the exact recorded camera, model, traffic and map scene offline; the
export marks unavailable observations and never replays controls.
The road-split view now includes verified roads attached to nearby junction
prefabs, even when there is no verified current-road match inside the junction.
Each arm stays separate; the panel does not draw a guessed path across the
unknown interior. Fresh GPS node pairs that agree with cached map coordinates
highlight matching road arms in blue. On the 2,195-frame October 3 recorded
drive, all 302 formerly blank map frames gained junction approach context,
with no change to the original road-match results.
Eight nearby freeway and town prefab types now have decoded PPD v25 AI lane
connections from the installed game assets. All 75 mounted archives were
checked for overrides. World placement validates every prefab attachment,
including height; invalid, stale or unsupported geometry is hidden. Purple
curves show authored traffic paths, with brighter GPS-matched connections.
These are sampled AI lane centres, not decoded painted road boundaries;
the game's exact interpolation remains unverified. The local cache covers
these prefabs and is not a complete map of ATS.
`control/lane_choice_preview.py` reports stable corridors between adjacent
confident model boundaries and forward tracked-vehicle footprint overlaps.
It qualifies road height, preserves straddling overlaps, and marks incomplete
side/rear coverage. It separately exposes authored input-lane indices matching
GPS node connections. It does not identify a model corridor with a map input
lane, recommend a lane, or permit automatic lane changes.
The stable inset retains a driver-seat anchor: its nominal origin is about
0.55 m left and 4.01 m forward of the truck origin. `vision/scene_frame.py`
rebases independent display copies into the native truck frame using SDK
rest positions and an explicitly captured seat baseline. Controller inputs
and original recorded model arrays retain their existing calibration.
`diagnostics/scene-origin.json` pins the truck, model, plugin and settings;
changed rest positions or unsupported pose values reject alignment. Cabin
heading/pitch/roll and truck body pitch/roll are applied to the camera anchor
and copied geometry using the SCS SDK's documented rotation composition.
Native map/traffic coordinates remain world-up with truck heading removed.
Rotated lane polylines are resampled only within their common observed forward
coverage, preserving the model's nonuniform spacing without extrapolation.
The display envelope is limited to 5 degrees of cabin rotation and 15 degrees
of body tilt; these limits do not authorize steering. The panel labels the
result as an SDK pose estimate: final render extrinsics have
not been measured. Missing alignment disables cross-frame traffic overlap
assessment and native overlays on the model perspective.
The town cache adds the exact installed definitions for `2k046`, `2o01g`,
`2k00w`, `2o01h`, `2o083` and `us_12`, alongside the two freeway definitions.
Its signalized intersection uses version-25 semaphore records with the extra
16-byte tail retained as unknown metadata; the preview makes no traffic-light
or permitted-turn claims. All seven prefab instances observed in the manual
test pass attachment validation. Other pitched or incomplete instances still
fail, and their rejection reasons are recorded. Authored raw lane slot numbers
are preserved independently from filtered entry ordinals. Asset rebuilding
verifies installed token bindings and archive precedence before atomic update.
Display-only traffic tracking reprojects the exact observed world positions
into the current truck view, including cached measurements. At least three
distinct observations are required for measured speed labels and relative
motion arrows; repeated cached samples do not become new measurements.
Unavailable/stale/paused samples hide actors immediately. Identity changes,
teleports, clock resets and implausible motion reset the track. The same drive
retained 2,111 fresh traffic samples and supplied measured motion in 1,591
frames. Tracking does not extrapolate positions or establish lane clearance.
`python -m tools.replay_scene_context RECORDING_DIRECTORY --start N --end M`
creates a separate offline derivative with recomputed map/traffic context,
unchanged model observations and copied exact camera frames. It never accesses
the live game or replays controls; the export explicitly labels recomputation.
Evidence: `diagnostics/road-scene-context-replay-20261003-verified/`.
Use `--scene-origin diagnostics/scene-origin.json` only when explicitly
replaying a matching historical camera configuration. Old recordings lack
SDK rest vectors and cabin rotation; the derivative records which values
were seeded from that nominal proof and does not describe them as measured
at the historical frame. Camera images and original model arrays stay intact.
The earlier aligned replay of 2,195 frames includes authored junction paths in 1,134,
stable observed corridors in 2,057, and forward footprint overlap in 935.
GPS-matched authored input-lane indices are available in 859 frames. All
historical frames are explicitly marked as seeded nominal pose estimates;
no driving controls were replayed. Evidence:
`diagnostics/junction-path-aligned-replay-20261003/`.
The latest manual bend/junction replay covers sequences 3301–4021 (721 frames).
Recorded SDK cabin/body pose now permits display alignment in all 721 frames,
recovering all 134 moving-frame rotation dropouts. Expanded town assets provide
authored paths in 713 frames (previously 152) and GPS-matched input-lane indices
in 699 (previously zero). Native traffic remains available in 674 frames, with
measured motion in 434. The preservation audit checks all original model,
telemetry and control fields, 8,247 actor world measurements and 53 exact camera
image hashes. No pose was seeded, no controls were replayed, and no lane
recommendation or clearance was inferred. Evidence:
`diagnostics/manual-junction-fixed-replay-20261003-verified/replay-audit.json`.
These are passive scene improvements; final render extrinsics and painted lane
identity remain unverified. That stage passed 193 regression tests.
The follow-up live trial is preserved in
`diagnostics/town-junction-live-test-20261003/`. Display alignment stayed
available in all 1,239 moving frames, but the driving model was usable in only
589. ATS fatigue notifications obscured the input, including one frame that
still passed the old model-confidence checks. The new auxiliary-camera guard
checks the exact raw frame for the observed anchored notification panel before
inference. A detection skips inference, resets temporal history, cancels pending
or engaged controls, and saves the raw frame with previous model arrays marked
stale. The panel and saved overlays hide that stale geometry. This detector
covers the tested ATS notification layout; absence does not establish a clear
road or detect every possible obstruction. Exact hashed camera fixtures are
included under `tests/fixtures/camera-obstruction/`.
The same trial exposed a GPS rejection when the first stored route node was
ahead of the truck. The reader now validates a bounded approach using SDK pose,
height, heading, local distance scale and remaining-distance consistency while
preserving exact native nodes and IDs. That connector is an estimated display
schematic, never a road or lane center; the driving planner rejects it.
Endpoint and residual diagnostics are retained on rejection, and a large GPS
progress jump invalidates the cached route immediately. A qualified comparison
using a later accepted node array supports 382 of 384 settled poses; it does
not prove that array existed at the historical rejected frame. See
`diagnostics/town-junction-lead-in-candidate-20261003.json`.
The passive route/corridor check compares directed GPS/authored paths with
fresh unobstructed scene-aligned model boundaries over measured 5–30 metre
coverage. It rejects missing, folded, disjoint, stale or ambiguous evidence,
and labels a unique candidate as an estimate. It never recommends a lane,
grants clearance or controls the truck. Nearby junctions explicitly require
manual handling because STOP requirements, signals and right-of-way remain
unverified. The earlier trial produced no supported route/corridor match.
Active steering calibration remains specific to the Pinnacle. The Peterbilt
579 now has a separate nominal display origin in
`diagnostics/scene-origin-579.json`: 30 fresh stationary SDK samples and four
fresh camera-hook records, with the model, plugin and settings identities
checked before and after capture. It aligns display copies using the 579's
own cabin/head rest configuration. The original Pinnacle proof and active
calibration remain unchanged; the 579 proof cannot authorize control or claim
measured final render extrinsics. The live panel selects the matching truck's
display proof, and offline rendering preserves that selection per recorded row.
Capture again while parked with
`python tools/snapshot_scene_origin.py --truck 579 --output diagnostics/scene-origin-579.json`.
The tool refuses paused, stale, moving, mismatched or unstable measurements.
The 579 follow-up passed 237 tests, and the live parked panel confirmed display
alignment with controls off. See `diagnostics/scene-579-live-check-20261003.json`.
The first lock-measurement window contained no head movements, so full-look
stability and moving calibration remain pending.
The subsequent 579 sweep revealed a left-window failure: camera frames show
cabin/grille geometry starting around 112 degrees of left yaw in the reviewed
examples, while right-pan frames remain forward. Some grille frames still
passed model confidence. `diagnostics/579-left-pan-20261003.json` preserves the
paired evidence. Until the native correction is validated, the auxiliary input
guard rejects the 579 above 80 degrees left yaw or with more than 5 cm left head
displacement. Position also catches the left-window branch across yaw wrap.
The runtime rereads head telemetry after capture, skips inference, clears
history, marks old geometry stale and releases pending/engaged controls.
This is a restricted pose envelope, not general grille/traffic recognition.
ForwardCamera 0.2.4 adds a diagnostic-only 60-second render pose trace at at most
10 Hz. It records the actual composition quaternion, SPF/SDK head angles,
interior-outside state, translation and offsets; camera correction is unchanged.
The minute starts only with fresh, unpaused, stationary SDK telemetry and the
parking brake set; menus cannot consume the recording window.
`python tools/prepare_camera_trace.py` previews the hashed diagnostic installation.
`--apply` requires ATS closed, backs up the DLL/settings/manifest, preserves the
historical proof files and explicitly invalidates active camera calibration.
`python tools/analyze_render_pose.py <ForwardCamera.log> --recording <recording-directory>`
compares the recorded angle sources and offset composition using fresh parked
telemetry. All 259 Python checks and native diagnostic/build checks pass; a new trace and
camera correction are still required before full-left stability can be claimed.
The installed diagnostic's first minute missed the manual sweep. A parked SPF
Framework reload rearmed it without restarting ATS. The second trace captured
the sweep: corrected orientation drift stayed below 0.002425 degrees, yet the
held-left raw image still showed the grille while SPF/SDK angles agreed.
This narrows investigation to camera position/visibility; it does not verify
the render origin or authorize control. See
`diagnostics/579-rearmed-render-sweep-audit-20261003.json`. All 129 guarded rows
skipped inference and marked old geometry stale, with no driving commands.
The analyzer retains only the latest SDK timestamp epoch after a reload; the
camera `outside` flag is descriptive and cannot disqualify a centered baseline
because it is also true in the observed forward view.
This follow-up passed 221 regression tests. The restarted passive panel was
checked with the 579 parked: fresh inference and GPS preview were available,
controls remained off, and scene alignment correctly rejected the truck's
unverified calibration. See
`diagnostics/road-scene-guarded-live-check-20261003.json`.
## Analog vJoy setup
Use the official [signed vJoy release](https://github.com/BrunnerInnovation/vJoy/releases) (v2.2.2.0 was checked). Installation requires the Windows administrator prompt and may require a restart. No virtual-controller driver is bundled or installed automatically.
1. In Configure vJoy, enable device 1 with **X, Y, and Z** axes. Close other vJoy feeders so the assistant can acquire it.
2. In ATS Controls, select keyboard plus vJoy, using the steering-wheel control type. Bind **X to steering**, **Y to throttle**, and **Z to brake**, with separate pedal axes in **centered mode**, using center-to-maximum for pedal travel. To move an axis during binding, run `python -m control.bind_vjoy steering` (or `throttle` / `brake`), then return to ATS and select that axis within five seconds. The helper stops after twelve seconds and refuses to operate while ATS is unpaused. Use linear steering (nonlinearity zero), minimal deadzone, and normal steering direction: decreasing X turns left. Pedal center must mean released and maximum must mean fully pressed; use normal (uninverted) centered pedal mode.
3. Verify the ATS input bars before driving: X midpoint centers the wheel, Y/Z midpoint release the pedals. The parked telemetry check passed on this installation on October 3, 2026.
4. Launch with `python main.py --backend vjoy --lane-only --speed 15` for the first lane test. F8/Escape and physical steering/camera keys take over. Manual pedal keys are allowed in lane-only mode.
5. Once direction and lane tracking are verified, use `python main.py --backend vjoy --speed 15` to test cruise and braking.
The desktop steering launcher explicitly uses the validated vJoy device. The direct CLI default `--backend auto` selects vJoy when its matching DLL is installed, otherwise keyboard feedback. An installed but disabled, unconfigured, or busy vJoy device produces an error rather than silently changing backends. `--backend keyboard` explicitly selects the fallback. Dry run and diagnose never acquire a vJoy device or change its axes.
If menu binding is inconvenient, `python -m control.configure_vjoy "PROFILE_DIRECTORY"` previews the bindings using vJoy's exact device identification from `game.log.txt`. Close ATS and add `--apply` to save a timestamped backup and set the three axes, centered pedals, linear steering, and zero deadzones. This uses [SCS's documented input format](https://modding.scssoft.com/wiki/Documentation/Engine/Advanced_input_configuration); verify the resulting input bars when restarting ATS.
vJoy sends a steady wheel position and independent pedal values instead of pulses. Disengagement, focus loss, stale commands, and shutdown center steering and release both pedals. Physical keyboard takeover is supported; physical gamepad/wheel takeover is not yet monitored.
## Validation and diagnostics
Use `Run-Native-Drive.bat` or the **Tesla Semi FSD** desktop shortcut. Both start the native backend.
```powershell
python -m unittest discover -s tests -v
python main.py --diagnose
python main.py --dry-run --no-hud --duration 30
python main.py --speed 15
python main.py --lane-only
python main.py --backend vjoy --lane-only --speed 15
python -m control.verify_vjoy
C:\Python314\python.exe -B tools/run_native_gameplay.py --input auto --cab-only --no-record
```
- Diagnose reports game/provider/telemetry health without injecting controls.
- Dry run checks readiness and logs intended controls and perception measurements without applying them. Manual pedal keys are allowed during passive tests.
- Lane-only mode allows manual throttle/brake; steering/camera controls still take over.
- Speed accepts 5–55 MPH (default 15). Runtime logs go to `diagnostics/session.log`.
- The actuator watchdog releases analog inputs after a 500 ms command stall (keyboard: 250 ms); focus loss releases immediately. Game state is refreshed after inference before applying controls.
- vJoy sends direct analog positions. The keyboard fallback uses pedal pulse modulation and measured steering feedback.
- The vJoy input check requires the driving view, fresh telemetry, a stationary truck, parking brake, and either neutral gear or the engine off. In simple automatic mode, use E to turn the engine off for this check. It sends brief 20% steering/pedal commands, compares ATS's reported user inputs and camera orientation, verifies release after shutdown, and saves `diagnostics/vjoy-input-check.json`. Every exit centers steering and releases pedals. A passing parked input check precedes lane-keeping tests.
The engine must be powered, Drive selected, ATS cruise disabled, and a supported GPS route available before engagement. The map cache prepares the trip in the background and the screen reports readiness and missing connections.
## Current validation
- **F8:** engage or release driving controls.
- **Home / End:** adjust MAX by 5 MPH.
- **Manual steering/braking or Escape:** release controls.
- **Cabin mouse-look:** independent of driving observations.
76 regression tests passed, including capture isolation, calibration recording, live camera health, independent-camera readiness, engagement confidence, comfort cruise, model pins, parked setting changes, passive path/signal previews and read-only GPS route geometry. GPS tests cover same-count route changes, torn snapshots, stale/paused/cancelled routes, SDK mismatch, recovery from a GPS update disagreement, wrong builds, pose/heading matching and left/right bends. The installed telemetry and vJoy device have been verified live. The parked input check measured left/right steering at +/-0.20, independent throttle/brake at 0.20, unchanged camera orientation, and zero controls after shutdown. Centered pedals also removed the previous idle 50% throttle/brake.
User-facing speeds, distances and range use imperial units. MAX follows increases in the truck navigator's posted limit, with a 5 MPH trailer offset or 10 MPH bobtail offset. Home/End can override the target within 5–80 MPH. A lower or unchanged posted limit does not overwrite a manual setting.
The initial October 3 passive inset drive recorded 298 telemetry samples and 50 model-camera
images. Of 52 moving one-second model reports, 50 had usable lane geometry; those
reports had median left/right confidence of 0.96/0.93 and lane widths of 3.60–4.37 m.
The final two low-confidence reports coincided with pulling onto the shoulder,
confirmed by saved images. Brief confidence drops also occurred between reports,
so these counts are not a per-frame pass rate. Head rotation stayed constant
during this drive; moving cabin looks and live projection alignment remain to be
checked in that initial drive. Evidence is in
`diagnostics/manual-inset-calibration/summary.json`. This run used ONNX Runtime
DirectML; the current Python runtime exposes DirectML and CPU providers only.
The verified automatic input transport is vJoy. `--input vjoy`, `--input ets2la` and `--input spf` select explicit transports; the SPF bridge is diagnostic and its acknowledgement alone does not establish that ATS mapped its controls.
The subsequent live calibration saved the actual model output paired with each
input frame. Of 266 moving frames, 253 had usable lanes; all 155 frames during
cabin looks had usable lanes, with median left/right confidence of 0.97/0.96.
Reviewed overlays align with lane paint. Lane z already contains camera-relative
height in the historical decoder; adding another 1.22 m produced an incorrect
review overlay, which was corrected against the original UI source. The reviewed
evidence is `diagnostics/inset-cal-20261003-044742-900055/summary.json`.
The inset is now calibrated only for a limited `--lane-only` test with manual
speed. Active startup checks the model, truck, plugin and settings identity;
missing, stale, or stopped render/translation correction blocks or disengages
control. Speed above 20 MPH also disengages the inset test. The default desktop
launcher now opens the limited steering test. With CPU inference, an active inset road test stayed
engaged for 21.054 seconds at sampled speeds of 9.4–16.9 MPH. It applied only
small steering corrections while the user controlled speed. Manual takeover
released control; fresh parked telemetry then showed zero steering and pedals.
Evidence is `diagnostics/inset-steering-20261003-045631.json`. This validates a
short, mostly straight centered-view test. A later attempt disengaged after
0.214 seconds on a confidence dip before active cabin looks could be checked.
The next run stayed engaged for 25.029 seconds during mouse-look, including
sampled yaw from -80.3 to +59.1 degrees, before releasing on a lane-confidence
drop. Another episode released at the 20 MPH speed limit. Fresh parked SDK
telemetry showed zero steering, throttle and brake after test shutdown. Evidence:
`diagnostics/inset-steering-20261003-050109.json`. These are short supervised
tests; bends, intersections and general lane-change behavior remain unvalidated.
On automatic inset release after successful inference, the runtime saves the exact model input,
matching live outputs, input age and release telemetry under `inset-release-*`
after releasing controls. This diagnostic has now been exercised by multiple live releases.
## Native driving
Saved release images exposed ATS notifications over the road inset: first a fatigue warning, then "Kingman discovered." Fatigue was disabled in the backed-up Ger profile, but that did not remove discovery notifications. Manually pressing F3 hid the widgets for the next test. Keep widgets hidden while using screen capture; clipping out a popup cannot recover the road it covers. Longer-term capture before the game's UI would remove this dependency.
`NativeLaneGraphManager` verifies mounted game/mod assets, keeps a persistent map cache, and expands it in a separate process as the truck and GPS route move. A changed executable or mounted archive invalidates incompatible geometry.
The runtime permits at most 150 ms of marginal lane confidence (both scores at least 0.30), holding the last steering and releasing pedals. Holding frames do not renew the deadline. Geometry faults, lower scores, camera faults and other readiness failures still release immediately. Live evidence caught a 46 ms dip that recovered, followed by release when a fatigue popup drove confidence lower.
The whole-trip planner works backwards from the destination over directed lane connections. It selects lanes needed for later turns and exits, reports unresolved segments, and plans supported truck detours. A prepared maneuver still needs current boundary permissions and observed traffic clearance.
After hiding widgets and adding predictive, ramped comfort braking, the restricted Chill test stayed engaged for 67.287 seconds. The 15-to-8 MPH target change used at most 0.05 brake in one-second control reports, tapering to zero before reaching the target; sampled speed settled around 7 MPH (minimum 6.8). The previous attempt used 0.23 brake and sampled 5.6 MPH before a discovery popup forced release. The new run released when the truck entered neutral. Fresh parked telemetry after shutdown showed zero steering/throttle/brake. Evidence is `diagnostics/inset-cruise-20261003-052254.json` and its matching log. This validates a short straight-road response with a remaining speed error; ordinary inset cruise remains restricted to the bounded test launcher.
Steering follows ordered lane geometry with lane-center feedback, damping, speed-dependent limits, and stronger low-speed authority for tight turns. Speed control combines the selected path, curve anticipation, coverage, traffic following, and signal stops. Braking slows a zero-drag truck when a lower target requires it; releasing throttle alone is insufficient in this game.
Use `--inference-provider cpu` on this installation to avoid GPU contention with
ATS. In a foreground-game benchmark, CPU inference took a median 6.60 ms and a
maximum 7.29 ms; DirectML took a median 2.18 ms but spiked to 501.23 ms while
another DirectML session was also running. The first CPU road test's one-second
control reports showed 6–7 ms inference. Three same-input recurrent steps agreed
between providers within 0.000367 maximum absolute output difference. The model
has not been changed or connected to ROCm. `auto` remains the direct CLI default,
and `--inference-provider directml` explicitly requires DirectML.
Passing uses mounted adjacent-road lane definitions and measured vehicle bodies. When MAX exceeds a slower lead's speed, the planner checks a supported passing lane, signals, follows a road-anchored transition, and returns only after the passed vehicle clears the player's trailer. Shoulders and opposing lanes are excluded. Signalized junction queues do not trigger a pass.
For the corrected inset, F8 preserves model history only if the most recent
inference is less than 250 ms old. Other camera modes and stale history reset
as before. Inset preflight requires ten consecutive usable frames with both
lane confidences at least 0.55; active release retains its 0.35 threshold.
Traffic-light planning associates live lamp states with authored stop curves. Green entry also requires the supported crossing policy and fresh observed traffic gaps. Incomplete observations retain a hold. Vehicle observations do not provide complete detection of random construction cones, yellow X barriers, invisible walls, or temporary closures. Unsupported geometry remains an explicit route gap.
The initial cabin road test disengaged on implausible lane geometry. Its crop did not match the historical MED model projection. A corrected bumper-camera crop passed all 30 sampled frames with about 99% lane confidence and 3.29 m lane width. This crop was checked at 2560x1440; other camera/FOV setups need validation. `--camera cabin` retains the experimental cabin mode. The forward bumper view is the validated default.
Roads and prefab paths use verified source formulas and measured spans. Banked roads support an experimental linear endpoint-roll surface model up to six degrees; truck heading, height and lane-membership checks still apply. The approximation and driving controller remain experimental.
Live validation on October 3, 2026:
## Charging stops
- In the earlier bumper-camera test, steering-only control remained engaged for about 40 seconds through a bend at roughly 20–23 MPH, with measured wheel input following the command.
- Combined lane keeping and cruise remained engaged for about 47 seconds. It accelerated from 1.6 to 14.0 MPH toward a 15 MPH setting, tapering measured throttle from 0.45 to about 0.08 and coasting near the set-speed deadband.
- F8 disengagement returned measured steering/throttle/brake to zero. Camera telemetry stayed centered throughout.
- Both pedals passed the parked 20% input check, including release after feeder shutdown. The moving braking check engaged at 12.3 MPH and reduced the cruise setting from 15 to 8 MPH. It commanded 0.29 brake, slowed to 7.1 MPH by the next one-second log sample, then resumed light throttle after dipping to 6.4 MPH. This verifies braking response; the speed loop still needs tuning for smoother set-speed changes.
- The braking diagnostic exited normally after its timed run. Fresh SDK telemetry then reported zero steering, throttle, and brake inputs, with unchanged centered camera orientation.
- Focus/stalled-command release and stale/paused SDK rejection are covered by regression tests. DirectML frame spikes caused false 250 ms analog timeouts; the analog deadline is now 500 ms, with game state refreshed after inference.
The Tesla Semi battery estimate uses the mod's SDK fuel amount divided by capacity. At **20% or below**, a background planner searches for the nearest reachable mapped charging/fuel service over qualified connected lanes.
Clearly marked roads are required; intersections and lane changes are outside this first milestone. This is a custom Supercombo simulator controller, not the full openpilot stack.
The custom navigation display shows the detour and retains the original trip. Game GPS/job data is preserved. At a supported pump approach, the controller holds the brake while the driver completes the game's refuelling interaction. At **90% or above**, it resumes the original route. A diversion never automatically engages F8. Unsupported station entrances are reported and leave the original route selected.
## Contracts and sources
## Cab displays
Pop Model v2 is installed as an experimental, passive option (`--model pop-v2
--dry-run --path-preview`). Both original split ONNX files are SHA-256 pinned;
the March 24, 2026 catalog entry resolves to commaai/openpilot revision
`62bf6fb072880905a4c490f0f4f4a6b3c23346ec`. It uses 200 ms image pairs and 25
feature samples over 4.8 seconds, with a separate wide camera input. Its unary
trajectory has no plan-selection confidence. This Windows runner uses ONNX
Runtime CPU or DirectML; it is not ROCm.
The two custom Tesla Semi screens show driving status, vehicle and trailer visuals, nearby traffic, the selected path, active navigation, gear, truck indicators, battery estimate and range. The right screen powers off with the truck. Hide the optional desktop panel with `--cab-only`.
The complete 33x15 motion plan is now decoded into position, three-axis
velocity, acceleration, orientation and orientation rate, with the pinned
quadratic time grid. `control/pop_model_actions.py` extracts curvature from
planned yaw and initial yaw rate, and acceleration/stop intent from planned
forward speed and acceleration using the
[pinned upstream action formulas](https://github.com/commaai/openpilot/blob/62bf6fb072880905a4c490f0f4f4a6b3c23346ec/selfdrive/controls/lib/drive_helpers.py).
It retains upstream 0.05-second smoothing steps and 0.3-second longitudinal
smoothing. The default ATS lateral and longitudinal delays are each 0.2 seconds
and are explicitly **unvalidated**. Missing complete modern outputs are marked
unavailable; older recordings cannot supply acceleration or stop intent from
position alone. These actions remain previews and never command pedals.
Native driving does not capture a camera feed. The auxiliary viewport and camera hook are retired. `Disable-Forward-Camera.bat` runs the reversible removal helper with ATS closed, preserving the SPF framework, TruckScreen plugin, telemetry and vJoy.
The current 2560x1440 layout keeps the road inset at left 2016/top 32.
`Install-Pop-Camera-Rectification.bat` installs the native asymmetric SBIG
profile using ForwardCamera 0.2.6, native pitch zero, equal 58.727464-degree
full-frustum FOVs and a bottom-origin subrect at y=0.296484375, height=0.5.
This uses [SCS's documented frustum cropping](https://modding.scssoft.com/wiki/Documentation/Engine/Multi_monitor_configuration)
to target SBIG intrinsics fx=fy=455, cx=256, cy=151.8. The narrow MED input is
derived with nearest-neighbor sampling. The camera XYZ offset and cabin view
are preserved. The earlier MED/top-right and pitched SBIG installers remain
historical profiles and are not interchangeable with the current one.
`native/truck_screen` consumes display-only shared frames. Producers and the installed plugin use matching native V1 protocol names. The bridge validates frame handoffs, retains its last valid frame through short gaps, and shows an offline state when the producer expires. `native/spf_sdk` contains shared framework headers used by the screen and optional input plugins.
The asymmetric installer was applied with backup
`diagnostics/inset-top-right-backup-20261003-125918-777899`. It re-prepares and
checks exact current hashes while ATS and the runtime are closed, uses
transactional backup/rollback, and requests elevation only if ordinary writes
are denied. Preparation alone leaves installed files unchanged. Prior control
and nominal-origin proofs are invalidated. Native FOV/subrect readback was
observed after restart, but final rendered physical pose and control calibration
remain unverified. Inset placement cannot guarantee every game overlay stays
outside the camera.
Build with `native/truck_screen/build.ps1`; install the display package with `Install-Tesla-Screens.bat` while ATS is closed. Addon installation preserves existing game/mod archives.
`Run-Pop-v2-Preview.bat` keeps driving controls off and records both real camera
streams for two minutes after the truck starts moving, at up to 20 saved frames
per second. It waits indefinitely with sparse parked evidence until forward
motion is observed. Actual timestamps
are retained; missing frames are not synthesized. The earlier 67-frame
comparison in `diagnostics/pop-v2-cold-frame-comparison-20261003.json` uses
independent cold inference and a duplicated narrow input. It cannot establish
better road performance or authorize laneless control. The default driving
launcher still selects the original model.
## Runtime reliability and diagnostics
Pop evidence recording now uses a bounded background writer with eight queued
jobs. A full queue drops evidence instead of blocking inference; attempted
sequence gaps and drop ranges are explicit. Shutdown drains accepted jobs and
records final counts, flush state and any writer error in `writer-status.json`
and `writer-events.jsonl`. A recording is complete only when final status
confirms full flush, zero drops and no writer error. Rows now retain the full
modern motion plan, model actions, trajectory assessment and actual context
coverage. Recorded drops are evidence gaps, not interpolated camera frames.
GPS, actor and signal reads run in independent background workers. The control loop consumes completed observations without waiting for slow process-memory reads or reconnects. Original observation times and expiry checks remain; a late result cannot become fresh by completing late. Pauses and GPS destination changes invalidate cached observations immediately.
The October 3 Pop moving preview captured 1,019 moving frames over about 87
seconds at 2.2–24.7 MPH. Of these, 933 passed the basic trajectory geometry
checks; 47 exceeded the lateral bound and 39 had nonmonotonic forward geometry.
These checks do not establish road safety or confidence. The run had a capture
gap and a median cadence near 13 Hz, below the expected 20 Hz. Controls remained
off throughout; the camera/model control calibration remains unvalidated.
See `diagnostics/pop-v2-wide-moving-drive-audit-20261003.json` for paired evidence.
Cab rendering runs on a separate worker. Actuator command publication and release use separate synchronization. A 500 ms command watchdog remains active; manual takeover and confirmed focus/actuator faults release controls. Every new engagement requires a human F8 press.
Auxiliary runtime capture now reads the exact 512x256 inset directly after
checking the ATS client resolution and rectangle, instead of copying the entire
2560x1440 client. Full-client capture remains available for diagnostic callers.
Pixel equality, window offsets, changed resolution, and unavailable camera
rejection are tested. A ten-frame parked profile of the installed asymmetric
view measured median capture 15.55 ms and inference 20.73 ms in
`diagnostics/pop-v2-rectified-preview-performance-20261003.json`. It excludes
actual display/event-pump and disk writer costs, and does not establish moving
performance or upstream 20 Hz cadence.
The passive Pop panel redraws at 5 Hz while its input events are handled with
nonblocking `pollKey` every loop and model capture targets 20 Hz. Actual inference timestamps and context
coverage remain authoritative; the panel's loop FPS is not a cadence proof.
`diagnostics/native-control.jsonl` records engagements, releases, source ages, reader durations, selected lanes, trip gaps, traffic, charging status, and control/render timings. `diagnostics/native-lanes/trips` contains trip reports. `--no-record` disables image recording but retains compact control logs.
Pop path preview now uses `control/pop_trajectory.py` rather than the unfiltered
trajectory steering calculation. It assesses only the ascending near-path
prefix covering the steering horizon, checks predicted path and road-edge
uncertainty, requires actual complete temporal context and distinct fresh
frames, and warms stable observations before producing capped, rate-limited
steering. Painted lane probabilities are not an admission requirement. Missing
or uncertain evidence resets tracking; no previous command is held through it.
The current preview implementation uses the modern yaw-derived model action
for curvature after these admission checks. Geometric point-tracking remains available for
explicit historical replay. Curve-speed advice and desired acceleration/stop
intent are advisory only and do not command the pedals.
```powershell
C:\Python314\python.exe -B -m unittest discover -s tests
C:\Python314\python.exe -B tools/check_native_trip.py
```
The existing Pop preview launcher records paired decisions and the full motion
plan. The dashboard displays readiness, steering, acceleration/stop previews
and path uncertainty. Every controller decision explicitly keeps
`control_eligible=false` and `controls_applied=false`; active Pop invocation
continues to be rejected before model/controller acquisition.
`Run-Pop-v2-Steering-Trial.bat` is a separate supervised simulator experiment:
three distinct fresh parked-neutral snapshots arm the launcher, then one user
F8 press can request at most 15 seconds of steering at 24–28 MPH (target
25–27 MPH) with manual pedals. An unready F8 press shows its refusal reason
and leaves the panel in standby without acquiring controls or consuming the
single admitted attempt; a later attempt requires another human F8 press.
Standby expires after five minutes. It uses the pinned asymmetric 579
camera. Read-only vJoy capability queries are warmed before model history
starts; the retained DLL is revalidated and acquired only after a ready human
F8 press. It uses real paired temporal coverage, modern yaw actions and the
existing uncertainty/road-envelope checks. Edge uncertainty must be at most
1.5m to engage; only this active experiment allows a continuation band up to
1.75m, while every frame still passes the unchanged uncertainty-adjusted
corridor and other quality checks. The descriptive local steering gain is
0.1254; requests outside normalized steering [-0.05, +0.03] (right/left)
are rejected, and output changes are limited
to 0.1 axis units/s. F8, Escape, manual steering, focus loss or any failed active
guard ends the attempt and releases vJoy ownership. Records distinguish queued
commands, successful worker writes and independent SDK observations;
`trial-status.json` records final release even when the last image row was
active. After release, the panel stays open with the stop reason and an explicit
frozen-snapshot label; controls and recording are already closed. Escape or the
window's X closes it. This launcher does not grant physical camera calibration, validated
model delays, production eligibility, pedal control or junction competence.
`python tools/run_pop_steering_trial.py --diagnose --no-hud` checks assets and
parked startup without acquiring controls or creating a keyboard hook.
Historical geometric replay of the captured drive accepted only 76/1,019 moving
frames, with a longest accepted interval of 1.53 seconds. Most denials were predicted path or
road-edge uncertainty. This is insufficient for sustained driving; thresholds
have not been relaxed to make the recording pass. The replay preserves actual
timestamps/context, reports missing historical velocity as unavailable, and
does not reconstruct missing modern actions or simulate steering feedback.
These counts do not validate the newly installed asymmetric camera or modern
yaw-action strategy. Delay assumptions, final camera pose, moving live cadence
and closed-loop vehicle response remain unvalidated. Report:
`diagnostics/pop-v2-trajectory-controller-replay-20261003.json`. Reproduce with
`python tools/replay_pop_trajectory.py diagnostics/inset-cal-20261003-123419-822490`.
After the asymmetric camera installation, the completed manual drive in
`diagnostics/inset-cal-20261003-130507-234700` produced 2,091 moving observations
over 120 seconds. The modern yaw-action preview accepted 1,299/1,948 observations
within its supported speed range (66.7%); 143 exceeded the 30 MPH preview limit.
Its longest uninterrupted accepted preview lasted 44.4 seconds. Median actual
inference cadence was 17.3 Hz, with complete context on 95.3% of moving rows.
All 2,095 evidence rows flushed with zero writer drops/errors; 1,880 rows include
camera image pairs at the configured maximum save frequency. Controls stayed
off. Camera, controller strategy and route conditions differ from the earlier
drive, so this is not a controlled comparison or physical calibration proof.
See `diagnostics/pop-v2-rectified-live-audit-20261003.json`.
The subsequent bounded, panel-free timing run recorded 403 moving observations
at median 19.89 Hz with zero writer drops/errors. This isolates a feasible
model-loop budget, not sustained panel-inclusive cadence or control validation;
the nonblocking panel event change still needs live timing verification.
See `diagnostics/pop-v2-rectified-no-hud-timing-audit-20261003.json`.
A subsequent short parked run with the nonblocking panel recorded 160 frames
at median 19.83 Hz. Three intervals exceeded 150 ms (maximum 512 ms), so this
does not establish sustained moving cadence. Final evidence flushed without
writer drops/errors. See `diagnostics/pop-v2-panel-poll-parked-audit-20261003.json`.
`tools/measure_stationary_steering_response.py` performs only small parked
steering steps with neutral between them. It requires distinct fresh SDK
samples, neutral gear, the parking brake, foreground ATS and released manual
inputs before acquiring vJoy; guard failures release and close the device.
The October 3 run reached 90% of the +/-0.1 SDK steering targets within observed
41-61 ms brackets and verified neutral after shutdown. This includes feeder,
game and SDK observation latency; it is not a moving yaw-delay measurement.
See `diagnostics/stationary-steering-response-20261003.json`.
Older 579 highway recordings independently suggest local left-positive
curvature approximately equals 0.1254 times normalized SDK steering, over the
observed small steering/speed range. These estimates do not grant camera or
full-range steering calibration. New active command records timestamp command
enqueue separately from loop start; neither timestamp is a driver acknowledgment.
See `diagnostics/579-steering-response-existing-evidence-20261003.json`.
The model hash and tensor layout are pinned in `models/manifest.json`. Its original training/export version is unrecorded. The matching historical 6409 decoder includes five trajectory hypotheses, odd-index lane probabilities, five lead hypotheses, separate lead probabilities, and 512 recurrent-state floats. Plan selection weights are not treated as road-view confidence.
Telemetry opens an existing `Local\\SCSTelemetry` mapping and requires revision 12 / ATS, active SDK, unpaused state, and changing timestamps. Missing telemetry blocks engagement. Speed, gear, steering, pedals, engine/parking state, and head orientation use the versioned layout.
- [RenCloud v1.12.1 layout](https://github.com/RenCloud/scs-sdk-plugin/blob/V.1.12.1/scs-telemetry/inc/scs-telemetry-common.hpp)
- [Historical output decoder](https://github.com/commaai/openpilot/blob/v0.8.5/selfdrive/modeld/models/driving.cc)
- [Lane coordinate convention](https://github.com/commaai/openpilot/blob/v0.8.5/selfdrive/controls/lib/lane_planner.py)
- [YUV packing](https://github.com/commaai/openpilot/blob/v0.8.5/selfdrive/modeld/transforms/loadyuv.cl)
- [Historical MED projection and camera height](https://github.com/commaai/openpilot/blob/v0.8.5/common/transformations/model.py)
- [Runtime use of the MED ground transform](https://github.com/commaai/openpilot/blob/v0.8.5/selfdrive/modeld/modeld.cc)
- [Windows input contract](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendinput)
## Files
The October 3 Tesla Semi shoulder departure is addressed by
`control/gameplay_road_tracking.py`. It confirms an ego-containing observed
lane over three frames, compares its identity using SDK vehicle motion, and
tracks its near center with a 12–25 m lookahead. Validated GPS/signal maneuver
paths retain precedence. Paint gaps propagate the observed corridor for up
to one second. A further bounded recovery is allowed only when fresh matching
GPS and current model geometry agree with the motion-projected acquired lane,
the truck stays near its center, and observed lane coverage remains. It expires
after two seconds, inhibits acceleration, and gently reduces the speed target.
Longer or contradictory loss brakes and fades steering toward neutral instead
of following an uncertain off-road forecast. Model-only laneless following
remains available before a lane is acquired. A large uncertain local forecast
also requests braking. F8 and manual takeover still release all controls.
Tesla Semi gameplay uses descriptive steering gain 0.1535, estimated from
195 moving SDK samples in `diagnostics/tesla-steering-response-20261003.json`;
the 579 retains 0.1254. Neither is physical calibration. Reproduce the saved
failure-frame decision comparison with `python tools/replay_gameplay_road_tracking.py
diagnostics/pop-gameplay-20261003-165000-855391 --output diagnostics/wmi-road-tracking-replay-20261003.json`.
This replay preserves the original truck trajectory and images, so it does
not prove the outcome of a changed closed-loop drive. Independent kinematic
tests cover delayed steering on a curve, short marking gaps, lane identity
jumps, validated lane changes, and braking after a prolonged road loss.
`tools/build_tesla_screen_addon.py` prepares a separate companion `.scs`
for the installed Tesla Semi mod. The left screen keeps native imperial truck
instruments (speed, gear, limit, ATS cruise, clock, signals and parking brake)
above an independent live app tile showing Autopilot state/release reason,
MAX, pedals, following distance, trailer state, lights and SDK warning flags.
The right 1024×512 screen has a legible road/traffic scene beside an active GPS
route map, next verified route bend, remaining miles and ATS-clock arrival time.
The ego tractor uses a Tesla Semi cab-over mesh, with actual trailer attachment
and articulation retained. Camera input remains hidden unless requested in the
desktop panel. `ui/dashboard_stream.py` publishes both display-only BGRA streams.
The Tesla mod reflects the right surface vertically; both placeholder and
live uploads reverse their image rows so the cabin display reads upright.
Missing or failed display publishing cannot interrupt gameplay controls.
The native texture consumer and add-on must be installed and enabled before
the screens can show live app data. Original mod files are preserved. The
earlier right display was observed upright on 2026-10-03. On 2026-10-04 the
corrected dual-stream build reached a powered, parked cabin without repeating
the entry crash; the right road/map panel was visibly upright and native logs
reported two marked textures with fresh left/right frames. The left physical
screen originally sampled separate UV regions. A source-pinned companion mesh
override remaps only those display vertices to one continuous native dashboard;
the powered cabin then showed the new speed/gear layout and removed the baked
truck artwork. The status-image cursor/tint/layer fix was then observed in the
powered cabin: native speed/gear/clock/cruise fields and the live Autopilot
status/indicators/warnings tile are upright and visible across the full left
surface, alongside the upright right panel. No repeat entry crash was observed.
Moving display stability remains unverified; see
`diagnostics/ats-crash-20261004-220212/verification.json` and its cabin screenshot.
The gear instrument uses native transmission mode (ID 1380): D/N/R/M, rather
than the gear-number field that emits A5 and similar automatic gear labels.
The native bridge retains its last valid texture through short producer gaps,
handles both UNORM/sRGB views and uses cached replacements during contention.
After two seconds without valid frames the right view dims and says DISPLAY
OFFLINE, while the left app tile returns to APP OFFLINE with native instruments
still updating. Fresh producer frames restore both streams independently.
With ATS closed, `Install-Tesla-Screens.bat` installs the companion and the
enabled display prototype (both its own flag and SPF's TruckScreen flag).
Activate "ATS OP Tesla screens" above the original
Tesla Semi in Mod Manager. The native `TruckScreen` log must show marked
textures, fresh HUD frames, and replacement binds before live integration can
be claimed. This display prototype requires a normal game restart for updates;
see `native/truck_screen/README.md` for supported texture scope and rollback.
`ui/map_background.py` expands only display road references from mounted game
archives on a bounded background worker (36 sectors by default). The blue GPS
route comes from the native route graph, not a fabricated ego connector; map
references are not control lanes. Heading-up and overview displays share
smoothed visual pose/zoom, while control uses original telemetry. R in the
desktop panel toggles route overview. Unknown street names, exit numbers and
destinations are not invented. `tools/preview_cab_screens.py` renders a labeled
offline preview from a saved drive; `tools/expand_display_map.py` prepares the
display cache without changing installed game files or steering map caches.
When the stable native route array agrees with the SDK trip but the truck's
approach to its first node cannot be qualified, the map shows only the actual
route nodes with a connection-unverified label. It adds no approach connector
or turn instruction, and GPS control still receives an unavailable route.
That display-only geometry expires on stale telemetry or a destination change.
Gameplay speed holding now brakes gently for small overspeed when ATS coast
drag is absent, releases early using measured deceleration, and uses separate
braking-entry/release thresholds to reduce pedal cycling. SDK-observed native
ATS cruise produces an explicit conflict instead of trying a guessed cancel
key. Lead emergency braking remains independent of confidence recovery.
Native live signal phases and authored stop points are now decoded and joined
to selected prefab paths. Restrictive stopping has a separate native planner;
green alone does not establish intersection priority or authorize entry.
The active development goal is an ATS-native navigation planner. The separate
native launcher operates without openpilot or Pop/WMI inference. The earlier
model launcher and assets remain available for development rollback while the
native backend is validated on representative roads.
The implementation order is:
1. Repair the recorded trailer-chain traffic failure, exhausted-lane tracking,
and stopped-queue GPS short-horizon disengagement; replay the saved failures
before another ordinary drive.
2. Separate shared geometry types from model inference. Build a timestamped
driving scene and connected lane graph from mounted road definitions and
prefab navigation curves, with actual lane placement, drivable boundaries,
directed connectivity, vehicle pose and attached-trailer geometry. GPS road
references and display-only curves must not be substituted for lane centers.
3. Give that planner smooth traffic following, stopped-queue holding/restart,
curve and route speed targets, and an adjustable maximum in imperial units.
4. Plan turn-signal lane changes, GPS exits and intersection turns using the
connected lanes and observed clearance. Live light phases and authored stop
points are joined by exact prefab/curve identity; complete stop-line spans,
protected phase arbitration and unsignalized right-of-way remain unfinished.
5. Render the same selected lane, route, maneuver, target speed and stop reason
on both Tesla Semi screens. Retire inference from the driving runtime once
the native planner has demonstrated replacement coverage.
Completion requires representative mixed-road driving with lane holding,
smooth traffic stops/restarts, correct GPS maneuvers and traffic-rule stops,
stable screens, and explicit handling of genuinely missing data. Passing unit
tests, a model change or a short straight drive alone is not completion. Keep
archived model assets available for rollback; they are not required inputs to
the target native planner.
`main.py` orchestrates readiness, F8, takeover, perception, controls, HUD, and logs. `runtime_checks.py` contains readiness checks. `control/windows_input.py` owns correctly sized Win32 input, ATS discovery, and the takeover hook. `control/fsd_controller.py` tracks paths and modulates keyboard controls with feedback and a watchdog. `telemetry/ats_telemetry.py` reads the versioned plugin mapping. `vision/screen_capture.py` captures the ATS client area and packs two-frame YUV. `model/openpilot_brain.py` executes and decodes the pinned model. `ui/tesla_fsd_hud.py` shows real telemetry and health.
## ATS-native experimental driving backend
`Run-Native-Drive.bat` starts `tools/run_native_gameplay.py` without loading
openpilot, ONNX, Pop/WMI inference, camera tensors, or temporal model history.
F8 still owns engagement and release; Home/End adjusts MAX in MPH. Controls
follow the selected directed native GPS lane, measure actor/trailer contact
along that same path, and use SDK speed for smooth following and queue restart.
The screens and evidence recorder receive the actual commanded trajectory.
Native evidence explicitly has no camera or inference outputs.
Use `--cab-only` to keep both live cabin displays without rendering a separate
desktop window. The default launcher retains the optional desktop panel.
The local mounted-map cache covers nine sectors: 2,549 road-lane candidates,
2,061 prefab paths, and 4,739 directed connections. Full quaternion placement
now resolves graded prefabs. Independently measured spans qualify only their
observed intervals. The native launcher additionally opts into complete PPD
curves derived from the published SCS stored-length cubic and verified asset
placement, plus 2,483 ordinary road primitives from a pinned reverse-engineered
stored-length/full-quaternion formula and measured cross-sections. These are
experimental source qualifications, not empirical tests of every curve.
Fifty-eight banked lanes and eight profile transitions remain excluded, and
the speed planner stops before qualified coverage ends. Ordered arc-distance
trajectories retain sharp turns without sorting or extrapolating a path.
The native graph is now a persistent cache rather than a one-shot artifact.
`NativeLaneGraphManager` keeps the last verified graph, watches the current
pose and the live GPS route, and launches the bounded extractor in a separate
process before the route reaches an uncached sector. Completed sectors are
deduplicated by stable lane identity and atomically merged; a changed ATS or
mod archive starts a new graph instead of mixing incompatible geometry. The
control loop never waits for extraction and never engages without current
route coverage, so a rebuild no longer requires restarting ATS or manually
replacing the graph.
Setting or changing the ATS GPS route now starts a background **whole-trip
lane plan** in `control/native_trip_planner.py`. The cache manager preloads
every route sector, including intermediate sectors on long GPS edges. The
planner works backwards from the destination over actual lane connections,
so an earlier fork uses the lane needed by a later exit. It records required
road lane changes and looks for connected truck-compatible detours around
unsupported GPS segments. Off-route detours require positive player-truck
access metadata; NPC geometry alone cannot authorize a shortcut through a
yellow X barrier or inaccessible scenery. Live lane changes still require exact mounted
boundary permission and fresh vehicle/trailer clearance; a planned maneuver
does not authorize a lateral jump. Route preparation takes priority over
passing and does not depend on finding a slower lead vehicle.
Plans are bound to the GPS revision and verified mounted graph. GPS changes
invalidate old policies; compatible cache extensions keep serving the previous
policy while a worker refreshes it. Full reports are saved under
`diagnostics/native-lanes/trips/`, and the right navigation screen shows loading
or upcoming gaps and displays generated truck detours. Missing geometry,
unconnected lanes and truck-restricted paths remain explicit gaps, rather than
being labelled a complete route. This is a trip lane plan, not a promise that
traffic, signals or temporary roadwork will be clear when the truck arrives.
SCS prefab allowed-vehicle flags describe NPC preferences, rather than player
access restrictions. A source-qualified small-vehicle variant can be used as
a fallback only for the exact node pair requested by the live game GPS, while
truck-preferred variants retain a routing advantage. Explicit mounted player
access switches override this fallback. Legacy zero access masks are unknown;
the access decoder does not claim complete coverage of invisible collision
walls or dynamic closures. See the [SCS prefab locator documentation](https://modding.scssoft.com/wiki/Documentation/Tools/SCS_Blender_Tools/Locators/Prefab_Locators)
and `telemetry/native_player_access.py` for the separate contracts.
`python -B tools/check_native_trip.py` reads the live trip without actuation;
`--route <saved JSON>` checks an offline route or SDK capture.
`control/native_signal_planner.py` joins authored cross-line start points to the
first actual governing semaphore by exact prefab/curve identity. The native
controller can restrict speed and hold the brake for that point. Experimental
green entry requires supported absolute authored priority, fresh measured
traffic motion, complete observed traversal and coverage through the prefab
exit. This is a permissive observed-gap policy, not protected-phase proof or
exhaustive clearance; permissions expire after 0.2 seconds and cap entry speed
at 8 m/s (about 18 MPH). Unknowns and conflicts retain a hold. Unsignalized
priority and native turn-signal lane changes remain unfinished. Retain model
assets for rollback until representative mixed-road drives pass.
The right-screen traffic scene draws the actual selected solid blue driving
path. The separate dashed GPS chord and its debug legend are removed; active
navigation stays on the map. Dashboard addon 0.2.2 suppresses six duplicate ATS
symbol quads where custom indications are mapped, preserving unmapped native
warning/service/differential-lock indicators and the native speed/gear display.
The native runner now watches the Tesla Semi's battery estimate (the mod's
SDK fuel amount divided by capacity). At **20% or below**, it plans a detour
to the nearest reachable mapped fuel service. Exact mounted PPD gas spawn
points identify service locations; directed, qualified lanes and existing
lane-change permissions determine reachability. Station search and asset
decoding run on a background worker. A charging detour never acquires F8 or
grants traffic clearance, and blocked/unqualified paths remain excluded.
The custom screen shows the charging route and retains the ATS GPS/job
destination. The game GPS itself is not rewritten. The controller approaches
the supported pump path, holds the brake, and leaves the game's refuelling
interaction to the driver. At **90% or above**, it restores the original route;
the detour stays active throughout charging below that target. Distances
to the stop are estimates from the map's local scale. If no supported
connection reaches a station, the panel reports that limitation and leaves
the existing route intact. Some station approaches still need native map
connection coverage before automatic detours work there.
Banked ordinary roads use an experimental linear endpoint-roll surface model
up to six degrees. This rotates the measured lane offset in height as well as
laterally, reconstructs source coordinates before qualification, and checks
connections again. The original unmodelled geometry retains its three-degree
bound. Truck heading, height and lane-membership gates are unchanged; this
surface approximation still requires live driving validation.
The regression suite covers native routing, geometry, traffic, signals, speed, input ownership, displays and asynchronous observations. Simulator behavior still needs live validation; passing tests does not establish complete route coverage or collision avoidance.
-12
View File
@@ -1,12 +0,0 @@
@echo off
title ATS - Continuous Pop v2 Gameplay
cd /d "%~dp0"
echo Continuous experimental gameplay with live model panel.
echo Warm up the camera, then F8 toggles driving. Home/End adjust speed by 5 MPH.
echo Your speed target is saved. First launch defaults to 35 MPH. Range: 5-80 MPH.
echo Manual steering or braking releases. Camera looks remain available.
echo Disengagement returns to live passive view. F8 can engage again when ready.
echo Escape releases controls and keeps the panel open. Close the panel or press Q in it to exit.
echo Keep ATS foreground while engaged.
python tools\run_pop_gameplay.py
pause
-9
View File
@@ -1,9 +0,0 @@
@echo off
title ATS - Pop v2 Preview
cd /d "%~dp0"
echo Pop v2 trajectory preview. Manual driving; F8 cannot apply controls.
echo Steering assessment uses the local path, uncertainty, and estimated road edges.
echo Use the Pop wide-camera profile for distinct wide and narrow inputs.
echo Waits for forward motion, then records two minutes at the available capture rate.
python main.py --camera auxiliary --model pop-v2 --dry-run --path-preview --record-calibration --record-image-hz 20 --navigation-preview --inference-provider cpu --speed 25 --duration 120 --duration-after-motion
pause
-12
View File
@@ -1,12 +0,0 @@
@echo off
title ATS - Experimental Pop Steering Trial
cd /d "%~dp0"
echo Experimental one-shot 15-second steering test. MANUAL PEDALS.
echo Start parked in neutral with parking brake on and inputs released.
echo After the panel is ready, drive centered at 25-27 MPH, then press F8 once.
echo The permitted speed band is 24-28 MPH; leaving it releases steering.
echo F8 again, Escape, manual steering, focus loss or failed model guard ends the test.
echo No automatic engagement, throttle or brake control. Five-minute standby maximum.
echo A blocked F8 leaves standby running; wait for ready, then press F8 again.
python tools\run_pop_steering_trial.py
pause
-7
View File
@@ -1,7 +0,0 @@
@echo off
cd /d "%~dp0"
echo Supervised inset Chill cruise test: 15 MPH target, 2 minute limit.
echo Keep ATS widgets hidden with F3 and use a marked lane.
echo Release manual pedals before F8. F8 again or driving keys take over.
python main.py --camera auxiliary --backend vjoy --inference-provider cpu --inset-cruise-test --driving-mode chill --speed 15 --duration 120
pause
-7
View File
@@ -1,7 +0,0 @@
@echo off
cd /d "%~dp0"
echo Passive model-path and turn-signal evaluation. You control the truck.
echo Keep ATS widgets hidden with F3 so popups cannot cover the road inset.
echo Model-intent previews do not steer or press pedals.
python main.py --camera auxiliary --dry-run --record-calibration --inference-provider cpu --path-preview --signal-preview --signal-delay 1 --driving-mode manual
pause
-9
View File
@@ -1,9 +0,0 @@
@echo off
cd /d "%~dp0"
echo GPS-assisted simulator driving trial: 12 MPH Chill cruise, 2 minute limit.
echo Keep ATS widgets hidden with F3. Start centered in a marked lane.
echo Select Drive, release the parking brake and pedals, then press F8 once.
echo F8 again or physical steering/pedal keys take over.
echo GPS guides camera-supported steering; complex intersections still need manual driving.
python main.py --camera auxiliary --backend vjoy --inference-provider cpu --navigation-driving-test --driving-mode chill --speed 12 --duration 120
pause
-7
View File
@@ -1,7 +0,0 @@
@echo off
cd /d "%~dp0"
echo Live ATS GPS route and road model preview. You control the truck.
echo Keep ATS widgets hidden with F3 and leave F8 off.
echo The original dashboard shows the road camera, model and route map.
python main.py --camera auxiliary --dry-run --record-calibration --inference-provider cpu --navigation-preview --driving-mode manual
pause
-6
View File
@@ -1,6 +0,0 @@
@echo off
title Tesla Semi FSD - Passive Model View
cd /d "%~dp0"
echo Passive road, nearby traffic, model camera and GPS view. F8 driving is disabled.
python main.py --camera auxiliary --dry-run --record-calibration --navigation-preview --inference-provider cpu --driving-mode manual --speed 12
pause
+1 -6
View File
@@ -1,9 +1,4 @@
@echo off
title Tesla Semi FSD - Native ATS Autopilot
cd /d "%~dp0"
echo Starting ATS-native GPS/lane/traffic autopilot with the Tesla Semi screens...
echo Openpilot and camera inference are not used for control in this launcher.
echo F8 engages/releases; Home/End adjusts the MAX speed in MPH.
echo Input auto prefers the ETS2LA semantic controller and falls back to vJoy.
python tools\run_native_gameplay.py --input auto %*
"C:\Python314\python.exe" -B tools\run_native_gameplay.py --input auto %*
pause
-8
View File
@@ -1,8 +0,0 @@
@echo off
title ATS - WMI Driving
cd /d "%~dp0"
echo WMI 0.11 driving model. F8 toggles driving after the camera warms up.
echo Home/End adjust MAX by 5 MPH. Higher navigation limits can raise MAX.
echo Escape releases controls. Panel V toggles the camera; panel Q exits.
python tools\run_pop_gameplay.py --model wmi-v0.11.0
pause
+1 -1
View File
@@ -26,7 +26,7 @@ class FSDController:
raise ValueError('Steering authority must be within 0.35..1.0')
self.max_steer_norm = float(max_steer_norm)
# DirectML/ATS capture can share the renderer's GPU. Bound an analog
# position's lifetime to 500 ms; the continuous WMI runner may opt into
# position's lifetime to 500 ms; the continuous native runner may opt into
# its own bounded host-spike profile. Focus loss still releases at once.
self.command_timeout = 0.5 if mode in ("vjoy", "ets2la", "spf") else 0.25
if not math.isfinite(focus_confirm_s) or not 0. <= focus_confirm_s <= .15:
-307
View File
@@ -1,307 +0,0 @@
"""Signal-requested observed-corridor changes for experimental ATS gameplay.
No actuator access. Model coordinates are forward/right/down; native actors
are forward/left. Empty loaded-actor reports are not a coverage guarantee.
Travel identity requires map-count support or a measured same-direction actor,
and target truck-footprint clearance inside the estimated physical road edge.
"""
import math
import numbers
import time
import numpy as np
def _finite(value):
if isinstance(value, bool) or not isinstance(value, numbers.Real) or not math.isfinite(value):
raise ValueError('Finite numeric measurement required')
return float(value)
class GameplayLaneChange:
SIGNAL_DELAY_S = .5
MAX_MANEUVER_S = 8.
MAX_AGE_S = .3
def __init__(self):
self.reset()
def reset(self):
self.direction = 'none'
self.state = 'idle'
self.started = self.active_since = self.last_now = self.last_stamp = None
self.used = False
self.target = self.previous = None
self.centered_since = None
self.centered_frames = 0
self.cancel_reason = ''
def cancel(self,reason):
"""Caller rejects this admitted path (for example GPS disagreement)."""
self.state='cancelled'
self.used=True
self.cancel_reason=str(reason) or 'Lane change cancelled'
return self._report(self.cancel_reason)
def _report(self, reason='', allowed=False, **extra):
report=dict(state=self.state, status=reason or self.state, direction=self.direction,
active=self.state == 'changing' and allowed, blocked=bool(reason),
allowed_for_gameplay=allowed, reason=reason, path_override=None,
desiredpulse='none', completed_corridor=None,
require_manual=self.state=='cancelled',
source='observed four camera boundaries + measured native actors',
experimental=True, production_eligible=False, control_eligible=False,
controls_applied=False, physical_calibration_validated=False,
clearance_verified=False, lane_identity_verified=False)
report.update(extra)
return report
@staticmethod
def _geometry(perception, data, now):
if (data.get('valid') is not True or data.get('paused') is not False
or data.get('model_inferred_this_frame') is not True
or data.get('model_obstructed') is not False or data.get('model_geometry_stale') is not False):
raise ValueError('Fresh unobstructed camera and SDK required')
stamp = _finite(data.get('model_input_monotonic'))
if not 0 <= _finite(data.get('model_age_s')) <= .3 or not -.02 <= now-stamp <= .3:
raise ValueError('Lane-change camera frame stale')
if not 0 <= _finite(data.get('age')) <= .3:
raise ValueError('Lane-change SDK stale')
speed = _finite(data.get('speed_mps'))
if speed < 1 or data.get('park_brake') is not False or data.get('gear', 0) <= 0:
raise ValueError('Moving forward gear required for lane change')
lanes = perception.lanes
x, ys, zs, ps = (np.asarray(getattr(lanes, k), float)
for k in ('x', 'all_y', 'all_z', 'probabilities'))
if (x.shape != (33,) or ys.shape != (4,33) or zs.shape != (4,33) or ps.shape != (4,)
or not all(np.isfinite(a).all() for a in (x,ys,zs,ps))
or np.any(np.diff(x)<=0) or x[0] > 0 or x[-1] < 25
or np.any((ps<0)|(ps>1))):
raise ValueError('Four finite ordered camera boundaries required')
position, rotation = (np.asarray(data.get(k),float) for k in ('world_position','world_rotation'))
if any(a.shape != (3,) or not np.isfinite(a).all() for a in (position,rotation)):
raise ValueError('Finite SDK pose required for corridor continuity')
return x,ys,zs,ps,speed,stamp,position,float(rotation[0])*2*math.pi
@staticmethod
def _corridor(x,ys,zs,ps,key,horizon):
a,b=key
grid=np.unique(np.r_[0.,x[(x>0)&(x<horizon)],horizon])
if len(grid)>33:grid=np.linspace(0.,horizon,33)
low,high=np.interp(grid,x,ys[a]),np.interp(grid,x,ys[b])
width=high-low
if min(ps[a],ps[b]) < .6 or np.any(width<2.6) or np.any(width>4.8) or np.ptp(width)>1.2:
raise ValueError('Adjacent travel corridor markings or width ambiguous')
return dict(key=tuple(key),grid=grid,low=low,high=high,center=(low+high)*.5,
z=(np.interp(grid,x,zs[a])+np.interp(grid,x,zs[b]))*.5)
@staticmethod
def _edge(perception,corridor,x):
grid=corridor['grid']
ex=np.asarray(getattr(perception,'road_edge_x',x),float)
edges=np.asarray(perception.road_edges,float)
std=np.asarray(perception.road_edge_std,float)
if (ex.shape!=(33,) or edges.shape!=(2,33,2) or std.shape!=edges.shape
or not all(np.isfinite(a).all() for a in (ex,edges,std))
or np.any(np.diff(ex)<=0) or np.any(std<0) or ex[0]>grid[0] or ex[-1]<grid[-1]):
raise ValueError('Physical road-edge evidence unavailable')
low,high=(np.interp(grid,ex,edges[i,:,0]) for i in (0,1))
uncertainty=np.maximum(np.interp(grid,ex,std[0,:,0]),np.interp(grid,ex,std[1,:,0]))
margin=np.minimum(corridor['center']-low,high-corridor['center'])-uncertainty
if np.any(high<=low) or uncertainty.max()>.75 or margin.min()<1.5:
raise ValueError('Shoulder or road-edge corridor ambiguous')
return float(margin.min())
@staticmethod
def _traffic(data,now,corridor,speed):
report=data.get('nearby_traffic')
if not isinstance(report,dict) or report.get('available') is not True:
raise ValueError('Fresh all-around native traffic required')
age=max(_finite(report.get('age_s')),now-_finite(report.get('sampled_at')))
if not 0 <= age <= .3 or report.get('latest_read_failed') is True:
raise ValueError('Native traffic verification stale or failed')
if (report.get('trailer_chain_traversal_complete') is False
or report.get('truncated_trailer_chains')):
raise ValueError('Native trailer traversal incomplete; adjacent clearance unknown')
actors=report.get('actors')
if not isinstance(actors,list) or len(actors)>500:
raise ValueError('Native actor list invalid')
direction_evidence=False
assessments=[]
for actor in actors:
f,left,length,width,heading=(_finite(actor.get(k)) for k in
('forward_m','left_m','length_m','width_m','heading_delta_rad'))
if not .2<=length<=60 or not .2<=width<=8:
raise ValueError('Native actor footprint invalid')
c,s=abs(math.cos(heading)),abs(math.sin(heading))
half_f=c*length/2+s*width/2
half_y=s*length/2+c*width/2
y=-left
probe=max(0.,min(float(corridor['grid'][-1]),f))
low=np.interp(probe,corridor['grid'],corridor['low'])
high=np.interp(probe,corridor['grid'],corridor['high'])
rel_f=actor.get('relative_forward_mps')
rel_y=actor.get('relative_left_mps')
moving=actor.get('motion_available') is True
if moving:
rel_f=_finite(rel_f);rel_y=-_finite(rel_y)
else:
rel_f=rel_y=0.
lateral_margin=.4+abs(rel_y)*3.
overlap=(y+half_y+lateral_margin>=low and y-half_y-lateral_margin<=high)
if not overlap:continue
# A distant measured tractor/trailer on this corridor is direction
# evidence, never an invented lane or a clearance certificate.
actor_speed=actor.get('speed_mps')
if (moving and actor.get('type') in ('ai','player','ai-trailer','player-trailer')
and actor_speed is not None and _finite(actor_speed)>1.
and abs(heading)<math.radians(20) and f>0):
direction_evidence=True
if abs(heading)>math.radians(35) and -60<f<max(50.,speed*4):
raise ValueError('Adjacent actor travel direction conflicting')
front_gap=f-half_f
rear_gap=-f-half_f
if f>=0:
required=max(25.,speed*2.5)+max(0.,-rel_f)*4.
blocked=front_gap<required
else:
required=35.+max(0.,rel_f)*5.
blocked=rear_gap<required
if not moving and -80<f<max(60.,speed*4):
blocked=True
assessments.append(dict(id=actor.get('id'),forward_m=f,footprint_half_forward_m=half_f,
front_gap_m=front_gap,rear_gap_m=rear_gap,required_gap_m=required,
motion_available=moving,blocked=blocked))
if blocked:
raise ValueError('Adjacent lane occupied or closing gap unknown: '+str(actor.get('id')))
return direction_evidence,assessments,age
@staticmethod
def _travel(data,direction_evidence):
geometry=data.get('road_geometry') or data.get('lane_geometry')
counts=geometry.get('lane_counts') if isinstance(geometry,dict) and geometry.get('available') is True else None
if counts is not None:
age=_finite(geometry.get('age_s'))
count=counts.get('travel_direction')
if not 0<=age<=.5 or type(count) is not int or not 1<=count<=12:
raise ValueError('Native travel lane-count evidence stale or invalid')
if count<2:
raise ValueError('Native road has no adjacent travel lane')
if counts.get('opposing_direction',0)>0 and not direction_evidence:
raise ValueError('Adjacent travel direction ambiguous on two-way road')
return 'native travel lane count + observed truck-footprint road-edge margin'
if not direction_evidence:
raise ValueError('Adjacent lane versus shoulder/travel direction unassessed')
return 'measured same-direction actor + observed truck-footprint road-edge margin'
def _match_target(self,candidates,position,yaw):
old=self.previous
if old is None:return candidates[self.target[0]]
grid,center,oldpos,oldyaw=old
fx,fz=-math.sin(oldyaw),-math.cos(oldyaw)
wx=oldpos[0]+grid*fx-center*fz
wz=oldpos[2]+grid*fz+center*fx
dx,dz=wx-position[0],wz-position[2]
fx,fz=-math.sin(yaw),-math.cos(yaw)
px,py=dx*fx+dz*fz,-(dx*fz-dz*fx)
if np.any(np.diff(px)<=0) or px[-1]<12 or px[0]>12:
raise ValueError('Observed target corridor continuity unavailable')
expected=np.interp(12.,px,py)
scores=sorted((abs(np.interp(12.,c['grid'],c['center'])-expected),i)
for i,c in candidates.items())
if not scores or scores[0][0]>.9 or (len(scores)>1 and scores[1][0]-scores[0][0]<1.):
raise ValueError('Observed adjacent corridor changed ambiguously')
return candidates[scores[0][1]]
def assess(self,perception,telemetry,now=None):
now=time.monotonic() if now is None else now
try:now=_finite(now)
except ValueError:return self._report('Lane-change clock invalid')
if self.last_now is not None and now<self.last_now:
self.reset();return self._report('Lane-change clock regressed')
self.last_now=now
left,right=telemetry.get('blinker_left'),telemetry.get('blinker_right')
if type(left) is not bool or type(right) is not bool:
if self.state=='changing':self.state='cancelled';self.used=True
return self._report('Actual SDK turn-signal flags unavailable')
if not left and not right:
self.reset();return self._report()
if telemetry.get('hazards') is True or left and right:
self.used=True;self.state='cancelled';return self._report('Hazards cancel lane change')
direction='left' if left else 'right'
if self.direction=='none':
self.direction=direction;self.started=now;self.state='waiting'
elif direction!=self.direction:
self.used=True;self.state='cancelled';return self._report('Signal must turn off before another maneuver')
if self.used and self.state!='changing':
return self._report(self.cancel_reason or 'One maneuver consumed; turn signal off to rearm'
if self.state!='complete' else '')
if telemetry.get('gameplay_engaged') is not True:
if self.state=='changing':
self.state='cancelled';self.used=True
return self._report('Gameplay disengaged; lane change cancelled')
return self._report('Turn-signal request pending gameplay engagement')
if now-self.started<self.SIGNAL_DELAY_S:
return self._report('Waiting for 0.5-second turn-signal delay')
try:
x,ys,zs,ps,speed,stamp,position,yaw=self._geometry(perception,telemetry,now)
if self.last_stamp is not None and stamp<=self.last_stamp:
raise ValueError('Distinct fresh lane-change frame required')
self.last_stamp=stamp
horizon=min(float(x[-1]),max(30.,speed*4.))
candidates={}
for i in range(3):
try:candidates[i]=self._corridor(x,ys,zs,ps,(i,i+1),horizon)
except ValueError:pass
if self.state!='changing':
ego=candidates.get(1)
if ego is None or not ego['low'][0]+.25<0<ego['high'][0]-.25:
raise ValueError('Ego zero not inside observed central travel corridor')
self.target=(0,1) if direction=='left' else (2,3)
if self.target[0] not in candidates:
raise ValueError('Adjacent observed travel corridor unavailable')
target=self._match_target(candidates,position,yaw)
edge_margin=self._edge(perception,target,x)
direction_evidence,actors,traffic_age=self._traffic(telemetry,now,target,speed)
travel_source=self._travel(telemetry,direction_evidence)
pulse='none'
if self.state!='changing':
self.state='changing';self.used=True;self.active_since=now;pulse=direction
if now-self.active_since>self.MAX_MANEUVER_S:
raise ValueError('Lane-change timeout; manual completion required')
self.target=target['key']
self.previous=(target['grid'].copy(),target['center'].copy(),position.copy(),yaw)
centered=(target['low'][0]+.35<0<target['high'][0]-.35 and abs(target['center'][0])<.45)
if centered:
if self.centered_since is None:self.centered_since=now;self.centered_frames=0
self.centered_frames+=1
if self.centered_frames>=3 and now-self.centered_since>=.2:
self.state='complete'
return self._report(completed_corridor=dict(boundary_indices=list(self.target)),
travel_evidence_source=travel_source)
else:self.centered_since=None;self.centered_frames=0
# Use the observed curved target center throughout. The quintic
# blend starts at truck ego zero and meets the measured corridor;
# there is no GPS chord, extrapolation, or constant steering offset.
distance=max(20.,speed*4.)
grid=target['grid']
u=np.clip(grid/distance,0.,1.)
blend=10*u**3-15*u**4+6*u**5
occupied=[c for c in candidates.values() if c['low'][0]<=0<=c['high'][0]]
if not occupied:raise ValueError('Ego zero outside observed corridors during maneuver')
source=min(occupied,key=lambda c:abs(c['center'][0]))
source_curve=np.interp(grid,source['grid'],source['center'])-source['center'][0]
selected=source_curve+blend*(target['center']-source_curve)
override={axis:np.pad(values,(0,33-len(values)),mode='edge').tolist()
for axis,values in zip(('x','y','z'),(grid,selected,target['z']))}
return self._report(allowed=True) | dict(
path_override=override,desiredpulse=pulse,target_corridor=dict(boundary_indices=list(self.target)),
traffic_assessments=actors,traffic_age_s=traffic_age,
road_edge_margin_m=edge_margin,travel_evidence_source=travel_source,
continuity_reference='SDK pose reprojection of previous observed target center; nominal camera origin',
rear_corridor_reference='near observed cross-section; rear road curvature unverified')
except (AttributeError,KeyError,TypeError,ValueError,IndexError) as exc:
if self.state=='changing':
return self.cancel(str(exc))
else:self.state='blocked'
return self._report(str(exc))
-541
View File
@@ -1,541 +0,0 @@
"""Experimental route constraint on a current camera path, without actuators.
Native GPS graph points supply direction only. They are never lane centers.
The only alternative trajectory is a measured, continuously committed camera
corridor. This module does not choose another lane, prove clearance or decide
intersection priority. The caller uses the same selected plan for steering,
curve speed and collision assessment, and retains its existing control gates.
"""
import math
import numbers
import time
import numpy as np
from model.perception import X_IDXS
def _number(value):
if isinstance(value, bool) or not isinstance(value, numbers.Real):
return None
value = float(value)
return value if math.isfinite(value) else None
def _angle_error(a, b):
return abs(math.atan2(math.sin(a-b), math.cos(a-b)))
class GameplayNavigation:
MAX_ROUTE_AGE_S = .5
MAX_DIRECTION_HOLD_S = .45
MAX_MODEL_AGE_S = .35
# Pop's low-speed horizon contracts to roughly four metres. That is
# expected while the truck is rolling to a stop, but GPS admission still
# needs a small forward window to compare headings.
LOW_SPEED_PLAN_EXTENSION_MPS = 7.0
MIN_PLAN_COVERAGE_M = 3.0
ROUTE_COMPARISON_HORIZON_M = 10.0
ROUTE_APPROACH_DISTANCE_M = 120.0
MANUAL_JUNCTION_DISTANCE_M = 45.0
CORRIDOR_CONFIDENCE = .6
MODEL_DIRECTION_LIMIT_RAD = math.radians(20.)
CORRIDOR_DIRECTION_LIMIT_RAD = math.radians(8.)
COMPLETION_HANDOFF_S = 1.
def __init__(self, clock=time.monotonic, model_age_s=None):
self.clock = clock
age = _number(model_age_s) if model_age_s is not None else self.MAX_MODEL_AGE_S
if age is None or age <= 0:
raise ValueError('Positive navigation model age limit required')
self.model_age_limit_s = age
self.reset()
def reset(self):
self._last_now = None
self._direction = None
self._revision = None
self._committed = None
self._candidate_key = None
self._candidate_since = None
self._candidate_samples = 0
self._last_input_stamp = None
self._last_pose = None
self._completion_handoff = None
self._completed_key = None
self._handoff_status = 'none'
self._handoff_provisional = False
def adopt_committed_corridor(self, boundary_indices):
"""Caller acknowledges a completed, explicitly validated lane maneuver.
Signals or an uncompleted maneuver must never call this method. This
acknowledgement changes only the camera boundary identity, not GPS.
"""
if (not isinstance(boundary_indices, (list, tuple)) or len(boundary_indices) != 2
or any(type(i) is not int for i in boundary_indices)
or boundary_indices[0] not in (0, 1, 2)
or boundary_indices[1] != boundary_indices[0]+1):
raise ValueError('Adjacent observed boundary indices required')
self._committed = tuple(boundary_indices)
self._completed_key = self._committed
self._completion_handoff = (dict(deadline=self._last_now+self.COMPLETION_HANDOFF_S,
origin=self._last_pose) if self._last_now is not None and self._last_pose is not None else None)
self._handoff_status = 'awaiting-renumber' if self._completion_handoff else 'pose-unavailable'
self._candidate_key = None
self._candidate_since = None
self._candidate_samples = 0
@staticmethod
def _report(reason='', **extra):
return dict(available=False, allowed_for_gameplay=False, reason=reason,
strategy='manual-required', path_override=None,
require_manual=True, transient=False, route_revision=None,
navigation_phase='route-uncertain', next_bend=None,
route_speed_cap_mph=None,
direction_evidence=None, committed_corridor=None,
gps_direction_held=False, direction_age_s=None, gps_sampled_at=None,
automatic_lane_change=False, lane_change_required=False,
lane_association_verified=False, clearance_verified=False,
intersection_priority_verified=False, experimental=True,
production_eligible=False, route_competence_validated=False,
**extra)
@staticmethod
def _pose(telemetry):
if (not isinstance(telemetry, dict) or telemetry.get('valid') is not True
or telemetry.get('position_valid') is not True or telemetry.get('paused') is not False):
raise ValueError('Fresh unpaused SDK pose required for route steering')
age = _number(telemetry.get('age'))
if age is None or not 0 <= age <= .35:
raise ValueError('SDK pose is stale for route steering')
position, rotation = (np.asarray(telemetry.get(k), float) for k in ('world_position', 'world_rotation'))
if any(a.shape != (3,) or not np.isfinite(a).all() for a in (position, rotation)):
raise ValueError('Finite SDK position and heading required')
yaw = float(rotation[0])*2*math.pi
return position, yaw, -math.sin(yaw), -math.cos(yaw)
def _plan(self, perception, telemetry, now):
if (telemetry.get('model_obstructed') is not False or telemetry.get('model_geometry_stale') is not False
or telemetry.get('model_inferred_this_frame') is not True):
raise ValueError('Fresh unobstructed model geometry required for route steering')
age, stamp = _number(telemetry.get('model_age_s')), _number(telemetry.get('model_input_monotonic'))
if (age is None or not 0 <= age <= self.model_age_limit_s or stamp is None
or not -.05 <= now-stamp <= self.model_age_limit_s):
raise ValueError('Model camera geometry is stale for route steering')
arrays = [np.asarray(getattr(perception.plan, axis), float) for axis in ('x', 'y', 'z')]
if any(a.shape != (33,) or not np.isfinite(a).all() for a in arrays):
raise ValueError('Finite current Pop trajectory required')
x, y, z = arrays
end = 1
while end < len(x) and x[end] > x[end-1]+1e-4:
end += 1
speed = _number(telemetry.get('speed_mps'))
if speed is None or speed < -.02:
raise ValueError('Finite forward speed required for route steering')
coverage = float(x[end-1])
if x[0] < 0 or x[0] > 5 or end < 3 or coverage < self.MIN_PLAN_COVERAGE_M:
raise ValueError('Current trajectory lacks near-to-forward route comparison')
distance = min(max(18., min(45., max(0., speed)*2.5)), coverage)
if coverage < self.ROUTE_COMPARISON_HORIZON_M:
if speed > self.LOW_SPEED_PLAN_EXTENSION_MPS:
raise ValueError('Current trajectory lacks near-to-forward route comparison')
# At queue speed Pop intentionally predicts only a short distance.
# Extend that measured tangent for GPS admission only; the padded
# path is never sent to the actuator as a replacement model path.
dx = float(x[end-1]-x[end-2])
if not math.isfinite(dx) or dx <= 1e-4:
raise ValueError('Current trajectory lacks near-to-forward route comparison')
extension = self.ROUTE_COMPARISON_HORIZON_M-coverage
slope_y = float((y[end-1]-y[end-2])/dx)
slope_z = float((z[end-1]-z[end-2])/dx)
x = np.r_[x[:end], self.ROUTE_COMPARISON_HORIZON_M]
y = np.r_[y[:end], y[end-1]+slope_y*extension]
z = np.r_[z[:end], z[end-1]+slope_z*extension]
distance = self.ROUTE_COMPARISON_HORIZON_M
return x, y, z, distance, stamp
@classmethod
def _route_state(cls, preview):
"""Classify the next graph bend for speed advice and UI state.
A native GPS node is still not a lane center or a right-of-way signal.
This state deliberately stops at an approach/hand-off boundary; it is
useful for slowing early and telling the driver what will happen next,
but it never creates a turn trajectory.
"""
state = dict(navigation_phase='route-cruise', next_bend=None,
route_speed_cap_mph=None)
if not isinstance(preview, dict):
return state
bend = preview.get('next_bend')
if bend is None:
return state
if not isinstance(bend, dict):
return dict(state, navigation_phase='route-uncertain')
distance = _number(bend.get('distance_m'))
angle = _number(bend.get('angle_deg'))
direction = bend.get('direction')
if (distance is None or angle is None or distance < 0 or
direction not in ('left', 'right')):
return dict(state, navigation_phase='route-uncertain')
turn = dict(direction=direction, distance_m=distance, angle_deg=angle,
distance_units=bend.get('distance_units', 'ATS advisor metres'))
magnitude = abs(angle)
if distance <= cls.MANUAL_JUNCTION_DISTANCE_M:
return dict(state, navigation_phase='manual-junction', next_bend=turn,
route_speed_cap_mph=15.0)
if distance <= cls.ROUTE_APPROACH_DISTANCE_M or magnitude >= 45.0:
# Advisory cap only. It eases speed before the handoff without
# pretending the graph supplies a safe intersection trajectory.
cap = 50.0 - .35*max(0., magnitude-25.)
cap -= .25*max(0., cls.ROUTE_APPROACH_DISTANCE_M-distance)
cap = max(15.0, min(45.0, cap))
return dict(state, navigation_phase='approach-turn', next_bend=turn,
route_speed_cap_mph=cap)
return dict(state, next_bend=turn)
def validate_maneuver_path(self, path, navreport, now=None):
"""Route check an independently validated explicit lane-change path.
This does not validate traffic clearance or generate a maneuver. Only
current-corridor selection failures can be waived; GPS/camera failures
cannot. The caller retains its lane-change and native collision gates.
"""
reject=lambda reason:dict(allowed=False,reason=reason)
now=_number(self.clock() if now is None else now)
if now is None or not isinstance(navreport,dict) or navreport.get('available') is not True:
return reject('Valid current GPS direction assessment required')
assessed=_number(navreport.get('assessed_at'));sampled=_number(navreport.get('gps_sampled_at'))
if (assessed is None or not -.05<=now-assessed<=.15 or sampled is None
or not -.05<=now-sampled<=self.MAX_DIRECTION_HOLD_S):
return reject('GPS maneuver direction timestamp is stale')
waivable=('Model crosses occupied corridor and GPS does not support retaining it',
'GPS branch requires a different observed corridor; automatic lane changes unavailable',
'GPS and model diverge without a stable aligned committed lane')
if navreport.get('allowed_for_gameplay') is not True and navreport.get('reason') not in waivable:
return reject('Current GPS/camera admission failure cannot be waived by a signal')
try:
evidence=navreport['direction_evidence'];horizon=evidence['measured_horizon_m']
distance=float(horizon[1]);gps=math.radians(float(evidence['gps_right_heading_deg']))
arrays=[np.asarray(path[k] if isinstance(path,dict) else getattr(path,k),float)for k in ('x','y','z')]
if any(a.shape!=(33,)or not np.isfinite(a).all()for a in arrays):
return reject('Finite measured maneuver path required')
x,y,z=arrays;end=1
while end<len(x)and x[end]>x[end-1]+1e-4:end+=1
x,y,z=x[:end],y[:end],z[:end]
if x[0]>5 or x[0]<0 or x[-1]<distance or distance<10:
return reject('Maneuver path lacks measured route comparison coverage')
heading=math.atan2(float(np.interp(distance,x,y)-np.interp(5.,x,y)),distance-5.)
error=_angle_error(heading,gps)
if error>self.MODEL_DIRECTION_LIMIT_RAD:
return reject('Requested lane-change path conflicts with the GPS branch')
return dict(allowed=True,reason='',gps_direction_age_s=max(0.,now-sampled),
gps_sampled_at=sampled,heading_error_deg=math.degrees(error),
current_corridor_guard_waived=navreport.get('allowed_for_gameplay') is not True,
clearance_verified=False)
except (ValueError,KeyError,TypeError,AttributeError,IndexError,OverflowError):
return reject('Malformed GPS maneuver direction or path')
def _fresh_direction(self, route, preview, telemetry, position, fx, fz, distance, now):
if telemetry.get('navigation_valid') is not True:
raise ValueError('Native GPS telemetry unavailable')
if not isinstance(route, dict) or route.get('available') is not True:
raise ValueError('Native GPS route unavailable')
if (route.get('geometry_kind') != 'native-route-node-array'
or route.get('lead_in') is not None or not isinstance(preview, dict)
or preview.get('lead_in_estimated') or preview.get('segment_kind') != 'native-node-pair'):
raise ValueError('Estimated GPS lead-in or unverified route geometry cannot guide steering')
age, sampled = _number(route.get('age_s')), _number(route.get('sampled_at'))
if (age is None or not 0 <= age <= self.MAX_ROUTE_AGE_S or sampled is None
or not -.05 <= now-sampled <= self.MAX_ROUTE_AGE_S):
raise ValueError('Native GPS route is stale')
if preview.get('available') is not True or preview.get('reason'):
raise ValueError(preview.get('reason') or 'Native GPS route matching unavailable')
if preview.get('revision') != route.get('revision') or not route.get('revision'):
raise ValueError('GPS route revision and match disagree')
nodes, segment = route.get('nodes'), preview.get('segment')
if (not isinstance(nodes, list) or not 2 <= len(nodes) <= 1024
or type(segment) is not int or not 0 <= segment < len(nodes)-1):
raise ValueError('Invalid directed native GPS route segment')
points = []
for node in nodes:
point = np.asarray(node.get('position'), float)
if point.shape != (3,) or not np.isfinite(point).all() or node.get('uid') is None:
raise ValueError('Invalid native GPS endpoint identity/position')
points.append(point)
a, b = points[segment:segment+2]
delta = b-a; length2 = delta[0]**2+delta[2]**2
if length2 < 1 or str(nodes[segment]['uid']) == str(nodes[segment+1]['uid']):
raise ValueError('Directed native GPS pair has no usable extent')
t = float(np.clip(((position[0]-a[0])*delta[0]+(position[2]-a[2])*delta[2])/length2, 0, 1))
projection = a+t*delta
error = float(np.linalg.norm((projection-position)[[0, 2]]))
heading = float((fx*delta[0]+fz*delta[2])/math.sqrt(length2))
progress = _number(preview.get('progress_error_m'))
if error > 18 or abs(projection[1]-position[1]) > 4 or heading < .5 or progress is None or not 0 <= progress <= 500:
raise ValueError('Truck does not match the directed GPS route')
# Keep the actual projected graph point, including its lateral offset.
# The offset cancels in the tangent calculation; no synthetic (0,0)
# graph lead-in or graph-center lateral steering term is introduced.
ego = []
for point in [projection]+points[segment+1:]:
dx, dz = point[0]-position[0], point[2]-position[2]
sample = [dx*fx+dz*fz, dx*fz-dz*fx]
if ego and abs(sample[0]-ego[-1][0]) < 1e-5 and abs(sample[1]-ego[-1][1]) < 1e-5:
continue
if ego and sample[0] <= ego[-1][0]+1e-5:
break
ego.append(sample)
if sample[0] >= distance:
break
curve = np.asarray(ego, float)
if len(curve) < 2 or curve[0, 0] > 5 or curve[-1, 0] < distance:
raise ValueError('Native GPS direction has insufficient forward coverage')
lateral_change = float(np.interp(distance, curve[:,0],curve[:,1])-np.interp(5.,curve[:,0],curve[:,1]))
slope_left = lateral_change/(distance-5.)
angle = -math.atan(slope_left) # model right-positive; GPS left-positive.
if abs(angle) > math.radians(45):
raise ValueError('Sharp route turn requires manual junction handling')
# Save a world-space direction. Brief holds rotate it with the current
# truck heading instead of pretending an old relative angle is fresh.
world = np.array([fx+fz*slope_left, fz-fx*slope_left])
world /= np.linalg.norm(world)
return dict(right_heading_rad=angle, world_direction=world.tolist(),
sampled_at=sampled, revision=route['revision'],
pair_uids=[str(nodes[segment]['uid']),str(nodes[segment+1]['uid'])],
measured_horizon_m=[5.,distance], graph_offset_world_m=error,
graph_offset_used_for_steering=False)
@staticmethod
def _corridors(perception, x, y, distance):
lanes = getattr(perception,'lanes',None)
try:
lx=np.asarray(getattr(lanes,'x',None),float)
ys=np.asarray(getattr(lanes,'all_y',None),float)
ps=np.asarray(getattr(lanes,'probabilities',None),float)
except (TypeError,ValueError):
return []
if (lx.shape!=(33,) or ys.shape!=(4,33) or ps.shape!=(4,) or not np.isfinite(lx).all()
or not np.isfinite(ys).all() or not np.isfinite(ps).all() or np.any(np.diff(lx)<=0)
or np.any((ps<0)|(ps>1)) or lx[0]>5 or lx[-1]<distance):
return []
grid=np.unique(np.r_[5.,lx[(lx>5.)&(lx<distance)],distance])
# Ego zero identifies the occupied corridor. A wandering network plan
# is not evidence that the truck has already changed lanes.
near=float(np.clip(np.interp(5.,x,y), -.5, .5));candidates=[]
for left in range(3):
right=left+1
confidence=float(min(ps[left],ps[right]))
if confidence<.6:continue
low=np.interp(grid,lx,ys[left]);high=np.interp(grid,lx,ys[right]);width=high-low
if np.any(width<2.3) or np.any(width>5.5) or np.ptp(width)>1.5 or np.any(np.abs(low)>25) or np.any(np.abs(high)>25):continue
center=(low+high)*.5
if not low[0]+.3<0.<high[0]-.3:continue
near=float(np.clip(near, low[0]+.35, high[0]-.35))
offset=near-center[0]
selected=center+offset
if np.any(np.minimum(selected-low,high-selected)<.3):continue
heading=math.atan2(float(center[-1]-center[0]),distance-5.)
candidates.append(dict(key=(left,right),confidence=confidence,lane_x=lx,
center=(ys[left]+ys[right])*.5,offset=float(offset),heading=heading,
low=low,high=high,grid=grid,near_anchor=near))
return candidates
@staticmethod
def _edge_evidence(perception, grid, selected):
"""Predicted edge proximity is caution, not proof of painted-lane type."""
try:
ex=np.asarray(getattr(perception,'road_edge_x',X_IDXS),float)
edges=np.asarray(perception.road_edges,float)
std=np.asarray(perception.road_edge_std,float)
except (AttributeError,TypeError,ValueError):
return dict(available=False,reason='Predicted road-edge evidence unavailable')
if (ex.shape!=(33,) or edges.shape!=(2,33,2) or std.shape!=(2,33,2)
or not all(np.isfinite(a).all() for a in (ex,edges,std))
or np.any(np.diff(ex)<=0) or np.any(std<0) or ex[0]>grid[0] or ex[-1]<grid[-1]):
return dict(available=False,reason='Predicted road-edge evidence malformed')
lo=np.interp(grid,ex,edges[0,:,0]);hi=np.interp(grid,ex,edges[1,:,0])
sigma=np.maximum(np.interp(grid,ex,std[0,:,0]),np.interp(grid,ex,std[1,:,0]))
if np.any(hi<=lo) or np.max(sigma)>1.:
return dict(available=False,reason='Predicted road edges uncertain or crossed')
clearance=float(np.min(np.minimum(selected-lo,hi-selected)-sigma))
return dict(available=True,minimum_predicted_edge_margin_m=clearance,
near_edge=clearance<.65,road_edge_identity_verified=False)
def _commit(self, candidates, stamp, now):
self._handoff_provisional=False
handoff=self._completion_handoff
if handoff is not None:
origin_position,origin_yaw=handoff['origin']
position,yaw=self._last_pose
continuous=(float(np.linalg.norm((position-origin_position)[[0,2]]))<=30.
and abs(float(position[1]-origin_position[1]))<=1.5
and _angle_error(yaw,origin_yaw)<=math.radians(12.))
if now>handoff['deadline'] or not continuous:
self._handoff_status='expired' if now>handoff['deadline'] else 'pose-discontinuous'
self._completion_handoff=None;handoff=None
self._candidate_key=None;self._candidate_since=None;self._candidate_samples=0
if len(candidates)!=1:
self._candidate_key=None;self._candidate_since=None;self._candidate_samples=0
return None
candidate=candidates[0];key=candidate['key']
if self._committed is not None:
if key==self._committed:return candidate
if handoff is None:return None
# A validated completion can be followed by camera index
# renumbering. Rewarm the one measured ego-containing corridor
# within a short, pose-continuous window. Its boundary guard stays
# active provisionally; persistent identity changes only after
# three distinct observations, not from a signal or stale frame.
self._handoff_provisional=True
self._handoff_status='renumber-warming'
if key!=self._candidate_key:
self._candidate_key=key;self._candidate_since=now;self._candidate_samples=0
if self._last_input_stamp is None or stamp>self._last_input_stamp:
self._candidate_samples+=1
if self._candidate_samples>=3 and now-self._candidate_since>=.1:
self._committed=key
if handoff is not None:
self._completion_handoff=None;self._handoff_status='renumbered'
self._handoff_provisional=False
return candidate
if handoff is not None:return candidate
return None
@staticmethod
def _override(x,y,z,corridor,distance):
selected_x=np.r_[x[x<distance],distance]
if len(selected_x)>33:
selected_x=selected_x[:32];selected_x=np.r_[selected_x,distance]
center=np.interp(selected_x,corridor['lane_x'],corridor['center'])+corridor['offset']
near=selected_x<5.
# Do not preserve an already wandering near-model anchor during a
# boundary intervention. Bound it to the ego vicinity and measured
# corridor rather than creating an early shoulder excursion.
center[near]=np.clip(np.interp(selected_x[near],x,y),-.5,.5)
# Candidate bounds were evaluated on the measured grid; use them only
# at/after5m, never extrapolate a road boundary toward the truck.
far=selected_x>=5.
center[far]=np.clip(center[far],np.interp(selected_x[far],corridor['grid'],corridor['low'])+.3,
np.interp(selected_x[far],corridor['grid'],corridor['high'])-.3)
selected_z=np.interp(selected_x,x,z)
# Pad with an exact repeated endpoint. Existing steering/collision
# geometry stops at the first non-increasing x; no inferred continuation
# beyond the observed, validated corridor is supplied.
return {axis:np.pad(values,(0,33-len(values)),mode='edge').tolist()
for axis,values in zip(('x','y','z'),(selected_x,center,selected_z))}
def assess(self, perception, telemetry, route, preview, now=None):
now=_number(self.clock() if now is None else now)
if now is None or (self._last_now is not None and now<self._last_now):
self.reset();return self._report('Navigation clock unavailable or regressed')
self._last_now=now
route_state=self._route_state(preview)
try:
position,yaw,fx,fz=self._pose(telemetry)
x,y,z,distance,stamp=self._plan(perception,telemetry,now)
self._last_pose=(position.copy(),yaw)
route_revision=route.get('revision') if isinstance(route,dict) else None
if route_revision and route_revision!=self._revision:
self._direction=None;self._committed=None;self._candidate_key=None
self._candidate_since=None;self._candidate_samples=0;self._revision=route_revision
self._completion_handoff=None;self._completed_key=None;self._handoff_status='none'
held=False;route_reason=''
try:
direction=self._fresh_direction(route,preview,telemetry,position,fx,fz,distance,now)
self._direction=direction
except (ValueError,KeyError,TypeError,IndexError) as exc:
route_reason=str(exc)
# A changed/estimated representation must never inherit the
# previous native route. Holds cover only short unavailable or
# stale reader samples on the same route/unknown revision.
incompatible=(isinstance(route,dict) and (route.get('lead_in') is not None
or route.get('geometry_kind') not in (None,'native-route-node-array')))
incompatible=incompatible or (isinstance(preview,dict) and (preview.get('lead_in_estimated')
or preview.get('segment_kind') not in (None,'native-node-pair')))
# Definitive geometric disagreement is not a dropped sample.
incompatible=incompatible or route_reason in (
'Truck does not match the directed GPS route',
'Sharp route turn requires manual junction handling',
'GPS route revision and match disagree')
if (incompatible or self._direction is None
or not 0<=now-self._direction['sampled_at']<=self.MAX_DIRECTION_HOLD_S):
result=self._report(route_reason)
result.update(route_state)
if self._direction is not None:
result.update(gps_hold_expired=now-self._direction['sampled_at']>self.MAX_DIRECTION_HOLD_S,
direction_age_s=max(0.,now-self._direction['sampled_at']),
gps_sampled_at=self._direction['sampled_at'],
hold_deadline_monotonic=self._direction['sampled_at']+self.MAX_DIRECTION_HOLD_S)
return result
direction=dict(self._direction);world=direction['world_direction']
forward=world[0]*fx+world[1]*fz;left=world[0]*fz-world[1]*fx
if forward<.7:return self._report('Held GPS direction no longer agrees with truck heading')
direction['right_heading_rad']=-math.atan2(left,forward);held=True
candidates=self._corridors(perception,x,y,distance)
corridor=self._commit(candidates,stamp,now)
self._last_input_stamp=stamp
model_heading=math.atan2(float(np.interp(distance,x,y)-np.interp(5.,x,y)),distance-5.)
gps_heading=direction['right_heading_rad'];model_error=_angle_error(model_heading,gps_heading)
result=self._report()
result.update(route_state,available=True,allowed_for_gameplay=True,require_manual=False,
assessed_at=now,
strategy='camera-path-follows-gps',reason='',route_revision=direction['revision'],
gps_direction_held=held,direction_age_s=max(0.,now-direction['sampled_at']),
gps_sampled_at=direction['sampled_at'],
completed_corridor_boundary_indices=list(self._completed_key) if self._completed_key else None,
corridor_identity_handoff=self._handoff_status,
direction_evidence=dict(model_right_heading_deg=math.degrees(model_heading),
gps_right_heading_deg=math.degrees(gps_heading),model_error_deg=math.degrees(model_error),
measured_horizon_m=[5.,distance],native_pair_uids=direction['pair_uids'],
graph_offset_world_m=direction['graph_offset_world_m'],graph_offset_used_for_steering=False,
held_reader_reason=route_reason if held else ''))
if (self._committed is not None and corridor is None and len(candidates)==1
and candidates[0]['key']!=self._committed):
result.update(allowed_for_gameplay=False,require_manual=True,lane_change_required=True,
strategy='manual-required',
reason='GPS branch requires a different observed corridor; automatic lane changes unavailable')
return result
if corridor is not None:
result['committed_corridor']=dict(boundary_indices=list(corridor['key']),confidence=corridor['confidence'],
identity_handoff_pending=self._handoff_provisional)
corridor_error=_angle_error(corridor['heading'],gps_heading)
result['direction_evidence']['corridor_error_deg']=math.degrees(corridor_error)
plan=np.interp(corridor['grid'],x,y)
inside=np.minimum(plan-corridor['low'],corridor['high']-plan)
crossed_boundary=float(np.min(inside))<.25
result['committed_corridor'].update(estimated=True,travel_lane_identity_verified=False,
minimum_model_boundary_margin_m=float(np.min(inside)))
selected=np.interp(corridor['grid'],corridor['lane_x'],corridor['center'])+corridor['offset']
edge=self._edge_evidence(perception,corridor['grid'],selected)
result['road_edge_caution']=edge
if edge.get('near_edge'):
result.update(allowed_for_gameplay=False,require_manual=True,strategy='manual-required',
reason='Occupied observed corridor approaches an uncertain road edge or shoulder')
return result
if corridor_error<=self.CORRIDOR_DIRECTION_LIMIT_RAD and (crossed_boundary or model_error>self.MODEL_DIRECTION_LIMIT_RAD):
if corridor['key']!=(1,2) and not edge.get('available'):
result.update(allowed_for_gameplay=False,require_manual=True,strategy='manual-required',
reason='Outer observed corridor lacks road-edge evidence; travel lane versus shoulder unknown')
return result
result.update(strategy='gps-committed-camera-corridor',
path_override=self._override(x,y,z,corridor,distance),
reason='Retaining the occupied observed corridor against a predicted boundary crossing')
return result
if crossed_boundary:
result.update(allowed_for_gameplay=False,require_manual=True,strategy='manual-required',
reason='Model crosses occupied corridor and GPS does not support retaining it')
return result
if model_error<=self.MODEL_DIRECTION_LIMIT_RAD:
return result
other_aligned=any(_angle_error(candidate['heading'],gps_heading)<=self.CORRIDOR_DIRECTION_LIMIT_RAD
for candidate in candidates)
result.update(allowed_for_gameplay=False,require_manual=True,strategy='manual-required',
transient=self._committed is None and other_aligned,
lane_change_required=self._committed is not None and other_aligned,
reason=('GPS branch requires a different observed corridor; automatic lane changes unavailable' if self._committed is not None and other_aligned
else 'GPS and model diverge without a stable aligned committed lane'))
return result
except (ValueError,KeyError,TypeError,AttributeError,IndexError,OverflowError) as exc:
return self._report(str(exc))
-425
View File
@@ -1,425 +0,0 @@
"""Track an observed ego lane, including brief paint gaps, without actuators.
The model's four line slots are candidates, not permanent lane identities.
A committed lane is compared in world space so an adjacent line pair cannot
silently become the steering target. Explicit validated maneuvers own their path.
"""
import copy
import math
import numpy as np
from model.perception import X_IDXS
class GameplayRoadTracking:
HOLD_S = 1.
ROUTE_RECOVERY_S = 2.
# A paint dropout should not turn a valid, route-aligned model path into
# an emergency stop. This is deliberately a bounded laneless recovery:
# it is only available at moderate speed, with a fresh route admission,
# low predicted lateral uncertainty, and a path that remains close to the
# current lane. At higher speed or near a junction the existing braking
# handoff remains the safer behaviour.
LANELESS_MAX_SPEED_MPS = 18.0
LANELESS_MAX_PATH_STD_M = 1.0
LANELESS_MAX_HEADING_ERROR_DEG = 6.0
LANELESS_CRAWL_HEADING_ERROR_DEG = 12.0
def __init__(self):
self.reset()
def reset(self):
self.world = self.seen = self.candidate = self.candidate_since = None
self.count = 0
self.lost = False
self.verified_route_revision = None
self.observed_speed_mph = None
self.reacquire_world = self.reacquire_since = self.reacquire_at = None
self.reacquire_count = 0
@staticmethod
def pose(data):
try:
p = np.asarray(data['world_position'], float)[[0, 2]]
yaw = float(data['world_rotation'][0])*2*math.pi
if data.get('position_valid') is not True or not np.isfinite(p).all() or not math.isfinite(yaw):
return None
# Model coordinates are forward/right; SDK horizontal axes are X/Z.
basis = np.array([[-math.sin(yaw), -math.cos(yaw)],
[math.cos(yaw), -math.sin(yaw)]])
return p, basis
except (KeyError, TypeError, ValueError, IndexError):
return None
def projected(self, pose):
if pose is None or self.world is None:
return None
p, basis = pose
points = (self.world-p)@basis.T
if not np.isfinite(points).all() or np.any(np.diff(points[:, 0]) <= 0):
return None
return points
@staticmethod
def candidates(perception):
try:
lanes = perception.lanes
x, ys, probs = (np.asarray(getattr(lanes, k), float) for k in ('x', 'all_y', 'probabilities'))
if (x.shape != (33,) or ys.shape != (4, 33) or probs.shape != (4,)
or not all(np.isfinite(a).all() for a in (x, ys, probs))
or np.any(np.diff(x) <= 0) or x[0] > 3 or x[-1] < 30
or np.any((probs < 0) | (probs > 1))):
return []
grid = np.unique(np.r_[3., x[(x > 3) & (x < 30)], 30.])
result = []
for i in range(3):
if min(probs[i:i+2]) < .65:
continue
left, right = (np.interp(grid, x, ys[j]) for j in (i, i+1))
width = right-left
if (np.any((width < 2.8) | (width > 4.5)) or np.ptp(width) > .8
or not left[0]+.2 < 0 < right[0]-.2):
continue
# Keep more observed coverage for motion propagation, but do
# not use the far forecast for the lane-centering controller.
keep = x <= 60.
result.append((i, np.column_stack((x[keep], ((ys[i]+ys[i+1])*.5)[keep]))))
return result
except (AttributeError, TypeError, ValueError, IndexError):
return []
@staticmethod
def selected(perception, points):
selected = copy.copy(perception)
selected.plan = copy.copy(perception.plan)
old_x = np.asarray(perception.plan.x)
# Never extend a held corridor beyond the road that was observed.
x = np.linspace(max(0., float(points[0, 0])), min(30., float(points[-1, 0])), 33)
selected.plan.x = x
selected.plan.y = np.interp(x, points[:, 0], points[:, 1])
if hasattr(perception.plan, 'z'):
selected.plan.z = np.interp(x, old_x, perception.plan.z)
return selected
@staticmethod
def _fresh_route(data, now):
navigation = data.get('navigation_driver') or {}
if (not isinstance(navigation, dict) or navigation.get('allowed_for_gameplay') is not True
or navigation.get('require_manual') is True
or navigation.get('navigation_phase') in ('manual-junction', 'route-uncertain')
or not navigation.get('route_revision')):
return None
try:
assessed, sampled = (float(navigation[key]) for key in ('assessed_at', 'gps_sampled_at'))
error = float(navigation['direction_evidence']['model_error_deg'])
if (not all(math.isfinite(v) for v in (assessed, sampled, error))
or not -.05 <= now-assessed <= .35
or not -.05 <= now-sampled <= .45 or abs(error) > 6.):
return None
return navigation['route_revision']
except (KeyError, TypeError, ValueError):
return None
def _temporary_recovery(self, perception, data, now, old, candidates):
"""Use only the remaining observed lane through a short confidence dip.
GPS cannot supply lane geometry. A matching route must have been fresh
when the lane was actually observed, and remain fresh now. Neither
repeated uncertain frames nor route updates extend that observation's
deadline. Current model/ego disagreement revokes the hold immediately.
"""
age = now-self.seen if self.seen is not None else math.inf
if (not .35 < age <= self.ROUTE_RECOVERY_S or old is None or candidates
or self.verified_route_revision is None or self.observed_speed_mph is None
or self._fresh_route(data, now) != self.verified_route_revision):
return None
try:
speed = float(data['speed_mps'])
x, y = (np.asarray(getattr(perception.plan, key), float) for key in ('x', 'y'))
std = np.asarray(perception.plan_std, float)
if (not math.isfinite(speed) or speed < 0
or x.shape != (33,) or y.shape != (33,) or std.shape != (33, 15)
or not np.isfinite(x).all() or not np.isfinite(y).all()
or not np.isfinite(std).all() or np.any(std < 0)):
return None
end = 1
while end < len(x) and x[end] > x[end-1]+1e-4:
end += 1
x, y, std = x[:end], y[:end], std[:end]
horizon = max(8., min(18., speed))
# Retained geometry is finite coverage, not a extrapolated road.
if (x[0] > 3. or x[-1] < horizon or old[0, 0] > 3.
or old[-1, 0] < max(15., speed)
or abs(float(np.interp(3., old[:, 0], old[:, 1]))) > .9):
return None
grid = np.linspace(3., horizon, 8)
delta = np.interp(grid, x, y)-np.interp(grid, old[:, 0], old[:, 1])
uncertainty = np.interp(grid, x, std[:, 1])
if np.max(np.abs(delta)) > .75 or np.max(uncertainty) > 4.:
return None
# A confident current road edge contradicting the saved corridor
# revokes recovery. Uncertain edges cannot generate a new lane.
if hasattr(perception, 'road_edges'):
ex=np.asarray(getattr(perception,'road_edge_x',X_IDXS),float)
edges=np.asarray(perception.road_edges,float)
edge_std=np.asarray(perception.road_edge_std,float)
if (ex.shape!=(33,) or edges.shape!=(2,33,2) or edge_std.shape!=(2,33,2)
or not all(np.isfinite(v).all() for v in (ex,edges,edge_std))
or np.any(np.diff(ex)<=0) or np.any(edge_std<0)
or ex[0]>grid[0] or ex[-1]<grid[-1]):
return None
lo,hi=(np.interp(grid,ex,edges[i,:,0]) for i in range(2))
sigma=np.maximum(*(np.interp(grid,ex,edge_std[i,:,0]) for i in range(2)))
saved=np.interp(grid,old[:,0],old[:,1])
if (np.max(sigma)<=1. and
(np.any(hi<=lo) or np.any(np.minimum(saved-lo,hi-saved)-sigma<.2))):
return None
cap = max(5., self.observed_speed_mph-min(4., 2.*age))
return dict(strategy='route-verified-observed-lane-recovery',
lane_tracking=True, brake_required=False, road_lost=False,
corridor_age_s=age, temporary_recovery=True,
recovery_deadline_monotonic=self.seen+self.ROUTE_RECOVERY_S,
recovery_speed_cap_mph=cap,
recovery_remaining_observed_m=float(old[-1, 0]),
recovery_model_offset_m=float(np.max(np.abs(delta))))
except (KeyError, AttributeError, TypeError, ValueError, IndexError):
return None
def _reacquire_consumed_lane(self, perception, data, now, pose, old, points):
"""Reobserve a lane after driving beyond the old finite corridor.
An exhausted world-space segment can no longer prove continuity, but
must not permanently prevent acquisition of fresh road at a queue.
This permits only a nearly stopped truck and several stable, confident
current lane observations that agree with the current model path.
It does not reset a conflicting corridor still visible ahead.
"""
try:
speed = float(data['speed_mps'])
x, y = (np.asarray(getattr(perception.plan, key), float) for key in ('x', 'y'))
std = np.asarray(perception.plan_std, float)
navigation = data.get('navigation_driver') or {}
if (old is None or old[-1, 0] >= 20. or self.seen is None
or now-self.seen <= self.HOLD_S or not 0 <= speed <= 3.
or (navigation.get('enabled') and navigation.get('allowed_for_gameplay') is not True)
or x.shape != (33,) or y.shape != (33,) or std.shape != (33, 15)
or not all(np.isfinite(v).all() for v in (x, y, std))):
raise ValueError('No exhausted corridor reacquisition')
end = 1
while end < len(x) and x[end] > x[end-1]+1e-4:
end += 1
if x[0] > 3. or x[end-1] < 20.:
raise ValueError('Short current path')
grid = np.array([3., 10., 20.])
center = np.interp(grid, points[:, 0], points[:, 1])
if (abs(center[0]) > .65
or np.max(np.abs(np.interp(grid, x[:end], y[:end])-center)) > .5
or np.max(np.interp(grid, x[:end], std[:end, 1])) > .75):
raise ValueError('Current path and lane disagree')
if hasattr(perception, 'road_edges'):
ex = np.asarray(getattr(perception, 'road_edge_x', X_IDXS), float)
edges, sigma = (np.asarray(getattr(perception, k), float)
for k in ('road_edges', 'road_edge_std'))
if (ex.shape != (33,) or edges.shape != (2, 33, 2) or sigma.shape != (2, 33, 2)
or not all(np.isfinite(v).all() for v in (ex, edges, sigma))
or np.any(np.diff(ex) <= 0) or np.any(sigma < 0)):
raise ValueError('Invalid road edge evidence')
lo, hi = (np.interp(grid, ex, edges[i, :, 0]) for i in range(2))
uncertainty = np.maximum(*(np.interp(grid, ex, sigma[i, :, 0]) for i in range(2)))
if np.max(uncertainty) <= 1. and np.any(np.minimum(center-lo, hi-center)-uncertainty < .2):
raise ValueError('Current lane approaches a confident road edge')
p, basis = pose
world = points@basis+p
stable = (self.reacquire_at is not None and 0 < now-self.reacquire_at <= .5
and self.reacquire_world.shape == world.shape
and np.max(np.linalg.norm(world-self.reacquire_world, axis=1)) <= .35)
if not stable:
self.reacquire_since, self.reacquire_count = now, 0
self.reacquire_world, self.reacquire_at = world, now
self.reacquire_count += 1
return self.reacquire_count >= 3 and now-self.reacquire_since >= .3
except (KeyError, AttributeError, TypeError, ValueError, IndexError):
self.reacquire_world = self.reacquire_since = self.reacquire_at = None
self.reacquire_count = 0
return False
@classmethod
def _safe_laneless_fallback(cls, perception, data):
"""Return evidence for continuing on a bounded model path.
Four line slots are useful when present, but they are not guaranteed
to survive the Tesla Semi cabin projection or a bright/occluded
frame. When GPS has already admitted the current road, a short,
nearly centred Pop path is stronger evidence than a synthetic
straight line. The returned path is still the model's measured path;
this method never extrapolates it or creates a new corridor.
"""
navigation = data.get('navigation_driver') if isinstance(data, dict) else None
if not isinstance(navigation, dict) or navigation.get('allowed_for_gameplay') is not True:
return None
if navigation.get('navigation_phase') in ('manual-junction', 'route-uncertain'):
return None
speed = data.get('speed_mps')
if isinstance(speed, bool) or not isinstance(speed, (int, float)) or not np.isfinite(speed):
return None
if speed < 0 or speed > cls.LANELESS_MAX_SPEED_MPS:
return None
try:
x = np.asarray(perception.plan.x, dtype=float)
y = np.asarray(perception.plan.y, dtype=float)
std = np.asarray(perception.plan_std, dtype=float)
if (x.shape != (33,) or y.shape != (33,) or std.shape[0] != 33
or std.shape[1] < 2 or not np.isfinite(x).all()
or not np.isfinite(y).all() or not np.isfinite(std).all()):
return None
end = 1
while end < len(x) and x[end] > x[end - 1] + 1e-4:
end += 1
x, y, std = x[:end], y[:end], std[:end]
# Pop's forecast horizon contracts while the truck is slowing.
# Requiring the full highway horizon at crawl speed creates a
# feedback loop: a valid short path is rejected, braking starts,
# the horizon contracts further, and the truck never pulls away.
horizon = min(18., float(x[-1]))
minimum_horizon = (18. if speed > 8. else
8. if speed > 3. else 3.)
if x[0] < 0 or horizon < minimum_horizon:
return None
sample = np.array([max(1., min(5., horizon*.33)),
max(2., min(10., horizon*.66)), horizon])
lateral = np.interp(sample, x, y)
uncertainty = np.interp(sample, x, std[:, 1])
# Once the truck is already below queue speed, the model's far
# horizon is naturally noisier. A centred, GPS-agreed path may
# continue at a crawl through that dropout; requiring the normal
# highway uncertainty limit here was the feedback loop that drove
# the previous implementation all the way to zero.
uncertainty_limit = (2.0 if speed <= 12.0 else
cls.LANELESS_MAX_PATH_STD_M)
if (not np.isfinite(lateral).all() or not np.isfinite(uncertainty).all()
or np.any(np.abs(lateral) > np.array([1.4, 1.7, 2.2]))
or np.max(uncertainty) > uncertainty_limit):
return None
# Do not carry a path whose first 18 m already point across a
# route branch. The navigation assessor supplies this error only
# after checking the fresh native node pair.
heading = math.degrees(math.atan2(float(lateral[-1] - lateral[0]), 13.))
evidence = navigation.get('direction_evidence')
route_error = evidence.get('model_error_deg') if isinstance(evidence, dict) else None
route_limit = (cls.LANELESS_CRAWL_HEADING_ERROR_DEG if speed <= 3.
else 8. if speed <= 8. else cls.LANELESS_MAX_HEADING_ERROR_DEG)
if (not isinstance(route_error, (int, float)) or not np.isfinite(route_error)
or abs(float(route_error)) > route_limit):
return None
if abs(heading) > cls.LANELESS_MAX_HEADING_ERROR_DEG:
return None
# Edges are a guard against silently treating a shoulder as a
# lane. Missing edge telemetry is not promoted to a pass.
edge_std = np.asarray(getattr(perception, 'road_edge_std', None), dtype=float)
# Some replay frames and older WMI payloads carry edge confidence
# without the matching coordinate vector. The edge tensor uses
# the same fixed 33-point horizon as the model plan; using the
# plan's truncated x array here can pair far-horizon coordinates
# with near-horizon confidence and reject a valid path.
edge_x = np.asarray(getattr(perception, 'road_edge_x', X_IDXS), dtype=float)
if edge_std.shape != (2, 33, 2) or edge_x.shape != (33,):
return None
edge_window = edge_std[:, (edge_x >= 0) & (edge_x <= horizon), 0]
edge_limit = 3.0 if speed <= 3. else 2.25
if (not edge_window.size or not np.isfinite(edge_window).all()
or float(np.max(edge_window)) > edge_limit):
return None
return dict(strategy='gps-guided-model-laneless', lane_tracking=False,
brake_required=False, road_lost=False, corridor_age_s=None,
laneless_fallback=True,
laneless_evidence=dict(speed_mps=float(speed),
max_path_std_m=float(np.max(uncertainty)),
path_std_limit_m=float(uncertainty_limit),
lateral_samples_m=lateral.tolist(),
heading_deg=float(heading),
route_error_deg=float(route_error),
route_error_limit_deg=float(route_limit),
edge_std_limit_m=float(edge_limit),
horizon_m=float(horizon)))
except (AttributeError, TypeError, ValueError, IndexError):
return None
def assess(self, perception, data, now):
navigation, change = data.get('navigation_driver') or {}, data.get('lane_change_driver') or {}
if ((change.get('active') is True and change.get('allowed_for_gameplay') is True)
or navigation.get('path_override') is not None):
self.reset()
return perception, dict(strategy='validated-selected-path', lane_tracking=False, brake_required=False)
pose = self.pose(data)
old = self.projected(pose)
candidates = self.candidates(perception)
accepted = None
reacquired = False
if pose is not None and len(candidates) == 1:
key, points = candidates[0]
continuous = True
if self.world is not None:
if old is None or old[0, 0] > 3 or old[-1, 0] < 20:
continuous = False
else:
grid = np.array([3., 10., 20.])
delta = np.interp(grid, points[:, 0], points[:, 1])-np.interp(grid, old[:, 0], old[:, 1])
continuous = bool(np.max(np.abs(delta)) <= .65)
if continuous:
if self.world is not None:
accepted = points
else:
if key != self.candidate:
self.candidate, self.candidate_since, self.count = key, now, 0
self.count += 1
if self.count >= 3 and now-self.candidate_since >= .1:
accepted = points
else:
self.candidate = None
self.count = 0
if self._reacquire_consumed_lane(perception, data, now, pose, old, points):
accepted, reacquired = points, True
else:
self.candidate = None
self.count = 0
if accepted is not None:
p, basis = pose
self.world = accepted@basis+p
self.seen, self.lost = now, False
self.verified_route_revision = self._fresh_route(data, now)
speed = data.get('speed_mps')
self.observed_speed_mph = (float(speed)*2.2369362921 if isinstance(speed, (int, float))
and np.isfinite(speed) and speed >= 0 else None)
return self.selected(perception, accepted), dict(strategy='observed-ego-lane',
lane_tracking=True, brake_required=False, corridor_age_s=0.,
consumed_corridor_reacquired=reacquired,
near_center_y_m=float(np.interp(3., accepted[:, 0], accepted[:, 1])))
if self.seen is not None:
age = now-self.seen
recovery = self._temporary_recovery(perception, data, now, old, candidates)
if recovery is not None:
self.lost = False
return self.selected(perception, old), recovery
held = bool(old is not None and 0 <= age <= self.HOLD_S and old[0, 0] <= 3 and old[-1, 0] >= 15)
self.lost = not held
if not held:
fallback = self._safe_laneless_fallback(perception, data)
if fallback is not None:
fallback['corridor_age_s'] = age
return perception, fallback
straight=np.array([[0.,0.],[30.,0.]])
return self.selected(perception, old if held else straight), dict(
strategy='motion-propagated-ego-lane' if held else 'road-lost-braking',
lane_tracking=held, brake_required=age > .35 or not held,
corridor_age_s=age, road_lost=not held)
# Laneless model following remains available. Do not treat mere paint
# loss as failure, but reject the large uncertain path seen off-road.
implausible = False
try:
x, y = (np.asarray(getattr(perception.plan, k), float) for k in ('x', 'y'))
std = np.asarray(perception.plan_std, float)
implausible = bool(abs(np.interp(10., x, y)) > 2.5 and np.max(std[(x >= 0) & (x <= 20), 1]) > .5)
except (AttributeError, TypeError, ValueError, IndexError):
pass
return (self.selected(perception,np.array([[0.,0.],[30.,0.]])) if implausible else perception), dict(strategy='road-lost-braking' if implausible else 'model-laneless',
lane_tracking=False, brake_required=implausible, road_lost=implausible)
-213
View File
@@ -1,213 +0,0 @@
"""Passive authored-path/model-corridor comparison, never driving permission.
Authored prefab paths use forward/left/up; scene-aligned observations use
forward/right/down. This comparison is estimated because the model boundaries
and final camera extrinsics are unverified. No painted lane identity, right of
way, signal state, obstacle clearance or actuator command is established here.
"""
import math
import re
import numpy as np
DECODER_COMMIT = 'e853797bec3620659f14811d70ceea213399b83d'
HORIZON = (5., 30.)
GRID = np.arange(5., 30.01, 1.)
def _fresh(value):
age = value.get('age_s') if isinstance(value, dict) else None
return type(age) in (int, float) and math.isfinite(age) and 0 <= age <= .5
def unavailable(reason):
return dict(available=False, reason=reason, estimated=True, display_only=True,
usable_for_control=False, matched_slot_id=None, candidates=[],
ambiguity=False, route_revision=None, coverage_m=list(HORIZON),
painted_lane_identity_verified=False, clear_lane_verified=False,
traffic_rules_verified=False,
source='directed GPS UID pair + authored AI center + observed model corridor',
thresholds=dict(boundary_margin_m=.3, max_vertical_residual_m=.6,
max_direction_difference_rad=.25,
max_grade_difference=.06, max_sample_gap_m=12.),
limitation='Estimated geometric association; final render extrinsics, paint identity and driving permission unverified')
def junction_handling_preview(geometry):
"""A nearby authored junction is a manual-handling requirement, not a rule."""
nearby = (isinstance(geometry, dict) and geometry.get('context_available') is True
and _fresh(geometry) and isinstance(geometry.get('junctions'), list)
and bool(geometry['junctions']))
return dict(available=bool(nearby), nearby_junction=bool(nearby),
manual_required=True if nearby else None,
status='manual-required' if nearby else 'junction-context-unavailable',
reason=('Nearby map junction; autonomous junction handling unverified' if nearby
else 'No fresh verified nearby junction context'),
stop_requirement='unknown', right_of_way='unknown',
traffic_rules_verified=False, clearance_verified=False,
display_only=True, usable_for_control=False)
def _validate_provenance(path):
source = path.get('provenance')
if not isinstance(source, dict):
raise ValueError('Authored asset provenance unavailable')
asset = source.get('asset_path')
digest = source.get('asset_sha256')
if (not isinstance(asset, str) or not asset.startswith('/prefab/') or not asset.endswith('.ppd')
or not isinstance(digest, str) or not re.fullmatch('[0-9a-f]{64}', digest)
or type(source.get('ppd_version')) is not int or source['ppd_version'] not in (24, 25)):
raise ValueError('Unsupported authored asset provenance')
for key, limit in (('attachment_error_m', .25), ('attachment_height_error_m', .5)):
error = source.get(key)
if type(error) not in (int, float) or not math.isfinite(error) or not 0 <= error <= limit:
raise ValueError('Authored placement attachment error unverified')
curves = path.get('curve_indices')
lane = path.get('input_lane_index')
if (type(lane) is not int or not 0 <= lane < 64 or not isinstance(curves, list)
or not 1 <= len(curves) <= 128
or any(type(index) is not int or not 0 <= index < 65536 for index in curves)):
raise ValueError('Authored input lane/curve identity unavailable')
def _path_samples(path):
points = np.asarray(path.get('points'), dtype=float)
if (points.ndim != 2 or points.shape[1] != 3 or not 6 <= len(points) <= 8192
or not np.all(np.isfinite(points)) or np.any(np.abs(points) > 10000)):
raise ValueError('Invalid authored path point array')
# Adjacent authored curves repeat an identical join. Only that exact join
# is removed; lateral/height jumps at equal forward position are rejected.
points = points[np.r_[True, np.any(np.abs(np.diff(points, axis=0)) > 1e-6, axis=1)]]
if len(points) < 6 or np.min(points[:, 0]) > HORIZON[0] or np.max(points[:, 0]) < HORIZON[1]:
raise ValueError('Authored path lacks measured 5–30 m coverage')
# A complete route can curve behind the truck outside our horizon. Use one
# unique contiguous traversal of the measured span, never join separate
# visits, or accept a reverse/sideways segment inside that span.
segments = np.flatnonzero((np.maximum(points[:-1, 0], points[1:, 0]) > HORIZON[0])
& (np.minimum(points[:-1, 0], points[1:, 0]) < HORIZON[1]))
if (not len(segments) or np.any(np.diff(segments) != 1)
or np.any(np.diff(points[:, 0])[segments] <= 1e-6)):
raise ValueError('Authored path reverses, folds or revisits the comparison horizon')
points = points[segments[0]:segments[-1]+2]
if points[0, 0] > HORIZON[0] or points[-1, 0] < HORIZON[1]:
raise ValueError('Authored path lacks contiguous measured 5–30 m coverage')
# Include the two enclosing samples in the gap check, never extrapolate.
first = max(0, int(np.searchsorted(points[:, 0], HORIZON[0], side='right'))-1)
last = min(len(points)-1, int(np.searchsorted(points[:, 0], HORIZON[1])))
if np.any(np.diff(points[first:last+1, 0]) > 12):
raise ValueError('Authored path has a gap across the comparison horizon')
# Coordinate conversion: authored left/up become model right/down.
return np.array([np.interp(GRID, points[:, 0], -points[:, axis]) for axis in (1, 2)])
def route_corridor_association(x, ys, zs, slots, route, paths, telemetry, geometry):
"""Return candidate evidence; one match remains estimated and display-only."""
result = unavailable('Fresh aligned, unobstructed model evidence required')
if not (isinstance(telemetry, dict) and telemetry.get('valid') is True
and not telemetry.get('paused') and telemetry.get('model_obstructed') is False
and telemetry.get('model_geometry_stale') is not True
and isinstance(telemetry.get('scene_alignment'), dict)
and telemetry['scene_alignment'].get('available') is True
and _fresh(dict(age_s=telemetry.get('model_age_s')))):
return result
obstruction = telemetry.get('camera_obstruction')
if obstruction is not None and (not isinstance(obstruction, dict)
or obstruction.get('checked') is not True or obstruction.get('blocked') is not False):
return dict(result, reason='Camera obstruction gate not verified clear')
if not (isinstance(route, dict) and route.get('available') is True and _fresh(route)
and isinstance(geometry, dict) and geometry.get('route_context_verified') is True
and geometry.get('context_available') is True and _fresh(geometry)):
return dict(result, reason='Fresh verified directed GPS/map context required')
if not (isinstance(paths, dict) and paths.get('available') is True and _fresh(paths)
and paths.get('source') == 'ATS authored prefab AI paths'
and paths.get('geometry_kind') == 'authored-ai-lane-centers'
and paths.get('decoder_commit') == DECODER_COMMIT
and paths.get('usable_for_control') is False):
return dict(result, reason='Fresh pinned authored prefab path provenance required')
try:
nodes = route.get('nodes')
if not isinstance(nodes, list) or not 2 <= len(nodes) <= 1024:
raise ValueError('Invalid directed GPS endpoint list')
for node in nodes:
if (not isinstance(node.get('uid'), (str, int)) or not str(node['uid'])
or len(node['position']) != 3
or not all(type(v) in (int, float) and math.isfinite(v) for v in node['position'])):
raise ValueError('Invalid directed GPS endpoint identity or position')
pairs = {(str(a['uid']), str(b['uid'])) for a, b in zip(nodes, nodes[1:])}
# Require the same explicit route pair in fresh map context too. The
# path's cached route_match flag alone cannot survive a route revision.
map_pairs = {(str(j['prefab_uid']), str(link['start_node_uid']), str(link['end_node_uid']))
for j in geometry.get('junctions', [])[:4] for link in j.get('route_links', [])}
result['route_revision'] = route.get('revision')
if x[0] > HORIZON[0] or x[-1] < HORIZON[1]:
return dict(result, reason='Observed boundaries lack measured 5–30 m coverage')
first = max(0, int(np.searchsorted(x, 5., side='right'))-1)
last = min(len(x)-1, int(np.searchsorted(x, 30.)))
if np.any(np.diff(x[first:last+1]) > 12):
return dict(result, reason='Observed boundary samples have an unsupported forward gap')
raw = paths.get('paths')
if not isinstance(raw, list) or len(raw) > 512:
raise ValueError('Invalid bounded authored path list')
matched = []
seen = set()
duplicate_identity = False
for path in raw:
if not isinstance(path, dict) or path.get('route_match') is not True:
continue
pair = (str(path.get('start_node_uid')), str(path.get('end_node_uid')))
prefab = str(path.get('prefab_uid'))
evidence = dict(prefab_uid=prefab, start_node_uid=pair[0], end_node_uid=pair[1],
input_lane_index=path.get('input_lane_index'),
curve_indices=path.get('curve_indices'), comparisons=[], fits=False, reason='')
result['candidates'].append(evidence)
try:
if pair not in pairs or (prefab, *pair) not in map_pairs:
raise ValueError('Authored path does not match current directed GPS/map UID pair')
_validate_provenance(path)
identity = (prefab, *pair, path['input_lane_index'], tuple(path['curve_indices']))
if identity in seen:
duplicate_identity = True
raise ValueError('Duplicate authored path identity')
seen.add(identity)
sampled = _path_samples(path)
for slot in slots:
left, right = slot['left_boundary_index'], slot['right_boundary_index']
low, high = np.interp(GRID, x, ys[left]), np.interp(GRID, x, ys[right])
center = (low+high)*.5
down = (np.interp(GRID, x, zs[left])+np.interp(GRID, x, zs[right]))*.5
margin = np.minimum(sampled[0]-low, high-sampled[0])
direction_error = np.abs(np.arctan(np.diff(sampled[0]))-np.arctan(np.diff(center)))
grade_error = np.abs(np.diff(sampled[1])-np.diff(down))
vertical_error = np.abs(sampled[1]-down)
reasons = []
if np.min(margin) < .3:
reasons.append('Authored center crosses or approaches observed boundary')
if np.max(direction_error) > .25 or np.max(np.abs(np.diff(sampled[0]))) > .65:
reasons.append('Forward direction differs or path turn exceeds comparison range')
if np.max(vertical_error) > .6 or np.max(grade_error) > .06:
reasons.append('Road grade or height differs from observed corridor')
comparison = dict(slot_id=slot['slot_id'], fits=not reasons, reason='; '.join(reasons),
min_boundary_margin_m=float(np.min(margin)),
max_center_residual_m=float(np.max(np.abs(sampled[0]-center))),
max_vertical_residual_m=float(np.max(vertical_error)),
max_direction_difference_rad=float(np.max(direction_error)),
max_grade_difference=float(np.max(grade_error)),
measured_coverage_m=list(HORIZON))
evidence['comparisons'].append(comparison)
if not reasons:
matched.append((identity, slot['slot_id']))
evidence['fits'] = any(item['fits'] for item in evidence['comparisons'])
if not evidence['fits']:
evidence['reason'] = 'No observed corridor fits throughout measured 5–30 m horizon'
except (KeyError, TypeError, ValueError, OverflowError) as exc:
evidence['reason'] = str(exc)
if duplicate_identity:
return dict(result, reason='Duplicate authored path identity; association ambiguous', ambiguity=True)
if len(matched) == 1:
return dict(result, available=True, reason='', matched_slot_id=matched[0][1])
if len(matched) > 1:
return dict(result, reason='Multiple authored paths/corridors fit; route association ambiguous', ambiguity=True)
return dict(result, reason='No uniquely supported authored route/observed corridor association')
except (KeyError, TypeError, ValueError, OverflowError, IndexError) as exc:
return dict(result, reason=str(exc))
-292
View File
@@ -1,292 +0,0 @@
"""Observed model corridors, measured actor overlap and GPS attachment hints.
This module is display-only. A corridor between two observed lines is not a
verified map lane, an empty actor list is not clearance, and a GPS attachment
does not tell us which lane reaches it. No controller or input modules exist here.
"""
import math
import numpy as np
from control.junction_association import (junction_handling_preview,
route_corridor_association,
unavailable as association_unavailable)
def _get(value, key):
return value.get(key) if isinstance(value, dict) else getattr(value, key, None)
def _fresh(report):
age = report.get('age_s') if isinstance(report, dict) else None
return (isinstance(age, (int, float)) and math.isfinite(age) and 0 <= age <= .5)
def _area(polygon):
return abs(sum(a[0]*b[1]-b[0]*a[1] for a, b in
zip(polygon, polygon[1:]+polygon[:1])))*.5 if len(polygon) >= 3 else 0.
def _intersection(polygon, boundary):
"""Clip a measured rectangle against one ordered lane trapezoid."""
for a, b in zip(boundary, boundary[1:]+boundary[:1]):
if not polygon:
break
def side(point):
return (b[0]-a[0])*(point[1]-a[1])-(b[1]-a[1])*(point[0]-a[0])
clipped = []
for p, q in zip(polygon, polygon[1:]+polygon[:1]):
sp, sq = side(p), side(q)
if sp >= 0:
clipped.append(p)
if (sp >= 0) != (sq >= 0):
fraction = sp/(sp-sq)
clipped.append((p[0]+fraction*(q[0]-p[0]), p[1]+fraction*(q[1]-p[1])))
polygon = clipped
return polygon
def _footprint(actor):
values = [float(actor[key]) for key in
('forward_m', 'left_m', 'length_m', 'width_m', 'heading_delta_rad')]
forward, left, length, width, yaw = values
if (not all(math.isfinite(value) for value in values) or
not .2 <= length <= 60 or not .2 <= width <= 8):
raise ValueError('Invalid measured actor footprint')
cosine, sine = math.cos(yaw), math.sin(yaw)
# Model coordinates are forward/right; actor coordinates are forward/left.
return [(forward+cosine*f-sine*l, -(left+sine*f+cosine*l))
for f, l in ((length/2, width/2), (length/2, -width/2),
(-length/2, -width/2), (-length/2, width/2))]
def _branch_hint(geometry, route):
if not (isinstance(geometry, dict) and geometry.get('context_available')
and geometry.get('route_context_verified') and isinstance(route, dict)
and route.get('available') and _fresh(route)):
return dict(available=False, reason='Fresh verified map/GPS attachment match unavailable')
try:
nodes = route['nodes']
if not isinstance(nodes, list) or not 2 <= len(nodes) <= 1024:
raise ValueError('Invalid GPS endpoint list')
if any(len(node['position']) != 3 or not all(math.isfinite(value) for value in node['position'])
for node in nodes):
raise ValueError('Invalid GPS endpoint positions')
if geometry.get('age_s') is not None and not _fresh(geometry):
raise ValueError('Stale road geometry context')
pairs = {(str(a['uid']), str(b['uid'])) for a, b in zip(nodes, nodes[1:])}
hints = []
for junction in geometry.get('junctions', []):
attachments = junction.get('attachments', [])
for link in junction.get('route_links', []):
start, end = str(link['start_node_uid']), str(link['end_node_uid'])
if (start, end) not in pairs:
continue
incoming = [a for a in attachments if str(a['node_uid']) == start and a['incoming_lanes'] > 0]
outgoing = [a for a in attachments if str(a['node_uid']) == end and a['outgoing_lanes'] > 0]
if not incoming or not outgoing:
continue
# Retain actual endpoints and counts, never connect unknown
# prefab interior curves or infer a turn lane from lane counts.
hints.append(dict(prefab_uid=junction['prefab_uid'], from_node_uid=start,
to_node_uid=end, incoming_road_uids=[a['road_uid'] for a in incoming],
outgoing_road_uids=[a['road_uid'] for a in outgoing],
outgoing_lane_counts=[a['outgoing_lanes'] for a in outgoing],
outgoing_endpoints=[a['endpoint'] for a in outgoing],
route_revision=route.get('revision'), lane_mapping_verified=False))
return dict(available=bool(hints), reason='' if hints else 'No exact directed GPS junction attachment pair',
source='verified map attachments and directed GPS UID pairs',
attachments=hints, interior_path_verified=False, usable_for_control=False)
except (KeyError, TypeError, ValueError):
return dict(available=False, reason='Invalid map/GPS junction attachment evidence')
def _authored_route_lanes(paths, route):
if not (isinstance(paths, dict) and paths.get('available') and isinstance(route, dict)
and route.get('available') and _fresh(route)):
return []
if paths.get('age_s') is not None and not _fresh(paths):
return []
try:
if (not isinstance(route.get('nodes'), list) or not 2 <= len(route['nodes']) <= 1024
or any(len(node['position']) != 3 or not all(math.isfinite(value) for value in node['position'])
for node in route['nodes'])):
return []
pairs = {(str(a['uid']), str(b['uid'])) for a, b in zip(route['nodes'], route['nodes'][1:])}
result = []
for item in paths.get('route_lanes', []):
pair = str(item['start_node_uid']), str(item['target_node_uid'])
indices = item['input_lane_indices']
if (pair not in pairs or not isinstance(indices, list) or not indices
or any(type(index) is not int or not 0 <= index < 64 for index in indices)):
continue
result.append(dict(prefab_uid=item['prefab_uid'], start_node_uid=pair[0],
target_node_uid=pair[1], input_lane_indices=sorted(set(indices)),
observed_corridor_alignment_verified=False))
return result
except (KeyError, TypeError, ValueError):
return []
def lane_choice_preview(lanes, traffic, geometry, route=None, telemetry=None, junction_paths=None):
"""Assess factual forward corridor occupancy; never recommend a driving lane."""
result = dict(available=False, reason='', display_only=True, usable_for_control=False,
complete_coverage=False, clear_lane_verified=False, observed_slots=[],
current_slot=None, current_slot_available=False, route_lane_choice_available=False,
current_slot_reference='zero lateral in near forward model samples; not map lane membership',
route_lane_choice_reason='Exact route-to-observed-lane mapping is unavailable',
recommended_slot=None, branch_hint=_branch_hint(geometry, route),
authored_route_lanes=_authored_route_lanes(junction_paths, route),
authored_route_lane_indices_available=False,
route_corridor_association=association_unavailable('Observed corridor evidence unavailable'),
junction_handling=junction_handling_preview(geometry),
actor_assessments=[], traffic_assessment_available=False,
traffic_reason='Fresh tracked simulator actor report required',
source='forward model boundaries + measured ATS actors',
map_lane_counts=(geometry.get('lane_counts') if isinstance(geometry, dict)
and geometry.get('available')
and (geometry.get('age_s') is None or _fresh(geometry)) else None),
map_lane_membership_verified=False,
actor_road_level_tolerance_m=2.,
limitations=['Observed corridors have unverified travel direction and map lane identity',
'Forward model geometry is never extrapolated behind the truck',
'Missing loaded actors do not establish lane clearance',
'Upright height approximation leaves substantial grades/overpasses unassessed',
'GPS attachments do not establish route-to-lane connectivity'])
if result['authored_route_lanes']:
result['authored_route_lane_indices_available'] = True
result['route_lane_choice_reason'] = 'Authored route lane indices available; model corridor alignment unverified'
if telemetry is not None and (not telemetry.get('valid') or telemetry.get('paused')):
return dict(result, reason='Fresh, unpaused perception context required',
branch_hint=dict(available=False, reason='Truck telemetry unavailable'),
authored_route_lanes=[], authored_route_lane_indices_available=False)
if telemetry is not None and telemetry.get('model_age_s') is not None:
age = telemetry['model_age_s']
if not isinstance(age, (int, float)) or not math.isfinite(age) or not 0 <= age <= .5:
return dict(result, reason='Model boundary sample stale')
try:
x = np.asarray(_get(lanes, 'x'), dtype=float)
ys = np.asarray(_get(lanes, 'all_y'), dtype=float)
zs = np.asarray(_get(lanes, 'all_z'), dtype=float)
probabilities = np.asarray(_get(lanes, 'probabilities'), dtype=float)
if (x.ndim != 1 or len(x) < 3 or ys.shape != (4, len(x)) or zs.shape != ys.shape
or probabilities.shape != (4,) or not np.all(np.isfinite(x))
or not np.all(np.isfinite(ys)) or not np.all(np.isfinite(zs))
or not np.all(np.isfinite(probabilities)) or np.any(np.diff(x) <= 0)
or np.any((probabilities < 0) | (probabilities > 1))):
return dict(result, reason='Four-line model observations invalid or unavailable')
start, end = max(3., float(x[0])), min(40., float(x[-1]))
if start > 6 or end < 20 or sum((x >= start) & (x <= end)) < 3:
return dict(result, reason='Model boundaries lack a useful near-to-forward horizon')
grid = np.unique(np.r_[start, x[(x > start) & (x < end)], end])
interpolated = [np.interp(grid, x, line) for line in ys]
confident = np.flatnonzero(probabilities >= .55)
if any(np.any(interpolated[a] >= interpolated[b]-.3)
for a, b in zip(confident, confident[1:])):
return dict(result, reason='Confident model boundaries cross or are out of order')
slots = []
rejected = []
for left in range(3):
right = left+1
if min(probabilities[left], probabilities[right]) < .55:
continue
lo, hi = interpolated[left], interpolated[right]
widths = hi-lo
if (np.any(np.abs(lo) > 25) or np.any(np.abs(hi) > 25)
or np.any(widths < 2.3) or np.any(widths > 5.5)
or np.ptp(widths) > 1.5):
rejected.append([left, right])
continue
near = grid <= 6
contains_zero = bool(np.all(lo[near] < -.15) and np.all(hi[near] > .15))
slots.append(dict(slot_id=f'model-{left}-{right}', left_boundary_index=left,
right_boundary_index=right, confidence=float(min(probabilities[left], probabilities[right])),
forward_range_m=[start, end], width_min_m=float(min(widths)),
width_max_m=float(max(widths)), contains_ego_zero_nearby=contains_zero,
map_lane_index=None, travel_direction_verified=False,
boundaries=[dict(forward_m=float(g), left_y_m=float(l), right_y_m=float(h))
for g, l, h in zip(grid, lo, hi)],
observed_actor_ids=[], occupancy_status='unassessed',
occupancy_complete=False, clear_lane_verified=False))
result['rejected_boundary_pairs'] = rejected
result['confident_boundary_indices'] = [int(i) for i in np.flatnonzero(probabilities >= .55)]
result['observed_slots'] = slots
if not slots:
return dict(result, reason='No adjacent confident boundaries form a stable forward corridor')
current = [slot['slot_id'] for slot in slots if slot['contains_ego_zero_nearby']]
if len(current) == 1:
result.update(current_slot=current[0], current_slot_available=True)
result.update(available=True, reason='', forward_range_m=[start, end])
result['route_corridor_association'] = route_corridor_association(
x, ys, zs, slots, route, junction_paths, telemetry, geometry)
if not (isinstance(traffic, dict) and traffic.get('available') and _fresh(traffic)
and traffic.get('tracking') and isinstance(traffic.get('actors'), list)):
return result
result.update(traffic_assessment_available=True, traffic_reason='')
for slot in slots:
slot['occupancy_status'] = 'no observed overlap; coverage incomplete'
for actor in traffic['actors'][:500]:
if not isinstance(actor, dict):
result['traffic_reason'] = 'Some actor footprint evidence unavailable'
continue
samples = actor.get('sample_count', 0)
assessment = dict(id=actor.get('id'), observed_slot_ids=[], assessed=False,
reason='', continuity_verified=isinstance(samples, int) and samples >= 2,
motion_available=bool(actor.get('motion_available')))
result['actor_assessments'].append(assessment)
try:
actor_age = actor.get('measured_age_s', traffic['age_s'])
if not isinstance(actor_age, (int, float)) or not math.isfinite(actor_age) or not 0 <= actor_age <= .5:
assessment['reason'] = 'Actor measurement stale'
continue
polygon = _footprint(actor)
if float(actor['forward_m']) <= 0:
assessment['reason'] = 'Rear actor: model lane geometry unavailable'
continue
if max(p[0] for p in polygon) < start or min(p[0] for p in polygon) > end:
assessment['reason'] = 'Actor outside observed forward horizon'
continue
actor_position = actor.get('world_position')
ego_position = telemetry.get('world_position') if isinstance(telemetry, dict) else None
height = actor.get('height_m')
if (not isinstance(actor_position, (list, tuple)) or len(actor_position) != 3
or not isinstance(ego_position, (list, tuple)) or len(ego_position) != 3
or not all(isinstance(v, (int, float)) and math.isfinite(v)
for v in (*actor_position, *ego_position))
or not isinstance(height, (int, float)) or not math.isfinite(height)
or not .2 <= height <= 60):
assessment['reason'] = 'Measured actor/ego road-height qualification unavailable'
result['traffic_reason'] = 'Actor road-height qualification incomplete'
for slot in slots:
if not slot['observed_actor_ids']:
slot['occupancy_status'] = 'unassessed actor road level; coverage incomplete'
continue
base_height = actor_position[1]-height*.5
level_error = abs(base_height-ego_position[1])
assessment.update(road_level_error_m=level_error,
road_level_method='upright center minus half-height against SDK ego height')
if level_error > 2:
assessment['reason'] = 'Relative road level differs; grade/overpass occupancy unverified'
continue
assessment.update(assessed=True,
coverage='partial' if min(p[0] for p in polygon) < start or max(p[0] for p in polygon) > end else 'forward footprint',
reason='Measured footprint against forward model corridors; not map-lane assignment')
for slot in slots:
bounds = slot['boundaries']
overlap = 0.
for a, b in zip(bounds, bounds[1:]):
if b['forward_m'] < min(p[0] for p in polygon) or a['forward_m'] > max(p[0] for p in polygon):
continue
trapezoid = [(a['forward_m'], a['left_y_m']), (b['forward_m'], b['left_y_m']),
(b['forward_m'], b['right_y_m']), (a['forward_m'], a['right_y_m'])]
overlap += _area(_intersection(polygon, trapezoid))
if overlap > .02:
slot['observed_actor_ids'].append(actor['id'])
slot['occupancy_status'] = 'observed footprint overlap'
assessment['observed_slot_ids'].append(slot['slot_id'])
except (KeyError, TypeError, ValueError, OverflowError):
assessment.update(assessed=False, reason='Invalid measured actor footprint')
result['traffic_reason'] = 'Some actor footprint evidence unavailable'
return result
except (TypeError, ValueError, OverflowError):
return dict(result, reason='Invalid forward corridor evidence')
+18 -3
View File
@@ -42,8 +42,8 @@ class NativeGameplayController:
ROUTE_GAP_HOLD_S = 1.5
ROUTE_GAP_MAX_SPEED_MPS = 2.0
ROUTE_GAP_STOP_TARGET_MPH = 5.0
ROUTE_SOURCE_GAP_HOLD_S = 1.5
ROUTE_SOURCE_GAP_MAX_SPEED_MPS = 18.0
ROUTE_SOURCE_GAP_HOLD_S = .5
ROUTE_SOURCE_GAP_MAX_SPEED_MPS = 80.*.44704
# Small curve/traffic-map target changes should not alternate the pedal
# every control sample. Large drops remain immediate for real stops and
# emergency geometry.
@@ -227,6 +227,19 @@ class NativeGameplayController:
or speed < -self.REVERSE_SPEED_TOLERANCE_MPS
or speed > self.ROUTE_SOURCE_GAP_MAX_SPEED_MPS):
return False
if not 0. <= now-self._last <= self.output_gap_limit_s:
return False
route = data.get('navigation_route') or {}
revision = route.get('route_revision') or route.get('revision')
if revision and revision != self._last_good_plan.get('route_revision'):
return False
previous_distance = self._last_good_plan.get('navigation_distance_m')
distance = number(data.get('navigation_distance_m'))
if (previous_distance is not None and distance is not None
and abs(distance-previous_distance) > max(100.,abs(speed)*10.)):
return False
if self._last_good_plan.get('path_extent_m',0.) < max(15.,speed*self.ROUTE_SOURCE_GAP_HOLD_S):
return False
position = data.get('world_position')
if (not isinstance(position,(list,tuple)) or len(position) != 3
or any(not isinstance(v,(int,float)) or not math.isfinite(v) for v in position)
@@ -546,7 +559,9 @@ class NativeGameplayController:
geometry['native_path_axis'] = geometry['raw_axis']
geometry['raw_axis'] += feedback
self._last_good_plan = dict(route_revision=plan.get('route_revision'),
selected_lane_ids=list(plan.get('selected_lane_ids') or []))
selected_lane_ids=list(plan.get('selected_lane_ids') or []),
path_extent_m=geometry.get('path_extent_m',0.),
navigation_distance_m=number(telemetry.get('navigation_distance_m')))
position = telemetry.get('world_position')
self._last_good_position = list(position) if isinstance(position,(list,tuple)) and len(position)==3 else None
self._route_gap_since = None
-204
View File
@@ -1,204 +0,0 @@
"""Route execution state for the experimental ATS Navigate-on-Autopilot HUD.
The native GPS graph tells us which directed road pair is next. This module
turns that evidence into a small, restartable state machine: it announces an
approach, requests one turn signal pulse, and explicitly hands a junction to
the driver when the map does not contain a verified lane and right-of-way
solution. It has no actuator access. Steering remains owned by the current
Pop path and all existing traffic, focus, and camera gates remain in force.
"""
import math
import numbers
import time
def _number(value):
if isinstance(value, bool) or not isinstance(value, numbers.Real):
return None
value = float(value)
return value if math.isfinite(value) else None
class NavigateOnAutopilot:
"""Keep route maneuvers coherent across noisy GPS/model frames."""
SIGNAL_APPROACH_M = 350.0
MANUAL_JUNCTION_M = 45.0
MAX_AGE_S = .6
def __init__(self, clock=time.monotonic):
self.clock = clock
self.reset()
def reset(self):
self._revision = None
self._bend_key = None
self._signal_sent = False
self._last_phase = 'route-uncertain'
self._last_now = None
@staticmethod
def _report(reason='', **extra):
result = dict(
enabled=True,
available=False,
phase='route-uncertain',
reason=str(reason),
route_revision=None,
next_bend=None,
requested_signal='none',
signal_pulse='none',
signal_active=False,
automatic_signal=False,
lane_change_request=None,
automatic_lane_change=False,
junction_execution='manual-required',
reroute=False,
path_override=None,
speed_cap_mph=None,
experimental=True,
production_eligible=False,
control_eligible=False,
)
result.update(extra)
return result
@staticmethod
def _bend(preview):
if not isinstance(preview, dict) or preview.get('available') is not True:
return None, 'Fresh matched GPS preview required'
bend = preview.get('next_bend')
if bend is None:
return None, ''
if not isinstance(bend, dict):
return None, 'Malformed next GPS bend'
distance = _number(bend.get('distance_m'))
angle = _number(bend.get('angle_deg'))
direction = bend.get('direction')
node = bend.get('node_index')
if (distance is None or angle is None or distance < 0
or direction not in ('left', 'right') or type(node) is not int or node < 1):
return None, 'Malformed next GPS bend'
if abs(angle) < 20 or abs(angle) > 180:
return None, 'GPS bend angle outside supported range'
if (angle < 0) != (direction == 'left'):
return None, 'GPS bend direction/sign disagreement'
return dict(direction=direction, distance_m=distance, angle_deg=angle,
node_index=node, distance_units=bend.get('distance_units',
'ATS advisor metres')), ''
@staticmethod
def _signal_matches(telemetry, direction):
if direction == 'left':
return telemetry.get('blinker_left') is True and telemetry.get('blinker_right') is not True
if direction == 'right':
return telemetry.get('blinker_right') is True and telemetry.get('blinker_left') is not True
return False
@staticmethod
def _lane_request(lane_choice, bend):
"""Convert a future verified lane recommendation into a request.
Current lane-choice reports deliberately leave this unavailable for the
Tesla Semi calibration. Keeping the conversion here makes the runtime
ready for a verified map/corridor association without guessing a lane
from a turn direction today.
"""
if not isinstance(lane_choice, dict) or lane_choice.get('route_lane_choice_available') is not True:
return None
if lane_choice.get('clear_lane_verified') is not True:
return None
current = lane_choice.get('current_slot')
target = lane_choice.get('recommended_slot')
if target is None or current is None or target == current:
return None
direction = lane_choice.get('recommended_direction')
if direction not in ('left', 'right'):
return None
return dict(direction=direction, current_slot=current, target_slot=target,
reason='Verified route lane recommendation and fresh clear-lane evidence')
def assess(self, route, preview, telemetry, *, base_navigation=None,
lane_choice=None, junction_paths=None, now=None):
now = _number(self.clock() if now is None else now)
if now is None or (self._last_now is not None and now < self._last_now):
self.reset()
return self._report('Navigate-on-Autopilot clock unavailable or regressed')
self._last_now = now
if (not isinstance(telemetry, dict) or telemetry.get('valid') is not True
or telemetry.get('paused') is not False
or telemetry.get('navigation_valid') is not True):
return self._report('Fresh unpaused GPS telemetry required')
if not isinstance(route, dict) or route.get('available') is not True:
return self._report(route.get('reason', 'Native GPS route unavailable')
if isinstance(route, dict) else 'Native GPS route unavailable')
sampled = _number(route.get('sampled_at'))
if sampled is None or not -.05 <= now-sampled <= self.MAX_AGE_S:
return self._report('Native GPS route is stale', route_revision=route.get('revision'))
revision = route.get('revision')
if not revision:
return self._report('Native GPS route revision unavailable')
reroute = self._revision is not None and revision != self._revision
if reroute:
# Never carry a signal, lane request, or junction path across a
# changed destination/route array.
self._bend_key = None
self._signal_sent = False
self._revision = revision
bend, reason = self._bend(preview)
if reason:
return self._report(reason, route_revision=revision, reroute=reroute)
base = base_navigation if isinstance(base_navigation, dict) else {}
cap = _number(base.get('route_speed_cap_mph'))
common = dict(route_revision=revision, reroute=reroute,
speed_cap_mph=cap,
route_navigation_phase=base.get('navigation_phase', 'route-cruise'))
if bend is None:
self._bend_key = None
self._signal_sent = False
report = self._report('', available=True, phase='route-cruise',
next_bend=None, requested_signal='none',
signal_active=False, automatic_signal=False,
junction_execution='none', **common)
self._last_phase = report['phase']
return report
bend_key = (revision, bend['node_index'], bend['direction'])
if bend_key != self._bend_key:
self._bend_key = bend_key
self._signal_sent = False
distance = bend['distance_m']
lane_request = self._lane_request(lane_choice, bend)
requested = bend['direction'] if distance <= self.SIGNAL_APPROACH_M else 'none'
pulse = 'none'
if (requested != 'none' and telemetry.get('gameplay_engaged') is True
and not self._signal_sent and not self._signal_matches(telemetry, requested)):
pulse = requested
self._signal_sent = True
if distance <= self.MANUAL_JUNCTION_M:
phase = 'junction'
# Authored prefab paths are display-only until lane boundaries,
# signals and right-of-way are verified. A future verified report
# can supply a path without changing this state-machine contract.
verified_paths = (isinstance(junction_paths, dict)
and junction_paths.get('usable_for_control') is True
and junction_paths.get('complete_coverage') is True
and junction_paths.get('traffic_rules_verified') is True)
junction_execution = 'authored-path' if verified_paths else 'manual-required'
if junction_execution == 'manual-required':
lane_request = None
elif lane_request is not None:
phase = 'prepare-lane'
junction_execution = 'lane-change-requested'
else:
phase = 'signal-approach' if requested != 'none' else 'route-cruise'
junction_execution = 'none'
report = self._report('', available=True, phase=phase, next_bend=bend,
requested_signal=requested, signal_pulse=pulse,
signal_active=requested != 'none',
automatic_signal=requested != 'none',
lane_change_request=lane_request,
automatic_lane_change=lane_request is not None,
junction_execution=junction_execution, **common)
self._last_phase = phase
return report
-198
View File
@@ -1,198 +0,0 @@
"""Bounded GPS-assisted camera trajectory selection for an ATS trial.
The GPS graph selects a direction; it is never a steering centerline. This
planner has no actuator APIs and does not establish intersection right-of-way.
"""
import math
import time
import numpy as np
from control.path_preview import path_reason
class NavigationDriver:
MAX_SPEED_MPH = 15.0
MAX_STEER = .25
MAX_STEER_RATE = .25
def __init__(self, clock=time.monotonic):
self.clock = clock
self.reset()
def reset(self):
self.current_steer = 0.0
self._last_time = None
self._path_history = []
self._revision = None
def _stop(self, reason):
self.reset()
return dict(allowed=False, strategy='manual', steer=0.0,
max_speed_mph=self.MAX_SPEED_MPH, reason=reason,
obstacles_verified=False, intersection_clearance_verified=False)
@staticmethod
def _lanes(perception, lookahead):
lanes = perception.lanes
arrays = (lanes.x, lanes.left_y, lanes.right_y)
if any(np.shape(a) != (33,) or not np.all(np.isfinite(a)) for a in arrays):
return None, 'Invalid model lane geometry'
if lanes.x[0] != 0 or lanes.x[-1] < 25 or np.any(np.diff(lanes.x) <= 0):
return None, 'Model lanes have no usable forward extent'
region = lanes.x <= lookahead + 4
width = lanes.right_y[region] - lanes.left_y[region]
center = (lanes.left_y + lanes.right_y) * .5
if np.any(width < 2.2) or np.any(width > 5.5) or np.max(np.abs(center[region])) > 5:
return None, 'Lane geometry is not plausible'
probabilities = (lanes.left_prob, lanes.right_prob)
if not all(math.isfinite(v) and 0 <= v <= 1 for v in probabilities):
return None, 'Invalid model lane confidence'
return center, ''
def _path_supported(self, perception, speed, center, now):
"""Require partial visual evidence, a lane corridor and temporal coherence.
Plan hypothesis scores are deliberately not used as road confidence.
Both unobserved markings cannot be rescued by GPS graph geometry.
"""
lanes, plan = perception.lanes, perception.plan
probabilities = (lanes.left_prob, lanes.right_prob)
if min(probabilities) < .25 or max(probabilities) < .45 or path_reason(plan, speed):
self._path_history = []
return False
samples = np.array([4., 8., 12.])
if plan.x[-1] < 14:
self._path_history = []
return False
proposed = np.interp(samples, plan.x, plan.y)
lane_center = np.interp(samples, lanes.x, center)
half_width = np.interp(samples, lanes.x, (lanes.right_y-lanes.left_y)*.5)
# Keep the selected trajectory inside the camera corridor, allowing
# no more than 1.2 m disagreement with the lane-center hypothesis.
if np.any(np.abs(proposed-lane_center) > np.minimum(1.2, half_width-.35)):
self._path_history = []
return False
if self._path_history:
previous_time, previous = self._path_history[-1]
if now-previous_time > .5 or np.max(np.abs(proposed-previous)) > .35:
self._path_history = []
# Reassessing the same frame/time cannot build temporal evidence.
if not self._path_history or now > self._path_history[-1][0]:
self._path_history.append((now, proposed))
self._path_history = [(t, p) for t, p in self._path_history if now-t <= .5]
return len(self._path_history) >= 3 and now-self._path_history[0][0] >= .2
@staticmethod
def _near_bend(route, preview, telemetry, lookahead):
bend = preview.get('next_bend')
if not bend:
return None
try:
point = route['nodes'][bend['node_index']]['position']
position = telemetry['world_position']
distance = math.hypot(point[0]-position[0], point[2]-position[2])
angle = float(bend['angle_deg'])
direction = bend['direction']
if (not all(math.isfinite(v) for v in (distance, angle))
or not 25 <= abs(angle) <= 180
or direction not in ('left', 'right')
or (angle < 0) != (direction == 'left')):
raise ValueError('Invalid route bend')
# Advisor metres are map-scaled; use world metres for this horizon.
if distance <= 60:
return dict(direction=direction, distance_world_m=distance,
angle_deg=angle, near=distance <= lookahead+8)
except (KeyError, IndexError, TypeError, ValueError):
return dict(invalid=True)
return None
def assess(self, perception, speed_mps, route, preview, telemetry, now=None):
"""Return an allow/release decision and a rate-limited lateral command.
Call once per freshly inferred frame. The caller retains focus, camera,
telemetry, inference age, F8/manual override and actuator watchdog gates.
"""
now = self.clock() if now is None else now
if not math.isfinite(now) or (self._last_time is not None and now < self._last_time):
return self._stop('Invalid navigation planner clock')
if not math.isfinite(speed_mps) or speed_mps < 0:
return self._stop('Invalid navigation trial speed')
if speed_mps / .44704 > self.MAX_SPEED_MPH + .5:
return self._stop('Navigation trial speed exceeds 15 MPH limit')
if not (telemetry.get('valid') and telemetry.get('position_valid') and telemetry.get('navigation_valid')):
return self._stop('Fresh GPS telemetry required')
if not route.get('available') or not preview.get('available'):
return self._stop(route.get('reason') or preview.get('reason') or 'No active GPS route')
if (route.get('lead_in') is not None or preview.get('lead_in_estimated')
or preview.get('segment_kind') == 'lead-in'):
return self._stop('Estimated GPS lead-in is display-only; native route matching required')
if (route.get('geometry_kind') not in (None, 'native-route-node-array')
or preview.get('segment_kind') not in (None, 'native-node-pair')):
return self._stop('Unverified GPS geometry representation requires manual driving')
age = route.get('age_s')
if age is None or not math.isfinite(age) or not 0 <= age <= .5:
return self._stop('GPS route sample is stale')
error, progress, heading = (preview.get(k, float('nan')) for k in
('lateral_error_world_m', 'progress_error_m', 'heading_dot'))
if not all(isinstance(v, (int, float)) and math.isfinite(v) for v in (error, progress, heading)):
return self._stop('Invalid GPS matching geometry')
if error > 18 or error < 0 or progress > 250 or progress < 0 or not .65 <= heading <= 1.000001:
return self._stop('Truck is off route or not aligned with GPS direction')
if preview.get('reason'):
return self._stop(preview['reason'])
revision = route.get('revision')
if revision != self._revision:
self._path_history = []
self._revision = revision
lookahead = float(np.clip(speed_mps*1.5, 8., 25.))
center, reason = self._lanes(perception, lookahead)
if reason:
return self._stop(reason)
path_supported = self._path_supported(perception, speed_mps, center, now)
lane_clear = min(perception.lanes.left_prob, perception.lanes.right_prob) >= .35
bend = self._near_bend(route, preview, telemetry, lookahead)
if bend and bend.get('invalid'):
return self._stop('Invalid route bend geometry')
target_y = -float(np.interp(lookahead, perception.lanes.x, center))
strategy = 'camera-lanes'
# Left is positive in GPS ego coordinates and SCS steering; model y is right.
if bend and abs(bend['angle_deg']) >= 65 and bend['distance_world_m'] <= 25:
return self._stop('Sharp GPS turn: intersection/right-of-way requires manual driving')
if bend and bend['near']:
if abs(bend['angle_deg']) >= 65:
return self._stop('Sharp GPS turn: intersection/right-of-way requires manual driving')
direction = 1 if bend['direction'] == 'left' else -1
lane_curve = -float(np.interp(lookahead, perception.lanes.x, center)
- np.interp(2., perception.lanes.x, center))
lane_matches = direction*lane_curve > .10
if not lane_matches or not lane_clear:
if not path_supported:
return self._stop('GPS bend has no stable camera-supported trajectory')
path_curve = -float(np.interp(lookahead, perception.plan.x, perception.plan.y)
- np.interp(2., perception.plan.x, perception.plan.y))
if direction*path_curve <= .10:
return self._stop('Model trajectory disagrees with GPS bend')
target_y = -float(np.interp(lookahead, perception.plan.x, perception.plan.y))
strategy = 'route-confirmed-model-path'
elif not lane_clear:
if not path_supported:
return self._stop('Lane confidence low and camera path is not confirmed')
# Straight route agreement also constrains the fallback's local heading.
path_curve = -float(np.interp(lookahead, perception.plan.x, perception.plan.y)
- np.interp(2., perception.plan.x, perception.plan.y))
if abs(math.atan2(path_curve, lookahead-2)) > math.radians(12):
return self._stop('Low-confidence model path does not follow straight GPS context')
target_y = -float(np.interp(lookahead, perception.plan.x, perception.plan.y))
strategy = 'route-confirmed-model-path'
curvature = 2*target_y/(lookahead*lookahead+target_y*target_y)
target = float(np.clip(math.atan(curvature*4.5)/math.radians(35),
-self.MAX_STEER, self.MAX_STEER))
dt = .05 if self._last_time is None else max(.001, min(.1, now-self._last_time))
self.current_steer += float(np.clip(target-self.current_steer,
-self.MAX_STEER_RATE*dt, self.MAX_STEER_RATE*dt))
self._last_time = now
return dict(allowed=True, strategy=strategy, steer=self.current_steer, reason='',
max_speed_mph=8.0 if bend else self.MAX_SPEED_MPH,
route_revision=revision, next_bend=bend,
obstacles_verified=False, intersection_clearance_verified=False)
-30
View File
@@ -1,30 +0,0 @@
"""Laneless trajectory assessment for passive runs only; no actuator access."""
import math
import numpy as np
def path_reason(plan, speed_mps):
if not math.isfinite(speed_mps) or speed_mps < 0:
return "Invalid preview speed"
arrays = (plan.x, plan.y, plan.z)
if any(np.shape(a) != (33,) or not np.all(np.isfinite(a)) for a in arrays):
return "Invalid model trajectory"
lookahead = float(np.clip(speed_mps*1.5, 8.0, 25.0))
if (abs(plan.x[0]) > 2 or np.any(np.diff(plan.x) <= 0)
or plan.x[-1] < lookahead+2):
return "Model trajectory has no usable forward extent"
nearby = plan.y[(plan.x >= 0) & (plan.x <= lookahead+2)]
if not len(nearby) or np.max(np.abs(nearby)) > 5:
return "Model trajectory leaves the forward road region"
# Hypothesis weight is deliberately not treated as road confidence.
return ""
def preview_steering(plan, speed_mps):
reason = path_reason(plan, speed_mps)
if reason:
raise ValueError(reason)
lookahead = float(np.clip(speed_mps*1.5, 8.0, 25.0))
y = -float(np.interp(lookahead, plan.x, plan.y))
curvature = 2*y/(lookahead*lookahead+y*y)
return float(np.clip(math.atan(curvature*4.5)/math.radians(35), -0.35, 0.35))
-515
View File
@@ -1,515 +0,0 @@
"""Pure continuous experimental ATS Pop steering and bounded Chill cruise.
No actuator access or calibrated/production eligibility is granted here.
The caller owns engagement, foreground, blank-camera and operator cancellation.
"""
import math
import numbers
import time
import copy
import numpy as np
from model.perception import X_IDXS
from control.pop_path_steering import path_steering,preview_curve_speed
from control.gameplay_lead_guard import GameplayLeadGuard
from control.native_collision_path import collision_gap
from control.gameplay_road_tracking import GameplayRoadTracking
def _number(value):
if isinstance(value, bool) or not isinstance(value, numbers.Real):
return None
value = float(value)
return value if math.isfinite(value) else None
from control.gameplay_cruise import GameplayCruise
class PopGameplayController:
MIN_TARGET_MPH = 5.
MAX_TARGET_MPH = 80.
MAX_AXIS = .20
STEERING_RATE_PER_S = .35
DESCRIPTIVE_579_GAIN = .1254
# SDK yaw/actual steering fit from the October 3 Tesla Semi drive (195
# moving samples); descriptive simulator tuning, not physical calibration.
DESCRIPTIVE_TESLA_GAIN = .1535
MAX_MODEL_AGE_S = .35
MAX_OUTPUT_GAP_S = .50
CURVE_LATERAL_ACCEL_MPS2 = 2.
CURVE_SPEED_RECOVERY_MPH_PER_S = 3.
def __init__(self, target_speed_mph=35., smoothing_tau_s=.12,
model_age_s=None, output_gap_s=None):
speed, tau = _number(target_speed_mph), _number(smoothing_tau_s)
if speed is None or not self.MIN_TARGET_MPH <= speed <= self.MAX_TARGET_MPH or tau is None or tau <= 0:
raise ValueError('Finite gameplay speed 5..80 mph and positive smoothing required')
model_age = self.MAX_MODEL_AGE_S if model_age_s is None else _number(model_age_s)
output_gap = self.MAX_OUTPUT_GAP_S if output_gap_s is None else _number(output_gap_s)
if model_age is None or model_age <= 0 or output_gap is None or output_gap <= 0:
raise ValueError('Positive model age and output gap limits required')
self.target_speed_mph, self.smoothing_tau_s = speed, tau
# The default limits remain the conservative controller contract used
# by the unit tests and other callers. The continuous WMI runner opts
# into a slightly wider, still bounded host-spike profile.
self.model_age_limit_s, self.output_gap_limit_s = model_age, output_gap
self._now = 0.
self.cruise = GameplayCruise(clock=lambda: self._now)
self.lead_guard=GameplayLeadGuard()
self.road_tracking=GameplayRoadTracking()
self.reset()
def set_target_speed(self, mph):
speed=_number(mph)
if speed is None or not self.MIN_TARGET_MPH<=speed<=self.MAX_TARGET_MPH:
raise ValueError('Speed target must be finite and within 5..80 mph')
if speed<self.target_speed_mph:
self.cruise.integral=0.
self.target_speed_mph=speed
return speed
def _navigation_target_mph(self, telemetry):
"""Apply an advisory GPS bend cap without changing the user's MAX."""
target = self.target_speed_mph
navigation = telemetry.get('navigation_driver') if isinstance(telemetry, dict) else None
cap = _number(navigation.get('route_speed_cap_mph')) if isinstance(navigation, dict) else None
if navigation and navigation.get('enabled') and cap is not None:
target = min(target, max(self.MIN_TARGET_MPH, cap))
return target
def reset(self):
self._axis = self._smoothed = 0.
self._last_output_time = self._last_good_time = self._last_input = None
self._warmed_once = False
self._curve_target_mph=None
self._neutral_brake=None
self._road_brake=0.
self.cruise.reset()
self.lead_guard.reset()
self.road_tracking.reset()
def _result(self, reason, allowed=False, axis=0., action='coast', intensity=0., warnings=None, **extra):
return dict(allowed=allowed, allowed_for_gameplay=allowed, requested_axis=axis, steer=axis,
action=action, intensity=intensity,
throttle=intensity if action == 'throttle' else 0., brake=intensity if action == 'brake' else 0.,
reason=reason, warnings=list(warnings or []), target_speed_mph=self.target_speed_mph,
experimental_gameplay=True, production_eligible=False, calibrated=False,
physical_calibration_validated=False, controls_applied=False, control_eligible=False,
route_competence_validated=False, intersection_competence_validated=False, **extra)
@staticmethod
def _complete(data):
coverage = data.get('model_temporal_coverage')
return (isinstance(coverage, dict) and coverage.get('complete') is True
and coverage.get('feature_slots_present') == 25 and coverage.get('feature_slots_required') == 25
and coverage.get('narrow_pair_present') is True and coverage.get('wide_pair_present') is True)
def _sdk_reason(self, data, now, allow_neutral_braking=False):
if now is None or not isinstance(data, dict):
return 'Finite time and SDK data required'
if data.get('valid') is not True or data.get('paused') is not False:
return 'Fresh unpaused SDK required'
stamp = data.get('timestamp')
if isinstance(stamp, bool) or not isinstance(stamp, int) or stamp <= 0:
return 'Positive SDK timestamp required'
age, speed = _number(data.get('age')), _number(data.get('speed_mps'))
if age is None or not 0 <= age <= .35 or speed is None or speed < -.02:
return 'Finite fresh forward SDK speed required'
gear = data.get('gear')
if (isinstance(gear, bool) or not isinstance(gear, int)
or gear < 0 or (gear == 0 and not allow_neutral_braking)):
return 'Select Drive before engaging'
if data.get('engine_enabled') is not True:
return 'Turn on the engine before engaging'
if data.get('park_brake') is not False:
return 'Release the parking brake before engaging'
return ''
def _model_reason(self, data, model_action, now):
if (data.get('model_current_pair_available') is not True
or data.get('model_inferred_this_frame') is not True
or data.get('model_obstructed') is not False or data.get('model_geometry_stale') is not False):
return 'Fresh current unobstructed paired Pop camera input required'
stamp, age = _number(data.get('model_input_monotonic')), _number(data.get('model_age_s'))
if (stamp is None or age is None or not 0 <= age <= self.model_age_limit_s
or now-stamp > self.model_age_limit_s or stamp-now > .05):
return 'Current model frame timestamp unavailable or stale'
if self._last_input is not None and stamp <= self._last_input:
return 'Waiting for a new unique Pop model frame'
if (not isinstance(model_action, dict) or model_action.get('available') is not True
or _number(model_action.get('desired_curvature')) is None
or _number(model_action.get('desired_acceleration')) is None
or type(model_action.get('should_stop')) is not bool):
return 'Finite available modern Pop action required'
return ''
def _warnings(self, perception, data, model_action):
warnings = []
if not self._complete(data):
warnings.append('Historical temporal slots incomplete after real initial warmup')
if model_action.get('should_stop') is True:
warnings.append('Model stop intent advisory only; gameplay uses SDK speed/native traffic')
try:
horizon = min(25., max(8., data['speed_mps']*1.5))+2.
plan_x = np.asarray(perception.plan.x, dtype=float)
std = np.asarray(perception.plan_std, dtype=float)
edges_std = np.asarray(perception.road_edge_std, dtype=float)
edge_x = np.asarray(getattr(perception, 'road_edge_x', X_IDXS), dtype=float)
if std.shape != (33, 15) or edges_std.shape != (2, 33, 2) or plan_x.shape != (33,) or edge_x.shape != (33,):
raise ValueError('Unavailable shapes')
path = std[(plan_x >= 0) & (plan_x <= horizon), 1]
edges = edges_std[:, (edge_x >= 0) & (edge_x <= horizon), 0]
if not path.size or not edges.size or not np.isfinite(path).all() or not np.isfinite(edges).all():
raise ValueError('Unavailable uncertainty')
if path.max() > .75: warnings.append('Predicted local path uncertainty elevated')
if edges.max() > 1.5: warnings.append('Predicted local road-edge uncertainty elevated')
except (AttributeError, TypeError, ValueError, IndexError):
warnings.append('Predicted local path/edge uncertainty unavailable')
return warnings
def _native_lead(self, perception, telemetry, now, warnings):
report = telemetry.get('nearby_traffic')
age = _number(report.get('age_s')) if isinstance(report, dict) else None
sampled = _number(report.get('sampled_at')) if isinstance(report, dict) else None
ego = telemetry.get('world_position')
if (not isinstance(report, dict) or report.get('available') is not True
or report.get('source') != 'ATS simulator actors' or age is None or not 0 <= age <= .3
or sampled is None or not 0 <= now-sampled <= .3 or not isinstance(ego, (list, tuple))
or len(ego) != 3 or _number(ego[1]) is None):
warnings.append('Native traffic unavailable: acceleration inhibited without a tracked lead')
return None
candidates = []
for actor in report.get('actors', []):
if not isinstance(actor, dict):
continue
values = {key:_number(actor.get(key)) for key in
('forward_m','left_m','length_m','width_m','height_m','heading_delta_rad')}
relative=_number(actor.get('relative_forward_mps'))
motion_known=actor.get('motion_available') is True and relative is not None and abs(relative)<=80
position = actor.get('world_position')
if (any(v is None for v in values.values()) or not isinstance(position, (list, tuple))
or len(position) != 3 or _number(position[1]) is None):
continue
rotation=telemetry.get('world_rotation')
if isinstance(rotation,(list,tuple)) and len(rotation)==3 and _number(rotation[0]) is not None:
yaw=rotation[0]*2*math.pi
dx,dz=position[0]-ego[0],position[2]-ego[2]
if _number(position[0]) is None or _number(position[2]) is None:continue
fx,fz=-math.sin(yaw),-math.cos(yaw)
values['forward_m']=dx*fx+dz*fz
values['left_m']=dx*fz-dz*fx
world_heading=_number(actor.get('world_heading_rad'))
if world_heading is not None:
values['heading_delta_rad']=(world_heading-yaw+math.pi)%(2*math.pi)-math.pi
if (not 0 < values['forward_m'] <= 100 or not 0 < values['length_m'] <= 25
or not 0 < values['width_m'] <= 4 or not 0 < values['height_m'] <= 5
or abs(position[1]-values['height_m']*.5-ego[1]) > 2.):
continue
own_front=_number(report.get('own_front_extent_m'))
own_front=own_front if own_front is not None and 0<=own_front<=15 else 0.
contact=collision_gap(values,getattr(perception,'plan',None),own_front)
if contact is None:continue
candidates.append(dict(id=actor.get('id'), **contact,
relative_forward_mps=relative if motion_known else -telemetry['speed_mps'],
motion_estimated=not motion_known,source='ATS simulator actors',
lane_association_verified=False))
warnings.append('Native traffic coverage/lane association incomplete; supervise following')
return min(candidates, key=lambda actor:actor['distance_m']) if candidates else None
def preflight(self, perception, telemetry, model_action, now=None, warmed_once=False):
now = _number(time.monotonic() if now is None else now)
reason = self._sdk_reason(telemetry, now)
if not reason: reason = self._model_reason(telemetry, model_action, now)
if not reason: _,reason=self._navigation_path(perception,telemetry)
if reason: return self._result(reason, preflight_only=True)
if self._complete(telemetry): self._warmed_once = True
if not self._warmed_once and warmed_once is not True:
return self._result('Real complete Pop temporal context required once before engagement', preflight_only=True)
return self._result('Experimental gameplay preflight ready; no controls requested', allowed=True,
warnings=self._warnings(perception, telemetry, model_action), preflight_only=True)
@staticmethod
def _navigation_path(perception,telemetry):
change=telemetry.get('lane_change_driver') or {}
if change.get('require_manual') is True:
return perception,'Lane change: '+str(change.get('reason') or 'Manual completion required')
navigation=telemetry.get('navigation_driver')
if isinstance(navigation,dict) and navigation.get('enabled') is True and navigation.get('allowed_for_gameplay') is not True:
# A transient GPS/model heading disagreement is a route-selection
# gap, not proof that the camera model stopped seeing the road. The
# navigation layer has already checked the model corridor and marks
# only that recoverable case as transient. Keep the current camera
# path for the short gap; hard route/shoulder/junction failures
# continue to require manual control below.
if navigation.get('transient') is True and navigation.get('require_manual') is not True:
telemetry['_gps_model_fallback_reason'] = str(
navigation.get('reason') or 'GPS alignment temporarily unavailable')
return perception,''
return perception,'GPS: '+str(navigation.get('reason') or 'Route-aligned road path unavailable')
if change.get('active') is True and change.get('allowed_for_gameplay') is True:
override=change.get('path_override')
label='Lane change'
else:
override=navigation.get('path_override') if isinstance(navigation,dict) and navigation.get('enabled') is True else None
label='GPS'
if override is None:return perception,''
try:
selected=copy.copy(perception)
selected.plan=copy.copy(perception.plan)
for axis in ('x','y','z'):
values=np.asarray(override[axis],dtype=float)
if values.shape!=(33,) or not np.isfinite(values).all():
raise ValueError('Invalid route-selected camera path')
setattr(selected.plan,axis,values)
return selected,''
except (AttributeError,KeyError,TypeError,ValueError):
return perception,label+': invalid selected camera path'
def _gap_pedals(self,telemetry,now):
"""A brief path/camera gap must not cancel a closing-traffic brake."""
self._now=now
native=self._native_lead(None,telemetry,now,[])
lead,guard=self.lead_guard.assess(native,None,telemetry,now)
action,duty=self.cruise.compute(min(self._navigation_target_mph(telemetry),
self._curve_target_mph or self.target_speed_mph),telemetry['speed_mps']*2.2369362921,lead,
pedal_feedback=telemetry)
if self._neutral_brake is not None:
action,duty='brake',max(self._neutral_brake,duty if action=='brake' else 0.)
self.cruise.action,self.cruise.intensity=action,duty
elif action!='brake':
action,duty='coast',0.
self.cruise.reset()
if self._road_brake:
action,duty='brake',max(self._road_brake,duty if action=='brake' else 0.)
return dict(action=action,intensity=duty,following_guard=guard,
following_braking=self.cruise.following)
def _stopped_queue_hold(self, telemetry, now, reason, road_tracking=None):
"""Keep a stopped queue brake engaged without inventing a drive path.
A short model horizon behind a nearby vehicle is not a reason to drop
an already applied brake. Fresh simulator contact in the actual forward
footprint and fresh SDK/model input remain necessary. This branch can
never accelerate or steer around the lead; departure uses the normal
current-road/navigation admission again.
"""
if (self._last_good_time is None or not 0 <= telemetry['speed_mps'] <= .5
or not (self._road_brake > 0 or self.cruise.action == 'brake')):
return None
warnings = []
native = self._native_lead(None, telemetry, now, warnings)
if native is None or not 0 < native['distance_m'] <= 20.:
return None
lead, guard = self.lead_guard.assess(native, None, telemetry, now)
if not guard['native_report_fresh'] or guard['held_during_dropout']:
return None
self._now = now
action, duty = self.cruise.compute(0., telemetry['speed_mps']*2.2369362921,
lead, pedal_feedback=telemetry)
duty = max(.12, duty if action == 'brake' else 0.)
self.cruise.action, self.cruise.intensity = 'brake', duty
self.cruise.integral = 0.
self._axis = self._smoothed = 0.
self._last_output_time = self._last_good_time = now
self._last_input = float(telemetry['model_input_monotonic'])
return self._result('Stopped behind traffic: brake held; waiting for a current road path',
allowed=True, action='brake', intensity=duty, warnings=[reason],
queue_brake_hold=True, departure_requires_current_geometry=True,
native_lead=native, following_guard=guard, following_braking=self.cruise.following,
effective_speed_target_mph=0., model_input_monotonic=self._last_input,
steering_geometry=dict(available=False, reason=reason,
road_tracking=road_tracking or dict(strategy='stopped-traffic-brake-hold',
lane_tracking=False,brake_required=True)))
def assess(self, perception, telemetry, model_action, now=None, warmed_once=False):
now = _number(time.monotonic() if now is None else now)
neutral_braking=(isinstance(telemetry,dict) and type(telemetry.get('gear')) is int
and telemetry['gear']==0 and (self._neutral_brake is not None
or (self.cruise.action=='brake' and (self.cruise.following is not None or self._road_brake))))
previous_brake=self._neutral_brake if self._neutral_brake is not None else self.cruise.intensity
sdk_reason = self._sdk_reason(telemetry, now,allow_neutral_braking=neutral_braking)
if sdk_reason:
self.reset()
return self._result(sdk_reason)
if neutral_braking:self._neutral_brake=previous_brake
# SDK wheel noise can report tiny negative speed at a stationary truck.
# Do not release a stopped-traffic brake for that noise. Keep the raw
# caller/evidence data unchanged; real reverse motion remains rejected.
stationary_noise=telemetry['speed_mps']<0
if stationary_noise:telemetry=dict(telemetry,speed_mps=0.)
if self._last_output_time is not None and now < self._last_output_time:
self.reset()
return self._result('Monotonic time regressed')
output_gap=now-self._last_good_time if self._last_good_time is not None else 0.
if output_gap > self.output_gap_limit_s:
self.reset()
return self._result('Command gap exceeds %.2f seconds; reengagement required'%self.output_gap_limit_s)
reason = self._model_reason(telemetry, model_action, now)
if reason:
if (self._last_good_time is not None and self._last_input is not None
and 0 <= now-self._last_good_time <= self.model_age_limit_s
and 0 <= now-self._last_input <= self.model_age_limit_s):
return self._result('Brief model gap: last steering held; traffic braking retained',
allowed=True, axis=self._axis, warnings=[reason], held_previous_steering=True,
model_hold_age_s=now-self._last_good_time,**self._gap_pedals(telemetry,now))
self.reset()
return self._result(reason+'; model hold deadline expired')
if self._complete(telemetry): self._warmed_once = True
if not self._warmed_once and warmed_once is not True:
self.cruise.reset()
return self._result('Real complete Pop temporal context required once before engagement')
if neutral_braking:
# Automatic shifts briefly report gear zero. A shift must not
# release an already-commanded traffic brake while still moving.
pedals=self._gap_pedals(telemetry,now)
duty=max(previous_brake,pedals['intensity'])
self._neutral_brake=duty
self.cruise.action,self.cruise.intensity='brake',duty
self._last_output_time=self._last_good_time=now
self._last_input=float(telemetry['model_input_monotonic'])
pedals.update(action='brake',intensity=duty)
return self._result('Traffic brake retained through neutral/automatic shift',
allowed=True,axis=self._axis,neutral_traffic_brake_held=True,
held_previous_steering=True,**pedals)
self._neutral_brake=None
self._now = now
warnings = self._warnings(perception, telemetry, model_action)
game_cruise_conflict=telemetry.get('game_cruise_active') is True
if game_cruise_conflict:
warnings.append('ATS cruise control is active: it can hold speed after our throttle releases')
selected,navigation_reason=self._navigation_path(perception,telemetry)
if navigation_reason:
# Only missing comparison distance is a queue-hold exception. A
# shoulder, changed route, or positive GPS/model disagreement must
# retain its existing manual-handoff path.
if navigation_reason == 'GPS: Current trajectory lacks near-to-forward route comparison':
queued = self._stopped_queue_hold(telemetry, now, navigation_reason)
if queued is not None:
return queued
navigation=telemetry.get('navigation_driver') or {}
expired=navigation.get('gps_hold_expired') is True
deadline=_number(navigation.get('hold_deadline_monotonic'))
if deadline is not None and now>deadline:expired=True
if not expired and self._last_good_time is not None and now-self._last_good_time<=self.model_age_limit_s:
return self._result('Brief GPS gap: traffic braking retained',allowed=True,
axis=self._axis,warnings=[navigation_reason],held_previous_steering=True,
**self._gap_pedals(telemetry,now))
self.reset()
return self._result(navigation_reason+'; manual steering required')
fallback_reason=telemetry.get('_gps_model_fallback_reason')
if fallback_reason:
warnings.append('GPS alignment gap; using the current camera path')
perception,road_tracking=self.road_tracking.assess(selected,telemetry,now)
if road_tracking['brake_required']:
queued = self._stopped_queue_hold(telemetry, now,
'Current road confidence reduced behind a nearby vehicle', road_tracking)
if queued is not None:
return queued
if output_gap > self.model_age_limit_s:
# Only a unique current frame that passed the unchanged exposure
# age checks reaches here. Restart from measured steering, rather
# than applying a rate-limit step accumulated across the pause.
actual=_number(telemetry.get('steering'))
if actual is not None:self._axis=max(-self.MAX_AXIS,min(self.MAX_AXIS,actual))
self._smoothed=self._axis
self._last_output_time=now
self.cruise.reset()
warnings.append('Fresh model recovered after brief processing pause')
gain=(self.DESCRIPTIVE_TESLA_GAIN if telemetry.get('truck_name')=='Semi truck 2019'
else self.DESCRIPTIVE_579_GAIN)
options=dict(lookahead_s=1.2,minimum_m=12.,maximum_m=25.) if road_tracking['lane_tracking'] else {}
geometry=path_steering(perception.plan,telemetry['speed_mps'],gain,**options)
if not geometry['available']:
queued = self._stopped_queue_hold(telemetry, now, geometry['reason'], road_tracking)
if queued is not None:
return queued
if self._last_good_time is not None and now-self._last_good_time<=self.model_age_limit_s:
return self._result('Brief path gap: last steering held; traffic braking retained',allowed=True,
axis=self._axis,warnings=[geometry['reason']],held_previous_steering=True,
steering_geometry=geometry,**self._gap_pedals(telemetry,now))
self.reset()
return self._result(geometry['reason'],steering_geometry=geometry)
geometry['lane_center_assist']=dict(available=False,enabled=False,
reason='Disabled after reported lane-keeping regression',correction_m=0.)
geometry['road_tracking']=road_tracking
geometry['selected_path']={key:np.asarray(getattr(perception.plan,key)).tolist()
for key in ('x','y','z') if hasattr(perception.plan,key)}
geometry['descriptive_steering_gain']=gain
if road_tracking['lane_tracking']:geometry['source']=road_tracking['strategy']
navigation=telemetry.get('navigation_driver')
if isinstance(navigation,dict) and navigation.get('enabled'):
geometry['navigation_strategy']=navigation.get('strategy')
if geometry['lookahead_limited']:warnings.append('Steering lookahead limited to actual predicted path')
target = max(-self.MAX_AXIS, min(self.MAX_AXIS,geometry['raw_axis']))
if road_tracking.get('road_lost'):
target=0.
warnings.insert(0,'Road estimate lost: braking; take over')
dt = min(.35, max(0., now-self._last_output_time)) if self._last_output_time is not None else .05
tau=max(.35,self.smoothing_tau_s) if geometry['lookahead_limited'] else self.smoothing_tau_s
smoothed = self._smoothed + dt/(tau+dt)*(target-self._smoothed)
change = self.STEERING_RATE_PER_S*dt
axis = max(self._axis-change, min(self._axis+change, smoothed))
native_lead = self._native_lead(perception, telemetry, now, warnings)
following_lead,following_guard=self.lead_guard.assess(native_lead,perception,telemetry,now)
# MAX is a ceiling, not a demand to enter every bend at that speed.
# Use the same current path curvature as steering, never painted-lane
# association. Decrease promptly; restore speed gradually after a bend.
curve_limit_mph=math.sqrt(self.CURVE_LATERAL_ACCEL_MPS2/
max(1e-6,abs(geometry['curvature'])))*2.2369362921
navigation_target=self._navigation_target_mph(telemetry)
wanted_speed=min(navigation_target,max(10.,curve_limit_mph))
curve_preview=preview_curve_speed(perception.plan,self.CURVE_LATERAL_ACCEL_MPS2)
if curve_preview['speed_limit_mph'] is not None:
wanted_speed=min(wanted_speed,max(10.,curve_preview['speed_limit_mph']))
recovery_cap=_number(road_tracking.get('recovery_speed_cap_mph'))
if recovery_cap is not None:
wanted_speed=min(wanted_speed,recovery_cap)
warnings.insert(0,'Brief road-confidence gap: holding observed lane; reducing speed gently')
if self._curve_target_mph is None:self._curve_target_mph=wanted_speed
else:self._curve_target_mph=min(wanted_speed,
self._curve_target_mph+self.CURVE_SPEED_RECOVERY_MPH_PER_S*dt)
effective_speed=min(navigation_target,self._curve_target_mph)
navigation=telemetry.get('navigation_driver')
if (isinstance(navigation,dict) and navigation.get('enabled') and
isinstance(navigation.get('route_speed_cap_mph'),(int,float)) and
navigation['route_speed_cap_mph'] < self.target_speed_mph-.5):
warnings.insert(0,'GPS turn approach cap %.0f MPH (MAX %.0f)' %
(navigation['route_speed_cap_mph'],self.target_speed_mph))
if effective_speed<self.target_speed_mph-.5:
warnings.insert(0,'Curve speed %.0f MPH (MAX %.0f)'%(effective_speed,self.target_speed_mph))
action, intensity = self.cruise.compute(effective_speed,
telemetry['speed_mps']*2.2369362921, following_lead,
curve_limited=effective_speed<self.target_speed_mph-.5,
pedal_feedback=telemetry)
if (following_guard['acceleration_inhibited'] or recovery_cap is not None) and action=='throttle':
action,intensity='coast',0.
self.cruise.action,self.cruise.intensity='coast',0.
if road_tracking['brake_required']:
# Keep control long enough to brake. Releasing engagement here
# would drop the brake as well as the unreliable steering request.
self._road_brake=min(.45,self._road_brake+.5*dt)
action,intensity='brake',max(self._road_brake,intensity if action=='brake' else 0.)
self.cruise.integral=0.
self.cruise.action,self.cruise.intensity=action,intensity
else:self._road_brake=0.
brake_cap=1. if self.cruise.following else .45 if self._road_brake else .20
intensity = max(0., min(1. if action == 'throttle' else brake_cap if action == 'brake' else 0., intensity))
self._axis, self._smoothed = axis, smoothed
self._last_output_time = self._last_good_time = now
self._last_input = float(telemetry['model_input_monotonic'])
return self._result('Experimental continuous Pop gameplay', allowed=True, axis=axis,
action=action, intensity=intensity, warnings=warnings, target_axis=target,
steering_rate_limit_per_s=self.STEERING_RATE_PER_S, smoothing_tau_s=tau,
longitudinal_source='SDK speed hold; native lead and persistent camera rear braking', native_lead=native_lead,
visual_lead_advisory_only=False,throttle_cap=1.,brake_cap=brake_cap,
following_guard=following_guard,following_braking=self.cruise.following,
pedal_feedback=self.cruise.pedal_feedback,
game_cruise_conflict=game_cruise_conflict,
stationary_speed_noise_clamped=stationary_noise,
effective_speed_target_mph=effective_speed,curve_speed_limit_mph=curve_limit_mph,
curve_speed_preview=curve_preview,
curve_lateral_accel_limit_mps2=self.CURVE_LATERAL_ACCEL_MPS2,
held_previous_steering=False, model_input_monotonic=self._last_input,
steering_geometry=geometry,modern_action_curvature=model_action['desired_curvature'])
-130
View File
@@ -1,130 +0,0 @@
"""Pure modern Pop action extraction; never an actuator or control approval.
Primary source revision 62bf6fb072880905a4c490f0f4f4a6b3c23346ec:
https://github.com/commaai/openpilot/blob/62bf6fb072880905a4c490f0f4f4a6b3c23346ec/selfdrive/controls/lib/drive_helpers.py
https://github.com/commaai/openpilot/blob/62bf6fb072880905a4c490f0f4f4a6b3c23346ec/selfdrive/modeld/modeld.py
https://github.com/commaai/openpilot/blob/62bf6fb072880905a4c490f0f4f4a6b3c23346ec/selfdrive/modeld/constants.py
These formulas match upstream model actions, before vehicle-specific control.
The .2s ATS lateral/longitudinal defaults are UNVALIDATED assumptions. The
upstream .05s model step and .3s longitudinal smoothing are retained exactly;
calling at a different cadence does not establish equivalent temporal behavior.
"""
import math
import numbers
import numpy as np
SOURCE_REVISION = '62bf6fb072880905a4c490f0f4f4a6b3c23346ec'
SOURCE_SHA256 = {
'selfdrive/controls/lib/drive_helpers.py': '0c8b32b1667000d48ee4630f0b197a05edabd811d718709ab616872c35918844',
'selfdrive/modeld/modeld.py': '571496f6e8b8364d90d0e2dddcb2a6f375ecbb434927e11078f40084e56f3b66',
'selfdrive/modeld/constants.py': 'e1e3a01ea31dd57dbd9ffd588ff1f2ab22e6088a558c65ad68bf20678552c00c',
}
CONTRACT = 'pop-v2-split-1576-1000'
PLAN_TIMES = 10. * (np.arange(33, dtype=np.float64) / 32.) ** 2
MODEL_DT = .05
LONG_SMOOTH_SECONDS = .3
MIN_LAT_CONTROL_SPEED = .3
MIN_CURVATURE_SPEED = 1.
UPSTREAM_MAX_CURVATURE = .2
def _finite_number(value):
if isinstance(value, bool) or not isinstance(value, numbers.Real):
return None
try:
value = float(value)
except (OverflowError, ValueError):
return None
return value if math.isfinite(value) else None
class PopModelActions:
"""Extract model actions with explicit unvalidated delay assumptions.
Broad input rejection bounds (100m/s speed, 100m/s² acceleration, two
revolutions of yaw/radian-rate) reject corrupt outputs without fitting a
recording. The .2/m curvature rejection bound is the upstream downstream
helper MAX_CURVATURE; no clipping hides an out-of-bound prediction.
"""
def __init__(self, *, lateral_delay_s=.2, longitudinal_delay_s=.2):
lateral, longitudinal = _finite_number(lateral_delay_s), _finite_number(longitudinal_delay_s)
if lateral is None or longitudinal is None or not (0 <= lateral <= 2 and 0 <= longitudinal <= 2):
raise ValueError('Unvalidated action delay must be finite and within0..2 seconds')
self.lateral_delay_s, self.longitudinal_delay_s = lateral, longitudinal
self.reset()
def reset(self):
self.previous_acceleration = 0.
self.previous_curvature = 0.
def assess(self, perception, speed_mps):
lat_action_t = self.lateral_delay_s + MODEL_DT
long_action_t = self.longitudinal_delay_s + LONG_SMOOTH_SECONDS + MODEL_DT
result = dict(available=False, desired_curvature=None, desired_acceleration=None,
raw_desired_curvature=None, raw_desired_acceleration=None, should_stop=None,
target_speed_mps=None, target_speed_1s_mps=None,
lateral_action_time_s=lat_action_t, longitudinal_action_time_s=long_action_t,
lateral_delay_s=self.lateral_delay_s,
longitudinal_delay_s=self.longitudinal_delay_s,
delay_parameters_validated=False, expected_model_hz=20,
smoothing_dt_s=MODEL_DT, upstream_cadence_validated=False,
controls_applied=False, control_eligible=False, preview_only=True,
source_revision=SOURCE_REVISION, source_sha256=dict(SOURCE_SHA256), reason='')
def unavailable(reason):
self.reset()
result['reason'] = reason
return result
speed = _finite_number(speed_mps)
if speed is None or not 0 <= speed <= 100:
return unavailable('Invalid model action speed')
if getattr(perception, 'pop_plan_contract', None) != CONTRACT:
return unavailable('Full modern Pop plan contract is unavailable')
try:
velocity, acceleration, orientation, orientation_rate = (
np.asarray(getattr(perception, name), dtype=np.float64)
for name in ('velocity_xyz', 'acceleration_xyz', 'orientation_xyz', 'orientation_rate_xyz'))
times = np.asarray(perception.plan_times, dtype=np.float64)
except (AttributeError, TypeError, ValueError):
return unavailable('Complete modern motion plan is unavailable')
if (any(a.shape != (33, 3) or not np.all(np.isfinite(a))
for a in (velocity, acceleration, orientation, orientation_rate))
or times.shape != (33,) or not np.all(np.isfinite(times))
or not np.allclose(times, PLAN_TIMES, rtol=0, atol=1e-7)):
return unavailable('Invalid modern motion plan arrays/time contract')
if (np.max(np.abs(velocity)) > 100 or np.max(np.abs(acceleration)) > 100
or np.max(np.abs(orientation)) > 4*math.pi
or np.max(np.abs(orientation_rate)) > 4*math.pi):
return unavailable('Modern motion plan exceeds broad input bounds')
# drive_helpers.get_accel_from_plan: x speed/acceleration at delay.
v_now, a_now = float(velocity[0, 0]), float(acceleration[0, 0])
v_target = float(np.interp(long_action_t, times, velocity[:, 0]))
v_target_1sec = float(np.interp(long_action_t+1., times, velocity[:, 0]))
raw_accel = 2*(v_target-v_now)/long_action_t-a_now
should_stop = v_target < .05 and v_target_1sec < .05
# Upstream smooth_value retains DT_MDL=.05 and LONG_SMOOTH_SECONDS=.3.
alpha = 1-math.exp(-MODEL_DT/LONG_SMOOTH_SECONDS)
desired_accel = alpha*raw_accel + (1-alpha)*self.previous_acceleration
# drive_helpers.get_curvature_from_plan uses interpolated yaw but
# initial yaw rate, not the rate interpolated at the actuator delay.
psi_target = float(np.interp(lat_action_t, times, orientation[:, 2]))
psi_rate = float(orientation_rate[0, 2])
safe_speed = max(speed, MIN_CURVATURE_SPEED)
raw_curvature = 2*psi_target/(safe_speed*lat_action_t)-psi_rate/safe_speed
desired_curvature = raw_curvature if speed > MIN_LAT_CONTROL_SPEED else self.previous_curvature
if (not all(math.isfinite(v) for v in (raw_accel, desired_accel, raw_curvature, desired_curvature))
or abs(desired_curvature) > UPSTREAM_MAX_CURVATURE):
return unavailable('Modern model action is nonfinite or exceeds upstream curvature bound')
self.previous_acceleration, self.previous_curvature = desired_accel, desired_curvature
result.update(available=True, desired_curvature=desired_curvature,
raw_desired_curvature=raw_curvature,
desired_acceleration=desired_accel, raw_desired_acceleration=raw_accel,
should_stop=bool(should_stop), target_speed_mps=v_target,
target_speed_1s_mps=v_target_1sec,
low_speed_curvature_held=speed <= MIN_LAT_CONTROL_SPEED,
reason='Modern Pop action preview; ATS delays and control response remain unvalidated')
return result
-131
View File
@@ -1,131 +0,0 @@
"""Geometric lookahead on the current Pop path, without path extrapolation."""
import math
import numpy as np
class LaneCenterAssist:
"""Gradual paint guidance in the same model frame; path remains fallback."""
def __init__(self):self.reset()
def reset(self):
self.correction=0.
self.last_time=self.last_near=None
self.block_until=0.
def apply(self,geometry,lanes,now,gain=.1254):
dt=min(.35,max(0.,now-self.last_time)) if self.last_time is not None else .05
if self.last_time is not None and now-self.last_time>.5:
self.reset();dt=.05
self.last_time=now
wanted=weight=0.
detail=dict(available=False,reason='Lane markings unavailable')
try:
x,left,right=(np.asarray(getattr(lanes,key),dtype=float) for key in ('x','left_y','right_y'))
probs=np.asarray([lanes.left_prob,lanes.right_prob],dtype=float)
distance=geometry['lookahead_m']
if (any(a.shape!=(33,) or not np.isfinite(a).all() for a in (x,left,right))
or not np.isfinite(probs).all() or np.any((probs<0)|(probs>1))
or np.any(np.diff(x)<=0) or x[0]>5 or x[-1]<distance):
raise ValueError('Lane geometry unavailable at current lookahead')
if min(probs)<.55:raise ValueError('Lane markings uncertain: path fallback')
samples=np.r_[5.,x[(x>5.)&(x<distance)],distance]
widths=np.interp(samples,x,right-left)
if np.any((widths<2.8)|(widths>4.5)) or np.ptp(widths)>.8:
raise ValueError('Lane width/order inconsistent: path fallback')
center=(left+right)*.5
near=float(np.interp(5.,x,center))
lateral=float(np.interp(distance,x,center))
if abs(near)>2.:raise ValueError('Lane center outside ego corridor: path fallback')
if self.last_near is not None and abs(near-self.last_near)>.75+dt:
self.block_until=now+.6
self.last_near=near
if now<self.block_until:raise ValueError('Lane association changed: path fallback')
weight=.65*min(1.,max(0.,(float(min(probs))-.55)/.35))
delta=lateral-geometry['target_lateral_m']
wanted=weight*max(-1.2,min(1.2,delta))
detail=dict(available=True,lane_center_y_m=lateral,near_center_y_m=near,
confidence=float(min(probs)),weight=weight,path_center_delta_m=delta)
except (AttributeError,TypeError,ValueError,IndexError) as exc:
detail=dict(available=False,reason=str(exc))
# Smooth the correction itself, including fading back to the path.
# Limit its rate so a changed line slot cannot inject a steering step.
tau=.35 if detail['available'] else .2
change=dt/(tau+dt)*(wanted-self.correction)
self.correction+=max(-.6*dt,min(.6*dt,change))
if abs(self.correction)<1e-6:self.correction=0.
lateral=geometry['target_lateral_m']+self.correction
distance=geometry['lookahead_m']
curvature=2*lateral/(distance*distance+lateral*lateral)
return dict(geometry,path_target_lateral_m=geometry['target_lateral_m'],
target_lateral_m=lateral,curvature=curvature,undamped_axis=-curvature/gain,
raw_axis=-curvature/gain*geometry['extent_gain_scale'],
lane_center_assist=dict(detail,correction_m=self.correction),
source='current-model-path-with-lane-center-assist' if self.correction else geometry['source'])
def path_steering(plan, speed_mps, gain=.1254, *, lookahead_s=2.5, minimum_m=18., maximum_m=45.):
try:
x=np.asarray(plan.x,dtype=float)
y=np.asarray(plan.y,dtype=float)
if x.shape!=(33,) or y.shape!=(33,) or not np.isfinite(x).all() or not np.isfinite(y).all():
raise ValueError('Invalid current path')
if not math.isfinite(speed_mps) or speed_mps<0:
raise ValueError('Invalid current speed')
# Never sort a folded plan into a road the model did not predict.
end=1
while end<len(x) and x[end]>x[end-1]+1e-4:end+=1
x,y=x[:end],y[:end]
positive=x>=0
x,y=x[positive],y[positive]
if len(x)<2 or x[-1]<3:
raise ValueError('Current forward path shorter than three metres')
# At queue speed the model intentionally reports a short horizon. Use
# the measured endpoint with the existing extent-gain damping; never
# accept that shortened horizon at normal road speed.
if x[-1] < 6 and speed_mps > 7.:
raise ValueError('Current forward path shorter than six metres')
requested=max(minimum_m,min(maximum_m,speed_mps*lookahead_s))
distance=min(requested,float(x[-1]))
lateral=float(np.interp(distance,x,y))
curvature=2*lateral/(distance*distance+lateral*lateral)
# A short forecast has less information, not permission for the much
# stronger correction produced by shrinking the pursuit denominator.
# Dampen its command; do not invent a point beyond the available path.
extent_scale=min(1.,(distance/requested)**2)
return dict(available=True,curvature=curvature,raw_axis=-curvature/gain*extent_scale,
undamped_axis=-curvature/gain,extent_gain_scale=extent_scale,
lookahead_m=distance,requested_lookahead_m=requested,
path_extent_m=float(x[-1]),lookahead_limited=distance<requested,
target_lateral_m=lateral,source='current-model-path-pure-pursuit')
except (AttributeError,TypeError,ValueError,IndexError) as exc:
return dict(available=False,reason=str(exc))
def preview_curve_speed(plan,lateral_accel=2.,deceleration=1.5):
"""Current speed bound for bends in the covered path, without extrapolation."""
try:
x,y=np.asarray(plan.x,dtype=float),np.asarray(plan.y,dtype=float)
if any(a.shape!=(33,) or not np.isfinite(a).all() for a in (x,y)):
raise ValueError('Invalid current path')
end=1
while end<len(x) and x[end]>x[end-1]+1e-4:end+=1
x,y=x[:end],y[:end]
if x[0]>10 or x[-1]<30:raise ValueError('Insufficient covered curve preview')
samples=np.arange(10.,min(100.,x[-1])+1e-6,10.)
points=np.column_stack((samples,np.interp(samples,x,y)))
best=None
for a,b,c in zip(points,points[1:],points[2:]):
ab,ac,bc=b-a,c-a,c-b
denom=np.linalg.norm(ab)*np.linalg.norm(ac)*np.linalg.norm(bc)
curvature=abs(2*(ab[0]*ac[1]-ab[1]*ac[0])/denom)
if curvature<1e-4:continue
curve_mps=math.sqrt(lateral_accel/curvature)
allowed_mps=math.sqrt(curve_mps**2+2*deceleration*float(b[0]))
if best is None or allowed_mps<best['speed_limit_mph'] / 2.2369362921:
best=dict(speed_limit_mph=allowed_mps*2.2369362921,
bend_distance_m=float(b[0]),curvature=curvature,
bend_speed_mph=curve_mps*2.2369362921)
return dict(available=True,covered_distance_m=float(samples[-1]),
braking_budget_mps2=deceleration,**(best or dict(speed_limit_mph=None)))
except (AttributeError,TypeError,ValueError,IndexError) as exc:
return dict(available=False,reason=str(exc),speed_limit_mph=None)
-209
View File
@@ -1,209 +0,0 @@
"""Pure admission policy for a limited simulator steering experiment.
This module has no actuator access. Its descriptive 579 inverse gain is not a
steering-angle calibration, and admission never grants production eligibility.
The caller owns foreground/operator cancellation and actual release/measurement.
"""
import math
import numbers
import time
def _finite(value):
if isinstance(value, bool) or not isinstance(value, numbers.Real):
return None
value = float(value)
return value if math.isfinite(value) else None
class PopSteeringTrial:
MAX_ACTIVE_S = 15.
MIN_SPEED_MPH = 24.
MAX_SPEED_MPH = 28.
MIN_AXIS = -.05
MAX_AXIS = .03
RATE_PER_S = .1
DESCRIPTIVE_579_GAIN = .1254
MAX_AGE_S = .15
ADMISSION_EDGE_STD_M = 1.5
CONTINUE_EDGE_STD_M = 1.75
def __init__(self):
self.reset()
def reset(self):
self._armed = False
self._started = None
self._finished = False
self._finish_reason = ''
self._last_stamp = None
self._last_sdk = None
self._last_sdk_change = None
self._last_output_time = None
self._axis = 0.
def _result(self, reason='', allowed=False, axis=0., **extra):
return dict(allowed_for_test=allowed, requested_axis=axis, reason=reason,
limited_simulator_experiment=True, production_eligible=False,
calibration=False, physical_calibration_validated=False,
controls_applied=False, pedals_commanded=False,
route_competence_validated=False, intersection_competence_validated=False,
active_since_monotonic=self._started, max_active_s=self.MAX_ACTIVE_S,
descriptive_inverse_gain=self.DESCRIPTIVE_579_GAIN,
admission_edge_std_limit_m=self.ADMISSION_EDGE_STD_M,
continuation_edge_std_limit_m=self.CONTINUE_EDGE_STD_M,
phase_edge_std_limit_m=(self.CONTINUE_EDGE_STD_M if self._started is not None
else self.ADMISSION_EDGE_STD_M),
edge_hysteresis_scope='limited active simulator trial only',
permitted_axis_range=[self.MIN_AXIS, self.MAX_AXIS], **extra)
def finish(self, reason='Operator finished trial'):
self._finished = True
self._armed = False
self._finish_reason = reason
self._axis = 0.
return self._result(reason)
def _sdk_reason(self, data, camera_guard):
if not isinstance(camera_guard, dict) or camera_guard.get('valid') is not True:
return 'Valid baseline camera guard required'
if not isinstance(data, dict) or data.get('valid') is not True or data.get('paused') is not False:
return 'Fresh unpaused SDK required'
if data.get('truck_name') != '579':
return 'This limited experiment is restricted to truck 579'
stamp = data.get('timestamp')
if isinstance(stamp, bool) or not isinstance(stamp, int) or stamp <= 0:
return 'Positive SDK timestamp required'
age = _finite(data.get('age'))
if age is None or not 0 <= age <= self.MAX_AGE_S:
return 'SDK age exceeds the experiment freshness bound'
if _finite(data.get('speed_mps')) is None:
return 'Finite SDK speed required'
return ''
def arm(self, telemetry, camera_guard, now=None):
now = _finite(time.monotonic() if now is None else now)
if self._started is not None or self._finished:
return self._result('Explicit reset and parked rearm required for another trial')
reason = self._sdk_reason(telemetry, camera_guard)
if not reason and now is None:
reason = 'Finite monotonic time required'
if not reason and (telemetry.get('park_brake') is not True or telemetry.get('gear') != 0
or abs(telemetry['speed_mps']) > .05):
reason = 'Parked stationary neutral startup required'
if not reason:
for key in ('user_steering', 'user_throttle', 'user_brake'):
value = _finite(telemetry.get(key))
if value is None or abs(value) > .02:
reason = 'Neutral manual inputs required before arming'
break
self._armed = not reason
return self._result(reason or 'Parked baseline armed; no steering requested', armed=self._armed)
def start(self, now=None):
now = _finite(time.monotonic() if now is None else now)
if not self._armed or self._finished or self._started is not None or now is None:
return self._result('A parked arm and a single explicit start are required')
self._started = now
self._last_output_time = now
return self._result('Limited experiment clock started; awaiting guarded model frame', started=True)
def _moving_reason(self, data, decision, model_action, camera_guard, now):
reason = self._sdk_reason(data, camera_guard)
if reason:
return reason
if now is None:
return 'Finite monotonic time required'
gear = data.get('gear')
if (isinstance(gear, bool) or not isinstance(gear, int) or gear <= 0
or data.get('park_brake') is not False or data.get('engine_enabled') is not True):
return 'Forward gear, released parking brake and running engine required'
mph = data['speed_mps'] * 2.2369362921
if not self.MIN_SPEED_MPH <= mph <= self.MAX_SPEED_MPH:
return 'Limited experiment speed must remain within 24–28 mph'
if (data.get('model_obstructed') is not False or data.get('model_geometry_stale') is not False
or data.get('model_inferred_this_frame') is not True):
return 'Fresh unobstructed inferred model frame required'
age = _finite(data.get('model_age_s'))
stamp = _finite(data.get('model_input_monotonic'))
if (age is None or not 0 <= age <= self.MAX_AGE_S or stamp is None
or not 0 <= now-stamp <= self.MAX_AGE_S):
return 'Model frame exceeds the experiment freshness bound'
coverage = data.get('model_temporal_coverage')
if (not isinstance(coverage, dict) or coverage.get('complete') is not True
or coverage.get('feature_slots_present') != 25
or coverage.get('feature_slots_required') != 25
or coverage.get('narrow_pair_present') is not True
or coverage.get('wide_pair_present') is not True):
return 'Complete actual paired Pop temporal coverage required'
if (not isinstance(decision, dict) or decision.get('allowed') is not True
or decision.get('steering_strategy') != 'model-yaw-action'):
detail = decision.get('reason') if isinstance(decision, dict) else None
return ('Trajectory not ready: ' + detail if isinstance(detail, str) and detail
else 'Current modern-action trajectory quality must be allowed by the core')
uncertainty = decision.get('uncertainty')
edge_max = _finite(uncertainty.get('max_edge_lateral_std_m')) if isinstance(uncertainty, dict) else None
configured_limit = _finite(uncertainty.get('edge_std_limit_m')) if isinstance(uncertainty, dict) else None
phase_cap = self.CONTINUE_EDGE_STD_M if self._started is not None else self.ADMISSION_EDGE_STD_M
if (edge_max is None or edge_max < 0 or configured_limit is None or configured_limit <= 0
or edge_max > phase_cap or configured_limit > phase_cap or edge_max > configured_limit):
return 'Road-edge uncertainty/configured limit exceeds the trial phase bound or is unavailable'
context = decision.get('context')
if not isinstance(context, dict) or context.get('model_input_monotonic') != stamp:
return 'Core quality decision must match this exact model frame'
if (not isinstance(model_action, dict) or model_action.get('available') is not True
or model_action.get('should_stop') is not False):
return 'Available modern action with no stop request required'
curvature = _finite(model_action.get('desired_curvature'))
acceleration = _finite(model_action.get('desired_acceleration'))
core_curve = _finite(decision.get('curvature'))
if curvature is None or acceleration is None or core_curve is None:
return 'Finite modern action and matching core curvature required'
if not math.isclose(core_curve, -curvature, rel_tol=1e-9, abs_tol=1e-12):
return 'Core curvature does not match the modern right-positive action'
target = -curvature / self.DESCRIPTIVE_579_GAIN
if not self.MIN_AXIS <= target <= self.MAX_AXIS:
return 'Requested axis outside [-0.05, 0.03]; the experiment rejects rather than clips'
return ''
def preflight(self, telemetry, decision, model_action, camera_guard, now=None):
now = _finite(time.monotonic() if now is None else now)
if not self._armed or self._finished or self._started is not None:
return self._result('Parked arm required before moving preflight')
reason = self._moving_reason(telemetry, decision, model_action, camera_guard, now)
return self._result(reason or 'Moving preflight eligible; no controls requested',
allowed=not reason, preflight_only=True)
def assess(self, telemetry, decision, model_action, camera_guard, now=None):
now = _finite(time.monotonic() if now is None else now)
if self._finished or self._started is None:
return self._result(self._finish_reason or 'Explicit start required')
if now is None or now < self._started or now-self._started >= self.MAX_ACTIVE_S:
return self.finish('Limited experiment time expired or clock invalid')
reason = self._moving_reason(telemetry, decision, model_action, camera_guard, now)
if reason:
return self.finish(reason)
stamp = float(telemetry['model_input_monotonic'])
if self._last_stamp is not None:
if stamp <= self._last_stamp:
return self.finish('Duplicate or out-of-order model input frame')
if stamp-self._last_stamp > self.MAX_AGE_S + 1e-12:
return self.finish('Model frame gap exceeds .15 seconds')
sdk = telemetry['timestamp']
if self._last_sdk is not None and sdk < self._last_sdk:
return self.finish('SDK timestamp reset during the trial')
if sdk != self._last_sdk:
self._last_sdk_change = now
elif now-self._last_sdk_change > self.MAX_AGE_S:
return self.finish('SDK distinct samples stalled during the trial')
dt = now-self._last_output_time
if dt < 0 or dt > self.MAX_AGE_S + 1e-12:
return self.finish('Active output cadence exceeds .15 seconds')
target = -float(model_action['desired_curvature']) / self.DESCRIPTIVE_579_GAIN
change = self.RATE_PER_S * dt
axis = min(self._axis+change, max(self._axis-change, target))
self._last_stamp, self._last_sdk = stamp, sdk
self._last_output_time, self._axis = now, axis
return self._result('Guarded limited simulator steering experiment', allowed=True, axis=axis,
target_axis=target, elapsed_active_s=now-self._started,
model_input_monotonic=stamp, desired_curvature_right_positive=model_action['desired_curvature'])
-230
View File
@@ -1,230 +0,0 @@
"""Passive Pop trajectory admission and steering preview; no actuator access.
Defaults are conservative simulator preview assumptions, not calibrated road
confidence or an approval for driving. The edge envelope and uncertainty are
network predictions. Physical extrinsics and upstream cadence remain unverified.
"""
import math
import numbers
import time
import numpy as np
from model.perception import X_IDXS
def _number(value):
if isinstance(value, bool) or not isinstance(value, numbers.Real):
return None
try:
value = float(value)
except (ValueError, OverflowError):
return None
return value if math.isfinite(value) else None
class PopTrajectoryController:
"""Assess fresh local geometry and output a bounded *unapplied* preview.
Path-center clearance is .35m plus one predicted standard deviation from
each path/edge. This is not a truck swept-volume or collision check. A
.75m path-std ceiling and 1.5m edge-std ceiling are preview rejection bounds.
Three frames and .2s are required to establish stable observations. The
.25 steering cap and .4 units/s rate limit do not validate vehicle response.
"""
def __init__(self, *, path_std_limit_m=.75, edge_std_limit_m=1.5,
corridor_margin_m=.35, uncertainty_sigma=1.,
steering_cap=.25, steering_rate_per_s=.4,
target_change_limit=.12, warmup_frames=3, warmup_s=.2,
max_frame_age_s=.2, max_frame_gap_s=.2,
max_speed_mph=30., advisory_lateral_accel_mps2=1.):
values = (path_std_limit_m, edge_std_limit_m, corridor_margin_m,
uncertainty_sigma, steering_cap, steering_rate_per_s,
target_change_limit, warmup_s, max_frame_age_s,
max_frame_gap_s, max_speed_mph, advisory_lateral_accel_mps2)
if any(_number(v) is None or v <= 0 for v in values):
raise ValueError('Invalid trajectory preview limits')
if (isinstance(warmup_frames, bool) or not isinstance(warmup_frames, int)
or warmup_frames < 3 or steering_cap > .35 or max_speed_mph > 30):
raise ValueError('Invalid trajectory preview bounds')
self.path_std_limit_m = float(path_std_limit_m)
self.edge_std_limit_m = float(edge_std_limit_m)
self.corridor_margin_m = float(corridor_margin_m)
self.uncertainty_sigma = float(uncertainty_sigma)
self.steering_cap = float(steering_cap)
self.steering_rate_per_s = float(steering_rate_per_s)
self.target_change_limit = float(target_change_limit)
self.warmup_frames, self.warmup_s = warmup_frames, float(warmup_s)
self.max_frame_age_s, self.max_frame_gap_s = float(max_frame_age_s), float(max_frame_gap_s)
self.max_speed_mph = float(max_speed_mph)
self.advisory_lateral_accel_mps2 = float(advisory_lateral_accel_mps2)
self.reset()
def reset(self):
self._last_seen = None
self._clear_tracking()
def _clear_tracking(self):
self._stable_since = None
self._stable_frames = 0
self._previous_target = None
self._previous_steer = 0.
self._previous_output_time = None
def assess(self, perception, speed_mps, telemetry, now=None, model_action=None):
now = time.monotonic() if now is None else now
result = dict(allowed=False, steer=0., target_steer=None, curvature=None,
max_speed_mph=None, reason='', controls_applied=False,
control_eligible=False, preview_only=True,
physical_calibration_validated=False,
upstream_cadence_validated=False,
path_std_max_m=None, road_edge_std_max_m=None, lookahead_m=None,
local_path={}, uncertainty={}, corridor={}, context={}, stability={},
steering_strategy='position-preview', desired_acceleration=None, should_stop=None)
def reject(reason):
self._clear_tracking()
result['reason'] = reason
return result
now, speed = _number(now), _number(speed_mps)
if now is None or speed is None or speed < .5 or speed * 2.2369362921 > self.max_speed_mph:
return reject('Invalid or unsupported preview speed/time')
if not isinstance(telemetry, dict):
return reject('Missing fresh model telemetry')
if telemetry.get('valid') is not True or telemetry.get('paused') is not False:
return reject('SDK unavailable or paused')
if (telemetry.get('model_obstructed') is not False
or telemetry.get('model_geometry_stale') is not False
or telemetry.get('model_inferred_this_frame') is not True):
return reject('Fresh unobstructed model geometry required')
obstruction = telemetry.get('camera_obstruction')
if obstruction is not None and (not isinstance(obstruction, dict)
or obstruction.get('checked') is not True or obstruction.get('blocked') is not False):
return reject('Camera obstruction check unavailable or blocked')
age = _number(telemetry.get('model_age_s'))
stamp = _number(telemetry.get('model_input_monotonic'))
if (age is None or age < 0 or age > self.max_frame_age_s or stamp is None
or now - stamp > self.max_frame_age_s or stamp - now > .05):
return reject('Model frame timestamp is missing or stale')
coverage = telemetry.get('model_temporal_coverage')
if (not isinstance(coverage, dict) or coverage.get('complete') is not True
or coverage.get('feature_slots_present') != 25
or coverage.get('feature_slots_required') != 25
or coverage.get('narrow_pair_present') is not True
or (coverage.get('wide_pair_required') is True
and coverage.get('wide_pair_present') is not True)):
return reject('Complete actual model temporal coverage required')
result['context'] = dict(coverage, model_input_monotonic=stamp, model_age_s=age)
if self._last_seen is not None and stamp <= self._last_seen:
return reject('Duplicate or out-of-order model frame')
gap = stamp - self._last_seen if self._last_seen is not None else None
self._last_seen = stamp
if gap is not None and gap > self.max_frame_gap_s:
return reject('Model inference gap; stable preview must rewarm')
result['context']['frame_gap_s'] = gap
plan = getattr(perception, 'plan', None)
try:
x, y, z = (np.asarray(getattr(plan, name), dtype=float) for name in ('x', 'y', 'z'))
std = np.asarray(perception.plan_std, dtype=float)
edges = np.asarray(perception.road_edges, dtype=float)
edge_std = np.asarray(perception.road_edge_std, dtype=float)
edge_x = np.asarray(getattr(perception, 'road_edge_x', X_IDXS), dtype=float)
except (AttributeError, TypeError, ValueError):
return reject('Missing trajectory or road-edge uncertainty evidence')
if (any(a.shape != (33,) or not np.all(np.isfinite(a)) for a in (x, y, z))
or std.shape != (33, 15) or not np.all(np.isfinite(std)) or np.any(std < 0)
or edges.shape != (2, 33, 2) or not np.all(np.isfinite(edges))
or edge_std.shape != (2, 33, 2) or not np.all(np.isfinite(edge_std))
or np.any(edge_std < 0) or edge_x.shape != (33,)
or not np.all(np.isfinite(edge_x)) or np.any(np.diff(edge_x) <= 0)):
return reject('Invalid trajectory or road-edge arrays')
lookahead = float(np.clip(speed * 1.5, 8., 25.))
result['lookahead_m'] = lookahead
horizon = lookahead + 2.
breaks = np.flatnonzero(np.diff(x) <= 0)
prefix_count = int(breaks[0]) + 1 if len(breaks) else 33
px, py, ps = x[:prefix_count], y[:prefix_count], std[:prefix_count, 1]
result['local_path'] = dict(lookahead_m=lookahead, required_horizon_m=horizon,
prefix_points=prefix_count,
prefix_end_x_m=float(px[-1]),
future_x_reversal=bool(len(breaks)),
velocity_evidence_present=getattr(plan, 'velocity', None) is not None,
stop_intent_assessed=False)
if abs(x[0]) > 2 or prefix_count < 2 or px[-1] < horizon or x[0] > 1:
return reject('Ascending local trajectory does not cover steering horizon')
start = max(0., float(px[0]))
grid = np.unique(np.concatenate(([start, lookahead, horizon],
px[(px >= start) & (px <= horizon)],
edge_x[(edge_x >= start) & (edge_x <= horizon)])))
if edge_x[0] > start or edge_x[-1] < horizon:
return reject('Road edges do not cover local steering horizon')
path_y, path_std = np.interp(grid, px, py), np.interp(grid, px, ps)
left = np.interp(grid, edge_x, edges[0, :, 0])
right = np.interp(grid, edge_x, edges[1, :, 0])
left_std = np.interp(grid, edge_x, edge_std[0, :, 0])
right_std = np.interp(grid, edge_x, edge_std[1, :, 0])
result['uncertainty'] = dict(max_path_lateral_std_m=float(path_std.max()),
max_edge_lateral_std_m=float(max(left_std.max(), right_std.max())),
path_std_limit_m=self.path_std_limit_m,
edge_std_limit_m=self.edge_std_limit_m,
probability_assessed=False)
result['path_std_max_m'] = float(path_std.max())
result['road_edge_std_max_m'] = float(max(left_std.max(), right_std.max()))
if np.any(left >= right):
return reject('Road edges are unordered in the local horizon')
if path_std.max() > self.path_std_limit_m:
return reject('Local path uncertainty exceeds preview bound')
if max(left_std.max(), right_std.max()) > self.edge_std_limit_m:
return reject('Local road-edge uncertainty exceeds preview bound')
lower = left + self.corridor_margin_m + self.uncertainty_sigma * (left_std + path_std)
upper = right - self.corridor_margin_m - self.uncertainty_sigma * (right_std + path_std)
left_clearance, right_clearance = path_y - lower, upper - path_y
result['corridor'] = dict(source='model road edges; estimated, uncalibrated',
margin_m=self.corridor_margin_m, uncertainty_sigma=self.uncertainty_sigma,
min_left_clearance_m=float(left_clearance.min()),
min_right_clearance_m=float(right_clearance.min()),
truck_swept_volume_assessed=False, traffic_assessed=False)
if np.any(lower >= upper) or np.any(left_clearance < 0) or np.any(right_clearance < 0):
return reject('Local path is outside the uncertainty-adjusted road envelope')
lateral = -float(np.interp(lookahead, px, py))
curvature = 2 * lateral / (lookahead * lookahead + lateral * lateral)
if model_action is not None:
if not isinstance(model_action, dict) or model_action.get('available') is not True:
return reject('Complete modern model action required')
model_curvature = _number(model_action.get('desired_curvature'))
acceleration = _number(model_action.get('desired_acceleration'))
if model_curvature is None or acceleration is None or type(model_action.get('should_stop')) is not bool:
return reject('Invalid modern model action')
# Modern yaw curvature is positive right; the ATS axis is positive left.
curvature = -model_curvature
result.update(steering_strategy='model-yaw-action',
desired_acceleration=acceleration, should_stop=model_action['should_stop'],
model_action=model_action)
target = float(np.clip(math.atan(curvature * 4.5) / math.radians(35),
-self.steering_cap, self.steering_cap))
curve_speed = (math.sqrt(self.advisory_lateral_accel_mps2 / abs(curvature)) * 2.2369362921
if abs(curvature) > 1e-8 else self.max_speed_mph)
result.update(target_steer=target, curvature=curvature,
max_speed_mph=min(self.max_speed_mph, curve_speed),
speed_advisory_semantics='curvature-only; unassessed vehicle/road dynamics, not a speed command')
if self._previous_target is not None and abs(target - self._previous_target) > self.target_change_limit:
return reject('Trajectory steering target changed abruptly; rewarm')
if self._stable_since is None:
self._stable_since = stamp
self._stable_frames += 1
self._previous_target = target
stable_s = stamp - self._stable_since
result['stability'] = dict(unique_frames=self._stable_frames, duration_s=stable_s,
required_frames=self.warmup_frames, required_duration_s=self.warmup_s)
if self._stable_frames < self.warmup_frames or stable_s + 1e-9 < self.warmup_s:
result['reason'] = 'Warming stable local trajectory preview'
return result
output_dt = (stamp - self._previous_output_time
if self._previous_output_time is not None else min(gap or 0., self.max_frame_gap_s))
change = self.steering_rate_per_s * max(0., output_dt)
steer = float(np.clip(target, self._previous_steer - change, self._previous_steer + change))
self._previous_steer, self._previous_output_time = steer, stamp
result.update(allowed=True, steer=steer, reason='Stable bounded trajectory preview; active control remains ineligible')
return result
-41
View File
@@ -1,41 +0,0 @@
"""One model-intent pulse per turn signal, solely for passive evaluation.
Inspired by IQ.Pilot's delay/consumed/cancel behavior. This does not establish
adjacent-lane clearance, monitor blind spots, or command a lane change.
"""
import math
class SignalPreview:
def __init__(self, delay=1.0):
if delay not in (0.05, 0.5, 1.0, 2.0, 3.0):
raise ValueError("Unsupported signal delay")
self.delay = delay
self.reset()
def reset(self):
self.direction = "none"
self.started = None
self.used = False
def update(self, data, now):
left, right = data.get('blinker_left', False), data.get('blinker_right', False)
direction = 'left' if left and not right else 'right' if right and not left else 'none'
if (not data.get('valid') or data.get('paused') or direction == 'none'
or data.get('hazards') or not math.isfinite(now)):
self.reset()
return 'none'
if direction != self.direction:
self.direction, self.started, self.used = direction, now, False
if now < self.started:
self.reset()
return 'none'
# Braking cancels the current signal even if it is subsequently released.
if data.get('user_brake', 0) > 0.05 or data.get('park_brake'):
self.used = True
speed = data.get('speed_mph', 0)
if (not self.used and math.isfinite(speed) and speed >= 10
and now-self.started >= self.delay):
self.used = True
return direction
return 'none'
-743
View File
@@ -1,743 +0,0 @@
"""ATS Supercombo driving loop with verified telemetry and supervised engagement."""
import argparse
import json
import logging
import os
from pathlib import Path
import time
import cv2
import numpy as np
from datetime import datetime
from control.windows_input import ATSWindow, KeyboardInput, TakeoverMonitor
from control.fsd_controller import FSDController
from control.path_preview import path_reason, preview_steering
from control.pop_trajectory import PopTrajectoryController
from control.pop_model_actions import PopModelActions
from control.signal_preview import SignalPreview
from control.navigation_preview import route_preview
from control.lane_choice_preview import lane_choice_preview
from control.virtual_joystick import dll_path
from telemetry.ats_telemetry import ATSTelemetry
from telemetry.gps_route_reader import GPSRouteReader
from telemetry.nearby_traffic import NearbyTrafficReader
from telemetry.traffic_tracker import TrafficTracker
from telemetry.road_geometry import RoadGeometryReader
from telemetry.junction_paths import JunctionPathReader
from model.runner import create_brain
from model.registry import ModelRegistry
from vision.screen_capture import ScreenCapture
from vision.calibration_recorder import CalibrationRecorder
from vision.auxiliary_camera_health import AuxiliaryCameraHealth
from vision.scene_frame import scene_perception, load_scene_origin
from vision.camera_obstruction import guarded_model_step
from vision.preview_clock import MotionRecordingClock
from ui.tesla_fsd_hud import TeslaFSDHUD
from audio.chimes import TeslaChimes
from runtime_checks import readiness_reason, LaneConfidenceGrace, inset_cruise_test_reason, parked_setting_reason
ROOT = Path(__file__).resolve().parent
TITLE = "Tesla Semi FSD - OpenPilot"
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--diagnose", action="store_true", help="Report health without injecting controls")
parser.add_argument("--dry-run", action="store_true", help="Show requested controls without injecting them")
parser.add_argument("--record-calibration", action="store_true",
help="Record exact inset frames and model outputs; requires auxiliary dry run")
parser.add_argument('--record-image-hz', type=int, choices=range(1, 21), default=1,
help='Maximum saved camera frames per second for passive calibration (1 to 20)')
parser.add_argument("--duration", type=float, help="Exit after this many seconds")
parser.add_argument('--duration-after-motion', action='store_true',
help='Passive recording: wait for forward motion before starting --duration')
parser.add_argument("--no-hud", action="store_true")
parser.add_argument("--hud-mode", choices=("dashboard", "cockpit_screen"), default="dashboard",
help="Panel layout: dashboard includes the model camera preview")
parser.add_argument("--speed", type=float, default=15.0, help="Cruise speed MPH (5 to 55; default 15)")
parser.add_argument("--lane-only", action="store_true", help="Validate lane keeping with manual speed control")
parser.add_argument("--driving-mode", choices=("manual", "cruise", "chill"),
help="Manual pedals, speed cruise, or gentler cruise with a longer following gap")
parser.add_argument("--model", default="supercombo-6409", help="Registered local model ID")
parser.add_argument("--list-models", action="store_true", help="List local models without acquiring controls")
parser.add_argument("--path-preview", action="store_true", help="Passive laneless trajectory evaluation; requires --dry-run")
parser.add_argument("--signal-preview", action="store_true", help="Passive turn-signal model-intent evaluation; requires --dry-run")
parser.add_argument("--navigation-preview", action="store_true", help="Live GPS route/map preview; requires --dry-run, sends no navigation commands")
parser.add_argument("--navigation-observe", action="store_true", help="Show and record read-only GPS beside existing inset driving")
parser.add_argument("--navigation-driving-test", action="store_true", help="Bounded GPS-assisted inset steering and Chill cruise trial")
parser.add_argument("--signal-delay", type=float, choices=(0.05, 0.5, 1.0, 2.0, 3.0), default=1.0)
parser.add_argument("--inset-cruise-test", action="store_true",
help="Bounded inset cruise validation after steering checks; max 15 MPH, 120 seconds")
parser.add_argument("--camera", choices=("bumper", "cabin", "auxiliary"), default="bumper",
help="Model camera: validated bumper, experimental cabin, or configured road inset")
parser.add_argument("--backend", choices=("auto", "vjoy", "keyboard"), default="auto",
help="Analog vJoy when installed, otherwise keyboard feedback")
parser.add_argument("--inference-provider", choices=("auto", "cpu", "directml"), default="auto",
help="Model runner; CPU avoids contention with ATS rendering on this system")
args = parser.parse_args()
registry = ModelRegistry(ROOT / "models")
if args.list_models:
print(json.dumps(registry.inventory(), indent=2))
return
if args.lane_only and args.driving_mode not in (None, "manual"):
parser.error("--lane-only requires manual driving mode")
args.driving_mode = args.driving_mode or ("manual" if args.lane_only else "cruise")
args.lane_only = args.driving_mode == "manual"
if args.navigation_driving_test:
if args.dry_run or args.navigation_preview:
parser.error("Navigation driving test is an active bounded trial; use --navigation-preview for passive evaluation")
args.navigation_observe = True
args.inset_cruise_test = True
if args.driving_mode != 'chill':
parser.error('Navigation driving test requires --driving-mode chill')
if args.navigation_observe and args.camera != "auxiliary":
parser.error("Navigation observation requires the configured auxiliary camera")
if (args.path_preview or args.signal_preview or args.navigation_preview) and not args.dry_run:
parser.error("Path, signal and navigation previews require --dry-run; they cannot control the truck")
try:
selected_model = registry.select(args.model)
except (ValueError, OSError, KeyError) as exc:
parser.error(str(exc))
model_manifest = selected_model["metadata"]
if model_manifest.get('preview_only') and not args.dry_run and not args.diagnose:
parser.error('Pop v2 requires --dry-run until its wide camera and trajectory control are validated')
baseline_hash = json.loads((ROOT / "models/manifest.json").read_text())["sha256"]
if not args.dry_run and args.camera != "auxiliary" and model_manifest["sha256"] != baseline_hash:
parser.error("New models require passive evaluation and camera calibration before control")
if args.record_calibration and (not args.dry_run or args.camera != "auxiliary"):
parser.error("--record-calibration requires --camera auxiliary --dry-run")
if args.record_image_hz > 1 and not (args.record_calibration and args.dry_run):
parser.error('High-rate images require --record-calibration --dry-run')
if args.duration_after_motion:
if not (args.dry_run and args.record_calibration and args.duration is not None):
parser.error('--duration-after-motion requires --dry-run --record-calibration --duration')
try:
motion_clock = MotionRecordingClock(args.duration)
except ValueError as exc:
parser.error(str(exc))
else:
motion_clock = None
if args.inset_cruise_test:
test_reason = inset_cruise_test_reason(args.camera, args.backend, args.lane_only,
args.dry_run, args.duration, args.speed)
if test_reason:
parser.error(test_reason)
os.chdir(ROOT)
(ROOT / "diagnostics").mkdir(exist_ok=True)
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s",
handlers=[logging.StreamHandler(),
logging.FileHandler(ROOT / "diagnostics/session.log", encoding="utf-8")])
log = logging.getLogger("ats-fsd")
window = ATSWindow()
brain = create_brain(selected_model, use_gpu=args.inference_provider != "cpu")
telemetry = ATSTelemetry()
if args.inference_provider == "directml" and brain.active_provider != "DmlExecutionProvider":
telemetry.close()
raise RuntimeError("DirectML was requested but is not available")
backend = args.backend
if backend == "auto":
backend = "vjoy" if dll_path() else "keyboard"
log.info("Model provider=%s; backend=%s; dry_run=%s", brain.active_provider, backend, args.dry_run)
log.info("Model id=%s hash=%s driving_mode=%s", args.model, model_manifest["sha256"], args.driving_mode)
if args.diagnose:
data = telemetry.get_data()
time.sleep(0.1)
data = telemetry.get_data()
output = {"ats_window": bool(window.find()), "ats_foreground": window.foreground(),
"provider": brain.active_provider, "telemetry": data,
"backend": backend, "vjoy_dll": str(dll_path()) if dll_path() else None}
print(json.dumps(output, indent=2))
telemetry.close()
return
capture = ScreenCapture(window=window, camera_view=args.camera)
scene_configs = {
'Pinnacle': load_scene_origin(capture.auxiliary, ROOT / 'diagnostics' / 'scene-origin.json'),
'579': load_scene_origin(capture.auxiliary, ROOT / 'diagnostics' / 'scene-origin-579.json'),
}
scene_config = scene_configs.get(telemetry.get_data().get('truck_name'), scene_configs['Pinnacle'])
if args.camera == "auxiliary" and not args.dry_run and not capture.auxiliary.get("calibrated"):
capture.close()
telemetry.close()
raise RuntimeError("Road inset needs passive calibration first; use --camera auxiliary --dry-run")
camera_health = None
if args.camera == "auxiliary" and not args.dry_run:
camera_health = AuxiliaryCameraHealth(capture.auxiliary,
model_manifest["sha256"], args.lane_only,
cruise_test=args.inset_cruise_test)
if camera_health.startup_reason:
capture.close()
telemetry.close()
raise RuntimeError(camera_health.startup_reason)
if args.camera == "auxiliary":
log.warning("Experimental road inset: verify ForwardCamera operation and passive calibration before active control")
# Passive dry runs never acquire or alter virtual-controller axes.
controller = FSDController(mode="keyboard" if args.dry_run else backend,
keyboard=KeyboardInput(window), camera_view=args.camera,
driving_mode=args.driving_mode)
controller.cruise_set_speed = min(55.0, max(5.0, args.speed))
monitor = TakeoverMonitor(ignore_pedals=args.lane_only or args.dry_run)
chimes = TeslaChimes()
hud = TeslaFSDHUD(width=1280, height=720)
hud.mode = args.hud_mode
if not args.no_hud:
cv2.namedWindow(TITLE, cv2.WINDOW_NORMAL)
cv2.resizeWindow(TITLE, 1280, 720)
# Put diagnostics on a second monitor when one is available.
if len(capture.sct.monitors) > 2:
second = capture.sct.monitors[2]
cv2.moveWindow(TITLE, second["left"], second["top"])
engaged = False
pending_until = None
stable_frames = 0
status = "Bring ATS to the foreground; F8 engages"
last_status = None
started = last_report = time.monotonic()
next_idle_record_at = 0.
next_hud_render_at = 0.
last_perception_report = started
perception = brain.step(np.zeros((1, 12, 128, 256), np.float32))
camera = np.zeros((256, 512, 3), np.uint8)
last_inference_ms = 0.0
last_inference_at = None
obstruction_report = dict(checked=False, blocked=False, inference_skipped=True,
reason='Waiting for a fresh forward camera frame')
inference_telemetry = None
recorder = None
confidence_grace = LaneConfidenceGrace()
holding_vision = False
signal_preview = SignalPreview(args.signal_delay) if args.signal_preview else None
navigation = GPSRouteReader() if args.navigation_preview or args.navigation_observe else None
navigation_driver = None
if args.navigation_driving_test:
from control.navigation_driver import NavigationDriver
navigation_driver = NavigationDriver()
navigation_decision = None
pop_controller = (PopTrajectoryController()
if args.path_preview and selected_model.get('id') == 'pop-v2' else None)
pop_actions = PopModelActions() if pop_controller else None
pop_decision = None
last_control_command = None
traffic = NearbyTrafficReader()
traffic_tracker = TrafficTracker()
road_geometry = RoadGeometryReader()
junction_paths = JunctionPathReader(road_geometry)
last_navigation_label = None
def refresh_scene(data, original, route):
nonlocal scene_config
# Display copies only: steering and paired model evidence retain the
# original camera-frame perception and their existing calibration.
data['camera_mode'] = args.camera
scene_config = scene_configs.get(data.get('truck_name'), scene_configs['Pinnacle'])
scene, alignment = scene_perception(original, data, scene_config)
if (data.get('model_obstructed') is not False
or data.get('model_geometry_stale') is True):
alignment.update(available=False,
reason=(data.get('camera_obstruction', {}).get('reason')
if data.get('model_obstructed') is True else
'Fresh unobstructed model geometry is unavailable'))
data['scene_alignment'] = alignment
traffic_for_lanes = data['nearby_traffic'] if alignment['available'] else {
'available': False, 'reason': 'Camera-to-truck alignment unavailable'}
data['lane_choice_preview'] = lane_choice_preview(scene.lanes,
traffic_for_lanes, data['road_geometry'], route if navigation else None,
data, data['junction_paths'])
data['lane_choice_preview']['scene_alignment_estimated'] = alignment['available']
return scene
def disengage(reason):
nonlocal engaged, pending_until, stable_frames, status, holding_vision, last_control_command
was_active = engaged or pending_until is not None
engaged, pending_until, stable_frames = False, None, 0
controller.release_all_controls()
last_control_command = None
confidence_grace.reset()
if navigation_driver:
navigation_driver.reset()
if pop_controller:
pop_controller.reset()
pop_actions.reset()
holding_vision = False
status = "Disengaged: " + reason
if was_active:
chimes.play_disengage()
log.info("DISENGAGED: %s", reason)
log.info("GPS preview: driving controls OFF; F8 does not enable driving." if args.navigation_preview else
"F8 toggles. Physical driving/camera controls or Escape take over. Tab belongs to ATS.")
try:
if args.record_calibration or args.navigation_observe:
prefix = 'navigation-drive-' if args.navigation_driving_test else 'navigation-observe-' if args.navigation_observe else 'inset-cal-'
directory = ROOT / "diagnostics" / (prefix + datetime.now().strftime("%Y%m%d-%H%M%S-%f"))
recorder = CalibrationRecorder(directory, dict(
camera=scene_config, provider=brain.active_provider,
model=model_manifest,
image_save_hz=args.record_image_hz,
async_write=bool(pop_controller), async_queue_capacity=8,
auxiliary_camera=capture.auxiliary,
duration_clock='first_forward_motion' if motion_clock else 'startup',
dry_run=args.dry_run, path_preview=args.path_preview, signal_preview=args.signal_preview,
navigation_preview=args.navigation_preview, navigation_observe=args.navigation_observe,
navigation_driving=args.navigation_driving_test,
projection="Historical MED calibration frame: lane z already includes height; visual alignment check"))
log.info("PAIRED recording to %s; driving controls %s; GPS mode=%s", directory,
'OFF' if args.dry_run else 'available through F8',
'driving trial' if args.navigation_driving_test else 'observation')
previous_loop_start = None
while (not motion_clock.expired(time.monotonic()) if motion_clock else
args.duration is None or time.monotonic() - started < args.duration):
loop_start = time.monotonic()
loop_fps = (1.0 / max(0.001, loop_start - previous_loop_start)
if previous_loop_start is not None else 0.0)
previous_loop_start = loop_start
toggles, takeover = monitor.consume()
data = telemetry.get_data()
data['nearby_traffic'] = traffic_tracker.snapshot(traffic.snapshot(data), data)
if navigation:
route = navigation.snapshot(data)
data['navigation_preview'] = route_preview(route, data)
data['navigation_route'] = route
data['navigation_observer'] = args.navigation_observe
data['navigation_driving'] = args.navigation_driving_test
data['road_geometry'] = road_geometry.snapshot(data, route if navigation else None)
data['junction_paths'] = junction_paths.snapshot(data, data['road_geometry'])
foreground = window.foreground()
if takeover and (engaged or pending_until is not None):
disengage(takeover)
if toggles % 2 and not args.navigation_preview:
if engaged or pending_until is not None:
disengage("Disengaged with F8")
else:
# Only reset camera after game and telemetry are live.
reason = readiness_reason(foreground, data,
independent_camera=camera_health is not None)
if not reason and camera_health:
reason = camera_health.reason(data)
if not reason and obstruction_report.get('blocked'):
reason = obstruction_report['reason']
if reason == "Look straight ahead through the windshield":
reason = ""
if reason:
status = "Engagement blocked: " + reason
log.info(status)
else:
if navigation_driver:
navigation_driver.reset()
if not args.dry_run:
controller.reset()
else:
controller.fault = None
# The corrected inset has not changed when F8 centers
# the driver's view. Keep its recent recurrent context;
# reset after a pause/focus gap or for other camera modes.
if not (camera_health and last_inference_at is not None
and time.monotonic() - last_inference_at < 0.25):
brain.reset_state()
capture.reset_history()
pending_until = loop_start + 3.0
stable_frames = 0
status = "Checking forward road view"
vision_reason = "Waiting for forward camera"
inferred_this_loop = False
captured_this_loop = False
pop_decision = None
obstruction_report = dict(checked=False, blocked=False, inference_skipped=True,
reason='No fresh forward camera frame')
if signal_preview and not (foreground and data.get("valid")):
signal_preview.reset()
if foreground and data.get("valid"):
try:
imgs, camera, _ = capture.get_model_input(inset_only=True) if args.camera == 'auxiliary' else capture.get_model_input()
if hasattr(brain, 'set_wide_input'):
brain.set_wide_input(capture.wide_input)
captured_this_loop = True
# Head look can cross into the window animation during
# capture. Check its latest pose before feeding this frame.
data.update(telemetry.get_data())
before = time.perf_counter()
if signal_preview:
pulse = signal_preview.update(data, loop_start)
brain.set_desire(pulse)
data["model_desire_pulse"] = pulse
if pulse != "none":
log.info("SIGNAL PREVIEW desire=%s; driving controls OFF; adjacent traffic unverified", pulse)
fresh_perception, obstruction_report = guarded_model_step(
brain, imgs, camera, enabled=args.camera == 'auxiliary',
report_sink=obstruction_report, telemetry=data,
wide_image=getattr(capture, 'wide_camera', None))
data['camera_obstruction'] = obstruction_report
data['model_obstructed'] = (obstruction_report['blocked']
if obstruction_report.get('checked') else None)
if fresh_perception is None:
# Retain the previous actual model arrays as stale evidence.
# Reset image/recurrent history so the blocked frame cannot
# become the next clear frame's temporal context.
vision_reason = obstruction_report['reason']
capture.reset_history()
confidence_grace.reset()
navigation_decision = None
if signal_preview:
signal_preview.reset()
data['model_desire_pulse'] = 'none'
if navigation_driver:
navigation_driver.reset()
if engaged or pending_until is not None:
disengage(vision_reason)
else:
perception = fresh_perception
last_inference_ms = (time.perf_counter() - before) * 1000
last_inference_at = time.monotonic()
vision_reason = (path_reason(perception.plan, data["speed_mps"]) if args.path_preview
else controller.vision_reason(perception))
if navigation_driver:
navigation_decision = navigation_driver.assess(perception, data['speed_mps'],
route, data['navigation_preview'], data, now=loop_start)
vision_reason = '' if navigation_decision['allowed'] else navigation_decision['reason']
data['navigation_driver'] = navigation_decision
inferred_this_loop = True
data['model_age_s'] = 0.0
data['model_inferred_this_frame'] = True
data['model_geometry_stale'] = False
if hasattr(brain, 'camera_input_mode'):
data['model_camera_input_mode'] = brain.camera_input_mode
data['model_temporal_ready'] = brain.temporal_ready
data['model_input_monotonic'] = brain.last_timestamp
data['model_temporal_coverage'] = brain.temporal_coverage
if pop_controller:
data['pop_model_actions'] = pop_actions.assess(perception, data['speed_mps'])
data['camera_projection'] = capture.auxiliary.get('projection')
pop_decision = pop_controller.assess(perception, data['speed_mps'],
data, now=time.monotonic(), model_action=data['pop_model_actions'])
data['pop_trajectory_controller'] = pop_decision
vision_reason = '' if pop_decision['allowed'] else pop_decision['reason']
if args.path_preview:
data['trajectory_preview'] = dict(
applied=False, reason=vision_reason,
requested_steering=(pop_decision['steer'] if pop_decision and pop_decision['allowed']
else preview_steering(perception.plan, data['speed_mps'])
if not pop_controller and not vision_reason else None),
confidence_unassessed=True)
refresh_scene(data, perception, route if navigation else None)
except (RuntimeError, ValueError, cv2.error) as exc:
vision_reason = "Camera/model failure: " + str(exc)
if pop_controller and not inferred_this_loop:
pop_controller.reset()
pop_actions.reset()
data.update(camera_obstruction=obstruction_report,
model_obstructed=(obstruction_report.get('blocked') if obstruction_report.get('checked') else None),
model_inferred_this_frame=inferred_this_loop,
model_geometry_stale=not inferred_this_loop,
model_age_s=(max(0., time.monotonic()-last_inference_at)
if last_inference_at is not None else 1e6))
if captured_this_loop:
if not inferred_this_loop:
refresh_scene(data, perception, route if navigation else None)
inference_telemetry = dict(data)
# Inference can wait on the game's GPU. Recheck game state before
# publishing a command, rather than using the pre-inference sample.
data = telemetry.get_data()
if inferred_this_loop and inference_telemetry:
for key in ('model_camera_input_mode', 'model_temporal_ready',
'model_input_monotonic', 'model_temporal_coverage',
'trajectory_preview', 'pop_trajectory_controller', 'pop_model_actions',
'camera_projection'):
if key in inference_telemetry:
data[key] = inference_telemetry[key]
data.update(camera_obstruction=obstruction_report,
model_obstructed=(obstruction_report.get('blocked') if obstruction_report.get('checked') else None),
model_inferred_this_frame=inferred_this_loop,
model_geometry_stale=not inferred_this_loop)
data['nearby_traffic'] = traffic_tracker.snapshot(traffic.snapshot(data), data)
if navigation:
route = navigation.snapshot(data)
data['navigation_preview'] = route_preview(route, data)
data['navigation_route'] = route
data['navigation_observer'] = args.navigation_observe
data['navigation_driving'] = args.navigation_driving_test
data['navigation_driver'] = navigation_decision
nav_label = (data['navigation_preview']['label'], data['navigation_preview']['reason'])
if nav_label != last_navigation_label:
log.info('GPS: %s; %s; navigation mode=%s', *nav_label,
'trial' if navigation_driver else 'observation')
last_navigation_label = nav_label
data['road_geometry'] = road_geometry.snapshot(data, route if navigation else None)
data['junction_paths'] = junction_paths.snapshot(data, data['road_geometry'])
data['model_age_s'] = (max(0., time.monotonic()-last_inference_at)
if last_inference_at is not None else 1e6)
display_perception = refresh_scene(data, perception, route if navigation else None)
foreground = window.foreground()
reason = readiness_reason(foreground, data, actuator_fault=controller.fault,
independent_camera=camera_health is not None)
if not reason and camera_health:
reason = camera_health.reason(data)
if not reason and obstruction_report.get('blocked'):
reason = obstruction_report['reason']
if not reason and navigation_driver and not data['navigation_preview']['available']:
reason = 'GPS driving trial: ' + data['navigation_preview']['reason']
if not reason and navigation_driver and not navigation_decision:
reason = 'Waiting for fresh GPS driving decision'
if navigation_driver and navigation_decision and navigation_decision['allowed']:
controller.cruise_set_speed = min(args.speed, navigation_decision['max_speed_mph'])
if not reason and camera_health:
reason = camera_health.speed_reason(data)
if (not reason and not args.lane_only and not args.dry_run and not engaged
and max(data.get("user_throttle",0),data.get("user_brake",0)) > 0.05):
reason = "Release manual pedals before engaging cruise"
hold_vision = False
if engaged and camera_health:
hold_vision = confidence_grace.allow_hold(time.monotonic(), vision_reason,
(perception.lanes.left_prob, perception.lanes.right_prob), healthy=not reason)
else:
confidence_grace.reset()
if not reason and not hold_vision:
reason = vision_reason
if hold_vision and not holding_vision:
log.info("VISION_GRACE holding previous steering, pedals released; lane_prob=%.3f/%.3f",
perception.lanes.left_prob, perception.lanes.right_prob)
elif holding_vision and not hold_vision and not reason:
log.info("VISION_GRACE recovered")
holding_vision = hold_vision
if not reason and camera_health and pending_until is not None:
reason = controller.engagement_reason(perception)
if (args.dry_run or args.camera == "auxiliary") and foreground and data.get("valid") and loop_start - last_perception_report > 1.0:
log.info("PERCEPTION speed=%.1f lane_prob=%.2f/%.2f width=%.2f path_forward=%.1f inference=%.1fms reason=%s",
data["speed_mph"], perception.lanes.left_prob, perception.lanes.right_prob,
float(np.median(perception.lanes.right_y[:10] - perception.lanes.left_y[:10])),
float(perception.plan.x[-1]), last_inference_ms, vision_reason or "usable")
last_perception_report = loop_start
if engaged and reason:
disengage(reason)
# Controls are already released. Preserve the last actual
# model input/output so a dropout can be inspected afterward.
if (camera_health and inference_telemetry is not None
and last_inference_at is not None and last_inference_at >= loop_start):
release_recorder = None
try:
directory = ROOT / "diagnostics" / ("inset-release-" + datetime.now().strftime("%Y%m%d-%H%M%S-%f"))
release_recorder = CalibrationRecorder(directory, dict(
camera=scene_config, provider=brain.active_provider,
model=model_manifest,
controls_released=True, release_reason=reason,
input_age_seconds=time.monotonic()-last_inference_at,
release_telemetry=data,
projection="Historical MED calibration frame; last inferred input/output"))
release_recorder.record(camera, perception, inference_telemetry,
last_inference_ms, vision_reason)
log.info("Release evidence saved to %s", directory)
except Exception:
log.exception("Could not save release evidence; controls remain released")
finally:
if release_recorder:
try:
release_recorder.close()
except Exception:
log.exception("Could not close release evidence")
if pending_until is not None:
if not foreground or not data.get("valid") or controller.fault:
disengage(reason)
elif reason:
stable_frames = 0
status = "Checking road: " + reason
else:
stable_frames += 1
if stable_frames >= 10:
engaged = True
pending_until = None
confidence_grace.allow_hold(time.monotonic(), "",
(perception.lanes.left_prob, perception.lanes.right_prob))
chimes.play_engage()
status = ("GPS-assisted steering and Chill cruise trial" if navigation_driver else
"DRY RUN" if args.dry_run else
f"Lane keeping active; manual speed ({backend})" if args.lane_only else
f"Lane keeping and cruise active ({backend})")
log.info("ENGAGED speed=%.1f MPH lane_prob=%.2f/%.2f", data["speed_mph"],
perception.lanes.left_prob, perception.lanes.right_prob)
if pending_until is not None and loop_start > pending_until:
disengage("Engagement blocked: " + (reason or "Road view did not stabilize"))
if engaged:
if args.path_preview:
steer = (pop_decision['steer'] if pop_controller and pop_decision
else preview_steering(perception.plan, data["speed_mps"]))
action, intensity = "coast", 0.0
elif hold_vision:
steer = controller.current_steer
action, intensity = "coast", 0.0
controller.cruise.reset()
else:
steer = (navigation_decision['steer'] if navigation_driver and navigation_decision
else controller.compute_lateral(perception, data["speed_mps"]))
action, intensity = controller.compute_longitudinal(perception, data["speed_mph"])
if args.lane_only:
action, intensity = "coast", 0.0
command_issued_at = time.monotonic()
if not args.dry_run:
controller.apply_controls(steer, action, intensity, data["steering"])
last_control_command = dict(steering=steer, action=action, intensity=intensity,
applied=not args.dry_run, monotonic=command_issued_at,
loop_monotonic=loop_start,
enqueued_monotonic=time.monotonic() if not args.dry_run else None,
timing_source='host command enqueue; not driver acknowledgment')
if loop_start - last_report > 1.0:
log.info("CONTROL steer=%.3f actual=%.3f pedal=%s duty=%.2f input_pedals=%.2f/%.2f speed=%.1f lane_prob=%.2f/%.2f width=%.2f inference=%.0fms head_deg=%.1f/%.1f/%.1f",
steer, data["steering"], action, intensity, data["user_throttle"], data["user_brake"], data["speed_mph"],
perception.lanes.left_prob, perception.lanes.right_prob,
float(np.median(perception.lanes.right_y[:10] - perception.lanes.left_y[:10])), last_inference_ms,
*[(((v + 0.5) % 1.0) - 0.5) * 360 for v in data['head_rotation']])
last_report = loop_start
elif pending_until is None and not status.startswith(("Disengaged", "Engagement blocked", "Manual")):
status = reason or "Ready: F8 engages"
if args.navigation_preview:
status = ('GPS preview: you control the truck; F8 does not enable driving'
if foreground and data.get('valid') else
data.get('reason') or 'Bring ATS to the foreground for the road model preview')
if obstruction_report.get('blocked'):
status = obstruction_report['reason'] + '; inference skipped'
if motion_clock:
previous_start = motion_clock.started_at
motion_clock.update(loop_start, data, fresh_camera=inferred_this_loop and foreground)
data['preview_recording'] = motion_clock.snapshot(loop_start)
if previous_start is None and motion_clock.started_at is not None:
log.info('DRIVE RECORDING started at %.1f MPH; duration %.0fs; controls OFF',
data['speed_mph'], motion_clock.duration)
recorder.next_image = 0.
recorder.image_interval = 1 / args.record_image_hz
if (motion_clock.started_at is None and foreground and data.get('valid')
and not obstruction_report.get('blocked')):
status = 'Pop preview ready: recording starts when you drive; controls OFF'
data.update(cruise_speed_mph=controller.cruise_set_speed, status=status,
provider=brain.active_provider, dry_run=args.dry_run, camera_mode=args.camera,
model_label=selected_model["label"], driving_mode=controller.driving_mode)
data['fsd_engaged'] = engaged
save_idle = (not motion_clock or motion_clock.started_at is not None
or loop_start >= next_idle_record_at)
if recorder and captured_this_loop and save_idle:
if motion_clock and motion_clock.started_at is None:
# Waiting is indefinite; save only sparse parked evidence.
recorder.image_interval = 1.
next_idle_record_at = loop_start + 1.
paired_data = dict(inference_telemetry, fsd_engaged=engaged,
control_command=last_control_command, status=status,
driving_mode=controller.driving_mode,
control_telemetry={key:data.get(key) for key in (
'timestamp', 'valid', 'speed_mph', 'engine_rpm', 'gear', 'park_brake',
'steering', 'throttle', 'brake', 'user_steering', 'user_throttle', 'user_brake')})
if motion_clock:
paired_data['preview_recording'] = data['preview_recording']
if pop_controller:
paired_data['evidence_writer'] = recorder.get_status()
recorder.record(camera, perception, paired_data,
last_inference_ms if inferred_this_loop else None, vision_reason,
wide_image=getattr(capture, 'wide_camera', None))
if pop_controller:
data['evidence_writer'] = recorder.get_status()
if args.path_preview:
data["driving_mode"] = "path-preview"
if status != last_status:
log.info("STATUS: %s", status)
last_status = status
if not args.no_hud:
# Passive Pop rendering is budgeted at 5 Hz. Input events
# still run each loop; model capture keeps its 20 Hz target.
hud_now = time.monotonic()
if not pop_controller or hud_now >= next_hud_render_at:
frame = hud.render(display_perception, data, engaged, camera,
fps=loop_fps,
inference_ms=last_inference_ms)
cv2.imshow(TITLE, frame)
next_hud_render_at = hud_now + .2
# pollKey handles panel events without adding the Windows
# waitKey timer delay to every passive model frame.
key = (cv2.pollKey() if pop_controller else cv2.waitKey(1)) & 0xFF
if key in (ord("m"), ord("M")):
hud.toggle_mode()
if key in (ord("c"), ord("C")):
setting_reason = parked_setting_reason(data, engaged, pending_until is not None)
if setting_reason:
status = "Manual settings: " + setting_reason
elif navigation_driver:
status = 'GPS driving trial uses Chill mode; exit the trial to change modes'
elif args.camera == "auxiliary" and not (args.dry_run or args.inset_cruise_test):
status = "Inset supports manual pedals; cruise needs the bounded test launcher"
else:
modes = ("manual", "cruise", "chill")
controller.release_all_controls()
args.driving_mode = modes[(modes.index(controller.driving_mode)+1) % len(modes)]
controller.set_driving_mode(args.driving_mode)
args.lane_only = args.driving_mode == "manual"
monitor.set_ignore_pedals(args.lane_only or args.dry_run)
status = "Manual settings: driving mode " + args.driving_mode
log.info("Driving mode changed while parked: %s", args.driving_mode)
if key in (ord("n"), ord("N")):
setting_reason = parked_setting_reason(data, engaged, pending_until is not None)
compatible = [e for e in registry.inventory() if e["compatible"]]
if setting_reason:
status = "Manual settings: " + setting_reason
elif recorder:
status = "Manual settings: finish the calibration recording before changing model"
elif len(compatible) < 2:
status = "Manual settings: only one compatible model is installed"
else:
try:
ids = [e["id"] for e in compatible]
candidate = registry.select(ids[(ids.index(args.model)+1) % len(ids)])
digest = candidate["metadata"]["sha256"]
if not args.dry_run and digest != model_manifest["sha256"]:
raise ValueError("New model requires passive evaluation and camera recalibration")
controller.release_all_controls()
if candidate['metadata'].get('preview_only') and not args.dry_run:
raise ValueError('Selected model is currently preview only')
candidate_brain = create_brain(candidate,
use_gpu=args.inference_provider != "cpu")
if args.inference_provider == "directml" and candidate_brain.active_provider != "DmlExecutionProvider":
raise ValueError("DirectML is unavailable")
candidate_perception = candidate_brain.step(np.zeros((1,12,128,256), np.float32))
capture.reset_history()
brain, perception, selected_model = candidate_brain, candidate_perception, candidate
args.model, model_manifest = candidate["id"], candidate["metadata"]
last_inference_at, inference_telemetry = None, None
pop_controller = (PopTrajectoryController()
if args.path_preview and selected_model.get('id') == 'pop-v2' else None)
pop_actions = PopModelActions() if pop_controller else None
pop_decision = None
if signal_preview:
signal_preview.reset()
status = "Manual settings: model " + candidate["label"]
log.info("Parked model change: id=%s hash=%s", args.model, digest)
except Exception as exc:
log.exception("Model change failed; keeping the previous model")
status = "Manual settings: model change blocked: " + str(exc)
if key in (ord("q"), ord("Q")):
break
if cv2.getWindowProperty(TITLE, cv2.WND_PROP_VISIBLE) < 1:
break
time.sleep(max(0.0, 0.05 - (time.monotonic() - loop_start)))
except KeyboardInterrupt:
log.info("Stopped")
except Exception:
log.exception("Runtime stopped; releasing controls")
raise
finally:
traffic.close()
road_geometry.close()
if navigation:
navigation.close()
if recorder:
try:
recorder.close()
except Exception:
log.exception("Could not close calibration recorder")
for cleanup in (controller.close, monitor.close, telemetry.close,
capture.close, cv2.destroyAllWindows):
try:
cleanup()
except Exception:
log.exception("Cleanup failed: %s", cleanup)
if __name__ == "__main__":
main()
-190
View File
@@ -1,190 +0,0 @@
"""
OpenPilot Neural Perception Brain
Runs comma.ai's Supercombo ONNX driving model on AMD Radeon GPU using DirectML.
Parses full 3D trajectory plans, lane lines, road edges, lead cars, and meta predictions.
"""
import os
import hashlib
import json
import numpy as np
import onnxruntime as ort
# Re-export the old public imports for existing decoder clients.
from model.perception import (Perception, OpenPilotPerception, TrajectoryPlan,
LaneLines, LeadVehicle, X_IDXS)
class OpenPilotBrain:
def __init__(self, model_path="models/supercombo.onnx", use_gpu=True, manifest_path=None):
self.model_path = os.path.abspath(model_path)
if not os.path.exists(self.model_path):
raise FileNotFoundError(f"Model file not found at {self.model_path}")
manifest_path = manifest_path or os.path.join(os.path.dirname(self.model_path), "manifest.json")
with open(manifest_path, encoding="utf-8") as manifest_file:
manifest = json.load(manifest_file)
if manifest.get("output_layout") != "historical supercombo 6409":
raise ValueError("Unsupported model decoder layout")
with open(self.model_path, "rb") as model_file:
digest = hashlib.file_digest(model_file, "sha256").hexdigest()
if digest != manifest["sha256"]:
raise ValueError("Model hash differs from the pinned 6409-output model")
# Choose execution providers
providers = [p for p in ['DmlExecutionProvider', 'CPUExecutionProvider']
if p in ort.get_available_providers()] if use_gpu else ['CPUExecutionProvider']
# Session options for low latency
opts = ort.SessionOptions()
opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
opts.enable_mem_pattern = False
opts.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
self.session = ort.InferenceSession(self.model_path, sess_options=opts, providers=providers)
self.active_provider = self.session.get_providers()[0]
expected = {'input_imgs': [1, 12, 128, 256], 'desire': [1, 8],
'traffic_convention': [1, 2], 'initial_state': [1, 512]}
outputs = self.session.get_outputs()
if ({i.name: i.shape for i in self.session.get_inputs()} != expected
or len(outputs) != 1 or outputs[0].shape != [1, 6409]
or any(i.type != 'tensor(float)' for i in self.session.get_inputs()+outputs)):
raise ValueError("Unsupported model tensor contract")
# State tensors
self.recurrent_state = np.zeros((1, 512), dtype=np.float32)
self.desire = np.zeros((1, 8), dtype=np.float32)
# Historical model consumes rising-edge desire pulses; keep lane is zero.
self.traffic_convention = np.array([[1.0, 0.0]], dtype=np.float32) # Right-hand traffic (US / ATS)
def set_desire(self, desire_type="none"):
"""
Sets lane change intent: 'none', 'left', 'right'
"""
self.desire.fill(0.0)
if desire_type == "left":
self.desire[0, 3] = 1.0 # laneChangeLeft
elif desire_type == "right":
self.desire[0, 4] = 1.0 # laneChangeRight
def reset_state(self):
"""Resets recurrent hidden state (e.g. on new trip or disengagement)."""
self.recurrent_state.fill(0.0)
self.desire.fill(0.0)
def step(self, input_imgs):
"""
Runs one step of perception on (1, 12, 128, 256) image input.
Returns OpenPilotPerception dataclass.
"""
inputs = {
'input_imgs': input_imgs,
'desire': self.desire,
'traffic_convention': self.traffic_convention,
'initial_state': self.recurrent_state
}
res = self.session.run(None, inputs)[0][0]
self.desire.fill(0.0)
return self.parse_outputs(res)
def parse_outputs(self, res):
"""Decode the historical 6409 layout in reference/driving.cc."""
res = np.asarray(res, dtype=np.float32)
if res.shape != (6409,) or not np.all(np.isfinite(res)):
raise ValueError("Model returned invalid outputs")
# Update recurrent state for next frame (last 512 floats)
self.recurrent_state[0, :] = res[5897:6409]
# 1. Parse 5 Trajectory Plans (0 to 4955)
# Each plan has 991 floats: mean (33*15), std (33*15), prob (1)
plan_len = 991
best_hyp = 0
best_prob = -1e9
for i in range(5):
prob = res[i * plan_len + 990]
if prob > best_prob:
best_prob = prob
best_hyp = i
best_offset = best_hyp * plan_len
logits = np.array([res[i * plan_len + 990] for i in range(5)])
weights = np.exp(logits - np.max(logits))
best_weight = weights[best_hyp] / weights.sum()
# Mean trajectory: 33 points x 15 elements
# Columns: pos(x,y,z)=0..2, vel(x,y,z)=3..5, acc(x,y,z)=6..8
mean_data = res[best_offset : best_offset + 33 * 15].reshape((33, 15))
pos_x = mean_data[:, 0]
pos_y = mean_data[:, 1]
pos_z = mean_data[:, 2]
vel_x = mean_data[:, 3]
# Compute curvature at ~12m lookahead (waypoint idx 8)
lookahead_idx = 8
lx = max(3.0, pos_x[lookahead_idx])
ly = pos_y[lookahead_idx]
curv = 2.0 * ly / (lx * lx)
plan = TrajectoryPlan(
x=pos_x,
y=pos_y,
z=pos_z,
velocity=vel_x,
curvature=curv,
prob=float(best_weight)
)
# 2. Parse Lane Lines (4955 to 5483)
# 4 lines x 33 points x 2 (y, z) = 264 for mean
lanes_mean = res[4955 : 4955 + 264].reshape((4, 33, 2))
# Line 1: left near, Line 2: right near
left_y = lanes_mean[1, :, 0]
left_z = lanes_mean[1, :, 1]
right_y = lanes_mean[2, :, 0]
right_z = lanes_mean[2, :, 1]
# Lane probabilities (5483 to 5491)
lane_probs = res[5483 : 5491]
# Sigmoid on probabilities
lp_sig = 1.0 / (1.0 + np.exp(-np.clip(lane_probs, -80.0, 80.0)))
left_prob = float(lp_sig[3])
right_prob = float(lp_sig[5])
lanes = LaneLines(
left_y=left_y,
left_z=left_z,
right_y=right_y,
right_z=right_z,
left_prob=left_prob,
right_prob=right_prob,
x=X_IDXS.copy(),
all_y=lanes_mean[:, :, 0].copy(),
all_z=lanes_mean[:, :, 1].copy(),
probabilities=lp_sig[1::2].copy()
)
# 3. Parse Lead Vehicle (around 5755 to 5850)
# Five hypotheses describe alternatives for ONE lead; selection column
# 8 is t=0. Columns 9/10 predict that lead at t=2/4, not other cars.
leads = res[5755:5810].reshape((5, 11))
lead_slice = leads[int(np.argmax(leads[:, 8]))]
lead_dist = float(lead_slice[0])
lead_v = float(lead_slice[2])
# Lead probability in lead prediction
lead_prob = 1.0 / (1.0 + np.exp(-float(np.clip(res[5810], -80.0, 80.0))))
lead_detected = bool(lead_prob > 0.6 and 0.0 < lead_dist < 120.0 and abs(float(lead_slice[1])) < 2.5)
lead = LeadVehicle(
detected=lead_detected,
distance=max(0.0, lead_dist) if lead_detected else 999.0,
rel_speed=lead_v if lead_detected else 0.0,
prob=float(lead_prob),
lateral_offset=float(lead_slice[1])
)
return OpenPilotPerception(
plan=plan,
lanes=lanes,
lead=lead,
raw_outputs=res
)
-68
View File
@@ -1,68 +0,0 @@
"""Shared driving observations, independent of any model inference runtime.
The legacy sample grid remains the fallback for observations without their own
longitudinal coordinates. Adapters may attach additional evidence to Perception
as before; this module neither loads a model nor chooses a driving policy.
"""
from dataclasses import dataclass
import numpy as np
# Legacy 33-point longitudinal sampling, in metres. Keep the original dtype and
# values: existing lane and road-edge fallback geometry relies on this grid.
X_IDXS = np.array([
0.0, 0.1875, 0.75, 1.6875, 3.0, 4.6875,
6.75, 9.1875, 12.0, 15.1875, 18.75, 22.6875,
27.0, 31.6875, 36.75, 42.1875, 48.0, 54.1875,
60.75, 67.6875, 75.0, 82.6875, 90.75, 99.1875,
108.0, 117.1875, 126.75, 136.6875, 147.0, 157.6875,
168.75, 180.1875, 192.0
], dtype=np.float32)
@dataclass
class TrajectoryPlan:
x: np.ndarray # 33 waypoints longitudinal (m)
y: np.ndarray # 33 waypoints lateral (m)
z: np.ndarray # 33 waypoints vertical (m)
velocity: np.ndarray # 33 waypoints speed (m/s)
curvature: float # target steering curvature at lookahead
prob: float # confidence of chosen plan hypothesis
@dataclass
class LaneLines:
left_y: np.ndarray
left_z: np.ndarray
right_y: np.ndarray
right_z: np.ndarray
left_prob: float
right_prob: float
x: np.ndarray = None
# Official v0.8.5 order: outer left, ego left, ego right, outer right.
# These are observed lines, not proof of four drivable lanes.
all_y: np.ndarray = None
all_z: np.ndarray = None
probabilities: np.ndarray = None
@dataclass
class LeadVehicle:
detected: bool
distance: float # meters ahead
rel_speed: float # m/s relative speed
prob: float
lateral_offset: float = 0.0 # model coordinates: positive is right
@dataclass
class Perception:
plan: TrajectoryPlan
lanes: LaneLines
lead: LeadVehicle
raw_outputs: np.ndarray
# Existing callers and old serialized class references resolve to the same type.
OpenPilotPerception = Perception
-301
View File
@@ -1,301 +0,0 @@
"""Pinned Pop v2 split ONNX runner; experimental simulator preview only.
The default MED inset is duplicated for comparison. Callers may provide a
separate SBIG frame, explicitly not proof of camera calibration.
Temporal sampling uses timestamps rather than assuming the ATS loop is 20 Hz.
"""
from collections import deque
import hashlib
import json
import math
from pathlib import Path
import time
import numpy as np
import onnxruntime as ort
from model.perception import (Perception, OpenPilotPerception, TrajectoryPlan, LaneLines,
LeadVehicle, X_IDXS)
CONTRACT = "pop-v2-split-1576-1000"
class PopV2Brain:
def __init__(self, model_path, use_gpu=True, manifest_path=None):
self.model_path = str(Path(model_path).resolve())
parent = Path(self.model_path).parent
manifest = json.loads(Path(manifest_path or parent / 'manifest.json').read_text())
if manifest.get('output_layout') != CONTRACT:
raise ValueError('Unsupported Pop v2 model layout')
policy = (parent / manifest['policy_file']).resolve()
if not policy.is_relative_to(parent):
raise ValueError('Pop v2 policy must be inside its model directory')
for path, key in ((Path(self.model_path), 'sha256'), (policy, 'policy_sha256')):
with path.open('rb') as stream:
digest = hashlib.file_digest(stream, 'sha256').hexdigest()
if digest != manifest[key]:
raise ValueError('Pop v2 model hash differs from its manifest')
providers = ([p for p in ('DmlExecutionProvider', 'CPUExecutionProvider')
if p in ort.get_available_providers()] if use_gpu
else ['CPUExecutionProvider'])
options = ort.SessionOptions()
options.enable_mem_pattern = False
options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
# Avoid competing with ATS across every CPU core.
options.intra_op_num_threads = 2
self.vision = ort.InferenceSession(self.model_path, options, providers=providers)
self.policy = ort.InferenceSession(str(policy), options, providers=providers)
self.active_provider = self.vision.get_providers()[0]
if self.active_provider != self.policy.get_providers()[0]:
raise ValueError('Pop v2 sessions use different providers')
expected_vision = {'img': ([1, 12, 128, 256], 'tensor(uint8)'),
'big_img': ([1, 12, 128, 256], 'tensor(uint8)')}
expected_policy = {'desire_pulse': ([1, 25, 8], 'tensor(float16)'),
'traffic_convention': ([1, 2], 'tensor(float16)'),
'features_buffer': ([1, 25, 512], 'tensor(float16)')}
for session, expected, output_size in ((self.vision, expected_vision, 1576),
(self.policy, expected_policy, 1000)):
outputs = session.get_outputs()
if ({i.name: (i.shape, i.type) for i in session.get_inputs()} != expected
or len(outputs) != 1 or outputs[0].shape != [1, output_size]
or outputs[0].type != 'tensor(float16)'):
raise ValueError('Unsupported Pop v2 tensor contract')
self.desire = np.zeros(8, np.float16)
self.traffic_convention = np.array([[1, 0]], np.float16)
self.reset_state()
def reset_state(self):
self.images = deque()
self.wide_images = deque()
self.pending_wide_input = None
self.camera_input_mode = 'narrow-duplicated'
self.features = deque()
self.pulses = deque()
self.desire.fill(0)
self.last_timestamp = None
self.temporal_ready = False
self.temporal_coverage = {}
def set_wide_input(self, parsed):
"""Supply one current SBIG frame; consumed by the next step only.
The caller derives MED separately from the same source exposure. The
supplied projection is not independently validated by this adapter.
"""
self.pending_wide_input = None
if parsed is None:
return
frame = np.asarray(parsed)
if (frame.shape != (6, 128, 256)
or frame.dtype not in (np.dtype(np.uint8), np.dtype(np.float32))
or not np.all(np.isfinite(frame))
or frame.min() < 0 or frame.max() > 255):
raise ValueError('Invalid Pop v2 wide image input')
self.pending_wide_input = frame.astype(np.uint8, copy=True)
def set_desire(self, desire_type='none'):
self.desire.fill(0)
if desire_type in ('left', 'right'):
self.desire[3 if desire_type == 'left' else 4] = 1
@staticmethod
def _sample_entry(history, timestamp):
for t, value in reversed(history):
if t <= timestamp + 1e-6:
# Never fill a missing temporal interval with a stale image.
if timestamp - t <= 0.10:
return t, value
break
return None
@staticmethod
def _sample(history, timestamp, width):
entry = PopV2Brain._sample_entry(history, timestamp)
if entry is not None:
return entry[1]
return np.zeros(width, np.float16)
def _feature_gap_limit(self):
"""Permit continuous CPU cadence without bridging a dropped interval.
The policy grid is 5 Hz even when inference runs slightly below 5 Hz.
A past-only 100 ms lookup leaves roughly half of that real history zero.
Resampling must still reject a gap that is abnormal for this run, and
never bridge more than 250 ms regardless of the observed cadence.
"""
gaps = np.diff([entry[0] for entry in self.features])
if not gaps.size:
return .10
return min(.25, max(.10, 1.75 * float(np.median(gaps))))
def _feature_sample(self, timestamp, gap_limit):
"""Return a real sample or bounded interpolation of two real features.
Historical targets may use a later recorded feature, already available
at the current inference. No extrapolation, stale repetition, pixel
interpolation, or fabricated inference is allowed. The explicit sample
kind and bracket width are included in coverage evidence below.
"""
earlier = None
for t, value in self.features:
if abs(t - timestamp) <= 1e-6:
return value, 'observed', 0., 0.
if t < timestamp:
earlier = (t, value)
continue
if earlier is None:
return None
before, left = earlier
gap = t - before
if gap > gap_limit + 1e-6:
return None
alpha = (timestamp - before) / gap
# Float32 avoids cancellation/overflow during half-precision math.
sampled = (left.astype(np.float32) * (1. - alpha)
+ value.astype(np.float32) * alpha).astype(np.float16)
return sampled, 'interpolated', max(timestamp - before, t - timestamp), gap
return None
def _feature_context(self, timestamp):
limit = self._feature_gap_limit()
return ([self._feature_sample(timestamp - .2*i, limit)
for i in range(24, -1, -1)], limit)
def _context_coverage(self, timestamp):
"""Measure availability independently of tensor values or elapsed time.
Complete bounded context does not validate the upstream 20 Hz cadence
or rendered camera calibration. Interpolated slots are reported apart
from observed slots. Zero-valued real features remain valid.
"""
entries, gap_limit = self._feature_context(timestamp)
present = sum(entry is not None for entry in entries)
narrow_present = self._sample_entry(self.images, timestamp - .2) is not None
wide_required = self.camera_input_mode == 'sbig-with-derived-med'
wide_present = (self._sample_entry(self.wide_images, timestamp - .2) is not None
if wide_required else narrow_present)
ages = [entry[2] for entry in entries if entry is not None]
brackets = [entry[3] for entry in entries if entry is not None]
gaps = [right[0] - left[0] for left, right in zip(self.features,
list(self.features)[1:])]
span = (timestamp - self.features[0][0]) if self.features else 0.
return dict(feature_slots_present=present, feature_slots_required=25,
feature_slots_observed=sum(e is not None and e[1] == 'observed'
for e in entries),
feature_slots_interpolated=sum(e is not None and e[1] == 'interpolated'
for e in entries),
feature_sampling='bounded-linear-between-real-features',
feature_bracket_limit_s=gap_limit,
max_feature_bracket_s=max(brackets) if brackets else None,
real_feature_samples=len(self.features),
narrow_pair_present=narrow_present, wide_pair_present=wide_present,
wide_pair_required=wide_required,
complete=present == 25 and narrow_present and wide_present,
max_sample_age_s=max(ages) if ages else None,
sample_age_limit_s=gap_limit, camera_sample_age_limit_s=.10,
expected_run_hz=20,
observed_run_hz=(len(self.features)-1)/span if span > 0 else None,
max_inference_gap_s=max(gaps) if gaps else None,
upstream_cadence_validated=False)
def step(self, input_imgs, timestamp=None):
wide_current = self.pending_wide_input
self.pending_wide_input = None
timestamp = time.monotonic() if timestamp is None else float(timestamp)
imgs = np.asarray(input_imgs)
if (imgs.shape != (1, 12, 128, 256) or not np.isfinite(timestamp)
or not np.all(np.isfinite(imgs)) or imgs.min() < 0 or imgs.max() > 255):
raise ValueError('Invalid Pop v2 image input')
if self.last_timestamp is not None:
delta = timestamp - self.last_timestamp
if delta <= 0:
raise ValueError('Pop v2 timestamps must increase')
# A brief missing camera frame leaves an unsupported interval in
# the bounded sampler; it need not discard all earlier evidence.
# Long pauses still start a completely new temporal context.
if delta >= .5:
self.reset_state()
mode = ('sbig-with-derived-med' if wide_current is not None
else 'narrow-duplicated')
if self.last_timestamp is not None and mode != self.camera_input_mode:
# A change of projection must not share a policy feature history.
self.reset_state()
self.camera_input_mode = mode
current = imgs[0, 6:].astype(np.uint8)
self.images.append((timestamp, current))
if wide_current is not None:
self.wide_images.append((timestamp, wide_current))
else:
self.wide_images.clear()
for history in (self.images, self.wide_images, self.features, self.pulses):
while history and history[0][0] < timestamp - 5.1:
history.popleft()
old = self._sample(self.images, timestamp - .2, current.shape).astype(np.uint8)
image_pair = np.concatenate((old, current), axis=0)[None]
wide_pair = image_pair
if wide_current is not None:
wide_old = self._sample(self.wide_images, timestamp - .2,
wide_current.shape).astype(np.uint8)
wide_pair = np.concatenate((wide_old, wide_current), axis=0)[None]
v = self.vision.run(None, {'img': image_pair, 'big_img': wide_pair})[0][0]
if v.shape != (1576,) or not np.all(np.isfinite(v)):
raise ValueError('Pop v2 returned invalid vision outputs')
self.features.append((timestamp, v[1064:1576].copy()))
self.pulses.append((timestamp, self.desire.copy()))
feature_context, _ = self._feature_context(timestamp)
feature_input = np.stack([entry[0] if entry is not None else np.zeros(512, np.float16)
for entry in feature_context])[None].astype(np.float16)
pulse_input = np.zeros((1, 25, 8), np.float16)
for i in range(25):
end = timestamp - .2*(24-i)
for t, pulse in self.pulses:
if end - .2 < t <= end + 1e-6:
pulse_input[0, i] = np.maximum(pulse_input[0, i], pulse)
p = self.policy.run(None, {'features_buffer': feature_input,
'desire_pulse': pulse_input,
'traffic_convention': self.traffic_convention})[0][0]
self.desire.fill(0)
self.temporal_coverage = self._context_coverage(timestamp)
self.temporal_ready = self.temporal_coverage['complete']
self.last_timestamp = timestamp
return self.parse_outputs(v, p)
def parse_outputs(self, vision, policy):
v, p = np.asarray(vision, np.float32), np.asarray(policy, np.float32)
if (v.shape != (1576,) or p.shape != (1000,)
or not np.all(np.isfinite(v)) or not np.all(np.isfinite(p))):
raise ValueError('Pop v2 returned invalid outputs')
mean = p[:495].reshape(33, 15)
lx, ly = max(3., float(mean[8, 0])), float(mean[8, 1])
plan = TrajectoryPlan(mean[:, 0].copy(), mean[:, 1].copy(), mean[:, 2].copy(),
mean[:, 3].copy(), 2*ly/(lx*lx), None)
lane_mean = v[117:381].reshape(4, 33, 2)
probabilities = (1/(1+np.exp(np.clip(-v[645:653], -np.inf, 11))))[1::2]
lanes = LaneLines(lane_mean[1, :, 0].copy(), lane_mean[1, :, 1].copy(),
lane_mean[2, :, 0].copy(), lane_mean[2, :, 1].copy(),
float(probabilities[1]), float(probabilities[2]),
X_IDXS.copy(), lane_mean[:, :, 0].copy(),
lane_mean[:, :, 1].copy(), probabilities.copy())
# Three temporal predictions of one lead, not three nearby vehicles.
first_lead = v[917:989].reshape(3, 6, 4)[0, 0]
prob = float(1/(1+math.exp(min(-float(v[1061]), 11))))
dist, lateral, velocity = map(float, first_lead[:3])
detected = prob > .6 and 0 < dist < 120 and abs(lateral) < 2.5
lead = LeadVehicle(detected, dist if detected else 999., 0., prob, lateral)
perception = Perception(plan, lanes, lead, np.concatenate((v, p)))
# Keep uncertainty and road edges available for future trajectory gates.
perception.road_edges = v[653:785].reshape(2, 33, 2).copy()
perception.road_edge_std = np.exp(np.clip(v[785:917].reshape(2, 33, 2), -np.inf, 11))
perception.plan_std = np.exp(np.clip(p[495:990].reshape(33, 15), -np.inf, 11))
# Modern unary plan columns from the pinned ModelConstants/Plan layout.
# Additive evidence only: preserve the legacy TrajectoryPlan interface.
perception.velocity_xyz = mean[:, 3:6].copy()
perception.acceleration_xyz = mean[:, 6:9].copy()
perception.orientation_xyz = mean[:, 9:12].copy()
perception.orientation_rate_xyz = mean[:, 12:15].copy()
perception.plan_times = 10. * (np.arange(33, dtype=np.float64) / 32.) ** 2
perception.pop_plan_contract = CONTRACT
perception.lead_speed_mps = velocity
perception.lead_velocity_semantics = 'upstream lead.v; relativity not validated'
perception.camera_input_mode = self.camera_input_mode
return perception
-64
View File
@@ -1,64 +0,0 @@
"""Explicit local model selection; each entry keeps its own pinned manifest."""
import hashlib
import json
from pathlib import Path
import re
CONTRACT = "historical supercombo 6409"
POP_CONTRACT = "pop-v2-split-1576-1000"
class ModelRegistry:
def __init__(self, directory):
self.directory = Path(directory).resolve()
self.entries = json.loads((self.directory / "registry.json").read_text(encoding="utf-8"))
ids = [entry["id"] for entry in self.entries]
if len(ids) != len(set(ids)) or not ids:
raise ValueError("Model registry needs unique model IDs")
def select(self, model_id):
entry = next((e for e in self.entries if e["id"] == model_id), None)
if entry is None:
raise ValueError("Unknown model ID: " + model_id)
paths = []
for field in ("file", "manifest"):
path = (self.directory / entry[field]).resolve()
if not path.is_relative_to(self.directory):
raise ValueError("Registered model files must be inside models/")
paths.append(path)
model_path, manifest_path = paths
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
if manifest.get("output_layout") not in (CONTRACT, POP_CONTRACT):
raise ValueError("Model needs a different decoder/runner adapter")
digest = manifest.get("sha256", "")
if not re.fullmatch("[0-9a-f]{64}", digest):
raise ValueError("Model manifest needs a SHA-256 pin")
with model_path.open("rb") as stream:
actual = hashlib.file_digest(stream, "sha256").hexdigest()
if actual != digest:
raise ValueError("Registered model hash differs from its manifest")
if manifest['output_layout'] == POP_CONTRACT:
policy = (model_path.parent / manifest['policy_file']).resolve()
if not policy.is_relative_to(model_path.parent):
raise ValueError('Registered policy must be inside its model directory')
pin = manifest.get('policy_sha256', '')
if not re.fullmatch('[0-9a-f]{64}', pin):
raise ValueError('Policy manifest needs a SHA-256 pin')
with policy.open('rb') as stream:
actual = hashlib.file_digest(stream, 'sha256').hexdigest()
if actual != pin:
raise ValueError('Registered policy hash differs from its manifest')
return dict(entry, path=model_path, manifest_path=manifest_path, metadata=manifest)
def inventory(self):
result = []
for entry in self.entries:
try:
selected = self.select(entry["id"])
result.append(dict(id=entry["id"], label=entry["label"],
compatible=True, sha256=selected["metadata"]["sha256"],
preview_only=bool(selected['metadata'].get('preview_only'))))
except (OSError, ValueError, KeyError) as exc:
result.append(dict(id=entry.get("id"), label=entry.get("label"),
compatible=False, reason=str(exc)))
return result
-13
View File
@@ -1,13 +0,0 @@
"""Select a decoder only after the registry has verified its pinned contract."""
from model.registry import POP_CONTRACT as CONTRACT
def create_brain(selected, use_gpu=True):
if selected['metadata']['output_layout'] == CONTRACT:
from model.pop_v2 import PopV2Brain
runner = PopV2Brain
else:
from model.openpilot_brain import OpenPilotBrain
runner = OpenPilotBrain
return runner(str(selected['path']), use_gpu=use_gpu,
manifest_path=selected['manifest_path'])
-7
View File
@@ -1,7 +0,0 @@
{
"sha256": "77a31e5a3a70c39a3fcb07e939a668baf80b1eb778fe792fbe256de983fab5cd",
"output_layout": "historical supercombo 6409",
"parser_reference": "https://github.com/commaai/openpilot/blob/v0.8.5/selfdrive/modeld/models/driving.cc",
"provenance": "Existing local PyTorch-exported model; original training/export version unrecorded",
"validated": "Tensor contract, finite inference, historical decoder layout; road performance requires replay and driving validation"
}
-146
View File
@@ -1,146 +0,0 @@
{
"repository": "commaai/openpilot",
"revision": "62bf6fb072880905a4c490f0f4f4a6b3c23346ec",
"catalog_commit": "9850fb07544b3c1f8c21b793c454e606dbb7fdca",
"catalog_ref": "PMV2",
"artifacts": [
{
"name": "driving_vision.onnx",
"url": "https://media.githubusercontent.com/media/commaai/openpilot/62bf6fb072880905a4c490f0f4f4a6b3c23346ec/selfdrive/modeld/models/driving_vision.onnx",
"sha256": "940e9006a25f27f0b6e85da798e6a8fd1f6dd492dd7d0b9ff1a9436460f46129",
"bytes": 46887794,
"seconds": 1.35
},
{
"name": "driving_policy.onnx",
"url": "https://media.githubusercontent.com/media/commaai/openpilot/62bf6fb072880905a4c490f0f4f4a6b3c23346ec/selfdrive/modeld/models/driving_policy.onnx",
"sha256": "853c6634746ff439a848349d00e4d5581cd941f13f7c1862c31b72a31cc24858",
"bytes": 14061595,
"seconds": 0.86
}
],
"pickle_executed": false,
"runtime_changed": false,
"source_files": [
{
"file": "source/catalog-identity.json",
"sha256": "1d5f0ab6ef037096f8ddcb976cfed0b81c122415e3b6e095797631beefa15cef",
"bytes": 173
},
{
"file": "source/comma-common_transformations_camera.py",
"sha256": "3ac87fd236aa9c9e284059c47c9eb96a7c6e0be5106f514a95e6ec06e1060fb5",
"bytes": 6141
},
{
"file": "source/comma-common_transformations_model.py",
"sha256": "c87aad27074362fe9fe361a71da92c1fc90daf63bcfd4d8c47d65d3a936ec15e",
"bytes": 2766
},
{
"file": "source/comma-selfdrive_modeld_compile_warp.py",
"sha256": "574aa090de6fa272f95b00e039b1467d60c6d9445ee8d774e8529369648fcf0f",
"bytes": 8372
},
{
"file": "source/comma-selfdrive_modeld_constants.py",
"sha256": "e1e3a01ea31dd57dbd9ffd588ff1f2ab22e6088a558c65ad68bf20678552c00c",
"bytes": 2145
},
{
"file": "source/comma-selfdrive_modeld_fill_model_msg.py",
"sha256": "d99289ee16ddbcc286abc7184f1de55ad4378d860092ec896d1cdc4cf4f12799",
"bytes": 9415
},
{
"file": "source/comma-selfdrive_modeld_get_model_metadata.py",
"sha256": "045d9fd4b10ff989adc5837b9a5dfad2b961b890f46f0bbe995335dae5e68789",
"bytes": 1855
},
{
"file": "source/comma-selfdrive_modeld_modeld.py",
"sha256": "571496f6e8b8364d90d0e2dddcb2a6f375ecbb434927e11078f40084e56f3b66",
"bytes": 19621
},
{
"file": "source/comma-selfdrive_modeld_models_driving_policy.onnx",
"sha256": "37629fbdf9fd80ad6d00bc02d6f85024820cb941727d9810cca3c75cf47e3fb3",
"bytes": 133
},
{
"file": "source/comma-selfdrive_modeld_models_driving_vision.onnx",
"sha256": "806ec3815cbc3c58fc93c0c5c8d09f0a093a6d8a61d6e34a461fb6759040f796",
"bytes": 133
},
{
"file": "source/comma-selfdrive_modeld_models_README.md",
"sha256": "f2613800954f09805728228efd51cd16025c8bd18e569cd1fba42b7b75691a8b",
"bytes": 3417
},
{
"file": "source/comma-selfdrive_modeld_parse_model_outputs.py",
"sha256": "82d5eb5391f2c02c187adb3ad9ae6ad9d97fd0ae681d54e808a438f415802ed4",
"bytes": 5592
},
{
"file": "source/comma-selfdrive_modeld_SConscript",
"sha256": "a24250835b2d34bfcdad95fffe0dc96809c95850178c461e9b1943826d683e1b",
"bytes": 3429
},
{
"file": "source/driving_models_chestnut_v25.json",
"sha256": "152db3f375fa02cef5211a06e14a83c52461b0fe32a3f04a8570d52829c69b8c",
"bytes": 100628
},
{
"file": "source/driving_models_v22.json",
"sha256": "a4b5bd581bd252218d7dc6c9c146d2b13bfecc677a10a153ef55060d96a74e1b",
"bytes": 119213
},
{
"file": "source/driving_policy.onnx.output_slices.pickle-dis.txt",
"sha256": "36b7df7c5062ba16e0daf1a75fa06dc27b1ce3fa06d348063db336b12c0543f1",
"bytes": 1340
},
{
"file": "source/driving_vision.onnx.output_slices.pickle-dis.txt",
"sha256": "0f24e89ab286c42d6c7ae1ebc64dab0ec52013e2a6dc27d5d75ae8dc0502ff11",
"bytes": 4219
},
{
"file": "source/sunnypilot-models-fetcher.py",
"sha256": "8f600cc803250ca34d8a86904af5812e0d17a6e600c72d96a14c69fd2f2fce29",
"bytes": 11102
},
{
"file": "source/sunnypilot-models-helpers.py",
"sha256": "369e1e0e81d617c57e61116041728f50ce4fe66458c725558fa0093cfb34c3bd",
"bytes": 8531
},
{
"file": "source/sunnypilot-models-manager.py",
"sha256": "39cbfbeefe0f0b7b42bc8ca0ea3238e52028f7503ec416653f312c99e74eb1cc",
"bytes": 16737
},
{
"file": "source/sunnypilot-models-model_name.py",
"sha256": "89059f73cc2272141fcf0b5ac0d3b7c9d87565760c4d52db6af779e0ae86d442",
"bytes": 193
},
{
"file": "source/sunnypilot-models-README.md",
"sha256": "5b0cf47f9893488977c2169878117b9bfc9ecd096d31a7f2f262ec3b45ab626b",
"bytes": 3409
},
{
"file": "source/sunnypilot-models-runners_constants.py",
"sha256": "e737aeb63a3b125ac5b62d5e21fe1cf3e635553802caf1d8bec6add9710b6942",
"bytes": 411
},
{
"file": "source/sunnypilot-models-split_model_constants.py",
"sha256": "3d374354b182d388e413556f3f06b58aabf32700e14bc6e5744980fa48d7cb07",
"bytes": 2320
}
]
}
-30
View File
@@ -1,30 +0,0 @@
{
"name": "Pop Model v2 (March 24, 2026)",
"model_id": "pop-v2",
"output_layout": "pop-v2-split-1576-1000",
"model_file": "driving_vision.onnx",
"sha256": "940e9006a25f27f0b6e85da798e6a8fd1f6dd492dd7d0b9ff1a9436460f46129",
"policy_file": "driving_policy.onnx",
"policy_sha256": "853c6634746ff439a848349d00e4d5581cd941f13f7c1862c31b72a31cc24858",
"source_repository": "commaai/openpilot",
"source_revision": "62bf6fb072880905a4c490f0f4f4a6b3c23346ec",
"catalog_repository": "sunnypilot/sunnypilot-models",
"catalog_commit": "9850fb07544b3c1f8c21b793c454e606dbb7fdca",
"catalog_short_name": "PMV2",
"experimental": true,
"preview_only": true,
"camera_validated": false,
"usable_for_control": false,
"expected_run_hz": 20,
"context_hz": 5,
"image_pair_separation_s": 0.2,
"feature_context_samples": 25,
"feature_context_span_s": 4.8,
"plan_confidence": "unassessed: unary mean/logstd plan has no selection probability",
"camera_approximation": "pop-wide-sbig supplies an ATS wide SBIG render and derived narrow MED crop; other captures duplicate narrow input. Physical camera calibration remains unvalidated; recording rows identify the actual mode.",
"source_urls": {
"catalog": "https://raw.githubusercontent.com/sunnypilot/sunnypilot-models/9850fb07544b3c1f8c21b793c454e606dbb7fdca/docs/driving_models_v22.json",
"vision": "https://media.githubusercontent.com/media/commaai/openpilot/62bf6fb072880905a4c490f0f4f4a6b3c23346ec/selfdrive/modeld/models/driving_vision.onnx",
"policy": "https://media.githubusercontent.com/media/commaai/openpilot/62bf6fb072880905a4c490f0f4f4a6b3c23346ec/selfdrive/modeld/models/driving_policy.onnx"
}
}
-70
View File
@@ -1,70 +0,0 @@
{
"vision": {
"meta": [
0,
55
],
"desire_pred": [
55,
87
],
"pose": [
87,
99
],
"wide_from_device_euler": [
99,
105
],
"road_transform": [
105,
117
],
"lane_lines": [
117,
645
],
"lane_lines_prob": [
645,
653
],
"road_edges": [
653,
917
],
"lead": [
917,
1061
],
"lead_prob": [
1061,
1064
],
"hidden_state": [
1064,
1576
]
},
"policy": {
"plan": [
0,
990
],
"desire_state": [
990,
998
]
},
"lane_probability_logit_indices": [
1,
3,
5,
7
],
"plan_mean_shape": [
33,
15
],
"plan_std_encoding": "second495 values exp(logstd), exponent clipped11 upstream",
"extraction": "manually transcribed from pickletools opcode disassembly; no pickle execution"
}
@@ -1,5 +0,0 @@
{
"repository": "sunnypilot/sunnypilot-models",
"commit": "9850fb07544b3c1f8c21b793c454e606dbb7fdca",
"source_commit": "a5f44653d7f43ad57fef2f546f3916ec4cbf3c56"
}
@@ -1,179 +0,0 @@
import itertools
import numpy as np
from dataclasses import dataclass
import openpilot.common.transformations.orientation as orient
## -- hardcoded hardware params --
@dataclass(frozen=True)
class CameraConfig:
width: int
height: int
focal_length: float
@property
def size(self):
return (self.width, self.height)
@property
def intrinsics(self):
# aka 'K' aka camera_frame_from_view_frame
return np.array([
[self.focal_length, 0.0, float(self.width)/2],
[0.0, self.focal_length, float(self.height)/2],
[0.0, 0.0, 1.0]
])
@property
def intrinsics_inv(self):
# aka 'K_inv' aka view_frame_from_camera_frame
return np.linalg.inv(self.intrinsics)
@dataclass(frozen=True)
class _NoneCameraConfig(CameraConfig):
width: int = 0
height: int = 0
focal_length: float = 0
@dataclass(frozen=True)
class DeviceCameraConfig:
fcam: CameraConfig
dcam: CameraConfig
ecam: CameraConfig
def all_cams(self):
for cam in ['fcam', 'dcam', 'ecam']:
if not isinstance(getattr(self, cam), _NoneCameraConfig):
yield cam, getattr(self, cam)
_ar_ox_fisheye = CameraConfig(1928, 1208, 567.0) # focal length probably wrong? magnification is not consistent across frame
_os_fisheye = CameraConfig(2688 // 2, 1520 // 2, 567.0 / 4 * 3)
_ar_ox_config = DeviceCameraConfig(CameraConfig(1928, 1208, 2648.0), _ar_ox_fisheye, _ar_ox_fisheye)
_os_config = DeviceCameraConfig(CameraConfig(2688 // 2, 1520 // 2, 1522.0 * 3 / 4), _os_fisheye, _os_fisheye)
_neo_config = DeviceCameraConfig(CameraConfig(1164, 874, 910.0), CameraConfig(816, 612, 650.0), _NoneCameraConfig())
DEVICE_CAMERAS = {
# A "device camera" is defined by a device type and sensor
# sensor type was never set on eon/neo/two
("neo", "unknown"): _neo_config,
# unknown here is AR0231, field was added with OX03C10 support
("tici", "unknown"): _ar_ox_config,
# before deviceState.deviceType was set, assume tici AR config
("unknown", "ar0231"): _ar_ox_config,
("unknown", "ox03c10"): _ar_ox_config,
# simulator (emulates a tici)
("pc", "unknown"): _ar_ox_config,
}
prods = itertools.product(('tici', 'tizi', 'mici'), (('ar0231', _ar_ox_config), ('ox03c10', _ar_ox_config), ('os04c10', _os_config)))
DEVICE_CAMERAS.update({(d, c[0]): c[1] for d, c in prods})
# device/mesh : x->forward, y-> right, z->down
# view : x->right, y->down, z->forward
device_frame_from_view_frame = np.array([
[ 0., 0., 1.],
[ 1., 0., 0.],
[ 0., 1., 0.]
])
view_frame_from_device_frame = device_frame_from_view_frame.T
# aka 'extrinsic_matrix'
# road : x->forward, y -> left, z->up
def get_view_frame_from_road_frame(roll, pitch, yaw, height):
device_from_road = orient.rot_from_euler([roll, pitch, yaw]).dot(np.diag([1, -1, -1]))
view_from_road = view_frame_from_device_frame.dot(device_from_road)
return np.hstack((view_from_road, [[0], [height], [0]]))
# aka 'extrinsic_matrix'
def get_view_frame_from_calib_frame(roll, pitch, yaw, height):
device_from_calib= orient.rot_from_euler([roll, pitch, yaw])
view_from_calib = view_frame_from_device_frame.dot(device_from_calib)
return np.hstack((view_from_calib, [[0], [height], [0]]))
def vp_from_ke(m):
"""
Computes the vanishing point from the product of the intrinsic and extrinsic
matrices C = KE.
The vanishing point is defined as lim x->infinity C (x, 0, 0, 1).T
"""
return (m[0, 0]/m[2, 0], m[1, 0]/m[2, 0])
def roll_from_ke(m):
# note: different from calibration.h/RollAnglefromKE: i think that one's just wrong
return np.arctan2(-(m[1, 0] - m[1, 1] * m[2, 0] / m[2, 1]),
-(m[0, 0] - m[0, 1] * m[2, 0] / m[2, 1]))
def normalize(img_pts, intrinsics):
# normalizes image coordinates
# accepts single pt or array of pts
intrinsics_inv = np.linalg.inv(intrinsics)
img_pts = np.array(img_pts)
input_shape = img_pts.shape
img_pts = np.atleast_2d(img_pts)
img_pts = np.hstack((img_pts, np.ones((img_pts.shape[0], 1))))
img_pts_normalized = img_pts.dot(intrinsics_inv.T)
img_pts_normalized[(img_pts < 0).any(axis=1)] = np.nan
return img_pts_normalized[:, :2].reshape(input_shape)
def denormalize(img_pts, intrinsics, width=np.inf, height=np.inf):
# denormalizes image coordinates
# accepts single pt or array of pts
img_pts = np.array(img_pts)
input_shape = img_pts.shape
img_pts = np.atleast_2d(img_pts)
img_pts = np.hstack((img_pts, np.ones((img_pts.shape[0], 1), dtype=img_pts.dtype)))
img_pts_denormalized = img_pts.dot(intrinsics.T)
if np.isfinite(width):
img_pts_denormalized[img_pts_denormalized[:, 0] > width] = np.nan
img_pts_denormalized[img_pts_denormalized[:, 0] < 0] = np.nan
if np.isfinite(height):
img_pts_denormalized[img_pts_denormalized[:, 1] > height] = np.nan
img_pts_denormalized[img_pts_denormalized[:, 1] < 0] = np.nan
return img_pts_denormalized[:, :2].reshape(input_shape)
def get_calib_from_vp(vp, intrinsics):
vp_norm = normalize(vp, intrinsics)
yaw_calib = np.arctan(vp_norm[0])
pitch_calib = -np.arctan(vp_norm[1]*np.cos(yaw_calib))
roll_calib = 0
return roll_calib, pitch_calib, yaw_calib
def device_from_ecef(pos_ecef, orientation_ecef, pt_ecef):
# device from ecef frame
# device frame is x -> forward, y-> right, z -> down
# accepts single pt or array of pts
input_shape = pt_ecef.shape
pt_ecef = np.atleast_2d(pt_ecef)
ecef_from_device_rot = orient.rotations_from_quats(orientation_ecef)
device_from_ecef_rot = ecef_from_device_rot.T
pt_ecef_rel = pt_ecef - pos_ecef
pt_device = np.einsum('jk,ik->ij', device_from_ecef_rot, pt_ecef_rel)
return pt_device.reshape(input_shape)
def img_from_device(pt_device):
# img coordinates from pts in device frame
# first transforms to view frame, then to img coords
# accepts single pt or array of pts
input_shape = pt_device.shape
pt_device = np.atleast_2d(pt_device)
pt_view = np.einsum('jk,ik->ij', view_frame_from_device_frame, pt_device)
# This function should never return negative depths
pt_view[pt_view[:, 2] < 0] = np.nan
pt_img = pt_view/pt_view[:, 2:3]
return pt_img.reshape(input_shape)[:, :2]
@@ -1,70 +0,0 @@
import numpy as np
from openpilot.common.transformations.orientation import rot_from_euler
from openpilot.common.transformations.camera import get_view_frame_from_calib_frame, view_frame_from_device_frame, _ar_ox_fisheye
# segnet
SEGNET_SIZE = (512, 384)
# MED model
MEDMODEL_INPUT_SIZE = (512, 256)
MEDMODEL_YUV_SIZE = (MEDMODEL_INPUT_SIZE[0], MEDMODEL_INPUT_SIZE[1] * 3 // 2)
MEDMODEL_CY = 47.6
medmodel_fl = 910.0
medmodel_intrinsics = np.array([
[medmodel_fl, 0.0, 0.5 * MEDMODEL_INPUT_SIZE[0]],
[0.0, medmodel_fl, MEDMODEL_CY],
[0.0, 0.0, 1.0]])
# BIG model
BIGMODEL_INPUT_SIZE = (1024, 512)
BIGMODEL_YUV_SIZE = (BIGMODEL_INPUT_SIZE[0], BIGMODEL_INPUT_SIZE[1] * 3 // 2)
bigmodel_fl = 910.0
bigmodel_intrinsics = np.array([
[bigmodel_fl, 0.0, 0.5 * BIGMODEL_INPUT_SIZE[0]],
[0.0, bigmodel_fl, 256 + MEDMODEL_CY],
[0.0, 0.0, 1.0]])
# SBIG model (big model with the size of small model)
SBIGMODEL_INPUT_SIZE = (512, 256)
SBIGMODEL_YUV_SIZE = (SBIGMODEL_INPUT_SIZE[0], SBIGMODEL_INPUT_SIZE[1] * 3 // 2)
sbigmodel_fl = 455.0
sbigmodel_intrinsics = np.array([
[sbigmodel_fl, 0.0, 0.5 * SBIGMODEL_INPUT_SIZE[0]],
[0.0, sbigmodel_fl, 0.5 * (256 + MEDMODEL_CY)],
[0.0, 0.0, 1.0]])
DM_INPUT_SIZE = (1440, 960)
dmonitoringmodel_fl = _ar_ox_fisheye.focal_length
dmonitoringmodel_intrinsics = np.array([
[dmonitoringmodel_fl, 0.0, DM_INPUT_SIZE[0]/2],
[0.0, dmonitoringmodel_fl, DM_INPUT_SIZE[1]/2 - (_ar_ox_fisheye.height - DM_INPUT_SIZE[1])/2],
[0.0, 0.0, 1.0]])
bigmodel_frame_from_calib_frame = np.dot(bigmodel_intrinsics,
get_view_frame_from_calib_frame(0, 0, 0, 0))
sbigmodel_frame_from_calib_frame = np.dot(sbigmodel_intrinsics,
get_view_frame_from_calib_frame(0, 0, 0, 0))
medmodel_frame_from_calib_frame = np.dot(medmodel_intrinsics,
get_view_frame_from_calib_frame(0, 0, 0, 0))
medmodel_frame_from_bigmodel_frame = np.dot(medmodel_intrinsics, np.linalg.inv(bigmodel_intrinsics))
calib_from_medmodel = np.linalg.inv(medmodel_frame_from_calib_frame[:, :3])
calib_from_sbigmodel = np.linalg.inv(sbigmodel_frame_from_calib_frame[:, :3])
# This function is verified to give similar results to xx.uncommon.utils.transform_img
def get_warp_matrix(device_from_calib_euler: np.ndarray, intrinsics: np.ndarray, bigmodel_frame: bool = False) -> np.ndarray:
calib_from_model = calib_from_sbigmodel if bigmodel_frame else calib_from_medmodel
device_from_calib = rot_from_euler(device_from_calib_euler)
camera_from_calib = intrinsics @ view_frame_from_device_frame @ device_from_calib
warp_matrix: np.ndarray = camera_from_calib @ calib_from_model
return warp_matrix
@@ -1,77 +0,0 @@
import os
import glob
from openpilot.common.file_chunker import chunk_file, get_chunk_paths
Import('env', 'arch')
chunker_file = File("#common/file_chunker.py")
lenv = env.Clone()
tinygrad_root = env.Dir("#").abspath
tinygrad_files = ["#"+x for x in glob.glob(env.Dir("#tinygrad_repo").relpath + "/**", recursive=True, root_dir=tinygrad_root)
if 'pycache' not in x and os.path.isfile(os.path.join(tinygrad_root, x))]
def estimate_pickle_max_size(onnx_size):
return 1.2 * onnx_size + 10 * 1024 * 1024 # 20% + 10MB is plenty
# compile warp
# THREADS=0 is need to prevent bug: https://github.com/tinygrad/tinygrad/issues/14689
tg_flags = {
'larch64': 'DEV=QCOM FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0',
'Darwin': f'DEV=CPU THREADS=0 HOME={os.path.expanduser("~")}', # tinygrad calls brew which needs a $HOME in the env
}.get(arch, 'DEV=CPU CPU_LLVM=1 THREADS=0')
# Get model metadata
for model_name in ['driving_vision', 'driving_policy', 'dmonitoring_model']:
fn = File(f"models/{model_name}").abspath
script_files = [File(Dir("#selfdrive/modeld").File("get_model_metadata.py").abspath)]
cmd = f'{tg_flags} python3 {Dir("#selfdrive/modeld").abspath}/get_model_metadata.py {fn}.onnx'
lenv.Command(fn + "_metadata.pkl", [fn + ".onnx"] + tinygrad_files + script_files, cmd)
image_flag = {
'larch64': 'IMAGE=2',
}.get(arch, 'IMAGE=0')
script_files = [File(Dir("#selfdrive/modeld").File("compile_warp.py").abspath)]
compile_warp_cmd = f'{tg_flags} python3 {Dir("#selfdrive/modeld").abspath}/compile_warp.py '
from openpilot.common.transformations.camera import _ar_ox_fisheye, _os_fisheye
warp_targets = []
for cam in [_ar_ox_fisheye, _os_fisheye]:
w, h = cam.width, cam.height
warp_targets += [File(f"models/warp_{w}x{h}_tinygrad.pkl").abspath, File(f"models/dm_warp_{w}x{h}_tinygrad.pkl").abspath]
lenv.Command(warp_targets, tinygrad_files + script_files, compile_warp_cmd)
def tg_compile(flags, model_name):
pythonpath_string = 'PYTHONPATH="${PYTHONPATH}:' + env.Dir("#tinygrad_repo").abspath + '"'
fn = File(f"models/{model_name}").abspath
pkl = fn + "_tinygrad.pkl"
onnx_path = fn + ".onnx"
chunk_targets = get_chunk_paths(pkl, estimate_pickle_max_size(os.path.getsize(onnx_path)))
compile_node = lenv.Command(
pkl,
[onnx_path] + tinygrad_files + [chunker_file],
f'{pythonpath_string} {flags} {image_flag} python3 {Dir("#tinygrad_repo").abspath}/examples/openpilot/compile3.py {fn}.onnx {pkl}',
)
def do_chunk(target, source, env):
chunk_file(pkl, chunk_targets)
return lenv.Command(
chunk_targets,
compile_node,
do_chunk,
)
# Compile small models
for model_name in ['driving_vision', 'driving_policy', 'dmonitoring_model']:
tg_compile(tg_flags, model_name)
# Compile BIG model if USB GPU is available
if "USBGPU" in os.environ:
import subprocess
# because tg doesn't support multi-process
devs = subprocess.check_output('python3 -c "from tinygrad import Device; print(list(Device.get_available_devices()))"', shell=True, cwd=env.Dir('#').abspath)
if b"AMD" in devs:
print("USB GPU detected... building")
flags = "DEV=AMD AMD_IFACE=USB AMD_LLVM=1 NOLOCALS=0 IMAGE=0"
bp = tg_compile(flags, "big_driving_policy")
bv = tg_compile(flags, "big_driving_vision")
lenv.SideEffect('lock', [bp, bv]) # tg doesn't support multi-process so build serially
else:
print("USB GPU not detected... skipping")
@@ -1,209 +0,0 @@
#!/usr/bin/env python3
import time
import pickle
import numpy as np
from pathlib import Path
from tinygrad.tensor import Tensor
from tinygrad.helpers import Context
from tinygrad.device import Device
from tinygrad.engine.jit import TinyJit
from openpilot.system.camerad.cameras.nv12_info import get_nv12_info
from openpilot.common.transformations.model import MEDMODEL_INPUT_SIZE, DM_INPUT_SIZE
from openpilot.common.transformations.camera import _ar_ox_fisheye, _os_fisheye
MODELS_DIR = Path(__file__).parent / 'models'
CAMERA_CONFIGS = [
(_ar_ox_fisheye.width, _ar_ox_fisheye.height), # tici: 1928x1208
(_os_fisheye.width, _os_fisheye.height), # mici: 1344x760
]
UV_SCALE_MATRIX = np.array([[0.5, 0, 0], [0, 0.5, 0], [0, 0, 1]], dtype=np.float32)
UV_SCALE_MATRIX_INV = np.linalg.inv(UV_SCALE_MATRIX)
IMG_BUFFER_SHAPE = (30, MEDMODEL_INPUT_SIZE[1] // 2, MEDMODEL_INPUT_SIZE[0] // 2)
def warp_pkl_path(w, h):
return MODELS_DIR / f'warp_{w}x{h}_tinygrad.pkl'
def dm_warp_pkl_path(w, h):
return MODELS_DIR / f'dm_warp_{w}x{h}_tinygrad.pkl'
def warp_perspective_tinygrad(src_flat, M_inv, dst_shape, src_shape, stride_pad):
w_dst, h_dst = dst_shape
h_src, w_src = src_shape
x = Tensor.arange(w_dst).reshape(1, w_dst).expand(h_dst, w_dst).reshape(-1)
y = Tensor.arange(h_dst).reshape(h_dst, 1).expand(h_dst, w_dst).reshape(-1)
# inline 3x3 matmul as elementwise to avoid reduce op (enables fusion with gather)
src_x = M_inv[0, 0] * x + M_inv[0, 1] * y + M_inv[0, 2]
src_y = M_inv[1, 0] * x + M_inv[1, 1] * y + M_inv[1, 2]
src_w = M_inv[2, 0] * x + M_inv[2, 1] * y + M_inv[2, 2]
src_x = src_x / src_w
src_y = src_y / src_w
x_nn_clipped = Tensor.round(src_x).clip(0, w_src - 1).cast('int')
y_nn_clipped = Tensor.round(src_y).clip(0, h_src - 1).cast('int')
idx = y_nn_clipped * (w_src + stride_pad) + x_nn_clipped
return src_flat[idx]
def frames_to_tensor(frames, model_w, model_h):
H = (frames.shape[0] * 2) // 3
W = frames.shape[1]
in_img1 = Tensor.cat(frames[0:H:2, 0::2],
frames[1:H:2, 0::2],
frames[0:H:2, 1::2],
frames[1:H:2, 1::2],
frames[H:H+H//4].reshape((H//2, W//2)),
frames[H+H//4:H+H//2].reshape((H//2, W//2)), dim=0).reshape((6, H//2, W//2))
return in_img1
def make_frame_prepare(cam_w, cam_h, model_w, model_h):
stride, y_height, uv_height, _ = get_nv12_info(cam_w, cam_h)
uv_offset = stride * y_height
stride_pad = stride - cam_w
def frame_prepare_tinygrad(input_frame, M_inv):
# UV_SCALE @ M_inv @ UV_SCALE_INV simplifies to elementwise scaling
M_inv_uv = M_inv * Tensor([[1.0, 1.0, 0.5], [1.0, 1.0, 0.5], [2.0, 2.0, 1.0]])
# deinterleave NV12 UV plane (UVUV... -> separate U, V)
uv = input_frame[uv_offset:uv_offset + uv_height * stride].reshape(uv_height, stride)
with Context(SPLIT_REDUCEOP=0):
y = warp_perspective_tinygrad(input_frame[:cam_h*stride],
M_inv, (model_w, model_h),
(cam_h, cam_w), stride_pad).realize()
u = warp_perspective_tinygrad(uv[:cam_h//2, :cam_w:2].flatten(),
M_inv_uv, (model_w//2, model_h//2),
(cam_h//2, cam_w//2), 0).realize()
v = warp_perspective_tinygrad(uv[:cam_h//2, 1:cam_w:2].flatten(),
M_inv_uv, (model_w//2, model_h//2),
(cam_h//2, cam_w//2), 0).realize()
yuv = y.cat(u).cat(v).reshape((model_h * 3 // 2, model_w))
tensor = frames_to_tensor(yuv, model_w, model_h)
return tensor
return frame_prepare_tinygrad
def make_update_img_input(frame_prepare, model_w, model_h):
def update_img_input_tinygrad(tensor, frame, M_inv):
M_inv = M_inv.to(Device.DEFAULT)
new_img = frame_prepare(frame, M_inv)
full_buffer = tensor[6:].cat(new_img, dim=0).contiguous()
return full_buffer, Tensor.cat(full_buffer[:6], full_buffer[-6:], dim=0).contiguous().reshape(1, 12, model_h//2, model_w//2)
return update_img_input_tinygrad
def make_update_both_imgs(frame_prepare, model_w, model_h):
update_img = make_update_img_input(frame_prepare, model_w, model_h)
def update_both_imgs_tinygrad(calib_img_buffer, new_img, M_inv,
calib_big_img_buffer, new_big_img, M_inv_big):
calib_img_buffer, calib_img_pair = update_img(calib_img_buffer, new_img, M_inv)
calib_big_img_buffer, calib_big_img_pair = update_img(calib_big_img_buffer, new_big_img, M_inv_big)
return calib_img_buffer, calib_img_pair, calib_big_img_buffer, calib_big_img_pair
return update_both_imgs_tinygrad
def make_warp_dm(cam_w, cam_h, dm_w, dm_h):
stride, y_height, _, _ = get_nv12_info(cam_w, cam_h)
stride_pad = stride - cam_w
def warp_dm(input_frame, M_inv):
M_inv = M_inv.to(Device.DEFAULT)
result = warp_perspective_tinygrad(input_frame[:cam_h*stride], M_inv, (dm_w, dm_h), (cam_h, cam_w), stride_pad).reshape(-1, dm_h * dm_w)
return result
return warp_dm
def compile_modeld_warp(cam_w, cam_h):
model_w, model_h = MEDMODEL_INPUT_SIZE
_, _, _, yuv_size = get_nv12_info(cam_w, cam_h)
print(f"Compiling modeld warp for {cam_w}x{cam_h}...")
frame_prepare = make_frame_prepare(cam_w, cam_h, model_w, model_h)
update_both_imgs = make_update_both_imgs(frame_prepare, model_w, model_h)
update_img_jit = TinyJit(update_both_imgs, prune=True)
full_buffer = Tensor.zeros(IMG_BUFFER_SHAPE, dtype='uint8').contiguous().realize()
big_full_buffer = Tensor.zeros(IMG_BUFFER_SHAPE, dtype='uint8').contiguous().realize()
full_buffer_np = np.zeros(IMG_BUFFER_SHAPE, dtype=np.uint8)
big_full_buffer_np = np.zeros(IMG_BUFFER_SHAPE, dtype=np.uint8)
for i in range(10):
new_frame_np = (32 * np.random.randn(yuv_size).astype(np.float32) + 128).clip(0, 255).astype(np.uint8)
img_inputs = [full_buffer,
Tensor.from_blob(new_frame_np.ctypes.data, (yuv_size,), dtype='uint8').realize(),
Tensor(Tensor.randn(3, 3).mul(8).realize().numpy(), device='NPY')]
new_big_frame_np = (32 * np.random.randn(yuv_size).astype(np.float32) + 128).clip(0, 255).astype(np.uint8)
big_img_inputs = [big_full_buffer,
Tensor.from_blob(new_big_frame_np.ctypes.data, (yuv_size,), dtype='uint8').realize(),
Tensor(Tensor.randn(3, 3).mul(8).realize().numpy(), device='NPY')]
inputs = img_inputs + big_img_inputs
Device.default.synchronize()
inputs_np = [x.numpy() for x in inputs]
inputs_np[0] = full_buffer_np
inputs_np[3] = big_full_buffer_np
st = time.perf_counter()
out = update_img_jit(*inputs)
full_buffer = out[0].contiguous().realize().clone()
big_full_buffer = out[2].contiguous().realize().clone()
mt = time.perf_counter()
Device.default.synchronize()
et = time.perf_counter()
print(f" [{i+1}/10] enqueue {(mt-st)*1e3:6.2f} ms -- total {(et-st)*1e3:6.2f} ms")
pkl_path = warp_pkl_path(cam_w, cam_h)
with open(pkl_path, "wb") as f:
pickle.dump(update_img_jit, f)
print(f" Saved to {pkl_path}")
jit = pickle.load(open(pkl_path, "rb"))
jit(*inputs)
def compile_dm_warp(cam_w, cam_h):
dm_w, dm_h = DM_INPUT_SIZE
_, _, _, yuv_size = get_nv12_info(cam_w, cam_h)
print(f"Compiling DM warp for {cam_w}x{cam_h}...")
warp_dm = make_warp_dm(cam_w, cam_h, dm_w, dm_h)
warp_dm_jit = TinyJit(warp_dm, prune=True)
for i in range(10):
inputs = [Tensor.from_blob((32 * Tensor.randn(yuv_size,) + 128).cast(dtype='uint8').realize().numpy().ctypes.data, (yuv_size,), dtype='uint8'),
Tensor(Tensor.randn(3, 3).mul(8).realize().numpy(), device='NPY')]
Device.default.synchronize()
st = time.perf_counter()
warp_dm_jit(*inputs)
mt = time.perf_counter()
Device.default.synchronize()
et = time.perf_counter()
print(f" [{i+1}/10] enqueue {(mt-st)*1e3:6.2f} ms -- total {(et-st)*1e3:6.2f} ms")
pkl_path = dm_warp_pkl_path(cam_w, cam_h)
with open(pkl_path, "wb") as f:
pickle.dump(warp_dm_jit, f)
print(f" Saved to {pkl_path}")
def run_and_save_pickle():
for cam_w, cam_h in CAMERA_CONFIGS:
compile_modeld_warp(cam_w, cam_h)
compile_dm_warp(cam_w, cam_h)
if __name__ == "__main__":
run_and_save_pickle()
@@ -1,87 +0,0 @@
import numpy as np
def index_function(idx, max_val=192, max_idx=32):
return (max_val) * ((idx/max_idx)**2)
class ModelConstants:
# time and distance indices
IDX_N = 33
T_IDXS = [index_function(idx, max_val=10.0) for idx in range(IDX_N)]
X_IDXS = [index_function(idx, max_val=192.0) for idx in range(IDX_N)]
LEAD_T_IDXS = [0., 2., 4., 6., 8., 10.]
LEAD_T_OFFSETS = [0., 2., 4.]
META_T_IDXS = [2., 4., 6., 8., 10.]
# model inputs constants
N_FRAMES = 2
MODEL_RUN_FREQ = 20
MODEL_CONTEXT_FREQ = 5 # "model_trained_fps"
FEATURE_LEN = 512
DESIRE_LEN = 8
TRAFFIC_CONVENTION_LEN = 2
LAT_PLANNER_STATE_LEN = 4
LATERAL_CONTROL_PARAMS_LEN = 2
PREV_DESIRED_CURV_LEN = 1
# model outputs constants
FCW_THRESHOLDS_5MS2 = np.array([.05, .05, .15, .15, .15], dtype=np.float32)
FCW_THRESHOLDS_3MS2 = np.array([.7, .7], dtype=np.float32)
FCW_5MS2_PROBS_WIDTH = 5
FCW_3MS2_PROBS_WIDTH = 2
DISENGAGE_WIDTH = 5
POSE_WIDTH = 6
WIDE_FROM_DEVICE_WIDTH = 3
LEAD_WIDTH = 4
LANE_LINES_WIDTH = 2
ROAD_EDGES_WIDTH = 2
PLAN_WIDTH = 15
DESIRE_PRED_WIDTH = 8
LAT_PLANNER_SOLUTION_WIDTH = 4
DESIRED_CURV_WIDTH = 1
NUM_LANE_LINES = 4
NUM_ROAD_EDGES = 2
LEAD_TRAJ_LEN = 6
DESIRE_PRED_LEN = 4
PLAN_MHP_N = 5
LEAD_MHP_N = 2
PLAN_MHP_SELECTION = 1
LEAD_MHP_SELECTION = 3
FCW_THRESHOLD_5MS2_HIGH = 0.15
FCW_THRESHOLD_5MS2_LOW = 0.05
FCW_THRESHOLD_3MS2 = 0.7
CONFIDENCE_BUFFER_LEN = 5
RYG_GREEN = 0.01165
RYG_YELLOW = 0.06157
POLY_PATH_DEGREE = 4
# model outputs slices
class Plan:
POSITION = slice(0, 3)
VELOCITY = slice(3, 6)
ACCELERATION = slice(6, 9)
T_FROM_CURRENT_EULER = slice(9, 12)
ORIENTATION_RATE = slice(12, 15)
class Meta:
ENGAGED = slice(0, 1)
# next 2, 4, 6, 8, 10 seconds
GAS_DISENGAGE = slice(1, 31, 6)
BRAKE_DISENGAGE = slice(2, 31, 6)
STEER_OVERRIDE = slice(3, 31, 6)
HARD_BRAKE_3 = slice(4, 31, 6)
HARD_BRAKE_4 = slice(5, 31, 6)
HARD_BRAKE_5 = slice(6, 31, 6)
# next 0, 2, 4, 6, 8, 10 seconds
GAS_PRESS = slice(31, 55, 4)
BRAKE_PRESS = slice(32, 55, 4)
LEFT_BLINKER = slice(33, 55, 4)
RIGHT_BLINKER = slice(34, 55, 4)
@@ -1,193 +0,0 @@
import os
import capnp
import numpy as np
from cereal import log
from openpilot.selfdrive.modeld.constants import ModelConstants, Plan, Meta
SEND_RAW_PRED = os.getenv('SEND_RAW_PRED')
ConfidenceClass = log.ModelDataV2.ConfidenceClass
class PublishState:
def __init__(self):
self.disengage_buffer = np.zeros(ModelConstants.CONFIDENCE_BUFFER_LEN*ModelConstants.DISENGAGE_WIDTH, dtype=np.float32)
self.prev_brake_5ms2_probs = np.zeros(ModelConstants.FCW_5MS2_PROBS_WIDTH, dtype=np.float32)
self.prev_brake_3ms2_probs = np.zeros(ModelConstants.FCW_3MS2_PROBS_WIDTH, dtype=np.float32)
def fill_xyzt(builder, t, x, y, z, x_std=None, y_std=None, z_std=None):
builder.t = t
builder.x = x.tolist()
builder.y = y.tolist()
builder.z = z.tolist()
if x_std is not None:
builder.xStd = x_std.tolist()
if y_std is not None:
builder.yStd = y_std.tolist()
if z_std is not None:
builder.zStd = z_std.tolist()
def fill_xyvat(builder, t, x, y, v, a, x_std=None, y_std=None, v_std=None, a_std=None):
builder.t = t
builder.x = x.tolist()
builder.y = y.tolist()
builder.v = v.tolist()
builder.a = a.tolist()
if x_std is not None:
builder.xStd = x_std.tolist()
if y_std is not None:
builder.yStd = y_std.tolist()
if v_std is not None:
builder.vStd = v_std.tolist()
if a_std is not None:
builder.aStd = a_std.tolist()
def fill_xyz_poly(builder, degree, x, y, z):
xyz = np.stack([x, y, z], axis=1)
coeffs = np.polynomial.polynomial.polyfit(ModelConstants.T_IDXS, xyz, deg=degree)
builder.xCoefficients = coeffs[:, 0].tolist()
builder.yCoefficients = coeffs[:, 1].tolist()
builder.zCoefficients = coeffs[:, 2].tolist()
def fill_lane_line_meta(builder, lane_lines, lane_line_probs):
builder.leftY = lane_lines[1].y[0]
builder.leftProb = lane_line_probs[1]
builder.rightY = lane_lines[2].y[0]
builder.rightProb = lane_line_probs[2]
def fill_model_msg(base_msg: capnp._DynamicStructBuilder, extended_msg: capnp._DynamicStructBuilder,
net_output_data: dict[str, np.ndarray], action: log.ModelDataV2.Action,
publish_state: PublishState, vipc_frame_id: int, vipc_frame_id_extra: int,
frame_id: int, frame_drop: float, timestamp_eof: int, model_execution_time: float,
valid: bool) -> None:
frame_age = frame_id - vipc_frame_id if frame_id > vipc_frame_id else 0
frame_drop_perc = frame_drop * 100
extended_msg.valid = valid
base_msg.valid = valid
driving_model_data = base_msg.drivingModelData
driving_model_data.frameId = vipc_frame_id
driving_model_data.frameIdExtra = vipc_frame_id_extra
driving_model_data.frameDropPerc = frame_drop_perc
driving_model_data.modelExecutionTime = model_execution_time
driving_model_data.action = action
modelV2 = extended_msg.modelV2
modelV2.frameId = vipc_frame_id
modelV2.frameIdExtra = vipc_frame_id_extra
modelV2.frameAge = frame_age
modelV2.frameDropPerc = frame_drop_perc
modelV2.timestampEof = timestamp_eof
modelV2.modelExecutionTime = model_execution_time
# plan
fill_xyzt(modelV2.position, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.POSITION].T, *net_output_data['plan_stds'][0,:,Plan.POSITION].T)
fill_xyzt(modelV2.velocity, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.VELOCITY].T)
fill_xyzt(modelV2.acceleration, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.ACCELERATION].T)
fill_xyzt(modelV2.orientation, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.T_FROM_CURRENT_EULER].T)
fill_xyzt(modelV2.orientationRate, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.ORIENTATION_RATE].T)
# poly path
fill_xyz_poly(driving_model_data.path, ModelConstants.POLY_PATH_DEGREE, *net_output_data['plan'][0,:,Plan.POSITION].T)
# action
modelV2.action = action
# times at X_IDXS of edges and lines aren't used
LINE_T_IDXS: list[float] = []
# lane lines
modelV2.init('laneLines', 4)
for i in range(4):
lane_line = modelV2.laneLines[i]
fill_xyzt(lane_line, LINE_T_IDXS, np.array(ModelConstants.X_IDXS), net_output_data['lane_lines'][0,i,:,0], net_output_data['lane_lines'][0,i,:,1])
modelV2.laneLineStds = net_output_data['lane_lines_stds'][0,:,0,0].tolist()
modelV2.laneLineProbs = net_output_data['lane_lines_prob'][0,1::2].tolist()
fill_lane_line_meta(driving_model_data.laneLineMeta, modelV2.laneLines, modelV2.laneLineProbs)
# road edges
modelV2.init('roadEdges', 2)
for i in range(2):
road_edge = modelV2.roadEdges[i]
fill_xyzt(road_edge, LINE_T_IDXS, np.array(ModelConstants.X_IDXS), net_output_data['road_edges'][0,i,:,0], net_output_data['road_edges'][0,i,:,1])
modelV2.roadEdgeStds = net_output_data['road_edges_stds'][0,:,0,0].tolist()
# leads
modelV2.init('leadsV3', 3)
for i in range(3):
lead = modelV2.leadsV3[i]
fill_xyvat(lead, ModelConstants.LEAD_T_IDXS, *net_output_data['lead'][0,i].T, *net_output_data['lead_stds'][0,i].T)
lead.prob = net_output_data['lead_prob'][0,i].tolist()
lead.probTime = ModelConstants.LEAD_T_OFFSETS[i]
# meta
meta = modelV2.meta
meta.desireState = net_output_data['desire_state'][0].reshape(-1).tolist()
meta.desirePrediction = net_output_data['desire_pred'][0].reshape(-1).tolist()
meta.engagedProb = net_output_data['meta'][0,Meta.ENGAGED].item()
meta.init('disengagePredictions')
disengage_predictions = meta.disengagePredictions
disengage_predictions.t = ModelConstants.META_T_IDXS
disengage_predictions.brakeDisengageProbs = net_output_data['meta'][0,Meta.BRAKE_DISENGAGE].tolist()
disengage_predictions.gasDisengageProbs = net_output_data['meta'][0,Meta.GAS_DISENGAGE].tolist()
disengage_predictions.steerOverrideProbs = net_output_data['meta'][0,Meta.STEER_OVERRIDE].tolist()
disengage_predictions.brake3MetersPerSecondSquaredProbs = net_output_data['meta'][0,Meta.HARD_BRAKE_3].tolist()
disengage_predictions.brake4MetersPerSecondSquaredProbs = net_output_data['meta'][0,Meta.HARD_BRAKE_4].tolist()
disengage_predictions.brake5MetersPerSecondSquaredProbs = net_output_data['meta'][0,Meta.HARD_BRAKE_5].tolist()
disengage_predictions.gasPressProbs = net_output_data['meta'][0,Meta.GAS_PRESS].tolist()
disengage_predictions.brakePressProbs = net_output_data['meta'][0,Meta.BRAKE_PRESS].tolist()
publish_state.prev_brake_5ms2_probs[:-1] = publish_state.prev_brake_5ms2_probs[1:]
publish_state.prev_brake_5ms2_probs[-1] = net_output_data['meta'][0,Meta.HARD_BRAKE_5][0]
publish_state.prev_brake_3ms2_probs[:-1] = publish_state.prev_brake_3ms2_probs[1:]
publish_state.prev_brake_3ms2_probs[-1] = net_output_data['meta'][0,Meta.HARD_BRAKE_3][0]
hard_brake_predicted = (publish_state.prev_brake_5ms2_probs > ModelConstants.FCW_THRESHOLDS_5MS2).all() and \
(publish_state.prev_brake_3ms2_probs > ModelConstants.FCW_THRESHOLDS_3MS2).all()
meta.hardBrakePredicted = hard_brake_predicted.item()
# confidence
if vipc_frame_id % (2*ModelConstants.MODEL_RUN_FREQ) == 0:
# any disengage prob
brake_disengage_probs = net_output_data['meta'][0,Meta.BRAKE_DISENGAGE]
gas_disengage_probs = net_output_data['meta'][0,Meta.GAS_DISENGAGE]
steer_override_probs = net_output_data['meta'][0,Meta.STEER_OVERRIDE]
any_disengage_probs = 1-((1-brake_disengage_probs)*(1-gas_disengage_probs)*(1-steer_override_probs))
# independent disengage prob for each 2s slice
ind_disengage_probs = np.r_[any_disengage_probs[0], np.diff(any_disengage_probs) / (1 - any_disengage_probs[:-1])]
# rolling buf for 2, 4, 6, 8, 10s
publish_state.disengage_buffer[:-ModelConstants.DISENGAGE_WIDTH] = publish_state.disengage_buffer[ModelConstants.DISENGAGE_WIDTH:]
publish_state.disengage_buffer[-ModelConstants.DISENGAGE_WIDTH:] = ind_disengage_probs
score = 0.
for i in range(ModelConstants.DISENGAGE_WIDTH):
score += publish_state.disengage_buffer[i*ModelConstants.DISENGAGE_WIDTH+ModelConstants.DISENGAGE_WIDTH-1-i].item() / ModelConstants.DISENGAGE_WIDTH
if score < ModelConstants.RYG_GREEN:
modelV2.confidence = ConfidenceClass.green
elif score < ModelConstants.RYG_YELLOW:
modelV2.confidence = ConfidenceClass.yellow
else:
modelV2.confidence = ConfidenceClass.red
# raw prediction if enabled
if SEND_RAW_PRED:
modelV2.rawPredictions = net_output_data['raw_pred'].tobytes()
def fill_pose_msg(msg: capnp._DynamicStructBuilder, net_output_data: dict[str, np.ndarray],
vipc_frame_id: int, vipc_dropped_frames: int, timestamp_eof: int, live_calib_seen: bool) -> None:
msg.valid = live_calib_seen & (vipc_dropped_frames < 1)
cameraOdometry = msg.cameraOdometry
cameraOdometry.frameId = vipc_frame_id
cameraOdometry.timestampEof = timestamp_eof
cameraOdometry.trans = net_output_data['pose'][0,:3].tolist()
cameraOdometry.rot = net_output_data['pose'][0,3:].tolist()
cameraOdometry.wideFromDeviceEuler = net_output_data['wide_from_device_euler'][0,:].tolist()
cameraOdometry.roadTransformTrans = net_output_data['road_transform'][0,:3].tolist()
cameraOdometry.transStd = net_output_data['pose_stds'][0,:3].tolist()
cameraOdometry.rotStd = net_output_data['pose_stds'][0,3:].tolist()
cameraOdometry.wideFromDeviceEulerStd = net_output_data['wide_from_device_euler_stds'][0,:].tolist()
cameraOdometry.roadTransformTransStd = net_output_data['road_transform_stds'][0,:3].tolist()
@@ -1,55 +0,0 @@
#!/usr/bin/env python3
import sys
import pathlib
import codecs
import pickle
from typing import Any
from tinygrad.nn.onnx import OnnxPBParser
class MetadataOnnxPBParser(OnnxPBParser):
def _parse_ModelProto(self) -> dict:
obj: dict[str, Any] = {"graph": {"input": [], "output": []}, "metadata_props": []}
for fid, wire_type in self._parse_message(self.reader.len):
match fid:
case 7:
obj["graph"] = self._parse_GraphProto()
case 14:
obj["metadata_props"].append(self._parse_StringStringEntryProto())
case _:
self.reader.skip_field(wire_type)
return obj
def get_name_and_shape(value_info: dict[str, Any]) -> tuple[str, tuple[int, ...]]:
shape = tuple(int(dim) if isinstance(dim, int) else 0 for dim in value_info["parsed_type"].shape)
name = value_info["name"]
return name, shape
def get_metadata_value_by_name(model: dict[str, Any], name: str) -> str | Any:
for prop in model["metadata_props"]:
if prop["key"] == name:
return prop["value"]
return None
if __name__ == "__main__":
model_path = pathlib.Path(sys.argv[1])
model = MetadataOnnxPBParser(model_path).parse()
output_slices = get_metadata_value_by_name(model, 'output_slices')
assert output_slices is not None, 'output_slices not found in metadata'
metadata = {
'model_checkpoint': get_metadata_value_by_name(model, 'model_checkpoint'),
'output_slices': pickle.loads(codecs.decode(output_slices.encode(), "base64")),
'input_shapes': dict(get_name_and_shape(x) for x in model["graph"]["input"]),
'output_shapes': dict(get_name_and_shape(x) for x in model["graph"]["output"]),
}
metadata_path = model_path.parent / (model_path.stem + '_metadata.pkl')
with open(metadata_path, 'wb') as f:
pickle.dump(metadata, f)
print(f'saved metadata to {metadata_path}')
@@ -1,422 +0,0 @@
#!/usr/bin/env python3
import os
from openpilot.system.hardware import TICI
os.environ['DEV'] = 'QCOM' if TICI else 'CPU'
USBGPU = "USBGPU" in os.environ
if USBGPU:
os.environ['DEV'] = 'AMD'
os.environ['AMD_IFACE'] = 'USB'
from tinygrad.tensor import Tensor
import time
import pickle
import numpy as np
import cereal.messaging as messaging
from cereal import car, log
from pathlib import Path
from cereal.messaging import PubMaster, SubMaster
from msgq.visionipc import VisionIpcClient, VisionStreamType, VisionBuf
from opendbc.car.car_helpers import get_demo_car_params
from openpilot.common.swaglog import cloudlog
from openpilot.common.params import Params
from openpilot.common.filter_simple import FirstOrderFilter
from openpilot.common.realtime import config_realtime_process, DT_MDL
from openpilot.common.transformations.camera import DEVICE_CAMERAS
from openpilot.system.camerad.cameras.nv12_info import get_nv12_info
from openpilot.common.transformations.model import get_warp_matrix
from openpilot.selfdrive.controls.lib.desire_helper import DesireHelper
from openpilot.selfdrive.controls.lib.drive_helpers import get_accel_from_plan, smooth_value, get_curvature_from_plan
from openpilot.selfdrive.modeld.parse_model_outputs import Parser
from openpilot.selfdrive.modeld.fill_model_msg import fill_model_msg, fill_pose_msg, PublishState
from openpilot.common.file_chunker import read_file_chunked
from openpilot.selfdrive.modeld.constants import ModelConstants, Plan
PROCESS_NAME = "selfdrive.modeld.modeld"
SEND_RAW_PRED = os.getenv('SEND_RAW_PRED')
VISION_PKL_PATH = Path(__file__).parent / 'models/driving_vision_tinygrad.pkl'
POLICY_PKL_PATH = Path(__file__).parent / 'models/driving_policy_tinygrad.pkl'
VISION_METADATA_PATH = Path(__file__).parent / 'models/driving_vision_metadata.pkl'
POLICY_METADATA_PATH = Path(__file__).parent / 'models/driving_policy_metadata.pkl'
MODELS_DIR = Path(__file__).parent / 'models'
LAT_SMOOTH_SECONDS = 0.0
LONG_SMOOTH_SECONDS = 0.3
MIN_LAT_CONTROL_SPEED = 0.3
IMG_QUEUE_SHAPE = (6*(ModelConstants.MODEL_RUN_FREQ//ModelConstants.MODEL_CONTEXT_FREQ + 1), 128, 256)
assert IMG_QUEUE_SHAPE[0] == 30
def get_action_from_model(model_output: dict[str, np.ndarray], prev_action: log.ModelDataV2.Action,
lat_action_t: float, long_action_t: float, v_ego: float) -> log.ModelDataV2.Action:
plan = model_output['plan'][0]
desired_accel, should_stop = get_accel_from_plan(plan[:,Plan.VELOCITY][:,0],
plan[:,Plan.ACCELERATION][:,0],
ModelConstants.T_IDXS,
action_t=long_action_t)
desired_accel = smooth_value(desired_accel, prev_action.desiredAcceleration, LONG_SMOOTH_SECONDS)
desired_curvature = get_curvature_from_plan(plan[:,Plan.T_FROM_CURRENT_EULER][:,2],
plan[:,Plan.ORIENTATION_RATE][:,2],
ModelConstants.T_IDXS,
v_ego,
lat_action_t)
if v_ego > MIN_LAT_CONTROL_SPEED:
desired_curvature = smooth_value(desired_curvature, prev_action.desiredCurvature, LAT_SMOOTH_SECONDS)
else:
desired_curvature = prev_action.desiredCurvature
return log.ModelDataV2.Action(desiredCurvature=float(desired_curvature),
desiredAcceleration=float(desired_accel),
shouldStop=bool(should_stop))
class FrameMeta:
frame_id: int = 0
timestamp_sof: int = 0
timestamp_eof: int = 0
def __init__(self, vipc=None):
if vipc is not None:
self.frame_id, self.timestamp_sof, self.timestamp_eof = vipc.frame_id, vipc.timestamp_sof, vipc.timestamp_eof
class InputQueues:
def __init__ (self, model_fps, env_fps, n_frames_input):
assert env_fps % model_fps == 0
assert env_fps >= model_fps
self.model_fps = model_fps
self.env_fps = env_fps
self.n_frames_input = n_frames_input
self.dtypes = {}
self.shapes = {}
self.q = {}
def update_dtypes_and_shapes(self, input_dtypes, input_shapes) -> None:
self.dtypes.update(input_dtypes)
if self.env_fps == self.model_fps:
self.shapes.update(input_shapes)
else:
for k in input_shapes:
shape = list(input_shapes[k])
if 'img' in k:
n_channels = shape[1] // self.n_frames_input
shape[1] = (self.env_fps // self.model_fps + (self.n_frames_input - 1)) * n_channels
else:
shape[1] = (self.env_fps // self.model_fps) * shape[1]
self.shapes[k] = tuple(shape)
def reset(self) -> None:
self.q = {k: np.zeros(self.shapes[k], dtype=self.dtypes[k]) for k in self.dtypes.keys()}
def enqueue(self, inputs:dict[str, np.ndarray]) -> None:
for k in inputs.keys():
if inputs[k].dtype != self.dtypes[k]:
raise ValueError(f'supplied input <{k}({inputs[k].dtype})> has wrong dtype, expected {self.dtypes[k]}')
input_shape = list(self.shapes[k])
input_shape[1] = -1
single_input = inputs[k].reshape(tuple(input_shape))
sz = single_input.shape[1]
self.q[k][:,:-sz] = self.q[k][:,sz:]
self.q[k][:,-sz:] = single_input
def get(self, *names) -> dict[str, np.ndarray]:
if self.env_fps == self.model_fps:
return {k: self.q[k] for k in names}
else:
out = {}
for k in names:
shape = self.shapes[k]
if 'img' in k:
n_channels = shape[1] // (self.env_fps // self.model_fps + (self.n_frames_input - 1))
out[k] = np.concatenate([self.q[k][:, s:s+n_channels] for s in np.linspace(0, shape[1] - n_channels, self.n_frames_input, dtype=int)], axis=1)
elif 'pulse' in k:
# any pulse within interval counts
out[k] = self.q[k].reshape((shape[0], shape[1] * self.model_fps // self.env_fps, self.env_fps // self.model_fps, -1)).max(axis=2)
else:
idxs = np.arange(-1, -shape[1], -self.env_fps // self.model_fps)[::-1]
out[k] = self.q[k][:, idxs]
return out
class ModelState:
inputs: dict[str, np.ndarray]
output: np.ndarray
prev_desire: np.ndarray # for tracking the rising edge of the pulse
def __init__(self):
with open(VISION_METADATA_PATH, 'rb') as f:
vision_metadata = pickle.load(f)
self.vision_input_shapes = vision_metadata['input_shapes']
self.vision_input_names = list(self.vision_input_shapes.keys())
self.vision_output_slices = vision_metadata['output_slices']
vision_output_size = vision_metadata['output_shapes']['outputs'][1]
with open(POLICY_METADATA_PATH, 'rb') as f:
policy_metadata = pickle.load(f)
self.policy_input_shapes = policy_metadata['input_shapes']
self.policy_output_slices = policy_metadata['output_slices']
policy_output_size = policy_metadata['output_shapes']['outputs'][1]
self.prev_desire = np.zeros(ModelConstants.DESIRE_LEN, dtype=np.float32)
# policy inputs
self.numpy_inputs = {k: np.zeros(self.policy_input_shapes[k], dtype=np.float32) for k in self.policy_input_shapes}
self.full_input_queues = InputQueues(ModelConstants.MODEL_CONTEXT_FREQ, ModelConstants.MODEL_RUN_FREQ, ModelConstants.N_FRAMES)
for k in ['desire_pulse', 'features_buffer']:
self.full_input_queues.update_dtypes_and_shapes({k: self.numpy_inputs[k].dtype}, {k: self.numpy_inputs[k].shape})
self.full_input_queues.reset()
self.img_queues = {'img': Tensor.zeros(IMG_QUEUE_SHAPE, dtype='uint8').contiguous().realize(),
'big_img': Tensor.zeros(IMG_QUEUE_SHAPE, dtype='uint8').contiguous().realize()}
self.full_frames : dict[str, Tensor] = {}
self._blob_cache : dict[int, Tensor] = {}
self.transforms_np = {k: np.zeros((3,3), dtype=np.float32) for k in self.img_queues}
self.transforms = {k: Tensor(v, device='NPY').realize() for k, v in self.transforms_np.items()}
self.vision_output = np.zeros(vision_output_size, dtype=np.float32)
self.policy_inputs = {k: Tensor(v, device='NPY').realize() for k,v in self.numpy_inputs.items()}
self.policy_output = np.zeros(policy_output_size, dtype=np.float32)
self.parser = Parser()
self.frame_buf_params : dict[str, tuple[int, int, int, int]] = {}
self.update_imgs = None
self.vision_run = pickle.loads(read_file_chunked(str(VISION_PKL_PATH)))
self.policy_run = pickle.loads(read_file_chunked(str(POLICY_PKL_PATH)))
def slice_outputs(self, model_outputs: np.ndarray, output_slices: dict[str, slice]) -> dict[str, np.ndarray]:
parsed_model_outputs = {k: model_outputs[np.newaxis, v] for k,v in output_slices.items()}
return parsed_model_outputs
def run(self, bufs: dict[str, VisionBuf], transforms: dict[str, np.ndarray],
inputs: dict[str, np.ndarray], prepare_only: bool) -> dict[str, np.ndarray] | None:
# Model decides when action is completed, so desire input is just a pulse triggered on rising edge
inputs['desire_pulse'][0] = 0
new_desire = np.where(inputs['desire_pulse'] - self.prev_desire > .99, inputs['desire_pulse'], 0)
self.prev_desire[:] = inputs['desire_pulse']
if self.update_imgs is None:
for key in bufs.keys():
w, h = bufs[key].width, bufs[key].height
self.frame_buf_params[key] = get_nv12_info(w, h)
warp_path = MODELS_DIR / f'warp_{w}x{h}_tinygrad.pkl'
with open(warp_path, "rb") as f:
self.update_imgs = pickle.load(f)
for key in bufs.keys():
ptr = bufs[key].data.ctypes.data
yuv_size = self.frame_buf_params[key][3]
# There is a ringbuffer of imgs, just cache tensors pointing to all of them
cache_key = (key, ptr)
if cache_key not in self._blob_cache:
self._blob_cache[cache_key] = Tensor.from_blob(ptr, (yuv_size,), dtype='uint8')
self.full_frames[key] = self._blob_cache[cache_key]
for key in bufs.keys():
self.transforms_np[key][:,:] = transforms[key][:,:]
out = self.update_imgs(self.img_queues['img'], self.full_frames['img'], self.transforms['img'],
self.img_queues['big_img'], self.full_frames['big_img'], self.transforms['big_img'])
self.img_queues['img'], self.img_queues['big_img'] = out[0].realize(), out[2].realize()
vision_inputs = {'img': out[1], 'big_img': out[3]}
if prepare_only:
return None
self.vision_output = self.vision_run(**vision_inputs).contiguous().realize().uop.base.buffer.numpy().flatten()
vision_outputs_dict = self.parser.parse_vision_outputs(self.slice_outputs(self.vision_output, self.vision_output_slices))
self.full_input_queues.enqueue({'features_buffer': vision_outputs_dict['hidden_state'], 'desire_pulse': new_desire})
for k in ['desire_pulse', 'features_buffer']:
self.numpy_inputs[k][:] = self.full_input_queues.get(k)[k]
self.numpy_inputs['traffic_convention'][:] = inputs['traffic_convention']
self.policy_output = self.policy_run(**self.policy_inputs).contiguous().realize().uop.base.buffer.numpy().flatten()
policy_outputs_dict = self.parser.parse_policy_outputs(self.slice_outputs(self.policy_output, self.policy_output_slices))
combined_outputs_dict = {**vision_outputs_dict, **policy_outputs_dict}
if SEND_RAW_PRED:
combined_outputs_dict['raw_pred'] = np.concatenate([self.vision_output.copy(), self.policy_output.copy()])
return combined_outputs_dict
def main(demo=False):
cloudlog.warning("modeld init")
if not USBGPU:
# USB GPU currently saturates a core so can't do this yet,
# also need to move the aux USB interrupts for good timings
config_realtime_process(7, 54)
st = time.monotonic()
cloudlog.warning("loading model")
model = ModelState()
cloudlog.warning(f"models loaded in {time.monotonic() - st:.1f}s, modeld starting")
# visionipc clients
while True:
available_streams = VisionIpcClient.available_streams("camerad", block=False)
if available_streams:
use_extra_client = VisionStreamType.VISION_STREAM_WIDE_ROAD in available_streams and VisionStreamType.VISION_STREAM_ROAD in available_streams
main_wide_camera = VisionStreamType.VISION_STREAM_ROAD not in available_streams
break
time.sleep(.1)
vipc_client_main_stream = VisionStreamType.VISION_STREAM_WIDE_ROAD if main_wide_camera else VisionStreamType.VISION_STREAM_ROAD
vipc_client_main = VisionIpcClient("camerad", vipc_client_main_stream, True)
vipc_client_extra = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_WIDE_ROAD, False)
cloudlog.warning(f"vision stream set up, main_wide_camera: {main_wide_camera}, use_extra_client: {use_extra_client}")
while not vipc_client_main.connect(False):
time.sleep(0.1)
while use_extra_client and not vipc_client_extra.connect(False):
time.sleep(0.1)
cloudlog.warning(f"connected main cam with buffer size: {vipc_client_main.buffer_len} ({vipc_client_main.width} x {vipc_client_main.height})")
if use_extra_client:
cloudlog.warning(f"connected extra cam with buffer size: {vipc_client_extra.buffer_len} ({vipc_client_extra.width} x {vipc_client_extra.height})")
# messaging
pm = PubMaster(["modelV2", "drivingModelData", "cameraOdometry"])
sm = SubMaster(["deviceState", "carState", "roadCameraState", "liveCalibration", "driverMonitoringState", "carControl", "liveDelay"])
publish_state = PublishState()
params = Params()
# setup filter to track dropped frames
frame_dropped_filter = FirstOrderFilter(0., 10., 1. / ModelConstants.MODEL_RUN_FREQ)
frame_id = 0
last_vipc_frame_id = 0
run_count = 0
model_transform_main = np.zeros((3, 3), dtype=np.float32)
model_transform_extra = np.zeros((3, 3), dtype=np.float32)
live_calib_seen = False
buf_main, buf_extra = None, None
meta_main = FrameMeta()
meta_extra = FrameMeta()
if demo:
CP = get_demo_car_params()
else:
CP = messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams)
cloudlog.info("modeld got CarParams: %s", CP.brand)
# TODO this needs more thought, use .2s extra for now to estimate other delays
# TODO Move smooth seconds to action function
long_delay = CP.longitudinalActuatorDelay + LONG_SMOOTH_SECONDS
prev_action = log.ModelDataV2.Action()
DH = DesireHelper()
while True:
# Keep receiving frames until we are at least 1 frame ahead of previous extra frame
while meta_main.timestamp_sof < meta_extra.timestamp_sof + 25000000:
buf_main = vipc_client_main.recv()
meta_main = FrameMeta(vipc_client_main)
if buf_main is None:
break
if buf_main is None:
cloudlog.debug("vipc_client_main no frame")
continue
if use_extra_client:
# Keep receiving extra frames until frame id matches main camera
while True:
buf_extra = vipc_client_extra.recv()
meta_extra = FrameMeta(vipc_client_extra)
if buf_extra is None or meta_main.timestamp_sof < meta_extra.timestamp_sof + 25000000:
break
if buf_extra is None:
cloudlog.debug("vipc_client_extra no frame")
continue
if abs(meta_main.timestamp_sof - meta_extra.timestamp_sof) > 10000000:
cloudlog.error(f"frames out of sync! main: {meta_main.frame_id} ({meta_main.timestamp_sof / 1e9:.5f}),\
extra: {meta_extra.frame_id} ({meta_extra.timestamp_sof / 1e9:.5f})")
else:
# Use single camera
buf_extra = buf_main
meta_extra = meta_main
sm.update(0)
desire = DH.desire
is_rhd = sm["driverMonitoringState"].isRHD
frame_id = sm["roadCameraState"].frameId
v_ego = max(sm["carState"].vEgo, 0.)
lat_delay = sm["liveDelay"].lateralDelay + LAT_SMOOTH_SECONDS
if sm.updated["liveCalibration"] and sm.seen['roadCameraState'] and sm.seen['deviceState']:
device_from_calib_euler = np.array(sm["liveCalibration"].rpyCalib, dtype=np.float32)
dc = DEVICE_CAMERAS[(str(sm['deviceState'].deviceType), str(sm['roadCameraState'].sensor))]
model_transform_main = get_warp_matrix(device_from_calib_euler, dc.ecam.intrinsics if main_wide_camera else dc.fcam.intrinsics, False).astype(np.float32)
model_transform_extra = get_warp_matrix(device_from_calib_euler, dc.ecam.intrinsics, True).astype(np.float32)
live_calib_seen = True
traffic_convention = np.zeros(2)
traffic_convention[int(is_rhd)] = 1
vec_desire = np.zeros(ModelConstants.DESIRE_LEN, dtype=np.float32)
if desire >= 0 and desire < ModelConstants.DESIRE_LEN:
vec_desire[desire] = 1
# tracked dropped frames
vipc_dropped_frames = max(0, meta_main.frame_id - last_vipc_frame_id - 1)
frames_dropped = frame_dropped_filter.update(min(vipc_dropped_frames, 10))
if run_count < 10: # let frame drops warm up
frame_dropped_filter.x = 0.
frames_dropped = 0.
run_count = run_count + 1
frame_drop_ratio = frames_dropped / (1 + frames_dropped)
prepare_only = vipc_dropped_frames > 0
if prepare_only:
cloudlog.error(f"skipping model eval. Dropped {vipc_dropped_frames} frames")
bufs = {name: buf_extra if 'big' in name else buf_main for name in model.vision_input_names}
transforms = {name: model_transform_extra if 'big' in name else model_transform_main for name in model.vision_input_names}
inputs:dict[str, np.ndarray] = {
'desire_pulse': vec_desire,
'traffic_convention': traffic_convention,
}
mt1 = time.perf_counter()
model_output = model.run(bufs, transforms, inputs, prepare_only)
mt2 = time.perf_counter()
model_execution_time = mt2 - mt1
if model_output is not None:
modelv2_send = messaging.new_message('modelV2')
drivingdata_send = messaging.new_message('drivingModelData')
posenet_send = messaging.new_message('cameraOdometry')
action = get_action_from_model(model_output, prev_action, lat_delay + DT_MDL, long_delay + DT_MDL, v_ego)
prev_action = action
fill_model_msg(drivingdata_send, modelv2_send, model_output, action,
publish_state, meta_main.frame_id, meta_extra.frame_id, frame_id,
frame_drop_ratio, meta_main.timestamp_eof, model_execution_time, live_calib_seen)
desire_state = modelv2_send.modelV2.meta.desireState
l_lane_change_prob = desire_state[log.Desire.laneChangeLeft]
r_lane_change_prob = desire_state[log.Desire.laneChangeRight]
lane_change_prob = l_lane_change_prob + r_lane_change_prob
DH.update(sm['carState'], sm['carControl'].latActive, lane_change_prob)
modelv2_send.modelV2.meta.laneChangeState = DH.lane_change_state
modelv2_send.modelV2.meta.laneChangeDirection = DH.lane_change_direction
drivingdata_send.drivingModelData.meta.laneChangeState = DH.lane_change_state
drivingdata_send.drivingModelData.meta.laneChangeDirection = DH.lane_change_direction
fill_pose_msg(posenet_send, model_output, meta_main.frame_id, vipc_dropped_frames, meta_main.timestamp_eof, live_calib_seen)
pm.send('modelV2', modelv2_send)
pm.send('drivingModelData', drivingdata_send)
pm.send('cameraOdometry', posenet_send)
last_vipc_frame_id = meta_main.frame_id
if __name__ == "__main__":
try:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--demo', action='store_true', help='A boolean for demo mode.')
args = parser.parse_args()
main(demo=args.demo)
except KeyboardInterrupt:
cloudlog.warning("got SIGINT")
@@ -1,66 +0,0 @@
## Neural networks in openpilot
To view the architecture of the ONNX networks, you can use [netron](https://netron.app/)
## Driving Model (vision model + temporal policy model)
### Vision inputs (Full size: 799906 x float32)
* **image stream**
* Two consecutive images (256 * 512 * 3 in RGB) recorded at 20 Hz : 393216 = 2 * 6 * 128 * 256
* Each 256 * 512 image is represented in YUV420 with 6 channels : 6 * 128 * 256
* Channels 0,1,2,3 represent the full-res Y channel and are represented in numpy as Y[::2, ::2], Y[::2, 1::2], Y[1::2, ::2], and Y[1::2, 1::2]
* Channel 4 represents the half-res U channel
* Channel 5 represents the half-res V channel
* **wide image stream**
* Two consecutive images (256 * 512 * 3 in RGB) recorded at 20 Hz : 393216 = 2 * 6 * 128 * 256
* Each 256 * 512 image is represented in YUV420 with 6 channels : 6 * 128 * 256
* Channels 0,1,2,3 represent the full-res Y channel and are represented in numpy as Y[::2, ::2], Y[::2, 1::2], Y[1::2, ::2], and Y[1::2, 1::2]
* Channel 4 represents the half-res U channel
* Channel 5 represents the half-res V channel
### Policy inputs
* **desire**
* one-hot encoded buffer to command model to execute certain actions, bit needs to be sent for the past 5 seconds (at 20FPS) : 100 * 8
* **traffic convention**
* one-hot encoded vector to tell model whether traffic is right-hand or left-hand traffic : 2
* **lateral control params**
* speed and steering delay for predicting the desired curvature: 2
* **previous desired curvatures**
* vector of previously predicted desired curvatures: 100 * 1
* **feature buffer**
* a buffer of intermediate features including the current feature to form a 5 seconds temporal context (at 20FPS) : 100 * 512
### Driving Model output format (Full size: XXX x float32)
Refer to **slice_outputs** and **parse_vision_outputs/parse_policy_outputs** in modeld.
## Driver Monitoring Model
* .onnx model can be run with onnx runtimes
* .dlc file is a pre-quantized model and only runs on qualcomm DSPs
### input format
* single image W = 1440 H = 960 luminance channel (Y) from the planar YUV420 format:
* full input size is 1440 * 960 = 1382400
* normalized ranging from 0.0 to 1.0 in float32 (onnx runner) or ranging from 0 to 255 in uint8 (snpe runner)
* camera calibration angles (roll, pitch, yaw) from liveCalibration: 3 x float32 inputs
### output format
* 84 x float32 outputs = 2 + 41 * 2 ([parsing example](https://github.com/commaai/openpilot/blob/22ce4e17ba0d3bfcf37f8255a4dd1dc683fe0c38/selfdrive/modeld/models/dmonitoring.cc#L33))
* for each person in the front seats (2 * 41)
* face pose: 12 = 6 + 6
* face orientation [pitch, yaw, roll] in camera frame: 3
* face position [dx, dy] relative to image center: 2
* normalized face size: 1
* standard deviations for above outputs: 6
* face visible probability: 1
* eyes: 20 = (8 + 1) + (8 + 1) + 1 + 1
* eye position and size, and their standard deviations: 8
* eye visible probability: 1
* eye closed probability: 1
* wearing sunglasses probability: 1
* face occluded probability: 1
* touching wheel probability: 1
* paying attention probability: 1
* (deprecated) distracted probabilities: 2
* using phone probability: 1
* distracted probability: 1
* common outputs 1
* left hand drive probability: 1
@@ -1,124 +0,0 @@
import numpy as np
from openpilot.selfdrive.modeld.constants import ModelConstants
def safe_exp(x, out=None):
# -11 is around 10**14, more causes float16 overflow
return np.exp(np.clip(x, -np.inf, 11), out=out)
def sigmoid(x):
return 1. / (1. + safe_exp(-x))
def softmax(x, axis=-1):
x -= np.max(x, axis=axis, keepdims=True)
if x.dtype == np.float32 or x.dtype == np.float64:
safe_exp(x, out=x)
else:
x = safe_exp(x)
x /= np.sum(x, axis=axis, keepdims=True)
return x
class Parser:
def __init__(self, ignore_missing=False):
self.ignore_missing = ignore_missing
def check_missing(self, outs, name):
missing = name not in outs
if missing and not self.ignore_missing:
raise ValueError(f"Missing output {name}")
return missing
def parse_categorical_crossentropy(self, name, outs, out_shape=None):
if self.check_missing(outs, name):
return
raw = outs[name]
if out_shape is not None:
raw = raw.reshape((raw.shape[0],) + out_shape)
outs[name] = softmax(raw, axis=-1)
def parse_binary_crossentropy(self, name, outs):
if self.check_missing(outs, name):
return
raw = outs[name]
outs[name] = sigmoid(raw)
def parse_mdn(self, name, outs, in_N=0, out_N=1, out_shape=None):
if self.check_missing(outs, name):
return
raw = outs[name]
raw = raw.reshape((raw.shape[0], max(in_N, 1), -1))
n_values = (raw.shape[2] - out_N)//2
pred_mu = raw[:,:,:n_values]
pred_std = safe_exp(raw[:,:,n_values: 2*n_values])
if in_N > 1:
weights = np.zeros((raw.shape[0], in_N, out_N), dtype=raw.dtype)
for i in range(out_N):
weights[:,:,i - out_N] = softmax(raw[:,:,i - out_N], axis=-1)
if out_N == 1:
for fidx in range(weights.shape[0]):
idxs = np.argsort(weights[fidx][:,0])[::-1]
weights[fidx] = weights[fidx][idxs]
pred_mu[fidx] = pred_mu[fidx][idxs]
pred_std[fidx] = pred_std[fidx][idxs]
full_shape = tuple([raw.shape[0], in_N] + list(out_shape))
outs[name + '_weights'] = weights
outs[name + '_hypotheses'] = pred_mu.reshape(full_shape)
outs[name + '_stds_hypotheses'] = pred_std.reshape(full_shape)
pred_mu_final = np.zeros((raw.shape[0], out_N, n_values), dtype=raw.dtype)
pred_std_final = np.zeros((raw.shape[0], out_N, n_values), dtype=raw.dtype)
for fidx in range(weights.shape[0]):
for hidx in range(out_N):
idxs = np.argsort(weights[fidx,:,hidx])[::-1]
pred_mu_final[fidx, hidx] = pred_mu[fidx, idxs[0]]
pred_std_final[fidx, hidx] = pred_std[fidx, idxs[0]]
else:
pred_mu_final = pred_mu
pred_std_final = pred_std
if out_N > 1:
final_shape = tuple([raw.shape[0], out_N] + list(out_shape))
else:
final_shape = tuple([raw.shape[0],] + list(out_shape))
outs[name] = pred_mu_final.reshape(final_shape)
outs[name + '_stds'] = pred_std_final.reshape(final_shape)
def is_mhp(self, outs, name, shape):
if self.check_missing(outs, name):
return False
if outs[name].shape[1] == 2 * shape:
return False
return True
def parse_vision_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]:
self.parse_mdn('pose', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,))
self.parse_mdn('wide_from_device_euler', outs, in_N=0, out_N=0, out_shape=(ModelConstants.WIDE_FROM_DEVICE_WIDTH,))
self.parse_mdn('road_transform', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,))
self.parse_mdn('lane_lines', outs, in_N=0, out_N=0, out_shape=(ModelConstants.NUM_LANE_LINES,ModelConstants.IDX_N,ModelConstants.LANE_LINES_WIDTH))
self.parse_mdn('road_edges', outs, in_N=0, out_N=0, out_shape=(ModelConstants.NUM_ROAD_EDGES,ModelConstants.IDX_N,ModelConstants.LANE_LINES_WIDTH))
self.parse_binary_crossentropy('lane_lines_prob', outs)
self.parse_categorical_crossentropy('desire_pred', outs, out_shape=(ModelConstants.DESIRE_PRED_LEN,ModelConstants.DESIRE_PRED_WIDTH))
self.parse_binary_crossentropy('meta', outs)
self.parse_binary_crossentropy('lead_prob', outs)
lead_mhp = self.is_mhp(outs, 'lead', ModelConstants.LEAD_MHP_SELECTION * ModelConstants.LEAD_TRAJ_LEN * ModelConstants.LEAD_WIDTH)
lead_in_N, lead_out_N = (ModelConstants.LEAD_MHP_N, ModelConstants.LEAD_MHP_SELECTION) if lead_mhp else (0, 0)
lead_out_shape = (ModelConstants.LEAD_TRAJ_LEN, ModelConstants.LEAD_WIDTH) if lead_mhp else \
(ModelConstants.LEAD_MHP_SELECTION, ModelConstants.LEAD_TRAJ_LEN, ModelConstants.LEAD_WIDTH)
self.parse_mdn('lead', outs, in_N=lead_in_N, out_N=lead_out_N, out_shape=lead_out_shape)
return outs
def parse_policy_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]:
plan_mhp = self.is_mhp(outs, 'plan', ModelConstants.IDX_N * ModelConstants.PLAN_WIDTH)
plan_in_N, plan_out_N = (ModelConstants.PLAN_MHP_N, ModelConstants.PLAN_MHP_SELECTION) if plan_mhp else (0, 0)
self.parse_mdn('plan', outs, in_N=plan_in_N, out_N=plan_out_N, out_shape=(ModelConstants.IDX_N, ModelConstants.PLAN_WIDTH))
if 'planplus' in outs:
self.parse_mdn('planplus', outs, in_N=0, out_N=0, out_shape=(ModelConstants.IDX_N, ModelConstants.PLAN_WIDTH))
self.parse_categorical_crossentropy('desire_state', outs, out_shape=(ModelConstants.DESIRE_PRED_WIDTH,))
return outs
def parse_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]:
outs = self.parse_vision_outputs(outs)
outs = self.parse_policy_outputs(outs)
return outs
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,43 +0,0 @@
0: \x80 PROTO 4
2: \x95 FRAME 90
11: } EMPTY_DICT
12: \x94 MEMOIZE (as 0)
13: ( MARK
14: \x8c SHORT_BINUNICODE 'plan'
20: \x94 MEMOIZE (as 1)
21: \x8c SHORT_BINUNICODE 'builtins'
31: \x94 MEMOIZE (as 2)
32: \x8c SHORT_BINUNICODE 'slice'
39: \x94 MEMOIZE (as 3)
40: \x93 STACK_GLOBAL
41: \x94 MEMOIZE (as 4)
42: K BININT1 0
44: M BININT2 990
47: N NONE
48: \x87 TUPLE3
49: \x94 MEMOIZE (as 5)
50: R REDUCE
51: \x94 MEMOIZE (as 6)
52: \x8c SHORT_BINUNICODE 'desire_state'
66: \x94 MEMOIZE (as 7)
67: h BINGET 4
69: M BININT2 990
72: M BININT2 998
75: N NONE
76: \x87 TUPLE3
77: \x94 MEMOIZE (as 8)
78: R REDUCE
79: \x94 MEMOIZE (as 9)
80: \x8c SHORT_BINUNICODE 'pad'
85: \x94 MEMOIZE (as 10)
86: h BINGET 4
88: J BININT -2
93: N NONE
94: N NONE
95: \x87 TUPLE3
96: \x94 MEMOIZE (as 11)
97: R REDUCE
98: \x94 MEMOIZE (as 12)
99: u SETITEMS (MARK at 13)
100: . STOP
highest protocol among opcodes = 4
@@ -1,133 +0,0 @@
0: \x80 PROTO 4
2: \x95 FRAME 320
11: } EMPTY_DICT
12: \x94 MEMOIZE (as 0)
13: ( MARK
14: \x8c SHORT_BINUNICODE 'meta'
20: \x94 MEMOIZE (as 1)
21: \x8c SHORT_BINUNICODE 'builtins'
31: \x94 MEMOIZE (as 2)
32: \x8c SHORT_BINUNICODE 'slice'
39: \x94 MEMOIZE (as 3)
40: \x93 STACK_GLOBAL
41: \x94 MEMOIZE (as 4)
42: K BININT1 0
44: K BININT1 55
46: N NONE
47: \x87 TUPLE3
48: \x94 MEMOIZE (as 5)
49: R REDUCE
50: \x94 MEMOIZE (as 6)
51: \x8c SHORT_BINUNICODE 'desire_pred'
64: \x94 MEMOIZE (as 7)
65: h BINGET 4
67: K BININT1 55
69: K BININT1 87
71: N NONE
72: \x87 TUPLE3
73: \x94 MEMOIZE (as 8)
74: R REDUCE
75: \x94 MEMOIZE (as 9)
76: \x8c SHORT_BINUNICODE 'pose'
82: \x94 MEMOIZE (as 10)
83: h BINGET 4
85: K BININT1 87
87: K BININT1 99
89: N NONE
90: \x87 TUPLE3
91: \x94 MEMOIZE (as 11)
92: R REDUCE
93: \x94 MEMOIZE (as 12)
94: \x8c SHORT_BINUNICODE 'wide_from_device_euler'
118: \x94 MEMOIZE (as 13)
119: h BINGET 4
121: K BININT1 99
123: K BININT1 105
125: N NONE
126: \x87 TUPLE3
127: \x94 MEMOIZE (as 14)
128: R REDUCE
129: \x94 MEMOIZE (as 15)
130: \x8c SHORT_BINUNICODE 'road_transform'
146: \x94 MEMOIZE (as 16)
147: h BINGET 4
149: K BININT1 105
151: K BININT1 117
153: N NONE
154: \x87 TUPLE3
155: \x94 MEMOIZE (as 17)
156: R REDUCE
157: \x94 MEMOIZE (as 18)
158: \x8c SHORT_BINUNICODE 'lane_lines'
170: \x94 MEMOIZE (as 19)
171: h BINGET 4
173: K BININT1 117
175: M BININT2 645
178: N NONE
179: \x87 TUPLE3
180: \x94 MEMOIZE (as 20)
181: R REDUCE
182: \x94 MEMOIZE (as 21)
183: \x8c SHORT_BINUNICODE 'lane_lines_prob'
200: \x94 MEMOIZE (as 22)
201: h BINGET 4
203: M BININT2 645
206: M BININT2 653
209: N NONE
210: \x87 TUPLE3
211: \x94 MEMOIZE (as 23)
212: R REDUCE
213: \x94 MEMOIZE (as 24)
214: \x8c SHORT_BINUNICODE 'road_edges'
226: \x94 MEMOIZE (as 25)
227: h BINGET 4
229: M BININT2 653
232: M BININT2 917
235: N NONE
236: \x87 TUPLE3
237: \x94 MEMOIZE (as 26)
238: R REDUCE
239: \x94 MEMOIZE (as 27)
240: \x8c SHORT_BINUNICODE 'lead'
246: \x94 MEMOIZE (as 28)
247: h BINGET 4
249: M BININT2 917
252: M BININT2 1061
255: N NONE
256: \x87 TUPLE3
257: \x94 MEMOIZE (as 29)
258: R REDUCE
259: \x94 MEMOIZE (as 30)
260: \x8c SHORT_BINUNICODE 'lead_prob'
271: \x94 MEMOIZE (as 31)
272: h BINGET 4
274: M BININT2 1061
277: M BININT2 1064
280: N NONE
281: \x87 TUPLE3
282: \x94 MEMOIZE (as 32)
283: R REDUCE
284: \x94 MEMOIZE (as 33)
285: \x8c SHORT_BINUNICODE 'hidden_state'
299: \x94 MEMOIZE (as 34)
300: h BINGET 4
302: M BININT2 1064
305: M BININT2 1576
308: N NONE
309: \x87 TUPLE3
310: \x94 MEMOIZE (as 35)
311: R REDUCE
312: \x94 MEMOIZE (as 36)
313: \x8c SHORT_BINUNICODE 'pad'
318: \x94 MEMOIZE (as 37)
319: h BINGET 4
321: K BININT1 0
323: N NONE
324: N NONE
325: \x87 TUPLE3
326: \x94 MEMOIZE (as 38)
327: R REDUCE
328: \x94 MEMOIZE (as 39)
329: u SETITEMS (MARK at 13)
330: . STOP
highest protocol among opcodes = 4
@@ -1,63 +0,0 @@
# Model Selector Version Compatibility
This document explains the version compatibility mechanism used by the Model Selector system, and the rationale behind certain version constraints and JSON file management strategies.
## Overview
The Model Selector is responsible for selecting and validating model bundles based on their metadata and version constraints. Each model bundle is distributed via a JSON file and includes a `minimumSelectorVersion` field indicating the minimum selector version required to load it.
To ensure robust compatibility and prevent mismatches between model expectations and selector capabilities, the selector enforces two version boundaries:
* **`REQUIRED_MIN_SELECTOR_VERSION`**: the oldest selector version we support.
* **`CURRENT_SELECTOR_VERSION`**: the current version of the selector logic.
## Version Compatibility Check
A model bundle is considered compatible if:
```python
REQUIRED_MIN_SELECTOR_VERSION <= bundle["minimumSelectorVersion"] <= CURRENT_SELECTOR_VERSION
```
This ensures:
* **Old bundles are rejected** if they rely on deprecated selector behavior.
* **Future bundles are ignored** if they expect logic that the current selector doesn't yet implement.
## Handling Breaking Changes
When a deep change in selector behavior requires *all* models to be recompiled (e.g., due to a major architectural update), we:
1. **Create a new JSON file** (e.g., from `models_v4.json` to `models_v5.json`).
2. **Assign updated `minimumSelectorVersion` values** in the new bundles.
This allows older selector versions to continue using the previous JSON file, while newer versions point to the new one, preventing cross-contamination.
## Why `REQUIRED_MIN_SELECTOR_VERSION` Still Matters
Despite using new JSON files to isolate breaking changes, `REQUIRED_MIN_SELECTOR_VERSION` plays a critical role:
### 1. **Cached Bundle Validation**
Model bundles are cached locally (e.g., in-memory or on disk). A user might have previously loaded a now-invalid bundle from an older JSON file.
`REQUIRED_MIN_SELECTOR_VERSION` prevents the selector from reloading or trusting that stale cached bundle, even if the original JSON is gone.
### 2. **Explicit Deprecation Boundary**
By raising `REQUIRED_MIN_SELECTOR_VERSION`, we declare older bundles officially unsupported, even if they technically still exist in a legacy JSON file.
### 3. **Avoiding Race Conditions**
Some clients may have intermittent access to updated JSONs. The runtime check ensures version compatibility is enforced independently of external file state.
## Summary
| Component | Purpose |
| ------------------------------- | --------------------------------------------------------------------- |
| `minimumSelectorVersion` | Declares the minimum selector version required to load a model bundle |
| `REQUIRED_MIN_SELECTOR_VERSION` | Prevents loading bundles that are too old (e.g., from stale cache) |
| `CURRENT_SELECTOR_VERSION` | Prevents loading bundles that are too new or forward-incompatible |
| JSON file renaming | Isolates bundles by selector generation to handle full recompiles |
This layered strategy ensures safe evolution of the model selection system while maintaining backward compatibility and runtime protection against stale or incompatible bundles.
@@ -1,274 +0,0 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import time
import os
import requests
from requests.exceptions import (SSLError, RequestException, HTTPError)
from openpilot.common.params import Params
from openpilot.common.swaglog import cloudlog
from openpilot.common.hardware.hw import Paths
from openpilot.sunnypilot.models.helpers import is_bundle_version_compatible
from openpilot.cereal import custom
class ModelParser:
"""Handles parsing of model data into cereal objects"""
@staticmethod
def _parse_download_uri(download_uri_data) -> custom.ModelManagerSP.DownloadUri:
download_uri = custom.ModelManagerSP.DownloadUri()
download_uri.uri = download_uri_data.get("url")
download_uri.sha256 = download_uri_data.get("sha256")
return download_uri
@staticmethod
def _parse_chunk(chunk_data) -> custom.ModelManagerSP.Chunk:
chunk = custom.ModelManagerSP.Chunk()
chunk.fileName = chunk_data.get("file_name")
chunk.sha256 = chunk_data.get("sha256")
return chunk
@staticmethod
def _parse_artifact(artifact_data) -> custom.ModelManagerSP.Artifact:
artifact = custom.ModelManagerSP.Artifact()
artifact.fileName = artifact_data.get("file_name")
artifact.downloadUri = ModelParser._parse_download_uri(artifact_data.get("download_uri", {}))
if "chunks" in artifact_data:
artifact.chunks = [ModelParser._parse_chunk(chunk_data) for chunk_data in artifact_data["chunks"]]
try:
model_dir = Paths.model_root()
os.makedirs(model_dir, exist_ok=True)
manifest_path = os.path.join(model_dir, f"{artifact.fileName}.chunkmanifest")
num_chunks = str(len(artifact.chunks))
if not os.path.exists(manifest_path) or open(manifest_path).read().strip() != num_chunks:
with open(manifest_path, "w") as f:
f.write(num_chunks)
cloudlog.info(f"Wrote chunk manifest for {artifact.fileName}: {num_chunks} chunks")
except Exception as e:
cloudlog.warning(f"Failed to write chunk manifest for {artifact.fileName}: {e}")
return artifact
@staticmethod
def _parse_model(model_data) -> custom.ModelManagerSP.Model:
model = custom.ModelManagerSP.Model()
model.type = model_data.get("type")
model.artifact = ModelParser._parse_artifact(model_data.get("artifact", {}))
return model
@staticmethod
def _parse_overrides(overrides_data: dict[str, str]) -> list[custom.ModelManagerSP.Override]:
overrides = []
for key, value in overrides_data.items():
override = custom.ModelManagerSP.Override()
override.key = key
override.value = value
overrides.append(override)
return overrides
@staticmethod
def _parse_bundle(bundle) -> custom.ModelManagerSP.ModelBundle:
model_bundle = custom.ModelManagerSP.ModelBundle()
model_bundle.index = int(bundle["index"])
model_bundle.internalName = bundle["short_name"]
model_bundle.displayName = bundle["display_name"]
model_bundle.models = [ModelParser._parse_model(model) for model in bundle.get("models",[])]
model_bundle.status = 0
model_bundle.generation = int(bundle["generation"])
model_bundle.environment = bundle["environment"]
model_bundle.runner = bundle.get("runner", custom.ModelManagerSP.Runner.snpe)
model_bundle.is20hz = bundle.get("is_20hz", False)
model_bundle.minimumSelectorVersion = int(bundle["minimum_selector_version"])
model_bundle.overrides = ModelParser._parse_overrides(bundle.get("overrides", {}))
model_bundle.ref = bundle.get("ref")
return model_bundle
@staticmethod
def parse_models(json_data: dict) -> list[custom.ModelManagerSP.ModelBundle]:
found_bundles = [ModelParser._parse_bundle(bundle) for bundle in json_data.get("bundles", [])]
return [bundle for bundle in found_bundles if is_bundle_version_compatible(bundle.to_dict())]
class ModelCache:
"""Handles caching of model data to avoid frequent remote fetches"""
def __init__(self, params: Params, cache_timeout: int = int(3600 * 1e9), suffix: str = ""):
self.params = params
self.cache_timeout = cache_timeout
self._LAST_SYNC_KEY = f"ModelManager_LastSyncTime{suffix}"
self._CACHE_KEY = f"ModelManager_ModelsCache{suffix}"
def _is_expired(self) -> bool:
"""Checks if the cache has expired"""
current_time = int(time.monotonic() * 1e9)
last_sync = self.params.get(self._LAST_SYNC_KEY) or 0
return bool(last_sync == 0) or (current_time - last_sync) >= self.cache_timeout
def get(self) -> tuple[dict, bool]:
"""
Retrieves cached model data and expiration status atomically.
Returns: Tuple of (cached_data, is_expired)
If no cached data exists or on error, returns an empty dict
"""
try:
cached_data = self.params.get(self._CACHE_KEY)
if not cached_data:
cloudlog.warning("No cached model data available")
return {}, True
return cached_data, self._is_expired()
except Exception as e:
cloudlog.exception(f"Error retrieving cached model data: {str(e)}")
return {}, True
def set(self, data: dict) -> None:
"""Updates the cache with new model data"""
self.params.put(self._CACHE_KEY, data, block=True)
self.params.put(self._LAST_SYNC_KEY, int(time.monotonic() * 1e9), block=True)
class ModelFetcher:
"""Handles fetching and caching of model data from remote source"""
MODEL_URL = "https://raw.githubusercontent.com/sunnypilot/sunnypilot-models/refs/heads/gh-pages/docs/driving_models_v22.json"
MODEL_URL_CHESTNUT = "https://raw.githubusercontent.com/sunnypilot/sunnypilot-models/refs/heads/gh-pages/docs/driving_models_chestnut_v25.json"
MODEL_SOURCES = {
"qcom": (MODEL_URL, ""),
"chestnut": (MODEL_URL_CHESTNUT, "_Chestnut"),
}
def __init__(self, params: Params):
self.params = params
self.model_parser = ModelParser()
self.model_caches = {
source: ModelCache(params, suffix=suffix)
for source, (_, suffix) in self.MODEL_SOURCES.items()
}
self._refetched: set[str] = set()
self.params.put("ModelManager_ActiveJson", {
"qcom": self.MODEL_URL,
"chestnut": self.MODEL_URL_CHESTNUT,
}, block=True)
@staticmethod
def active_source(chestnut_present: bool) -> str:
return "chestnut" if chestnut_present else "qcom"
def _fetch_and_cache_models(self, source: str) -> list[custom.ModelManagerSP.ModelBundle] | None:
"""Fetches fresh model data from remote and updates cache.
Returns None on transport errors. Raises on 404 and other fatal HTTP errors.
"""
model_url, _ = self.MODEL_SOURCES[source]
try:
response = requests.get(model_url, timeout=10)
# Explicitly handle 404 differently
if response.status_code == 404:
cloudlog.error(f"Models URL returned 404 Not Found: {model_url}")
raise HTTPError(f"404 Not Found: {model_url}", response=response)
# Raise for any other 4xx/5xx
response.raise_for_status()
json_data = response.json()
parsed = self.model_parser.parse_models(json_data)
if parsed:
self.model_caches[source].set(json_data)
cloudlog.debug(f"Successfully updated models cache for {source}")
return parsed
except ConnectionError as e:
cloudlog.warning(f"DNS/connection error while fetching models: {e}")
except SSLError as e:
cloudlog.warning(f"SSL error while fetching models: {e}")
except RequestException as e:
cloudlog.warning(f"Request transport error while fetching models: {e}")
except Exception as e:
cloudlog.exception(f"Unexpected error fetching models: {e}")
return None
@staticmethod
def _cache_matches_source(source: str, cached_data: dict) -> bool:
bundles = cached_data.get("bundles", [])
if source == "chestnut":
return any(bundle.get("is_big") is True for bundle in bundles)
return not any(bundle.get("is_big") is True for bundle in bundles)
def get_bundles_for_source(self, source: str) -> list[custom.ModelManagerSP.ModelBundle]:
if source not in self.MODEL_SOURCES:
cloudlog.warning(f"Unknown model source: {source}")
return []
cached_data, is_expired = self.model_caches[source].get()
if cached_data and not is_expired:
# a source is refetched over a mismatch at most once per process: if the fresh
# manifest still mismatches, the URL is authoritative and the cache is trusted
if self._cache_matches_source(source, cached_data) or source in self._refetched:
try:
parsed = self.model_parser.parse_models(cached_data)
except Exception:
cloudlog.warning(f"Failed to parse cached models for {source}; refetching", exc_info=True)
else:
if parsed:
cloudlog.debug(f"Using valid cached models data for source {source}")
return parsed
# a source-matching cache that yields no valid bundles is stale (e.g. an old
# manifest version) - do not trust it, refetch so the source is repopulated
cloudlog.warning(f"Cached models for {source} have no valid bundles; refetching")
else:
self._refetched.add(source)
cloudlog.warning(f"Cached models for {source} not valid; refetching once")
fetched_bundles = self._fetch_and_cache_models(source)
if fetched_bundles is not None:
return fetched_bundles
if not cached_data:
cloudlog.warning("Failed to fetch fresh data and no cache available")
cloudlog.warning("Failed to fetch fresh data. Using expired cache as fallback")
try:
return self.model_parser.parse_models(cached_data)
except Exception:
return []
def get_cached_bundles(params: Params, source: str) -> list[custom.ModelManagerSP.ModelBundle]:
if source not in ModelFetcher.MODEL_SOURCES:
cloudlog.warning(f"Unknown model source: {source}")
return []
_, suffix = ModelFetcher.MODEL_SOURCES[source]
cached_data = params.get(f"ModelManager_ModelsCache{suffix}")
if not cached_data:
return []
try:
return ModelParser.parse_models(cached_data)
except Exception as e:
cloudlog.warning(f"Failed to parse cached models for source {source}: {e}")
return []
if __name__ == "__main__":
from openpilot.selfdrive.modeld.helpers import chestnut_present
params = Params()
model_fetcher = ModelFetcher(params)
bundles = model_fetcher.get_bundles_for_source(ModelFetcher.active_source(chestnut_present()))
for bundle in bundles:
for model in bundle.models:
model_overrides = {override.key: override.value for override in bundle.overrides}
print(f"Bundle: {bundle.internalName}, Type: {model.type}, Status: {bundle.status}, Overrides: {model_overrides}")
print(f"Artifact: {model.artifact.fileName}, Download URI: {model.artifact.downloadUri.uri}")
if model.artifact.chunks:
print(f"Contains {len(model.artifact.chunks)} chunks.")
@@ -1,221 +0,0 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import hashlib
import os
import numpy as np
from openpilot.cereal import custom
from openpilot.common.params import Params
from openpilot.common.swaglog import cloudlog
from openpilot.common.hardware.hw import Paths
from openpilot.selfdrive.modeld.helpers import chestnut_present
# SET ME TO THE EXACT JSON VERSION WE SET IN SUNNYPILOT_MODELS REPO
REQUIRED_JSON_VERSION = 19
CUSTOM_MODEL_PATH = Paths.model_root()
ModelManager = custom.ModelManagerSP
ACTIVE_BUNDLE_KEYS = {
"qcom": "ModelManager_ActiveBundle",
"chestnut": "ModelManager_ActiveBundleChestnut",
}
_LAST_VALIDATED_RAW: dict[str, dict | None] = {}
def _compute_hash(file_path: str) -> str | None:
from openpilot.common.file_chunker import open_file_chunked
try:
with open_file_chunked(file_path) as file:
return hashlib.file_digest(file, "sha256").hexdigest().lower()
except FileNotFoundError:
return None
async def verify_file(file_path: str, expected_hash: str) -> bool:
file_hash = _compute_hash(file_path)
return file_hash == expected_hash.lower() if file_hash else False
def _verify_file(file_path: str, expected_hash: str) -> bool:
file_hash = _compute_hash(file_path)
return file_hash == expected_hash.lower() if file_hash else False
def is_bundle_version_compatible(bundle: dict) -> bool:
"""
The bundle parsed from the json specifies a `minimum_selector_version`, which defines the minimum selector version
required to load the model. This function ensures that:
the bundle MUST match the `REQUIRED_JSON_VERSION` set here in helpers.
"""
return bundle.get("minimumSelectorVersion", 0) == REQUIRED_JSON_VERSION
def _bundle_artifacts(bundle: custom.ModelManagerSP.ModelBundle) -> list[tuple[str, str]]:
artifacts = []
from openpilot.common.file_chunker import get_chunk_name
for model in getattr(bundle, 'models', []) or []:
for artifact in (getattr(model, 'artifact', None),):
if artifact and getattr(artifact, 'fileName', None):
if len(artifact.chunks) > 0:
for i, chunk in enumerate(artifact.chunks):
chunk_name = get_chunk_name(artifact.fileName, i, len(artifact.chunks))
if getattr(chunk, 'sha256', None):
artifacts.append((chunk_name, chunk.sha256))
else:
if getattr(artifact, 'downloadUri', None):
sha256 = getattr(artifact.downloadUri, 'sha256', None)
if sha256:
artifacts.append((artifact.fileName, sha256))
return artifacts
def _bundle_is_valid_locally(bundle: custom.ModelManagerSP.ModelBundle) -> bool:
model_root = Paths.model_root()
return all(_verify_file(os.path.join(model_root, file_name), expected_hash)
for file_name, expected_hash in _bundle_artifacts(bundle))
def _bundle_needs_reset(active_bundle: custom.ModelManagerSP.ModelBundle, available_bundles: list[custom.ModelManagerSP.ModelBundle] | None) -> bool:
if active_bundle is None:
return False
if available_bundles is not None:
matching_bundle = None
for bundle in available_bundles:
if active_bundle.ref and bundle.ref:
if active_bundle.ref == bundle.ref:
matching_bundle = bundle
break
elif active_bundle.internalName == bundle.internalName:
matching_bundle = bundle
break
if matching_bundle is None:
return True
if active_bundle.minimumSelectorVersion != matching_bundle.minimumSelectorVersion:
return True
if active_bundle.runner != matching_bundle.runner:
return True
if set(_bundle_artifacts(active_bundle)) != set(_bundle_artifacts(matching_bundle)):
return True
return not _bundle_is_valid_locally(active_bundle)
def _parse_active_bundle(raw_bundle) -> "custom.ModelManagerSP.ModelBundle | None":
try:
if isinstance(raw_bundle, dict) and raw_bundle and is_bundle_version_compatible(raw_bundle):
return custom.ModelManagerSP.ModelBundle(**raw_bundle)
except Exception:
pass
return None
def get_selected_bundle(params: Params | None = None, source: str = "qcom") -> "custom.ModelManagerSP.ModelBundle | None":
params = params or Params()
return _parse_active_bundle(params.get(ACTIVE_BUNDLE_KEYS[source]))
def get_active_source(chestnut: bool | None = None, chestnut_active: bool | None = None,
chestnut_loading: bool | None = None, offroad: bool | None = None) -> str:
if chestnut is None:
chestnut = chestnut_present()
state_valid = chestnut_active is not None or chestnut_loading is not None or offroad is not None
big_active = chestnut and (not state_valid or chestnut_active or chestnut_loading or offroad)
return "chestnut" if big_active else "qcom"
def get_active_bundle(params: Params | None = None, *, chestnut: bool | None = None) -> "custom.ModelManagerSP.ModelBundle | None":
# no cross-slot fallback: an empty active slot means the hardware default, which
# only stock modeld can run - modeld_v2 requires a real bundle
params = params or Params()
return get_selected_bundle(params, get_active_source(chestnut=chestnut))
def resolve_bundle_by_ref(
ref: str, source_bundles: dict[str, list[custom.ModelManagerSP.ModelBundle]],
) -> "tuple[custom.ModelManagerSP.ModelBundle, str] | None":
for source, bundles in source_bundles.items():
for bundle in bundles:
if bundle.ref == ref:
return bundle, source
return None
def _validate_active_bundle(params: Params, source: str, available_bundles: list[custom.ModelManagerSP.ModelBundle] | None = None) -> None:
global _LAST_VALIDATED_RAW
key = ACTIVE_BUNDLE_KEYS[source]
raw_bundle = params.get(key)
if not raw_bundle:
return
if _LAST_VALIDATED_RAW.get(key) == raw_bundle:
return
active_bundle = _parse_active_bundle(raw_bundle)
if active_bundle is None or _bundle_needs_reset(active_bundle, available_bundles):
cloudlog.warning(f"Active model bundle invalid for {source}; resetting to default")
params.remove(key)
_LAST_VALIDATED_RAW[key] = None
else:
_LAST_VALIDATED_RAW[key] = raw_bundle
def validate_active_bundles(params: Params, source_bundles: dict[str, list[custom.ModelManagerSP.ModelBundle]]) -> None:
# an empty list means the fetch failed, not that the catalog dropped the bundle
for source, bundles in source_bundles.items():
_validate_active_bundle(params, source, bundles or None)
get_active_model_runner(params, force_check=True)
def get_active_model_runner(params: Params | None = None, force_check: bool = False) -> int:
params = params or Params()
cached_runner_type = params.get("ModelRunnerTypeCache")
if cached_runner_type is not None and not force_check:
return cached_runner_type
runner_type = custom.ModelManagerSP.Runner.stock
if active_bundle := get_active_bundle(params):
runner_type = active_bundle.runner.raw
if cached_runner_type != runner_type:
params.put("ModelRunnerTypeCache", int(runner_type), block=True)
return runner_type
def _get_model():
if bundle := get_active_bundle():
drive_model = next(model for model in bundle.models if model.type == ModelManager.Model.Type.supercombo)
return drive_model
return None
# The following method(s) are modeld helper methods
def plan_x_idxs_helper(constants, plan, model_output) -> list[float]:
# times at X_IDXS according to plan.
LINE_T_IDXS = [np.nan] * constants.IDX_N
LINE_T_IDXS[0] = 0.0
plan_x = model_output['plan'][0, :, plan.POSITION][:, 0].tolist()
for xidx in range(1, constants.IDX_N):
tidx = 0
# increment tidx until we find an element that's further away than the current xidx
while tidx < constants.IDX_N - 1 and plan_x[tidx + 1] < constants.X_IDXS[xidx]:
tidx += 1
if tidx == constants.IDX_N - 1:
# if the plan doesn't extend far enough, set plan_t to the max value (10s), then break
LINE_T_IDXS[xidx] = constants.T_IDXS[constants.IDX_N - 1]
break
# interpolate to find `t` for the current xidx
current_x_val = plan_x[tidx]
next_x_val = plan_x[tidx + 1]
p = (constants.X_IDXS[xidx] - current_x_val) / (next_x_val - current_x_val) if abs(
next_x_val - current_x_val) > 1e-9 else float('nan')
LINE_T_IDXS[xidx] = p * constants.T_IDXS[tidx + 1] + (1 - p) * constants.T_IDXS[tidx]
return LINE_T_IDXS
@@ -1,382 +0,0 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import asyncio
import os
import time
import requests
from openpilot.common.params import Params
from openpilot.common.realtime import Ratekeeper
from openpilot.common.swaglog import cloudlog
from openpilot.common.hardware.hw import Paths
from openpilot.cereal import messaging, custom
from openpilot.sunnypilot.models.fetcher import ModelFetcher
from openpilot.sunnypilot.models.helpers import (ACTIVE_BUNDLE_KEYS, get_active_bundle, get_selected_bundle,
resolve_bundle_by_ref, validate_active_bundles, verify_file)
# (connect, read) seconds. read is per-request inactivity, not a total cap
DOWNLOAD_TIMEOUT = (30, 30)
class DownloadCancelled(Exception):
pass
class ModelManagerSP:
"""Manages model downloads and status reporting"""
def __init__(self):
self.params = Params()
self.model_fetcher = ModelFetcher(self.params)
self.pm = messaging.PubMaster(["modelManagerSP"])
self.sm = messaging.SubMaster(["deviceState"])
self.chestnut_present = False
self.available_models: list[custom.ModelManagerSP.ModelBundle] = []
self.source_models: dict[str, list[custom.ModelManagerSP.ModelBundle]] = {}
self.selected_bundle: custom.ModelManagerSP.ModelBundle = None
self.active_bundle: custom.ModelManagerSP.ModelBundle = get_active_bundle(self.params, chestnut=self.chestnut_present)
self._chunk_size = 128 * 1000 # 128 KB chunks
self._download_start_times: dict[str, float] = {} # Track start time per model
self._download_ref: bytes | str | None = None
def _download_interrupted(self) -> bool:
# only removal cancels: a different ref is a queued selection that
# _release_download_ref leaves in place for the next tick
return self.params.get("ModelManager_DownloadRef") is None
def _release_download_ref(self) -> None:
if self.params.get("ModelManager_DownloadRef") == self._download_ref:
self.params.remove("ModelManager_DownloadRef")
self._download_ref = None
def _sync_artifact_progress(self, source_artifact) -> None:
"""Mirror download progress to all artifacts sharing the same filename in the selected bundle."""
if not self.selected_bundle:
return
for model in self.selected_bundle.models:
artifact = model.artifact
if artifact is not source_artifact and artifact.fileName == source_artifact.fileName:
artifact.downloadProgress.status = source_artifact.downloadProgress.status
artifact.downloadProgress.progress = source_artifact.downloadProgress.progress
artifact.downloadProgress.eta = source_artifact.downloadProgress.eta
def _calculate_eta(self, filename: str, progress: float) -> int:
"""Calculate ETA based on elapsed time and current progress"""
if filename not in self._download_start_times or progress <= 0:
return 60 # Default ETA for new downloads
elapsed_time = time.monotonic() - self._download_start_times[filename]
if elapsed_time <= 0:
return 60
# If we're at X% after Y seconds, we can estimate total time as (Y / X) * 100
total_estimated_time = (elapsed_time / progress) * 100
eta = total_estimated_time - elapsed_time
return max(1, int(eta)) # Return at least 1 second if download is ongoing
async def _download_file(self, url: str, path: str, model) -> None:
"""Downloads a file with progress tracking"""
self._download_start_times[model.fileName] = time.monotonic()
with requests.get(url, stream=True, timeout=DOWNLOAD_TIMEOUT) as response: # noqa: ASYNC210
response.raise_for_status()
total_size = int(response.headers.get("content-length", 0))
bytes_downloaded = 0
with open(path, 'wb') as f: # noqa: ASYNC230
for chunk in response.iter_content(chunk_size=self._chunk_size): # type: bytes
f.write(chunk)
bytes_downloaded += len(chunk)
if self._download_interrupted():
raise DownloadCancelled("Download cancelled")
if total_size > 0:
progress = (bytes_downloaded / total_size) * 100
model.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.downloading
model.downloadProgress.progress = progress
model.downloadProgress.eta = self._calculate_eta(model.fileName, progress)
self._sync_artifact_progress(model)
self._report_status()
# Clean up start time after download completes
del self._download_start_times[model.fileName]
async def _download_chunked(self, base_url: str, base_path: str, artifact, skip: frozenset[int] | set[int] = frozenset()) -> None:
from openpilot.common.file_chunker import get_chunk_name, get_manifest_path
num_chunks = len(artifact.chunks)
if num_chunks == 0:
raise ValueError("No chunks defined in artifact")
manifest_path = get_manifest_path(base_path)
self._download_start_times[artifact.fileName] = time.monotonic()
# Shared connection saves a TCP+TLS handshake per chunk.
# Keep sequential: the link saturates on one stream and Session is not thread-safe.
completed = len(skip)
with requests.Session() as session:
for i, _ in enumerate(artifact.chunks):
if i in skip:
continue
chunk_url = get_chunk_name(base_url, i, num_chunks)
chunk_path = get_chunk_name(base_path, i, num_chunks)
chunk_downloaded = 0
with session.get(chunk_url, stream=True, timeout=DOWNLOAD_TIMEOUT) as response:
response.raise_for_status()
chunk_size = int(response.headers.get("content-length", 0))
with open(chunk_path, 'wb') as f: # noqa: ASYNC230
for data in response.iter_content(chunk_size=self._chunk_size):
f.write(data)
chunk_downloaded += len(data)
if self._download_interrupted():
raise DownloadCancelled("Download cancelled")
intra = chunk_downloaded / max(chunk_size, 1)
progress = min(99.0, ((completed + intra) / num_chunks) * 100)
artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.downloading
artifact.downloadProgress.progress = progress
artifact.downloadProgress.eta = self._calculate_eta(artifact.fileName, progress)
self._sync_artifact_progress(artifact)
self._report_status()
completed += 1
with open(manifest_path, 'w') as f: # noqa: ASYNC230
f.write(str(num_chunks))
if os.path.isfile(base_path): # noqa: ASYNC240
os.remove(base_path)
del self._download_start_times[artifact.fileName]
async def _process_artifact(self, artifact, destination_path: str) -> None:
if not artifact.downloadUri.uri:
return None
if self._download_interrupted():
raise DownloadCancelled("Download cancelled")
url = artifact.downloadUri.uri
expected_hash = artifact.downloadUri.sha256
filename = artifact.fileName
full_path = os.path.join(destination_path, filename)
try:
# progress counts only valid chunks so a resumed download continues the
# bar from where verification left it, instead of falling back to zero
is_cached = False
valid_chunks: set[int] = set()
if len(artifact.chunks) > 0:
from openpilot.common.file_chunker import get_chunk_name
num_chunks = len(artifact.chunks)
for i, chunk in enumerate(artifact.chunks):
if self._download_interrupted():
raise DownloadCancelled("Download cancelled")
if await verify_file(get_chunk_name(full_path, i, num_chunks), chunk.sha256):
valid_chunks.add(i)
artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.verifying
artifact.downloadProgress.progress = (len(valid_chunks) / num_chunks) * 100
self._sync_artifact_progress(artifact)
self._report_status()
is_cached = len(valid_chunks) == num_chunks
else:
if await verify_file(full_path, expected_hash):
is_cached = True
if is_cached:
artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.cached
artifact.downloadProgress.progress = 100
artifact.downloadProgress.eta = 0
self._sync_artifact_progress(artifact)
self._report_status()
return
if len(artifact.chunks) > 0:
await self._download_chunked(url, full_path, artifact, skip=valid_chunks)
from openpilot.common.file_chunker import get_chunk_name
for i, chunk in enumerate(artifact.chunks):
chunk_path = get_chunk_name(full_path, i, len(artifact.chunks))
if not await verify_file(chunk_path, chunk.sha256):
raise ValueError(f"Hash validation failed for chunk {i+1} of {filename}")
else:
await self._download_file(url, full_path, artifact)
if not await verify_file(full_path, expected_hash):
raise ValueError(f"Hash validation failed for {filename}")
artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.downloaded
artifact.downloadProgress.progress = 100
artifact.downloadProgress.eta = 0
self._sync_artifact_progress(artifact)
self._report_status()
except DownloadCancelled:
# a cancel keeps whatever is on disk: complete chunks resume the next attempt
self._download_start_times.pop(artifact.fileName, None)
artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.failed
artifact.downloadProgress.eta = 0
self._sync_artifact_progress(artifact)
if self.selected_bundle:
self.selected_bundle.status = custom.ModelManagerSP.DownloadStatus.failed
self._report_status()
raise
except Exception as e:
cloudlog.error(f"Error downloading {filename}: {str(e)}")
for f in [full_path] + [p for p in (os.path.join(destination_path, f) for f in os.listdir(destination_path)) if filename in p]:
if os.path.isfile(f): # noqa: ASYNC240
os.remove(f)
artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.failed
artifact.downloadProgress.eta = 0
self._sync_artifact_progress(artifact)
if self.selected_bundle:
self.selected_bundle.status = custom.ModelManagerSP.DownloadStatus.failed
self._report_status()
self._download_start_times.pop(artifact.fileName, None)
raise
async def _process_model(self, model, destination_path: str) -> None:
"""Processes a single model download including verification"""
await self._process_artifact(model.artifact, destination_path)
def _report_status(self) -> None:
"""Reports current status through messaging system"""
msg = messaging.new_message('modelManagerSP', valid=True)
model_manager_state = msg.modelManagerSP
if self.selected_bundle:
model_manager_state.selectedBundle = self.selected_bundle
if self.active_bundle:
model_manager_state.activeBundle = self.active_bundle
model_manager_state.availableBundles = self.available_models
self.pm.send('modelManagerSP', msg)
async def _download_bundle(self, model_bundle: custom.ModelManagerSP.ModelBundle, destination_path: str, source: str) -> None:
self.selected_bundle = model_bundle
self.selected_bundle.status = custom.ModelManagerSP.DownloadStatus.downloading
for model in self.selected_bundle.models:
model.artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.downloading
self._report_status()
os.makedirs(destination_path, exist_ok=True)
try:
seen_artifacts: set[str] = set()
for model in self.selected_bundle.models:
artifact = model.artifact
if not artifact.fileName:
continue
if artifact.fileName in seen_artifacts:
artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.cached
artifact.downloadProgress.progress = 100
artifact.downloadProgress.eta = 0
else:
seen_artifacts.add(artifact.fileName)
await self._process_artifact(artifact, destination_path)
if self._download_interrupted():
raise DownloadCancelled("Download cancelled")
self.selected_bundle.status = custom.ModelManagerSP.DownloadStatus.downloaded
self.params.put(ACTIVE_BUNDLE_KEYS[source], model_bundle.to_dict(), block=True)
self.active_bundle = get_active_bundle(self.params, chestnut=self.chestnut_present)
except Exception:
if self.selected_bundle is not None:
self.selected_bundle.status = custom.ModelManagerSP.DownloadStatus.failed
raise
finally:
self._report_status()
def download(self, model_bundle: custom.ModelManagerSP.ModelBundle, destination_path: str, source: str) -> None:
"""Main entry point for downloading a model bundle"""
asyncio.run(self._download_bundle(model_bundle, destination_path, source))
def _process_download_requests(self) -> None:
# loops so a ref queued during a download starts in the same tick, without
# the bar dropping to idle for a tick between the two transfers
last_ref = None
while (ref_to_download := self.params.get("ModelManager_DownloadRef")) is not None:
if ref_to_download == last_ref: # a repeating ref falls back to the next tick instead of spinning
return
last_ref = ref_to_download
resolved = resolve_bundle_by_ref(ref_to_download, self.source_models)
if not resolved:
return
model_to_download, source = resolved
self._download_ref = ref_to_download
try:
self.download(model_to_download, Paths.model_root(), source)
except Exception as e:
cloudlog.exception(e)
finally:
self._release_download_ref()
self.selected_bundle = None
def main_thread(self) -> None:
"""Main thread for model management"""
rk = Ratekeeper(1, print_delay_threshold=None)
while True:
try:
self.sm.update(0)
self.chestnut_present = self.sm['deviceState'].chestnutPresent
self.source_models = {source: self.model_fetcher.get_bundles_for_source(source) for source in ModelFetcher.MODEL_SOURCES}
self.available_models = self.source_models[ModelFetcher.active_source(self.chestnut_present)]
validate_active_bundles(self.params, self.source_models)
self.active_bundle = get_active_bundle(self.params, chestnut=self.chestnut_present)
if get_selected_bundle(self.params, "chestnut") is not None and get_selected_bundle(self.params, "qcom") is None:
if self.params.get("ModelManager_DownloadRef") is None:
from openpilot.sunnypilot.models.model_name import DEFAULT_MODEL_REF
if DEFAULT_MODEL_REF:
self.params.put("ModelManager_DownloadRef", DEFAULT_MODEL_REF)
self._process_download_requests()
if self.params.get("ModelManager_ClearCache"):
self.clear_model_cache()
self.params.remove("ModelManager_ClearCache")
self._report_status()
rk.keep_time()
except Exception as e:
cloudlog.exception(f"Error in main thread: {str(e)}")
rk.keep_time()
def clear_model_cache(self) -> None:
"""
Clears the model cache directory of all files except those in the active model bundle.
"""
# Get list of files used by both slots' selected bundles (either may become
# the truly active bundle depending on hardware availability)
active_files = []
for source in ACTIVE_BUNDLE_KEYS:
if selected_bundle := get_selected_bundle(self.params, source):
for model in selected_bundle.models:
if model.artifact.fileName:
active_files.append(model.artifact.fileName)
# Remove all files except active ones (including their chunk files)
model_dir = Paths.model_root()
try:
for filename in os.listdir(model_dir):
base = filename.split('.chunk')[0] if '.chunk' in filename else filename
if base not in active_files and filename not in active_files:
file_path = os.path.join(model_dir, filename)
if os.path.isfile(file_path):
os.remove(file_path)
cloudlog.info("Model cache cleared, keeping active model files")
except Exception as e:
cloudlog.exception(f"Error clearing model cache: {str(e)}")
def main():
ModelManagerSP().main_thread()
if __name__ == "__main__":
main()
@@ -1,4 +0,0 @@
DEFAULT_MODEL = "CD210"
DEFAULT_MODEL_REF = "5b6436a90cf6902b8aaa71c2b6f3d7164d8ae391"
DEFAULT_BIG_MODEL = "BMRLNAP Model v4"
DEFAULT_BIG_MODEL_REF = "f877d7a0ccc3cce943c76e285214c020cd65c899"
@@ -1,15 +0,0 @@
import os
import numpy as np
from openpilot.common.hardware.hw import Paths
from openpilot.cereal import custom
# Type definitions for clarity
NumpyDict = dict[str, np.ndarray]
ShapeDict = dict[str, tuple[int, ...]]
SliceDict = dict[str, slice]
ModelType = custom.ModelManagerSP.Model.Type
Model = custom.ModelManagerSP.Model
SEND_RAW_PRED = os.getenv('SEND_RAW_PRED')
CUSTOM_MODEL_PATH = Paths.model_root()
@@ -1,95 +0,0 @@
import numpy as np
def index_function(idx, max_val=192, max_idx=32):
return max_val * ((idx/max_idx)**2)
class SplitModelConstants:
# time and distance indices
IDX_N = 33
T_IDXS = [index_function(idx, max_val=10.0) for idx in range(IDX_N)]
X_IDXS = [index_function(idx, max_val=192.0) for idx in range(IDX_N)]
LEAD_T_IDXS = [0., 2., 4., 6., 8., 10.]
LEAD_T_OFFSETS = [0., 2., 4.]
META_T_IDXS = [2., 4., 6., 8., 10.]
# model inputs constants
MODEL_FREQ = 20
HISTORY_FREQ = 5
HISTORY_LEN_SECONDS = 5
TEMPORAL_SKIP = MODEL_FREQ // HISTORY_FREQ
FULL_HISTORY_BUFFER_LEN = MODEL_FREQ * HISTORY_LEN_SECONDS
INPUT_HISTORY_BUFFER_LEN = HISTORY_FREQ * HISTORY_LEN_SECONDS
FEATURE_LEN = 512
DESIRE_LEN = 8
TRAFFIC_CONVENTION_LEN = 2
LAT_PLANNER_STATE_LEN = 4
LATERAL_CONTROL_PARAMS_LEN = 2
PREV_DESIRED_CURV_LEN = 1
# model outputs constants
FCW_THRESHOLDS_5MS2 = np.array([.05, .05, .15, .15, .15], dtype=np.float32)
FCW_THRESHOLDS_3MS2 = np.array([.7, .7], dtype=np.float32)
FCW_5MS2_PROBS_WIDTH = 5
FCW_3MS2_PROBS_WIDTH = 2
DISENGAGE_WIDTH = 5
POSE_WIDTH = 6
WIDE_FROM_DEVICE_WIDTH = 3
LEAD_WIDTH = 4
LANE_LINES_WIDTH = 2
ROAD_EDGES_WIDTH = 2
PLAN_WIDTH = 15
ACTION_WIDTH = 2
DESIRE_PRED_WIDTH = 8
LAT_PLANNER_SOLUTION_WIDTH = 4
DESIRED_CURV_WIDTH = 1
NUM_LANE_LINES = 4
NUM_ROAD_EDGES = 2
LEAD_TRAJ_LEN = 6
DESIRE_PRED_LEN = 4
PLAN_MHP_N = 5
LEAD_MHP_N = 2
PLAN_MHP_SELECTION = 1
LEAD_MHP_SELECTION = 3
FCW_THRESHOLD_5MS2_HIGH = 0.15
FCW_THRESHOLD_5MS2_LOW = 0.05
FCW_THRESHOLD_3MS2 = 0.7
CONFIDENCE_BUFFER_LEN = 5
RYG_GREEN = 0.01165
RYG_YELLOW = 0.06157
POLY_PATH_DEGREE = 4
# model outputs slices
class Plan:
POSITION = slice(0, 3)
VELOCITY = slice(3, 6)
ACCELERATION = slice(6, 9)
T_FROM_CURRENT_EULER = slice(9, 12)
ORIENTATION_RATE = slice(12, 15)
class Meta:
ENGAGED = slice(0, 1)
# next 2, 4, 6, 8, 10 seconds
GAS_DISENGAGE = slice(1, 31, 6)
BRAKE_DISENGAGE = slice(2, 31, 6)
STEER_OVERRIDE = slice(3, 31, 6)
HARD_BRAKE_3 = slice(4, 31, 6)
HARD_BRAKE_4 = slice(5, 31, 6)
HARD_BRAKE_5 = slice(6, 31, 6)
# next 0, 2, 4, 6, 8, 10 seconds
GAS_PRESS = slice(31, 55, 4)
BRAKE_PRESS = slice(32, 55, 4)
LEFT_BLINKER = slice(33, 55, 4)
RIGHT_BLINKER = slice(34, 55, 4)
-92
View File
@@ -1,92 +0,0 @@
{
"driving_vision.onnx": {
"inputs": [
{
"name": "img",
"shape": [
1,
12,
128,
256
],
"type": "tensor(uint8)"
},
{
"name": "big_img",
"shape": [
1,
12,
128,
256
],
"type": "tensor(uint8)"
}
],
"outputs": [
{
"name": "outputs",
"shape": [
1,
1576
],
"type": "tensor(float16)"
}
],
"metadata": {
"output_slices": "gASVQAEAAAAAAAB9lCiMBG1ldGGUjAhidWlsdGluc5SMBXNsaWNllJOUSwBLN06HlFKUjAtkZXNp\ncmVfcHJlZJRoBEs3S1dOh5RSlIwEcG9zZZRoBEtXS2NOh5RSlIwWd2lkZV9mcm9tX2RldmljZV9l\ndWxlcpRoBEtjS2lOh5RSlIwOcm9hZF90cmFuc2Zvcm2UaARLaUt1ToeUUpSMCmxhbmVfbGluZXOU\naARLdU2FAk6HlFKUjA9sYW5lX2xpbmVzX3Byb2KUaARNhQJNjQJOh5RSlIwKcm9hZF9lZGdlc5Ro\nBE2NAk2VA06HlFKUjARsZWFklGgETZUDTSUEToeUUpSMCWxlYWRfcHJvYpRoBE0lBE0oBE6HlFKU\njAxoaWRkZW5fc3RhdGWUaARNKARNKAZOh5RSlIwDcGFklGgESwBOToeUUpR1Lg==\n",
"model_checkpoint": "6a7d09ad-bcc9-43bc-916d-29287e60cee2/200"
},
"provider": [
"CPUExecutionProvider"
],
"producer": "pytorch"
},
"driving_policy.onnx": {
"inputs": [
{
"name": "desire_pulse",
"shape": [
1,
25,
8
],
"type": "tensor(float16)"
},
{
"name": "traffic_convention",
"shape": [
1,
2
],
"type": "tensor(float16)"
},
{
"name": "features_buffer",
"shape": [
1,
25,
512
],
"type": "tensor(float16)"
}
],
"outputs": [
{
"name": "outputs",
"shape": [
1,
1000
],
"type": "tensor(float16)"
}
],
"metadata": {
"output_slices": "gASVWgAAAAAAAAB9lCiMBHBsYW6UjAhidWlsdGluc5SMBXNsaWNllJOUSwBN3gNOh5RSlIwMZGVz\naXJlX3N0YXRllGgETd4DTeYDToeUUpSMA3BhZJRoBEr+////Tk6HlFKUdS4=\n",
"model_checkpoint": "05a58a51-e0e3-4e9b-8e27-e644685f2c50/100"
},
"provider": [
"CPUExecutionProvider"
],
"producer": "pytorch"
}
}
-20
View File
@@ -1,20 +0,0 @@
[
{
"id": "supercombo-6409",
"label": "Supercombo 6409 (current calibration)",
"file": "supercombo.onnx",
"manifest": "manifest.json"
},
{
"id": "pop-v2",
"label": "Pop v2 (experimental preview)",
"file": "pop-v2/driving_vision.onnx",
"manifest": "pop-v2/manifest.json"
},
{
"id": "wmi-v0.11.0",
"label": "Stock WMI (openpilot 0.11.0)",
"file": "wmi-v0.11.0/driving_vision.onnx",
"manifest": "wmi-v0.11.0/manifest.json"
}
]
@@ -1,18 +0,0 @@
{
"source_revision": "3469d9aadbc16eb854bad3d851bd580d2b8f132e",
"source_tag": "v0.11.0",
"source_hashes": {
"common_transformations_model.py": "c87aad27074362fe9fe361a71da92c1fc90daf63bcfd4d8c47d65d3a936ec15e",
"selfdrive_controls_lib_drive_helpers.py": "0c8b32b1667000d48ee4630f0b197a05edabd811d718709ab616872c35918844",
"selfdrive_modeld_compile_warp.py": "574aa090de6fa272f95b00e039b1467d60c6d9445ee8d774e8529369648fcf0f",
"selfdrive_modeld_constants.py": "e1e3a01ea31dd57dbd9ffd588ff1f2ab22e6088a558c65ad68bf20678552c00c",
"selfdrive_modeld_fill_model_msg.py": "d99289ee16ddbcc286abc7184f1de55ad4378d860092ec896d1cdc4cf4f12799",
"selfdrive_modeld_get_model_metadata.py": "045d9fd4b10ff989adc5837b9a5dfad2b961b890f46f0bbe995335dae5e68789",
"selfdrive_modeld_modeld.py": "571496f6e8b8364d90d0e2dddcb2a6f375ecbb434927e11078f40084e56f3b66",
"selfdrive_modeld_parse_model_outputs.py": "82d5eb5391f2c02c187adb3ad9ae6ad9d97fd0ae681d54e808a438f415802ed4"
},
"decoded_metadata_no_pickle_execution": true,
"same_output_slices_as_pop": true,
"same_parser_constants_modeld_source_as_pop": true,
"different_weights_from_pop": true
}
-29
View File
@@ -1,29 +0,0 @@
{
"name": "Stock openpilot 0.11.0 WMI",
"model_id": "wmi-v0.11.0",
"output_layout": "pop-v2-split-1576-1000",
"model_file": "driving_vision.onnx",
"sha256": "ee29ee5bce84d1ce23e9ff381280de9b4e4d96d2934cd751740354884e112c66",
"policy_file": "driving_policy.onnx",
"policy_sha256": "78477124cbf3ffe30fa951ebada8410b43c4242c6054584d656f1d329b067e15",
"source_repository": "commaai/openpilot",
"source_revision": "3469d9aadbc16eb854bad3d851bd580d2b8f132e",
"source_tag": "v0.11.0",
"expected_run_hz": 20,
"context_hz": 5,
"image_pair_separation_s": 0.2,
"feature_context_samples": 25,
"feature_context_span_s": 4.8,
"experimental": true,
"preview_only": true,
"camera_validated": false,
"usable_for_control": false,
"decoder_compatibility": "Tagged WMI tensor signatures and embedded output_slices exactly match the Pop v2 split contract; constants, parser and modeld source are byte-identical. Policy checkpoint is distinct; vision checkpoint is shared with Pop, with a different ONNX artifact hash.",
"plan_confidence": "unassessed: unary mean/logstd plan has no selection probability",
"camera_approximation": "ATS SBIG render with derived MED crop; physical calibration remains unvalidated. Display toggle does not change inference inputs.",
"source_urls": {
"vision": "https://media.githubusercontent.com/media/commaai/openpilot/3469d9aadbc16eb854bad3d851bd580d2b8f132e/selfdrive/modeld/models/driving_vision.onnx",
"policy": "https://media.githubusercontent.com/media/commaai/openpilot/3469d9aadbc16eb854bad3d851bd580d2b8f132e/selfdrive/modeld/models/driving_policy.onnx",
"release": "https://blog.comma.ai/011release/"
}
}
-70
View File
@@ -1,70 +0,0 @@
{
"vision": {
"meta": [
0,
55
],
"desire_pred": [
55,
87
],
"pose": [
87,
99
],
"wide_from_device_euler": [
99,
105
],
"road_transform": [
105,
117
],
"lane_lines": [
117,
645
],
"lane_lines_prob": [
645,
653
],
"road_edges": [
653,
917
],
"lead": [
917,
1061
],
"lead_prob": [
1061,
1064
],
"hidden_state": [
1064,
1576
]
},
"policy": {
"plan": [
0,
990
],
"desire_state": [
990,
998
]
},
"lane_probability_logit_indices": [
1,
3,
5,
7
],
"plan_mean_shape": [
33,
15
],
"plan_std_encoding": "second495 values exp(logstd), exponent clipped11 upstream",
"extraction": "WMI v0.11.0 embedded output_slices are byte-identical to Pop metadata, independently checked via pickletools disassembly; no pickle execution"
}
@@ -1,70 +0,0 @@
import numpy as np
from openpilot.common.transformations.orientation import rot_from_euler
from openpilot.common.transformations.camera import get_view_frame_from_calib_frame, view_frame_from_device_frame, _ar_ox_fisheye
# segnet
SEGNET_SIZE = (512, 384)
# MED model
MEDMODEL_INPUT_SIZE = (512, 256)
MEDMODEL_YUV_SIZE = (MEDMODEL_INPUT_SIZE[0], MEDMODEL_INPUT_SIZE[1] * 3 // 2)
MEDMODEL_CY = 47.6
medmodel_fl = 910.0
medmodel_intrinsics = np.array([
[medmodel_fl, 0.0, 0.5 * MEDMODEL_INPUT_SIZE[0]],
[0.0, medmodel_fl, MEDMODEL_CY],
[0.0, 0.0, 1.0]])
# BIG model
BIGMODEL_INPUT_SIZE = (1024, 512)
BIGMODEL_YUV_SIZE = (BIGMODEL_INPUT_SIZE[0], BIGMODEL_INPUT_SIZE[1] * 3 // 2)
bigmodel_fl = 910.0
bigmodel_intrinsics = np.array([
[bigmodel_fl, 0.0, 0.5 * BIGMODEL_INPUT_SIZE[0]],
[0.0, bigmodel_fl, 256 + MEDMODEL_CY],
[0.0, 0.0, 1.0]])
# SBIG model (big model with the size of small model)
SBIGMODEL_INPUT_SIZE = (512, 256)
SBIGMODEL_YUV_SIZE = (SBIGMODEL_INPUT_SIZE[0], SBIGMODEL_INPUT_SIZE[1] * 3 // 2)
sbigmodel_fl = 455.0
sbigmodel_intrinsics = np.array([
[sbigmodel_fl, 0.0, 0.5 * SBIGMODEL_INPUT_SIZE[0]],
[0.0, sbigmodel_fl, 0.5 * (256 + MEDMODEL_CY)],
[0.0, 0.0, 1.0]])
DM_INPUT_SIZE = (1440, 960)
dmonitoringmodel_fl = _ar_ox_fisheye.focal_length
dmonitoringmodel_intrinsics = np.array([
[dmonitoringmodel_fl, 0.0, DM_INPUT_SIZE[0]/2],
[0.0, dmonitoringmodel_fl, DM_INPUT_SIZE[1]/2 - (_ar_ox_fisheye.height - DM_INPUT_SIZE[1])/2],
[0.0, 0.0, 1.0]])
bigmodel_frame_from_calib_frame = np.dot(bigmodel_intrinsics,
get_view_frame_from_calib_frame(0, 0, 0, 0))
sbigmodel_frame_from_calib_frame = np.dot(sbigmodel_intrinsics,
get_view_frame_from_calib_frame(0, 0, 0, 0))
medmodel_frame_from_calib_frame = np.dot(medmodel_intrinsics,
get_view_frame_from_calib_frame(0, 0, 0, 0))
medmodel_frame_from_bigmodel_frame = np.dot(medmodel_intrinsics, np.linalg.inv(bigmodel_intrinsics))
calib_from_medmodel = np.linalg.inv(medmodel_frame_from_calib_frame[:, :3])
calib_from_sbigmodel = np.linalg.inv(sbigmodel_frame_from_calib_frame[:, :3])
# This function is verified to give similar results to xx.uncommon.utils.transform_img
def get_warp_matrix(device_from_calib_euler: np.ndarray, intrinsics: np.ndarray, bigmodel_frame: bool = False) -> np.ndarray:
calib_from_model = calib_from_sbigmodel if bigmodel_frame else calib_from_medmodel
device_from_calib = rot_from_euler(device_from_calib_euler)
camera_from_calib = intrinsics @ view_frame_from_device_frame @ device_from_calib
warp_matrix: np.ndarray = camera_from_calib @ calib_from_model
return warp_matrix
@@ -1,43 +0,0 @@
0: \x80 PROTO 4
2: \x95 FRAME 90
11: } EMPTY_DICT
12: \x94 MEMOIZE (as 0)
13: ( MARK
14: \x8c SHORT_BINUNICODE 'plan'
20: \x94 MEMOIZE (as 1)
21: \x8c SHORT_BINUNICODE 'builtins'
31: \x94 MEMOIZE (as 2)
32: \x8c SHORT_BINUNICODE 'slice'
39: \x94 MEMOIZE (as 3)
40: \x93 STACK_GLOBAL
41: \x94 MEMOIZE (as 4)
42: K BININT1 0
44: M BININT2 990
47: N NONE
48: \x87 TUPLE3
49: \x94 MEMOIZE (as 5)
50: R REDUCE
51: \x94 MEMOIZE (as 6)
52: \x8c SHORT_BINUNICODE 'desire_state'
66: \x94 MEMOIZE (as 7)
67: h BINGET 4
69: M BININT2 990
72: M BININT2 998
75: N NONE
76: \x87 TUPLE3
77: \x94 MEMOIZE (as 8)
78: R REDUCE
79: \x94 MEMOIZE (as 9)
80: \x8c SHORT_BINUNICODE 'pad'
85: \x94 MEMOIZE (as 10)
86: h BINGET 4
88: J BININT -2
93: N NONE
94: N NONE
95: \x87 TUPLE3
96: \x94 MEMOIZE (as 11)
97: R REDUCE
98: \x94 MEMOIZE (as 12)
99: u SETITEMS (MARK at 13)
100: . STOP
highest protocol among opcodes = 4
@@ -1,133 +0,0 @@
0: \x80 PROTO 4
2: \x95 FRAME 320
11: } EMPTY_DICT
12: \x94 MEMOIZE (as 0)
13: ( MARK
14: \x8c SHORT_BINUNICODE 'meta'
20: \x94 MEMOIZE (as 1)
21: \x8c SHORT_BINUNICODE 'builtins'
31: \x94 MEMOIZE (as 2)
32: \x8c SHORT_BINUNICODE 'slice'
39: \x94 MEMOIZE (as 3)
40: \x93 STACK_GLOBAL
41: \x94 MEMOIZE (as 4)
42: K BININT1 0
44: K BININT1 55
46: N NONE
47: \x87 TUPLE3
48: \x94 MEMOIZE (as 5)
49: R REDUCE
50: \x94 MEMOIZE (as 6)
51: \x8c SHORT_BINUNICODE 'desire_pred'
64: \x94 MEMOIZE (as 7)
65: h BINGET 4
67: K BININT1 55
69: K BININT1 87
71: N NONE
72: \x87 TUPLE3
73: \x94 MEMOIZE (as 8)
74: R REDUCE
75: \x94 MEMOIZE (as 9)
76: \x8c SHORT_BINUNICODE 'pose'
82: \x94 MEMOIZE (as 10)
83: h BINGET 4
85: K BININT1 87
87: K BININT1 99
89: N NONE
90: \x87 TUPLE3
91: \x94 MEMOIZE (as 11)
92: R REDUCE
93: \x94 MEMOIZE (as 12)
94: \x8c SHORT_BINUNICODE 'wide_from_device_euler'
118: \x94 MEMOIZE (as 13)
119: h BINGET 4
121: K BININT1 99
123: K BININT1 105
125: N NONE
126: \x87 TUPLE3
127: \x94 MEMOIZE (as 14)
128: R REDUCE
129: \x94 MEMOIZE (as 15)
130: \x8c SHORT_BINUNICODE 'road_transform'
146: \x94 MEMOIZE (as 16)
147: h BINGET 4
149: K BININT1 105
151: K BININT1 117
153: N NONE
154: \x87 TUPLE3
155: \x94 MEMOIZE (as 17)
156: R REDUCE
157: \x94 MEMOIZE (as 18)
158: \x8c SHORT_BINUNICODE 'lane_lines'
170: \x94 MEMOIZE (as 19)
171: h BINGET 4
173: K BININT1 117
175: M BININT2 645
178: N NONE
179: \x87 TUPLE3
180: \x94 MEMOIZE (as 20)
181: R REDUCE
182: \x94 MEMOIZE (as 21)
183: \x8c SHORT_BINUNICODE 'lane_lines_prob'
200: \x94 MEMOIZE (as 22)
201: h BINGET 4
203: M BININT2 645
206: M BININT2 653
209: N NONE
210: \x87 TUPLE3
211: \x94 MEMOIZE (as 23)
212: R REDUCE
213: \x94 MEMOIZE (as 24)
214: \x8c SHORT_BINUNICODE 'road_edges'
226: \x94 MEMOIZE (as 25)
227: h BINGET 4
229: M BININT2 653
232: M BININT2 917
235: N NONE
236: \x87 TUPLE3
237: \x94 MEMOIZE (as 26)
238: R REDUCE
239: \x94 MEMOIZE (as 27)
240: \x8c SHORT_BINUNICODE 'lead'
246: \x94 MEMOIZE (as 28)
247: h BINGET 4
249: M BININT2 917
252: M BININT2 1061
255: N NONE
256: \x87 TUPLE3
257: \x94 MEMOIZE (as 29)
258: R REDUCE
259: \x94 MEMOIZE (as 30)
260: \x8c SHORT_BINUNICODE 'lead_prob'
271: \x94 MEMOIZE (as 31)
272: h BINGET 4
274: M BININT2 1061
277: M BININT2 1064
280: N NONE
281: \x87 TUPLE3
282: \x94 MEMOIZE (as 32)
283: R REDUCE
284: \x94 MEMOIZE (as 33)
285: \x8c SHORT_BINUNICODE 'hidden_state'
299: \x94 MEMOIZE (as 34)
300: h BINGET 4
302: M BININT2 1064
305: M BININT2 1576
308: N NONE
309: \x87 TUPLE3
310: \x94 MEMOIZE (as 35)
311: R REDUCE
312: \x94 MEMOIZE (as 36)
313: \x8c SHORT_BINUNICODE 'pad'
318: \x94 MEMOIZE (as 37)
319: h BINGET 4
321: K BININT1 0
323: N NONE
324: N NONE
325: \x87 TUPLE3
326: \x94 MEMOIZE (as 38)
327: R REDUCE
328: \x94 MEMOIZE (as 39)
329: u SETITEMS (MARK at 13)
330: . STOP
highest protocol among opcodes = 4
-9
View File
@@ -1,9 +0,0 @@
{
"repository": "commaai/openpilot",
"tag": "v0.11.0",
"commit": "3469d9aadbc16eb854bad3d851bd580d2b8f132e",
"artifact_sha256": {
"driving_vision.onnx": "ee29ee5bce84d1ce23e9ff381280de9b4e4d96d2934cd751740354884e112c66",
"driving_policy.onnx": "78477124cbf3ffe30fa951ebada8410b43c4242c6054584d656f1d329b067e15"
}
}
@@ -1,65 +0,0 @@
import numpy as np
from openpilot.common.constants import ACCELERATION_DUE_TO_GRAVITY
from openpilot.common.realtime import DT_CTRL, DT_MDL
MIN_SPEED = 1.0
CONTROL_N = 17
CAR_ROTATION_RADIUS = 0.0
# This is a turn radius smaller than most cars can achieve
MAX_CURVATURE = 0.2
MAX_VEL_ERR = 5.0 # m/s
# EU guidelines
MAX_LATERAL_JERK = 5.0 # m/s^3
MAX_LATERAL_ACCEL_NO_ROLL = 3.0 # m/s^2
def clamp(val, min_val, max_val):
clamped_val = float(np.clip(val, min_val, max_val))
return clamped_val, clamped_val != val
def smooth_value(val, prev_val, tau, dt=DT_MDL):
alpha = 1 - np.exp(-dt/tau) if tau > 0 else 1
return alpha * val + (1 - alpha) * prev_val
def clip_curvature(v_ego, prev_curvature, new_curvature, roll) -> tuple[float, bool]:
# This function respects ISO lateral jerk and acceleration limits + a max curvature
v_ego = max(v_ego, MIN_SPEED)
max_curvature_rate = MAX_LATERAL_JERK / (v_ego ** 2) # inexact calculation, check https://github.com/commaai/openpilot/pull/24755
new_curvature = np.clip(new_curvature,
prev_curvature - max_curvature_rate * DT_CTRL,
prev_curvature + max_curvature_rate * DT_CTRL)
roll_compensation = roll * ACCELERATION_DUE_TO_GRAVITY
max_lat_accel = MAX_LATERAL_ACCEL_NO_ROLL + roll_compensation
min_lat_accel = -MAX_LATERAL_ACCEL_NO_ROLL + roll_compensation
new_curvature, limited_accel = clamp(new_curvature, min_lat_accel / v_ego ** 2, max_lat_accel / v_ego ** 2)
new_curvature, limited_max_curv = clamp(new_curvature, -MAX_CURVATURE, MAX_CURVATURE)
return float(new_curvature), limited_accel or limited_max_curv
def get_accel_from_plan(speeds, accels, t_idxs, action_t=DT_MDL, vEgoStopping=0.05):
if len(speeds) == len(t_idxs):
v_now = speeds[0]
a_now = accels[0]
v_target = np.interp(action_t, t_idxs, speeds)
a_target = 2 * (v_target - v_now) / (action_t) - a_now
v_target_1sec = np.interp(action_t + 1.0, t_idxs, speeds)
else:
v_target = 0.0
v_target_1sec = 0.0
a_target = 0.0
should_stop = (v_target < vEgoStopping and
v_target_1sec < vEgoStopping)
return a_target, should_stop
def curv_from_psis(psi_target, psi_rate, vego, action_t):
vego = np.clip(vego, MIN_SPEED, np.inf)
curv_from_psi = psi_target / (vego * action_t)
return 2*curv_from_psi - psi_rate / vego
def get_curvature_from_plan(yaws, yaw_rates, t_idxs, vego, action_t):
psi_target = np.interp(action_t, t_idxs, yaws)
psi_rate = yaw_rates[0]
return curv_from_psis(psi_target, psi_rate, vego, action_t)
@@ -1,209 +0,0 @@
#!/usr/bin/env python3
import time
import pickle
import numpy as np
from pathlib import Path
from tinygrad.tensor import Tensor
from tinygrad.helpers import Context
from tinygrad.device import Device
from tinygrad.engine.jit import TinyJit
from openpilot.system.camerad.cameras.nv12_info import get_nv12_info
from openpilot.common.transformations.model import MEDMODEL_INPUT_SIZE, DM_INPUT_SIZE
from openpilot.common.transformations.camera import _ar_ox_fisheye, _os_fisheye
MODELS_DIR = Path(__file__).parent / 'models'
CAMERA_CONFIGS = [
(_ar_ox_fisheye.width, _ar_ox_fisheye.height), # tici: 1928x1208
(_os_fisheye.width, _os_fisheye.height), # mici: 1344x760
]
UV_SCALE_MATRIX = np.array([[0.5, 0, 0], [0, 0.5, 0], [0, 0, 1]], dtype=np.float32)
UV_SCALE_MATRIX_INV = np.linalg.inv(UV_SCALE_MATRIX)
IMG_BUFFER_SHAPE = (30, MEDMODEL_INPUT_SIZE[1] // 2, MEDMODEL_INPUT_SIZE[0] // 2)
def warp_pkl_path(w, h):
return MODELS_DIR / f'warp_{w}x{h}_tinygrad.pkl'
def dm_warp_pkl_path(w, h):
return MODELS_DIR / f'dm_warp_{w}x{h}_tinygrad.pkl'
def warp_perspective_tinygrad(src_flat, M_inv, dst_shape, src_shape, stride_pad):
w_dst, h_dst = dst_shape
h_src, w_src = src_shape
x = Tensor.arange(w_dst).reshape(1, w_dst).expand(h_dst, w_dst).reshape(-1)
y = Tensor.arange(h_dst).reshape(h_dst, 1).expand(h_dst, w_dst).reshape(-1)
# inline 3x3 matmul as elementwise to avoid reduce op (enables fusion with gather)
src_x = M_inv[0, 0] * x + M_inv[0, 1] * y + M_inv[0, 2]
src_y = M_inv[1, 0] * x + M_inv[1, 1] * y + M_inv[1, 2]
src_w = M_inv[2, 0] * x + M_inv[2, 1] * y + M_inv[2, 2]
src_x = src_x / src_w
src_y = src_y / src_w
x_nn_clipped = Tensor.round(src_x).clip(0, w_src - 1).cast('int')
y_nn_clipped = Tensor.round(src_y).clip(0, h_src - 1).cast('int')
idx = y_nn_clipped * (w_src + stride_pad) + x_nn_clipped
return src_flat[idx]
def frames_to_tensor(frames, model_w, model_h):
H = (frames.shape[0] * 2) // 3
W = frames.shape[1]
in_img1 = Tensor.cat(frames[0:H:2, 0::2],
frames[1:H:2, 0::2],
frames[0:H:2, 1::2],
frames[1:H:2, 1::2],
frames[H:H+H//4].reshape((H//2, W//2)),
frames[H+H//4:H+H//2].reshape((H//2, W//2)), dim=0).reshape((6, H//2, W//2))
return in_img1
def make_frame_prepare(cam_w, cam_h, model_w, model_h):
stride, y_height, uv_height, _ = get_nv12_info(cam_w, cam_h)
uv_offset = stride * y_height
stride_pad = stride - cam_w
def frame_prepare_tinygrad(input_frame, M_inv):
# UV_SCALE @ M_inv @ UV_SCALE_INV simplifies to elementwise scaling
M_inv_uv = M_inv * Tensor([[1.0, 1.0, 0.5], [1.0, 1.0, 0.5], [2.0, 2.0, 1.0]])
# deinterleave NV12 UV plane (UVUV... -> separate U, V)
uv = input_frame[uv_offset:uv_offset + uv_height * stride].reshape(uv_height, stride)
with Context(SPLIT_REDUCEOP=0):
y = warp_perspective_tinygrad(input_frame[:cam_h*stride],
M_inv, (model_w, model_h),
(cam_h, cam_w), stride_pad).realize()
u = warp_perspective_tinygrad(uv[:cam_h//2, :cam_w:2].flatten(),
M_inv_uv, (model_w//2, model_h//2),
(cam_h//2, cam_w//2), 0).realize()
v = warp_perspective_tinygrad(uv[:cam_h//2, 1:cam_w:2].flatten(),
M_inv_uv, (model_w//2, model_h//2),
(cam_h//2, cam_w//2), 0).realize()
yuv = y.cat(u).cat(v).reshape((model_h * 3 // 2, model_w))
tensor = frames_to_tensor(yuv, model_w, model_h)
return tensor
return frame_prepare_tinygrad
def make_update_img_input(frame_prepare, model_w, model_h):
def update_img_input_tinygrad(tensor, frame, M_inv):
M_inv = M_inv.to(Device.DEFAULT)
new_img = frame_prepare(frame, M_inv)
full_buffer = tensor[6:].cat(new_img, dim=0).contiguous()
return full_buffer, Tensor.cat(full_buffer[:6], full_buffer[-6:], dim=0).contiguous().reshape(1, 12, model_h//2, model_w//2)
return update_img_input_tinygrad
def make_update_both_imgs(frame_prepare, model_w, model_h):
update_img = make_update_img_input(frame_prepare, model_w, model_h)
def update_both_imgs_tinygrad(calib_img_buffer, new_img, M_inv,
calib_big_img_buffer, new_big_img, M_inv_big):
calib_img_buffer, calib_img_pair = update_img(calib_img_buffer, new_img, M_inv)
calib_big_img_buffer, calib_big_img_pair = update_img(calib_big_img_buffer, new_big_img, M_inv_big)
return calib_img_buffer, calib_img_pair, calib_big_img_buffer, calib_big_img_pair
return update_both_imgs_tinygrad
def make_warp_dm(cam_w, cam_h, dm_w, dm_h):
stride, y_height, _, _ = get_nv12_info(cam_w, cam_h)
stride_pad = stride - cam_w
def warp_dm(input_frame, M_inv):
M_inv = M_inv.to(Device.DEFAULT)
result = warp_perspective_tinygrad(input_frame[:cam_h*stride], M_inv, (dm_w, dm_h), (cam_h, cam_w), stride_pad).reshape(-1, dm_h * dm_w)
return result
return warp_dm
def compile_modeld_warp(cam_w, cam_h):
model_w, model_h = MEDMODEL_INPUT_SIZE
_, _, _, yuv_size = get_nv12_info(cam_w, cam_h)
print(f"Compiling modeld warp for {cam_w}x{cam_h}...")
frame_prepare = make_frame_prepare(cam_w, cam_h, model_w, model_h)
update_both_imgs = make_update_both_imgs(frame_prepare, model_w, model_h)
update_img_jit = TinyJit(update_both_imgs, prune=True)
full_buffer = Tensor.zeros(IMG_BUFFER_SHAPE, dtype='uint8').contiguous().realize()
big_full_buffer = Tensor.zeros(IMG_BUFFER_SHAPE, dtype='uint8').contiguous().realize()
full_buffer_np = np.zeros(IMG_BUFFER_SHAPE, dtype=np.uint8)
big_full_buffer_np = np.zeros(IMG_BUFFER_SHAPE, dtype=np.uint8)
for i in range(10):
new_frame_np = (32 * np.random.randn(yuv_size).astype(np.float32) + 128).clip(0, 255).astype(np.uint8)
img_inputs = [full_buffer,
Tensor.from_blob(new_frame_np.ctypes.data, (yuv_size,), dtype='uint8').realize(),
Tensor(Tensor.randn(3, 3).mul(8).realize().numpy(), device='NPY')]
new_big_frame_np = (32 * np.random.randn(yuv_size).astype(np.float32) + 128).clip(0, 255).astype(np.uint8)
big_img_inputs = [big_full_buffer,
Tensor.from_blob(new_big_frame_np.ctypes.data, (yuv_size,), dtype='uint8').realize(),
Tensor(Tensor.randn(3, 3).mul(8).realize().numpy(), device='NPY')]
inputs = img_inputs + big_img_inputs
Device.default.synchronize()
inputs_np = [x.numpy() for x in inputs]
inputs_np[0] = full_buffer_np
inputs_np[3] = big_full_buffer_np
st = time.perf_counter()
out = update_img_jit(*inputs)
full_buffer = out[0].contiguous().realize().clone()
big_full_buffer = out[2].contiguous().realize().clone()
mt = time.perf_counter()
Device.default.synchronize()
et = time.perf_counter()
print(f" [{i+1}/10] enqueue {(mt-st)*1e3:6.2f} ms -- total {(et-st)*1e3:6.2f} ms")
pkl_path = warp_pkl_path(cam_w, cam_h)
with open(pkl_path, "wb") as f:
pickle.dump(update_img_jit, f)
print(f" Saved to {pkl_path}")
jit = pickle.load(open(pkl_path, "rb"))
jit(*inputs)
def compile_dm_warp(cam_w, cam_h):
dm_w, dm_h = DM_INPUT_SIZE
_, _, _, yuv_size = get_nv12_info(cam_w, cam_h)
print(f"Compiling DM warp for {cam_w}x{cam_h}...")
warp_dm = make_warp_dm(cam_w, cam_h, dm_w, dm_h)
warp_dm_jit = TinyJit(warp_dm, prune=True)
for i in range(10):
inputs = [Tensor.from_blob((32 * Tensor.randn(yuv_size,) + 128).cast(dtype='uint8').realize().numpy().ctypes.data, (yuv_size,), dtype='uint8'),
Tensor(Tensor.randn(3, 3).mul(8).realize().numpy(), device='NPY')]
Device.default.synchronize()
st = time.perf_counter()
warp_dm_jit(*inputs)
mt = time.perf_counter()
Device.default.synchronize()
et = time.perf_counter()
print(f" [{i+1}/10] enqueue {(mt-st)*1e3:6.2f} ms -- total {(et-st)*1e3:6.2f} ms")
pkl_path = dm_warp_pkl_path(cam_w, cam_h)
with open(pkl_path, "wb") as f:
pickle.dump(warp_dm_jit, f)
print(f" Saved to {pkl_path}")
def run_and_save_pickle():
for cam_w, cam_h in CAMERA_CONFIGS:
compile_modeld_warp(cam_w, cam_h)
compile_dm_warp(cam_w, cam_h)
if __name__ == "__main__":
run_and_save_pickle()
@@ -1,87 +0,0 @@
import numpy as np
def index_function(idx, max_val=192, max_idx=32):
return (max_val) * ((idx/max_idx)**2)
class ModelConstants:
# time and distance indices
IDX_N = 33
T_IDXS = [index_function(idx, max_val=10.0) for idx in range(IDX_N)]
X_IDXS = [index_function(idx, max_val=192.0) for idx in range(IDX_N)]
LEAD_T_IDXS = [0., 2., 4., 6., 8., 10.]
LEAD_T_OFFSETS = [0., 2., 4.]
META_T_IDXS = [2., 4., 6., 8., 10.]
# model inputs constants
N_FRAMES = 2
MODEL_RUN_FREQ = 20
MODEL_CONTEXT_FREQ = 5 # "model_trained_fps"
FEATURE_LEN = 512
DESIRE_LEN = 8
TRAFFIC_CONVENTION_LEN = 2
LAT_PLANNER_STATE_LEN = 4
LATERAL_CONTROL_PARAMS_LEN = 2
PREV_DESIRED_CURV_LEN = 1
# model outputs constants
FCW_THRESHOLDS_5MS2 = np.array([.05, .05, .15, .15, .15], dtype=np.float32)
FCW_THRESHOLDS_3MS2 = np.array([.7, .7], dtype=np.float32)
FCW_5MS2_PROBS_WIDTH = 5
FCW_3MS2_PROBS_WIDTH = 2
DISENGAGE_WIDTH = 5
POSE_WIDTH = 6
WIDE_FROM_DEVICE_WIDTH = 3
LEAD_WIDTH = 4
LANE_LINES_WIDTH = 2
ROAD_EDGES_WIDTH = 2
PLAN_WIDTH = 15
DESIRE_PRED_WIDTH = 8
LAT_PLANNER_SOLUTION_WIDTH = 4
DESIRED_CURV_WIDTH = 1
NUM_LANE_LINES = 4
NUM_ROAD_EDGES = 2
LEAD_TRAJ_LEN = 6
DESIRE_PRED_LEN = 4
PLAN_MHP_N = 5
LEAD_MHP_N = 2
PLAN_MHP_SELECTION = 1
LEAD_MHP_SELECTION = 3
FCW_THRESHOLD_5MS2_HIGH = 0.15
FCW_THRESHOLD_5MS2_LOW = 0.05
FCW_THRESHOLD_3MS2 = 0.7
CONFIDENCE_BUFFER_LEN = 5
RYG_GREEN = 0.01165
RYG_YELLOW = 0.06157
POLY_PATH_DEGREE = 4
# model outputs slices
class Plan:
POSITION = slice(0, 3)
VELOCITY = slice(3, 6)
ACCELERATION = slice(6, 9)
T_FROM_CURRENT_EULER = slice(9, 12)
ORIENTATION_RATE = slice(12, 15)
class Meta:
ENGAGED = slice(0, 1)
# next 2, 4, 6, 8, 10 seconds
GAS_DISENGAGE = slice(1, 31, 6)
BRAKE_DISENGAGE = slice(2, 31, 6)
STEER_OVERRIDE = slice(3, 31, 6)
HARD_BRAKE_3 = slice(4, 31, 6)
HARD_BRAKE_4 = slice(5, 31, 6)
HARD_BRAKE_5 = slice(6, 31, 6)
# next 0, 2, 4, 6, 8, 10 seconds
GAS_PRESS = slice(31, 55, 4)
BRAKE_PRESS = slice(32, 55, 4)
LEFT_BLINKER = slice(33, 55, 4)
RIGHT_BLINKER = slice(34, 55, 4)
@@ -1,193 +0,0 @@
import os
import capnp
import numpy as np
from cereal import log
from openpilot.selfdrive.modeld.constants import ModelConstants, Plan, Meta
SEND_RAW_PRED = os.getenv('SEND_RAW_PRED')
ConfidenceClass = log.ModelDataV2.ConfidenceClass
class PublishState:
def __init__(self):
self.disengage_buffer = np.zeros(ModelConstants.CONFIDENCE_BUFFER_LEN*ModelConstants.DISENGAGE_WIDTH, dtype=np.float32)
self.prev_brake_5ms2_probs = np.zeros(ModelConstants.FCW_5MS2_PROBS_WIDTH, dtype=np.float32)
self.prev_brake_3ms2_probs = np.zeros(ModelConstants.FCW_3MS2_PROBS_WIDTH, dtype=np.float32)
def fill_xyzt(builder, t, x, y, z, x_std=None, y_std=None, z_std=None):
builder.t = t
builder.x = x.tolist()
builder.y = y.tolist()
builder.z = z.tolist()
if x_std is not None:
builder.xStd = x_std.tolist()
if y_std is not None:
builder.yStd = y_std.tolist()
if z_std is not None:
builder.zStd = z_std.tolist()
def fill_xyvat(builder, t, x, y, v, a, x_std=None, y_std=None, v_std=None, a_std=None):
builder.t = t
builder.x = x.tolist()
builder.y = y.tolist()
builder.v = v.tolist()
builder.a = a.tolist()
if x_std is not None:
builder.xStd = x_std.tolist()
if y_std is not None:
builder.yStd = y_std.tolist()
if v_std is not None:
builder.vStd = v_std.tolist()
if a_std is not None:
builder.aStd = a_std.tolist()
def fill_xyz_poly(builder, degree, x, y, z):
xyz = np.stack([x, y, z], axis=1)
coeffs = np.polynomial.polynomial.polyfit(ModelConstants.T_IDXS, xyz, deg=degree)
builder.xCoefficients = coeffs[:, 0].tolist()
builder.yCoefficients = coeffs[:, 1].tolist()
builder.zCoefficients = coeffs[:, 2].tolist()
def fill_lane_line_meta(builder, lane_lines, lane_line_probs):
builder.leftY = lane_lines[1].y[0]
builder.leftProb = lane_line_probs[1]
builder.rightY = lane_lines[2].y[0]
builder.rightProb = lane_line_probs[2]
def fill_model_msg(base_msg: capnp._DynamicStructBuilder, extended_msg: capnp._DynamicStructBuilder,
net_output_data: dict[str, np.ndarray], action: log.ModelDataV2.Action,
publish_state: PublishState, vipc_frame_id: int, vipc_frame_id_extra: int,
frame_id: int, frame_drop: float, timestamp_eof: int, model_execution_time: float,
valid: bool) -> None:
frame_age = frame_id - vipc_frame_id if frame_id > vipc_frame_id else 0
frame_drop_perc = frame_drop * 100
extended_msg.valid = valid
base_msg.valid = valid
driving_model_data = base_msg.drivingModelData
driving_model_data.frameId = vipc_frame_id
driving_model_data.frameIdExtra = vipc_frame_id_extra
driving_model_data.frameDropPerc = frame_drop_perc
driving_model_data.modelExecutionTime = model_execution_time
driving_model_data.action = action
modelV2 = extended_msg.modelV2
modelV2.frameId = vipc_frame_id
modelV2.frameIdExtra = vipc_frame_id_extra
modelV2.frameAge = frame_age
modelV2.frameDropPerc = frame_drop_perc
modelV2.timestampEof = timestamp_eof
modelV2.modelExecutionTime = model_execution_time
# plan
fill_xyzt(modelV2.position, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.POSITION].T, *net_output_data['plan_stds'][0,:,Plan.POSITION].T)
fill_xyzt(modelV2.velocity, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.VELOCITY].T)
fill_xyzt(modelV2.acceleration, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.ACCELERATION].T)
fill_xyzt(modelV2.orientation, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.T_FROM_CURRENT_EULER].T)
fill_xyzt(modelV2.orientationRate, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.ORIENTATION_RATE].T)
# poly path
fill_xyz_poly(driving_model_data.path, ModelConstants.POLY_PATH_DEGREE, *net_output_data['plan'][0,:,Plan.POSITION].T)
# action
modelV2.action = action
# times at X_IDXS of edges and lines aren't used
LINE_T_IDXS: list[float] = []
# lane lines
modelV2.init('laneLines', 4)
for i in range(4):
lane_line = modelV2.laneLines[i]
fill_xyzt(lane_line, LINE_T_IDXS, np.array(ModelConstants.X_IDXS), net_output_data['lane_lines'][0,i,:,0], net_output_data['lane_lines'][0,i,:,1])
modelV2.laneLineStds = net_output_data['lane_lines_stds'][0,:,0,0].tolist()
modelV2.laneLineProbs = net_output_data['lane_lines_prob'][0,1::2].tolist()
fill_lane_line_meta(driving_model_data.laneLineMeta, modelV2.laneLines, modelV2.laneLineProbs)
# road edges
modelV2.init('roadEdges', 2)
for i in range(2):
road_edge = modelV2.roadEdges[i]
fill_xyzt(road_edge, LINE_T_IDXS, np.array(ModelConstants.X_IDXS), net_output_data['road_edges'][0,i,:,0], net_output_data['road_edges'][0,i,:,1])
modelV2.roadEdgeStds = net_output_data['road_edges_stds'][0,:,0,0].tolist()
# leads
modelV2.init('leadsV3', 3)
for i in range(3):
lead = modelV2.leadsV3[i]
fill_xyvat(lead, ModelConstants.LEAD_T_IDXS, *net_output_data['lead'][0,i].T, *net_output_data['lead_stds'][0,i].T)
lead.prob = net_output_data['lead_prob'][0,i].tolist()
lead.probTime = ModelConstants.LEAD_T_OFFSETS[i]
# meta
meta = modelV2.meta
meta.desireState = net_output_data['desire_state'][0].reshape(-1).tolist()
meta.desirePrediction = net_output_data['desire_pred'][0].reshape(-1).tolist()
meta.engagedProb = net_output_data['meta'][0,Meta.ENGAGED].item()
meta.init('disengagePredictions')
disengage_predictions = meta.disengagePredictions
disengage_predictions.t = ModelConstants.META_T_IDXS
disengage_predictions.brakeDisengageProbs = net_output_data['meta'][0,Meta.BRAKE_DISENGAGE].tolist()
disengage_predictions.gasDisengageProbs = net_output_data['meta'][0,Meta.GAS_DISENGAGE].tolist()
disengage_predictions.steerOverrideProbs = net_output_data['meta'][0,Meta.STEER_OVERRIDE].tolist()
disengage_predictions.brake3MetersPerSecondSquaredProbs = net_output_data['meta'][0,Meta.HARD_BRAKE_3].tolist()
disengage_predictions.brake4MetersPerSecondSquaredProbs = net_output_data['meta'][0,Meta.HARD_BRAKE_4].tolist()
disengage_predictions.brake5MetersPerSecondSquaredProbs = net_output_data['meta'][0,Meta.HARD_BRAKE_5].tolist()
disengage_predictions.gasPressProbs = net_output_data['meta'][0,Meta.GAS_PRESS].tolist()
disengage_predictions.brakePressProbs = net_output_data['meta'][0,Meta.BRAKE_PRESS].tolist()
publish_state.prev_brake_5ms2_probs[:-1] = publish_state.prev_brake_5ms2_probs[1:]
publish_state.prev_brake_5ms2_probs[-1] = net_output_data['meta'][0,Meta.HARD_BRAKE_5][0]
publish_state.prev_brake_3ms2_probs[:-1] = publish_state.prev_brake_3ms2_probs[1:]
publish_state.prev_brake_3ms2_probs[-1] = net_output_data['meta'][0,Meta.HARD_BRAKE_3][0]
hard_brake_predicted = (publish_state.prev_brake_5ms2_probs > ModelConstants.FCW_THRESHOLDS_5MS2).all() and \
(publish_state.prev_brake_3ms2_probs > ModelConstants.FCW_THRESHOLDS_3MS2).all()
meta.hardBrakePredicted = hard_brake_predicted.item()
# confidence
if vipc_frame_id % (2*ModelConstants.MODEL_RUN_FREQ) == 0:
# any disengage prob
brake_disengage_probs = net_output_data['meta'][0,Meta.BRAKE_DISENGAGE]
gas_disengage_probs = net_output_data['meta'][0,Meta.GAS_DISENGAGE]
steer_override_probs = net_output_data['meta'][0,Meta.STEER_OVERRIDE]
any_disengage_probs = 1-((1-brake_disengage_probs)*(1-gas_disengage_probs)*(1-steer_override_probs))
# independent disengage prob for each 2s slice
ind_disengage_probs = np.r_[any_disengage_probs[0], np.diff(any_disengage_probs) / (1 - any_disengage_probs[:-1])]
# rolling buf for 2, 4, 6, 8, 10s
publish_state.disengage_buffer[:-ModelConstants.DISENGAGE_WIDTH] = publish_state.disengage_buffer[ModelConstants.DISENGAGE_WIDTH:]
publish_state.disengage_buffer[-ModelConstants.DISENGAGE_WIDTH:] = ind_disengage_probs
score = 0.
for i in range(ModelConstants.DISENGAGE_WIDTH):
score += publish_state.disengage_buffer[i*ModelConstants.DISENGAGE_WIDTH+ModelConstants.DISENGAGE_WIDTH-1-i].item() / ModelConstants.DISENGAGE_WIDTH
if score < ModelConstants.RYG_GREEN:
modelV2.confidence = ConfidenceClass.green
elif score < ModelConstants.RYG_YELLOW:
modelV2.confidence = ConfidenceClass.yellow
else:
modelV2.confidence = ConfidenceClass.red
# raw prediction if enabled
if SEND_RAW_PRED:
modelV2.rawPredictions = net_output_data['raw_pred'].tobytes()
def fill_pose_msg(msg: capnp._DynamicStructBuilder, net_output_data: dict[str, np.ndarray],
vipc_frame_id: int, vipc_dropped_frames: int, timestamp_eof: int, live_calib_seen: bool) -> None:
msg.valid = live_calib_seen & (vipc_dropped_frames < 1)
cameraOdometry = msg.cameraOdometry
cameraOdometry.frameId = vipc_frame_id
cameraOdometry.timestampEof = timestamp_eof
cameraOdometry.trans = net_output_data['pose'][0,:3].tolist()
cameraOdometry.rot = net_output_data['pose'][0,3:].tolist()
cameraOdometry.wideFromDeviceEuler = net_output_data['wide_from_device_euler'][0,:].tolist()
cameraOdometry.roadTransformTrans = net_output_data['road_transform'][0,:3].tolist()
cameraOdometry.transStd = net_output_data['pose_stds'][0,:3].tolist()
cameraOdometry.rotStd = net_output_data['pose_stds'][0,3:].tolist()
cameraOdometry.wideFromDeviceEulerStd = net_output_data['wide_from_device_euler_stds'][0,:].tolist()
cameraOdometry.roadTransformTransStd = net_output_data['road_transform_stds'][0,:3].tolist()
@@ -1,55 +0,0 @@
#!/usr/bin/env python3
import sys
import pathlib
import codecs
import pickle
from typing import Any
from tinygrad.nn.onnx import OnnxPBParser
class MetadataOnnxPBParser(OnnxPBParser):
def _parse_ModelProto(self) -> dict:
obj: dict[str, Any] = {"graph": {"input": [], "output": []}, "metadata_props": []}
for fid, wire_type in self._parse_message(self.reader.len):
match fid:
case 7:
obj["graph"] = self._parse_GraphProto()
case 14:
obj["metadata_props"].append(self._parse_StringStringEntryProto())
case _:
self.reader.skip_field(wire_type)
return obj
def get_name_and_shape(value_info: dict[str, Any]) -> tuple[str, tuple[int, ...]]:
shape = tuple(int(dim) if isinstance(dim, int) else 0 for dim in value_info["parsed_type"].shape)
name = value_info["name"]
return name, shape
def get_metadata_value_by_name(model: dict[str, Any], name: str) -> str | Any:
for prop in model["metadata_props"]:
if prop["key"] == name:
return prop["value"]
return None
if __name__ == "__main__":
model_path = pathlib.Path(sys.argv[1])
model = MetadataOnnxPBParser(model_path).parse()
output_slices = get_metadata_value_by_name(model, 'output_slices')
assert output_slices is not None, 'output_slices not found in metadata'
metadata = {
'model_checkpoint': get_metadata_value_by_name(model, 'model_checkpoint'),
'output_slices': pickle.loads(codecs.decode(output_slices.encode(), "base64")),
'input_shapes': dict(get_name_and_shape(x) for x in model["graph"]["input"]),
'output_shapes': dict(get_name_and_shape(x) for x in model["graph"]["output"]),
}
metadata_path = model_path.parent / (model_path.stem + '_metadata.pkl')
with open(metadata_path, 'wb') as f:
pickle.dump(metadata, f)
print(f'saved metadata to {metadata_path}')
@@ -1,422 +0,0 @@
#!/usr/bin/env python3
import os
from openpilot.system.hardware import TICI
os.environ['DEV'] = 'QCOM' if TICI else 'CPU'
USBGPU = "USBGPU" in os.environ
if USBGPU:
os.environ['DEV'] = 'AMD'
os.environ['AMD_IFACE'] = 'USB'
from tinygrad.tensor import Tensor
import time
import pickle
import numpy as np
import cereal.messaging as messaging
from cereal import car, log
from pathlib import Path
from cereal.messaging import PubMaster, SubMaster
from msgq.visionipc import VisionIpcClient, VisionStreamType, VisionBuf
from opendbc.car.car_helpers import get_demo_car_params
from openpilot.common.swaglog import cloudlog
from openpilot.common.params import Params
from openpilot.common.filter_simple import FirstOrderFilter
from openpilot.common.realtime import config_realtime_process, DT_MDL
from openpilot.common.transformations.camera import DEVICE_CAMERAS
from openpilot.system.camerad.cameras.nv12_info import get_nv12_info
from openpilot.common.transformations.model import get_warp_matrix
from openpilot.selfdrive.controls.lib.desire_helper import DesireHelper
from openpilot.selfdrive.controls.lib.drive_helpers import get_accel_from_plan, smooth_value, get_curvature_from_plan
from openpilot.selfdrive.modeld.parse_model_outputs import Parser
from openpilot.selfdrive.modeld.fill_model_msg import fill_model_msg, fill_pose_msg, PublishState
from openpilot.common.file_chunker import read_file_chunked
from openpilot.selfdrive.modeld.constants import ModelConstants, Plan
PROCESS_NAME = "selfdrive.modeld.modeld"
SEND_RAW_PRED = os.getenv('SEND_RAW_PRED')
VISION_PKL_PATH = Path(__file__).parent / 'models/driving_vision_tinygrad.pkl'
POLICY_PKL_PATH = Path(__file__).parent / 'models/driving_policy_tinygrad.pkl'
VISION_METADATA_PATH = Path(__file__).parent / 'models/driving_vision_metadata.pkl'
POLICY_METADATA_PATH = Path(__file__).parent / 'models/driving_policy_metadata.pkl'
MODELS_DIR = Path(__file__).parent / 'models'
LAT_SMOOTH_SECONDS = 0.0
LONG_SMOOTH_SECONDS = 0.3
MIN_LAT_CONTROL_SPEED = 0.3
IMG_QUEUE_SHAPE = (6*(ModelConstants.MODEL_RUN_FREQ//ModelConstants.MODEL_CONTEXT_FREQ + 1), 128, 256)
assert IMG_QUEUE_SHAPE[0] == 30
def get_action_from_model(model_output: dict[str, np.ndarray], prev_action: log.ModelDataV2.Action,
lat_action_t: float, long_action_t: float, v_ego: float) -> log.ModelDataV2.Action:
plan = model_output['plan'][0]
desired_accel, should_stop = get_accel_from_plan(plan[:,Plan.VELOCITY][:,0],
plan[:,Plan.ACCELERATION][:,0],
ModelConstants.T_IDXS,
action_t=long_action_t)
desired_accel = smooth_value(desired_accel, prev_action.desiredAcceleration, LONG_SMOOTH_SECONDS)
desired_curvature = get_curvature_from_plan(plan[:,Plan.T_FROM_CURRENT_EULER][:,2],
plan[:,Plan.ORIENTATION_RATE][:,2],
ModelConstants.T_IDXS,
v_ego,
lat_action_t)
if v_ego > MIN_LAT_CONTROL_SPEED:
desired_curvature = smooth_value(desired_curvature, prev_action.desiredCurvature, LAT_SMOOTH_SECONDS)
else:
desired_curvature = prev_action.desiredCurvature
return log.ModelDataV2.Action(desiredCurvature=float(desired_curvature),
desiredAcceleration=float(desired_accel),
shouldStop=bool(should_stop))
class FrameMeta:
frame_id: int = 0
timestamp_sof: int = 0
timestamp_eof: int = 0
def __init__(self, vipc=None):
if vipc is not None:
self.frame_id, self.timestamp_sof, self.timestamp_eof = vipc.frame_id, vipc.timestamp_sof, vipc.timestamp_eof
class InputQueues:
def __init__ (self, model_fps, env_fps, n_frames_input):
assert env_fps % model_fps == 0
assert env_fps >= model_fps
self.model_fps = model_fps
self.env_fps = env_fps
self.n_frames_input = n_frames_input
self.dtypes = {}
self.shapes = {}
self.q = {}
def update_dtypes_and_shapes(self, input_dtypes, input_shapes) -> None:
self.dtypes.update(input_dtypes)
if self.env_fps == self.model_fps:
self.shapes.update(input_shapes)
else:
for k in input_shapes:
shape = list(input_shapes[k])
if 'img' in k:
n_channels = shape[1] // self.n_frames_input
shape[1] = (self.env_fps // self.model_fps + (self.n_frames_input - 1)) * n_channels
else:
shape[1] = (self.env_fps // self.model_fps) * shape[1]
self.shapes[k] = tuple(shape)
def reset(self) -> None:
self.q = {k: np.zeros(self.shapes[k], dtype=self.dtypes[k]) for k in self.dtypes.keys()}
def enqueue(self, inputs:dict[str, np.ndarray]) -> None:
for k in inputs.keys():
if inputs[k].dtype != self.dtypes[k]:
raise ValueError(f'supplied input <{k}({inputs[k].dtype})> has wrong dtype, expected {self.dtypes[k]}')
input_shape = list(self.shapes[k])
input_shape[1] = -1
single_input = inputs[k].reshape(tuple(input_shape))
sz = single_input.shape[1]
self.q[k][:,:-sz] = self.q[k][:,sz:]
self.q[k][:,-sz:] = single_input
def get(self, *names) -> dict[str, np.ndarray]:
if self.env_fps == self.model_fps:
return {k: self.q[k] for k in names}
else:
out = {}
for k in names:
shape = self.shapes[k]
if 'img' in k:
n_channels = shape[1] // (self.env_fps // self.model_fps + (self.n_frames_input - 1))
out[k] = np.concatenate([self.q[k][:, s:s+n_channels] for s in np.linspace(0, shape[1] - n_channels, self.n_frames_input, dtype=int)], axis=1)
elif 'pulse' in k:
# any pulse within interval counts
out[k] = self.q[k].reshape((shape[0], shape[1] * self.model_fps // self.env_fps, self.env_fps // self.model_fps, -1)).max(axis=2)
else:
idxs = np.arange(-1, -shape[1], -self.env_fps // self.model_fps)[::-1]
out[k] = self.q[k][:, idxs]
return out
class ModelState:
inputs: dict[str, np.ndarray]
output: np.ndarray
prev_desire: np.ndarray # for tracking the rising edge of the pulse
def __init__(self):
with open(VISION_METADATA_PATH, 'rb') as f:
vision_metadata = pickle.load(f)
self.vision_input_shapes = vision_metadata['input_shapes']
self.vision_input_names = list(self.vision_input_shapes.keys())
self.vision_output_slices = vision_metadata['output_slices']
vision_output_size = vision_metadata['output_shapes']['outputs'][1]
with open(POLICY_METADATA_PATH, 'rb') as f:
policy_metadata = pickle.load(f)
self.policy_input_shapes = policy_metadata['input_shapes']
self.policy_output_slices = policy_metadata['output_slices']
policy_output_size = policy_metadata['output_shapes']['outputs'][1]
self.prev_desire = np.zeros(ModelConstants.DESIRE_LEN, dtype=np.float32)
# policy inputs
self.numpy_inputs = {k: np.zeros(self.policy_input_shapes[k], dtype=np.float32) for k in self.policy_input_shapes}
self.full_input_queues = InputQueues(ModelConstants.MODEL_CONTEXT_FREQ, ModelConstants.MODEL_RUN_FREQ, ModelConstants.N_FRAMES)
for k in ['desire_pulse', 'features_buffer']:
self.full_input_queues.update_dtypes_and_shapes({k: self.numpy_inputs[k].dtype}, {k: self.numpy_inputs[k].shape})
self.full_input_queues.reset()
self.img_queues = {'img': Tensor.zeros(IMG_QUEUE_SHAPE, dtype='uint8').contiguous().realize(),
'big_img': Tensor.zeros(IMG_QUEUE_SHAPE, dtype='uint8').contiguous().realize()}
self.full_frames : dict[str, Tensor] = {}
self._blob_cache : dict[int, Tensor] = {}
self.transforms_np = {k: np.zeros((3,3), dtype=np.float32) for k in self.img_queues}
self.transforms = {k: Tensor(v, device='NPY').realize() for k, v in self.transforms_np.items()}
self.vision_output = np.zeros(vision_output_size, dtype=np.float32)
self.policy_inputs = {k: Tensor(v, device='NPY').realize() for k,v in self.numpy_inputs.items()}
self.policy_output = np.zeros(policy_output_size, dtype=np.float32)
self.parser = Parser()
self.frame_buf_params : dict[str, tuple[int, int, int, int]] = {}
self.update_imgs = None
self.vision_run = pickle.loads(read_file_chunked(str(VISION_PKL_PATH)))
self.policy_run = pickle.loads(read_file_chunked(str(POLICY_PKL_PATH)))
def slice_outputs(self, model_outputs: np.ndarray, output_slices: dict[str, slice]) -> dict[str, np.ndarray]:
parsed_model_outputs = {k: model_outputs[np.newaxis, v] for k,v in output_slices.items()}
return parsed_model_outputs
def run(self, bufs: dict[str, VisionBuf], transforms: dict[str, np.ndarray],
inputs: dict[str, np.ndarray], prepare_only: bool) -> dict[str, np.ndarray] | None:
# Model decides when action is completed, so desire input is just a pulse triggered on rising edge
inputs['desire_pulse'][0] = 0
new_desire = np.where(inputs['desire_pulse'] - self.prev_desire > .99, inputs['desire_pulse'], 0)
self.prev_desire[:] = inputs['desire_pulse']
if self.update_imgs is None:
for key in bufs.keys():
w, h = bufs[key].width, bufs[key].height
self.frame_buf_params[key] = get_nv12_info(w, h)
warp_path = MODELS_DIR / f'warp_{w}x{h}_tinygrad.pkl'
with open(warp_path, "rb") as f:
self.update_imgs = pickle.load(f)
for key in bufs.keys():
ptr = bufs[key].data.ctypes.data
yuv_size = self.frame_buf_params[key][3]
# There is a ringbuffer of imgs, just cache tensors pointing to all of them
cache_key = (key, ptr)
if cache_key not in self._blob_cache:
self._blob_cache[cache_key] = Tensor.from_blob(ptr, (yuv_size,), dtype='uint8')
self.full_frames[key] = self._blob_cache[cache_key]
for key in bufs.keys():
self.transforms_np[key][:,:] = transforms[key][:,:]
out = self.update_imgs(self.img_queues['img'], self.full_frames['img'], self.transforms['img'],
self.img_queues['big_img'], self.full_frames['big_img'], self.transforms['big_img'])
self.img_queues['img'], self.img_queues['big_img'] = out[0].realize(), out[2].realize()
vision_inputs = {'img': out[1], 'big_img': out[3]}
if prepare_only:
return None
self.vision_output = self.vision_run(**vision_inputs).contiguous().realize().uop.base.buffer.numpy().flatten()
vision_outputs_dict = self.parser.parse_vision_outputs(self.slice_outputs(self.vision_output, self.vision_output_slices))
self.full_input_queues.enqueue({'features_buffer': vision_outputs_dict['hidden_state'], 'desire_pulse': new_desire})
for k in ['desire_pulse', 'features_buffer']:
self.numpy_inputs[k][:] = self.full_input_queues.get(k)[k]
self.numpy_inputs['traffic_convention'][:] = inputs['traffic_convention']
self.policy_output = self.policy_run(**self.policy_inputs).contiguous().realize().uop.base.buffer.numpy().flatten()
policy_outputs_dict = self.parser.parse_policy_outputs(self.slice_outputs(self.policy_output, self.policy_output_slices))
combined_outputs_dict = {**vision_outputs_dict, **policy_outputs_dict}
if SEND_RAW_PRED:
combined_outputs_dict['raw_pred'] = np.concatenate([self.vision_output.copy(), self.policy_output.copy()])
return combined_outputs_dict
def main(demo=False):
cloudlog.warning("modeld init")
if not USBGPU:
# USB GPU currently saturates a core so can't do this yet,
# also need to move the aux USB interrupts for good timings
config_realtime_process(7, 54)
st = time.monotonic()
cloudlog.warning("loading model")
model = ModelState()
cloudlog.warning(f"models loaded in {time.monotonic() - st:.1f}s, modeld starting")
# visionipc clients
while True:
available_streams = VisionIpcClient.available_streams("camerad", block=False)
if available_streams:
use_extra_client = VisionStreamType.VISION_STREAM_WIDE_ROAD in available_streams and VisionStreamType.VISION_STREAM_ROAD in available_streams
main_wide_camera = VisionStreamType.VISION_STREAM_ROAD not in available_streams
break
time.sleep(.1)
vipc_client_main_stream = VisionStreamType.VISION_STREAM_WIDE_ROAD if main_wide_camera else VisionStreamType.VISION_STREAM_ROAD
vipc_client_main = VisionIpcClient("camerad", vipc_client_main_stream, True)
vipc_client_extra = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_WIDE_ROAD, False)
cloudlog.warning(f"vision stream set up, main_wide_camera: {main_wide_camera}, use_extra_client: {use_extra_client}")
while not vipc_client_main.connect(False):
time.sleep(0.1)
while use_extra_client and not vipc_client_extra.connect(False):
time.sleep(0.1)
cloudlog.warning(f"connected main cam with buffer size: {vipc_client_main.buffer_len} ({vipc_client_main.width} x {vipc_client_main.height})")
if use_extra_client:
cloudlog.warning(f"connected extra cam with buffer size: {vipc_client_extra.buffer_len} ({vipc_client_extra.width} x {vipc_client_extra.height})")
# messaging
pm = PubMaster(["modelV2", "drivingModelData", "cameraOdometry"])
sm = SubMaster(["deviceState", "carState", "roadCameraState", "liveCalibration", "driverMonitoringState", "carControl", "liveDelay"])
publish_state = PublishState()
params = Params()
# setup filter to track dropped frames
frame_dropped_filter = FirstOrderFilter(0., 10., 1. / ModelConstants.MODEL_RUN_FREQ)
frame_id = 0
last_vipc_frame_id = 0
run_count = 0
model_transform_main = np.zeros((3, 3), dtype=np.float32)
model_transform_extra = np.zeros((3, 3), dtype=np.float32)
live_calib_seen = False
buf_main, buf_extra = None, None
meta_main = FrameMeta()
meta_extra = FrameMeta()
if demo:
CP = get_demo_car_params()
else:
CP = messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams)
cloudlog.info("modeld got CarParams: %s", CP.brand)
# TODO this needs more thought, use .2s extra for now to estimate other delays
# TODO Move smooth seconds to action function
long_delay = CP.longitudinalActuatorDelay + LONG_SMOOTH_SECONDS
prev_action = log.ModelDataV2.Action()
DH = DesireHelper()
while True:
# Keep receiving frames until we are at least 1 frame ahead of previous extra frame
while meta_main.timestamp_sof < meta_extra.timestamp_sof + 25000000:
buf_main = vipc_client_main.recv()
meta_main = FrameMeta(vipc_client_main)
if buf_main is None:
break
if buf_main is None:
cloudlog.debug("vipc_client_main no frame")
continue
if use_extra_client:
# Keep receiving extra frames until frame id matches main camera
while True:
buf_extra = vipc_client_extra.recv()
meta_extra = FrameMeta(vipc_client_extra)
if buf_extra is None or meta_main.timestamp_sof < meta_extra.timestamp_sof + 25000000:
break
if buf_extra is None:
cloudlog.debug("vipc_client_extra no frame")
continue
if abs(meta_main.timestamp_sof - meta_extra.timestamp_sof) > 10000000:
cloudlog.error(f"frames out of sync! main: {meta_main.frame_id} ({meta_main.timestamp_sof / 1e9:.5f}),\
extra: {meta_extra.frame_id} ({meta_extra.timestamp_sof / 1e9:.5f})")
else:
# Use single camera
buf_extra = buf_main
meta_extra = meta_main
sm.update(0)
desire = DH.desire
is_rhd = sm["driverMonitoringState"].isRHD
frame_id = sm["roadCameraState"].frameId
v_ego = max(sm["carState"].vEgo, 0.)
lat_delay = sm["liveDelay"].lateralDelay + LAT_SMOOTH_SECONDS
if sm.updated["liveCalibration"] and sm.seen['roadCameraState'] and sm.seen['deviceState']:
device_from_calib_euler = np.array(sm["liveCalibration"].rpyCalib, dtype=np.float32)
dc = DEVICE_CAMERAS[(str(sm['deviceState'].deviceType), str(sm['roadCameraState'].sensor))]
model_transform_main = get_warp_matrix(device_from_calib_euler, dc.ecam.intrinsics if main_wide_camera else dc.fcam.intrinsics, False).astype(np.float32)
model_transform_extra = get_warp_matrix(device_from_calib_euler, dc.ecam.intrinsics, True).astype(np.float32)
live_calib_seen = True
traffic_convention = np.zeros(2)
traffic_convention[int(is_rhd)] = 1
vec_desire = np.zeros(ModelConstants.DESIRE_LEN, dtype=np.float32)
if desire >= 0 and desire < ModelConstants.DESIRE_LEN:
vec_desire[desire] = 1
# tracked dropped frames
vipc_dropped_frames = max(0, meta_main.frame_id - last_vipc_frame_id - 1)
frames_dropped = frame_dropped_filter.update(min(vipc_dropped_frames, 10))
if run_count < 10: # let frame drops warm up
frame_dropped_filter.x = 0.
frames_dropped = 0.
run_count = run_count + 1
frame_drop_ratio = frames_dropped / (1 + frames_dropped)
prepare_only = vipc_dropped_frames > 0
if prepare_only:
cloudlog.error(f"skipping model eval. Dropped {vipc_dropped_frames} frames")
bufs = {name: buf_extra if 'big' in name else buf_main for name in model.vision_input_names}
transforms = {name: model_transform_extra if 'big' in name else model_transform_main for name in model.vision_input_names}
inputs:dict[str, np.ndarray] = {
'desire_pulse': vec_desire,
'traffic_convention': traffic_convention,
}
mt1 = time.perf_counter()
model_output = model.run(bufs, transforms, inputs, prepare_only)
mt2 = time.perf_counter()
model_execution_time = mt2 - mt1
if model_output is not None:
modelv2_send = messaging.new_message('modelV2')
drivingdata_send = messaging.new_message('drivingModelData')
posenet_send = messaging.new_message('cameraOdometry')
action = get_action_from_model(model_output, prev_action, lat_delay + DT_MDL, long_delay + DT_MDL, v_ego)
prev_action = action
fill_model_msg(drivingdata_send, modelv2_send, model_output, action,
publish_state, meta_main.frame_id, meta_extra.frame_id, frame_id,
frame_drop_ratio, meta_main.timestamp_eof, model_execution_time, live_calib_seen)
desire_state = modelv2_send.modelV2.meta.desireState
l_lane_change_prob = desire_state[log.Desire.laneChangeLeft]
r_lane_change_prob = desire_state[log.Desire.laneChangeRight]
lane_change_prob = l_lane_change_prob + r_lane_change_prob
DH.update(sm['carState'], sm['carControl'].latActive, lane_change_prob)
modelv2_send.modelV2.meta.laneChangeState = DH.lane_change_state
modelv2_send.modelV2.meta.laneChangeDirection = DH.lane_change_direction
drivingdata_send.drivingModelData.meta.laneChangeState = DH.lane_change_state
drivingdata_send.drivingModelData.meta.laneChangeDirection = DH.lane_change_direction
fill_pose_msg(posenet_send, model_output, meta_main.frame_id, vipc_dropped_frames, meta_main.timestamp_eof, live_calib_seen)
pm.send('modelV2', modelv2_send)
pm.send('drivingModelData', drivingdata_send)
pm.send('cameraOdometry', posenet_send)
last_vipc_frame_id = meta_main.frame_id
if __name__ == "__main__":
try:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--demo', action='store_true', help='A boolean for demo mode.')
args = parser.parse_args()
main(demo=args.demo)
except KeyboardInterrupt:
cloudlog.warning("got SIGINT")
@@ -1,66 +0,0 @@
## Neural networks in openpilot
To view the architecture of the ONNX networks, you can use [netron](https://netron.app/)
## Driving Model (vision model + temporal policy model)
### Vision inputs (Full size: 799906 x float32)
* **image stream**
* Two consecutive images (256 * 512 * 3 in RGB) recorded at 20 Hz : 393216 = 2 * 6 * 128 * 256
* Each 256 * 512 image is represented in YUV420 with 6 channels : 6 * 128 * 256
* Channels 0,1,2,3 represent the full-res Y channel and are represented in numpy as Y[::2, ::2], Y[::2, 1::2], Y[1::2, ::2], and Y[1::2, 1::2]
* Channel 4 represents the half-res U channel
* Channel 5 represents the half-res V channel
* **wide image stream**
* Two consecutive images (256 * 512 * 3 in RGB) recorded at 20 Hz : 393216 = 2 * 6 * 128 * 256
* Each 256 * 512 image is represented in YUV420 with 6 channels : 6 * 128 * 256
* Channels 0,1,2,3 represent the full-res Y channel and are represented in numpy as Y[::2, ::2], Y[::2, 1::2], Y[1::2, ::2], and Y[1::2, 1::2]
* Channel 4 represents the half-res U channel
* Channel 5 represents the half-res V channel
### Policy inputs
* **desire**
* one-hot encoded buffer to command model to execute certain actions, bit needs to be sent for the past 5 seconds (at 20FPS) : 100 * 8
* **traffic convention**
* one-hot encoded vector to tell model whether traffic is right-hand or left-hand traffic : 2
* **lateral control params**
* speed and steering delay for predicting the desired curvature: 2
* **previous desired curvatures**
* vector of previously predicted desired curvatures: 100 * 1
* **feature buffer**
* a buffer of intermediate features including the current feature to form a 5 seconds temporal context (at 20FPS) : 100 * 512
### Driving Model output format (Full size: XXX x float32)
Refer to **slice_outputs** and **parse_vision_outputs/parse_policy_outputs** in modeld.
## Driver Monitoring Model
* .onnx model can be run with onnx runtimes
* .dlc file is a pre-quantized model and only runs on qualcomm DSPs
### input format
* single image W = 1440 H = 960 luminance channel (Y) from the planar YUV420 format:
* full input size is 1440 * 960 = 1382400
* normalized ranging from 0.0 to 1.0 in float32 (onnx runner) or ranging from 0 to 255 in uint8 (snpe runner)
* camera calibration angles (roll, pitch, yaw) from liveCalibration: 3 x float32 inputs
### output format
* 84 x float32 outputs = 2 + 41 * 2 ([parsing example](https://github.com/commaai/openpilot/blob/22ce4e17ba0d3bfcf37f8255a4dd1dc683fe0c38/selfdrive/modeld/models/dmonitoring.cc#L33))
* for each person in the front seats (2 * 41)
* face pose: 12 = 6 + 6
* face orientation [pitch, yaw, roll] in camera frame: 3
* face position [dx, dy] relative to image center: 2
* normalized face size: 1
* standard deviations for above outputs: 6
* face visible probability: 1
* eyes: 20 = (8 + 1) + (8 + 1) + 1 + 1
* eye position and size, and their standard deviations: 8
* eye visible probability: 1
* eye closed probability: 1
* wearing sunglasses probability: 1
* face occluded probability: 1
* touching wheel probability: 1
* paying attention probability: 1
* (deprecated) distracted probabilities: 2
* using phone probability: 1
* distracted probability: 1
* common outputs 1
* left hand drive probability: 1
@@ -1,124 +0,0 @@
import numpy as np
from openpilot.selfdrive.modeld.constants import ModelConstants
def safe_exp(x, out=None):
# -11 is around 10**14, more causes float16 overflow
return np.exp(np.clip(x, -np.inf, 11), out=out)
def sigmoid(x):
return 1. / (1. + safe_exp(-x))
def softmax(x, axis=-1):
x -= np.max(x, axis=axis, keepdims=True)
if x.dtype == np.float32 or x.dtype == np.float64:
safe_exp(x, out=x)
else:
x = safe_exp(x)
x /= np.sum(x, axis=axis, keepdims=True)
return x
class Parser:
def __init__(self, ignore_missing=False):
self.ignore_missing = ignore_missing
def check_missing(self, outs, name):
missing = name not in outs
if missing and not self.ignore_missing:
raise ValueError(f"Missing output {name}")
return missing
def parse_categorical_crossentropy(self, name, outs, out_shape=None):
if self.check_missing(outs, name):
return
raw = outs[name]
if out_shape is not None:
raw = raw.reshape((raw.shape[0],) + out_shape)
outs[name] = softmax(raw, axis=-1)
def parse_binary_crossentropy(self, name, outs):
if self.check_missing(outs, name):
return
raw = outs[name]
outs[name] = sigmoid(raw)
def parse_mdn(self, name, outs, in_N=0, out_N=1, out_shape=None):
if self.check_missing(outs, name):
return
raw = outs[name]
raw = raw.reshape((raw.shape[0], max(in_N, 1), -1))
n_values = (raw.shape[2] - out_N)//2
pred_mu = raw[:,:,:n_values]
pred_std = safe_exp(raw[:,:,n_values: 2*n_values])
if in_N > 1:
weights = np.zeros((raw.shape[0], in_N, out_N), dtype=raw.dtype)
for i in range(out_N):
weights[:,:,i - out_N] = softmax(raw[:,:,i - out_N], axis=-1)
if out_N == 1:
for fidx in range(weights.shape[0]):
idxs = np.argsort(weights[fidx][:,0])[::-1]
weights[fidx] = weights[fidx][idxs]
pred_mu[fidx] = pred_mu[fidx][idxs]
pred_std[fidx] = pred_std[fidx][idxs]
full_shape = tuple([raw.shape[0], in_N] + list(out_shape))
outs[name + '_weights'] = weights
outs[name + '_hypotheses'] = pred_mu.reshape(full_shape)
outs[name + '_stds_hypotheses'] = pred_std.reshape(full_shape)
pred_mu_final = np.zeros((raw.shape[0], out_N, n_values), dtype=raw.dtype)
pred_std_final = np.zeros((raw.shape[0], out_N, n_values), dtype=raw.dtype)
for fidx in range(weights.shape[0]):
for hidx in range(out_N):
idxs = np.argsort(weights[fidx,:,hidx])[::-1]
pred_mu_final[fidx, hidx] = pred_mu[fidx, idxs[0]]
pred_std_final[fidx, hidx] = pred_std[fidx, idxs[0]]
else:
pred_mu_final = pred_mu
pred_std_final = pred_std
if out_N > 1:
final_shape = tuple([raw.shape[0], out_N] + list(out_shape))
else:
final_shape = tuple([raw.shape[0],] + list(out_shape))
outs[name] = pred_mu_final.reshape(final_shape)
outs[name + '_stds'] = pred_std_final.reshape(final_shape)
def is_mhp(self, outs, name, shape):
if self.check_missing(outs, name):
return False
if outs[name].shape[1] == 2 * shape:
return False
return True
def parse_vision_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]:
self.parse_mdn('pose', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,))
self.parse_mdn('wide_from_device_euler', outs, in_N=0, out_N=0, out_shape=(ModelConstants.WIDE_FROM_DEVICE_WIDTH,))
self.parse_mdn('road_transform', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,))
self.parse_mdn('lane_lines', outs, in_N=0, out_N=0, out_shape=(ModelConstants.NUM_LANE_LINES,ModelConstants.IDX_N,ModelConstants.LANE_LINES_WIDTH))
self.parse_mdn('road_edges', outs, in_N=0, out_N=0, out_shape=(ModelConstants.NUM_ROAD_EDGES,ModelConstants.IDX_N,ModelConstants.LANE_LINES_WIDTH))
self.parse_binary_crossentropy('lane_lines_prob', outs)
self.parse_categorical_crossentropy('desire_pred', outs, out_shape=(ModelConstants.DESIRE_PRED_LEN,ModelConstants.DESIRE_PRED_WIDTH))
self.parse_binary_crossentropy('meta', outs)
self.parse_binary_crossentropy('lead_prob', outs)
lead_mhp = self.is_mhp(outs, 'lead', ModelConstants.LEAD_MHP_SELECTION * ModelConstants.LEAD_TRAJ_LEN * ModelConstants.LEAD_WIDTH)
lead_in_N, lead_out_N = (ModelConstants.LEAD_MHP_N, ModelConstants.LEAD_MHP_SELECTION) if lead_mhp else (0, 0)
lead_out_shape = (ModelConstants.LEAD_TRAJ_LEN, ModelConstants.LEAD_WIDTH) if lead_mhp else \
(ModelConstants.LEAD_MHP_SELECTION, ModelConstants.LEAD_TRAJ_LEN, ModelConstants.LEAD_WIDTH)
self.parse_mdn('lead', outs, in_N=lead_in_N, out_N=lead_out_N, out_shape=lead_out_shape)
return outs
def parse_policy_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]:
plan_mhp = self.is_mhp(outs, 'plan', ModelConstants.IDX_N * ModelConstants.PLAN_WIDTH)
plan_in_N, plan_out_N = (ModelConstants.PLAN_MHP_N, ModelConstants.PLAN_MHP_SELECTION) if plan_mhp else (0, 0)
self.parse_mdn('plan', outs, in_N=plan_in_N, out_N=plan_out_N, out_shape=(ModelConstants.IDX_N, ModelConstants.PLAN_WIDTH))
if 'planplus' in outs:
self.parse_mdn('planplus', outs, in_N=0, out_N=0, out_shape=(ModelConstants.IDX_N, ModelConstants.PLAN_WIDTH))
self.parse_categorical_crossentropy('desire_state', outs, out_shape=(ModelConstants.DESIRE_PRED_WIDTH,))
return outs
def parse_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]:
outs = self.parse_vision_outputs(outs)
outs = self.parse_policy_outputs(outs)
return outs
-79
View File
@@ -1,79 +0,0 @@
{
"driving_vision.onnx": {
"inputs": {
"img": {
"shape": [
1,
12,
128,
256
],
"type": "tensor(uint8)"
},
"big_img": {
"shape": [
1,
12,
128,
256
],
"type": "tensor(uint8)"
}
},
"outputs": {
"outputs": {
"shape": [
1,
1576
],
"type": "tensor(float16)"
}
},
"metadata": {
"output_slices": "gASVQAEAAAAAAAB9lCiMBG1ldGGUjAhidWlsdGluc5SMBXNsaWNllJOUSwBLN06HlFKUjAtkZXNp\ncmVfcHJlZJRoBEs3S1dOh5RSlIwEcG9zZZRoBEtXS2NOh5RSlIwWd2lkZV9mcm9tX2RldmljZV9l\ndWxlcpRoBEtjS2lOh5RSlIwOcm9hZF90cmFuc2Zvcm2UaARLaUt1ToeUUpSMCmxhbmVfbGluZXOU\naARLdU2FAk6HlFKUjA9sYW5lX2xpbmVzX3Byb2KUaARNhQJNjQJOh5RSlIwKcm9hZF9lZGdlc5Ro\nBE2NAk2VA06HlFKUjARsZWFklGgETZUDTSUEToeUUpSMCWxlYWRfcHJvYpRoBE0lBE0oBE6HlFKU\njAxoaWRkZW5fc3RhdGWUaARNKARNKAZOh5RSlIwDcGFklGgESwBOToeUUpR1Lg==\n",
"model_checkpoint": "6a7d09ad-bcc9-43bc-916d-29287e60cee2/200"
},
"same_slice_metadata_as_pop_v2": true
},
"driving_policy.onnx": {
"inputs": {
"desire_pulse": {
"shape": [
1,
25,
8
],
"type": "tensor(float16)"
},
"traffic_convention": {
"shape": [
1,
2
],
"type": "tensor(float16)"
},
"features_buffer": {
"shape": [
1,
25,
512
],
"type": "tensor(float16)"
}
},
"outputs": {
"outputs": {
"shape": [
1,
1000
],
"type": "tensor(float16)"
}
},
"metadata": {
"output_slices": "gASVWgAAAAAAAAB9lCiMBHBsYW6UjAhidWlsdGluc5SMBXNsaWNllJOUSwBN3gNOh5RSlIwMZGVz\naXJlX3N0YXRllGgETd4DTeYDToeUUpSMA3BhZJRoBEr+////Tk6HlFKUdS4=\n",
"model_checkpoint": "a27b3122-733e-4a65-938b-acfebebbe5e8/100"
},
"same_slice_metadata_as_pop_v2": true
}
}
-1
View File
@@ -1 +0,0 @@
build/
-388
View File
@@ -1,388 +0,0 @@
// Passive camera experiment. Does not create controllers or write vehicle inputs.
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <atomic>
#include "SPF_Plugin.h"
#include "SPF_Camera_API.h"
#include "SPF_GameConsole_API.h"
#include "SPF_Manifest_API.h"
#include "SPF_Config_API.h"
#include "SPF_Logger_API.h"
#include "rotation.h"
#include "motion.h"
#include "pose_probe.h"
#include "render_view.h"
#include "build_guard.h"
#include "head_telemetry.h"
#include "render_trace.h"
namespace {
constexpr const char* name = "ForwardCamera";
const SPF_Core_API* core = nullptr;
SPF_Logger_API* logger = nullptr;
SPF_Logger_Handle* log_handle = nullptr;
SPF_Config_API* config = nullptr;
SPF_Config_Handle* settings = nullptr;
forward_camera::HeadTelemetry head_telemetry;
bool have_head_center=false;
forward_camera::Vec head_center{};
bool applied = false;
ULONGLONG next_log = 0;
forward_camera::Compensation previous{};
bool have_previous = false;
std::atomic_flag updating = ATOMIC_FLAG_INIT;
using ProjectionFn = void (*)(void*, float, float);
ProjectionFn original_projection = nullptr;
std::atomic<unsigned long> projection_calls{0};
bool timing_attempted = false;
using ViewFn=forward_camera::Quat* (*)(forward_camera::ViewInfo*,forward_camera::Quat*,const forward_camera::Quat*,const float*);
ViewFn original_view=nullptr;
bool render_attempted=false;
std::atomic_bool render_ready{false},render_applied{false};
std::atomic<unsigned long> render_matches{0};
std::atomic<unsigned long> translation_matches{0};
std::atomic<float> head_delta_x{0},head_delta_y{0},head_delta_z{0};
forward_camera::HeadMotion head_motion;
forward_camera::RenderTrace render_trace;
double seconds() {
LARGE_INTEGER counter{}, frequency{};
QueryPerformanceCounter(&counter); QueryPerformanceFrequency(&frequency);
return static_cast<double>(counter.QuadPart)/static_cast<double>(frequency.QuadPart);
}
void on_update();
void log(const char* text);
bool flag(const char* key, bool fallback);
double value(const char* key,double fallback);
void drain_render_trace() {
forward_camera::RenderTraceSample s{};
if(!render_trace.take(s)) return;
char text[2600];
std::snprintf(text,sizeof(text),
"RENDER_POSE host_ms=%llu generation=%llu camera_valid=%d camera_type=%d outside_valid=%d outside=%d spf_valid=%d spf_roll_valid=%d spf_rad=%.7f,%.7f,%.7f sdk_valid=%d sdk_timestamp=%llu sdk_speed_mps=%.6f sdk_park_brake=%d sdk_paused=%d sdk_rad=%.7f,%.7f,%.7f sdk_position=%.5f,%.5f,%.5f seat_valid=%d seat=%.5f,%.5f,%.5f base_wxyz=%.7f,%.7f,%.7f,%.7f output_before_wxyz=%.7f,%.7f,%.7f,%.7f output_after_wxyz=%.7f,%.7f,%.7f,%.7f offset_before=%.5f,%.5f,%.5f offset_after=%.5f,%.5f,%.5f applied=%d translation=%d; observation only",
static_cast<unsigned long long>(s.host_ms),static_cast<unsigned long long>(s.generation),
s.camera_valid,s.camera_type,s.outside_valid,s.outside,s.spf_valid,s.spf_roll_valid,s.spf_yaw,s.spf_pitch,s.spf_roll,
s.sdk_valid,static_cast<unsigned long long>(s.sdk.timestamp),s.sdk.speed_mps,s.sdk.park_brake,s.sdk.paused,s.sdk.yaw,s.sdk.pitch,s.sdk.roll,
s.sdk.position.x,s.sdk.position.y,s.sdk.position.z,s.seat_valid,s.seat.x,s.seat.y,s.seat.z,
s.base.w,s.base.x,s.base.y,s.base.z,s.output_before.w,s.output_before.x,s.output_before.y,s.output_before.z,
s.output_after.w,s.output_after.x,s.output_after.y,s.output_after.z,
s.offset_before.x,s.offset_before.y,s.offset_before.z,s.offset_after.x,s.offset_after.y,s.offset_after.z,
s.applied,s.translation);
const auto used=std::strlen(text);
std::snprintf(text+used,sizeof(text)-used,
" viewport=%.9f,%.9f,%.9f,%.9f frustum_fov=%.6f,%.6f frustum_subrect_raw=%.9f,%.9f,%.9f,%.9f; subrect ABI unverified",
s.viewport[0],s.viewport[1],s.viewport[2],s.viewport[3],s.frustum_fov[0],s.frustum_fov[1],
s.frustum_subrect[0],s.frustum_subrect[1],s.frustum_subrect[2],s.frustum_subrect[3]);
log(text);
}
struct TraceScope {
bool selected=false;
forward_camera::RenderTraceSample sample{};
forward_camera::ViewInfo* view=nullptr;
forward_camera::Quat* output=nullptr;
~TraceScope() {
if(!selected) return;
sample.offset_after={view->offset[0],view->offset[1],view->offset[2]};
sample.output_after=*output;
render_trace.submit(sample);
}
};
forward_camera::Quat* monitor_view(forward_camera::ViewInfo* view,forward_camera::Quat* output,
const forward_camera::Quat* base,const float* first_fov) {
// ABI confirmed at both callers and the complete function in this exact game build.
auto* result=original_view(view,output,base,first_fov);
TraceScope trace{};
const auto now=GetTickCount64();
uint64_t generation=0;
forward_camera::HeadSample trace_head{};
const bool trace_enabled=flag("settings.enabled",false) && flag("settings.render_hook",false) &&
flag("settings.render_pose_trace",false);
const bool trace_road=view && output && base && result==output && core && core->camera &&
forward_camera::road_viewport(*view);
const bool trace_sdk_valid=trace_enabled && trace_road && head_telemetry.read(trace_head);
if(view && output && base && result==output && core && core->camera &&
render_trace.select(now,trace_enabled,trace_road,forward_camera::trace_parked(trace_sdk_valid,trace_head),generation)) {
trace.selected=true;trace.view=view;trace.output=output;
std::memcpy(trace.sample.viewport,view->rect,sizeof(view->rect));
std::memcpy(trace.sample.frustum_fov,view->fov,sizeof(view->fov));
std::memcpy(trace.sample.frustum_subrect,view->subrect,sizeof(view->subrect));
auto& s=trace.sample;s.host_ms=now;s.generation=generation;s.base=*base;s.output_before=*output;
s.offset_before={view->offset[0],view->offset[1],view->offset[2]};
const auto camera=core->camera;SPF_CameraType type{};float y=0,p=0,r=0,sx=0,sy=0,sz=0;
s.camera_valid=camera->Cam_GetCurrentCamera && camera->Cam_GetCurrentCamera(&type);
if(s.camera_valid) s.camera_type=int(type);
s.outside_valid=camera->Cam_GetInteriorOutside && camera->Cam_GetInteriorOutside(&s.outside);
s.spf_valid=camera->Cam_GetInteriorHeadRot && camera->Cam_GetInteriorHeadRot(&y,&p) &&
std::isfinite(y) && std::isfinite(p);
s.spf_roll_valid=camera->Cam_GetInteriorRoll && camera->Cam_GetInteriorRoll(&r) && std::isfinite(r);
s.spf_yaw=y;s.spf_pitch=p;s.spf_roll=r/forward_camera::degrees;
s.seat_valid=camera->Cam_GetInteriorSeatPos && camera->Cam_GetInteriorSeatPos(&sx,&sy,&sz) &&
std::isfinite(sx) && std::isfinite(sy) && std::isfinite(sz);
s.seat={sx,sy,sz};s.sdk_valid=trace_sdk_valid;s.sdk=trace_head;
}
if (!render_ready.load() || !flag("settings.enabled",false) || !flag("settings.render_hook",false) ||
!view || !output || !base || result!=output || !forward_camera::matches_road(*view) ||
!core || !core->camera) return result;
SPF_CameraType active{};float yaw=0,pitch=0,roll=0;
const auto c=core->camera;
if (!c->Cam_GetCurrentCamera || !c->Cam_GetInteriorHeadRot ||
!c->Cam_GetCurrentCamera(&active) || active!=SPF_CAMERA_INTERIOR ||
!c->Cam_GetInteriorHeadRot(&yaw,&pitch) ||
(c->Cam_GetInteriorRoll && !c->Cam_GetInteriorRoll(&roll))) return result;
forward_camera::Vec offset{value("settings.offset_x",0),value("settings.offset_y",-1.2),value("settings.offset_z",-2.5)};
if (flag("settings.cancel_head_translation",false)) {
forward_camera::HeadSample sample{};
float sx=0,sy=0,sz=0;
if(head_telemetry.read(sample)) {
bool seat_valid=c->Cam_GetInteriorSeatPos && c->Cam_GetInteriorSeatPos(&sx,&sy,&sz) &&
std::isfinite(sx) && std::isfinite(sy) && std::isfinite(sz);
if(!have_head_center && std::abs(sample.yaw)<5/forward_camera::degrees &&
std::abs(sample.pitch)<5/forward_camera::degrees) {
head_center=sample.position;have_head_center=true;
}
if (!seat_valid && have_head_center) {
sx=float(head_center.x);sy=float(head_center.y);sz=float(head_center.z);seat_valid=true;
}
const auto h=sample.position;
forward_camera::Vec corrected{};
if (seat_valid && forward_camera::cancel_translation(offset,h,{sx,sy,sz},corrected)) {
offset=corrected;++translation_matches;
trace.sample.translation=true;
head_delta_x.store(float(h.x-sx));head_delta_y.store(float(h.y-sy));head_delta_z.store(float(h.z-sz));
}
}
}
if (forward_camera::fix_view(*view,*base,*output,yaw,pitch,roll/forward_camera::degrees,
value("settings.pitch_degrees",-5.049066)/forward_camera::degrees,offset)) {
render_applied.store(true);++render_matches;
trace.sample.applied=true;
}
return result;
}
void probe_projection(void* object,float width,float height,bool after) {
// A bounded read-only trace. Values are candidates, not a verified memory ABI.
static void* objects[8]{};
static double next[8]{};
static double started=0;
static bool done=false;
static thread_local int selected=-1;
if (!flag("settings.pose_probe",false)) return;
const double now=seconds();
if (!started) started=now;
if (now-started>60) {
if (!done) { log("POSE probe complete after 60 seconds; no camera memory was changed."); done=true; }
return;
}
if (!after) {
selected=-1;
int i=0;
for (;i<8 && objects[i] && objects[i]!=object;++i) {}
if (i==8 || now<next[i]) return;
objects[i]=object; next[i]=now+0.10; selected=i;
} else if (selected<0) return;
forward_camera::PoseSnapshot snapshot{};
if (!forward_camera::read_pose_candidate(object,&snapshot)) return;
float yaw=0,pitch=0;
if (!core || !core->camera || !core->camera->Cam_GetInteriorHeadRot ||
!core->camera->Cam_GetInteriorHeadRot(&yaw,&pitch)) return;
const auto& r=snapshot.raw;
char text[640];
std::snprintf(text,sizeof(text),
"POSE t=%.6f object=%p stage=%s size=%.3f,%.3f head=%.7f,%.7f raw=%.7g,%.7g,%.7g,%.7g,%.7g,%.7g,%.7g,%.7g,%.7g,%.7g,%.7g,%.7g,%.7g,%.7g,%.7g,%.7g",
now-started,object,after?"after":"before",width,height,yaw,pitch,
r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11],r[12],r[13],r[14],r[15]);
log(text);
}
void projection_update(void* camera_object, float width, float height) {
// SPF v1.2.5 documents this exact engine ABI. Always preserve the original call.
++projection_calls;
// Ignore console-triggered nested calls in the diagnostic, preserving each engine call.
static thread_local unsigned depth=0;
const bool outer=depth++==0;
if (outer) probe_projection(camera_object,width,height,false);
on_update();
original_projection(camera_object,width,height);
if (outer) probe_projection(camera_object,width,height,true);
--depth;
}
forward_camera::Compensation base_camera{0,-5.049066,0,{0,-1.2,-2.5}};
void log(const char* text) {
if (logger && log_handle) logger->Log(log_handle, SPF_LOG_INFO, text);
}
double value(const char* key, double fallback) {
return config && settings ? config->Cfg_GetFloat(settings,key,fallback) : fallback;
}
bool flag(const char* key, bool fallback) {
return config && settings ? config->Cfg_GetBool(settings,key,fallback) : fallback;
}
void set(const char* attribute, double value) {
char command[160];
std::snprintf(command,sizeof(command),"multimon set road %s %.6f",attribute,value);
core->console->GCon_ExecuteCommand(command);
}
void apply(const forward_camera::Compensation& c) {
set("heading_offset",c.heading); set("pitch_offset",c.pitch); set("roll_offset",c.roll);
// SCS accepts the vector as three space-separated values in one command.
char command[192];
std::snprintf(command,sizeof(command),"multimon set road camera_space_offset %.6f %.6f %.6f",c.offset.x,c.offset.y,c.offset.z);
core->console->GCon_ExecuteCommand(command);
previous=c; have_previous=true;
}
void restore() {
head_motion.reset();
render_ready.store(false);
const bool had_render=render_applied.exchange(false);
if ((!applied && !had_render) || !core || !core->console || !core->console->GCon_ExecuteCommand) return;
apply(base_camera);
applied=false; have_previous=false;
log("Stopped compensation; restored road inset base angles and position.");
}
void install_render() {
if(render_attempted || !flag("settings.render_hook",false)) return;
render_attempted=true;
if (!core || !core->hooks || !core->hooks->Hook_FindPattern || !core->hooks->Hook_Register) {
log("Monitor render hook rejected: hook services unavailable.");return;
}
forward_camera::BuildCheck build_check{};
const bool file_matches=forward_camera::verified_game_build(nullptr,&build_check);
unsigned long mismatch=0;
if (!forward_camera::verified_loaded_camera(nullptr,&mismatch)) {
char message[192];
std::snprintf(message,sizeof(message),"Monitor render hook rejected: loaded camera code did not match inspected build at RVA=%lx",mismatch);
log(message);return;
}
if (!file_matches) {
char message[512];
std::snprintf(message,sizeof(message),"Self-read executable hash differs; all 4795 inspected camera code bytes match. Hash stage=%s error=%lu digest=%s path=%ls",
build_check.stage,build_check.error,build_check.digest,build_check.path);
log(message);
}
const char* signature="48 8B C4 48 89 58 08 48 89 70 10 57 48 81 EC 80 00 00 00 F3 0F 10 49 10 49 8B F1 0F 29 70 E8 48 8B DA F3 41 0F 10 70 04";
const auto address=core->hooks->Hook_FindPattern(signature);
if (address!=reinterpret_cast<uintptr_t>(GetModuleHandleW(nullptr))+0x69cb40) {
log("Monitor render hook rejected: function signature/location did not match.");return;
}
const auto handle=core->hooks->Hook_Register(name,"ForwardCameraMonitorView","Road inset render camera experiment",
reinterpret_cast<void*>(&monitor_view),reinterpret_cast<void**>(&original_view),signature,true);
log(handle && original_view ? "Monitor view hook installed after exact ATS 1.61.2 loaded camera code verification; image lock still needs measurement." :
"Monitor view hook unavailable; retaining console compensation.");
}
void on_load(const SPF_Load_API* api) {
if (!api) return;
logger=api->logger; config=api->config;
if (logger && logger->Log_GetContext) log_handle=logger->Log_GetContext(name);
if (config && config->Cfg_GetContext) settings=config->Cfg_GetContext(name);
log("Loaded passive forward-camera prototype. Game rotation convention is unverified.");
}
void install_timing() {
if(timing_attempted) return;
timing_attempted=true;
if (core && flag("settings.projection_timing",false) && core->hooks && core->hooks->Hook_Register) {
// Same function-entry signature as SPF's own CameraHooks.cpp, pinned to v1.2.5.
const char* signature="[MOV [r64+off8], r64] [MOV [r64+off8], r64] [PUSH r64] [SUB r64, imm8] [MOVZX r32, [r64+off8]] [LEA r64, [r64+off8]] [DIVSS xmm, xmm]";
const auto h=core->hooks->Hook_Register(name,"ForwardCameraProjection","Forward camera timing experiment",
reinterpret_cast<void*>(&projection_update),reinterpret_cast<void**>(&original_projection),signature,true);
log(h && original_projection ? "Projection timing hook registered; call frequency and image lock remain unverified." :
"Projection timing hook unavailable; using render-loop compensation.");
}
}
void on_activate(const SPF_Core_API* api) {
core=api; timing_attempted=false;render_attempted=false;render_ready.store(false);
head_telemetry.close();have_head_center=false;
render_trace.reset();
log("Activated. Only the monitor named road is changed. No vehicle input API is used.");
}
void on_unload() { restore(); head_telemetry.close();have_head_center=false;core=nullptr; config=nullptr; settings=nullptr; logger=nullptr; log_handle=nullptr; }
void on_world_unloaded() { restore(); head_telemetry.close();have_head_center=false;render_trace.reset(); }
void on_update() {
// Console changes can trigger projection updates recursively; skip that nested work.
if (updating.test_and_set()) return;
struct Release { ~Release() { updating.clear(); } } release;
drain_render_trace();
if (!core || !core->camera || !core->console || !core->console->GCon_ExecuteCommand) return;
if (!flag("settings.enabled",false)) { restore(); return; }
const auto camera=core->camera;
SPF_CameraType active{};
float yaw=0,pitch=0,roll_deg=0;
if (!camera->Cam_GetCurrentCamera || !camera->Cam_GetInteriorHeadRot ||
!camera->Cam_GetCurrentCamera(&active) || active!=SPF_CAMERA_INTERIOR ||
!camera->Cam_GetInteriorHeadRot(&yaw,&pitch) || !std::isfinite(yaw) ||
!std::isfinite(pitch) || std::abs(yaw)>3.3 || std::abs(pitch)>1.57) {
restore(); return;
}
if (camera->Cam_GetInteriorRoll && !camera->Cam_GetInteriorRoll(&roll_deg)) { restore(); return; }
if (!std::isfinite(roll_deg) || std::abs(roll_deg)>180) { restore(); return; }
// Camera services perform deferred pattern scans when the world loads.
// Wait for a valid camera read before detouring their shared function entry.
install_timing();
install_render();
if (original_view && flag("settings.render_hook",false)) {
// Switching modes restores earlier console values once. The view callback now
// computes the road camera directly from this frame's source quaternion.
if (applied) restore();
render_ready.store(true);
const auto now=GetTickCount64();
if (now>=next_log) {
next_log=now+1000;char text[256];
std::snprintf(text,sizeof(text),"RENDER road matches=%lu translation=%lu head delta=%.4f,%.4f,%.4f m; cabin unchanged; fixed image NOT verified",
render_matches.exchange(0),translation_matches.exchange(0),head_delta_x.load(),head_delta_y.load(),head_delta_z.load());
log(text);
}
return;
}
if (render_applied.load()) restore();
// GetInteriorRoll's implementation and per-function contract return degrees.
const double sy=value("settings.yaw_sign",1), sp=value("settings.pitch_sign",1);
const double base=value("settings.pitch_degrees",-5.049066);
const double yaw_lead=value("settings.yaw_lead_ms",0), pitch_lead=value("settings.pitch_lead_ms",0);
const forward_camera::Vec offset{value("settings.offset_x",0),value("settings.offset_y",-1.2),value("settings.offset_z",-2.5)};
if (!std::isfinite(sy) || std::abs(sy)!=1 || !std::isfinite(sp) || std::abs(sp)!=1 ||
!std::isfinite(base) || std::abs(base)>45 || !std::isfinite(offset.x) ||
!std::isfinite(yaw_lead) || yaw_lead<0 || yaw_lead>30 ||
!std::isfinite(pitch_lead) || pitch_lead<0 || pitch_lead>30 ||
!std::isfinite(offset.y) || !std::isfinite(offset.z) ||
std::abs(offset.x)>10 || std::abs(offset.y)>10 || std::abs(offset.z)>10) { restore(); return; }
base_camera={0,base,0,offset};
const auto predicted=head_motion.sample(seconds(),{yaw*sy,pitch*sp,roll_deg/forward_camera::degrees},yaw_lead/1000,pitch_lead/1000);
const auto c=forward_camera::compensate(predicted.x,predicted.y,predicted.z,
base/forward_camera::degrees,offset,flag("settings.local_matrix",false));
// Deadband limits console work while parked. Reapply every frame during head movement.
if (!have_previous || std::abs(c.heading-previous.heading)>0.001 ||
std::abs(c.pitch-previous.pitch)>0.001 || std::abs(c.roll-previous.roll)>0.001 ||
std::abs(c.offset.x-previous.offset.x)>0.0001 ||
std::abs(c.offset.y-previous.offset.y)>0.0001 || std::abs(c.offset.z-previous.offset.z)>0.0001) {
apply(c); applied=true;
}
const auto now=GetTickCount64();
if (now>=next_log) {
next_log=now+1000;
char text[256];
std::snprintf(text,sizeof(text),"EXPERIMENTAL head yaw=%.3f pitch=%.3f deg; road heading=%.3f pitch=%.3f roll=%.3f; projection calls=%lu; image lock NOT verified",
yaw*forward_camera::degrees,pitch*forward_camera::degrees,c.heading,c.pitch,c.roll,projection_calls.exchange(0));
log(text);
}
}
void manifest(SPF_Manifest_Builder_Handle* h,const SPF_Manifest_Builder_API* api) {
api->Info_SetName(h,name); api->Info_SetVersion(h,"0.2.6");
api->Info_SetMinFrameworkVersion(h,"1.2.5");
api->Info_SetAuthor(h,"ATS OP local project");
api->Info_SetDescriptionLiteral(h,"Passive prototype to cancel cabin head motion in the road inset; requires visual validation.");
api->Policy_SetAllowUserConfig(h,true);
api->Policy_AddConfigurableSystem(h,"settings");
api->Policy_AddRequiredHook(h,"GameConsole");
api->Defaults_SetLogging(h,"info",true);
api->Settings_SetJson(h,R"json({"enabled":false,"pitch_degrees":-5.049066,"offset_x":0,"offset_y":-1.2,"offset_z":-2.5,"yaw_sign":1,"pitch_sign":1,"local_matrix":false,"projection_timing":false,"yaw_lead_ms":0,"pitch_lead_ms":0,"pose_probe":false,"render_pose_trace":false,"render_hook":false,"cancel_head_translation":false})json");
}
}
extern "C" SPF_PLUGIN_EXPORT bool SPF_GetManifestAPI(SPF_Manifest_API* api) {
if (!api) return false; api->BuildManifest=manifest; return true;
}
extern "C" SPF_PLUGIN_EXPORT bool SPF_GetPlugin(SPF_Plugin_Exports* api) {
if (!api) return false;
*api={}; api->OnLoad=on_load; api->OnActivated=on_activate;
api->OnUnload=on_unload; api->OnUpdate=on_update; api->OnWorldUnloaded=on_world_unloaded;
return true;
}
-214
View File
@@ -1,214 +0,0 @@
# ForwardCamera passive prototype
Goal: keep the existing top-center `road` inset looking forward while the driver
looks around the cabin. This is a development prototype, not a verified solution.
It does not use the virtual input/vehicle APIs or engage automation.
Uses [SPF Framework v1.2.5](https://github.com/TrackAndTruckDevs/SPF-Framework/releases/tag/v1.2.5)
to read cabin head yaw/pitch and register the road monitor render callback.
The older console compensation remains available as a fallback.
The main monitor `cabin` is never changed. Default compensation is disabled.
The integration's `--camera auxiliary` calibration gate stays disabled.
Build with `./build.ps1` from PowerShell. Requires Visual Studio C++ Build Tools.
This compiles the DLL and runs a standalone check of 45 combined head rotations,
plus render-view checks with a rotated truck and combined head looks.
It also loads the built DLL with fake camera/config/console APIs to verify scoped
commands, deadband behavior, restoration, and no use of vehicle input APIs.
That proves the candidate matrix algebra; it does not prove SCS uses that matrix
order/sign convention, or that the output frame is independent of head movement.
Close ATS, then install with:
```powershell
./install.ps1 -PluginsDir 'C:/path/to/ATS/bin/win_x64/plugins' -EnablePassiveTest
```
The installer verifies pinned archive/DLL hashes, backs up existing framework and
ForwardCamera files, and disables SPF network connections and remote reports.
The game's existing telemetry DLL and saved driving profile are not edited.
Runtime settings are `plugins/spfPlugins/ForwardCamera/config/settings.json`.
Logs are `plugins/spfPlugins/ForwardCamera/logs/`. `enabled:false` stops the
experiment. With ATS closed, move `spf-framework.dll` outside the game's plugins
folder to prevent loading it; restore the inventory from the installation backup
if there was a previous SPF installation. Do not save compensated monitor values
with `multimon save`; the plugin only edits runtime values and resets on unload.
Installed status on ATS 1.61.2 (October 3, 2026): version 0.2.3 installed, camera and
console functions resolve, and vector commands accept three space-separated
values. The initial framework startup failure was resolved by precreating logs
and granting the current user Modify access only to SPF assets and this plugin's
directory. The first additive-angle test reduced movement but did not lock the
image. Full matrix compensation reduced that movement further: the sampled held
poses had a median/P95 feature shift of zero pixels, while moving poses still had
a P95 shift near 89 pixels. This is a limited parked measurement, not certification.
Version 0.1.3 adds an opt-in `projection_timing` experiment using the projection
function's signature and ABI documented in SPF v1.2.5. It installs only after a
valid interior-camera read, so the framework's deferred scans complete first.
The earlier 0.1.2 startup-hook test prevented that scan and produced no valid
compensation; its look measurements are invalid for comparing timing approaches.
The new callback preserves the original function and guards recursive console
updates. Its call rate and actual effect on rendering still require measurement.
Version 0.1.3's corrected hook runs around three times per rendered frame when
stationary, and the user reports further improvement. A sweep measurement still
showed motion (median 16 pixels, P95 65 pixels), so it is not a fixed camera yet.
The earlier callback still leaves residual delay correlated with head velocity.
Version 0.1.4 adds optional bounded prediction (`yaw_lead_ms`, `pitch_lead_ms`,
both default zero); the experiment used 12 ms yaw and 2 ms pitch from
that measurement. The prediction is capped at 0.08 radians and clears after
motion stops, a sample gap, camera changes, or disable. Its unit checks pass;
the live sweep measured a median shift of 12.5 pixels and P95 of 39.8 pixels.
Only one sufficiently different held pose was sampled (5.1-pixel shift). The user
reported no clear improvement or worsening. Different sweep speeds and poses
prevent a controlled before/after comparison, so both lead settings were reset
to zero. The camera is still not fixed.
Version 0.1.5 adds `pose_probe` (default false), a 60-second read-only diagnostic
inside the existing projection callback. It samples at most eight camera objects
at 10 Hz each, before and after the original function, preserving recursive calls.
Reads use VirtualQuery bounds and an exception guard. The candidate fields come
from [ETS2LA's ATS 1.60 core camera layout](https://github.com/ETS2LA/plugin/blob/main/src/prism/camera/core_camera.hpp);
this does **not** verify a writable ATS 1.61 layout. No camera memory is changed.
Logs carry `POSE` entries. To extract numeric candidates:
```powershell
python native/forward_camera/analyze_pose_probe.py PATH_TO_LOG --output diagnostics/render-camera-pose.json
```
The first trace captured 312 paired calls during cabin looks after loading.
The observed camera quaternion was normalized, and its yaw/pitch tracked the
API head angles: the difference varied by about 0.037/0.058 degrees. The parked
truck's world heading accounts for the constant yaw difference. Those paired
projection calls did not change the observed camera pose. Offline disassembly
of this installed executable also shows that this function computes FOV and
projection, rather than the per-monitor view transform. These observations
support investigating the monitor/frame update stage; they do not identify
the auxiliary transform or prove the cause of every residual pixel shift.
Saved evidence: `diagnostics/forward-camera-pose-probe.log`,
`diagnostics/render-camera-pose.json`, and
`diagnostics/render-camera-pose-analysis.json`.
Version 0.2.0 identifies the per-monitor quaternion composition function at RVA
`0x69cb40` by disassembling its complete function and both callers in the installed
ATS executable. The cached 80-byte monitor structure and its position/rotation
uses are verified from those instructions. `render_hook` is opt-in and requires
exact loaded-code matches, a unique function signature at the expected RVA,
and the existing road rectangle/FOV/exterior flags. A mismatched function or
layout cannot enter this experiment. The original function is always called.
The callback removes the current head rotation from the source quaternion and
rotates the road offset back into the head camera's space, retaining truck rotation.
It changes only the cached road view's rotation result and offset; the cabin and
monitor configuration units stay untouched. Version 0.2.0 did not activate this
hook; the loaded-code guard introduced in 0.2.1 allowed the verified hook to run.
A loaded DLL or passing algebra check is not evidence of a fixed image.
The standalone Windows hash check accepts the inspected ATS file and rejects its
own unrelated executable. Runtime logs distinguish missing hook services, failed
executable hashing, and a mismatched signature. `RENDER road matches` must become
positive before measuring this implementation; `EXPERIMENTAL` entries indicate
that the old console fallback is running.
The first 0.2.0 live attempt stayed in the fallback because in-process executable
hashing returned a different digest from the standalone Windows check. The cause
of that discrepancy is unresolved. Version 0.2.1 therefore verifies the loaded
camera code directly: all 4,795 bytes in 14 unwind ranges across the composition
function, both callers, cached-view builder, and position helper must match the
offline-inspected executable. PE timestamp, machine, image size, allocation bounds,
and readable page checks also apply. Generated ranges contain no base relocations.
`generate_build_fingerprint.py` refuses every input except the exact inspected
file hash. The non-executing real-executable fixture check verifies a match and
rejects an unrelated executable, invalid pointer, and single changed code byte.
Run that additional check with `build.ps1 -InspectedGameExecutable PATH_TO_EXE`.
The 0.2.1 hook ran live. A parked sweep had 251 look samples, with 58 unmatched
samples; matched shifts had a median of zero and P95 of 3.31 pixels. No different
held pose was sampled long enough for a settled result. The user reported a mostly
fixed inset with residual movement at extreme looks. A further trace confirmed
that ATS translates the head sideways and forward during large looks, while
cabin translation was only a fraction of a millimeter in that parked trace.
Version 0.2.2 attempted to read that translation through SPF telemetry, but its
live correction counter stayed zero. Version 0.2.3 instead reads the existing
[RenCloud revision 12 mapping](https://github.com/RenCloud/scs-sdk-plugin/blob/V.1.12.1/scs-telemetry/inc/scs-telemetry-common.hpp)
with `OpenFileMapping(FILE_MAP_READ)`. It never creates or writes the mapping.
It checks the ATS game ID, revision, active/paused flags, timestamp freshness,
finite placements, and bounded displacement. The seat position is the reference;
if the camera API cannot supply it, a centered head sample is used. Position
correction is opt-in through `cancel_head_translation`. Missing/stale telemetry
skips that correction. Rotation compensation still runs.
The native SDK reader passed 15 fresh live samples in the parked cabin. Decoder
checks cover position/rotation field separation, units, pauses, inactive/wrong
formats, and invalid positions. Rotation checks include the measured head
displacements and invalid/excess displacement rejection. The installed 0.2.3
correction counter is positive, and centered head delta is zero. A parked sweep
captured 117 look samples, all matched, with median/P95 feature shifts of zero
pixels at the feature detector's precision. No different pose was held long
enough for a settled result. The user reported an almost perfect inset with very
slight residual movement. Evidence: `diagnostics/inset-lock-translation-fixed.json`.
Subsequent live moving calibration recorded 266 moving model frames, 253 with
usable lanes. All 155 recorded moving cabin-look frames had usable lanes, and
reviewed overlays followed the lane paint. This supports limited Pinnacle
steering-only calibration; it does not prove identical pixels while the truck
itself moves. Evidence: `diagnostics/inset-cal-20261003-044742-900055/summary.json`.
The Python runtime checks matching model/plugin/settings/truck identities and
fresh positive rotation/translation correction counters before active control.
A centered-view CPU steering test lasted 21.054 seconds and released on manual
takeover, followed by zero parked input values. A later run stayed engaged for
25.029 seconds during mouse-look with sampled yaw from -80.3 to +59.1 degrees,
then released on low lane confidence. Another episode released above 20 MPH.
All parked inputs were zero after shutdown. This supports short supervised
steering tests; confidence dropouts, cab shake, reload transitions, other trucks
and inset cruise/braking remain unverified.
Further validation workflow:
1. Park with brake on and keep FSD disengaged. Verify SPF finds camera and console
functions and no command errors appear in the game/framework logs.
2. Look left/right, up/down, and diagonally. Compare the inset against the centered
image and check that its horizon/road features stay fixed, allowing moving traffic.
3. Confirm positive `translation` counters and near-zero centered `head delta`,
then measure the image during full-range looks and several-second holds.
4. Measure frame delay, FPS, cab sway/seat changes, and behavior on leaving cabin
view or reloading the world. Cab shake is not explicitly cancelled. Shared
telemetry may lag the current rendered camera during transitions.
5. Only after stable capture and truck-specific camera calibration should an
additional freshness/health gate permit active control with this camera mode.
Console and projection experiments remain fallback paths. Their movement results
do not validate the direct render hook or the new translation correction.
For a parked measurement, run `python -m vision.check_auxiliary_lock --duration 60`
from the repository root. It compares road features against the centered inset,
records head poses and affine transforms, and reports held-pose movement separately
from movement during transitions. It never opens an actuator or enables control.
# Version 0.2.4: bounded render observation
`settings.render_pose_trace=true` enables a diagnostic only, leaving the existing
camera correction algorithm unchanged. It starts at the first matching road
monitor render with fresh unpaused SDK, parking brake set, and speed below
0.1 mph after activation. Menu/paused/invalid SDK frames cannot start its timer.
It runs for 60 seconds, and selects at most ten
observations per second while those parked conditions remain true. Moving or
unparked frames are omitted; the minute timer does not restart. Disabled is the default. Re-activation resets its window;
leaving the flag enabled does not create an endless trace.
`RENDER_POSE` records host tick milliseconds, road-frame generation, camera type,
interior outside flag, raw SPF head angles and full SDK head orientation (radians),
SDK timestamp/position/speed/parking/paused fields, seat baseline, source/output quaternions in w,x,y,z order,
and monitor offset before/after. Validity flags distinguish unavailable getters
from real zero values. `applied` and `translation` describe the correction branch
for that same observed callback, including callbacks rejected by the existing
INTERIOR gate. These observations do not grant calibration or camera health.
The render callback queues one snapshot without waiting. SPF OnUpdate drains it
and calls the logger; contention and an undrained queue drop observations instead
of blocking rendering or flooding the log. The trace makes no game camera, input,
or settings writes. Build/deployment changes DLL identity and invalidates proofs
pinned to the earlier DLL until separately revalidated.
@@ -1,57 +0,0 @@
"""Summarize candidate render camera data; never infer a writable memory layout."""
import argparse
import json
import math
import re
from pathlib import Path
PATTERN = re.compile(
r"POSE t=(\S+) object=(\S+) stage=(before|after) size=(\S+) head=(\S+) raw=(\S+)"
)
def analyze(text):
rows = []
for match in PATTERN.finditer(text):
time, object_id, stage, size, head, raw = match.groups()
try:
row = dict(seconds=float(time), object=object_id, stage=stage,
size=[float(v) for v in size.split(",")],
head=[float(v) for v in head.split(",")],
candidate=[float(v) for v in raw.split(",")])
except ValueError:
continue
if len(row["candidate"]) == 16:
rows.append(row)
objects = {}
for object_id in sorted({r["object"] for r in rows}):
group = [r for r in rows if r["object"] == object_id and r["stage"] == "after"]
if not group:
continue
finite = [r for r in group if all(math.isfinite(v) for v in r["candidate"])]
norms = [math.sqrt(sum(v*v for v in r["candidate"][12:16])) for r in finite]
objects[object_id] = dict(
samples=len(group), sizes=sorted({tuple(r["size"]) for r in group}),
finite_samples=len(finite),
quaternion_norm_range=[min(norms), max(norms)] if norms else None,
candidate_field_ranges=[
[min(r["candidate"][i] for r in finite), max(r["candidate"][i] for r in finite)]
for i in range(16)
] if finite else [],
head_range_radians=[
[min(r["head"][i] for r in group), max(r["head"][i] for r in group)]
for i in range(2)
],
)
return dict(note="Read-only candidates from an older upstream layout; no writable ABI is verified.",
rows=rows, objects=objects)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("log", type=Path)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
result = analyze(args.log.read_text(encoding="utf-8-sig"))
args.output.write_text(json.dumps(result, indent=2), encoding="utf-8")
print(json.dumps(result["objects"], indent=2))
-43
View File
@@ -1,43 +0,0 @@
param([string]$InspectedGameExecutable)
$ErrorActionPreference = 'Stop'
Push-Location $PSScriptRoot
try {
$taskVsWhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
$taskInstall = & $taskVsWhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
if (-not $taskInstall) { throw 'Visual Studio C++ Build Tools were not found.' }
$taskVcVars = Join-Path $taskInstall 'VC\Auxiliary\Build\vcvars64.bat'
New-Item -ItemType Directory -Force build | Out-Null
# Only compilation runs in cmd; no file deletion or moving is composed across shells.
$taskBuild = @"
@echo off
call "$taskVcVars" >nul
if errorlevel 1 exit /b 1
cl /nologo /LD /EHsc /std:c++17 /W4 /O2 /MT /I vendor\SPF_API ForwardCamera.cpp /Fobuild\ForwardCamera.obj /Febuild\ForwardCamera.dll /link /IMPLIB:build\ForwardCamera.lib
if errorlevel 1 exit /b 1
cl /nologo /EHsc /std:c++17 /W4 /O2 /MT test_rotation.cpp /Fobuild\test_rotation.obj /Febuild\test_rotation.exe
if errorlevel 1 exit /b 1
build\test_rotation.exe
if errorlevel 1 exit /b 1
cl /nologo /EHsc /std:c++17 /W4 /O2 /MT /I vendor\SPF_API test_plugin.cpp /Fobuild\test_plugin.obj /Febuild\test_plugin.exe
if errorlevel 1 exit /b 1
build\test_plugin.exe
if errorlevel 1 exit /b 1
cl /nologo /EHsc /std:c++17 /W4 /O2 /MT test_build_guard.cpp /Fobuild\test_build_guard.obj /Febuild\test_build_guard.exe
if errorlevel 1 exit /b 1
cl /nologo /EHsc /std:c++17 /W4 /O2 /MT test_head_telemetry.cpp /Fobuild\test_head_telemetry.obj /Febuild\test_head_telemetry.exe
if errorlevel 1 exit /b 1
build\test_head_telemetry.exe
if errorlevel 1 exit /b 1
cl /nologo /EHsc /std:c++17 /W4 /O2 /MT test_render_trace.cpp /Fobuild\test_render_trace.obj /Febuild\test_render_trace.exe
if errorlevel 1 exit /b 1
build\test_render_trace.exe
if errorlevel 1 exit /b 1
"@
Set-Content -LiteralPath build/compile.cmd -Value $taskBuild -Encoding ascii
& cmd.exe /d /c build\compile.cmd
if ($LASTEXITCODE -ne 0) { throw 'ForwardCamera build or rotation checks failed.' }
if ($InspectedGameExecutable) {
& .\build\test_build_guard.exe $InspectedGameExecutable
if ($LASTEXITCODE -ne 0) { throw 'Loaded camera build guard check failed.' }
}
} finally { Pop-Location }
-358
View File
@@ -1,358 +0,0 @@
// Generated from the SHA256-verified, offline-inspected ATS 1.61.2 executable.
// Regenerate with generate_build_fingerprint.py; base-relocated ranges are rejected.
#pragma once
namespace forward_camera {
constexpr unsigned long inspected_image_size=0x3973000;
constexpr unsigned long inspected_timestamp=0x6ab3a5d4;
struct CodeRange { unsigned long rva; const unsigned char* bytes; unsigned long size; };
constexpr unsigned char code_0[]={
0x4c,0x89,0x44,0x24,0x18,0x55,0x53,0x56,0x41,0x54,0x41,0x56,0x48,0x8d,0x6c,0x24,
0xe0,0x48,0x81,0xec,0x20,0x01,0x00,0x00,0x48,0x8b,0x05,0x61,0x77,0x23,0x03,0x4d,
0x8b,0xe0,0x8b,0xda,0x48,0x8b,0xf1,0x4c,0x8b,0xf0,0x80,0xb8,0xb8,0x05,0x00,0x00,
0x00,0x74,0x0f,0x48,0x8b,0xc8,0xe8,0xf5,0xa3,0xfa,0xff,0x48,0x8b,0x05,0x3e,0x77,
0x23,0x03,0x49,0x81,0xc6,0xc0,0x05,0x00,0x00,0x4c,0x89,0xac,0x24,0x18,0x01,0x00,
0x00,0x83,0xb8,0xa8,0x05,0x00,0x00,0x01,0x0f,0x86,0x58,0x03,0x00,0x00,0x49,0x83,
0x7e,0x10,0x00,0x0f,0x84,0x4d,0x03,0x00,0x00,0x48,0x8b,0x8e,0x60,0x09,0x00,0x00,
};
constexpr unsigned char code_1[]={
0x48,0x89,0xbc,0x24,0x50,0x01,0x00,0x00,0x4c,0x89,0xbc,0x24,0x10,0x01,0x00,0x00,
0x48,0x83,0x79,0x70,0x00,0x75,0x14,0x8b,0x51,0x10,0xe8,0x91,0x13,0x08,0x00,0x48,
0x8b,0x8e,0x60,0x09,0x00,0x00,0x48,0x8b,0xf8,0xeb,0x0d,0x48,0x8b,0x51,0x70,0x48,
0x8b,0x41,0x68,0x48,0x8b,0x7c,0xd0,0xf8,0x48,0x8b,0x96,0x90,0x09,0x00,0x00,0x0f,
0x29,0xb4,0x24,0x00,0x01,0x00,0x00,0x0f,0x29,0xbc,0x24,0xf0,0x00,0x00,0x00,0xe8,
0xcc,0x18,0x08,0x00,0x48,0x8b,0x8e,0x90,0x09,0x00,0x00,0x48,0x8b,0xd7,0xe8,0xed,
0x70,0x31,0x00,0x49,0x8b,0x46,0x10,0x48,0x8d,0x57,0x40,0x49,0x8b,0x7e,0x08,0x45,
0x33,0xed,0x48,0x89,0x55,0x90,0x45,0x8b,0xfd,0x48,0xc7,0x45,0x68,0x00,0x00,0x00,
0x00,0x48,0x8d,0x0c,0x80,0x48,0xc1,0xe1,0x04,0x48,0x03,0xcf,0x48,0x3b,0xf9,0x0f,
0x84,0x42,0x02,0x00,0x00,0x48,0x8d,0x42,0x10,0x4c,0x89,0x6c,0x24,0x50,0x48,0x89,
0x45,0x88,0xf3,0x41,0x0f,0x10,0x44,0x24,0x14,0xf3,0x41,0x0f,0x5c,0x44,0x24,0x10,
0xf3,0x41,0x0f,0x10,0x4c,0x24,0x18,0xf3,0x41,0x0f,0x5c,0x4c,0x24,0x1c,0x0f,0x10,
0x1f,0x41,0x0f,0x10,0x14,0x24,0x0f,0x11,0x5c,0x24,0x40,0xf3,0x0f,0x10,0x74,0x24,
0x44,0xf3,0x0f,0x10,0x7c,0x24,0x48,0xf3,0x0f,0x10,0x64,0x24,0x4c,0xf3,0x0f,0x59,
0xd8,0xf3,0x0f,0x59,0xf0,0x41,0x0f,0x10,0x44,0x24,0x10,0xf3,0x0f,0x59,0xf9,0xf3,
0x0f,0x59,0xe1,0x41,0x0f,0x10,0x4c,0x24,0x20,0x0f,0x11,0x55,0x98,0x66,0x0f,0x73,
0xda,0x08,0x66,0x48,0x0f,0x7e,0xd0,0xf3,0x0f,0x11,0x5c,0x24,0x40,0x48,0xc1,0xe8,
0x20,0xf3,0x0f,0x11,0x74,0x24,0x44,0xf3,0x0f,0x11,0x7c,0x24,0x48,0xf3,0x0f,0x11,
0x64,0x24,0x4c,0x0f,0x11,0x45,0xa8,0x0f,0x11,0x4d,0xb8,0x83,0xf8,0x01,0x76,0x11,
0x0f,0x28,0x05,0x89,0xfa,0x09,0x02,0x0f,0x11,0x45,0xb8,0x44,0x89,0x6d,0xa4,0xeb,
0x07,0xc7,0x45,0xa4,0x01,0x00,0x00,0x00,0x0f,0x10,0x44,0x24,0x40,0x48,0x8b,0xcf,
0x4c,0x8d,0x44,0x24,0x50,0xf3,0x0f,0x5c,0xf3,0xf3,0x0f,0x5c,0xfc,0x48,0x8d,0x54,
0x24,0x58,0x0f,0x11,0x45,0xa8,0x0f,0x28,0xde,0xf3,0x0f,0x5e,0xdf,0xe8,0x6e,0xb6,
0x21,0x00,0x48,0x8b,0x86,0x90,0x09,0x00,0x00,0x0f,0x28,0xd7,0xf3,0x0f,0x10,0x4c,
0x24,0x5c,0xf3,0x0f,0x10,0x44,0x24,0x58,0xf3,0x0f,0x11,0x40,0x30,0x48,0x8b,0x86,
0x90,0x09,0x00,0x00,0xf3,0x0f,0x11,0x48,0x34,0x0f,0x28,0xce,0x48,0x8b,0x8e,0x90,
0x09,0x00,0x00,0x48,0x8b,0x01,0xff,0x90,0x80,0x00,0x00,0x00,0x4d,0x8b,0x66,0x08,
0x49,0x3b,0xfc,0x75,0x19,0x48,0x8b,0x86,0x90,0x09,0x00,0x00,0xf3,0x0f,0x10,0x48,
0x3c,0xf3,0x0f,0x10,0x40,0x38,0x0f,0x14,0xc1,0xf2,0x0f,0x11,0x45,0x68,0x4c,0x8b,
0x45,0x88,0x4c,0x8d,0x4d,0x68,0x48,0x8d,0x54,0x24,0x60,0x48,0x8b,0xcf,0xe8,0x6d,
0xb3,0x21,0x00,0x48,0x8b,0x86,0x90,0x09,0x00,0x00,0x4c,0x8d,0x47,0x28,0x0f,0x10,
0x44,0x24,0x60,0x48,0x8b,0x4d,0x90,0x48,0x8d,0x55,0xc8,0x0f,0x11,0x40,0x50,0xe8,
0xbc,0x9e,0xf1,0x00,0x48,0x8b,0x86,0x90,0x09,0x00,0x00,0x0f,0x10,0x45,0xc8,0x0f,
0x11,0x40,0x40,0x0f,0xb6,0x47,0x4d,0x0f,0x10,0x47,0x3c,0x48,0x8b,0x96,0xf0,0x09,
0x00,0x00,0x88,0x44,0x24,0x73,0x0f,0xb6,0x47,0x4c,0x88,0x44,0x24,0x72,0x66,0xc7,
0x44,0x24,0x70,0x01,0x01,0x44,0x88,0x6c,0x24,0x74,0x0f,0x11,0x44,0x24,0x78,0x48,
0x85,0xd2,0x74,0x24,0x49,0x3b,0xfc,0x75,0x19,0x0f,0x28,0xd7,0x48,0x8d,0x4d,0xd8,
0x0f,0x28,0xce,0xe8,0xf8,0xa7,0xff,0xff,0x0f,0x10,0x45,0xd8,0x0f,0x11,0x42,0x40,
0xeb,0x06,0xff,0x42,0x3c,0x41,0xff,0xc7,0x48,0x8b,0xd7,0x49,0x8b,0xce,0xe8,0x0d,
0x2b,0xe7,0xff,0x84,0xc0,0x0f,0x84,0xe5,0x00,0x00,0x00,0x48,0x8b,0xcf,0x4c,0x8d,
0x4d,0x98,0x49,0x2b,0x4e,0x08,0x48,0xb8,0x67,0x66,0x66,0x66,0x66,0x66,0x66,0x66,
0x48,0xf7,0xe9,0x44,0x8b,0xc3,0x48,0x8b,0xce,0x48,0xc1,0xfa,0x05,0x48,0x8b,0xc2,
0x48,0xc1,0xe8,0x3f,0x48,0x03,0xd0,0x48,0x8d,0x44,0x24,0x70,0x48,0x89,0x44,0x24,
0x20,0xe8,0x0a,0x01,0x00,0x00,0x49,0x8b,0x46,0x10,0x48,0x83,0xc7,0x50,0x4c,0x8b,
0x65,0x60,0x48,0x8d,0x0c,0x80,0x48,0xc1,0xe1,0x04,0x49,0x03,0x4e,0x08,0x48,0x3b,
0xf9,0x0f,0x85,0xcb,0xfd,0xff,0xff,0x48,0x8b,0x96,0x60,0x09,0x00,0x00,0x48,0x8b,
0x42,0x68,0x48,0x8b,0x4a,0x70,0x48,0x83,0xe8,0x08,0x48,0x8d,0x0c,0xc8,0x48,0x89,
0x4d,0x68,0x48,0x8d,0x4a,0x60,0x48,0x8d,0x55,0x68,0xe8,0x21,0x1b,0x08,0x00,0x45,
0x85,0xff,0x74,0x0b,0x48,0x8b,0x86,0xf0,0x09,0x00,0x00,0x44,0x29,0x78,0x3c,0x0f,
0x28,0xb4,0x24,0x00,0x01,0x00,0x00,0x0f,0x28,0xbc,0x24,0xf0,0x00,0x00,0x00,0x48,
0x8b,0xbc,0x24,0x50,0x01,0x00,0x00,0x4c,0x8b,0xbc,0x24,0x10,0x01,0x00,0x00,
};
constexpr unsigned char code_2[]={
0x4c,0x8b,0xac,0x24,0x18,0x01,0x00,0x00,0x48,0x81,0xc4,0x20,0x01,0x00,0x00,0x41,
0x5e,0x41,0x5c,0x5e,0x5b,0x5d,0xc3,0x45,0x33,0xed,0x4d,0x8b,0xcc,0x44,0x8b,0xc3,
0x4c,0x89,0x6c,0x24,0x20,0x33,0xd2,0x48,0x8b,0xce,0xe8,0x62,0x00,0x00,0x00,0xeb,
0xcf,
};
constexpr unsigned char code_3[]={
0x49,0x8b,0xce,0xe8,0xa8,0x2f,0xc7,0xff,0x48,0x8d,0x14,0x80,0x48,0xc1,0xe2,0x04,
0xe8,0x5b,0x30,0xc7,0xff,0x48,0x03,0xd0,0xe8,0x53,0x30,0xc7,0xff,0x48,0x89,0x54,
0x24,0x38,0x4c,0x8d,0x0d,0x1f,0x0b,0xd5,0x01,0x48,0x89,0x44,0x24,0x30,0x4c,0x8d,
0x05,0xfb,0x87,0xdc,0x01,0x48,0x8d,0x05,0x1c,0x0e,0x97,0x01,0x48,0x89,0x7c,0x24,
0x28,0xba,0xab,0x02,0x00,0x00,0x48,0x89,0x44,0x24,0x20,0x48,0x8d,0x0d,0x6e,0x0a,
0xd5,0x01,0xe8,0x79,0xb2,0xc7,0xff,0xcc,
};
constexpr unsigned char code_4[]={
0x40,0x55,0x57,0x41,0x56,0x41,0x57,0x48,0x8d,0x6c,0x24,0xf8,0x48,0x81,0xec,0x08,
0x01,0x00,0x00,0x48,0x8b,0x81,0x60,0x09,0x00,0x00,0x48,0x8b,0xf9,0x48,0x83,0x78,
0x70,0x00,0x75,0x10,0x8b,0x50,0x10,0x48,0x8b,0xc8,0xe8,0x31,0x88,0x07,0x00,0x4c,
0x8b,0xf8,0xeb,0x0d,0x48,0x8b,0x48,0x70,0x48,0x8b,0x40,0x68,0x4c,0x8b,0x7c,0xc8,
0xf8,0x4c,0x8b,0x35,0x78,0xeb,0x22,0x03,0x41,0x83,0xbe,0xa8,0x05,0x00,0x00,0x01,
0x77,0x1d,0x41,0xb1,0x01,0x4d,0x8b,0xc7,0x33,0xd2,0x48,0x8b,0xcf,0x48,0x81,0xc4,
0x08,0x01,0x00,0x00,0x41,0x5f,0x41,0x5e,0x5f,0x5d,0xe9,0xf1,0x09,0x00,0x00,0x41,
0x80,0xbe,0xb8,0x05,0x00,0x00,0x00,
};
constexpr unsigned char code_5[]={
0x48,0x89,0x9c,0x24,0x48,0x01,0x00,0x00,0x48,0x89,0xb4,0x24,0x00,0x01,0x00,0x00,
0x49,0x8b,0xf6,0x74,0x0f,0x49,0x8b,0xce,0xe8,0xdc,0x17,0xfa,0xff,0x4c,0x8b,0x35,
0x25,0xeb,0x22,0x03,0x48,0x8b,0x8f,0x90,0x09,0x00,0x00,0x49,0x8b,0xd7,0x48,0x81,
0xc6,0xc0,0x05,0x00,0x00,0xe8,0x4f,0xe5,0x30,0x00,0x48,0x8b,0x5e,0x08,0x48,0x8b,
0x46,0x10,0x48,0xc7,0x45,0x30,0x00,0x00,0x00,0x00,0x48,0x8d,0x0c,0x80,0x48,0xc1,
0xe1,0x04,0x48,0x03,0xcb,0x48,0x3b,0xd9,0x0f,0x84,0x33,0x04,0x00,0x00,
};
constexpr unsigned char code_6[]={
0x4c,0x89,0xa4,0x24,0xf8,0x00,0x00,0x00,0x4c,0x89,0xac,0x24,0xf0,0x00,0x00,0x00,
0x49,0xbd,0x67,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x0f,0x29,0xb4,0x24,0xe0,0x00,
0x00,0x00,0x0f,0x29,0xbc,0x24,0xd0,0x00,0x00,0x00,0x44,0x0f,0x29,0x84,0x24,0xc0,
0x00,0x00,0x00,0x44,0x0f,0x29,0x8c,0x24,0xb0,0x00,0x00,0x00,0xf3,0x44,0x0f,0x10,
0x0d,0x2e,0x40,0x09,0x02,0x44,0x0f,0x29,0x94,0x24,0xa0,0x00,0x00,0x00,0xf3,0x44,
0x0f,0x10,0x15,0x10,0x47,0x09,0x02,0x44,0x0f,0x29,0x9c,0x24,0x90,0x00,0x00,0x00,
0xf3,0x44,0x0f,0x10,0x1d,0xa2,0x6f,0x09,0x02,0x44,0x0f,0x29,0xa4,0x24,0x80,0x00,
0x00,0x00,0x45,0x0f,0x57,0xe4,0x48,0xc7,0x45,0x38,0x00,0x00,0x00,0x00,0xc7,0x44,
0x24,0x70,0x00,0x00,0x00,0x00,0x0f,0x1f,0x44,0x00,0x00,0x0f,0x10,0x1b,0x4c,0x8d,
0x45,0x38,0x48,0x8b,0xcb,0xf3,0x41,0x0f,0x10,0x8e,0x38,0x09,0x00,0x00,0x48,0x8d,
0x55,0x40,0xf3,0x41,0x0f,0x5c,0x8e,0x34,0x09,0x00,0x00,0xf3,0x41,0x0f,0x10,0x96,
0x3c,0x09,0x00,0x00,0x0f,0x28,0xfb,0xf3,0x41,0x0f,0x5c,0x96,0x40,0x09,0x00,0x00,
0x0f,0xc6,0xfb,0x55,0x0f,0x28,0xf3,0x0f,0xc6,0xf3,0xaa,0x0f,0x28,0xc3,0x0f,0xc6,
0xdb,0xff,0xf3,0x0f,0x59,0xf9,0xf3,0x0f,0x59,0xda,0xf3,0x0f,0x59,0xc1,0xf3,0x0f,
0x59,0xf2,0xf3,0x0f,0x5c,0xf8,0xf3,0x0f,0x5c,0xf3,0x0f,0x28,0xdf,0xf3,0x0f,0x5e,
0xde,0xe8,0xc5,0x2a,0x21,0x00,0x48,0x8b,0x87,0x90,0x09,0x00,0x00,0x0f,0x28,0xd6,
0xf3,0x0f,0x10,0x45,0x40,0x0f,0x28,0xcf,0xf3,0x0f,0x10,0x5d,0x44,0xf3,0x0f,0x11,
0x40,0x30,0x48,0x8b,0x87,0x90,0x09,0x00,0x00,0xf3,0x0f,0x11,0x58,0x34,0x48,0x8b,
0x8f,0x90,0x09,0x00,0x00,0x48,0x8b,0x01,0xff,0x90,0x80,0x00,0x00,0x00,0x48,0x3b,
0x5e,0x08,0x75,0x19,0x48,0x8b,0x87,0x90,0x09,0x00,0x00,0xf3,0x0f,0x10,0x48,0x3c,
0xf3,0x0f,0x10,0x40,0x38,0x0f,0x14,0xc1,0xf2,0x0f,0x11,0x45,0x30,0x4c,0x8d,0x4d,
0x30,0x48,0x8b,0xcb,0x4d,0x8d,0x47,0x50,0x48,0x8d,0x54,0x24,0x60,0xe8,0xc9,0x27,
0x21,0x00,0x48,0x8b,0x87,0x90,0x09,0x00,0x00,0x48,0x8d,0x4c,0x24,0x5c,0x0f,0x10,
0x44,0x24,0x60,0x0f,0x28,0x5c,0x24,0x70,0x45,0x0f,0x28,0xc4,0x0f,0x11,0x40,0x50,
0x41,0x0f,0x10,0x67,0x50,0xf3,0x0f,0x10,0x43,0x28,0xf3,0x0f,0x10,0x4b,0x2c,0x44,
0x0f,0x5c,0xc4,0xf3,0x0f,0x10,0x53,0x30,0x0f,0xc6,0xdb,0xe1,0xf3,0x0f,0x10,0xd8,
0x0f,0x28,0xc4,0x0f,0xc6,0xc4,0x66,0x0f,0xc6,0xdb,0xc6,0x41,0x0f,0x28,0xe8,0xf3,
0x0f,0x10,0xd9,0x41,0x0f,0x57,0xeb,0xf3,0x44,0x0f,0x10,0xc5,0x0f,0xc6,0xdb,0x27,
0xf3,0x0f,0x10,0xda,0x44,0x0f,0x29,0x44,0x24,0x40,0x0f,0xc6,0xdb,0x39,0x41,0x0f,
0x28,0xf0,0x41,0x0f,0xc6,0xf0,0x82,0x0f,0x28,0xfb,0x0f,0xc6,0xfb,0x82,0x0f,0x28,
0xcb,0x0f,0x59,0xf8,0x0f,0x28,0xd3,0x0f,0xc6,0xcb,0xe5,0x0f,0x28,0xc4,0x0f,0xc6,
0xc4,0x01,0x0f,0x59,0xc8,0x0f,0x28,0xc4,0x0f,0xc6,0xc4,0xfb,0x0f,0xc6,0xd3,0x1f,
0x0f,0x59,0xd0,0x0f,0x58,0xf9,0x0f,0x29,0x5c,0x24,0x70,0x41,0x0f,0x28,0xc8,0x0f,
0xc6,0xdb,0x78,0x41,0x0f,0xc6,0xc8,0xe5,0x0f,0xc6,0xe4,0x9c,0x0f,0x59,0xdc,0x0f,
0x58,0xfa,0x41,0x0f,0x28,0xd0,0x41,0x0f,0xc6,0xd0,0x1f,0x45,0x0f,0xc6,0xc0,0x78,
0x0f,0x5c,0xfb,0x0f,0x28,0xc7,0x41,0x0f,0x57,0xc3,0xf3,0x0f,0x10,0xf8,0x0f,0x28,
0xc7,0x0f,0x29,0x7c,0x24,0x40,0x0f,0xc6,0xc7,0x66,0x0f,0x59,0xf0,0x0f,0x28,0xc7,
0x0f,0xc6,0xc7,0x01,0x0f,0x59,0xc8,0x0f,0x28,0xc7,0x0f,0xc6,0xc7,0xfb,0x0f,0x59,
0xd0,0x0f,0x58,0xf1,0x0f,0xc6,0xff,0x9c,0x44,0x0f,0x59,0xc7,0x0f,0x58,0xf2,0x41,
0x0f,0x5c,0xf0,0x0f,0x28,0xc6,0x41,0x0f,0x57,0xc3,0xf3,0x0f,0x10,0xf0,0x0f,0x28,
0xce,0x0f,0x29,0x74,0x24,0x40,0x0f,0xc6,0xce,0x55,0xe8,0x6c,0x6b,0xca,0xff,0xf3,
0x0f,0x11,0x44,0x24,0x50,0x48,0x8d,0x4c,0x24,0x5e,0x0f,0x28,0xc6,0x0f,0xc6,0xc6,
0xaa,0x0f,0xc6,0xf6,0xff,0x0f,0x28,0xce,0xf3,0x0f,0x11,0x44,0x24,0x54,0xe8,0x48,
0x6b,0xca,0xff,0x41,0x0f,0x10,0x5f,0x40,0xf3,0x0f,0x11,0x44,0x24,0x58,0x0f,0x11,
0x5c,0x24,0x40,0xf3,0x0f,0x10,0x4c,0x24,0x44,0xf3,0x0f,0x10,0x54,0x24,0x48,0xf3,
0x0f,0x58,0x5c,0x24,0x50,0xf3,0x0f,0x58,0x4c,0x24,0x54,0xf3,0x0f,0x58,0xd0,0x41,
0x0f,0x2f,0xda,0xf3,0x0f,0x11,0x4c,0x24,0x44,0xf3,0x0f,0x11,0x54,0x24,0x48,0xf3,
0x0f,0x11,0x5c,0x24,0x40,0x77,0x12,0xf3,0x41,0x0f,0x58,0xd9,0xb9,0xff,0xff,0xff,
0xff,0xf3,0x0f,0x11,0x5c,0x24,0x40,0xeb,0x1a,0x41,0x0f,0x2f,0xd9,0x72,0x12,0xf3,
0x41,0x0f,0x5c,0xd9,0xb9,0x01,0x00,0x00,0x00,0xf3,0x0f,0x11,0x5c,0x24,0x40,0xeb,
0x02,0x33,0xc9,0x0f,0xbf,0x44,0x24,0x5c,0x44,0x0f,0xbf,0x44,0x24,0x4c,0x03,0xc1,
0x44,0x03,0xc0,0x41,0x0f,0x2f,0xd2,0x77,0x12,0xf3,0x41,0x0f,0x58,0xd1,0xba,0xff,
0xff,0xff,0xff,0xf3,0x0f,0x11,0x54,0x24,0x48,0xeb,0x1a,0x41,0x0f,0x2f,0xd1,0x72,
0x12,0xf3,0x41,0x0f,0x5c,0xd1,0xba,0x01,0x00,0x00,0x00,0xf3,0x0f,0x11,0x54,0x24,
0x48,0xeb,0x02,0x33,0xd2,0x0f,0xbf,0x44,0x24,0x5e,0x48,0x8b,0xce,0x03,0xc2,0x66,
0x44,0x89,0x44,0x24,0x4c,0x66,0x01,0x44,0x24,0x4e,0x48,0x8b,0xd3,0x48,0x8b,0x87,
0x90,0x09,0x00,0x00,0x0f,0x10,0x44,0x24,0x40,0x0f,0x11,0x40,0x40,0xe8,0xc9,0x9d,
0xe6,0xff,0x84,0xc0,0x0f,0x84,0xb7,0x00,0x00,0x00,0x44,0x0f,0xb6,0x4b,0x4d,0x48,
0x8b,0xcb,0x48,0x2b,0x4e,0x08,0x49,0x8b,0xc5,0x4c,0x8b,0x87,0x90,0x09,0x00,0x00,
0x48,0xf7,0xe9,0x48,0x8b,0xcf,0x48,0xc1,0xfa,0x05,0x48,0x8b,0xc2,0x48,0xc1,0xe8,
0x3f,0x48,0x03,0xd0,0xe8,0xc2,0x05,0x00,0x00,0x48,0x8b,0x46,0x10,0x48,0x83,0xc3,
0x50,0x48,0x8d,0x0c,0x80,0x48,0xc1,0xe1,0x04,0x48,0x03,0x4e,0x08,0x48,0x3b,0xd9,
0x0f,0x85,0xa5,0xfc,0xff,0xff,0x44,0x0f,0x28,0x9c,0x24,0x90,0x00,0x00,0x00,0x44,
0x0f,0x28,0x94,0x24,0xa0,0x00,0x00,0x00,0x44,0x0f,0x28,0x8c,0x24,0xb0,0x00,0x00,
0x00,0x44,0x0f,0x28,0x84,0x24,0xc0,0x00,0x00,0x00,0x0f,0x28,0xbc,0x24,0xd0,0x00,
0x00,0x00,0x0f,0x28,0xb4,0x24,0xe0,0x00,0x00,0x00,0x4c,0x8b,0xac,0x24,0xf0,0x00,
0x00,0x00,0x4c,0x8b,0xa4,0x24,0xf8,0x00,0x00,0x00,0x44,0x0f,0x28,0xa4,0x24,0x80,
0x00,0x00,0x00,
};
constexpr unsigned char code_7[]={
0x48,0x8b,0x9c,0x24,0x48,0x01,0x00,0x00,0x48,0x8b,0xb4,0x24,0x00,0x01,0x00,0x00,
0x48,0x81,0xc4,0x08,0x01,0x00,0x00,0x41,0x5f,0x41,0x5e,0x5f,0x5d,0xc3,
};
constexpr unsigned char code_8[]={
0x48,0x8b,0xce,0xe8,0x92,0xa2,0xc6,0xff,0x48,0x8d,0x14,0x80,0x48,0xc1,0xe2,0x04,
0xe8,0x45,0xa3,0xc6,0xff,0x48,0x03,0xd0,0xe8,0x3d,0xa3,0xc6,0xff,0x48,0x89,0x54,
0x24,0x38,0x4c,0x8d,0x0d,0x09,0x7e,0xd4,0x01,0x48,0x89,0x44,0x24,0x30,0x4c,0x8d,
0x05,0xe5,0xfa,0xdb,0x01,0x48,0x8d,0x05,0x06,0x81,0x96,0x01,0x48,0x89,0x5c,0x24,
0x28,0xba,0xab,0x02,0x00,0x00,0x48,0x89,0x44,0x24,0x20,0x48,0x8d,0x0d,0x58,0x7d,
0xd4,0x01,0xe8,0x63,0x25,0xc7,0xff,0xcc,
};
constexpr unsigned char code_9[]={
0x48,0x8b,0xc4,0x48,0x89,0x58,0x08,0x48,0x89,0x70,0x10,0x57,0x48,0x81,0xec,0x80,
0x00,0x00,0x00,0xf3,0x0f,0x10,0x49,0x10,0x49,0x8b,0xf1,0x0f,0x29,0x70,0xe8,0x48,
0x8b,0xda,0xf3,0x41,0x0f,0x10,0x70,0x04,0x48,0x8b,0xf9,0x0f,0x29,0x78,0xd8,0x0f,
0x57,0xff,0x0f,0x2e,0xcf,0x44,0x0f,0x29,0x40,0xc8,0xf3,0x45,0x0f,0x10,0x00,0x44,
0x0f,0x29,0x50,0xb8,0xf3,0x45,0x0f,0x10,0x50,0x08,0x44,0x0f,0x29,0x58,0xa8,0xf3,
0x45,0x0f,0x10,0x58,0x0c,0x0f,0x84,0xb4,0x00,0x00,0x00,0xf3,0x41,0x0f,0x59,0x09,
0xf3,0x0f,0x59,0x0d,0x54,0x03,0xe8,0x01,0x0f,0x28,0xc1,0xe8,0xb0,0x3f,0x6f,0x01,
0x0f,0x28,0xce,0x41,0x0f,0x28,0xda,0x41,0x0f,0x28,0xf0,0x41,0x0f,0x14,0xdb,0x0f,
0x14,0xf1,0x0f,0x28,0xc8,0x0f,0x16,0xf3,0x0f,0xc6,0xc0,0x01,0x0f,0x28,0xee,0x0f,
0x28,0xe0,0x0f,0xc6,0xee,0x01,0x0f,0x57,0xc0,0x0f,0x14,0xe1,0x0f,0x14,0xe0,0x0f,
0x28,0xde,0x0f,0xc6,0xde,0x66,0x44,0x0f,0x28,0xc6,0x44,0x0f,0xc6,0xc6,0xfb,0x0f,
0x28,0xc4,0x0f,0xc6,0xc4,0xe5,0x0f,0x28,0xcc,0x0f,0x59,0xe8,0x0f,0x28,0xd4,0x0f,
0xc6,0xf6,0x9c,0x0f,0xc6,0xcc,0x82,0x0f,0xc6,0xd4,0x1f,0x44,0x0f,0x59,0xc2,0x0f,
0x59,0xd9,0x0f,0xc6,0xe4,0x78,0x0f,0x59,0xf4,0x0f,0x58,0xeb,0x44,0x0f,0x58,0xc5,
0x44,0x0f,0x5c,0xc6,0x41,0x0f,0x28,0xc0,0x0f,0x57,0x05,0xf1,0x45,0xe8,0x01,0xf3,
0x44,0x0f,0x10,0xc0,0x41,0x0f,0x28,0xf0,0x45,0x0f,0x28,0xd0,0x45,0x0f,0x28,0xd8,
0x41,0x0f,0xc6,0xf0,0x55,0x45,0x0f,0xc6,0xd0,0xaa,0x45,0x0f,0xc6,0xd8,0xff,0xf3,
0x0f,0x10,0x4f,0x14,0x0f,0x2e,0xcf,0x0f,0x84,0xae,0x00,0x00,0x00,0xf3,0x0f,0x59,
0x4e,0x04,0xf3,0x0f,0x59,0x0d,0x92,0x02,0xe8,0x01,0x0f,0x28,0xc1,0xe8,0xee,0x3e,
0x6f,0x01,0x0f,0x28,0xce,0x41,0x0f,0x28,0xda,0x41,0x0f,0x14,0xdb,0x41,0x0f,0x28,
0xf0,0x0f,0x14,0xf1,0x0f,0x28,0xc8,0x0f,0x16,0xf3,0x0f,0xc6,0xc0,0x01,0x0f,0x28,
0xee,0x0f,0x28,0xe0,0x0f,0xc6,0xee,0x01,0x0f,0x57,0xc0,0x0f,0x14,0xe1,0x0f,0x16,
0xe0,0x0f,0x28,0xde,0x0f,0xc6,0xde,0x66,0x0f,0x28,0xfe,0x0f,0xc6,0xfe,0xfb,0x0f,
0x28,0xc4,0x0f,0xc6,0xc4,0xe5,0x0f,0x28,0xcc,0x0f,0x59,0xe8,0x0f,0x28,0xd4,0x0f,
0xc6,0xf6,0x9c,0x0f,0xc6,0xcc,0x82,0x0f,0xc6,0xd4,0x1f,0x0f,0x59,0xfa,0x0f,0x59,
0xd9,0x0f,0xc6,0xe4,0x78,0x0f,0x59,0xf4,0x0f,0x58,0xeb,0x0f,0x58,0xfd,0x0f,0x5c,
0xfe,0x0f,0x28,0xc7,0x0f,0x57,0x05,0x35,0x45,0xe8,0x01,0xf3,0x0f,0x10,0xf8,0x0f,
0x28,0xf7,0x44,0x0f,0x28,0xd7,0x0f,0xc6,0xf7,0x55,0x44,0x0f,0x28,0xc7,0x44,0x0f,
0xc6,0xd7,0xaa,0x0f,0xc6,0xff,0xff,0x44,0x0f,0x28,0xdf,0x0f,0x28,0x7c,0x24,0x60,
0x4c,0x8d,0x9c,0x24,0x80,0x00,0x00,0x00,0x49,0x8b,0x73,0x18,0x48,0x8b,0xc3,0x45,
0x0f,0xc6,0xc0,0xe1,0xf3,0x44,0x0f,0x10,0xc6,0x0f,0x28,0x74,0x24,0x70,0x45,0x0f,
0xc6,0xc0,0xc6,0xf3,0x45,0x0f,0x10,0xc2,0x45,0x0f,0x28,0x53,0xc0,0x45,0x0f,0xc6,
0xc0,0x27,0xf3,0x45,0x0f,0x10,0xc3,0x45,0x0f,0x28,0x5b,0xb0,0x45,0x0f,0xc6,0xc0,
0x39,0x44,0x0f,0x11,0x03,0x0f,0x10,0x5f,0x18,0x41,0x0f,0x28,0xc0,0x41,0x0f,0x28,
0xd0,0x41,0x0f,0xc6,0xc0,0x66,0x0f,0x28,0xe3,0x0f,0xc6,0xe3,0x82,0x0f,0x28,0xcb,
0x0f,0x59,0xe0,0x41,0x0f,0x28,0xc0,0x41,0x0f,0xc6,0xc0,0x01,0x0f,0xc6,0xcb,0xe5,
0x0f,0x59,0xc8,0x0f,0x28,0xc3,0x0f,0xc6,0xc3,0x1f,0x41,0x0f,0xc6,0xd0,0xfb,0x0f,
0x59,0xd0,0x0f,0x58,0xe1,0x45,0x0f,0xc6,0xc0,0x9c,0x0f,0xc6,0xdb,0x78,0x41,0x0f,
0x59,0xd8,0x45,0x0f,0x28,0x43,0xd0,0x0f,0x58,0xe2,0x0f,0x5c,0xe3,0x0f,0x28,0xc4,
0x0f,0x57,0x05,0x69,0x44,0xe8,0x01,0xf3,0x0f,0x10,0xe0,0x0f,0x11,0x23,0x49,0x8b,
0x5b,0x10,0x49,0x8b,0xe3,0x5f,0xc3,
};
constexpr unsigned char code_10[]={
0x48,0x8b,0xc4,0x55,0x57,0x41,0x55,0x41,0x56,0x48,0x8d,0x68,0xa8,0x48,0x81,0xec,
0x38,0x01,0x00,0x00,0x48,0xc7,0x41,0x10,0x00,0x00,0x00,0x00,0x4c,0x8b,0xea,0x4c,
0x8b,0x72,0x20,0x48,0x8b,0xf9,0x4c,0x8b,0x42,0x28,0x4f,0x8d,0x04,0xc6,0x4d,0x3b,
0xf0,0x0f,0x84,0x92,0x04,0x00,0x00,
};
constexpr unsigned char code_11[]={
0x48,0x89,0x58,0xd8,0x48,0x89,0x70,0xd0,0x4c,0x89,0x78,0xc8,0x0f,0x29,0x70,0xb8,
0x0f,0x29,0x78,0xa8,0x44,0x0f,0x29,0x40,0x98,0x44,0x0f,0x29,0x48,0x88,0x44,0x0f,
0x29,0x90,0x78,0xff,0xff,0xff,0x45,0x0f,0x57,0xd2,0x44,0x0f,0x29,0x98,0x68,0xff,
0xff,0xff,0xf3,0x44,0x0f,0x10,0x1d,0xf6,0x05,0xe8,0x01,0x44,0x0f,0x29,0xa0,0x58,
0xff,0xff,0xff,0x44,0x0f,0x29,0xa8,0x48,0xff,0xff,0xff,0x44,0x0f,0x29,0xb0,0x38,
0xff,0xff,0xff,0xf3,0x44,0x0f,0x10,0x35,0x49,0xff,0xe7,0x01,0x44,0x0f,0x29,0xb8,
0x28,0xff,0xff,0xff,0xf3,0x44,0x0f,0x10,0x3d,0x70,0x11,0xe8,0x01,0xc7,0x45,0x60,
0x00,0x00,0x32,0x43,0xc7,0x45,0x68,0x00,0x00,0x32,0x43,0x49,0x8b,0x1e,0xf3,0x0f,
0x10,0x43,0x30,0x41,0x0f,0x2f,0xc2,0x73,0x06,0x41,0x0f,0x28,0xc2,0xeb,0x0a,0x41,
0x0f,0x2f,0xc3,0x76,0x04,0x41,0x0f,0x28,0xc3,0xf3,0x0f,0x10,0x4b,0x34,0x41,0x0f,
0x2f,0xca,0xf3,0x0f,0x11,0x44,0x24,0x30,0x73,0x06,0x41,0x0f,0x28,0xca,0xeb,0x0a,
0x41,0x0f,0x2f,0xcb,0x76,0x04,0x41,0x0f,0x28,0xcb,0xf3,0x0f,0x58,0x43,0x38,0xf3,
0x0f,0x11,0x4c,0x24,0x3c,0x41,0x0f,0x2f,0xc2,0x73,0x06,0x41,0x0f,0x28,0xc2,0xeb,
0x05,0xf3,0x41,0x0f,0x5d,0xc3,0xf3,0x0f,0x58,0x4b,0x3c,0xf3,0x0f,0x11,0x44,0x24,
0x34,0x41,0x0f,0x2f,0xca,0x73,0x06,0x41,0x0f,0x28,0xca,0xeb,0x05,0xf3,0x41,0x0f,
0x5d,0xcb,0xf3,0x44,0x0f,0x10,0x63,0x40,0xf3,0x44,0x0f,0x10,0x6b,0x44,0xf3,0x0f,
0x11,0x4c,0x24,0x38,0xf3,0x0f,0x10,0x4b,0x48,0xf3,0x41,0x0f,0x59,0xce,0x0f,0x28,
0xc1,0xe8,0xf3,0x3a,0x6f,0x01,0xf3,0x0f,0x10,0x4b,0x4c,0x0f,0x28,0xf0,0xf3,0x41,
0x0f,0x59,0xce,0x0f,0x28,0xc1,0xe8,0xde,0x3a,0x6f,0x01,0x0f,0x28,0xc8,0xc7,0x45,
0x70,0x00,0x00,0x00,0x00,0x0f,0xc6,0xc0,0x01,0x0f,0x28,0xf8,0x0f,0x57,0xc0,0x0f,
0x14,0xf9,0xf3,0x0f,0x10,0x4b,0x50,0xf3,0x41,0x0f,0x59,0xce,0x0f,0x16,0xf8,0x0f,
0x28,0xc1,0xe8,0xb2,0x3a,0x6f,0x01,0x0f,0x28,0xd0,0x41,0x0f,0x28,0xca,0x0f,0xc6,
0xc0,0x01,0x44,0x0f,0x28,0xc8,0x0f,0x14,0xca,0x41,0x0f,0x28,0xc2,0x0f,0x28,0xd7,
0x44,0x0f,0x14,0xc8,0x0f,0x28,0xc6,0x0f,0xc6,0xf6,0x01,0x0f,0x14,0xf0,0x0f,0x57,
0xc0,0x0f,0x14,0xf0,0x0f,0x28,0xc7,0x0f,0xc6,0xc7,0xe5,0x0f,0x28,0xe6,0x0f,0xc6,
0xe6,0x01,0x0f,0x28,0xde,0x0f,0x59,0xe0,0x44,0x0f,0x28,0xc6,0x44,0x0f,0xc6,0xc6,
0xfb,0x0f,0xc6,0xde,0x66,0x44,0x0f,0x16,0xc9,0x0f,0x28,0xcf,0x0f,0xc6,0xcf,0x82,
0x0f,0x59,0xd9,0x0f,0xc6,0xd7,0x1f,0x44,0x0f,0x59,0xc2,0x0f,0x58,0xe3,0x0f,0xc6,
0xf6,0x9c,0x0f,0xc6,0xff,0x78,0x0f,0x59,0xf7,0x44,0x0f,0x58,0xc4,0x44,0x0f,0x5c,
0xc6,0x41,0x0f,0x28,0xc0,0x0f,0x57,0x05,0xed,0x40,0xe8,0x01,0xf3,0x44,0x0f,0x10,
0xc0,0x41,0x0f,0x28,0xc0,0x44,0x0f,0x29,0x44,0x24,0x20,0x41,0x0f,0x28,0xc8,0x41,
0x0f,0xc6,0xc0,0x55,0x41,0x0f,0x28,0xd0,0x41,0x0f,0xc6,0xc8,0xaa,0x41,0x0f,0xc6,
0xd0,0xff,0x45,0x0f,0xc6,0xc0,0xe1,0xf3,0x44,0x0f,0x10,0xc0,0x45,0x0f,0xc6,0xc0,
0xc6,0xf3,0x44,0x0f,0x10,0xc1,0x45,0x0f,0xc6,0xc0,0x27,0xf3,0x44,0x0f,0x10,0xc2,
0x45,0x0f,0xc6,0xc0,0x39,0x41,0x0f,0x28,0xe0,0x41,0x0f,0x28,0xd8,0x41,0x0f,0x28,
0xe8,0x41,0x0f,0xc6,0xe0,0x01,0x41,0x0f,0xc6,0xd8,0x66,0x41,0x0f,0xc6,0xe8,0xfb,
0x45,0x0f,0xc6,0xc0,0x9c,0x44,0x0f,0x2f,0x7b,0x60,0x48,0x8d,0x43,0x60,0x44,0x8b,
0x7b,0x5c,0x48,0x8d,0x4d,0x60,0xf2,0x0f,0x10,0x7b,0x54,0x41,0x0f,0x28,0xc1,0x41,
0x0f,0xc6,0xc1,0xe5,0x41,0x0f,0x28,0xc9,0x48,0x0f,0x47,0xc8,0x41,0x0f,0xc6,0xc9,
0x82,0x44,0x0f,0x2f,0x7b,0x64,0x48,0x8d,0x43,0x64,0x0f,0x59,0xe0,0x41,0x0f,0x28,
0xd1,0x41,0x0f,0xc6,0xd1,0x1f,0x0f,0x59,0xea,0x0f,0x59,0xd9,0xf3,0x0f,0x10,0x4b,
0x68,0x45,0x0f,0xc6,0xc9,0x78,0x45,0x0f,0x59,0xc1,0x0f,0x58,0xe3,0x0f,0x58,0xec,
0x41,0x0f,0x5c,0xe8,0xf3,0x44,0x0f,0x10,0x01,0x48,0x8d,0x4d,0x68,0x48,0x0f,0x47,
0xc8,0x41,0x0f,0x2f,0xca,0xf3,0x44,0x0f,0x10,0x09,0x0f,0x28,0xc5,0x0f,0x57,0x05,
0x05,0x40,0xe8,0x01,0xf3,0x0f,0x10,0xe8,0x0f,0x29,0x6c,0x24,0x20,0x0f,0x11,0x6c,
0x24,0x20,0x73,0x06,0x41,0x0f,0x28,0xca,0xeb,0x0a,0x41,0x0f,0x2f,0xcb,0x76,0x04,
0x41,0x0f,0x28,0xcb,0xf3,0x0f,0x10,0x43,0x6c,0x41,0x0f,0x2f,0xc2,0xf3,0x0f,0x11,
0x4c,0x24,0x6c,0x73,0x06,0x41,0x0f,0x28,0xc2,0xeb,0x0a,0x41,0x0f,0x2f,0xc3,0x76,
0x04,0x41,0x0f,0x28,0xc3,0xf3,0x0f,0x58,0x4b,0x70,0xf3,0x0f,0x11,0x44,0x24,0x78,
0x41,0x0f,0x2f,0xca,0x73,0x06,0x41,0x0f,0x28,0xca,0xeb,0x05,0xf3,0x41,0x0f,0x5d,
0xcb,0xf3,0x0f,0x58,0x43,0x74,0xf3,0x0f,0x11,0x4c,0x24,0x70,0x41,0x0f,0x2f,0xc2,
0x73,0x06,0x41,0x0f,0x28,0xc2,0xeb,0x05,0xf3,0x41,0x0f,0x5d,0xc3,0x48,0x8b,0x57,
0x10,0x0f,0xb6,0x73,0x78,0x48,0xff,0xc2,0x0f,0xb6,0x5b,0x79,0xf3,0x0f,0x11,0x44,
0x24,0x74,0x48,0x3b,0x57,0x18,0x76,0x11,0x48,0x8b,0x07,0x48,0x8b,0xcf,0xff,0x50,
0x18,0x84,0xc0,0x0f,0x84,0xa0,0x00,0x00,0x00,0x48,0x8b,0x57,0x10,0x48,0x8d,0x42,
0x01,0x4c,0x8d,0x0c,0x80,0x48,0x89,0x47,0x10,0x49,0xc1,0xe1,0x04,0x4c,0x8d,0x04,
0x92,0x4c,0x03,0x4f,0x08,0x49,0xc1,0xe0,0x04,0x4c,0x03,0x47,0x08,0x4d,0x3b,0xc1,
0x74,0x77,0x0f,0x10,0x4c,0x24,0x6c,0x49,0x8d,0x40,0x20,0x0f,0x10,0x54,0x24,0x30,
0xf3,0x0f,0x10,0x5c,0x24,0x2c,0xf3,0x0f,0x10,0x64,0x24,0x28,0xf3,0x0f,0x10,0x6c,
0x24,0x24,0xf3,0x0f,0x10,0x74,0x24,0x20,0x90,0x41,0x0f,0x11,0x10,0x49,0x83,0xc0,
0x50,0xf3,0x0f,0x11,0x70,0xf8,0xf3,0x0f,0x11,0x68,0xfc,0xf3,0x0f,0x11,0x20,0xf3,
0x0f,0x11,0x58,0x04,0xf2,0x0f,0x11,0x78,0x08,0x44,0x89,0x78,0x10,0xf3,0x44,0x0f,
0x11,0x60,0xf0,0xf3,0x44,0x0f,0x11,0x68,0xf4,0xf3,0x44,0x0f,0x11,0x40,0x14,0xf3,
0x44,0x0f,0x11,0x48,0x18,0x40,0x88,0x70,0x2c,0x88,0x58,0x2d,0x0f,0x11,0x48,0x1c,
0x48,0x8d,0x40,0x50,0x4d,0x3b,0xc1,0x75,0xb0,0x49,0x8b,0x4d,0x28,0x49,0x83,0xc6,
0x08,0x49,0x8b,0x45,0x20,0x48,0x8d,0x0c,0xc8,0x4c,0x3b,0xf1,0x0f,0x85,0x59,0xfc,
0xff,0xff,0x44,0x0f,0x28,0xbc,0x24,0x80,0x00,0x00,0x00,0x44,0x0f,0x28,0xb4,0x24,
0x90,0x00,0x00,0x00,0x44,0x0f,0x28,0xac,0x24,0xa0,0x00,0x00,0x00,0x44,0x0f,0x28,
0xa4,0x24,0xb0,0x00,0x00,0x00,0x44,0x0f,0x28,0x9c,0x24,0xc0,0x00,0x00,0x00,0x44,
0x0f,0x28,0x94,0x24,0xd0,0x00,0x00,0x00,0x44,0x0f,0x28,0x8c,0x24,0xe0,0x00,0x00,
0x00,0x44,0x0f,0x28,0x84,0x24,0xf0,0x00,0x00,0x00,0x0f,0x28,0xbc,0x24,0x00,0x01,
0x00,0x00,0x0f,0x28,0xb4,0x24,0x10,0x01,0x00,0x00,0x4c,0x8b,0xbc,0x24,0x20,0x01,
0x00,0x00,0x48,0x8b,0xb4,0x24,0x28,0x01,0x00,0x00,0x48,0x8b,0x9c,0x24,0x30,0x01,
0x00,0x00,
};
constexpr unsigned char code_12[]={
0x48,0x81,0xc4,0x38,0x01,0x00,0x00,0x41,0x5e,0x41,0x5d,0x5f,0x5d,0xc3,
};
constexpr unsigned char code_13[]={
0x48,0x8b,0xc4,0x53,0x48,0x81,0xec,0x80,0x00,0x00,0x00,0xf3,0x41,0x0f,0x10,0x28,
0x4c,0x8b,0xc9,0xf3,0x41,0x0f,0x10,0x60,0x08,0x48,0x8b,0xda,0x0f,0x29,0x70,0xe8,
0xf3,0x41,0x0f,0x10,0x70,0x04,0x0f,0x28,0xd6,0x0f,0x29,0x78,0xd8,0x0f,0x10,0x79,
0x10,0x48,0x8d,0x48,0xa4,0x0f,0x14,0xd4,0x0f,0x28,0xde,0x44,0x0f,0x29,0x40,0xc8,
0x0f,0x28,0xc7,0x0f,0xc6,0xc7,0x01,0x44,0x0f,0x29,0x48,0xb8,0x44,0x0f,0x28,0xcd,
0x44,0x0f,0x14,0xcd,0x44,0x0f,0x16,0xca,0x0f,0x57,0xd2,0x44,0x0f,0x59,0xc8,0x0f,
0x28,0xc7,0x0f,0xc6,0xc7,0x66,0x0f,0x14,0xd6,0x44,0x0f,0x29,0x50,0xa8,0x45,0x0f,
0x57,0xd2,0x0f,0x16,0xda,0x44,0x0f,0x5c,0xd7,0x0f,0x59,0xd8,0x0f,0x28,0xd4,0x0f,
0x14,0xd5,0x0f,0x28,0xc7,0x0f,0xc6,0xc7,0xfb,0x45,0x0f,0x28,0xc2,0x0f,0xc6,0xff,
0x9c,0x44,0x0f,0x57,0x05,0xd7,0x5a,0x18,0x01,0x44,0x0f,0x58,0xcb,0xf3,0x45,0x0f,
0x10,0xd0,0x0f,0x28,0xdc,0x0f,0x14,0xdc,0x0f,0x16,0xdd,0x0f,0x59,0xd8,0x44,0x0f,
0x58,0xcb,0x0f,0x57,0xdb,0x0f,0x14,0xde,0x0f,0x16,0xda,0x0f,0x59,0xdf,0x44,0x0f,
0x5c,0xcb,0x41,0x0f,0x28,0xc1,0x0f,0x57,0x05,0xa3,0x5a,0x18,0x01,0xf3,0x44,0x0f,
0x10,0xc8,0x41,0x0f,0x28,0xc2,0x41,0x0f,0xc6,0xc2,0xe5,0x41,0x0f,0x28,0xc9,0x41,
0x0f,0xc6,0xc9,0x66,0x41,0x0f,0x28,0xd1,0x44,0x0f,0x11,0x48,0x98,0x41,0x0f,0x28,
0xf1,0x41,0x0f,0xc6,0xf1,0x01,0x0f,0x59,0xf0,0x41,0x0f,0x28,0xc2,0x41,0x0f,0xc6,
0xc2,0x82,0x0f,0x59,0xc8,0x41,0x0f,0x28,0xc2,0x41,0x0f,0xc6,0xc2,0x1f,0x41,0x0f,
0xc6,0xd1,0xfb,0x0f,0x59,0xd0,0x0f,0x58,0xf1,0x44,0x0f,0x11,0x50,0x98,0x45,0x0f,
0xc6,0xc9,0x9c,0x45,0x0f,0xc6,0xd2,0x78,0x45,0x0f,0x59,0xca,0x0f,0x58,0xf2,0x41,
0x0f,0x5c,0xf1,0x0f,0x28,0xc6,0x0f,0x57,0x05,0x33,0x5a,0x18,0x01,0xf3,0x0f,0x10,
0xf0,0x0f,0x28,0xce,0x0f,0x11,0x70,0x98,0x0f,0xc6,0xce,0x55,0xe8,0x0f,0x58,0xd9,
0xfe,0xf3,0x0f,0x11,0x44,0x24,0x20,0x48,0x8d,0x4c,0x24,0x2e,0x0f,0x28,0xc6,0x0f,
0xc6,0xc6,0xaa,0x0f,0xc6,0xf6,0xff,0x0f,0x28,0xce,0xf3,0x0f,0x11,0x44,0x24,0x24,
0xe8,0xeb,0x57,0xd9,0xfe,0xf3,0x0f,0x11,0x44,0x24,0x28,0x48,0x8d,0x54,0x24,0x20,
0x41,0x0f,0x10,0x01,0x48,0x8b,0xcb,0x0f,0x11,0x03,0xe8,0x31,0x4a,0xd9,0xfe,0x0f,
0x28,0x74,0x24,0x70,0x48,0x8b,0xc3,0x0f,0x28,0x7c,0x24,0x60,0x44,0x0f,0x28,0x44,
0x24,0x50,0x44,0x0f,0x28,0x4c,0x24,0x40,0x44,0x0f,0x28,0x54,0x24,0x30,0x48,0x81,
0xc4,0x80,0x00,0x00,0x00,0x5b,0xc3,
};
constexpr CodeRange inspected_camera_code[]={
{0x481580,code_0,sizeof(code_0)},
{0x4815f0,code_1,sizeof(code_1)},
{0x48191f,code_2,sizeof(code_2)},
{0x481950,code_3,sizeof(code_3)},
{0x48a140,code_4,sizeof(code_4)},
{0x48a1b7,code_5,sizeof(code_5)},
{0x48a215,code_6,sizeof(code_6)},
{0x48a648,code_7,sizeof(code_7)},
{0x48a666,code_8,sizeof(code_8)},
{0x69cb40,code_9,sizeof(code_9)},
{0x69cf20,code_10,sizeof(code_10)},
{0x69cf57,code_11,sizeof(code_11)},
{0x69d3e9,code_12,sizeof(code_12)},
{0x139b6b0,code_13,sizeof(code_13)},
};
}
-80
View File
@@ -1,80 +0,0 @@
#pragma once
#include <windows.h>
#include <bcrypt.h>
#include <cstdio>
#include <cstring>
#include "build_fingerprint.h"
#pragma comment(lib,"bcrypt.lib")
namespace forward_camera {
inline bool verified_loaded_camera(const void* loaded_image=nullptr,unsigned long* mismatch=nullptr) {
// Compare every unwind chunk of the composition function, both callers,
// cached-view builder, and offset helper. No relocations occur in these ranges.
const auto* image=static_cast<const unsigned char*>(loaded_image ? loaded_image : GetModuleHandleW(nullptr));
if (mismatch) *mismatch=0;
__try {
MEMORY_BASIC_INFORMATION first{};
if (!image || !VirtualQuery(image,&first,sizeof(first)) || first.AllocationBase!=image ||
first.State!=MEM_COMMIT || (first.Protect&(PAGE_NOACCESS|PAGE_GUARD))) return false;
const auto* dos=reinterpret_cast<const IMAGE_DOS_HEADER*>(image);
if (dos->e_magic!=IMAGE_DOS_SIGNATURE || dos->e_lfanew<sizeof(*dos) || dos->e_lfanew>0x800) return false;
const auto* nt=reinterpret_cast<const IMAGE_NT_HEADERS64*>(image+dos->e_lfanew);
if (nt->Signature!=IMAGE_NT_SIGNATURE || nt->FileHeader.Machine!=IMAGE_FILE_MACHINE_AMD64 ||
nt->FileHeader.TimeDateStamp!=inspected_timestamp ||
nt->OptionalHeader.SizeOfImage!=inspected_image_size) return false;
for(const auto& range:inspected_camera_code) {
if (mismatch) *mismatch=range.rva;
if (range.rva>=inspected_image_size || range.size>inspected_image_size-range.rva) return false;
const auto* current=image+range.rva;
const auto* end=current+range.size;
while(current<end) {
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(current,&region,sizeof(region)) || region.AllocationBase!=image ||
region.State!=MEM_COMMIT || (region.Protect&(PAGE_NOACCESS|PAGE_GUARD))) return false;
const auto* next=static_cast<const unsigned char*>(region.BaseAddress)+region.RegionSize;
if (next<=current) return false;
current=next<end ? next : end;
}
if(std::memcmp(image+range.rva,range.bytes,range.size)!=0) return false;
}
if (mismatch) *mismatch=0;
return true;
} __except(EXCEPTION_EXECUTE_HANDLER) { return false; }
}
struct BuildCheck { const char* stage="path"; unsigned long error=0; char digest[65]{}; wchar_t path[32768]{}; };
inline bool verified_game_build(const wchar_t* inspected_path=nullptr,BuildCheck* detail=nullptr) {
// Exact executable inspected offline for the monitor function ABI and layout.
constexpr const char* expected="1d2d6b0c3a0ec3a6b379b629d2abbca9834afde771c85c0d6f5663ae9281260d";
BuildCheck local{};
auto& report=detail ? *detail : local;
auto& path=report.path;
if (inspected_path) {
if (wcslen(inspected_path)>=32768) return false;
wcscpy_s(path,inspected_path);
} else if (!GetModuleFileNameW(nullptr,path,32768)) { report.error=GetLastError();return false; }
report.stage="open";
const HANDLE file=CreateFileW(path,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
if (file==INVALID_HANDLE_VALUE) { report.error=GetLastError();return false; }
BCRYPT_ALG_HANDLE algorithm=nullptr;BCRYPT_HASH_HANDLE hash=nullptr;
report.stage="provider";
NTSTATUS status=BCryptOpenAlgorithmProvider(&algorithm,BCRYPT_SHA256_ALGORITHM,nullptr,0);
bool okay=status>=0;
if (okay) { report.stage="create";status=BCryptCreateHash(algorithm,&hash,nullptr,0,nullptr,0,0);okay=status>=0; }
unsigned char buffer[32768]{};DWORD count=0;
while (okay) {
report.stage="read";
if (!ReadFile(file,buffer,sizeof(buffer),&count,nullptr)) { report.error=GetLastError();okay=false;break; }
if (!count) break;
report.stage="hash";status=BCryptHashData(hash,buffer,count,0);okay=status>=0;
}
unsigned char digest[32]{};
if (okay) { report.stage="finish";status=BCryptFinishHash(hash,digest,sizeof(digest),0);okay=status>=0; }
if (hash) BCryptDestroyHash(hash);
if (algorithm) BCryptCloseAlgorithmProvider(algorithm,0);
CloseHandle(file);
if (!okay && !report.error) report.error=static_cast<unsigned long>(status);
for(int i=0;i<32;++i) std::snprintf(report.digest+2*i,3,"%02x",digest[i]);
if (okay) report.stage="compare";
return okay && std::strcmp(report.digest,expected)==0;
}
}
@@ -1,83 +0,0 @@
"""Generate exact loaded-code checks from the already inspected ATS executable."""
import argparse
import hashlib
import struct
from pathlib import Path
EXPECTED = "1d2d6b0c3a0ec3a6b379b629d2abbca9834afde771c85c0d6f5663ae9281260d"
FUNCTIONS = (0x69CB40, 0x481580, 0x48A140, 0x69CF20, 0x139B6B0)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("executable", type=Path)
args = parser.parse_args()
binary = args.executable.read_bytes()
if hashlib.sha256(binary).hexdigest() != EXPECTED:
raise SystemExit("Executable is not the inspected build; no fingerprint generated")
pe = struct.unpack_from("<I", binary, 0x3C)[0]
count, = struct.unpack_from("<H", binary, pe + 6)
optional_size, = struct.unpack_from("<H", binary, pe + 20)
optional = pe + 24
sections = []
for i in range(count):
at = optional + optional_size + i * 40
virtual_size, rva, raw_size, offset = struct.unpack_from("<4I", binary, at + 8)
sections.append((rva, virtual_size, offset, raw_size))
def data(rva, size):
for start, virtual_size, offset, raw_size in sections:
if start <= rva and rva + size <= start + min(virtual_size, raw_size):
return binary[offset + rva - start:offset + rva - start + size]
raise ValueError(f"Unmapped file range {rva:x}+{size:x}")
pdata_rva, pdata_size = struct.unpack_from("<II", binary, optional + 112 + 3 * 8)
entries = [struct.unpack("<III", data(pdata_rva + i, 12)) for i in range(0, pdata_size, 12)]
def root(entry):
for _ in range(12):
header = data(entry[2], 4)
if not header[0] >> 3 & 4:
return entry[0]
entry = struct.unpack("<III", data(entry[2] + 4 + ((2 * header[2] + 3) // 4) * 4, 12))
raise ValueError("Unwind chain too long")
ranges = [(start, end - start) for entry in entries
if root(entry) in FUNCTIONS for start, end, _ in [entry]]
if {root(e) for e in entries if root(e) in FUNCTIONS} != set(FUNCTIONS):
raise ValueError("Missing inspected function")
# Raw loaded-byte comparisons require ranges without PE base relocations.
reloc_rva, reloc_size = struct.unpack_from("<II", binary, optional + 112 + 5 * 8)
cursor = 0
while cursor < reloc_size:
page, size = struct.unpack("<II", data(reloc_rva + cursor, 8))
if size < 8 or size % 2:
raise ValueError("Invalid relocation block")
for i in range(8, size, 2):
item, = struct.unpack("<H", data(reloc_rva + cursor + i, 2))
target = page + (item & 0xFFF)
if item >> 12 and any(start <= target < start + length for start, length in ranges):
raise ValueError("Relocation in inspected function; raw comparison unsafe")
cursor += size
image_size, = struct.unpack_from("<I", binary, optional + 56)
timestamp, = struct.unpack_from("<I", binary, pe + 8)
lines = ["// Generated from the SHA256-verified, offline-inspected ATS 1.61.2 executable.",
"// Regenerate with generate_build_fingerprint.py; base-relocated ranges are rejected.",
"#pragma once", "namespace forward_camera {",
f"constexpr unsigned long inspected_image_size=0x{image_size:x};",
f"constexpr unsigned long inspected_timestamp=0x{timestamp:x};",
"struct CodeRange { unsigned long rva; const unsigned char* bytes; unsigned long size; };"]
for i, (start, size) in enumerate(ranges):
lines.append(f"constexpr unsigned char code_{i}[]={{")
body = data(start, size)
lines += [" " + ",".join(f"0x{v:02x}" for v in body[j:j+16]) + "," for j in range(0, size, 16)]
lines.append("};")
lines.append("constexpr CodeRange inspected_camera_code[]={")
lines += [f" {{0x{start:x},code_{i},sizeof(code_{i})}}," for i, (start, _) in enumerate(ranges)]
lines += ["};", "}", ""]
Path(__file__).with_name("build_fingerprint.h").write_text("\n".join(lines))
print(f"Generated {len(ranges)} ranges, {sum(size for _, size in ranges)} code bytes across five inspected functions")
if __name__ == "__main__":
main()
-69
View File
@@ -1,69 +0,0 @@
#pragma once
#include <windows.h>
#include <cstring>
#include <cstdint>
#include "rotation.h"
namespace forward_camera {
// Read-only RenCloud revision 12 transport, already used by the driving controller.
// Layout: https://github.com/RenCloud/scs-sdk-plugin/blob/V.1.12.1/scs-telemetry/inc/scs-telemetry-common.hpp
struct HeadSample { Vec position; double yaw,pitch,roll; uint64_t timestamp; float speed_mps; bool park_brake,paused; };
inline bool decode_head(const unsigned char* bytes,HeadSample& sample) {
uint32_t revision=0,game=0;float values[6]{};
std::memcpy(&revision,bytes+40,4);std::memcpy(&game,bytes+52,4);
std::memcpy(&sample.timestamp,bytes+8,8);
std::memcpy(&sample.speed_mps,bytes+948,4);
sample.park_brake=bytes[1566]!=0;
sample.paused=bytes[4]!=0;
std::memcpy(values,bytes+2024,sizeof(values));
if(!bytes[0] || bytes[4] || revision!=12 || game!=2 || !sample.timestamp) return false;
for(float v:values) if(!std::isfinite(v)) return false;
sample.position={values[0],values[1],values[2]};
sample.yaw=std::remainder(values[3]*2*pi,2*pi);sample.pitch=values[4]*2*pi;
sample.roll=std::remainder(values[5]*2*pi,2*pi);
return std::abs(sample.position.x)<3 && std::abs(sample.position.y)<3 &&
std::abs(sample.position.z)<3 && std::abs(sample.pitch)<pi;
}
class HeadTelemetry {
HANDLE mapping=nullptr;
const unsigned char* view=nullptr;
uint64_t previous=0;
ULONGLONG changed=0,retry=0;
public:
HeadTelemetry()=default;
HeadTelemetry(const HeadTelemetry&)=delete;
HeadTelemetry& operator=(const HeadTelemetry&)=delete;
~HeadTelemetry() { close(); }
void close() {
if(view) UnmapViewOfFile(view);
if(mapping) CloseHandle(mapping);
view=nullptr;mapping=nullptr;previous=0;changed=0;retry=0;
}
bool read(HeadSample& sample) {
const auto now=GetTickCount64();
if(!view) {
if(now<retry) return false;
retry=now+1000;
// Never create a mapping or write SDK memory.
mapping=OpenFileMappingW(FILE_MAP_READ,FALSE,L"Local\\SCSTelemetry");
if(!mapping) return false;
view=static_cast<const unsigned char*>(MapViewOfFile(mapping,FILE_MAP_READ,0,0,2048));
if(!view) { CloseHandle(mapping);mapping=nullptr;return false; }
}
unsigned char snapshot[2048]{};uint64_t before=0,after=0;
bool coherent=false;
for(int attempt=0;attempt<3;++attempt) {
std::memcpy(&before,view+8,8);
MemoryBarrier();
std::memcpy(snapshot,view,sizeof(snapshot));
MemoryBarrier();
std::memcpy(&after,view+8,8);
uint64_t copied=0;std::memcpy(&copied,snapshot+8,8);
if(before==after && before==copied) { coherent=true;break; }
}
if(!coherent || !decode_head(snapshot,sample)) return false;
if(sample.timestamp!=previous) { previous=sample.timestamp;changed=now; }
return changed && now-changed<250;
}
};
}
-74
View File
@@ -1,74 +0,0 @@
param(
[Parameter(Mandatory=$true)][string]$PluginsDir,
[switch]$EnablePassiveTest
)
$ErrorActionPreference='Stop'
$taskRoot=Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
$taskDestination=[IO.Path]::GetFullPath($PluginsDir)
if ((Split-Path $taskDestination -Leaf) -ne 'plugins' -or
-not (Test-Path -LiteralPath (Join-Path (Split-Path $taskDestination -Parent) 'amtrucks.exe'))) {
throw 'Expected the ATS bin/win_x64/plugins directory beside amtrucks.exe.'
}
if (Get-Process amtrucks -ErrorAction SilentlyContinue) { throw 'Close ATS before installing camera DLLs.' }
$taskDll=Join-Path $PSScriptRoot 'build/ForwardCamera.dll'
if (-not (Test-Path -LiteralPath $taskDll)) { throw 'Build ForwardCamera first.' }
$taskArchive=Join-Path $taskRoot 'diagnostics/spf-reference/spf-framework_v1.2.5.zip'
if (-not (Test-Path -LiteralPath $taskArchive)) {
New-Item -ItemType Directory -Force (Split-Path $taskArchive -Parent) | Out-Null
Invoke-WebRequest 'https://github.com/TrackAndTruckDevs/SPF-Framework/releases/download/v1.2.5/spf-framework_v1.2.5.zip' -OutFile $taskArchive
}
if ((Get-FileHash -LiteralPath $taskArchive).Hash -ne 'F863189F3AF4E17BBA6F1F6C8027CF3A3BFF5331D7EA53FFFA2B6B30F7D7B24C') { throw 'SPF archive hash mismatch.' }
$taskRuntime=Join-Path $taskRoot 'diagnostics/spf-reference/spf-framework_v1.2.5'
Expand-Archive -LiteralPath $taskArchive -DestinationPath $taskRuntime -Force
if ((Get-FileHash -LiteralPath (Join-Path $taskRuntime 'spf-framework.dll')).Hash -ne '92B98AACB6CF1099B7CC218438C680EF92D32DBABA09D2B474E640EBB25EB1D6') { throw 'SPF DLL hash mismatch.' }
$taskBackup=Join-Path $taskRoot ('diagnostics/forward-camera-install-'+(Get-Date -Format 'yyyyMMdd-HHmmss-fffffff'))
New-Item -ItemType Directory -Force $taskBackup,$taskDestination | Out-Null
$taskTouched=@('spf-framework.dll','spfAssets','spfPlugins/ForwardCamera')
foreach ($taskRelative in $taskTouched) {
$taskExisting=Join-Path $taskDestination $taskRelative
if (Test-Path -LiteralPath $taskExisting) {
$taskSaved=Join-Path $taskBackup $taskRelative
New-Item -ItemType Directory -Force (Split-Path $taskSaved -Parent) | Out-Null
Copy-Item -LiteralPath $taskExisting -Destination $taskSaved -Recurse
}
}
Copy-Item -LiteralPath (Join-Path $taskRuntime 'spf-framework.dll') -Destination $taskDestination -Force
Copy-Item -LiteralPath (Join-Path $taskRuntime 'spfAssets') -Destination $taskDestination -Recurse -Force
$taskPlugin=Join-Path $taskDestination 'spfPlugins/ForwardCamera'
New-Item -ItemType Directory -Force (Join-Path $taskPlugin 'config') | Out-Null
Copy-Item -LiteralPath $taskDll -Destination (Join-Path $taskPlugin 'ForwardCamera.dll') -Force
$taskUserSid=[Security.Principal.WindowsIdentity]::GetCurrent().User.Value
foreach ($taskData in @((Join-Path $taskDestination 'spfAssets'),$taskPlugin)) {
# SPF creates logs/config here during normal unelevated game startup.
& icacls.exe $taskData /grant "*$($taskUserSid):(OI)(CI)M" /T /Q | Out-Null
if ($LASTEXITCODE -ne 0) { throw "Could not grant the current user access to SPF data: $taskData" }
}
New-Item -ItemType Directory -Force (Join-Path $taskDestination 'spfAssets/logs'),(Join-Path $taskPlugin 'logs') | Out-Null
$taskFrameworkConfig=Join-Path $taskDestination 'spfAssets/config/framework_settings.json'
New-Item -ItemType Directory -Force (Split-Path $taskFrameworkConfig -Parent) | Out-Null
$taskFramework=@{}
if (Test-Path -LiteralPath $taskFrameworkConfig) { $taskFramework=Get-Content -LiteralPath $taskFrameworkConfig -Raw | ConvertFrom-Json -AsHashtable }
if (-not $taskFramework.ContainsKey('settings')) { $taskFramework.settings=@{} }
if (-not $taskFramework.settings.ContainsKey('framework')) { $taskFramework.settings.framework=@{} }
# This local camera experiment does not need online connections or remote reports.
$taskFramework.settings.framework.connect=$false
if (-not $taskFramework.settings.ContainsKey('plugin_states')) { $taskFramework.settings.plugin_states=@{} }
$taskFramework.settings.plugin_states.ForwardCamera=@{enabled=[bool]$EnablePassiveTest}
if (-not $taskFramework.ContainsKey('logging')) { $taskFramework.logging=@{} }
if (-not $taskFramework.logging.ContainsKey('sinks')) { $taskFramework.logging.sinks=@{} }
$taskFramework.logging.sinks.report=$false
$taskFramework | ConvertTo-Json -Depth 20 | Set-Content -LiteralPath $taskFrameworkConfig -Encoding utf8
$taskCameraConfig=Join-Path $taskPlugin 'config/settings.json'
$taskCamera=@{}
if (Test-Path -LiteralPath $taskCameraConfig) { $taskCamera=Get-Content -LiteralPath $taskCameraConfig -Raw | ConvertFrom-Json -AsHashtable }
if (-not $taskCamera.ContainsKey('settings')) { $taskCamera.settings=@{} }
$taskCameraDefaults=@{pitch_degrees=-5.049066;offset_x=0;offset_y=-1.2;offset_z=-2.5;yaw_sign=1;pitch_sign=1;local_matrix=$true;projection_timing=$false;yaw_lead_ms=0;pitch_lead_ms=0;pose_probe=$false;render_hook=$false;cancel_head_translation=$false}
foreach ($taskKey in $taskCameraDefaults.Keys) {
if (-not $taskCamera.settings.ContainsKey($taskKey)) { $taskCamera.settings[$taskKey]=$taskCameraDefaults[$taskKey] }
}
$taskCamera.settings.enabled=[bool]$EnablePassiveTest
$taskCamera | ConvertTo-Json -Depth 20 | Set-Content -LiteralPath $taskCameraConfig -Encoding utf8
@{plugins_dir=$taskDestination;backup=$taskBackup;touched=$taskTouched;passive_enabled=[bool]$EnablePassiveTest;validated=$false} |
ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $taskBackup 'installation.json') -Encoding utf8
Write-Output "Installed passive prototype. Backup/rollback inventory: $taskBackup"
Write-Output 'Restart ATS to load. Auxiliary active control remains blocked pending image validation and calibration.'
-37
View File
@@ -1,37 +0,0 @@
#pragma once
#include "rotation.h"
namespace forward_camera {
// Short prediction for the measured render delay; never used for vehicle inputs.
class HeadMotion {
bool ready=false;
double time=0, moved=0;
Vec pose{}, rate{};
static double delta(double a,double b) {
return std::remainder(a-b,2*pi);
}
public:
void reset() { ready=false; rate={}; }
Vec sample(double now,Vec head,double yaw_lead,double pitch_lead) {
if(!ready || now<=time || now-time>0.2) {
ready=true; time=moved=now; pose=head; rate={};
} else if(now-time>=0.006) {
const double dt=now-time;
const Vec change{delta(head.x,pose.x),head.y-pose.y,delta(head.z,pose.z)};
if(std::abs(change.x)+std::abs(change.y)+std::abs(change.z)>1e-6) {
const double weight=1-std::exp(-dt/0.015);
rate.x += weight*(std::clamp(change.x/dt,-12.0,12.0)-rate.x);
rate.y += weight*(std::clamp(change.y/dt,-12.0,12.0)-rate.y);
moved=now;
} else {
// Stop prediction promptly when the head stops moving.
rate.x*=std::exp(-dt/0.012); rate.y*=std::exp(-dt/0.012);
}
pose=head; time=now;
}
if(now-moved>0.04) rate={};
return {head.x+std::clamp(rate.x*yaw_lead,-0.08,0.08),
std::clamp(head.y+std::clamp(rate.y*pitch_lead,-0.08,0.08),-1.56,1.56),head.z};
}
};
}
-23
View File
@@ -1,23 +0,0 @@
#pragma once
#include <windows.h>
#include <cstring>
#include <cstdint>
namespace forward_camera {
// Read-only candidate layout from ETS2LA's core_camera_u for ATS 1.60.
// ATS 1.61 must be verified from observations; never write through this layout.
struct PoseSnapshot { float raw[16]; };
inline bool read_pose_candidate(void* object, PoseSnapshot* out) noexcept {
const auto start=reinterpret_cast<uintptr_t>(object);
if (!object || !out || start>UINTPTR_MAX-0x60) return false;
MEMORY_BASIC_INFORMATION region{};
const auto source=reinterpret_cast<const void*>(start+0x20);
if (!VirtualQuery(source,&region,sizeof(region)) || region.State!=MEM_COMMIT ||
(region.Protect & (PAGE_GUARD|PAGE_NOACCESS))) return false;
const auto end=reinterpret_cast<uintptr_t>(region.BaseAddress)+region.RegionSize;
if (end<start+0x60) return false;
__try { std::memcpy(out->raw,source,sizeof(out->raw)); }
__except(EXCEPTION_EXECUTE_HANDLER) { return false; }
return true;
}
}
-60
View File
@@ -1,60 +0,0 @@
#pragma once
#include <atomic>
#include <cstdint>
#include "render_view.h"
#include "head_telemetry.h"
namespace forward_camera {
inline bool trace_parked(bool fresh_sdk,const HeadSample& sample) {
// Same 0.1 mph stationary bound used by the nominal-origin capture.
// Motion validation affects diagnostics only, not camera compensation.
return fresh_sdk && !sample.paused && sample.park_brake && std::isfinite(sample.speed_mps) &&
std::abs(sample.speed_mps)<0.1/2.23693629;
}
// Opt-in, one-minute observation. The render callback never invokes the logger.
// A single pending snapshot is drained on SPF OnUpdate; contention drops samples.
struct RenderTraceSample {
uint64_t host_ms=0,generation=0;
int camera_type=-1;
bool camera_valid=false,outside_valid=false,outside=false,spf_valid=false,spf_roll_valid=false,
seat_valid=false,sdk_valid=false,applied=false,translation=false;
double spf_yaw=0,spf_pitch=0,spf_roll=0;
Vec seat{},offset_before{},offset_after{};
HeadSample sdk{};
Quat base{},output_before{},output_after{};
float viewport[4]{},frustum_fov[2]{},frustum_subrect[4]{};
};
class RenderTrace {
std::atomic_flag lock=ATOMIC_FLAG_INIT;
uint64_t started=0,next=0,generation=0;
bool begun=false,pending=false;
RenderTraceSample sample{};
public:
void reset() {
while(lock.test_and_set(std::memory_order_acquire)) {}
begun=false;pending=false;started=next=generation=0;
lock.clear(std::memory_order_release);
}
bool select(uint64_t now,bool enabled,bool road,bool parked,uint64_t& frame) {
if(!enabled || !road || !parked || lock.test_and_set(std::memory_order_acquire)) return false;
frame=++generation;
if(!begun) { started=now;next=now;begun=true; }
const bool selected=now>=started && now-started<60000 && now>=next;
if(selected) next=now+100;
lock.clear(std::memory_order_release);
return selected;
}
void submit(const RenderTraceSample& value) {
if(lock.test_and_set(std::memory_order_acquire)) return;
if(!pending) { sample=value;pending=true; }
lock.clear(std::memory_order_release);
}
bool take(RenderTraceSample& value) {
if(lock.test_and_set(std::memory_order_acquire)) return false;
const bool result=pending;
if(result) { value=sample;pending=false; }
lock.clear(std::memory_order_release);
return result;
}
};
}
-94
View File
@@ -1,94 +0,0 @@
#pragma once
#include "rotation.h"
#include <cstdint>
#include <cstddef>
namespace forward_camera {
struct Quat { float w,x,y,z; };
struct ViewInfo {
float rect[4]; // x_min, x_max, y_max, y_min
float relative_fov[2];
Quat rotation;
float offset[3];
float fov[2];
float subrect[4];
uint8_t interior,exterior;
uint8_t padding[2];
};
static_assert(sizeof(ViewInfo)==0x50);
static_assert(offsetof(ViewInfo,rotation)==0x18 && offsetof(ViewInfo,offset)==0x28);
static_assert(offsetof(ViewInfo,interior)==0x4c);
inline Quat product(Quat a,Quat b) {
return {a.w*b.w-a.x*b.x-a.y*b.y-a.z*b.z,
a.w*b.x+a.x*b.w+a.y*b.z-a.z*b.y,
a.w*b.y-a.x*b.z+a.y*b.w+a.z*b.x,
a.w*b.z+a.x*b.y-a.y*b.x+a.z*b.w};
}
inline Quat conjugate(Quat q) { return {q.w,-q.x,-q.y,-q.z}; }
inline bool normalize(Quat& q) {
const double length=std::sqrt(double(q.w)*q.w+double(q.x)*q.x+double(q.y)*q.y+double(q.z)*q.z);
if (!std::isfinite(length) || length<0.9 || length>1.1) return false;
q={float(q.w/length),float(q.x/length),float(q.y/length),float(q.z/length)};
return true;
}
inline Quat head_quaternion(double yaw,double pitch,double roll=0) {
const Quat y{float(std::cos(yaw/2)),0,float(std::sin(yaw/2)),0};
const Quat p{float(std::cos(pitch/2)),float(std::sin(pitch/2)),0,0};
const Quat r{float(std::cos(roll/2)),0,0,float(std::sin(roll/2))};
return product(product(y,p),r);
}
inline bool road_viewport(const ViewInfo& view) {
// Exact 512x256 viewports at 2560x1440: legacy top-center or top-right
// with 32px margins. MED placement preserves optics; optional SBIG optics
// must match their own exact pair below, never an arbitrary viewport/FOV.
// A different layout/FOV fails closed; the cabin and mirrors cannot match.
for(float value:view.rect) if(!std::isfinite(value)) return false;
const bool center=std::abs(view.rect[0]-0.4f)<0.00001f &&
std::abs(view.rect[1]-0.6f)<0.00001f;
const bool right=std::abs(view.rect[0]-0.7875f)<0.00001f &&
std::abs(view.rect[1]-0.9875f)<0.00001f;
if(!(center || right) || std::abs(view.rect[2]-0.2f)>0.00001f ||
std::abs(view.rect[3]-0.022222222f)>0.00001f) return false;
return view.interior==0 && view.exterior==1;
}
inline bool matches_road(const ViewInfo& view) {
if(!road_viewport(view)) return false;
const bool med=std::abs(view.fov[0]-31.424569f)<0.001f &&
std::abs(view.fov[1]-16.013317f)<0.001f;
const bool sbig=std::abs(view.fov[0]-58.727464f)<0.001f &&
std::abs(view.fov[1]-31.424569f)<0.001f;
// Config-pinned asymmetric SBIG candidate: square full frustum cropped by
// SCS's documented bottom-origin subrect. Raw subrect ABI is logged, not
// assumed to be verified by this FOV/viewport recognition.
const bool asymmetric=std::abs(view.rect[0]-0.7875f)<0.00001f &&
std::abs(view.fov[0]-58.727464f)<0.001f &&
std::abs(view.fov[1]-58.727464f)<0.001f;
return view.interior==0 && view.exterior==1 &&
std::isfinite(view.fov[0]) && std::isfinite(view.fov[1]) && (med || sbig || asymmetric) &&
view.relative_fov[0]==0 && view.relative_fov[1]==0;
}
inline bool cancel_translation(Vec target,Vec head,Vec seat,Vec& corrected) {
const Vec delta{head.x-seat.x,head.y-seat.y,head.z-seat.z};
if (!std::isfinite(delta.x) || !std::isfinite(delta.y) || !std::isfinite(delta.z) ||
std::abs(delta.x)>1 || std::abs(delta.y)>1 || std::abs(delta.z)>1) return false;
corrected={target.x-delta.x,target.y-delta.y,target.z-delta.z};
return true;
}
inline bool fix_view(ViewInfo& view,Quat base,Quat& output,
double yaw,double pitch,double roll,double target_pitch,Vec target_offset) {
if (!matches_road(view) || !normalize(base) || !std::isfinite(yaw) ||
!std::isfinite(pitch) || !std::isfinite(roll) || std::abs(yaw)>3.3 ||
std::abs(pitch)>1.57 || std::abs(roll)>pi || !std::isfinite(target_pitch) ||
std::abs(target_pitch)>pi/4 || !std::isfinite(target_offset.x) ||
!std::isfinite(target_offset.y) || !std::isfinite(target_offset.z) ||
std::abs(target_offset.x)>10 || std::abs(target_offset.y)>10 || std::abs(target_offset.z)>10) return false;
const auto head=head_quaternion(yaw,pitch,roll);
auto desired=product(product(base,conjugate(head)),head_quaternion(0,target_pitch));
if (!normalize(desired)) return false;
const auto offset=transform(transpose(rotation(yaw,pitch,roll)),target_offset);
output=desired;
// Only this frame's cached road offset is changed. Config units stay untouched.
view.offset[0]=float(offset.x);view.offset[1]=float(offset.y);view.offset[2]=float(offset.z);
return true;
}
}
-48
View File
@@ -1,48 +0,0 @@
#pragma once
#include <algorithm>
#include <cmath>
namespace forward_camera {
constexpr double pi = 3.14159265358979323846;
constexpr double degrees = 180.0 / pi;
struct Vec { double x, y, z; };
struct Mat { double v[3][3]; };
inline Mat multiply(const Mat& a, const Mat& b) {
Mat out{};
for (int i=0; i<3; ++i) for (int j=0; j<3; ++j)
for (int k=0; k<3; ++k) out.v[i][j] += a.v[i][k]*b.v[k][j];
return out;
}
inline Mat transpose(const Mat& a) {
Mat out{};
for (int i=0; i<3; ++i) for (int j=0; j<3; ++j) out.v[i][j]=a.v[j][i];
return out;
}
inline Vec transform(const Mat& a, Vec b) {
return {a.v[0][0]*b.x+a.v[0][1]*b.y+a.v[0][2]*b.z,
a.v[1][0]*b.x+a.v[1][1]*b.y+a.v[1][2]*b.z,
a.v[2][0]*b.x+a.v[2][1]*b.y+a.v[2][2]*b.z};
}
// Candidate SCS camera convention: yaw about Y, pitch about X, roll about Z.
// Algebra is tested separately; the game's signs/order still require visual validation.
inline Mat rotation(double yaw, double pitch, double roll=0) {
const double cy=std::cos(yaw), sy=std::sin(yaw);
const double cp=std::cos(pitch), sp=std::sin(pitch);
const double cr=std::cos(roll), sr=std::sin(roll);
return {{{cy*cr+sy*sp*sr, -cy*sr+sy*sp*cr, sy*cp},
{cp*sr, cp*cr, -sp},
{-sy*cr+cy*sp*sr, sy*sr+cy*sp*cr, cy*cp}}};
}
struct Compensation { double heading, pitch, roll; Vec offset; };
inline Compensation compensate(double yaw, double pitch, double roll,
double target_pitch, Vec target_offset, bool local_matrix) {
const Mat inverse = transpose(rotation(yaw, pitch, roll));
const Vec offset = transform(inverse, target_offset);
if (!local_matrix)
return {-yaw*degrees, (target_pitch-pitch)*degrees, -roll*degrees, offset};
const Mat relative = multiply(inverse, rotation(0, target_pitch));
return {std::atan2(relative.v[0][2], relative.v[2][2])*degrees,
std::asin(std::clamp(-relative.v[1][2], -1.0, 1.0))*degrees,
std::atan2(relative.v[1][0], relative.v[1][1])*degrees, offset};
}
}
-35
View File
@@ -1,35 +0,0 @@
param([string]$PluginsDir='C:\Program Files (x86)\DODI-Repacks\American Truck Simulator\bin\win_x64\plugins', [switch]$Disable)
$ErrorActionPreference='Stop'
$taskIdentity=[Security.Principal.WindowsIdentity]::GetCurrent()
$taskPrincipal=New-Object Security.Principal.WindowsPrincipal($taskIdentity)
if (-not $taskPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
$taskShell=(Get-Process -Id $PID).Path
$taskArguments='-NoProfile -ExecutionPolicy Bypass -File "{0}" -PluginsDir "{1}"' -f $PSCommandPath,$PluginsDir
if ($Disable) { $taskArguments+=' -Disable' }
$taskChild=Start-Process -FilePath $taskShell -ArgumentList $taskArguments -Verb RunAs -WindowStyle Hidden -Wait -PassThru
exit $taskChild.ExitCode
}
$taskRoot=Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
$taskLog=Join-Path $taskRoot 'diagnostics/forward-camera-setup.log'
New-Item -ItemType Directory -Force (Split-Path $taskLog -Parent) | Out-Null
Start-Transcript -Path $taskLog -Force | Out-Null
try {
if ($Disable) {
if (Get-Process amtrucks -ErrorAction SilentlyContinue) { throw 'Close ATS before disabling SPF.' }
$taskResolved=[IO.Path]::GetFullPath($PluginsDir)
if ((Split-Path $taskResolved -Leaf) -ne 'plugins' -or -not (Test-Path -LiteralPath (Join-Path (Split-Path $taskResolved -Parent) 'amtrucks.exe'))) { throw 'Invalid ATS plugins path.' }
$taskSource=Join-Path $taskResolved 'spf-framework.dll'
if (Test-Path -LiteralPath $taskSource) {
$taskSaved=Join-Path $taskRoot ('diagnostics/spf-disabled-'+(Get-Date -Format 'yyyyMMdd-HHmmss-fffffff')+'.dll')
Move-Item -LiteralPath $taskSource -Destination $taskSaved
Write-Output "SPF disabled and preserved at $taskSaved. Original telemetry and HUD remain available."
}
} else {
& (Join-Path $PSScriptRoot 'install.ps1') -PluginsDir $PluginsDir -EnablePassiveTest
}
} catch {
Write-Output $_
Stop-Transcript | Out-Null
exit 1
}
Stop-Transcript | Out-Null
@@ -1,34 +0,0 @@
// Map the real inspected executable as data; never execute its code.
#define WIN32_LEAN_AND_MEAN
#include "build_guard.h"
#include <cstdlib>
void require(bool condition,const char* message) {
if(!condition) { std::fprintf(stderr,"FAIL: %s\n",message);std::exit(1); }
}
int wmain(int argc,wchar_t** argv) {
require(argc==2,"supply inspected executable path");
require(forward_camera::verified_game_build(argv[1]),"fixture has inspected SHA256");
require(!forward_camera::verified_loaded_camera(),"unrelated running test executable rejected");
require(!forward_camera::verified_loaded_camera(reinterpret_cast<void*>(42)),"invalid image address rejected");
HANDLE file=CreateFileW(argv[1],GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
require(file!=INVALID_HANDLE_VALUE,"open inspected fixture");
HANDLE mapping=CreateFileMappingW(file,nullptr,PAGE_READONLY|SEC_IMAGE_NO_EXECUTE,0,0,nullptr);
require(mapping!=nullptr,"map fixture without executing code");
auto* image=static_cast<unsigned char*>(MapViewOfFile(mapping,FILE_MAP_READ,0,0,0));
require(image!=nullptr,"read-only fixture image");
require(forward_camera::verified_loaded_camera(image),"all real loaded camera ranges match");
// Modify only our non-executing mapped fixture to prove a one-byte change fails.
const auto& range=forward_camera::inspected_camera_code[0];
DWORD previous=0;
require(VirtualProtect(image+range.rva,range.size,PAGE_WRITECOPY,&previous)!=0,"make test fixture page private");
image[range.rva]^=1;
unsigned long mismatch=0;
require(!forward_camera::verified_loaded_camera(image,&mismatch) && mismatch==range.rva,
"one-byte camera function mismatch rejected");
image[range.rva]^=1;
require(forward_camera::verified_loaded_camera(image),"restored fixture matches");
DWORD ignored=0;VirtualProtect(image+range.rva,range.size,previous,&ignored);
UnmapViewOfFile(image);CloseHandle(mapping);CloseHandle(file);
std::puts("Build guard checks passed: exact real fixture, unrelated image, unreadable pointer, one-byte code mismatch, restoration.");
}
@@ -1,48 +0,0 @@
#define WIN32_LEAN_AND_MEAN
#include "head_telemetry.h"
#include <cstdio>
#include <cstdlib>
void require(bool value,const char* message) {
if(!value) { std::fprintf(stderr,"FAIL: %s\n",message);std::exit(1); }
}
int main(int argc,char** argv) {
unsigned char bytes[2048]{};
bytes[0]=1;uint64_t stamp=12345;uint32_t revision=12,game=2;
bytes[1566]=1;const float speed=.012f;std::memcpy(bytes+948,&speed,4);
std::memcpy(bytes+8,&stamp,8);std::memcpy(bytes+40,&revision,4);std::memcpy(bytes+52,&game,4);
float values[]{0.29f,-0.05f,-0.36f,0.4f,-0.02f,0.99f};
std::memcpy(bytes+2024,values,sizeof(values));
forward_camera::HeadSample sample{};
require(forward_camera::decode_head(bytes,sample),"supported fresh-looking SDK head placement");
require(sample.park_brake && !sample.paused && std::abs(sample.speed_mps-.012)<.000001,
"verified SDK speed and parking fields decoded for observation eligibility");
require(std::abs(sample.position.x-0.29)<0.000001 &&
std::abs(sample.position.z+0.36)<0.000001 &&
std::abs(sample.yaw-0.8*forward_camera::pi)<0.000001,"position and SDK turns decoded separately");
require(std::abs(sample.roll+0.02*forward_camera::pi)<0.000001,"SDK roll wraps continuously near one turn");
values[3]=0.47f;values[4]=-0.032f;values[5]=0.001f;
std::memcpy(bytes+2024,values,sizeof(values));
require(forward_camera::decode_head(bytes,sample) && std::abs(sample.yaw-0.94*forward_camera::pi)<0.000001 &&
std::abs(sample.pitch+0.064*forward_camera::pi)<0.000001 &&
std::abs(sample.roll-0.002*forward_camera::pi)<0.000001,"extreme left full SDK head orientation decoded independently of SPF");
bytes[4]=1;require(!forward_camera::decode_head(bytes,sample) && sample.paused,"paused sample rejected");bytes[4]=0;
bytes[0]=0;require(!forward_camera::decode_head(bytes,sample),"inactive SDK rejected");bytes[0]=1;
bytes[40]=11;require(!forward_camera::decode_head(bytes,sample),"wrong revision rejected");bytes[40]=12;
bytes[52]=1;require(!forward_camera::decode_head(bytes,sample),"different game rejected");bytes[52]=2;
values[0]=NAN;std::memcpy(bytes+2024,values,sizeof(values));
require(!forward_camera::decode_head(bytes,sample),"invalid position rejected");
std::puts("Head SDK checks passed: revision 12 placement/units, paused, inactive, wrong format, invalid position.");
if(argc==2 && std::strcmp(argv[1],"--live")==0) {
forward_camera::HeadTelemetry reader;unsigned samples=0;
for(unsigned i=0;i<15;++i) {
if(reader.read(sample)) {
++samples;
std::printf("Read-only live head %.4f,%.4f,%.4f m; yaw %.2f pitch %.2f deg\n",
sample.position.x,sample.position.y,sample.position.z,
sample.yaw*forward_camera::degrees,sample.pitch*forward_camera::degrees);
}
Sleep(100);
}
require(samples>2,"existing game SDK mapping supplies fresh head data");
}
}

Some files were not shown because too many files have changed in this diff Show More