Compare commits

..

22 Commits

Author SHA1 Message Date
rav4kumar 8ee5d10380 agnos-20.6-bluetooth 2026-12-02 14:54:12 -07:00
Armand du Parc Locmaria 35479a26b6 long mpc: use measured accel for fallback (#39542)
* long mpc: use measured accel for fallback

* add test case
2026-12-02 14:53:57 -07:00
rav4kumar cee0e30a1e vroom26 2026-12-02 14:53:57 -07:00
Armand du Parc Locmaria c0a2a98e68 long mpc uses both leadOne and leadTwo (#39525) 2026-12-02 14:53:57 -07:00
rav4kumar d7f5c489e7 Merge branch 'master' into toyota-bsm 2026-11-30 11:14:47 -07:00
rav4kumar 5fe5ec7ad1 ref 2026-11-28 10:21:27 -07:00
rav4kumar aa9bc9ddd1 Merge remote-tracking branch 'origin/master' into toyota-bsm 2026-11-28 10:11:53 -07:00
rav4kumar 6f903a7806 ref 2026-11-24 11:36:54 -07:00
rav4kumar e3829360d0 Merge branch 'master' into toyota-bsm 2026-11-24 11:35:49 -07:00
rav4kumar a598f43690 ref 2026-11-17 10:01:10 -07:00
rav4kumar 7f8db47fd0 Merge remote-tracking branch 'origin/master' into toyota-bsm 2026-11-17 09:59:36 -07:00
rav4kumar 1291d14108 Merge origin/master into toyota-bsm 2026-11-11 13:14:18 -07:00
rav4kumar c831334d76 gate op long 2026-11-11 13:11:34 -07:00
Kumar 5958b2d25b Merge branch 'master' into toyota-bsm 2026-11-05 11:26:28 -07:00
Kumar 73c8b30fa9 Merge branch 'master' into toyota-bsm 2026-11-04 12:14:55 -07:00
rav4kumar 8bdb2f54d9 Merge branch 'master' into toyota-bsm 2026-11-03 10:37:16 -07:00
rav4kumar 9c1bdde65b toyota: enable the enhanced BSM toggle for TSS-P cars with a smartDSU 2026-11-03 10:31:07 -07:00
Kumar 914aaefac1 Merge branch 'master' into toyota-bsm 2026-10-26 11:35:14 -07:00
rav4kumar d05649c0a4 toyota: bump opendbc and fix BSM wiring 2026-10-26 11:32:51 -07:00
rav4kumar 3521140920 ref 2026-10-25 11:56:26 -07:00
rav4kumar 56628fc770 ref 2026-10-25 11:55:52 -07:00
rav4kumar 60a9cc8657 toyota: add Enhanced Blind Spot Monitoring setting 2026-10-25 11:55:32 -07:00
142 changed files with 303 additions and 14880 deletions
-1
View File
@@ -2,6 +2,5 @@ Wen
REGIST
PullRequest
cancelled
indeces
FOF
NoO
-1
View File
@@ -149,7 +149,6 @@ jobs:
process_replay:
name: process replay
if: false #process replay disabled for angle steering until we are ready to merge it
runs-on: ${{
(github.repository == 'commaai/openpilot') &&
((github.event_name != 'pull_request') ||
+1
View File
@@ -4,6 +4,7 @@
[submodule "opendbc"]
path = opendbc_repo
url = https://github.com/sunnypilot/opendbc.git
branch = toyotabsmhack
[submodule "msgq"]
path = msgq_repo
url = https://github.com/sunnypilot/msgq.git
-7
View File
@@ -21,12 +21,5 @@
</clean>
</configuration>
</target>
<target id="f2590b2b-9b93-49f9-8510-da3f3724a2ae" name="replay" defaultType="TOOL">
<configuration id="d475264f-6f4c-4092-9b4e-6773309f38b7" name="replay" toolchainName="Default">
<build type="TOOL">
<tool actionId="Tool_External Tools_uv build tools replay" />
</build>
</configuration>
</target>
</component>
</project>
-7
View File
@@ -20,11 +20,4 @@
<option name="WORKING_DIRECTORY" value="$ProjectFileDir$" />
</exec>
</tool>
<tool name="uv build tools replay" showInMainMenu="false" showInEditor="false" showInProject="false" showInSearchPopup="false" disabled="false" useConsole="true" showConsoleOnStdOut="false" showConsoleOnStdErr="false" synchronizeAfterRun="true">
<exec>
<option name="COMMAND" value="bash" />
<option name="PARAMETERS" value="-c &quot;source .venv/bin/activate &amp;&amp; scons -u -j$(nproc) tools/replay/&quot;" />
<option name="WORKING_DIRECTORY" value="$ProjectFileDir$" />
</exec>
</tool>
</toolSet>
+1 -1
View File
@@ -1,5 +1,5 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Build Debug" type="CLionExternalRunConfiguration" factoryName="Application" REDIRECT_INPUT="false" ELEVATE="false" USE_EXTERNAL_CONSOLE="false" EMULATE_TERMINAL="false" WORKING_DIR="file://$ProjectFileDir$/selfdrive/ui" PASS_PARENT_ENVS_2="true" PROJECT_NAME="openpilot-special" TARGET_NAME="uv Scons Build Debug" CONFIG_NAME="uv Scons Build Debug" RUN_PATH="ui">
<configuration default="false" name="Build Debug" type="CLionExternalRunConfiguration" factoryName="Application" REDIRECT_INPUT="false" ELEVATE="false" USE_EXTERNAL_CONSOLE="false" EMULATE_TERMINAL="false" WORKING_DIR="file://$ProjectFileDir$/selfdrive/ui" PASS_PARENT_ENVS_2="true" PROJECT_NAME="sunnypilot" TARGET_NAME="uv Scons Build Debug" CONFIG_NAME="uv Scons Build Debug" RUN_PATH="ui">
<envs>
<env name="QT_DBL_CLICK_DIST" value="150" />
</envs>
-27
View File
@@ -1,27 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Debug Route Controls" type="PythonConfigurationType" factoryName="Python">
<module name="openpilot-special" />
<option name="ENV_FILES" value="" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
<env name="FINGERPRINT" value="KIA_EV9" />
<env name="SKIP_FW_QUERY" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/selfdrive/car" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/selfdrive/car/card.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="true" />
<option name="MODULE_MODE" value="false" />
<option name="REDIRECT_INPUT" value="false" />
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
</component>
-7
View File
@@ -1,7 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Replay for controls + ui" type="Multirun" separateTabs="false" reuseTabsWithFailures="false" startOneByOne="true" markFailedProcess="true" hideSuccessProcess="false" delayTime="0.0">
<runConfiguration name="replay for controls" type="Native Application" />
<runConfiguration name="Build Debug" type="Custom Build Application" />
<method v="2" />
</configuration>
</component>
-7
View File
@@ -1,7 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="replay for controls" type="CLionNativeAppRunConfigurationType" focusToolWindowBeforeRun="true" PROGRAM_PARAMS="&quot;$Prompt$&quot; --block &quot;sendcan,carState,carParams,carOutput,liveTracks,carParamsSP,carStateSP,bookmarkButton&quot;" REDIRECT_INPUT="false" ELEVATE="false" USE_EXTERNAL_CONSOLE="false" EMULATE_TERMINAL="true" WORKING_DIR="file://$ProjectFileDir$/tools/replay" PASS_PARENT_ENVS_2="true" PROJECT_NAME="openpilot-special" TARGET_NAME="replay" CONFIG_NAME="replay" version="1" RUN_PATH="replay">
<method v="2">
<option name="CLION.COMPOUND.BUILD" enabled="true" />
</method>
</configuration>
</component>
+1 -4
View File
@@ -4,7 +4,7 @@
A supported vehicle is one that just works when you install a comma device. All supported cars provide a better experience than any stock system. Supported vehicles reference the US market unless otherwise specified.
# 362 Supported Cars
# 359 Supported Cars
|Make|Model|Supported Package|ACC|No ACC accel below|No ALC below|Steering Torque|Resume from stop|<a href="##"><img width=2000></a>Hardware Needed<br>&nbsp;|Video|Setup Video|
|---|---|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
@@ -180,7 +180,6 @@ A supported vehicle is one that just works when you install a comma device. All
|Kia|Forte 2019-21|Smart Cruise Control (SCC)|openpilot available[<sup>1</sup>](#footnotes)|6 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|<details><summary>Parts</summary><sub>- 1 Hyundai G connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Kia Forte 2019-21">Buy Here</a></sub></details>|||
|Kia|Forte 2022-23|Smart Cruise Control (SCC)|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|<details><summary>Parts</summary><sub>- 1 Hyundai E connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Kia Forte 2022-23">Buy Here</a></sub></details>|||
|Kia|K5 2021-24|Smart Cruise Control (SCC)|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|<details><summary>Parts</summary><sub>- 1 Hyundai A connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Kia K5 2021-24">Buy Here</a></sub></details>|||
|Kia|K5 (without HDA II) 2025-26|Smart Cruise Control (SCC)|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|<details><summary>Parts</summary><sub>- 1 Hyundai M connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Kia K5 (without HDA II) 2025-26">Buy Here</a></sub></details>|||
|Kia|K5 Hybrid 2020-22|Smart Cruise Control (SCC)|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|<details><summary>Parts</summary><sub>- 1 Hyundai A connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Kia K5 Hybrid 2020-22">Buy Here</a></sub></details>|||
|Kia|K7 2017|Smart Cruise Control (SCC)|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|<details><summary>Parts</summary><sub>- 1 Hyundai C connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Kia K7 2017">Buy Here</a></sub></details>|||
|Kia|K8 Hybrid (with HDA II) 2023|Highway Driving Assist II|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|<details><summary>Parts</summary><sub>- 1 Hyundai Q connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Kia K8 Hybrid (with HDA II) 2023">Buy Here</a></sub></details>|||
@@ -206,8 +205,6 @@ A supported vehicle is one that just works when you install a comma device. All
|Kia|Sorento 2018|Advanced Smart Cruise Control & LKAS|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|<details><summary>Parts</summary><sub>- 1 Hyundai E connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Kia Sorento 2018">Buy Here</a></sub></details>|<a href="https://www.youtube.com/watch?v=Fkh3s6WHJz8" target="_blank"><img height="18px" src="assets/icon-youtube.svg" /></a>||
|Kia|Sorento 2019|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|<details><summary>Parts</summary><sub>- 1 Hyundai E connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Kia Sorento 2019">Buy Here</a></sub></details>|<a href="https://www.youtube.com/watch?v=Fkh3s6WHJz8" target="_blank"><img height="18px" src="assets/icon-youtube.svg" /></a>||
|Kia|Sorento 2021-23|Smart Cruise Control (SCC)|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|<details><summary>Parts</summary><sub>- 1 Hyundai K connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Kia Sorento 2021-23">Buy Here</a></sub></details>|||
|Kia|Sorento (without HDA II) 2024-25|Smart Cruise Control (SCC)|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|<details><summary>Parts</summary><sub>- 1 Hyundai A connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Kia Sorento (without HDA II) 2024-25">Buy Here</a></sub></details>|||
|Kia|Sorento (without HDA II, Middle East only) 2024|Smart Cruise Control (SCC)|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|<details><summary>Parts</summary><sub>- 1 Hyundai S connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Kia Sorento (without HDA II, Middle East only) 2024">Buy Here</a></sub></details>|||
|Kia|Sorento Hybrid 2021-23|All|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|<details><summary>Parts</summary><sub>- 1 Hyundai A connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Kia Sorento Hybrid 2021-23">Buy Here</a></sub></details>|||
|Kia|Sorento Plug-in Hybrid 2022-23|All|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|<details><summary>Parts</summary><sub>- 1 Hyundai A connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Kia Sorento Plug-in Hybrid 2022-23">Buy Here</a></sub></details>|||
|Kia|Sportage 2023-24|Smart Cruise Control (SCC)|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|<details><summary>Parts</summary><sub>- 1 Hyundai N connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Kia Sportage 2023-24">Buy Here</a></sub></details>|||
-3
View File
@@ -360,7 +360,6 @@ struct OnroadEventSP @0xda96579883444c35 {
e2eChime @23;
laneChangeRoadEdge @24;
bigModelReady @25;
stockSteerIntervention @26;
}
}
@@ -390,7 +389,6 @@ struct CarControlSP @0xa5cd762cd951a455 {
leadOne @2 :LeadData;
leadTwo @3 :LeadData;
intelligentCruiseButtonManagement @4 :IntelligentCruiseButtonManagement;
pathCurvature @5 :Float32;
struct Param {
key @0 :Text;
@@ -455,7 +453,6 @@ struct BackupManagerSP @0xf98d843bfd7004a3 {
struct CarStateSP @0xb86e6369214c01c8 {
speedLimit @0 :Float32;
stockSteerIntervention @1 :Bool;
}
struct LiveMapDataSP @0xf416ec09499d9d19 {
+2 -3
View File
@@ -182,7 +182,6 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"LastGPSPositionFused", {PERSISTENT, STRING}},
{"LeadDepartAlert", {PERSISTENT | BACKUP, BOOL, "0"}},
{"MaxTimeOffroad", {PERSISTENT | BACKUP, INT, "1800"}},
{"MiciRoboticUI", {PERSISTENT | BACKUP, BOOL, "0"}},
{"ModelRunnerTypeCache", {CLEAR_ON_ONROAD_TRANSITION, INT}},
{"OffroadMode", {CLEAR_ON_MANAGER_START, BOOL}},
{"Offroad_TiciSupport", {CLEAR_ON_MANAGER_START, JSON}},
@@ -193,7 +192,6 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"OnroadUploads", {PERSISTENT | BACKUP, BOOL, "1"}},
{"QuickBootToggle", {PERSISTENT | BACKUP, BOOL, "0"}},
{"QuietMode", {PERSISTENT | BACKUP, BOOL, "0"}},
{"RadarTracks", {PERSISTENT | BACKUP, INT, "0"}},
{"RainbowMode", {PERSISTENT | BACKUP, BOOL, "0"}},
{"RoadEdgeLaneChangeEnabled", {PERSISTENT | BACKUP, BOOL, "0"}},
{"RocketFuel", {PERSISTENT | BACKUP, BOOL, "0"}},
@@ -247,11 +245,12 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"BackupManager_RestoreVersion", {PERSISTENT, STRING}},
// sunnypilot car specific params
{"HyundaiLongitudinalTuning", {PERSISTENT | BACKUP, BOOL, "0"}},
{"HyundaiLongitudinalTuning", {PERSISTENT | BACKUP, INT, "0"}},
{"SubaruStopAndGo", {PERSISTENT | BACKUP, BOOL, "0"}},
{"SubaruStopAndGoManualParkingBrake", {PERSISTENT | BACKUP, BOOL, "0"}},
{"TeslaCoopSteering", {PERSISTENT | BACKUP, BOOL, "0"}},
{"TeslaMadsScreenButton", {PERSISTENT | BACKUP, INT, "0"}},
{"ToyotaEnhancedBsm", {PERSISTENT | BACKUP, BOOL, "0"}},
{"ToyotaEnforceStockLongitudinal", {PERSISTENT | BACKUP, BOOL, "0"}},
{"ToyotaStopAndGoHack", {PERSISTENT | BACKUP, BOOL, "0"}},
{"ToyotaTSS2Smooth", {PERSISTENT | BACKUP, BOOL, "0"}},
-2
View File
@@ -37,8 +37,6 @@ SP_BRANCH_MIGRATIONS = {
("tizi", "release3-staging"): "release-tizi-staging",
("mici", "release3"): "release-mici",
("mici", "release3-staging"): "release-mici-staging",
("tici", "hkg-angle-steering-2025"): "hkg-angle-steering-2025-tici",
("tici", "hkg-angle-steering-2025-prebuilt"): "hkg-angle-steering-2025-tici-prebuilt"
}
BUILD_METADATA_FILENAME = "build.json"
-17
View File
@@ -180,8 +180,6 @@ class Car:
self.is_metric = self.params.get_bool("IsMetric")
self.initial_cruise_speed = self.params.get("InitialCruiseSpeedKph", return_default=True)
self.radar_tracks = int(self.params.get("RadarTracks", return_default=True))
self._applied_radar_tracks = getattr(self.RI, "radar_mode", self.radar_tracks)
# card is driven by can recv, expected at 100Hz
self.rk = Ratekeeper(100, print_delay_threshold=None)
@@ -196,8 +194,6 @@ class Car:
CS, CS_SP = self.CI.update(can_list)
CS_SP = convert_to_capnp(CS_SP)
self._update_radar_tracks()
# Update radar tracks from CAN
RD: structs.RadarDataT | None = self.RI.update(can_list)
@@ -224,18 +220,6 @@ class Car:
return CS, CS_SP, RD
def _update_radar_tracks(self) -> None:
if self.CP.brand != "hyundai" or self.radar_tracks == self._applied_radar_tracks:
return
if self.RI.set_radar_mode(self.radar_tracks):
self.CP_SP_capnp = convert_to_capnp(self.CP_SP)
cp_sp_bytes = self.CP_SP_capnp.to_bytes()
self.params.put("CarParamsSP", cp_sp_bytes)
self.params.put("CarParamsSPCache", cp_sp_bytes)
self.params.put("CarParamsSPPersistent", cp_sp_bytes)
self._applied_radar_tracks = self.radar_tracks
def state_publish(self, CS: car.CarState, CS_SP: custom.CarStateSP, RD: structs.RadarDataT | None):
"""carState and carParams publish loop"""
@@ -315,7 +299,6 @@ class Car:
while not evt.is_set():
self.is_metric = self.params.get_bool("IsMetric")
self.initial_cruise_speed = self.params.get("InitialCruiseSpeedKph", return_default=True)
self.radar_tracks = int(self.params.get("RadarTracks", return_default=True))
# sunnypilot
self.v_cruise_helper.read_custom_set_speed_params()
@@ -318,7 +318,7 @@ class LongitudinalMpc:
lead_xv = self.integrate_lead(x_lead, v_lead, a_lead_traj)
# smoothly fall back to the more pessimistic radar trajectory when radar requires hard braking
x_obs_radar = radar_xv[:, 0] + get_stopped_equivalence_factor(radar_xv[:, 1], brake=-ACCEL_MIN)
x_obs_radar = radar_xv[:, 0] + get_stopped_equivalence_factor(radar_xv[:, 1], brake=max(-ACCEL_MIN, -a_lead))
a_req = v_ego**2 / (2. * max(np.min(x_obs_radar) - STOP_DISTANCE, 0.5))
w = np.interp(a_req, LEAD_FALLBACK_RANGE, [0.0, 1.0])
if w > 0.0:
@@ -144,7 +144,7 @@ class LongitudinalPlanner(LongitudinalPlannerSP):
longitudinalPlan.accels = self.a_desired_trajectory.tolist()
longitudinalPlan.jerks = self.j_desired_trajectory.tolist()
longitudinalPlan.hasLead = sm['radarState'].leadOne.present
longitudinalPlan.hasLead = sm['radarState'].leadOne.present or sm['radarState'].leadTwo.present
longitudinalPlan.longitudinalPlanSource = self.mpc.source
longitudinalPlan.fcw = self.fcw
+2 -14
View File
@@ -26,8 +26,6 @@ SPEED, ACCEL = 0, 1 # Kalman filter states enum
# stationary qualification parameters
V_EGO_STATIONARY = 4. # no stationary object flag below this speed
DBC_MOTION_STATIONARY = 1
DBC_MOTION_MOVING = 2
RADAR_TO_CAMERA = 1.52 # RADAR is ~ 1.5m ahead from center of mesh frame
@@ -193,14 +191,8 @@ def get_custom_yrel(CP: structs.CarParams, CP_SP: structs.CarParamsSP, lead_dict
return lead_dict
def radar_point_eligible_for_fusion(CP: structs.CarParams, CP_SP: structs.CarParamsSP,
point: car.RadarData.RadarPoint) -> bool:
use_dbc_motion = CP.brand == "hyundai" and CP_SP.flags & HyundaiFlagsSP.RADAR_FULL_RADAR
return not use_dbc_motion or point.motionState in (DBC_MOTION_STATIONARY, DBC_MOTION_MOVING)
class RadarD:
def __init__(self, CP: structs.CarParams, CP_SP: structs.CarParamsSP, delay: float = 0.0):
def __init__(self, CP: structs.CarParams, CP_SP: structs.CarParams, delay: float = 0.0):
self.CP = CP
self.CP_SP = CP_SP
@@ -226,11 +218,7 @@ class RadarD:
self.v_ego_hist.append(self.v_ego)
self.last_v_ego_frame = sm.recv_frame['carState']
ar_pts = {
pt.trackId: [pt.dRel, pt.yRel, pt.vRel]
for pt in rr.points
if radar_point_eligible_for_fusion(self.CP, self.CP_SP, pt)
}
ar_pts = {pt.trackId: [pt.dRel, pt.yRel, pt.vRel] for pt in rr.points}
# *** remove missing points from meta data ***
for ids in list(self.tracks.keys()):
@@ -185,6 +185,8 @@ def create_stopped_adv_maneuvers(kwargs):
def create_hard_braking_adv_maneuvers(kwargs):
cases = [(v0, d0, decel) for v0, d0 in ((10., 20.), (20., 35.), (30., 50.)) for decel in (2., 3., 3.5)]
cases.append((30., 80., 5.))
return [
Maneuver(
f"steady following ({v0:g}m/s) then lead brakes hard (-{decel:g}m/s^2), "
@@ -201,8 +203,7 @@ def create_hard_braking_adv_maneuvers(kwargs):
only_radar=model_a is None,
**kwargs,
)
for v0, d0 in ((10., 20.), (20., 35.), (30., 50.))
for decel in (2., 3., 3.5)
for v0, d0, decel in cases
for model_a in (None, 0., 2.)
]
@@ -100,19 +100,7 @@ class TogglesLayout(Widget):
icon="speed_limit.png"
)
self._radar_tracks_setting = None
self._toggles: dict[str, ListItem] = {}
if gui_app.sunnypilot_ui():
self._radar_tracks_setting = multiple_button_item(
lambda: tr("Radar Tracks"),
"",
buttons=[lambda: tr("Off"), lambda: tr("Lead Only"), lambda: tr("Full Radar")],
button_width=250,
callback=self._set_radar_tracks,
selected_index=self._params.get("RadarTracks", return_default=True),
)
self._toggles["RadarTracks"] = self._radar_tracks_setting
self._initial_cruise_speed = ListItem(
title=lambda: tr("Initial Max Speed"),
description=lambda: tr("Max speed when engaging openpilot. If you are already driving faster, your current speed is used. " +
@@ -181,8 +169,6 @@ class TogglesLayout(Widget):
# refresh toggles from params to mirror external changes
for param in self._toggle_defs:
self._toggles[param].action_item.set_state(self._params.get_bool(param))
if self._radar_tracks_setting is not None:
self._radar_tracks_setting.action_item.set_selected_button(self._params.get("RadarTracks", return_default=True))
# these toggles need restart, block while engaged
for toggle_def in self._toggle_defs:
@@ -202,6 +188,3 @@ class TogglesLayout(Widget):
def _set_longitudinal_personality(self, button_index: int):
self._params.put("LongitudinalPersonality", button_index, block=True)
def _set_radar_tracks(self, button_index: int):
self._params.put("RadarTracks", button_index, block=True)
+9 -36
View File
@@ -15,7 +15,6 @@ from openpilot.system.ui.lib.application import gui_app
if gui_app.sunnypilot_ui():
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.settings import SettingsLayoutSP as SettingsLayout
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.home import MiciHomeLayoutSP as MiciHomeLayout
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic import RoboticOnroadView
ONROAD_DELAY = 2.5 # seconds
GREET_IGNITION_OFF_TIME = 60 * 60 # greet again when the car turns on after being off this long
@@ -38,34 +37,23 @@ class MiciMainLayout(Scroller):
self._alerts_layout = MiciOffroadAlerts()
self._settings_layout = SettingsLayout()
self._car_onroad_layout = AugmentedRoadView(bookmark_callback=self._on_bookmark_clicked)
self._robotic_onroad_layout = RoboticOnroadView(bookmark_callback=self._on_bookmark_clicked) if gui_app.sunnypilot_ui() else None
self._body_onroad_layout = BodyLayout()
self._prev_robotic_ui = bool(gui_app.sunnypilot_ui() and ui_state.mici_robotic_ui)
# Initialize widget rects
all_widgets = [self._home_layout, self._alerts_layout, self._settings_layout,
self._car_onroad_layout, self._body_onroad_layout]
if self._robotic_onroad_layout is not None:
all_widgets.append(self._robotic_onroad_layout)
for widget in all_widgets:
for widget in (self._home_layout, self._alerts_layout, self._settings_layout,
self._car_onroad_layout, self._body_onroad_layout):
# TODO: set parent rect and use it if never passed rect from render (like in Scroller)
widget.set_rect(rl.Rectangle(0, 0, gui_app.width, gui_app.height))
scroller_widgets = [
self._scroller.add_widgets([
self._home_layout,
self._car_onroad_layout,
]
if self._robotic_onroad_layout is not None:
scroller_widgets.append(self._robotic_onroad_layout)
scroller_widgets.append(self._body_onroad_layout)
self._scroller.add_widgets(scroller_widgets)
self._body_onroad_layout,
])
self._scroller.set_reset_scroll_at_show(False)
# Disable scrolling when onroad is interacting with bookmark
self._scroller.set_scrolling_enabled(
lambda: not (self._car_onroad_layout.is_swiping_left() or
(self._robotic_onroad_layout is not None and self._robotic_onroad_layout.is_swiping_left()))
)
self._scroller.set_scrolling_enabled(lambda: not self._car_onroad_layout.is_swiping_left())
# Set callbacks
self._setup_callbacks()
@@ -84,11 +72,7 @@ class MiciMainLayout(Scroller):
@property
def _onroad_layout(self) -> Widget:
# For scroll_to
if ui_state.is_body:
return self._body_onroad_layout
if self._robotic_onroad_layout is not None and ui_state.mici_robotic_ui:
return self._robotic_onroad_layout
return self._car_onroad_layout
return self._body_onroad_layout if ui_state.is_body else self._car_onroad_layout
def _setup_callbacks(self):
self._alerts_layout.set_pairing_callback(self._settings_layout.show_pairing)
@@ -98,10 +82,7 @@ class MiciMainLayout(Scroller):
alert_count_callback=self._alerts_layout.active_alerts,
alert_icon_callback=self._alerts_layout.highest_severity_icon,
)
onroad_layouts = [self._car_onroad_layout, self._body_onroad_layout]
if self._robotic_onroad_layout is not None:
onroad_layouts.append(self._robotic_onroad_layout)
for layout in onroad_layouts:
for layout in (self._car_onroad_layout, self._body_onroad_layout):
layout.set_click_callback(lambda: self._scroll_to(self._home_layout))
device.add_interactive_timeout_callback(self._on_interactive_timeout)
@@ -111,11 +92,6 @@ class MiciMainLayout(Scroller):
layout_x = int(layout.rect.x)
self._scroller.scroll_to(layout_x, smooth=True)
def _update_state(self):
super()._update_state()
if self._robotic_onroad_layout is not None and ui_state.mici_robotic_ui != self._prev_robotic_ui:
self._prev_robotic_ui = ui_state.mici_robotic_ui
self._on_body_changed()
def _handle_transitions(self):
# greet when getting in the car after it's been off for a while
if ui_state.ignition != self._prev_ignition:
@@ -170,8 +146,5 @@ class MiciMainLayout(Scroller):
self._pm.send(service, msg)
def _on_body_changed(self):
use_robotic = self._robotic_onroad_layout is not None and ui_state.mici_robotic_ui
self._car_onroad_layout.set_visible(not ui_state.is_body and not use_robotic)
if self._robotic_onroad_layout is not None:
self._robotic_onroad_layout.set_visible(not ui_state.is_body and use_robotic)
self._car_onroad_layout.set_visible(not ui_state.is_body)
self._body_onroad_layout.set_visible(bool(ui_state.is_body))
@@ -28,17 +28,9 @@ class DrivingLayoutMici(NavScroller):
enable_openpilot = BigParamControl("enable sunnypilot", "OpenpilotEnabledToggle", toggle_callback=restart_needed_callback,
description="Enable to use sunnypilot driver assistance.\n" +
"Disable to use your car's stock driver assistance.")
robotic_ui_toggle = BigParamControl(
"robotic companion UI",
"MiciRoboticUI",
description="Replace the onroad camera view with an expressive EMO-inspired robotic face and robotic alert voices.",
)
radar_tracks = BigMultiParamToggle("radar tracks", "RadarTracks", ["off", "lead only", "full radar"])
self._radar_tracks_toggle = radar_tracks
self._scroller.add_widgets([
robotic_ui_toggle,
radar_tracks,
self._personality_toggle,
self._initial_cruise_speed,
always_on_dm_toggle,
@@ -48,7 +40,6 @@ class DrivingLayoutMici(NavScroller):
# Toggle lists
self._refresh_toggles = (
("MiciRoboticUI", robotic_ui_toggle),
("IsLdwEnabled", ldw_toggle),
("AlwaysOnDM", always_on_dm_toggle),
("OpenpilotEnabledToggle", enable_openpilot),
@@ -86,4 +77,3 @@ class DrivingLayoutMici(NavScroller):
# Refresh toggles from params to mirror external changes
for key, item in self._refresh_toggles:
item.set_checked(ui_state.params.get_bool(key))
self._radar_tracks_toggle._load_value()
@@ -1,274 +0,0 @@
"""Synthetic-fixture tests for the YAMNet cabin music detector."""
import math
import time
import numpy as np
from openpilot.common.test import OpenpilotTestCase
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic import music_analyzer
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import (
DEFAULT_SAMPLE_RATE,
MusicAnalyzer,
MusicState,
)
SR = DEFAULT_SAMPLE_RATE
CHUNK = 800
CHUNK_S = CHUNK / SR
def music_fixture(seconds=12.0):
"""Chords, kick, hats and a syllabic lead: timbres YAMNet has learned as music."""
t = np.arange(int(seconds * SR), dtype=np.float32) / SR
out = np.zeros_like(t)
chords = [(261.63, 329.63, 392.0), (220.0, 261.63, 329.63), (174.61, 220.0, 261.63), (196.0, 246.94, 293.66)]
bar = 2.0
for i, chord in enumerate((chords * 8)[:int(np.ceil(seconds / bar))]):
start = i * bar
mask = (t >= start) & (t < start + bar)
for f in chord:
for h in range(1, 6):
out[mask] += (0.13 / h) * np.sin(2 * np.pi * f * h * (t[mask] - start))
beat = 60.0 / 104.0
rng = np.random.default_rng(4)
for k in np.arange(0.0, seconds - 0.12, beat):
kick = (t >= k) & (t < k + 0.12)
tt = t[kick] - k
out[kick] += 0.45 * np.sin(2 * np.pi * (70.0 - 25.0 * tt / 0.12) * tt) * np.exp(-tt * 30.0)
hat = (t >= k + beat / 2) & (t < k + beat / 2 + 0.05)
ht = t[hat] - (k + beat / 2)
out[hat] += 0.12 * rng.standard_normal(len(ht)) * np.exp(-ht * 60.0)
mel = 330.0 * 2 ** (np.round(2.0 * np.sin(2 * np.pi * 0.13 * t)) / 12.0)
amp = 0.5 + 0.5 * np.maximum(0.0, np.sin(2 * np.pi * 3.7 * t)) ** 2
lead = sum((1.0 / h) * np.sin(2 * np.pi * np.cumsum(mel * h) / SR) for h in range(1, 7))
out += 0.10 * amp * lead / np.max(np.abs(lead))
return out.astype(np.float32)
def speech_fixture(seconds=12.0):
rng = np.random.default_rng(11)
n = int(seconds * SR)
t = np.arange(n, dtype=np.float32) / SR
out = np.zeros(n, dtype=np.float32)
f0 = 118.0 + 18.0 * np.sin(2 * np.pi * 0.4 * t)
voiced = sum((1.0 / h) * np.sin(2 * np.pi * np.cumsum(f0 * h) / SR) for h in range(1, 18))
voiced = voiced / np.max(np.abs(voiced)) * 0.35
period = 0.25
for i in range(int(seconds / period)):
start = i * period
dur = 0.13 + 0.02 * rng.random()
idx = (t >= start) & (t < start + dur)
if not np.any(idx):
continue
seg_len = int(idx.sum())
noise = rng.standard_normal(seg_len)
spec = np.fft.rfft(noise)
freqs = np.fft.rfftfreq(seg_len, 1.0 / SR)
env = (0.03 * np.exp(-((freqs - 500.0) / 130.0) ** 2)
+ 0.05 * np.exp(-((freqs - 1500.0) / 200.0) ** 2)
+ 0.04 * np.exp(-((freqs - 2500.0) / 300.0) ** 2))
formants = np.fft.irfft(spec * env, n=seg_len)
formants = formants / (np.max(np.abs(formants)) + 1e-9) * 0.25
attack = np.minimum(1.0, np.arange(seg_len) / (0.02 * SR))
out[idx] += (voiced[idx] + formants) * attack
return out + rng.normal(0.0, 0.004, n)
def road_noise_fixture(seconds=12.0):
"""Tyre/road rumble: low-frequency dominated, as measured in a cabin."""
rng = np.random.default_rng(5)
n = int(seconds * SR)
spec = np.fft.rfft(rng.standard_normal(n))
freqs = np.fft.rfftfreq(n, 1.0 / SR)
shape = 1.0 / (1.0 + (freqs / 250.0) ** 2) / np.sqrt(1.0 + (freqs / 1200.0) ** 4)
rumble = np.fft.irfft(spec * shape, n=n)
rumble /= np.sqrt(np.mean(rumble ** 2))
hiss = rng.standard_normal(n)
hiss /= np.sqrt(np.mean(hiss ** 2))
t = np.arange(n, dtype=np.float32) / SR
tones = sum(a * np.sin(2 * np.pi * f * t) for f, a in ((42.0, 0.25), (84.0, 0.12)))
return (rumble + 0.08 * hiss + tones).astype(np.float32)
def wind_noise_fixture(seconds=12.0):
"""Broadband wind and tyre hiss: must never be mistaken for music."""
rng = np.random.default_rng(9)
n = int(seconds * SR)
spec = np.fft.rfft(rng.standard_normal(n))
freqs = np.fft.rfftfreq(n, 1.0 / SR)
noise = np.fft.irfft(spec / np.sqrt(freqs + 30.0), n=n)
noise /= np.sqrt(np.mean(noise ** 2))
return (0.06 * noise).astype(np.float32)
def cabin_mix(signal, noise, snr_db):
"""Speaker path (bass roll-off, cabin reverb) mixed with road noise at a given SNR."""
spec = np.fft.rfft(signal)
freqs = np.fft.rfftfreq(len(signal), 1.0 / SR)
spec[freqs < 90.0] *= np.clip((freqs[freqs < 90.0] / 90.0) ** 2, 0.0, 1.0)
dry = np.fft.irfft(spec, n=len(signal)).astype(np.float32)
rng = np.random.default_rng(3)
n = int(0.22 * SR)
ir = rng.standard_normal(n) * np.exp(-np.arange(n) / (0.35 * n))
ir /= np.sqrt(np.sum(ir ** 2))
size = 1 << int(np.ceil(np.log2(len(dry) + n)))
wet = np.fft.irfft(np.fft.rfft(dry, size) * np.fft.rfft(ir, size), size)[:len(dry)]
y = 0.78 * dry + 0.22 * wet
noise = noise[:len(y)] * np.sqrt(np.mean(y ** 2) / 10 ** (snr_db / 10.0) / np.mean(noise[:len(y)] ** 2))
return (y + noise).astype(np.float32)
def _feed(analyzer, samples):
states = []
for i in range(0, len(samples) - CHUNK + 1, CHUNK):
states.append(analyzer.process_samples(samples[i:i + CHUNK].astype(np.float32)))
return states
def _first_entry(states):
for idx, state in enumerate(states):
if state.is_music:
return (idx + 1) * CHUNK_S
return None
class TestMusicAnalyzer(OpenpilotTestCase):
def test_model_loads(self):
analyzer = MusicAnalyzer(SR, synchronous=True)
assert analyzer._get_session() is not None, f"missing or invalid model at {music_analyzer.MODEL_PATH}"
def test_music_enters_and_pulses(self):
analyzer = MusicAnalyzer(SR, synchronous=True)
states = _feed(analyzer, music_fixture())
entry = _first_entry(states)
assert entry is not None, f"music never detected (score={states[-1].confidence:.3f})"
assert entry <= 6.0, f"music detected only at {entry:.2f}s"
assert states[-1].is_music
assert states[-1].confidence > 0.5
assert max(state.beat_pulse for state in states) > 0.4
def test_cabin_music_survives_road_noise(self):
analyzer = MusicAnalyzer(SR, synchronous=True)
mixed = cabin_mix(music_fixture(16.0), road_noise_fixture(16.0), snr_db=6.0)
states = _feed(analyzer, mixed)
entry = _first_entry(states)
assert entry is not None, f"music lost in cabin noise (score={states[-1].confidence:.3f})"
assert entry <= 8.0, f"music detected only at {entry:.2f}s"
def test_speech_is_rejected(self):
analyzer = MusicAnalyzer(SR, synchronous=True)
states = _feed(analyzer, speech_fixture())
assert not any(state.is_music for state in states), f"speech triggered at {_first_entry(states):.2f}s"
assert states[-1].confidence < 0.2
def test_road_noise_is_rejected(self):
analyzer = MusicAnalyzer(SR, synchronous=True)
states = _feed(analyzer, road_noise_fixture())
assert not any(state.is_music for state in states), f"road noise triggered at {_first_entry(states):.2f}s"
assert states[-1].confidence < 0.2
def test_broadband_wind_is_rejected(self):
analyzer = MusicAnalyzer(SR, synchronous=True)
states = _feed(analyzer, wind_noise_fixture())
assert not any(state.is_music for state in states), f"wind triggered at {_first_entry(states):.2f}s"
assert states[-1].confidence < 0.2
def test_silence_is_rejected(self):
analyzer = MusicAnalyzer(SR, synchronous=True)
states = _feed(analyzer, np.zeros(int(12.0 * SR), dtype=np.float32))
assert not any(state.is_music for state in states)
assert states[-1].confidence == 0.0
def test_suppress_blocks_evidence_and_holds_confidence(self):
analyzer = MusicAnalyzer(SR, synchronous=True)
_feed(analyzer, music_fixture(1.6))
assert not analyzer.state.is_music
held = analyzer.state.confidence
assert held > 0.4
analyzer.suppress(1.0)
quiet = _feed(analyzer, np.zeros(int(0.9 * SR), dtype=np.float32))
assert abs(quiet[0].confidence - held) < 0.02, "confidence must hold during suppression, not decay"
assert abs(quiet[-1].confidence - held) < 0.02
assert not any(state.is_music for state in quiet)
fresh = MusicAnalyzer(SR, synchronous=True)
fresh.suppress(3.0)
blocked = _feed(fresh, music_fixture(2.8))
assert not any(state.is_music for state in blocked)
assert blocked[-1].confidence == 0.0, "suppressed frames must not feed the detector"
def test_groove_phase_advances_one_sway_per_beat(self):
analyzer = MusicAnalyzer(SR, synchronous=True)
_feed(analyzer, music_fixture(6.0))
assert analyzer.state.is_music
before = analyzer.state
advanced = analyzer.step_visual_decay(1.0)
expected = (before.groove_phase + (before.bpm / 60.0) * math.tau) % math.tau
assert abs(((advanced.groove_phase - expected + math.pi) % math.tau) - math.pi) < 1e-4
def test_background_inference_updates_state(self):
analyzer = MusicAnalyzer(SR)
try:
samples = music_fixture(6.0)
for i in range(0, len(samples) - CHUNK + 1, CHUNK):
analyzer.process_samples(samples[i:i + CHUNK].astype(np.float32))
for _ in range(200):
analyzer.process_samples(samples[-CHUNK:].copy())
if analyzer.state.is_music:
break
time.sleep(0.05)
assert analyzer.state.is_music, "worker thread never classified music"
finally:
analyzer.close()
def test_stalled_microphone_exits_music(self):
analyzer = MusicAnalyzer(SR, synchronous=True)
_feed(analyzer, music_fixture(8.0))
assert analyzer.state.is_music
analyzer._clock = lambda: time.monotonic() + 10.0
for _ in range(60):
state = analyzer.step_visual_decay(0.05)
if not state.is_music:
break
assert not state.is_music, "music latched after the microphone stream stopped"
def test_audio_bytes_and_bands(self):
analyzer = MusicAnalyzer(SR, synchronous=True)
samples = music_fixture(4.0)
pcm = (np.clip(samples, -1.0, 1.0) * 32767).astype(np.int16)
state = MusicState()
for i in range(0, len(pcm) - CHUNK + 1, CHUNK):
state = analyzer.process_audio_bytes(pcm[i:i + CHUNK].tobytes(), SR)
assert isinstance(state, MusicState)
assert len(state.bands) == 12
assert state.energy > 0.0
assert max(state.bands) > 0.2
def test_missing_model_disables_detection_without_crashing(self):
original = music_analyzer.MODEL_PATH
music_analyzer.MODEL_PATH = "/nonexistent/yamnet.onnx"
try:
analyzer = MusicAnalyzer(SR, synchronous=True)
states = _feed(analyzer, music_fixture(4.0))
finally:
music_analyzer.MODEL_PATH = original
assert not any(state.is_music for state in states)
def test_cpu_budget(self):
analyzer = MusicAnalyzer(SR, synchronous=True)
_feed(analyzer, music_fixture(6.0))
blocks = [music_fixture(1.0)[i:i + CHUNK] for i in range(0, CHUNK * 300, CHUNK)]
start = time.perf_counter()
for block in blocks:
analyzer.process_samples(block)
per_frame_ms = (time.perf_counter() - start) / len(blocks) * 1000.0
print(f"\nmusic analyzer: {per_frame_ms:.3f} ms per 50 ms frame")
assert per_frame_ms < 4.0, f"{per_frame_ms:.2f} ms per frame exceeds the budget"
@@ -1,476 +0,0 @@
"""Tests for the MICI robotic character: cues, props, priorities, springs and blink."""
from contextlib import ExitStack
import math
import random
from unittest import mock
from openpilot.cereal import log
from openpilot.common.test import OpenpilotTestCase
from openpilot.selfdrive.ui.mici.onroad.alert_renderer import Alert
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.expressions import (
DrivingSnapshot,
GrooveStyle,
IdleAction,
MotionScheduler,
PALETTE,
RoboticMood,
RoboticMoodEngine,
STANDSTILL_POUT_DELAY,
STANDSTILL_SLEEPY_DELAY,
display_speed_and_set_speed,
)
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import MusicState
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.props import headphone_anchor, nightcap_geometry
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.scene import (
EyeGlyph,
MouthGlyph,
Pose,
Spring,
SpringBus,
volume_preserving,
)
from openpilot.selfdrive.ui.ui_state import UIStatus
AlertStatus = log.SelfdriveState.AlertStatus
def _music(**kwargs) -> MusicState:
base = {"is_music": True, "confidence": 0.85, "beat_pulse": 0.7, "groove_phase": 1.2, "bpm": 120.0, "energy": 0.7}
base.update(kwargs)
return MusicState(**base)
class TestCharacterCues(OpenpilotTestCase):
def _engine(self) -> RoboticMoodEngine:
return RoboticMoodEngine(rng=random.Random(42))
def test_engage_happy_then_speed_then_cruising(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=20.0)
pose = engine.update(snap, now=10.0)
assert engine.mood == RoboticMood.IDLE_CURIOUS
assert pose.color == PALETTE["disengaged"]
snap_eng = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, set_speed_kph=100.0)
pose = engine.update(snap_eng, now=11.0)
assert engine.mood == RoboticMood.HAPPY_ENGAGE
assert pose.glyph == EyeGlyph.CRESCENT
assert pose.color == PALETTE["engaged"]
engine.update(snap_eng, now=12.2)
assert engine.mood == RoboticMood.SPEED_DISPLAY
assert engine.showing_speed is True
pose = engine.update(snap_eng, now=15.0)
assert engine.mood == RoboticMood.CRUISING_HAPPY
assert engine.showing_speed is False
assert pose.color == PALETTE["engaged"]
def test_critical_alert_beats_every_cue(self):
engine = self._engine()
engine.trigger_love(now=10.0)
engine.trigger_speed_peek(now=10.0)
alert = Alert("TAKE CONTROL IMMEDIATELY", "Steering Required", status=AlertStatus.critical)
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, reverse=True, alert=alert)
pose = engine.update(snap, now=10.1)
assert engine.mood == RoboticMood.CRITICAL
assert pose.glyph == EyeGlyph.LASER_ALERT
assert pose.color == PALETTE["critical"]
assert pose.lid_top > 0.2
assert abs(pose.slant) > 10.0
assert pose.headphones == 0.0
assert engine.showing_speed is False
def test_distracted_turns_to_look_at_the_driver(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, dm_alert_level=1)
pose = engine.update(snap, now=20.0)
assert engine.mood == RoboticMood.DISTRACTED
assert pose.color == PALETTE["prompt"]
assert pose.mouth == MouthGlyph.FROWN
assert abs(pose.gaze_x) < 12.0
assert pose.eye_h > 112.0
def test_hard_decel_triggers_star_eyes(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, a_ego=-3.8)
pose = engine.update(snap, now=30.0)
assert engine.mood == RoboticMood.STARTLED_STARS
assert pose.glyph == EyeGlyph.STAR
assert pose.mouth == MouthGlyph.SURPRISED
def test_reverse_flips_the_face_upside_down(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=3.0, reverse=True)
pose = engine.update(snap, now=10.0)
assert engine.mood == RoboticMood.REVERSE
assert pose.flip == 1.0
assert pose.color == PALETTE["reverse"]
assert pose.glyph == EyeGlyph.CRESCENT
assert pose.mouth == MouthGlyph.BIG_GRIN
assert pose.hearts > 0.0
forward = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=3.0)
pose = engine.update(forward, now=11.0)
assert engine.mood != RoboticMood.REVERSE
assert pose.flip == 0.0
def test_music_drops_headphones_on(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=25.0, music=_music())
engine.update(snap, now=10.0)
pose = engine.update(snap, now=11.0)
assert engine.mood == RoboticMood.MUSIC_GROOVE
assert pose.headphones == 1.0
assert pose.notes == 1.0
assert 100.0 <= pose.eye_w <= 120.0
alerted = DrivingSnapshot(
started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=25.0, music=_music(),
alert=Alert("Pay Attention", "Eyes on road", status=AlertStatus.userPrompt),
)
pose = engine.update(alerted, now=11.5)
assert engine.mood == RoboticMood.USER_PROMPT
assert pose.headphones == 0.0
assert pose.notes == 0.0
def test_standstill_ladder_pout_then_nightcap_then_zzz(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, standstill=True)
engine.update(snap, now=100.0)
engine.update(snap, now=105.0)
assert engine.mood == RoboticMood.CRUISING_HAPPY
pose = engine.update(snap, now=100.0 + STANDSTILL_POUT_DELAY + 1.0)
assert engine.mood == RoboticMood.POUT_STANDSTILL
assert pose.mouth == MouthGlyph.FROWN
assert pose.nightcap == 0.0
pose = engine.update(snap, now=100.0 + STANDSTILL_SLEEPY_DELAY + 1.0)
assert engine.mood == RoboticMood.SLEEPY
assert pose.nightcap == 1.0
assert pose.zzz == 0.0
assert pose.glyph == EyeGlyph.CRESCENT
pose = engine.update(snap, now=100.0 + STANDSTILL_SLEEPY_DELAY + 21.0)
assert pose.zzz == 1.0
def test_lane_change_and_blind_spot_lean(self):
engine = self._engine()
snap_lc = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, pre_lane_change_left=True)
pose = engine.update(snap_lc, now=40.0)
assert engine.mood == RoboticMood.LANE_CHANGE
assert pose.glyph == EyeGlyph.ARROW_LEFT
assert pose.gaze_x < 0
assert pose.lean < 0
snap_bsm = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, right_blinker=True, right_blindspot=True)
pose = engine.update(snap_bsm, now=41.0)
assert engine.mood == RoboticMood.BLIND_SPOT
assert pose.gaze_x > 0
assert pose.blind_spot_side == 1
assert pose.edge_glow == 1.0
assert pose.arrow == 1.0
def test_blind_spot_respects_the_setting(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=20.0,
right_blinker=True, right_blindspot=True, blind_spot_enabled=False)
pose = engine.update(snap, now=42.0)
assert engine.mood == RoboticMood.TURN_SIGNAL
assert pose.blind_spot_side == 0
assert pose.edge_glow == 0.0
def test_music_props_survive_other_cues(self):
engine = self._engine()
blinker = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=18.0,
left_blinker=True, music=_music())
engine.update(blinker, now=20.0)
pose = engine.update(blinker, now=21.0)
assert engine.mood == RoboticMood.TURN_SIGNAL
assert pose.headphones > 0.8
assert pose.notes > 0.8
assert pose.beat > 0.5
engage = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, music=_music())
engine.update(engage, now=22.0)
pose = engine.update(engage, now=23.0)
assert engine.mood in (RoboticMood.HAPPY_ENGAGE, RoboticMood.SPEED_DISPLAY)
assert pose.headphones > 0.8
def test_alerts_strip_the_music_props(self):
engine = self._engine()
music = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, music=_music())
engine.update(music, now=30.0)
pose = engine.update(music, now=31.0)
assert pose.headphones > 0.8
alert = Alert("TAKE CONTROL IMMEDIATELY", "Steering Required", status=AlertStatus.critical)
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0,
music=_music(), alert=alert)
engine.update(snap, now=31.2)
pose = engine.update(snap, now=31.6)
assert engine.mood == RoboticMood.CRITICAL
assert pose.headphones < 0.3
assert pose.notes < 0.3
def test_music_props_hidden_when_offroad(self):
engine = self._engine()
snap = DrivingSnapshot(started=False, engaged=False, status=UIStatus.DISENGAGED, music=_music())
engine.update(snap, now=50.0)
pose = engine.update(snap, now=51.0)
assert engine.mood == RoboticMood.SLEEPY
assert pose.headphones < 0.3
assert pose.notes < 0.3
def test_blind_spot_outranks_turn_signal(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=25.0,
left_blinker=True, left_blindspot=True)
pose = engine.update(snap, now=40.0)
assert engine.mood == RoboticMood.BLIND_SPOT
assert pose.edge_glow > 0.0
def test_turn_signal_leans_toward_the_blinker(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=15.0, left_blinker=True)
pose = engine.update(snap, now=50.0)
assert engine.mood == RoboticMood.TURN_SIGNAL
assert pose.gaze_x < 0
assert pose.tilt < 0
assert pose.arrow == 1.0
def test_non_critical_alert_pulls_the_gaze_to_the_top_left(self):
engine = self._engine()
alert = Alert("Pay Attention", "Eyes on road", status=AlertStatus.normal)
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=20.0, alert=alert)
engine.update(snap, now=70.0)
pose = engine.update(snap, now=70.2)
assert engine.mood not in (RoboticMood.CRITICAL, RoboticMood.DISTRACTED)
assert pose.gaze_x < -15.0
assert pose.gaze_y < -12.0
def test_flip_animates_instead_of_snapping(self):
bus = SpringBus()
target = Pose(flip=1.0)
quarter = bus.step(target, 0.10)
assert 0.02 < quarter.flip < 0.98
for _ in range(120):
pose = bus.step(target, 1.0 / 60.0)
assert abs(pose.flip - 1.0) < 0.05
def test_pitch_rate_bounces_the_face(self):
engine = self._engine()
up = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, pitch_rate=0.6)
down = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, pitch_rate=-0.6)
pose_up = engine.update(up, now=60.0)
pose_down = engine.update(down, now=60.0)
assert pose_up.gaze_y - pose_down.gaze_y > 5.0
def test_headphones_and_nightcap_stay_on_screen(self):
cup_off, cup_y, crown_y = headphone_anchor(120.0, 108.0, 112.0, 166.0)
# cups sit at the eyes' outer edge, the band crown clears the eye tops, both fit the panel
assert cup_off < 166.0 / 2.0 + 108.0 / 2.0
assert crown_y < 120.0 - 112.0 / 2.0 - 10.0
assert 0.0 < cup_y < 240.0
_, tip_y = nightcap_geometry(56.0, 1.0)
assert 0.0 < tip_y < 56.0
def test_groove_feeds_the_beat_to_props(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=25.0,
music=_music(beat_pulse=0.9))
engine.update(snap, now=10.0)
pose = engine.update(snap, now=10.2)
assert engine.mood == RoboticMood.MUSIC_GROOVE
assert 0.85 <= pose.beat <= 0.95
def test_set_speed_change_still_shows_the_visual(self):
engine = self._engine()
snap1 = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, set_speed_kph=100.0)
engine.update(snap1, now=10.0)
engine.update(snap1, now=15.0)
assert engine.showing_speed is False
snap2 = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, set_speed_kph=110.0)
engine.update(snap2, now=16.0)
assert engine.mood == RoboticMood.SPEED_DISPLAY
assert engine.showing_speed is True
assert engine.speed_reason == "set_speed"
def test_mads_uses_warm_peach_palette(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.LAT_ONLY, v_ego=18.0)
engine.update(snap, now=10.0)
pose = engine.update(snap, now=15.0)
assert pose.color == PALETTE["lat_only"]
def test_display_speed_conversion(self):
snap_mph = DrivingSnapshot(v_ego=26.8224, set_speed_kph=100.0, is_metric=False)
cur, set_s = display_speed_and_set_speed(snap_mph)
assert cur == 60
assert set_s == 62
snap_kph = DrivingSnapshot(v_ego=27.7778, set_speed_kph=100.0, is_metric=True)
cur, set_s = display_speed_and_set_speed(snap_kph)
assert cur == 100
assert set_s == 100
def test_continuous_motion_never_freezes(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED)
p1 = engine.update(snap, now=40.0)
p2 = engine.update(snap, now=40.5)
assert (p1.gaze_y != p2.gaze_y) or (p1.gaze_x != p2.gaze_x) or (p1.tilt != p2.tilt)
class TestCentrifugalSquish(OpenpilotTestCase):
def _engine(self) -> RoboticMoodEngine:
return RoboticMoodEngine(rng=random.Random(7))
def test_low_speed_turn_stays_calm(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=5.0, yaw_rate=0.25)
engine.update(snap, now=10.0)
pose = engine.update(snap, now=15.0)
assert pose.squish == 0.0
assert engine.mood == RoboticMood.CRUISING_HAPPY
def test_high_speed_right_turn_pushes_left(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=24.0, yaw_rate=0.19)
pose = engine.update(snap, now=16.0)
assert engine.mood == RoboticMood.SHARP_TURN
assert pose.squish < -0.65
assert pose.mouth == MouthGlyph.SURPRISED
def test_high_speed_left_turn_pushes_right(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=24.0, yaw_rate=-0.19)
pose = engine.update(snap, now=17.0)
assert engine.mood == RoboticMood.SHARP_TURN
assert pose.squish > 0.65
class TestBlink(OpenpilotTestCase):
def test_blink_is_eased_and_never_fully_closes(self):
engine = RoboticMoodEngine(rng=random.Random(3))
snap = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=20.0)
engine.update(snap, now=10.0)
engine.trigger_blink(now=10.0)
peak = engine.update(snap, now=10.08)
closed = peak.lid_top + peak.lid_bottom
assert 0.10 < closed <= 0.92 + 1e-6
quarter = engine.update(snap, now=10.02)
assert 0.0 < quarter.lid_top + quarter.lid_bottom < closed
open_again = engine.update(snap, now=10.6)
assert open_again.lid_top + open_again.lid_bottom < 0.05
class TestRendererWiring(OpenpilotTestCase):
def test_prop_channels_reach_the_draw_calls(self):
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic import face_renderer as fr
renderer = fr.ProceduralFaceRenderer()
pose = Pose(mouth=MouthGlyph.SMILE, headphones=1.0, nightcap=1.0, notes=1.0, hearts=1.0,
zzz=1.0, edge_glow=1.0, blind_spot_side=1, arrow=1.0, blinker_side=-1,
speed_lines=1.0, beat=0.6)
rect = mock.MagicMock(x=0.0, y=0.0, width=536.0, height=240.0)
fake_rl = mock.MagicMock()
fake_rl.get_time.return_value = 10.0
fake_rl.Color.side_effect = lambda *args: tuple(args)
names = ["draw_headphones", "draw_nightcap", "draw_floating_notes", "draw_floating_hearts",
"draw_floating_zzz", "draw_edge_glow", "draw_speed_lines"]
with ExitStack() as stack:
stack.enter_context(mock.patch.object(fr, "rl", fake_rl))
eye = stack.enter_context(mock.patch.object(fr.ProceduralFaceRenderer, "_draw_eye"))
mouth = stack.enter_context(mock.patch.object(fr.ProceduralFaceRenderer, "_draw_mouth"))
spies = {name: stack.enter_context(mock.patch.object(fr, name)) for name in names}
renderer.render(rect, pose)
assert eye.call_count == 2
assert mouth.call_count == 1
assert all(call.args[8] == EyeGlyph.ARROW_LEFT for call in eye.call_args_list)
headphone_calls = spies["draw_headphones"].call_args_list
assert len(headphone_calls) == 2
assert all(call.args[5] > 0.99 for call in headphone_calls)
assert spies["draw_nightcap"].call_args.args[3] > 0.99
assert spies["draw_floating_notes"].call_args.args[1] > 0.99
assert abs(spies["draw_floating_notes"].call_args.args[4] - 0.6) < 1e-6
assert spies["draw_floating_hearts"].call_args.args[2] > 0.99
assert spies["draw_floating_zzz"].call_args.args[2] > 0.99
assert spies["draw_edge_glow"].call_args.args[1] == 1
assert spies["draw_speed_lines"].call_args.args[2] > 0.99
class TestMotionPrimitives(OpenpilotTestCase):
def test_spring_converges_with_controlled_overshoot(self):
spring = Spring(0.0, omega=26.0, zeta=0.62)
peak = 0.0
for _ in range(90):
peak = max(peak, spring.step(1.0, 1.0 / 60.0))
assert abs(spring.value - 1.0) < 0.03
assert 1.0 < peak < 1.30
def test_fixed_substep_makes_motion_frame_rate_independent(self):
a = Spring(0.0, omega=26.0, zeta=0.62)
b = Spring(0.0, omega=26.0, zeta=0.62)
for _ in range(10):
a.step(1.0, 1.0 / 60.0)
for _ in range(20):
b.step(1.0, 1.0 / 120.0)
assert abs(a.value - b.value) < 1e-9
def test_squash_preserves_volume(self):
for sx in (0.8, 0.95, 1.0, 1.2):
assert abs(sx * volume_preserving(sx) - 1.0) < 1e-9
def test_bus_smooths_and_copies_discrete_channels(self):
bus = SpringBus()
target = Pose(eye_w=140.0, glyph=EyeGlyph.STAR, mouth=MouthGlyph.SURPRISED, color=(10, 20, 30))
out = bus.step(target, 1.0 / 60.0)
assert out.eye_w > 104.0
assert out.eye_w < 140.0
assert out.glyph == EyeGlyph.STAR
assert out.mouth == MouthGlyph.SURPRISED
for _ in range(120):
out = bus.step(target, 1.0 / 60.0)
assert abs(out.eye_w - 140.0) < 1.0
class TestSchedulerAndIdle(OpenpilotTestCase):
def test_scheduler_respects_cooldown_and_no_repeat(self):
scheduler = MotionScheduler(["a", "b", "c"], random.Random(11), cooldown=10.0)
picks = [scheduler.pick(t) for t in (0.0, 0.5, 1.0, 1.5, 2.0)]
for i in range(1, len(picks)):
assert picks[i] != picks[i - 1]
def test_idle_produces_varied_actions(self):
engine = RoboticMoodEngine(rng=random.Random(5))
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=20.0)
seen: set[IdleAction] = set()
t = 100.0
for _ in range(600):
t += 0.1
engine.update(snap, now=t)
if engine.idle_action is not IdleAction.NONE:
seen.add(engine.idle_action)
assert len(seen) >= 3
def test_music_groove_phase_drives_pose_symmetrically(self):
engine = RoboticMoodEngine(rng=random.Random(9))
engine._groove_style = GrooveStyle.SIDE_SWAY
engine._groove_switch_at = 1e18
poses: list[Pose] = []
for i in range(40):
phase = i * math.tau / 20.0
snap = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=25.0,
music=_music(groove_phase=phase, beat_pulse=0.0))
poses.append(engine.update(snap, now=10.0 + i * 0.05))
assert min(p.gaze_x for p in poses) < -3.0
assert max(p.gaze_x for p in poses) > 3.0
+31 -114
View File
@@ -1,4 +1,3 @@
import contextlib
import math
import numpy as np
import time
@@ -9,27 +8,29 @@ from openpilot.cereal import log, messaging, custom
from openpilot.common.basedir import BASEDIR
from openpilot.common.filter_simple import FirstOrderFilter
from openpilot.common.realtime import Ratekeeper
from openpilot.common.utils import retry
from openpilot.common.swaglog import cloudlog
from openpilot.system import micd
from openpilot.common.hardware import HARDWARE
from openpilot.sunnypilot.selfdrive.ui.quiet_mode import QuietMode
from openpilot.sunnypilot.selfdrive.ui.robotic_sounds import REACTIVE_CHIRP_IDS, RoboticSoundPack
SAMPLE_RATE = 48000
SAMPLE_BUFFER = 4096 # (approx 100ms)
MAX_VOLUME = 1.0
AMBIENT_DB = 10.0 # DB where MIN_VOLUME is applied
DB_SCALE = 25.0 # AMBIENT_DB + DB_SCALE is where MAX_VOLUME is applied
MIN_VOLUME = 0.45
MIN_VOLUME = 0.1
ALERT_RAMP_TIME = 4 # seconds to ramp to max volume for immediate warnings
SELFDRIVE_STATE_TIMEOUT = 5 # 5 seconds
FILTER_DT = 1. / (micd.SAMPLE_RATE / micd.FFT_SAMPLES)
AMBIENT_DB = 26 # DB where MIN_VOLUME is applied
DB_SCALE = 30 # AMBIENT_DB + DB_SCALE is where MAX_VOLUME is applied
VOLUME_BASE = 20
REINIT_RETRY_INTERVAL = 3.0
if HARDWARE.get_device_type() == "tizi":
AMBIENT_DB = 30
VOLUME_BASE = 10
AudibleAlert = log.SelfdriveState.AudibleAlert
AudibleAlertSP = custom.SelfdriveStateSP.AudibleAlert
@@ -77,7 +78,6 @@ def check_selfdrive_timeout_alert(sm):
class Soundd(QuietMode):
def __init__(self):
super().__init__()
self.robotic_sound_pack = RoboticSoundPack(self.params, SAMPLE_RATE)
self.load_sounds()
@@ -92,7 +92,6 @@ class Soundd(QuietMode):
self.pending_stop = False
self.spl_filter_weighted = FirstOrderFilter(0, 2.5, FILTER_DT, initialized=False)
self.spl_received = False
def load_sounds(self):
self.loaded_sounds: dict[int, np.ndarray] = {}
@@ -109,32 +108,13 @@ class Soundd(QuietMode):
length = wavefile.getnframes()
self.loaded_sounds[sound] = np.frombuffer(wavefile.readframes(length), dtype=np.int16).astype(np.float32) / (2**16/2)
self.robotic_sound_pack.load()
def load_param(self) -> None:
prev_frame = self._frame
super().load_param()
if self._frame != prev_frame and self._frame % 50 == 0:
if self.robotic_sound_pack.refresh_param():
self.current_sound_frame = 0
def _sound_buffer(self, alert_id: int) -> np.ndarray | None:
"""Resolve the buffer for an alert id, or None when this id has no sound loaded."""
if alert_id == AudibleAlert.none:
return None
try:
return self.robotic_sound_pack.get_buffer(alert_id, self.loaded_sounds)
except KeyError:
return None
def get_sound_data(self, frames): # get "frames" worth of data from the current alert sound, looping when required
ret = np.zeros(frames, dtype=np.float32)
sound_data = self._sound_buffer(self.current_alert)
if sound_data is not None:
audible = self.should_play_sound(self.current_alert)
num_loops = 1 if self.current_alert in REACTIVE_CHIRP_IDS else sound_list[self.current_alert][1]
if self.should_play_sound(self.current_alert):
num_loops = sound_list[self.current_alert][1]
sound_data = self.loaded_sounds[self.current_alert]
written_frames = 0
current_sound_frame = self.current_sound_frame % len(sound_data)
@@ -143,8 +123,7 @@ class Soundd(QuietMode):
while written_frames < frames and (num_loops is None or loops < num_loops):
available_frames = sound_data.shape[0] - current_sound_frame
frames_to_write = min(available_frames, frames - written_frames)
if audible:
ret[written_frames:written_frames+frames_to_write] = sound_data[current_sound_frame:current_sound_frame+frames_to_write]
ret[written_frames:written_frames+frames_to_write] = sound_data[current_sound_frame:current_sound_frame+frames_to_write]
written_frames += frames_to_write
self.current_sound_frame += frames_to_write
current_sound_frame = self.current_sound_frame % len(sound_data)
@@ -154,35 +133,17 @@ class Soundd(QuietMode):
self.pending_stop = False
break
vol = self.current_volume
if self.robotic_sound_pack.enabled and not self.enabled and self.current_alert != AudibleAlert.none:
vol = max(vol, 0.35)
return ret * vol
return ret * self.current_volume
def callback(self, data_out: np.ndarray, frames: int, time, status) -> None:
if status:
cloudlog.warning(f"soundd stream over/underflow: {status}")
data_out[:frames, 0] = self.get_sound_data(frames)
def _note_play(self, alert_id: int) -> None:
"""Log the alert start together with the routing decision and the gain it plays at."""
if alert_id == AudibleAlert.none:
return
audible = self.should_play_sound(alert_id)
robotic = self.robotic_sound_pack.enabled and alert_id in self.robotic_sound_pack.sounds
cloudlog.debug(f"soundd play alert={alert_id} robotic={robotic} audible={audible} gain={self.current_volume:.2f}")
def update_alert(self, new_alert):
current_buffer = self._sound_buffer(self.current_alert)
current_alert_played_once = current_buffer is None or self.current_sound_frame >= len(current_buffer)
current_alert_played_once = self.current_alert == AudibleAlert.none or self.current_sound_frame >= len(self.loaded_sounds[self.current_alert])
# let looping sounds finish the current loop instead of cutting off mid tone
if (
new_alert == AudibleAlert.none
and self.current_alert != AudibleAlert.none
and self.current_alert not in REACTIVE_CHIRP_IDS
and sound_list[self.current_alert][1] is None
):
if new_alert == AudibleAlert.none and self.current_alert != AudibleAlert.none and sound_list[self.current_alert][1] is None:
if current_alert_played_once:
self.pending_stop = True
else:
@@ -196,8 +157,6 @@ class Soundd(QuietMode):
self.ramp_start_time = time.monotonic()
self.current_alert = new_alert
self.current_sound_frame = 0
self.robotic_sound_pack.start_alert(new_alert)
self._note_play(new_alert)
def get_audible_alert(self, sm):
if sm.updated['selfdriveState']:
@@ -210,78 +169,38 @@ class Soundd(QuietMode):
self.update_alert(AudibleAlert.none)
self.selfdrive_timeout_alert = False
# Trigger playful one-shot robotic chirps only when idle (never preempting safety alerts)
if self.robotic_sound_pack.enabled and self.current_alert == AudibleAlert.none:
chirp = self.robotic_sound_pack.detect_reactive_chirp(sm)
if chirp is not None:
self.update_alert(chirp)
def calculate_volume(self, weighted_db):
volume = ((weighted_db - AMBIENT_DB) / DB_SCALE) * (MAX_VOLUME - MIN_VOLUME) + MIN_VOLUME
return math.pow(VOLUME_BASE, (np.clip(volume, MIN_VOLUME, MAX_VOLUME) - 1))
def _reinit_stream(self, sd, stream):
if stream is not None:
with contextlib.suppress(Exception):
stream.close()
# reload sounddevice to reinitialize portaudio, then open the output stream
@retry(attempts=10, delay=3)
def get_stream(self, sd):
# reload sounddevice to reinitialize portaudio
sd._terminate()
sd._initialize()
new_stream = sd.OutputStream(channels=1, samplerate=SAMPLE_RATE, callback=self.callback, blocksize=SAMPLE_BUFFER)
try:
new_stream.start()
except Exception:
with contextlib.suppress(Exception):
new_stream.close()
raise
cloudlog.info(f"soundd stream started: {new_stream.samplerate=} {new_stream.channels=} {new_stream.dtype=} {new_stream.device=}, {new_stream.blocksize=}")
return new_stream
def update_volume(self, valid: bool, sound_pressure_weighted_db: float) -> None:
# Only adapt volume from valid mic data. With invalid (stale) soundPressure
# we freeze instead of decaying towards MIN_VOLUME, so critical alerts can
# never be silenced by a broken mic (https://github.com/commaai/openpilot/issues/36088)
if not valid:
if self.spl_received:
cloudlog.warning("soundd: soundPressure invalid, freezing alert volume")
self.spl_received = False
return
self.spl_received = True
self.spl_filter_weighted.update(sound_pressure_weighted_db)
# freeze volume during alerts to avoid mic feedback increasing volume
if self.current_alert == AudibleAlert.none:
self.current_volume = self.calculate_volume(float(self.spl_filter_weighted.x))
return sd.OutputStream(channels=1, samplerate=SAMPLE_RATE, callback=self.callback, blocksize=SAMPLE_BUFFER)
def soundd_thread(self):
# sounddevice must be imported after forking processes
import sounddevice as sd
micd.patch_sounddevice(sd)
sm = messaging.SubMaster(['selfdriveState', 'selfdriveStateSP', 'soundPressure', 'userBookmark', 'bookmarkButton'])
rk = Ratekeeper(20)
stream = None
last_reinit_time: float | None = None
sm = messaging.SubMaster(['selfdriveState', 'selfdriveStateSP', 'soundPressure'])
try:
with self.get_stream(sd) as stream:
rk = Ratekeeper(20)
cloudlog.info(f"soundd stream started: {stream.samplerate=} {stream.channels=} {stream.dtype=} {stream.device=}, {stream.blocksize=}")
while True:
if stream is None or not stream.active:
now = time.monotonic()
if last_reinit_time is None or (now - last_reinit_time) >= REINIT_RETRY_INTERVAL:
last_reinit_time = now
try:
stream = self._reinit_stream(sd, stream)
except Exception:
stream = None
cloudlog.exception("soundd failed to open stream")
sm.update(0)
self.load_param()
# freeze volume during alerts to avoid mic feedback increasing volume
if sm.updated['soundPressure']:
self.update_volume(bool(sm.valid['soundPressure']), float(sm["soundPressure"].soundPressureWeightedDb))
self.spl_filter_weighted.update(sm["soundPressure"].soundPressureWeightedDb)
if self.current_alert == AudibleAlert.none:
self.current_volume = self.calculate_volume(float(self.spl_filter_weighted.x))
self.get_audible_alert(sm)
@@ -292,10 +211,8 @@ class Soundd(QuietMode):
self.current_volume = max(self.current_volume, ramp_vol)
rk.keep_time()
finally:
if stream is not None:
with contextlib.suppress(Exception):
stream.close()
assert stream.active
def main():
@@ -195,7 +195,7 @@ class ConnectPhoneLayout(PairingDialog):
rl.draw_circle(int(circle_x), int(circle_y), circle_radius, rl.Color(70, 70, 70, 255))
number = str(i + 1)
number_size = measure_text_cached(font, number, 30)
rl.draw_text_ex(font, number, (int(circle_x - number_size.x // 2), int(circle_y - number_size.y // 2)), 30, 0, rl.WHITE)
rl.draw_text_ex(font, number, rl.Vector2(circle_x - number_size.x // 2, circle_y - number_size.y // 2), 30, 0.0, rl.WHITE)
rl.draw_text_ex(font, "\n".join(wrapped), rl.Vector2(text_x, y), 47, 0.0, rl.BLACK)
y += text_height + 50
@@ -114,7 +114,7 @@ class SettingsLayoutSP(OP.SettingsLayout):
self._panels = {
PanelType.DEVICE: PanelInfo(tr_noop("Device"), DeviceLayoutSP(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_home.png"),
PanelType.NETWORK: PanelInfo(tr_noop("Network"), NetworkUISP(wifi_manager), icon="icons/network.png"),
OP.PanelType.BLUETOOTH: PanelInfo(tr_noop("Bluetooth"), BluetoothLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_bluetooth.png"),
PanelType.BLUETOOTH: PanelInfo(tr_noop("Bluetooth"), BluetoothLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_bluetooth.png"),
PanelType.SUNNYLINK: PanelInfo(tr_noop("sunnylink"), SunnylinkLayout(), icon="icons/wifi_strength_full.png"),
PanelType.TOGGLES: PanelInfo(tr_noop("Toggles"), TogglesLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_toggle.png"),
PanelType.SOFTWARE: PanelInfo(tr_noop("Software"), SoftwareLayoutSP(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_software.png"),
@@ -7,7 +7,7 @@ See the LICENSE.md file in the root directory for more details.
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.base import BrandSettings
from openpilot.selfdrive.ui.ui_state import ui_state
from openpilot.system.ui.lib.multilang import tr
from openpilot.system.ui.sunnypilot.widgets.list_view import toggle_item_sp
from openpilot.system.ui.sunnypilot.widgets.list_view import multiple_button_item_sp
from opendbc.car.hyundai.values import CAR, UNSUPPORTED_LONGITUDINAL_CAR
@@ -16,9 +16,16 @@ class HyundaiSettings(BrandSettings):
super().__init__()
self.alpha_long_available = False
self.longitudinal_tuning_item = toggle_item_sp(tr("Custom Longitudinal Tuning"), "", param="HyundaiLongitudinalTuning")
tuning_texts = [tr("Off"), tr("Dynamic"), tr("Predictive")]
self.longitudinal_tuning_item = multiple_button_item_sp(tr("Custom Longitudinal Tuning"), "", tuning_texts,
button_width=300, callback=self._on_tuning_selected,
param="HyundaiLongitudinalTuning", inline=False)
self.items = [self.longitudinal_tuning_item]
@staticmethod
def _on_tuning_selected(index):
ui_state.params.put("HyundaiLongitudinalTuning", index)
def update_settings(self):
self.alpha_long_available = False
bundle = ui_state.params.get("CarPlatformBundle")
@@ -28,14 +35,25 @@ class HyundaiSettings(BrandSettings):
elif ui_state.CP is not None:
self.alpha_long_available = ui_state.CP.alphaLongitudinalAvailable
tuning_param = int(ui_state.params.get("HyundaiLongitudinalTuning") or "0")
long_enabled = ui_state.has_longitudinal_control
desc = tr("Accelerates and brakes the way your car's own cruise control does.")
if not ui_state.is_offroad():
desc = tr("This feature is unavailable while the car is onroad.")
elif not long_enabled:
desc = tr("This feature is unavailable because sunnypilot Longitudinal Control (Alpha) is not enabled.")
self.longitudinal_tuning_item.action_item.set_enabled(ui_state.is_offroad() and long_enabled)
self.longitudinal_tuning_item.set_description(desc)
long_tuning_descs = [
tr("Your vehicle will use the Default longitudinal tuning."),
tr("Your vehicle will use the Dynamic longitudinal tuning."),
tr("Your vehicle will use the Predictive longitudinal tuning."),
]
long_tuning_desc = long_tuning_descs[tuning_param] if tuning_param < len(long_tuning_descs) else long_tuning_descs[0]
longitudinal_tuning_disabled = not ui_state.is_offroad() or not long_enabled
if longitudinal_tuning_disabled:
if not ui_state.is_offroad():
long_tuning_desc = tr("This feature is unavailable while the car is onroad.")
elif not long_enabled:
long_tuning_desc = tr("This feature is unavailable because sunnypilot Longitudinal Control (Alpha) is not enabled.")
self.longitudinal_tuning_item.action_item.set_enabled(not longitudinal_tuning_disabled)
self.longitudinal_tuning_item.set_description(long_tuning_desc)
self.longitudinal_tuning_item.show_description(True)
self.longitudinal_tuning_item.action_item.set_selected_button(tuning_param)
self.longitudinal_tuning_item.set_visible(self.alpha_long_available)
@@ -11,11 +11,17 @@ from openpilot.system.ui.lib.multilang import tr, tr_noop
from openpilot.system.ui.widgets import DialogResult
from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog
from openpilot.system.ui.sunnypilot.widgets.list_view import toggle_item_sp
from opendbc.car.toyota.values import ToyotaFlags
from opendbc.car.toyota.values import CAR, ToyotaFlags
from opendbc.sunnypilot.car.toyota.values import ToyotaFlagsSP
ONROAD_ONLY_DESCRIPTION = tr_noop("Start the vehicle to check vehicle compatibility.")
SNG_HACK_UNAVAILABLE = tr_noop("sunnypilot Longitudinal Control must be available and enabled for your vehicle to use this feature.")
BSM_UNAVAILABLE = tr_noop("Enhanced Blind Spot Monitoring requires a TSS2 Toyota/Lexus without SecOC, " +
"or a smartDSU with sunnypilot longitudinal control.")
BSM_STOCK_LONG_UNAVAILABLE = tr_noop("Enhanced Blind Spot Monitoring is not available while Enforce Factory Longitudinal Control is enabled.")
BSM_REQUIRED = tr_noop("This vehicle does not report blind spot status over the standard CAN signals. " +
"Enhanced Blind Spot Monitoring is required for blind spot detection.")
PLATFORM_UNAVAILABLE = tr_noop("This feature is currently not available on this platform.")
DESCRIPTIONS = {
@@ -26,6 +32,10 @@ DESCRIPTIONS = {
'sunnypilot will allow some Toyota/Lexus cars to auto resume during stop and go traffic. ' +
'This feature is only applicable to certain models that are able to use longitudinal control. This is an alpha feature. Use at your own risk.'
),
'enhanced_bsm': tr_noop(
'sunnypilot will poll the blind spot monitor diagnostics directly from the radar. Use this on vehicles whose blind spot monitors ' +
'do not report blind spot status over the standard CAN signals. This is an alpha feature. Use at your own risk.'
),
'tss2_smooth': tr_noop(
'Enable smoother longitudinal control for TSS2 vehicles. ' +
'Uses a custom speed-dependent integral gain curve for smoother traffic driving.'
@@ -53,6 +63,14 @@ class ToyotaSettings(BrandSettings):
enabled=lambda: not ui_state.engaged,
)
self.enhanced_bsm = toggle_item_sp(
lambda: tr("Enhanced Blind Spot Monitoring (Alpha)"),
description=lambda: tr(DESCRIPTIONS["enhanced_bsm"]),
initial_state=ui_state.params.get_bool("ToyotaEnhancedBsm"),
callback=self._on_enable_enhanced_bsm,
enabled=lambda: not ui_state.engaged,
)
self.tss2_smooth = toggle_item_sp(
lambda: tr("TSS2 Smooth Longitudinal (Alpha)"),
description=lambda: tr(DESCRIPTIONS["tss2_smooth"]),
@@ -64,6 +82,7 @@ class ToyotaSettings(BrandSettings):
self.items = [
self.enforce_stock_longitudinal,
self.stop_and_go_hack,
self.enhanced_bsm,
self.tss2_smooth,
]
@@ -130,6 +149,25 @@ class ToyotaSettings(BrandSettings):
ui_state.params.put_bool("ToyotaStopAndGoHack", False)
ui_state.params.put_bool("OnroadCycleRequested", True)
def _on_enable_enhanced_bsm(self, state: bool):
if state:
def confirm_callback(result: int):
if result == DialogResult.CONFIRM:
ui_state.params.put_bool("ToyotaEnhancedBsm", True)
ui_state.params.put_bool("OnroadCycleRequested", True)
else:
self.enhanced_bsm.action_item.set_state(False)
content = (f"<h1>{self.enhanced_bsm.title}</h1><br>" +
f"<p>{self.enhanced_bsm.description}</p>")
dlg = ConfirmDialog(content, tr("Enable"), rich=True, callback=confirm_callback)
gui_app.push_widget(dlg)
else:
ui_state.params.put_bool("ToyotaEnhancedBsm", False)
ui_state.params.put_bool("OnroadCycleRequested", True)
def update_settings(self):
if ui_state.CP is not None:
longitudinal = ui_state.CP.openpilotLongitudinalControl
@@ -150,6 +188,33 @@ class ToyotaSettings(BrandSettings):
if show_desc:
self.stop_and_go_hack.show_description(True)
# Enhanced BSM needs the radar diagnostic address, which is only in the TX allowlist for
# TSS2 cars without SecOC, or for TSS-P cars with a smartDSU. Both need openpilot long.
sdsu_bsm_supported = (ui_state.CP_SP is not None and
bool(ui_state.CP_SP.flags & ToyotaFlagsSP.SMART_DSU))
bsm_supported = (not bool(ui_state.CP.flags & ToyotaFlags.SECOC) and
(bool(ui_state.CP.flags & ToyotaFlags.TSS2) or sdsu_bsm_supported))
bsm_available = bsm_supported and longitudinal and not enforce_stock
self.enhanced_bsm.action_item.set_enabled(bsm_available and not ui_state.engaged)
bsm_desc = tr(DESCRIPTIONS["enhanced_bsm"])
if not bsm_supported:
self.enhanced_bsm.action_item.set_state(False)
bsm_desc = "<b>" + tr(BSM_UNAVAILABLE) + "</b>\n\n" + bsm_desc
elif enforce_stock:
self.enhanced_bsm.action_item.set_state(False)
bsm_desc = "<b>" + tr(BSM_STOCK_LONG_UNAVAILABLE) + "</b>\n\n" + bsm_desc
elif not longitudinal:
self.enhanced_bsm.action_item.set_state(False)
bsm_desc = "<b>" + tr(SNG_HACK_UNAVAILABLE) + "</b>\n\n" + bsm_desc
elif ui_state.CP.carFingerprint == CAR.TOYOTA_PRIUS_TSS2:
bsm_desc = "<b>" + tr(BSM_REQUIRED) + "</b>\n\n" + bsm_desc
if self.enhanced_bsm.description != bsm_desc:
self.enhanced_bsm.set_description(bsm_desc)
if not bsm_available:
self.enhanced_bsm.show_description(True)
tss2 = bool(ui_state.CP.flags & ToyotaFlags.TSS2)
if longitudinal and not enforce_stock and tss2:
self.tss2_smooth.action_item.set_enabled(not ui_state.engaged)
@@ -173,6 +238,12 @@ class ToyotaSettings(BrandSettings):
self.stop_and_go_hack.set_description(new_desc)
self.stop_and_go_hack.show_description(True)
self.enhanced_bsm.action_item.set_enabled(False)
bsm_desc = "<b>" + tr(ONROAD_ONLY_DESCRIPTION) + "</b>\n\n" + tr(DESCRIPTIONS["enhanced_bsm"])
if self.enhanced_bsm.description != bsm_desc:
self.enhanced_bsm.set_description(bsm_desc)
self.enhanced_bsm.show_description(True)
self.tss2_smooth.action_item.set_enabled(False)
new_desc = "<b>" + tr(ONROAD_ONLY_DESCRIPTION) + "</b>\n\n" + tr(DESCRIPTIONS["tss2_smooth"])
if self.tss2_smooth.description != new_desc:
@@ -1,9 +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.
"""
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.robotic_view import RoboticOnroadView
__all__ = ["RoboticOnroadView"]
@@ -1,109 +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 math
import raylib_nb as rl
from openpilot.cereal import log
from openpilot.common.filter_simple import FirstOrderFilter
from openpilot.selfdrive.ui.onroad.alert_renderer import Alert, get_alert
from openpilot.selfdrive.ui.ui_state import ui_state
from openpilot.system.ui.lib.application import FontWeight, TextAlignment, gui_app
from openpilot.system.ui.widgets.label import UnifiedLabel
AlertStatus = log.SelfdriveState.AlertStatus
class RoboticAlertOverlay:
"""Alert text that fades in from the top edge, leaving the face unobstructed below."""
def __init__(self):
dt = 1.0 / max(gui_app.target_fps, 1)
self._prev_alert: Alert | None = None
self._alpha_filter = FirstOrderFilter(0.0, 0.05, dt)
self._text1_label = UnifiedLabel(
text="",
font_size=40,
font_weight=FontWeight.DISPLAY,
alignment=TextAlignment.CENTER,
line_height=0.9,
)
self._text2_label = UnifiedLabel(
text="",
font_size=24,
font_weight=FontWeight.MEDIUM,
alignment=TextAlignment.CENTER,
line_height=0.95,
)
def get_alert(self) -> Alert | None:
alert = get_alert(ui_state.sm)
if gui_app.sunnypilot_ui():
ui_state.onroad_brightness_handle_alerts(ui_state, alert)
return alert
def render(self, rect: rl.Rectangle, alert: Alert | None) -> float:
"""Render the top alert text and return its alpha so the caller can make room for it."""
alpha = self._alpha_filter.update(1.0 if alert is not None else 0.0)
if alert is not None:
self._prev_alert = alert
elif alpha > 0.02 and self._prev_alert is not None:
alert = self._prev_alert
else:
self._prev_alert = None
return 0.0
is_critical = alert.status == AlertStatus.critical
is_prompt = alert.status == AlertStatus.userPrompt
t = rl.get_time()
slide = (1.0 - alpha) * -20.0
# Feathered scrims only: no box, no band, no hard edge on the 240 px panel.
rl.draw_rectangle_gradient_v(int(rect.x), int(rect.y - 4), int(rect.width), 86,
rl.Color(0, 0, 0, int(140 * alpha)), rl.Color(0, 0, 0, 0))
if is_critical:
pulse = 0.60 + 0.40 * (0.5 + 0.5 * math.sin(t * 13.0))
rl.draw_rectangle_gradient_v(int(rect.x), int(rect.y - 4), int(rect.width), 92,
rl.Color(206, 6, 24, int(58 * alpha * pulse)), rl.Color(206, 6, 24, 0))
elif is_prompt:
rl.draw_rectangle_gradient_v(int(rect.x), int(rect.y - 4), int(rect.width), 86,
rl.Color(236, 108, 12, int(46 * alpha)), rl.Color(236, 108, 12, 0))
self._draw_alert_text(rect, alert, alpha, slide, is_critical)
return alpha
def _draw_alert_text(self, rect: rl.Rectangle, alert: Alert, alpha: float, slide: float,
critical: bool) -> None:
text1 = alert.text1.lower()
text2 = alert.text2.lower()
top = rect.y + 8.0 + slide
if critical:
font1 = 34 if len(text1) <= 18 else (29 if len(text1) <= 25 else 24)
color1 = rl.Color(255, 104, 112, int(250 * alpha))
elif alert.status == AlertStatus.userPrompt:
font1 = 32 if len(text1) <= 20 else 27
color1 = rl.Color(255, 206, 158, int(248 * alpha))
else:
font1 = 31 if len(text1) <= 22 else 25
color1 = rl.Color(255, 255, 255, int(248 * alpha))
margin_x = 26.0
w = rect.width - margin_x * 2.0
self._text1_label.set_text(text1)
self._text1_label.set_font_size(font1)
self._text1_label.set_text_color(color1)
self._text1_label.render(rl.Rectangle(rect.x + margin_x, top, w, font1 + 4.0))
if text2:
font2 = 24 if len(text2) <= 30 else 20
self._text2_label.set_text(text2)
self._text2_label.set_font_size(font2)
self._text2_label.set_text_color(rl.Color(255, 255, 255, int(185 * alpha)))
self._text2_label.render(rl.Rectangle(rect.x + margin_x, top + font1 * 0.92, w, font2 + 6.0))
@@ -1,176 +0,0 @@
"""Animation libraries for the MICI face: groove styles and idle actions."""
import math
from enum import Enum
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import MusicState
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.scene import (
EyeGlyph,
MouthGlyph,
Pose,
groove_prism_color,
)
class IdleAction(Enum):
NONE = "none"
HAPPY_SQUINT = "happy_squint"
CURIOUS_LOOK = "curious_look"
CHEEKY_WINK = "cheeky_wink"
STRETCH = "stretch"
SETTLE = "settle"
PERK_UP = "perk_up"
DAYDREAM = "daydream"
DOODLE = "doodle"
DOUBLE_BLINK_TILT = "double_blink_tilt"
class GrooveStyle(Enum):
HEAD_BOB = "head_bob"
SIDE_SWAY = "side_sway"
JELLY = "jelly"
SNARE_BLINK = "snare_blink"
LOOK_AROUND = "look_around"
ANTICIPATION_POP = "anticipation_pop"
GLOW_PULSE = "glow_pulse"
IDLE_ACTION_DURATION = {
IdleAction.HAPPY_SQUINT: 0.9,
IdleAction.CURIOUS_LOOK: 1.6,
IdleAction.CHEEKY_WINK: 0.6,
IdleAction.STRETCH: 1.8,
IdleAction.SETTLE: 2.4,
IdleAction.PERK_UP: 1.0,
IdleAction.DAYDREAM: 3.4,
IdleAction.DOODLE: 2.8,
IdleAction.DOUBLE_BLINK_TILT: 0.9,
}
IDLE_ACTION_WEIGHTS = {
IdleAction.HAPPY_SQUINT: 1.0,
IdleAction.CURIOUS_LOOK: 1.2,
IdleAction.CHEEKY_WINK: 0.7,
IdleAction.STRETCH: 0.8,
IdleAction.SETTLE: 0.7,
IdleAction.PERK_UP: 0.8,
IdleAction.DAYDREAM: 0.9,
IdleAction.DOODLE: 0.8,
IdleAction.DOUBLE_BLINK_TILT: 1.1,
}
GROOVE_WEIGHTS = {
GrooveStyle.HEAD_BOB: 1.2,
GrooveStyle.SIDE_SWAY: 1.1,
GrooveStyle.JELLY: 1.0,
GrooveStyle.SNARE_BLINK: 0.8,
GrooveStyle.LOOK_AROUND: 0.9,
GrooveStyle.ANTICIPATION_POP: 0.7,
GrooveStyle.GLOW_PULSE: 0.6,
}
def apply_groove(pose: Pose, style: GrooveStyle, t: float, m: MusicState, intensity: float) -> None:
beat = m.beat_pulse
phase = m.groove_phase
sway = math.sin(phase)
amp = intensity
pose.color = groove_prism_color(t)
pose.mouth = MouthGlyph.BIG_GRIN
pose.eye_w, pose.eye_h = 108.0, 112.0
if style is GrooveStyle.HEAD_BOB:
pose.gaze_y = (-13.0 * beat - abs(sway) * 4.0 - 6.0) * amp
pose.gaze_x = sway * 8.0 * amp
pose.scale_x = 1.0 + 0.05 * beat * amp
pose.scale_y = 1.0 - 0.04 * beat * amp
pose.tilt = sway * 4.0 * amp
if beat > 0.58:
pose.glyph = EyeGlyph.CRESCENT
elif style is GrooveStyle.SIDE_SWAY:
pose.gaze_y = -abs(sway) * 5.0 * amp - 4.0
pose.gaze_x = sway * 24.0 * amp
pose.tilt = sway * 14.0 * amp
pose.lean = sway * 10.0 * amp
pose.scale_x = 1.0 - 0.06 * abs(sway) * amp
pose.scale_y = 1.0 + 0.05 * abs(sway) * amp
elif style is GrooveStyle.JELLY:
pose.eye_h = 116.0
pose.scale_x = 1.0 + 0.13 * beat * amp
pose.scale_y = 1.0 - 0.11 * beat * amp
pose.gaze_y = -8.0 * beat * amp
elif style is GrooveStyle.SNARE_BLINK:
half = math.sin(phase * 0.5)
pose.gaze_x = sway * 10.0 * amp
pose.gaze_y = -abs(half) * 7.0 * amp
pose.glyph = EyeGlyph.CRESCENT if half > 0.6 else EyeGlyph.ROUND_RECT
elif style is GrooveStyle.LOOK_AROUND:
look = math.sin(phase * 0.5)
pose.gaze_x = look * 26.0 * amp
pose.tilt = look * 10.0 * amp
pose.gaze_y = -6.0 * beat * amp
elif style is GrooveStyle.ANTICIPATION_POP:
cycle = (phase / math.tau) % 1.0
if cycle < 0.75:
build = cycle / 0.75
pose.scale_y = 1.0 - 0.12 * build * amp
pose.scale_x = 1.0 + 0.10 * build * amp
pose.gaze_y = 6.0 * build * amp
else:
pop = math.sin((cycle - 0.75) / 0.25 * math.pi)
pose.scale_y = 1.0 + 0.16 * pop * amp
pose.scale_x = 1.0 - 0.12 * pop * amp
pose.gaze_y = -18.0 * pop * amp
elif style is GrooveStyle.GLOW_PULSE:
pose.scale_x = 1.0 + 0.04 * beat * amp
pose.scale_y = 1.0 + 0.04 * beat * amp
pose.gaze_y = -4.0 - 3.0 * m.energy
pose.color = groove_prism_color(t * 0.6)
def apply_idle_action(pose: Pose, action: IdleAction, t: float, direction: float) -> None:
if action is IdleAction.HAPPY_SQUINT:
pose.glyph = EyeGlyph.CRESCENT
pose.mouth = MouthGlyph.BIG_GRIN
pose.gaze_y = -abs(math.sin(t * 9.0)) * 12.0
elif action is IdleAction.CURIOUS_LOOK:
pose.gaze_x = direction * 34.0
pose.gaze_y = -6.0
pose.tilt = direction * 10.0
pose.eye_h = 118.0
elif action is IdleAction.CHEEKY_WINK:
pose.wink_right = True
pose.mouth = MouthGlyph.BIG_GRIN
pose.tilt = 6.0
pose.gaze_y = -8.0
elif action is IdleAction.STRETCH:
s = math.sin(t * 3.0)
pose.scale_y = 1.0 + 0.12 * s
pose.scale_x = 1.0 - 0.09 * s
pose.gaze_y = -10.0 * abs(s)
pose.mouth = MouthGlyph.SMILE
elif action is IdleAction.SETTLE:
pose.lid_top = 0.34
pose.eye_h = 92.0
pose.gaze_y = 6.0
pose.mouth = MouthGlyph.SMILE
elif action is IdleAction.PERK_UP:
pose.eye_w, pose.eye_h = 112.0, 122.0
pose.gaze_x = math.sin(t * 11.0) * 16.0
pose.gaze_y = -8.0
pose.mouth = MouthGlyph.SURPRISED
elif action is IdleAction.DAYDREAM:
pose.gaze_x = 26.0 + math.sin(t * 0.9) * 4.0
pose.gaze_y = -10.0 - math.sin(t * 0.6) * 3.0
pose.tilt = 7.0
pose.lid_top = 0.16
pose.mouth = MouthGlyph.SMILE
elif action is IdleAction.DOODLE:
ang = t * 3.4
pose.gaze_x = math.cos(ang) * 20.0
pose.gaze_y = math.sin(ang * 2.0) * 8.0
pose.mouth = MouthGlyph.SMILE
elif action is IdleAction.DOUBLE_BLINK_TILT:
pose.tilt = 5.0
pose.lid_top = max(pose.lid_top, 0.30)
pose.mouth = MouthGlyph.SMILE
@@ -1,625 +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.
"""
from enum import Enum
import math
import random
import time
from openpilot.cereal import log
from openpilot.common.constants import CV
from openpilot.common.swaglog import cloudlog
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.animations import (
GROOVE_WEIGHTS,
IDLE_ACTION_DURATION,
IDLE_ACTION_WEIGHTS,
GrooveStyle,
IdleAction,
apply_groove,
apply_idle_action,
)
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import MusicState
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.scene import (
EyeGlyph,
MotionScheduler,
MouthGlyph,
Pose,
clamp,
ease_in_quad,
ease_out_back,
smoothstep,
)
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.snapshot import DrivingSnapshot, SET_SPEED_NA
from openpilot.selfdrive.ui.ui_state import UIStatus
AlertStatus = log.SelfdriveState.AlertStatus
KM_TO_MILE = 0.621371
HARD_DECEL_THRESHOLD = -3.0
SHARP_ACCEL_THRESHOLD = 2.2
STANDSTILL_POUT_DELAY = 8.0
STANDSTILL_SLEEPY_DELAY = 35.0
STANDSTILL_DREAM_DELAY = 55.0
MIN_TURN_SPEED_MS = 6.5
MIN_LAT_ACCEL_MS2 = 1.6
FULL_LAT_ACCEL_MS2 = 3.6
LAT_JERK_WEIGHT = 0.5
LAT_JERK_LOW = 400.0
LAT_JERK_HIGH = 900.0
SQUISH_ATTACK_RATE = 20.0
SQUISH_RELEASE_RATE = 3.3
SET_SPEED_SHOW_DURATION = 3.0
ENGAGE_HAPPY_DURATION = 0.9
ENGAGE_SPEED_CONFIRM = 2.0
STARTLED_HOLD_DURATION = 1.5
BOOST_HOLD_DURATION = 1.2
LOVE_HOLD_DURATION = 1.6
MANUAL_SPEED_PEEK_DURATION = 4.0
BLINK_CLOSE_S = 0.070
BLINK_HOLD_S = 0.035
BLINK_OPEN_S = 0.130
BLINK_COVER_MAX = 0.92
BLINK_DOUBLE_PROB = 0.28
DEBUG_PARAM = "MiciRoboticDebug"
class RoboticMood(Enum):
CRITICAL = "critical"
DISTRACTED = "distracted"
USER_PROMPT = "user_prompt"
REVERSE = "reverse"
STARTLED_STARS = "startled_stars"
LANE_CHANGE = "lane_change"
BLIND_SPOT = "blind_spot"
BOOKMARK_LOVE = "bookmark_love"
HAPPY_ENGAGE = "happy_engage"
SPEED_DISPLAY = "speed_display"
BOOST_ACCEL = "boost_accel"
TURN_SIGNAL = "turn_signal"
SHARP_TURN = "sharp_turn"
CURVE_FOCUS = "curve_focus"
MUSIC_GROOVE = "music_groove"
POUT_STANDSTILL = "pout_standstill"
SLEEPY = "sleepy"
CRUISING_HAPPY = "cruising_happy"
IDLE_CURIOUS = "idle_curious"
ATTENTION_MOODS = (RoboticMood.CRITICAL, RoboticMood.DISTRACTED, RoboticMood.USER_PROMPT)
PALETTE = {
"engaged": (64, 240, 226),
"lat_only": (255, 212, 178),
"long_only": (92, 198, 255),
"disengaged": (218, 232, 248),
"override": (255, 196, 68),
"boost": (76, 178, 255),
"prompt": (255, 125, 20),
"critical": (255, 38, 48),
"love": (255, 112, 168),
"sleepy": (176, 162, 255),
"reverse": (255, 236, 180),
}
class RoboticMoodEngine:
"""Priority ladder over DrivingSnapshot producing a Pose the renderer animates."""
def __init__(self, rng: random.Random | None = None, params=None):
self._rng = rng or random.Random()
self._params = params
self._debug_frame = 0
self.mood: RoboticMood = RoboticMood.IDLE_CURIOUS
self.idle_action: IdleAction = IdleAction.NONE
self.showing_speed: bool = False
self.speed_reason: str = ""
self.cruising_smoothly: bool = False
self._prev_engaged: bool = False
self._prev_set_speed: float = SET_SPEED_NA
self._standstill_since: float | None = None
self._last_lane_dir: int = 0
self._boredom: float = 0.0
self._startled_until: float = 0.0
self._boost_until: float = 0.0
self._love_until: float = 0.0
self._love_wink: bool = False
self._happy_engage_until: float = 0.0
self._speed_display_until: float = 0.0
now = time.monotonic()
self._next_blink_at: float = now + self._rng.uniform(2.0, 5.0)
self._blink_start_at: float = now - 999.0
self._double_blink_at: float | None = None
self._next_glance_at: float = now + self._rng.uniform(2.5, 7.0)
self._idle_gaze_x: float = 0.0
self._idle_gaze_y: float = 0.0
self._idle_tilt: float = 0.0
self._next_idle_action_at: float = now + self._rng.uniform(2.5, 5.0)
self._idle_action_until: float = 0.0
self._idle_action_dir: float = 1.0
self._idle_scheduler = MotionScheduler(
[a for a in IdleAction if a is not IdleAction.NONE], self._rng, weights=IDLE_ACTION_WEIGHTS, cooldown=26.0,
)
self._groove_scheduler = MotionScheduler(list(GrooveStyle), self._rng, weights=GROOVE_WEIGHTS, cooldown=24.0)
self._groove_style: GrooveStyle = GrooveStyle.HEAD_BOB
self._groove_switch_at: float = 0.0
self._groove_intensity: float = 0.0
self._prev_update_t: float | None = None
self._prev_abs_lat: float = 0.0
self._squish_shown: float = 0.0
def trigger_love(self, now: float | None = None, wink: bool = False) -> None:
t = time.monotonic() if now is None else now
self._love_until = t + LOVE_HOLD_DURATION
self._love_wink = wink
self._boredom = max(0.0, self._boredom - 0.3)
def trigger_blink(self, now: float | None = None) -> None:
t = time.monotonic() if now is None else now
self._blink_start_at = t
self._double_blink_at = None
def trigger_speed_peek(self, now: float | None = None) -> None:
t = time.monotonic() if now is None else now
self._speed_display_until = max(self._speed_display_until, t + MANUAL_SPEED_PEEK_DURATION)
self.speed_reason = "peek"
def trigger_startled(self, now: float | None = None) -> None:
t = time.monotonic() if now is None else now
self._startled_until = max(self._startled_until, t + STARTLED_HOLD_DURATION)
def trigger_boost(self, now: float | None = None) -> None:
t = time.monotonic() if now is None else now
self._boost_until = max(self._boost_until, t + BOOST_HOLD_DURATION)
def _status_color(self, snap: DrivingSnapshot) -> tuple[int, int, int]:
if snap.status == UIStatus.OVERRIDE:
return PALETTE["override"]
if snap.status == UIStatus.ENGAGED:
return PALETTE["engaged"]
if snap.status == UIStatus.LAT_ONLY:
return PALETTE["lat_only"]
if snap.status == UIStatus.LONG_ONLY:
return PALETTE["long_only"]
return PALETTE["disengaged"]
def _blink_cover(self, t: float) -> float:
p = t - self._blink_start_at
close_end = BLINK_CLOSE_S
hold_end = close_end + BLINK_HOLD_S
total = hold_end + BLINK_OPEN_S
if p < 0.0 or p > total:
return 0.0
if p < close_end:
return ease_in_quad(p / close_end)
if p < hold_end:
return 1.0
return clamp(1.0 - ease_out_back((p - hold_end) / BLINK_OPEN_S, 1.1), 0.0, 1.0)
def _advance_personality(self, t: float, dt: float, busy: bool) -> None:
if t >= self._next_blink_at and t - self._blink_start_at > 0.4:
self._blink_start_at = t
self._next_blink_at = t + self._rng.uniform(2.4, 6.5)
if self._rng.random() < BLINK_DOUBLE_PROB:
self._double_blink_at = t + BLINK_CLOSE_S + BLINK_HOLD_S + BLINK_OPEN_S + 0.10
if self._double_blink_at is not None and t >= self._double_blink_at:
self._blink_start_at = self._double_blink_at
self._double_blink_at = None
if t >= self._next_glance_at:
self._idle_gaze_x = self._rng.uniform(-30.0, 30.0)
self._idle_gaze_y = self._rng.uniform(-9.0, 7.0)
self._idle_tilt = self._rng.uniform(-4.0, 4.0)
self._next_glance_at = t + self._rng.uniform(2.5, 7.0)
self._boredom = clamp(self._boredom + dt / 150.0 - (0.25 if busy else 0.0), 0.0, 1.0)
if self.idle_action is not IdleAction.NONE and t >= self._idle_action_until:
self.idle_action = IdleAction.NONE
self._next_idle_action_at = t + self._rng.uniform(2.5, 6.5)
if self.idle_action is IdleAction.NONE and t >= self._next_idle_action_at and not busy:
action = self._idle_scheduler.pick(t)
if self._boredom > 0.65 and action not in (IdleAction.SETTLE, IdleAction.DAYDREAM) and self._rng.random() < 0.5:
action = IdleAction.DAYDREAM
self.idle_action = action
self._idle_action_dir = 1.0 if self._rng.random() < 0.5 else -1.0
self._idle_action_until = t + IDLE_ACTION_DURATION[action]
def update(self, snap: DrivingSnapshot, now: float | None = None) -> Pose:
t = time.monotonic() if now is None else now
dt = 0.0 if self._prev_update_t is None else clamp(t - self._prev_update_t, 0.0, 0.5)
if self._prev_update_t is None:
self._next_blink_at = t + self._rng.uniform(2.0, 5.0)
self._next_glance_at = t + self._rng.uniform(2.5, 7.0)
self._next_idle_action_at = t + self._rng.uniform(2.5, 5.0)
self._prev_update_t = t
if snap.standstill or not snap.started:
if self._standstill_since is None:
self._standstill_since = t
else:
self._standstill_since = None
standstill_dur = (t - self._standstill_since) if self._standstill_since is not None else 0.0
if snap.engaged and not self._prev_engaged:
self._happy_engage_until = t + ENGAGE_HAPPY_DURATION
self._speed_display_until = max(self._speed_display_until, t + ENGAGE_HAPPY_DURATION + ENGAGE_SPEED_CONFIRM)
self.speed_reason = "engage"
self._prev_engaged = snap.engaged
cruise_set = 0 < snap.set_speed_kph < SET_SPEED_NA
if cruise_set and snap.set_speed_kph != self._prev_set_speed and self._prev_set_speed != SET_SPEED_NA:
self._speed_display_until = max(self._speed_display_until, t + SET_SPEED_SHOW_DURATION)
self.speed_reason = "set_speed"
self._prev_set_speed = snap.set_speed_kph
if snap.a_ego < HARD_DECEL_THRESHOLD or snap.lane_change_blocked:
self._startled_until = max(self._startled_until, t + STARTLED_HOLD_DURATION)
elif snap.a_ego > SHARP_ACCEL_THRESHOLD and not snap.standstill:
self._boost_until = max(self._boost_until, t + BOOST_HOLD_DURATION)
if snap.pre_lane_change_left:
self._last_lane_dir = -1
elif snap.pre_lane_change_right:
self._last_lane_dir = 1
elif not snap.lane_change:
self._last_lane_dir = 0
blinker_side = -1 if snap.left_blinker else (1 if snap.right_blinker else 0)
bsm_side = 0
if snap.left_blindspot and (snap.left_blinker or snap.pre_lane_change_left):
bsm_side = -1
elif snap.right_blindspot and (snap.right_blinker or snap.pre_lane_change_right):
bsm_side = 1
elif snap.left_blindspot and not snap.standstill:
bsm_side = -1
elif snap.right_blindspot and not snap.standstill:
bsm_side = 1
self.cruising_smoothly = snap.engaged and not snap.standstill and abs(snap.a_ego) < 0.8
alert = snap.alert
alert_status = alert.status if alert is not None else -1
alert_type = alert.alert_type if alert is not None else ""
is_dm_alert = snap.dm_alert_level >= 1 or "Distracted" in alert_type or "Unresponsive" in alert_type
if not snap.blind_spot_enabled:
bsm_side = 0
squish_force = self._update_squish(snap, t, dt)
if alert is not None and alert_status == AlertStatus.critical:
self.mood = RoboticMood.CRITICAL
elif is_dm_alert:
self.mood = RoboticMood.DISTRACTED
elif alert is not None and alert_status == AlertStatus.userPrompt:
self.mood = RoboticMood.USER_PROMPT
elif snap.reverse:
self.mood = RoboticMood.REVERSE
elif t < self._startled_until:
self.mood = RoboticMood.STARTLED_STARS
elif snap.pre_lane_change_left or snap.pre_lane_change_right or snap.lane_change:
self.mood = RoboticMood.LANE_CHANGE
elif bsm_side != 0 and blinker_side != 0:
self.mood = RoboticMood.BLIND_SPOT
elif blinker_side != 0:
self.mood = RoboticMood.TURN_SIGNAL
elif t < self._love_until:
self.mood = RoboticMood.BOOKMARK_LOVE
elif t < self._happy_engage_until:
self.mood = RoboticMood.HAPPY_ENGAGE
elif t < self._speed_display_until and snap.started:
self.mood = RoboticMood.SPEED_DISPLAY
elif t < self._boost_until:
self.mood = RoboticMood.BOOST_ACCEL
elif abs(squish_force) >= 0.35:
self.mood = RoboticMood.SHARP_TURN
elif abs(squish_force) >= 0.12:
self.mood = RoboticMood.CURVE_FOCUS
elif snap.started and snap.music is not None and snap.music.is_music and alert is None:
self.mood = RoboticMood.MUSIC_GROOVE
elif not snap.started or standstill_dur >= STANDSTILL_SLEEPY_DELAY:
self.mood = RoboticMood.SLEEPY
elif standstill_dur >= STANDSTILL_POUT_DELAY:
self.mood = RoboticMood.POUT_STANDSTILL
elif snap.engaged:
self.mood = RoboticMood.CRUISING_HAPPY
else:
self.mood = RoboticMood.IDLE_CURIOUS
self.showing_speed = self.mood == RoboticMood.SPEED_DISPLAY and alert is None
busy = self.mood in (RoboticMood.CRITICAL, RoboticMood.MUSIC_GROOVE, RoboticMood.LANE_CHANGE,
RoboticMood.BLIND_SPOT, RoboticMood.REVERSE)
self._advance_personality(t, dt, busy)
return self._build_pose(snap, t, squish_force, blinker_side, bsm_side, standstill_dur)
def _update_squish(self, snap: DrivingSnapshot, t: float, dt: float) -> float:
effective_yaw = snap.yaw_rate
if abs(effective_yaw) < 1e-4 and abs(snap.curvature) > 1e-5:
effective_yaw = snap.v_ego * snap.curvature
target_squish = 0.0
abs_lat = 0.0
jerk = 0.0
if not snap.standstill and snap.v_ego >= MIN_TURN_SPEED_MS:
lat_accel = -snap.v_ego * effective_yaw
abs_lat = abs(lat_accel)
if abs_lat >= MIN_LAT_ACCEL_MS2:
base = smoothstep(MIN_LAT_ACCEL_MS2, FULL_LAT_ACCEL_MS2, abs_lat)
if dt > 1e-4:
jerk = abs(abs_lat - self._prev_abs_lat) / dt
jerk_term = LAT_JERK_WEIGHT * smoothstep(LAT_JERK_LOW, LAT_JERK_HIGH, jerk)
mag = min(1.0, base + jerk_term)
target_squish = mag if lat_accel > 0 else -mag
self._prev_abs_lat = abs_lat
delta = target_squish - self._squish_shown
if dt <= 0.0:
step = abs(delta)
elif abs(target_squish) < abs(self._squish_shown):
step = SQUISH_RELEASE_RATE * dt
else:
step = SQUISH_ATTACK_RATE * dt
self._squish_shown += max(-step, min(step, delta))
self._log_squish_debug(snap, abs_lat, jerk, effective_yaw, self._squish_shown)
return self._squish_shown
def _log_squish_debug(self, snap: DrivingSnapshot, abs_lat: float, jerk: float, yaw_rate: float, squish_force: float) -> None:
if self._params is None:
return
self._debug_frame += 1
if self._debug_frame % 60 != 0:
return
try:
if not self._params.get_bool(DEBUG_PARAM):
return
cloudlog.info(f"MICI squish lat={abs_lat:.2f} jerk={jerk:.0f} yaw={yaw_rate:.3f} squish={squish_force:.2f} v={snap.v_ego:.1f}")
except Exception:
self._params = None
def _build_pose(self, snap: DrivingSnapshot, t: float, squish_force: float,
blinker_side: int, bsm_side: int, standstill_dur: float) -> Pose:
base_color = self._status_color(snap)
blink = self._blink_cover(t)
energy = 1.0 + min(0.55, snap.v_ego / 35.0)
bus_phase = t * 2.2 * energy
breath = math.sin(bus_phase) * 0.72 + math.sin(bus_phase * 0.5 + 0.9) * 0.28
breathe_y = breath * 6.5
breathe_scale = 1.0 + 0.032 * breath
micro_drift_x = math.sin(bus_phase * 0.33) * 5.0
steer_gaze = clamp(-snap.steering_angle_deg * 0.78, -40.0, 40.0)
pose = Pose(
color=base_color,
gaze_y=breathe_y * 0.35,
scale_x=breathe_scale,
scale_y=2.0 - breathe_scale,
squish=squish_force,
blinker_side=blinker_side,
blind_spot_side=bsm_side,
)
if bsm_side != 0:
pose.edge_glow = 1.0
if blinker_side != 0:
pose.arrow = 1.0
if self.mood == RoboticMood.CRITICAL:
pose.glyph = EyeGlyph.LASER_ALERT
pose.color = PALETTE["critical"]
pose.eye_w, pose.eye_h = 114.0, 84.0
pose.roundness = 0.42
pose.lid_top = 0.28
pose.slant = 18.0
pose.pulse = 5.5
pose.gaze_y = math.sin(t * 28.0) * 3.5
pose.mouth = MouthGlyph.FROWN
elif self.mood == RoboticMood.DISTRACTED:
pose.color = PALETTE["prompt"]
pose.eye_w, pose.eye_h = 106.0, 120.0
pose.roundness = 0.52
pose.lid_top = 0.30
pose.slant = 12.0
pose.gaze_x = micro_drift_x * 0.3
pose.gaze_y = -2.0
pose.tilt = math.sin(t * 1.7) * 3.0
pose.mouth = MouthGlyph.FROWN
pose.pulse = 2.5
elif self.mood == RoboticMood.USER_PROMPT:
pose.color = PALETTE["prompt"]
pose.eye_w, pose.eye_h = 108.0, 118.0
pose.lid_top = 0.08
pose.slant = -7.0
pose.gaze_x = -26.0 + micro_drift_x * 0.3
pose.gaze_y = -22.0
pose.tilt = -6.0
pose.mouth = MouthGlyph.SURPRISED
pose.pulse = 1.8
elif self.mood == RoboticMood.REVERSE:
pose.color = PALETTE["reverse"]
pose.flip = 1.0
pose.glyph = EyeGlyph.CRESCENT
pose.eye_w, pose.eye_h = 112.0, 100.0
pose.lean = math.sin(t * 2.6) * 4.0
pose.tilt = math.sin(t * 1.9) * 5.0
pose.gaze_y = -abs(math.sin(t * 3.0)) * 7.0
pose.mouth = MouthGlyph.BIG_GRIN
pose.hearts = 0.8
elif self.mood == RoboticMood.STARTLED_STARS:
pose.glyph = EyeGlyph.STAR
pose.color = PALETTE["override"]
pose.eye_w, pose.eye_h = 114.0, 114.0
pose.mouth = MouthGlyph.SURPRISED
pose.gaze_y = math.sin(t * 26.0) * 6.0
pose.scale_x = 1.0 + 0.08 * math.sin(t * 22.0)
pose.scale_y = 1.0 - 0.08 * math.sin(t * 22.0)
elif self.mood == RoboticMood.LANE_CHANGE:
direction = -1 if snap.pre_lane_change_left else (1 if snap.pre_lane_change_right else self._last_lane_dir or 1)
pose.glyph = EyeGlyph.ARROW_LEFT if direction < 0 else EyeGlyph.ARROW_RIGHT
pose.gaze_x = direction * 32.0 + math.sin(t * 6.5) * 5.0
pose.eye_h = 106.0
pose.lid_top = 0.10
pose.tilt = direction * 7.0
pose.lean = direction * 8.0
pose.mouth = MouthGlyph.SMILE
elif self.mood == RoboticMood.BLIND_SPOT:
pose.color = PALETTE["override"]
pose.gaze_x = bsm_side * 38.0
pose.eye_h = 102.0
pose.lid_top = 0.22
pose.slant = 9.0
pose.tilt = bsm_side * 6.0
pose.pulse = 3.2
elif self.mood == RoboticMood.BOOKMARK_LOVE:
pose.glyph = EyeGlyph.HEART
pose.color = PALETTE["love"]
pose.eye_w, pose.eye_h = 114.0, 114.0
pose.wink_right = self._love_wink
pose.mouth = MouthGlyph.BIG_GRIN
pose.gaze_y = -abs(math.sin(t * 10.5)) * 15.0
pose.hearts = 1.0
elif self.mood == RoboticMood.HAPPY_ENGAGE:
pose.glyph = EyeGlyph.CRESCENT
pose.color = PALETTE["engaged"]
pose.eye_w, pose.eye_h = 116.0, 100.0
pose.mouth = MouthGlyph.BIG_GRIN
pose.gaze_y = -abs(math.sin(t * 9.5)) * 16.0
elif self.mood == RoboticMood.SPEED_DISPLAY:
pose.eye_w, pose.eye_h = 104.0, 112.0
pose.mouth = MouthGlyph.SMILE
pose.gaze_x = steer_gaze * 0.3
elif self.mood == RoboticMood.BOOST_ACCEL:
pose.glyph = EyeGlyph.SPARKLE_BOOST
pose.color = PALETTE["boost"]
pose.eye_w, pose.eye_h = 116.0, 120.0
pose.gaze_y = -7.0
pose.mouth = MouthGlyph.BIG_GRIN
pose.gaze_y -= math.sin(t * 18.0) * 5.0
pose.speed_lines = 1.0
elif self.mood == RoboticMood.TURN_SIGNAL:
beat = 0.5 + 0.5 * math.sin(t * 8.4)
pose.gaze_x = blinker_side * (8.0 + 5.0 * beat)
pose.tilt = blinker_side * 7.0
pose.eye_w, pose.eye_h = 106.0, 108.0
pose.lid_top = 0.08
pose.mouth = MouthGlyph.SMILE
elif self.mood == RoboticMood.POUT_STANDSTILL:
pose.eye_w, pose.eye_h = 98.0, 84.0
pose.roundness = 0.34
pose.lid_top = 0.26 + 0.05 * math.sin(t * 1.8)
pose.gaze_x = self._idle_gaze_x * 0.75 + micro_drift_x
pose.gaze_y = 6.0
pose.tilt = self._idle_tilt * 0.7
pose.mouth = MouthGlyph.FROWN
elif self.mood == RoboticMood.SLEEPY:
pose.glyph = EyeGlyph.CRESCENT
pose.color = PALETTE["sleepy"]
pose.eye_w, pose.eye_h = 116.0, 96.0
pose.roundness = 0.55
pose.gaze_y = 8.0
pose.gaze_x = math.sin(t * 0.7) * 8.0
pose.nightcap = 1.0
pose.zzz = 1.0 if standstill_dur >= STANDSTILL_DREAM_DELAY else 0.0
elif self.mood in (RoboticMood.SHARP_TURN, RoboticMood.CURVE_FOCUS):
intensity = abs(squish_force)
push_dir = 1.0 if squish_force >= 0 else -1.0
pose.squish = push_dir * intensity
pose.eye_w, pose.eye_h = 108.0, 104.0
if self.mood == RoboticMood.CURVE_FOCUS:
pose.eye_h = 106.0
pose.lid_top = 0.08
pose.gaze_x = push_dir * 8.0
pose.tilt = push_dir * (5.0 + 6.0 * intensity)
pose.mouth = MouthGlyph.SMILE
else:
pose.lid_top = 0.10 + 0.14 * intensity
pose.slant = 5.0 + 7.0 * intensity
pose.gaze_x = push_dir * 12.0
pose.tilt = push_dir * (8.0 + 8.0 * intensity)
pose.mouth = MouthGlyph.SURPRISED if intensity >= 0.55 else MouthGlyph.SMILE
elif self.mood == RoboticMood.MUSIC_GROOVE:
m = snap.music or MusicState()
self._groove_intensity = 0.45 + 0.55 * smoothstep(0.30, 0.80, m.confidence)
if t >= self._groove_switch_at:
self._groove_style = self._groove_scheduler.pick(t)
self._groove_switch_at = t + max(8.0, 32.0 * 60.0 / max(60.0, m.bpm))
apply_groove(pose, self._groove_style, t, m, self._groove_intensity)
elif self.mood == RoboticMood.CRUISING_HAPPY:
pose.eye_w, pose.eye_h = 106.0, 114.0
pose.mouth = MouthGlyph.SMILE
pose.gaze_x = steer_gaze * 0.35 + self._idle_gaze_x * 0.65 + micro_drift_x
pose.gaze_y = self._idle_gaze_y * 0.65
pose.tilt = self._idle_tilt * 0.75 + math.sin(t * 1.6) * 3.0
apply_idle_action(pose, self.idle_action, t, self._idle_action_dir)
else:
pose.eye_w, pose.eye_h = 104.0, 110.0
pose.mouth = MouthGlyph.SMILE
pose.gaze_x = self._idle_gaze_x + micro_drift_x
pose.gaze_y = self._idle_gaze_y
pose.tilt = self._idle_tilt + math.sin(t * 1.4) * 3.0
apply_idle_action(pose, self.idle_action, t, self._idle_action_dir)
if snap.alert is not None and snap.alert.status != AlertStatus.critical and self.mood not in ATTENTION_MOODS:
pose.gaze_x = -24.0
pose.gaze_y = -22.0
pose.tilt = -5.0
music = snap.music
if music is not None and music.is_music and snap.started and snap.alert is None \
and self.mood not in (*ATTENTION_MOODS, RoboticMood.SLEEPY):
pose.headphones = 1.0
pose.notes = 1.0
pose.beat = music.beat_pulse
pose.gaze_y += clamp(snap.pitch_rate * 9.0, -7.0, 7.0)
pose.tilt += clamp(snap.pitch_rad * 60.0, -6.0, 6.0)
if pose.glyph is EyeGlyph.ROUND_RECT and not pose.wink_right and blink > 0.0:
pose.lid_top = max(pose.lid_top, 0.50 * blink)
pose.lid_bottom = max(pose.lid_bottom, 0.42 * blink)
pose.lid_top = clamp(pose.lid_top, 0.0, BLINK_COVER_MAX)
pose.scale_x = clamp(pose.scale_x, 0.74, 1.36)
pose.scale_y = clamp(pose.scale_y, 0.74, 1.36)
return pose
def display_speed_and_set_speed(snap: DrivingSnapshot) -> tuple[int, int | None]:
"""Convert current speed and cruise set speed to display units (mph or km/h)."""
speed_conv = CV.MS_TO_KPH if snap.is_metric else CV.MS_TO_MPH
cur_speed = round(max(0.0, snap.v_ego * speed_conv))
if 0 < snap.set_speed_kph < SET_SPEED_NA:
set_val = snap.set_speed_kph if snap.is_metric else snap.set_speed_kph * KM_TO_MILE
return cur_speed, round(set_val)
return cur_speed, None
@@ -1,296 +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 math
import raylib_nb as rl
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.props import (
draw_capsule,
draw_edge_glow,
draw_floating_hearts,
draw_floating_notes,
draw_floating_zzz,
draw_headphones,
draw_nightcap,
draw_sparkle,
draw_speed_lines,
fill_polygon,
heart_points,
)
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.scene import (
EyeGlyph,
MouthGlyph,
Pose,
SpringBus,
clamp,
)
def _rotated(x: float, y: float, ca: float, sa: float) -> tuple[float, float]:
return x * ca - y * sa, x * sa + y * ca
class ProceduralFaceRenderer:
"""Spring-driven, prop-wearing face renderer for the 536x240 MICI OLED."""
def __init__(self):
self._bus = SpringBus()
self._first_frame = True
self._glyph: EyeGlyph | None = None
self._pop_start = -1.0
def render(self, rect: rl.Rectangle, target: Pose, alpha: float = 1.0, y_shift: float = 0.0) -> None:
if alpha < 0.01:
return
now = rl.get_time()
if self._first_frame:
self._bus.snap(target)
self._first_frame = False
dt = 0.0
else:
dt = max(0.0, min(0.1, now - self._last_t))
self._last_t = now
p = self._bus.step(target, dt)
t = now
# A short squash-pop masks the instant eye-glyph swap when the mood changes.
if self._glyph is not None and target.glyph != self._glyph:
self._pop_start = now
self._glyph = target.glyph
pop = 1.0
pop_t = now - self._pop_start
if 0.0 <= pop_t < 0.22:
pop = 1.0 + 0.09 * math.sin(math.pi * pop_t / 0.22)
pulse = 1.0
if p.pulse > 0.0:
pulse = 0.80 + 0.20 * (0.5 + 0.5 * math.sin(t * p.pulse * math.tau))
eff = clamp(alpha, 0.0, 1.0)
# Pulse in brightness, never in alpha: translucent overlapping strokes would seam.
color = (int(p.color[0] * pulse * eff), int(p.color[1] * pulse * eff), int(p.color[2] * pulse * eff))
core = rl.Color(color[0], color[1], color[2], int(255 * eff))
angle = math.pi * clamp(p.flip, 0.0, 1.0)
ca, sa = math.cos(angle), math.sin(angle)
mirror = 1.0 if ca >= 0.0 else -1.0
vscale = max(0.10, abs(ca))
squish = clamp(p.squish, -1.0, 1.0)
squish_abs = abs(squish)
if p.edge_glow > 0.02 and p.blind_spot_side != 0:
draw_edge_glow(rect, p.blind_spot_side, rl.Color(255, 160, 30, int(145 * p.edge_glow * alpha)), p.edge_glow * alpha)
if p.speed_lines > 0.02:
draw_speed_lines(rect, core, p.speed_lines * eff, t)
cx = rect.x + rect.width / 2.0 + p.lean + p.gaze_x * 0.18 + squish * 62.0
cy = rect.y + rect.height / 2.0 - 8.0 + p.gaze_y * 0.12 + y_shift
w = max(20.0, p.eye_w * p.scale_x) * pop
h = max(16.0, p.eye_h * p.scale_y * vscale) * pop
spacing = p.spacing * (1.0 - 0.22 * squish_abs)
eye_top = cy - h * 0.5 * mirror
# Crescent eyes sit low in their box, so the cap rides just above the visible arcs.
cap_top = cy - h * 0.12 if p.glyph == EyeGlyph.CRESCENT else eye_top
draw_nightcap(cx, cap_top, w * 1.02, p.nightcap, color, t, mirror)
draw_headphones(cx, cy, w, h, spacing, p.headphones, color, t, mirror, p.beat, layer="band")
eyes = []
for side, is_right in ((-1.0, False), (1.0, True)):
dx = side * spacing / 2.0
dy = side * p.tilt * vscale
ex, ey = _rotated(dx, dy, ca, sa)
eyes.append((cx + ex, cy + ey, is_right))
left_w = w * (1.0 - 0.36 * max(0.0, -squish)) * (1.0 - 0.14 * max(0.0, squish))
left_h = h * (1.0 + 0.16 * max(0.0, -squish)) * (1.0 - 0.05 * max(0.0, squish))
right_w = w * (1.0 - 0.36 * max(0.0, squish)) * (1.0 - 0.14 * max(0.0, -squish))
right_h = h * (1.0 + 0.16 * max(0.0, squish)) * (1.0 - 0.05 * max(0.0, -squish))
lid_a = p.lid_top if mirror > 0.0 else p.lid_bottom
lid_b = p.lid_bottom if mirror > 0.0 else p.lid_top
for ecx, ecy, is_right in eyes:
ew, eh = (right_w, right_h) if is_right else (left_w, left_h)
glyph = p.glyph
arrow = 1.0 if glyph in (EyeGlyph.ARROW_LEFT, EyeGlyph.ARROW_RIGHT) else 0.0
if p.arrow > 0.01 and p.blinker_side != 0:
glyph = EyeGlyph.ARROW_LEFT if p.blinker_side < 0 else EyeGlyph.ARROW_RIGHT
arrow = p.arrow
if is_right and p.wink_right:
glyph = EyeGlyph.CRESCENT
lid_slant = p.slant * (1.0 if not is_right else -1.0)
self._draw_eye(ecx, ecy, ew, eh, p.roundness, lid_a, lid_b, lid_slant, glyph, core, eff,
p.gaze_x, p.gaze_y, t, p.bloom, angle, arrow)
draw_headphones(cx, cy, w, h, spacing, p.headphones, color, t, mirror, p.beat, layer="cups")
if p.mouth != MouthGlyph.NONE:
self._draw_mouth(cx, cy + h * 0.74 * mirror, p.mouth, core, mirror)
if p.flip > 0.55:
for i in range(3):
phase = t * 1.6 + i * 2.1
sx = cx + math.cos(phase) * w * 1.05
sy = cy + math.sin(phase * 0.8) * h * 0.85
draw_sparkle(sx, sy, 7.0 + 2.0 * math.sin(t * 6.0 + i), eff * min(1.0, (p.flip - 0.55) * 3.0))
draw_floating_hearts(cx, cy - h * 0.62 * mirror, p.hearts, color, t)
draw_floating_zzz(cx + w * 0.92, cy - h * 0.30 * mirror, p.zzz, color, t)
draw_floating_notes(rect, p.notes, color, t, p.beat)
def _draw_eye(self, cx: float, cy: float, w: float, h: float, roundness: float,
lid_top: float, lid_bottom: float, lid_slant: float, glyph: EyeGlyph,
color: rl.Color, alpha: float, gaze_x: float, gaze_y: float, t: float,
bloom: float, view_angle: float, arrow: float) -> None:
if glyph == EyeGlyph.STAR:
self._draw_star_eye(cx, cy, min(w, h) * 0.48, color, alpha, t)
return
if glyph == EyeGlyph.HEART:
self._draw_heart_eye(cx, cy, min(w, h) * 0.48, color, alpha)
return
if glyph == EyeGlyph.CRESCENT:
self._draw_crescent_eye(cx, cy, w, h, color, alpha, view_angle)
return
if glyph in (EyeGlyph.ARROW_LEFT, EyeGlyph.ARROW_RIGHT):
self._draw_arrow_eye(cx, cy, w, h, -1.0 if glyph == EyeGlyph.ARROW_LEFT else 1.0, color, alpha, t, arrow)
if arrow > 0.92:
return
body_alpha = alpha * (1.0 - arrow)
visible = max(0.10, 1.0 - lid_top - lid_bottom) * (1.0 - arrow)
bloom_r = max(w, h) * 0.80 * (0.62 + 0.38 * max(visible, 0.1)) * bloom
rl.draw_circle_gradient(rl.Vector2(cx, cy), bloom_r,
rl.Color(color.r, color.g, color.b, int(92 * visible)),
rl.Color(color.r, color.g, color.b, 0))
core_rec = rl.Rectangle(cx - w / 2.0, cy - h / 2.0, w, h)
body = rl.Color(color.r, color.g, color.b, int(255 * body_alpha))
rl.draw_rectangle_rounded(core_rec, clamp(roundness, 0.15, 0.85), 24, body)
ca, sa = math.cos(view_angle), math.sin(view_angle)
glint_fade = (0.30 + 0.70 * visible) * (1.0 - arrow) * alpha
gx = gaze_x * 0.16 + math.sin(t * 3.0) * 1.6
gy = gaze_y * 0.14 + math.cos(t * 2.4) * 1.2 + lid_top * h * 0.30
ox, oy = _rotated(-w * 0.16 + gx, -h * 0.30 + gy, ca, sa)
gx_main = cx + ox
gy_main = cy + oy
rl.begin_scissor_mode(int(cx - w * 0.5) + 1, int(cy - h * 0.5) + 1, int(w) - 2, int(h) - 2)
rl.draw_circle_gradient(rl.Vector2(gx_main + w * 0.06, gy_main + h * 0.04), max(w, h) * 0.21,
rl.Color(255, 255, 255, int(66 * glint_fade)),
rl.Color(255, 255, 255, 0))
rl.end_scissor_mode()
rl.draw_rectangle_rounded(
rl.Rectangle(gx_main - w * 0.15, gy_main - h * 0.09, w * 0.30, h * 0.18),
0.95, 16, rl.Color(255, 255, 255, int(244 * glint_fade)),
)
sdx, sdy = _rotated(w * 0.19 + gx * 0.6, h * 0.21 + gy * 0.6, ca, sa)
rl.draw_circle(int(cx + sdx), int(cy + sdy), max(3.5, min(w, h) * 0.058),
rl.Color(255, 255, 255, int(185 * glint_fade)))
if glyph == EyeGlyph.SPARKLE_BOOST:
draw_sparkle(cx, cy, min(w, h) * 0.22 * (0.85 + 0.25 * math.sin(t * 14.0)), alpha)
if glyph == EyeGlyph.LASER_ALERT:
rl.draw_rectangle_rounded(
rl.Rectangle(cx - w * 0.36, cy - 5.0, w * 0.72, 10.0), 0.85, 12,
rl.Color(255, 235, 235, int(215 * alpha)),
)
eye_top = cy - h / 2.0
if lid_top > 0.02 or abs(lid_slant) > 0.5:
self._draw_lid(cx, eye_top, w, h, lid_top, lid_slant, from_top=True)
if lid_bottom > 0.02:
self._draw_lid(cx, eye_top, w, h, lid_bottom, -lid_slant, from_top=False)
def _draw_lid(self, cx: float, eye_top: float, w: float, h: float, cover: float,
slant_deg: float, from_top: bool) -> None:
"""Slanted brow cut out of a fat round-capped capsule, so the lid edge is angled but never square."""
covered = clamp(cover, 0.0, 0.92) * h
thickness = covered + 44.0
length = w + 12.0
ang = math.radians(slant_deg if from_top else -slant_deg)
dx, dy = math.cos(ang), math.sin(ang)
px, py = -dy, dx
edge_y = eye_top + covered if from_top else eye_top + h - covered
sign = 1.0 if from_top else -1.0
mx = cx - px * thickness * 0.5 * sign
my = edge_y - py * thickness * 0.5 * sign
draw_capsule(rl.Vector2(mx - dx * length * 0.5, my - dy * length * 0.5),
rl.Vector2(mx + dx * length * 0.5, my + dy * length * 0.5), thickness, rl.BLACK)
def _draw_arrow_eye(self, cx: float, cy: float, w: float, h: float, direction: float,
color: rl.Color, alpha: float, t: float, amount: float) -> None:
"""Both eyes become rounded arrows that point where the car is about to go."""
pulse = 1.0 + 0.09 * math.sin(t * 7.0)
length = w * 0.80 * (0.58 + 0.42 * amount) * pulse
thick = max(7.0, h * 0.28) * (0.62 + 0.38 * amount)
tip_x = cx + direction * length * 0.5
tail_x = cx - direction * length * 0.5
head = length * 0.32
col = rl.Color(color.r, color.g, color.b, int(255 * alpha * amount))
glow = rl.Color(color.r, color.g, color.b, int(64 * alpha * amount))
rl.draw_circle_gradient(rl.Vector2(tip_x, cy), thick * 1.7, glow, rl.Color(color.r, color.g, color.b, 0))
draw_capsule(rl.Vector2(tail_x, cy), rl.Vector2(tip_x, cy), thick, col)
draw_capsule(rl.Vector2(tip_x, cy), rl.Vector2(tip_x - direction * head, cy - head * 0.78), thick * 0.92, col)
draw_capsule(rl.Vector2(tip_x, cy), rl.Vector2(tip_x - direction * head, cy + head * 0.78), thick * 0.92, col)
def _draw_star_eye(self, cx: float, cy: float, outer_r: float, color: rl.Color, alpha: float, t: float) -> None:
spin = math.sin(t * 7.0) * 0.10
pts: list[rl.Vector2] = []
for i in range(64):
a = (i / 64.0) * math.tau + spin
r = outer_r * (0.34 + 0.66 * abs(math.cos(2.0 * a)) ** 1.35)
pts.append(rl.Vector2(cx + math.cos(a) * r, cy + math.sin(a) * r))
rl.draw_circle_gradient(rl.Vector2(cx, cy), outer_r * 1.25,
rl.Color(color.r, color.g, color.b, int(90 * alpha)),
rl.Color(color.r, color.g, color.b, 0))
fill_polygon(pts, color)
def _draw_heart_eye(self, cx: float, cy: float, radius: float, color: rl.Color, alpha: float) -> None:
rl.draw_circle_gradient(rl.Vector2(cx, cy), radius * 1.4,
rl.Color(color.r, color.g, color.b, int(92 * alpha)),
rl.Color(color.r, color.g, color.b, 0))
fill_polygon(heart_points(cx, cy, radius), color)
def _draw_crescent_eye(self, cx: float, cy: float, w: float, h: float, color: rl.Color,
alpha: float, view_angle: float) -> None:
radius = min(w, h) * 0.36
mirror = 1.0 if math.cos(view_angle) >= 0.0 else -1.0
arc_cy = cy + radius * 0.94 * mirror
start, end = (200.0, 340.0) if mirror > 0.0 else (20.0, 160.0)
rl.draw_ring(rl.Vector2(cx, arc_cy), radius - 15.0, radius + 5.0, start, end, 30,
rl.Color(color.r, color.g, color.b, int(55 * alpha)))
self._capped_ring(rl.Vector2(cx, arc_cy), radius - 10.0, radius, start + 2.0, end - 2.0, color)
def _capped_ring(self, center: rl.Vector2, r0: float, r1: float, start: float, end: float,
color: rl.Color) -> None:
rl.draw_ring(center, r0, r1, start, end, 30, color)
mid = (r0 + r1) * 0.5
cap = (r1 - r0) * 0.5
for deg in (start, end):
a = math.radians(deg)
rl.draw_circle(int(center.x + mid * math.cos(a)), int(center.y + mid * math.sin(a)), cap, color)
def _stroke_arc(self, cx: float, cy: float, radius: float, start: float, end: float,
thickness: float, color: rl.Color, mirror: float) -> None:
s, e = (start, end) if mirror > 0 else (-end, -start)
self._capped_ring(rl.Vector2(cx, cy), radius - thickness * 0.5, radius + thickness * 0.5, s, e, color)
def _draw_mouth(self, cx: float, cy: float, mouth: MouthGlyph, color: rl.Color, mirror: float) -> None:
if mouth == MouthGlyph.SMILE:
self._stroke_arc(cx, cy - 10.0 * mirror, 20.0, 25.0, 155.0, 6.0, color, mirror)
elif mouth == MouthGlyph.BIG_GRIN:
self._stroke_arc(cx, cy - 12.0 * mirror, 23.0, 14.0, 166.0, 10.5, color, mirror)
elif mouth == MouthGlyph.FROWN:
self._stroke_arc(cx, cy + 16.0 * mirror, 20.0, 205.0, 335.0, 6.0, color, mirror)
elif mouth == MouthGlyph.SURPRISED:
rl.draw_ring(rl.Vector2(cx, cy + 2.0 * mirror), 9.0, 15.0, 0.0, 360.0, 26, color)
@@ -1,8 +0,0 @@
# YAMNet
`yamnet.onnx` is YAMNet (AudioSet, 521 classes) exported to ONNX by
[rostrumstudios/yamnet](https://huggingface.co/rostrumstudios/yamnet) and licensed under Apache-2.0
(see `YAMNET_LICENSE.txt`). Input is a 0.975 s, 16 kHz mono float waveform; output 0 is
`[frames, 521]` class probabilities.
sha256: `1510041dce24a2e9e84ec546807ac408ae496da6d1ed41bc3ccba649623f8e19`
@@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:1510041dce24a2e9e84ec546807ac408ae496da6d1ed41bc3ccba649623f8e19
size 16093603
@@ -1,303 +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.
"""
from collections import deque
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
import math
import os
import threading
import time
import numpy as np
from openpilot.common.swaglog import cloudlog
DEFAULT_SAMPLE_RATE = 16000
FRAME_RATE = 20.0
FFT_SIZE = 1024
NUM_BANDS = 12
MODEL_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models", "yamnet.onnx")
MODEL_SAMPLES = 15600 # YAMNet's 0.975 s patch
MODEL_CLASSES = 521
MUSIC_ID, SINGING_ID = 132, 24 # YAMNet's AudioSet ontology indices
HOP_S = 0.5
INPUT_RMS = 0.1
MAX_INPUT_GAIN = 8.0
ENTER_SCORE = 0.22
EXIT_SCORE = 0.10
ENTER_WINDOWS = 3
EXIT_WINDOWS = 6
SCORE_ALPHA = 0.5
COOLDOWN_S = 5.0
MIN_ACTIVE_RMS = 0.0025
AUDIO_TIMEOUT_S = 1.5
@dataclass
class MusicState:
is_music: bool = False
confidence: float = 0.0
beat_pulse: float = 0.0
groove_phase: float = 0.0
bpm: float = 100.0
energy: float = 0.0
bands: tuple[float, ...] = field(default_factory=lambda: (0.0,) * NUM_BANDS)
class MusicAnalyzer:
"""Classifies cabin audio as music or speech with YAMNet, plus a light beat/EQ layer for the visuals."""
def __init__(self, sample_rate: int = DEFAULT_SAMPLE_RATE, synchronous: bool = False):
self._sample_rate = sample_rate
self._synchronous = synchronous
self._window = np.hanning(FFT_SIZE).astype(np.float32)
self._ring = np.zeros(MODEL_SAMPLES, dtype=np.float32)
self._pending = 0
self._audio_lock = threading.Lock()
self._state_lock = threading.Lock()
self._executor: ThreadPoolExecutor | None = None
self._inferring = False
self._session = None
self._session_failed = False
self._input_name = ""
self._closed = False
self._rate_warned = False
self._clock = time.monotonic
self._last_audio_mono = 0.0
self._t = 0.0
self._suppress_until = 0.0
self._holdoff_until = 0.0
self._score = 0.0
self._above = 0
self._below = 0
self._is_music = False
self._beat_pulse = 0.0
self._groove_phase = 0.0
self._bpm = 100.0
self._energy = 0.0
self._bands = np.zeros(NUM_BANDS, dtype=np.float32)
self._freqs = np.fft.rfftfreq(FFT_SIZE, 1.0 / sample_rate)
self._band_slices = self._build_band_slices()
self._flux_band = (self._freqs >= 40.0) & (self._freqs <= 4000.0)
self._prev_mag: np.ndarray | None = None
self._flux_hist: deque[float] = deque(maxlen=int(FRAME_RATE * 2))
def _build_band_slices(self) -> list[tuple[int, int]]:
edges = np.geomspace(60.0, min(7200.0, self._sample_rate * 0.47), NUM_BANDS + 1)
slices = []
for i in range(NUM_BANDS):
lo = int(np.searchsorted(self._freqs, edges[i]))
hi = max(lo + 1, int(np.searchsorted(self._freqs, edges[i + 1])))
slices.append((lo, min(hi, len(self._freqs))))
return slices
@property
def state(self) -> MusicState:
with self._state_lock:
return MusicState(
is_music=self._is_music,
confidence=self._score,
beat_pulse=self._beat_pulse,
groove_phase=self._groove_phase,
bpm=self._bpm,
energy=self._energy,
bands=tuple(float(b) for b in self._bands),
)
def suppress(self, seconds: float) -> None:
"""Ignore input for a while because the device itself is playing a sound."""
self._suppress_until = max(self._suppress_until, self._t + max(0.0, seconds))
def close(self) -> None:
self._closed = True
if self._executor is not None:
self._executor.shutdown(wait=False, cancel_futures=True)
self._executor = None
def step_visual_decay(self, dt: float) -> MusicState:
"""Advance the groove one full sway per beat and decay beat pulses between audio chunks."""
with self._state_lock:
if self._clock() - self._last_audio_mono > AUDIO_TIMEOUT_S:
# the mic stream stalled: stop dancing instead of latching on stale evidence
self._score *= math.exp(-dt * 4.0)
self._above = 0
if self._is_music and self._score < EXIT_SCORE:
self._is_music = False
self._holdoff_until = self._t + COOLDOWN_S
cloudlog.info("cabin music ended (microphone silent)")
if self._is_music:
self._groove_phase = (self._groove_phase + (self._bpm / 60.0) * math.tau * dt) % math.tau
self._beat_pulse *= math.exp(-dt * 7.5)
if not self._is_music:
self._bands *= math.exp(-dt * 6.0)
return self.state
def process_audio_bytes(self, data: bytes, sample_rate: int = DEFAULT_SAMPLE_RATE) -> MusicState:
"""Process a rawAudioData int16 PCM buffer from micd."""
if not data:
return self.state
if sample_rate not in (0, self._sample_rate):
if not self._rate_warned:
cloudlog.error(f"music analyzer expects {self._sample_rate} Hz, got {sample_rate}; detection disabled")
self._rate_warned = True
return self.state
samples = np.frombuffer(data, dtype=np.int16).astype(np.float32) / 32768.0
return self.process_samples(samples)
def process_samples(self, samples: np.ndarray) -> MusicState:
"""Analyze one normalized float32 mono chunk (~50 ms)."""
n = len(samples)
if n == 0:
return self.state
self._t += n / self._sample_rate
self._last_audio_mono = self._clock()
if self._t < self._suppress_until:
return self.state
samples = samples.astype(np.float32, copy=False)
rms = float(np.sqrt(np.mean(samples * samples)))
self._energy = float(np.clip(rms / 0.35, 0.0, 1.0))
due = self._push(samples)
self._update_visual()
if due:
if rms < MIN_ACTIVE_RMS:
self._decide(0.0)
else:
self._schedule_inference()
return self.state
def _push(self, samples: np.ndarray) -> bool:
n = samples.size
with self._audio_lock:
if n >= MODEL_SAMPLES:
self._ring[:] = samples[-MODEL_SAMPLES:]
else:
self._ring[:-n] = self._ring[n:]
self._ring[-n:] = samples
self._pending += n
if self._pending < HOP_S * self._sample_rate:
return False
self._pending = 0
return True
def _update_visual(self) -> None:
with self._audio_lock:
chunk = self._ring[-FFT_SIZE:].copy()
mag = np.abs(np.fft.rfft(chunk * self._window)) / (FFT_SIZE * 0.5)
for i, (lo, hi) in enumerate(self._band_slices):
band_mag = float(np.sqrt(np.mean(mag[lo:hi] ** 2)))
tilt = 1.0 + 0.16 * i
norm = float(np.clip(math.log1p(band_mag * 95.0 * tilt) / 2.1, 0.0, 1.0))
rate = 0.55 if norm > self._bands[i] else 0.22
self._bands[i] = (1.0 - rate) * self._bands[i] + rate * norm
flux = 0.0
if self._prev_mag is not None:
flux = float(np.sum(np.maximum(0.0, mag - self._prev_mag)[self._flux_band]))
self._prev_mag = mag
self._flux_hist.append(flux)
if len(self._flux_hist) >= 10:
arr = np.asarray(self._flux_hist, dtype=np.float32)
if flux > float(arr.mean() + 0.9 * arr.std()) and flux > 1e-3:
self._on_onset()
def _on_onset(self) -> None:
self._beat_pulse = max(self._beat_pulse, 0.55)
def _schedule_inference(self) -> None:
if self._closed:
return
if self._synchronous:
self._infer()
return
if self._executor is None:
self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="music")
with self._state_lock:
if self._inferring:
return
self._inferring = True
self._executor.submit(self._infer_task)
def _infer_task(self) -> None:
try:
self._infer()
finally:
with self._state_lock:
self._inferring = False
def _infer(self) -> None:
session = self._get_session()
if session is None:
return
with self._audio_lock:
wav = self._ring.copy()
rms = float(np.sqrt(np.mean(wav * wav)))
gain = min(MAX_INPUT_GAIN, INPUT_RMS / max(rms, 1e-6))
wav = np.clip(wav * gain, -1.0, 1.0).astype(np.float32)
try:
out = session.run(None, {self._input_name: wav})[0]
except Exception:
cloudlog.exception("music model inference failed")
return
if self._t < self._suppress_until:
return # discard windows that straddle a self-audio suppression
probs = np.asarray(out, dtype=np.float32).reshape(-1, MODEL_CLASSES).mean(axis=0)
self._decide(float(np.clip(probs[MUSIC_ID] + 0.5 * probs[SINGING_ID], 0.0, 1.0)))
def _get_session(self):
if self._session is not None or self._session_failed:
return self._session
try:
import onnxruntime as ort
if not os.path.isfile(MODEL_PATH) or os.path.getsize(MODEL_PATH) < 1_000_000:
raise FileNotFoundError(f"{MODEL_PATH} is missing or an LFS pointer")
options = ort.SessionOptions()
options.intra_op_num_threads = 2
options.inter_op_num_threads = 1
options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
self._session = ort.InferenceSession(MODEL_PATH, sess_options=options, providers=["CPUExecutionProvider"])
self._input_name = self._session.get_inputs()[0].name
cloudlog.info(f"music model loaded: {MODEL_PATH}")
except Exception:
cloudlog.exception("music model unavailable, cabin music detection disabled")
self._session_failed = True
self._session = None
return self._session
def _decide(self, score: float) -> None:
with self._state_lock:
self._score = (1.0 - SCORE_ALPHA) * self._score + SCORE_ALPHA * score
if self._is_music:
self._below = self._below + 1 if self._score < EXIT_SCORE else 0
if self._below >= EXIT_WINDOWS:
self._is_music = False
self._below = 0
self._holdoff_until = self._t + COOLDOWN_S
cloudlog.info("cabin music ended")
elif self._t >= self._holdoff_until:
self._above = self._above + 1 if self._score >= ENTER_SCORE else 0
if self._above >= ENTER_WINDOWS:
self._is_music = True
self._above = 0
cloudlog.info(f"cabin music detected (score={self._score:.2f})")
@@ -1,75 +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 math
import raylib_nb as rl
from openpilot.common.filter_simple import FirstOrderFilter
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import NUM_BANDS, MusicState
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.scene import groove_prism_color
from openpilot.system.ui.lib.application import gui_app
class MusicVisualizerRenderer:
"""Ambient bass aura and a 12-band pill equalizer along the bottom edge."""
def __init__(self):
dt = 1.0 / max(gui_app.target_fps, 1)
self._alpha = FirstOrderFilter(0.0, 0.16, dt)
self._bar_filters = [FirstOrderFilter(0.0, 0.06, dt) for _ in range(NUM_BANDS)]
def render_background(self, rect: rl.Rectangle, music: MusicState, active: bool) -> float:
alpha = self._alpha.update(1.0 if active else 0.0)
if alpha < 0.01:
return 0.0
t = rl.get_time()
cr, cg, cb = groove_prism_color(t)
aura_r = 140.0 + 75.0 * music.beat_pulse + 35.0 * music.energy
rl.draw_circle_gradient(
rl.Vector2(rect.x + rect.width / 2.0, rect.y + rect.height + 10.0),
aura_r,
rl.Color(cr, cg, cb, int((42 + 52 * music.beat_pulse) * alpha)),
rl.Color(cr, cg, cb, 0),
)
total_w = rect.width - 76.0
gap = 10.0
bar_w = (total_w - gap * (NUM_BANDS - 1)) / NUM_BANDS
start_x = rect.x + (rect.width - total_w) / 2.0
base_y = rect.y + rect.height - 8.0
max_bar_h = 44.0
for i in range(NUM_BANDS):
raw_level = music.bands[i] if i < len(music.bands) else 0.0
wave = 0.14 + 0.10 * math.sin(t * 5.0 + i * 0.65)
beat_lift = music.beat_pulse * (0.28 if i < 6 else 0.16)
level = self._bar_filters[i].update(min(1.0, max(wave, raw_level + beat_lift)))
bar_h = max(8.0, level * max_bar_h)
bx = start_x + i * (bar_w + gap)
by = base_y - bar_h
frac = i / max(1, NUM_BANDS - 1)
br = int(min(255, cr * (1.0 - frac * 0.25) + 255 * frac * 0.25))
bg = int(min(255, cg * (1.0 - frac * 0.30) + 120 * frac * 0.30))
bb = int(min(255, cb * 0.85 + 255 * 0.15))
if level > 0.35:
rl.draw_circle_gradient(
rl.Vector2(bx + bar_w / 2.0, by + 4.0),
bar_w * 1.15,
rl.Color(br, bg, bb, int(75 * level * alpha)),
rl.Color(br, bg, bb, 0),
)
rl.draw_rectangle_rounded(
rl.Rectangle(bx, by, bar_w, bar_h), 0.9, 10,
rl.Color(br, bg, bb, int((155 + 90 * level) * alpha)),
)
return alpha
@@ -1,247 +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 math
import raylib_nb as rl
def _v(x: float, y: float) -> rl.Vector2:
return rl.Vector2(x, y)
def _c(color: tuple[int, int, int], alpha: float) -> rl.Color:
return rl.Color(color[0], color[1], color[2], int(max(0.0, min(1.0, alpha)) * 255))
def _white(alpha: float) -> rl.Color:
return rl.Color(255, 255, 255, int(max(0.0, min(1.0, alpha)) * 255))
def _fade(color: tuple[int, int, int], amount: float) -> rl.Color:
# Dim toward black at full opacity: overlapping strokes of a glyph must not seam.
a = max(0.0, min(1.0, amount))
return rl.Color(int(color[0] * a), int(color[1] * a), int(color[2] * a), 255)
def draw_capsule(a: rl.Vector2, b: rl.Vector2, thickness: float, color: rl.Color) -> None:
"""Stroke with round caps, so no prop ever ends in a corner."""
rl.draw_line_ex(a, b, thickness, color)
r = max(0.8, thickness * 0.5)
rl.draw_circle(int(a.x), int(a.y), r, color)
rl.draw_circle(int(b.x), int(b.y), r, color)
def bezier_points(p0: rl.Vector2, p1: rl.Vector2, p2: rl.Vector2, p3: rl.Vector2, n: int = 20) -> list[rl.Vector2]:
pts: list[rl.Vector2] = []
for i in range(n + 1):
u = i / n
iu = 1.0 - u
x = iu ** 3 * p0.x + 3.0 * iu * iu * u * p1.x + 3.0 * iu * u * u * p2.x + u ** 3 * p3.x
y = iu ** 3 * p0.y + 3.0 * iu * iu * u * p1.y + 3.0 * iu * u * u * p2.y + u ** 3 * p3.y
pts.append(_v(x, y))
return pts
def ellipse_points(cx: float, cy: float, rx: float, ry: float, rot: float = 0.0, n: int = 40) -> list[rl.Vector2]:
c, s = math.cos(rot), math.sin(rot)
pts: list[rl.Vector2] = []
for i in range(n):
a = (i / n) * math.tau
x, y = rx * math.cos(a), ry * math.sin(a)
pts.append(_v(cx + x * c - y * s, cy + x * s + y * c))
return pts
def fill_polygon(pts: list[rl.Vector2], color: rl.Color) -> None:
if len(pts) < 3:
return
cx = sum(p.x for p in pts) / len(pts)
cy = sum(p.y for p in pts) / len(pts)
fan = [_v(cx, cy), *reversed(pts), pts[0]]
rl.draw_triangle_fan(fan, len(fan), color)
def heart_points(cx: float, cy: float, radius: float, n: int = 40) -> list[rl.Vector2]:
scale = radius / 16.0
pts: list[rl.Vector2] = []
for i in range(n):
ang = (i / n) * math.tau
s = math.sin(ang)
hx = 16.0 * s * s * s
hy = -(13.0 * math.cos(ang) - 5.0 * math.cos(2.0 * ang) - 2.0 * math.cos(3.0 * ang) - math.cos(4.0 * ang)) - 2.2
pts.append(_v(cx + hx * scale, cy + hy * scale))
return pts
def draw_heart(cx: float, cy: float, radius: float, color: rl.Color) -> None:
fill_polygon(heart_points(cx, cy, radius), color)
def headphone_anchor(cy: float, eye_w: float, eye_h: float, spacing: float, mirror: float = 1.0) -> tuple[float, float, float]:
"""Cup offset from centre, cup centre y, and the band's crown y, shared with the layout tests."""
return spacing * 0.5 + eye_w * 0.5 - 4.0, cy + 18.0 * mirror, cy - eye_h * 1.02 * mirror
def nightcap_geometry(top_y: float, amount: float, mirror: float = 1.0) -> tuple[float, float]:
y0 = top_y + (1.0 - amount) * 26.0 * mirror
return y0, y0 - 22.0 * amount * mirror
def draw_headphones(cx: float, cy: float, eye_w: float, eye_h: float, spacing: float, amount: float,
color: tuple[int, int, int], t: float, mirror: float = 1.0, beat: float = 0.0,
layer: str = "all") -> None:
"""Cushioned over-ear headphones: the band is drawn behind the eyes, the cups in front."""
if amount < 0.02:
return
drop = (1.0 - amount) * -64.0 * mirror
wobble = math.sin(t * 2.2) * 1.0 * amount
cup_off, cup_y, crown_y = headphone_anchor(cy, eye_w, eye_h, spacing, mirror)
cup_y += drop
left_x = cx - cup_off * mirror
right_x = cx + cup_off * mirror
# One continuous curve from cup to cup, so the band is never a floating arc.
band = bezier_points(_v(left_x, cup_y - 14.0 * mirror), _v(cx - eye_w * 0.60 + wobble, crown_y + drop),
_v(cx + eye_w * 0.60 + wobble, crown_y + drop), _v(right_x, cup_y - 14.0 * mirror), 34)
if layer in ("all", "band"):
thickness = 10.0 + 0.7 * beat
for i in range(len(band) - 1):
draw_capsule(band[i], band[i + 1], thickness, _fade(color, 0.97 * amount))
for i in range(len(band) - 1):
draw_capsule(_v(band[i].x, band[i].y - 3.0 * mirror), _v(band[i + 1].x, band[i + 1].y - 3.0 * mirror),
2.6, _white(0.16 * amount))
if layer == "band":
return
cup_scale = 1.0 + 0.05 * beat
for side in (-1.0, 1.0):
cup_x = cx + side * cup_off * mirror
rl.draw_circle_gradient(_v(cup_x, cup_y), 38.0 * cup_scale, _c(color, 0.14 * amount), _c(color, 0.0))
draw_capsule(_v(cup_x, cup_y - 9.0 * cup_scale), _v(cup_x, cup_y + 9.0 * cup_scale), 38.0 * cup_scale, _fade(color, 0.90 * amount))
draw_capsule(_v(cup_x + side * 6.0 * mirror, cup_y - 7.0 * cup_scale), _v(cup_x + side * 6.0 * mirror, cup_y + 7.0 * cup_scale),
18.0 * cup_scale, _fade(color, 0.50 * amount))
draw_capsule(_v(cup_x - side * 6.0, cup_y - 16.0 * mirror), _v(cup_x - side * 6.0, cup_y - 3.0 * mirror),
3.0, _white(0.30 * amount))
def draw_nightcap(cx: float, top_y: float, width: float, amount: float,
color: tuple[int, int, int], t: float, mirror: float = 1.0) -> None:
"""Droopy stocking cap: soft cone that curls to one side, band and pom included."""
if amount < 0.02:
return
y0, tip_y = nightcap_geometry(top_y, amount, mirror)
sway = math.sin(t * 1.3) * 5.0
peak = 50.0 * amount
tip = _v(cx + width * 0.55 + sway, tip_y)
base_y = y0 - 5.0 * mirror
half = width * 0.31
# Soft cone with a flat base: a stocking cap, not a ball.
left = bezier_points(_v(cx - half, base_y), _v(cx - half * 0.95, base_y - peak * 0.55 * mirror),
_v(cx - width * 0.05, base_y - peak * 0.92 * mirror), tip, 16)
right = bezier_points(tip, _v(cx + width * 0.18, base_y - peak * 0.55 * mirror),
_v(cx + half * 0.9, base_y - peak * 0.18 * mirror), _v(cx + half, base_y), 16)
skirt = [_v(cx + half * math.cos(a), base_y + half * 0.10 * math.sin(a))
for a in (math.pi * i / 10.0 for i in range(11))]
fill_polygon(left + right + skirt, _fade(color, 0.95 * amount))
rl.draw_rectangle_rounded(rl.Rectangle(cx - width * 0.36, y0 - 5.0 * mirror, width * 0.72, 10.0), 0.95, 14, _white(0.92 * amount))
rl.draw_circle_gradient(_v(tip.x, tip.y), 18.0 * amount, _white(0.20 * amount), _white(0.0))
rl.draw_circle(int(tip.x), int(tip.y), 10.0 * amount, _white(0.95 * amount))
def draw_floating_hearts(cx: float, y: float, amount: float, color: tuple[int, int, int], t: float) -> None:
if amount < 0.02:
return
for idx, dx in enumerate((-70.0, 0.0, 70.0)):
phase = (t * 0.9 + idx * 0.33) % 1.0
fade = math.sin(phase * math.pi) * amount
hx = cx + dx + math.sin(phase * math.tau) * 7.0
hy = y - phase * 34.0
draw_heart(hx, hy, 9.0 + 2.0 * fade, _fade(color, fade))
def draw_z(cx: float, cy: float, size: float, color: rl.Color) -> None:
"""One continuous rounded Z: the diagonal grows out of the bars, so no stub pokes past a corner."""
stroke = max(2.4, size * 0.18)
top, bottom = cy - size * 0.5 + stroke * 0.5, cy + size * 0.5 - stroke * 0.5
left, right = cx - size * 0.5 + stroke * 0.5, cx + size * 0.5 - stroke * 0.5
draw_capsule(_v(left, top), _v(right, top), stroke, color)
draw_capsule(_v(right, top), _v(left, bottom), stroke, color)
draw_capsule(_v(left, bottom), _v(right, bottom), stroke, color)
def draw_floating_zzz(cx: float, y: float, amount: float, color: tuple[int, int, int], t: float) -> None:
if amount < 0.02:
return
for idx, size in enumerate((16.0, 22.0)):
phase = (t * 0.42 + idx * 0.5) % 1.0
fade = math.sin(phase * math.pi) * amount
draw_z(cx + phase * 24.0 + math.sin(phase * math.tau) * 5.0, y - phase * 46.0, size, _fade(color, 0.85 * fade))
def draw_note(cx: float, cy: float, r: float, color: rl.Color) -> None:
fill_polygon(ellipse_points(cx, cy, r * 0.92, r * 0.66, rot=-0.35, n=28), color)
stem_x = cx + r * 0.72
stem_top = cy - r * 2.6
draw_capsule(_v(stem_x, cy), _v(stem_x, stem_top), max(2.2, r * 0.34), color)
flag = bezier_points(_v(stem_x, stem_top), _v(stem_x + r * 0.9, stem_top - r * 0.05),
_v(stem_x + r * 1.2, stem_top + r * 0.75), _v(stem_x + r * 1.35, stem_top + r * 1.5), 12)
for i in range(len(flag) - 1):
draw_capsule(flag[i], flag[i + 1], max(2.2, r * 0.34), color)
def draw_floating_notes(rect: rl.Rectangle, amount: float, color: tuple[int, int, int], t: float, beat: float) -> None:
if amount < 0.02:
return
specs = (
(rect.x + 54.0, 0.0, 1.0),
(rect.x + rect.width - 54.0, 0.5, -1.0),
(rect.x + 92.0, 0.28, 0.8),
(rect.x + rect.width - 92.0, 0.76, -0.8),
)
for base_x, phase_off, sway in specs:
phase = (t * 0.42 + phase_off) % 1.0
fade = math.sin(phase * math.pi) * amount
nx = base_x + math.sin(phase * math.tau) * 11.0 * sway
ny = rect.y + 168.0 - phase * 104.0
draw_note(nx, ny, (7.0 + 2.2 * beat) * amount, _fade(color, 0.85 * fade))
def draw_sparkle(cx: float, cy: float, size: float, alpha: float) -> None:
"""Four soft petals instead of a hard cross, so the glint reads as light, not geometry."""
pts: list[rl.Vector2] = []
for i in range(48):
a = (i / 48.0) * math.tau
r = size * (0.34 + 0.66 * abs(math.cos(2.0 * a)) ** 1.35)
pts.append(_v(cx + math.cos(a) * r, cy + math.sin(a) * r))
rl.draw_circle_gradient(_v(cx, cy), size * 1.35, _white(0.30 * alpha), _white(0.0))
fill_polygon(pts, _white(0.9 * alpha))
def draw_speed_lines(rect: rl.Rectangle, color: rl.Color, alpha: float, t: float) -> None:
for i in range(4):
phase = (t * 4.5 + i * 0.25) % 1.0
y = rect.y + 68.0 + i * 44.0
line_len = 26.0 + 22.0 * math.sin(phase * math.pi)
fade = 0.67 * math.sin(phase * math.pi) * alpha
col = _fade((color.r, color.g, color.b), fade)
lx = rect.x + 12.0 + (1.0 - phase) * 28.0
rx = rect.x + rect.width - 12.0 - (1.0 - phase) * 28.0
draw_capsule(_v(lx, y), _v(lx + line_len, y), 3.5, col)
draw_capsule(_v(rx - line_len, y), _v(rx, y), 3.5, col)
def draw_edge_glow(rect: rl.Rectangle, side: int, color: rl.Color, alpha: float) -> None:
glow_w = 56
clear = rl.Color(color.r, color.g, color.b, 0)
if side < 0:
rl.draw_rectangle_gradient_h(int(rect.x), int(rect.y), glow_w, int(rect.height), color, clear)
else:
rl.draw_rectangle_gradient_h(int(rect.x + rect.width - glow_w), int(rect.y), glow_w, int(rect.height), clear, color)
@@ -1,229 +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 raylib_nb as rl
from openpilot.cereal import log
from openpilot.common.filter_simple import FirstOrderFilter
from openpilot.common.swaglog import cloudlog
from openpilot.selfdrive.ui.mici.onroad.augmented_road_view import BookmarkIcon
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.alert_overlay import RoboticAlertOverlay
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.expressions import (
DrivingSnapshot,
RoboticMood,
RoboticMoodEngine,
)
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.snapshot import snapshot_from_ui_state
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.face_renderer import ProceduralFaceRenderer
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import MusicAnalyzer, MusicState
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_visualizer import MusicVisualizerRenderer
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.speed_arc_renderer import SpeedArcRenderer
from openpilot.selfdrive.ui.sunnypilot.ui_state import OnroadTimerStatus
from openpilot.selfdrive.ui.ui_state import UIStatus, ui_state
from openpilot.system.ui.lib.application import (
FontWeight,
MouseEvent,
MousePos,
TextAlignment,
TextAlignmentVertical,
gui_app,
)
from openpilot.system.ui.widgets import Widget
from openpilot.system.ui.widgets.label import UnifiedLabel
VERTICAL_SWIPE_THRESHOLD = 45.0 # px
class RoboticOnroadView(Widget):
"""Full-screen EMO-inspired Robotic Companion onroad view for MICI (536x240 @ 60 FPS)."""
def __init__(self, bookmark_callback=None):
super().__init__()
self._bookmark_callback = bookmark_callback
self._mood_engine = RoboticMoodEngine(params=getattr(ui_state, "params", None))
self._face_renderer = ProceduralFaceRenderer()
self._speed_renderer = SpeedArcRenderer()
self._alert_overlay = RoboticAlertOverlay()
self._music_analyzer = MusicAnalyzer()
self._music_visualizer = MusicVisualizerRenderer()
self._audio_warned = False
self._active_logged = False
self._bookmark_icon = BookmarkIcon(self._on_bookmark_triggered)
dt = 1.0 / max(gui_app.target_fps, 1)
self._speed_blend = FirstOrderFilter(0.0, 0.08, dt)
self._alert_shift_filter = FirstOrderFilter(0.0, 0.07, dt)
# Vertical swipe tracking (up = speed peek, down = pet robot)
self._touch_start_y: float = 0.0
self._touch_start_x: float = 0.0
self._vertical_swipe_handled: bool = False
self._offroad_label = UnifiedLabel(
"start the car to\nuse sunnypilot",
54,
FontWeight.DISPLAY,
text_color=rl.Color(255, 255, 255, int(255 * 0.9)),
alignment=TextAlignment.CENTER,
alignment_vertical=TextAlignmentVertical.MIDDLE,
)
def _on_bookmark_triggered(self) -> None:
self._mood_engine.trigger_love(wink=True)
if self._bookmark_callback is not None:
self._bookmark_callback()
def is_swiping_left(self) -> bool:
"""Match AugmentedRoadView API so MiciMainLayout disables horizontal scroller during bookmark swipe."""
return self._bookmark_icon.is_swiping_left()
def _update_state(self) -> None:
super()._update_state()
if ui_state.panda_type == log.PandaState.PandaType.unknown:
self._offroad_label.set_text("system booting")
elif ui_state.ignition and not ui_state.started:
self._offroad_label.set_text("openpilot can't start\ncheck alerts")
else:
self._offroad_label.set_text("start the car to\nuse sunnypilot")
def _handle_mouse_event(self, mouse_event: MouseEvent) -> None:
if ui_state.started:
if mouse_event.left_pressed:
self._touch_start_x = mouse_event.pos.x
self._touch_start_y = mouse_event.pos.y
self._vertical_swipe_handled = False
elif mouse_event.left_down and not self._vertical_swipe_handled:
dx = abs(mouse_event.pos.x - self._touch_start_x)
dy = mouse_event.pos.y - self._touch_start_y
if abs(dy) > VERTICAL_SWIPE_THRESHOLD and abs(dy) > dx * 1.4:
self._vertical_swipe_handled = True
if dy < 0:
self._mood_engine.trigger_speed_peek()
else:
self._mood_engine.trigger_love()
self._bookmark_icon._handle_mouse_event(mouse_event)
super()._handle_mouse_event(mouse_event)
def _handle_mouse_release(self, mouse_pos: MousePos) -> None:
if self._vertical_swipe_handled:
self._vertical_swipe_handled = False
return
if not self._bookmark_icon.interacting():
super()._handle_mouse_release(mouse_pos)
def _render(self, _) -> None:
rl.draw_rectangle_rec(self.rect, rl.BLACK)
if not ui_state.started:
# Keep subtle animated sleepy eyes behind the offroad message so the screen is never static
sleepy_snap = DrivingSnapshot(started=False, standstill=True)
eye_target = self._mood_engine.update(sleepy_snap)
self._face_renderer.render(self.rect, eye_target, alpha=0.28, y_shift=16.0)
self._offroad_label.render(self._rect)
return
if not self._active_logged:
self._active_logged = True
cloudlog.info(f"robotic onroad view active (ignition={ui_state.ignition})")
alert = self._alert_overlay.get_alert()
if ui_state.sm.updated["rawAudioData"]:
raw_audio = ui_state.sm["rawAudioData"]
if raw_audio.data:
self._music_analyzer.process_audio_bytes(raw_audio.data, int(raw_audio.sampleRate))
self._audio_warned = False
elif not self._audio_warned and time.monotonic() - ui_state.sm.recv_time["rawAudioData"] > 10.0:
self._audio_warned = True
cloudlog.error("cabin music: no rawAudioData for 10 s, check micd")
if alert is not None:
self._music_analyzer.suppress(0.35)
music_state = self._music_analyzer.step_visual_decay(1.0 / max(gui_app.target_fps, 1))
snap = snapshot_from_ui_state(ui_state, alert)
snap.music = music_state
self._render_from_snapshot(snap, alert)
self._bookmark_icon.render(self.rect)
def _render_from_snapshot(self, snap: DrivingSnapshot, alert) -> None:
eye_target = self._mood_engine.update(snap)
speed_alpha = self._speed_blend.update(1.0 if self._mood_engine.showing_speed else 0.0)
face_alpha = 1.0 - speed_alpha
# The alert text fades in from the top edge, so the face makes room by settling down
grooving = self._mood_engine.mood == RoboticMood.MUSIC_GROOVE and alert is None
music_on = snap.music is not None and snap.music.is_music and alert is None
alert_shift = self._alert_shift_filter.update(10.0 if alert is not None else (-14.0 if grooving else 0.0))
music_state = snap.music or MusicState()
if face_alpha > 0.01:
self._music_visualizer.render_background(self.rect, music_state, active=music_on)
self._face_renderer.render(self.rect, eye_target, alpha=face_alpha, y_shift=alert_shift)
if alert is None:
self._speed_renderer.render_corner_badge(self.rect, snap, alpha=face_alpha)
if speed_alpha > 0.01:
self._speed_renderer.render_speed_mode(
self.rect,
snap,
alpha=speed_alpha,
cruising_smoothly=self._mood_engine.cruising_smoothly,
reason=self._mood_engine.speed_reason,
)
self._alert_overlay.render(self.rect, alert)
def show_event(self) -> None:
if gui_app.sunnypilot_ui():
ui_state.reset_onroad_sleep_timer(OnroadTimerStatus.RESUME)
def hide_event(self) -> None:
if gui_app.sunnypilot_ui():
ui_state.reset_onroad_sleep_timer(OnroadTimerStatus.PAUSE)
if __name__ == "__main__":
from openpilot.selfdrive.ui.mici.onroad.alert_renderer import Alert
gui_app.init_window("MICI Robotic Companion Preview")
view = RoboticOnroadView()
view.set_rect(rl.Rectangle(0, 0, gui_app.width, gui_app.height))
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=29.0, set_speed_kph=105.0)
print("Keys: [1] Engaged [2] MADS [3] Disengaged [4] Speed Peek [5] Stars [6] Love [7] Prompt [8] Critical [9] Pout [Left/Right] Steer")
for _ in gui_app.render():
if rl.is_key_pressed(rl.KeyboardKey.KEY_ONE):
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=29.0, set_speed_kph=105.0)
elif rl.is_key_pressed(rl.KeyboardKey.KEY_TWO):
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.LAT_ONLY, v_ego=20.0, set_speed_kph=90.0)
elif rl.is_key_pressed(rl.KeyboardKey.KEY_THREE):
snap = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=15.0)
elif rl.is_key_pressed(rl.KeyboardKey.KEY_FOUR):
view._mood_engine.trigger_speed_peek()
elif rl.is_key_pressed(rl.KeyboardKey.KEY_FIVE):
view._mood_engine.trigger_startled()
elif rl.is_key_pressed(rl.KeyboardKey.KEY_SIX):
view._mood_engine.trigger_love()
elif rl.is_key_pressed(rl.KeyboardKey.KEY_SEVEN):
snap.alert = Alert("Pay Attention", "Eyes on road", status=log.SelfdriveState.AlertStatus.userPrompt)
elif rl.is_key_pressed(rl.KeyboardKey.KEY_EIGHT):
snap.alert = Alert("TAKE CONTROL IMMEDIATELY", "Steering Required", status=log.SelfdriveState.AlertStatus.critical)
elif rl.is_key_pressed(rl.KeyboardKey.KEY_NINE):
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, standstill=True)
elif rl.is_key_down(rl.KeyboardKey.KEY_LEFT):
snap.steering_angle_deg = 30.0
elif rl.is_key_down(rl.KeyboardKey.KEY_RIGHT):
snap.steering_angle_deg = -30.0
else:
snap.steering_angle_deg = 0.0
rl.draw_rectangle_rec(view.rect, rl.BLACK)
view._render_from_snapshot(snap, snap.alert)
@@ -1,205 +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.
"""
from dataclasses import dataclass, fields
import math
import random
from enum import Enum
SUBSTEP_HZ = 120.0
MAX_DT = 0.1
class EyeGlyph(Enum):
ROUND_RECT = "round_rect"
STAR = "star"
HEART = "heart"
CRESCENT = "crescent"
ARROW_LEFT = "arrow_left"
ARROW_RIGHT = "arrow_right"
LASER_ALERT = "laser_alert"
SPARKLE_BOOST = "sparkle_boost"
class MouthGlyph(Enum):
NONE = "none"
SMILE = "smile"
BIG_GRIN = "big_grin"
FROWN = "frown"
SURPRISED = "surprised"
def clamp(x: float, lo: float, hi: float) -> float:
return max(lo, min(hi, x))
def smoothstep(edge0: float, edge1: float, x: float) -> float:
if edge1 <= edge0:
return 1.0 if x >= edge1 else 0.0
p = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0)
return p * p * (3.0 - 2.0 * p)
def ease_in_quad(p: float) -> float:
return clamp(p, 0.0, 1.0) ** 2
def ease_out_back(p: float, s: float = 1.35) -> float:
p = clamp(p, 0.0, 1.0) - 1.0
return p * p * ((s + 1.0) * p + s) + 1.0
def volume_preserving(sx: float) -> float:
"""Squash stretch that keeps the eye's apparent area constant."""
return 1.0 / clamp(sx, 0.72, 1.38)
@dataclass
class Pose:
"""Every channel the character can express, as targets rather than smoothed values."""
eye_w: float = 104.0
eye_h: float = 112.0
spacing: float = 166.0
roundness: float = 0.62
lid_top: float = 0.0
lid_bottom: float = 0.0
slant: float = 0.0
gaze_x: float = 0.0
gaze_y: float = 0.0
tilt: float = 0.0
scale_x: float = 1.0
scale_y: float = 1.0
squish: float = 0.0
lean: float = 0.0
flip: float = 0.0
bloom: float = 1.0
headphones: float = 0.0
nightcap: float = 0.0
hearts: float = 0.0
zzz: float = 0.0
notes: float = 0.0
speed_lines: float = 0.0
edge_glow: float = 0.0
arrow: float = 0.0
beat: float = 0.0
color: tuple[int, int, int] = (64, 240, 226)
pulse: float = 0.0
glyph: EyeGlyph = EyeGlyph.ROUND_RECT
mouth: MouthGlyph = MouthGlyph.NONE
wink_right: bool = False
blind_spot_side: int = 0
blinker_side: int = 0
SPRING_CONFIG: dict[str, tuple[float, float]] = {
"eye_w": (26.0, 0.62),
"eye_h": (26.0, 0.62),
"spacing": (24.0, 0.66),
"roundness": (18.0, 0.90),
"lid_top": (34.0, 0.95),
"lid_bottom": (34.0, 0.95),
"slant": (20.0, 0.90),
"gaze_x": (26.0, 0.60),
"gaze_y": (24.0, 0.62),
"tilt": (18.0, 0.60),
"scale_x": (30.0, 0.55),
"scale_y": (30.0, 0.55),
"squish": (18.0, 0.50),
"lean": (16.0, 0.62),
"flip": (6.0, 0.58),
"bloom": (18.0, 0.85),
"headphones": (14.0, 0.55),
"nightcap": (12.0, 0.65),
"hearts": (16.0, 0.70),
"zzz": (10.0, 0.80),
"notes": (12.0, 0.70),
"speed_lines": (16.0, 0.80),
"edge_glow": (14.0, 0.90),
"arrow": (20.0, 0.82),
"beat": (30.0, 0.90),
}
_SPRUNG = tuple(SPRING_CONFIG)
_DISCRETE = tuple(f.name for f in fields(Pose) if f.name not in SPRING_CONFIG and f.name != "color")
class Spring:
"""Damped harmonic oscillator stepped at a fixed rate so frame rate never changes the feel."""
def __init__(self, value: float, omega: float, zeta: float):
self.value = float(value)
self.velocity = 0.0
self.omega = float(omega)
self.zeta = float(zeta)
def step(self, target: float, dt: float) -> float:
remaining = clamp(dt, 0.0, MAX_DT)
h = 1.0 / SUBSTEP_HZ
while remaining > 1e-6:
sub = min(h, remaining)
accel = self.omega * self.omega * (target - self.value) - 2.0 * self.zeta * self.omega * self.velocity
self.velocity += accel * sub
self.value += self.velocity * sub
remaining -= sub
return self.value
def snap(self, value: float) -> None:
self.value = float(value)
self.velocity = 0.0
class SpringBus:
"""One spring per continuous channel, producing a smoothed Pose from a target Pose."""
def __init__(self, initial: Pose | None = None):
start = initial or Pose()
self._springs = {name: Spring(getattr(start, name), *SPRING_CONFIG[name]) for name in _SPRUNG}
self._color = [Spring(c, 10.0, 0.90) for c in start.color]
def snap(self, pose: Pose) -> None:
for name, spring in self._springs.items():
spring.snap(getattr(pose, name))
for i, spring in enumerate(self._color):
spring.snap(pose.color[i])
def step(self, target: Pose, dt: float) -> Pose:
values = {name: spring.step(getattr(target, name), dt) for name, spring in self._springs.items()}
color = tuple(int(clamp(spring.step(target.color[i], dt), 0, 255)) for i, spring in enumerate(self._color))
discrete = {name: getattr(target, name) for name in _DISCRETE if name != "color"}
return Pose(**values, color=color, **discrete)
def groove_prism_color(t: float) -> tuple[int, int, int]:
"""Smoothly cycling cyan -> aqua -> orchid -> mint, bright enough for the OLED."""
r = int(125 + 95 * math.sin(t * 0.9 + 2.2))
g = int(195 + 55 * math.sin(t * 0.9 + 0.4))
b = int(215 + 40 * math.sin(t * 0.9 + 4.1))
return (max(50, min(255, r)), max(90, min(255, g)), max(140, min(255, b)))
class MotionScheduler:
"""Weighted pick with per-clip cooldown and no immediate repeat."""
def __init__(self, options, rng: random.Random, weights: dict | None = None, cooldown: float = 30.0):
self._options = list(options)
self._rng = rng
self._weights = {o: (weights or {}).get(o, 1.0) for o in self._options}
self._cooldown = cooldown
self._cooldowns = dict.fromkeys(self._options, -1e9)
self._current = None
@property
def current(self):
return self._current
def pick(self, now: float):
candidates = [o for o in self._options if o != self._current and now - self._cooldowns[o] >= self._cooldown]
if not candidates:
candidates = [o for o in self._options if o != self._current] or list(self._options)
choice = self._rng.choices(candidates, weights=[self._weights[o] for o in candidates], k=1)[0]
self._current = choice
self._cooldowns[choice] = now
return choice
@@ -1,132 +0,0 @@
"""UI adapter that turns openpilot messages into the engine's DrivingSnapshot."""
from dataclasses import dataclass
from opendbc.car.structs import car
from openpilot.cereal import log
from openpilot.selfdrive.ui.mici.onroad.alert_renderer import Alert
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import MusicState
from openpilot.selfdrive.ui.ui_state import UIStatus
EventName = log.OnroadEvent.EventName
GearShifter = car.CarState.GearShifter
SET_SPEED_NA = 255
@dataclass
class DrivingSnapshot:
"""Pure-data snapshot of driving signals for deterministic mood evaluation & testing."""
started: bool = True
engaged: bool = False
status: UIStatus = UIStatus.DISENGAGED
v_ego: float = 0.0
a_ego: float = 0.0
standstill: bool = False
reverse: bool = False
steering_angle_deg: float = 0.0
yaw_rate: float = 0.0
pitch_rad: float = 0.0
pitch_rate: float = 0.0
curvature: float = 0.0
set_speed_kph: float = SET_SPEED_NA
is_metric: bool = False
left_blinker: bool = False
right_blinker: bool = False
left_blindspot: bool = False
right_blindspot: bool = False
blind_spot_enabled: bool = True
pre_lane_change_left: bool = False
pre_lane_change_right: bool = False
lane_change: bool = False
lane_change_blocked: bool = False
dm_alert_level: int = 0
alert: Alert | None = None
music: MusicState | None = None
class _GyroBiasEstimator:
"""Tracks the stationary yaw-gyro bias so a DC offset is not read as a permanent corner."""
def __init__(self):
self.bias = 0.0
self._seeded = False
def correct(self, yaw_rate: float, v_ego: float, dt: float) -> float:
if v_ego < 0.5:
if not self._seeded:
self.bias = yaw_rate
self._seeded = True
elif dt > 0.0:
self.bias += (yaw_rate - self.bias) * min(1.0, dt / 2.0)
return yaw_rate - self.bias
_GYRO_BIAS = _GyroBiasEstimator()
def snapshot_from_ui_state(ui_state, alert: Alert | None) -> DrivingSnapshot:
"""Build a DrivingSnapshot safely from ui_state.sm."""
sm = ui_state.sm
cs = sm["carState"]
controls = sm["controlsState"]
dm = sm["driverMonitoringState"]
events = sm["onroadEvents"]
v_cruise_cluster = cs.vCruiseCluster
set_speed_kph = controls.deprecated.vCruise if v_cruise_cluster == 0.0 else v_cruise_cluster
pre_left = any(e.name == EventName.preLaneChangeLeft for e in events)
pre_right = any(e.name == EventName.preLaneChangeRight for e in events)
lane_change = any(e.name == EventName.laneChange for e in events)
lane_blocked = any(e.name == EventName.laneChangeBlocked for e in events)
v_ego_cluster = cs.vEgoCluster
v_ego = v_ego_cluster if v_ego_cluster != 0.0 else cs.vEgo
yaw_rate = 0.0
pitch_rad = 0.0
pitch_rate = 0.0
if sm.valid.get("modelV2"):
mv2 = sm["modelV2"]
if len(mv2.orientation.y) > 0:
pitch_rad = float(mv2.orientation.y[0])
if len(mv2.orientationRate.y) > 0 and len(mv2.orientationRate.z) > 0:
pitch_rate = float(mv2.orientationRate.y[0])
yaw_rate = float(mv2.orientationRate.z[0])
if sm.valid.get("gyroscope"):
gyro_msg = sm["gyroscope"]
gyro_which = gyro_msg.which()
gv = gyro_msg.gyroUncalibrated.v if gyro_which == "gyroUncalibrated" else (gyro_msg.gyro.v if gyro_which == "gyro" else ())
if len(gv) >= 3:
pitch_rate = 0.5 * pitch_rate + 0.5 * float(gv[1]) if pitch_rate != 0.0 else float(gv[1])
yaw_rate = 0.5 * yaw_rate + 0.5 * float(gv[2]) if yaw_rate != 0.0 else float(gv[2])
yaw_rate = _GYRO_BIAS.correct(yaw_rate, max(0.0, float(v_ego)), 1.0 / 60.0)
return DrivingSnapshot(
started=ui_state.started,
engaged=ui_state.engaged,
status=ui_state.status,
v_ego=max(0.0, float(v_ego)),
a_ego=float(cs.aEgo),
standstill=bool(cs.standstill),
reverse=cs.gearShifter == GearShifter.reverse,
steering_angle_deg=float(cs.steeringAngleDeg),
yaw_rate=yaw_rate,
pitch_rad=pitch_rad,
pitch_rate=pitch_rate,
curvature=float(controls.curvature) if sm.valid.get("controlsState") else 0.0,
set_speed_kph=float(set_speed_kph),
is_metric=bool(ui_state.is_metric),
left_blinker=bool(cs.leftBlinker),
right_blinker=bool(cs.rightBlinker),
left_blindspot=bool(cs.leftBlindspot),
right_blindspot=bool(cs.rightBlindspot),
blind_spot_enabled=bool(getattr(ui_state, "blindspot", True)),
pre_lane_change_left=pre_left,
pre_lane_change_right=pre_right,
lane_change=lane_change,
lane_change_blocked=lane_blocked,
dm_alert_level=int(dm.alertLevel.raw) if sm.valid["driverMonitoringState"] else 0,
alert=alert,
)
@@ -1,205 +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 math
import raylib_nb as rl
from openpilot.common.filter_simple import BounceFilter
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.expressions import (
DrivingSnapshot,
PALETTE,
display_speed_and_set_speed,
)
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.props import draw_heart
from openpilot.selfdrive.ui.ui_state import UIStatus
from openpilot.system.ui.lib.application import FontWeight, gui_app
from openpilot.system.ui.lib.multilang import tr
from openpilot.system.ui.lib.text_measure import measure_text_cached
class SpeedArcRenderer:
"""Reference-video-inspired color-coded speed + curved arc gauge and subtle Set-Speed badge."""
SPEED_FONT_SIZE = 114
UNIT_FONT_SIZE = 24
BADGE_SPEED_FONT_SIZE = 32
def __init__(self):
dt = 1.0 / max(gui_app.target_fps, 1)
self._font_display: rl.Font = gui_app.font(FontWeight.DISPLAY)
self._font_semi_bold: rl.Font = gui_app.font(FontWeight.SEMI_BOLD)
self._font_medium: rl.Font = gui_app.font(FontWeight.MEDIUM)
self._arc_progress = BounceFilter(0.0, 0.11, dt, bounce=2.4)
def _speed_color(self, snap: DrivingSnapshot) -> tuple[int, int, int]:
if snap.status == UIStatus.OVERRIDE or snap.a_ego > 1.8:
return (255, 205, 65) # Warm yellow/amber
if snap.status == UIStatus.ENGAGED:
return (85, 238, 150) # Vibrant green
if snap.status == UIStatus.LAT_ONLY:
return PALETTE["lat_only"]
return (240, 245, 255) # Crisp white
def render_speed_mode(
self,
rect: rl.Rectangle,
snap: DrivingSnapshot,
alpha: float,
cruising_smoothly: bool,
reason: str,
) -> None:
if alpha < 0.01:
return
t = rl.get_time()
cur_speed, set_speed = display_speed_and_set_speed(snap)
sr, sg, sb = self._speed_color(snap)
speed_color = rl.Color(sr, sg, sb, int(255 * alpha))
sub_color = rl.Color(255, 255, 255, int(195 * alpha))
cx = rect.x + rect.width / 2.0
# Subtle breathing float so speed mode is alive and never frozen
float_y = math.sin(t * 2.2) * 2.0
# Top accent above speed: MAX set-speed pill or gently pulsing heart
if reason == "set_speed" and set_speed is not None:
pill_text = f"{tr('MAX')} {set_speed}"
pill_sz = measure_text_cached(self._font_semi_bold, pill_text, 26)
pill_w = pill_sz.x + 28
pill_h = 34
pill_rect = rl.Rectangle(cx - pill_w / 2.0, rect.y + 14 + float_y * 0.5, pill_w, pill_h)
rl.draw_rectangle_rounded(pill_rect, 0.5, 14, rl.Color(sr, sg, sb, int(48 * alpha)))
rl.draw_rectangle_rounded_lines_ex(pill_rect, 0.5, 14, 2.0, rl.Color(sr, sg, sb, int(180 * alpha)))
rl.draw_text_ex(
self._font_semi_bold,
pill_text,
rl.Vector2(cx - pill_sz.x / 2.0, pill_rect.y + (pill_h - pill_sz.y) / 2.0),
26,
0,
speed_color,
)
elif cruising_smoothly:
heart_r = 10.0 * (1.0 + 0.10 * math.sin(t * 4.5))
draw_heart(cx, rect.y + 30 + float_y * 0.5, heart_r, rl.Color(255, 118, 168, int(240 * alpha)))
elif set_speed is not None:
max_lbl = f"{tr('MAX')} {set_speed}"
lbl_sz = measure_text_cached(self._font_medium, max_lbl, self.UNIT_FONT_SIZE)
rl.draw_text_ex(
self._font_medium,
max_lbl,
rl.Vector2(cx - lbl_sz.x / 2.0, rect.y + 18 + float_y * 0.5),
self.UNIT_FONT_SIZE,
0,
sub_color,
)
# Big centered speed number
speed_text = str(cur_speed)
speed_sz = measure_text_cached(self._font_display, speed_text, self.SPEED_FONT_SIZE)
speed_y = rect.y + rect.height / 2.0 - speed_sz.y / 2.0 - 8.0 + float_y
rl.draw_text_ex(
self._font_display,
speed_text,
rl.Vector2(cx - speed_sz.x / 2.0, speed_y),
self.SPEED_FONT_SIZE,
0,
speed_color,
)
# Unit beside speed (small & subtle)
unit_text = tr("km/h") if snap.is_metric else tr("mph")
rl.draw_text_ex(
self._font_medium,
unit_text,
rl.Vector2(cx + speed_sz.x / 2.0 + 10.0, speed_y + speed_sz.y - 34.0),
self.UNIT_FONT_SIZE,
0,
rl.Color(255, 255, 255, int(150 * alpha)),
)
# Curved arc speedometer gauge underneath (matches reference video)
max_ref = float(set_speed) if (set_speed is not None and set_speed > 0) else (130.0 if snap.is_metric else 85.0)
raw_frac = max(0.0, min(1.0, cur_speed / max_ref))
frac = max(0.0, min(1.0, self._arc_progress.update(raw_frac)))
arc_center = rl.Vector2(cx, rect.y + rect.height + 74.0)
inner_r = 104.0
outer_r = 114.0
mid_r = (inner_r + outer_r) / 2.0
cap_r = (outer_r - inner_r) / 2.0
start_deg = 228.0
end_deg = 312.0
span_deg = end_deg - start_deg
# Track background arc with rounded caps
track_col = rl.Color(255, 255, 255, int(45 * alpha))
rl.draw_ring(arc_center, inner_r, outer_r, start_deg, end_deg, 32, track_col)
for deg in (start_deg, end_deg):
rad = math.radians(deg)
rl.draw_circle(int(arc_center.x + math.cos(rad) * mid_r), int(arc_center.y + math.sin(rad) * mid_r), cap_r, track_col)
# Active glowing arc + bright animated tip pip
if frac > 0.01:
active_end = start_deg + span_deg * frac
glow_pulse = 0.78 + 0.22 * math.sin(t * 3.5)
rl.draw_ring(
arc_center,
inner_r - 4.0,
outer_r + 4.0,
start_deg,
active_end,
32,
rl.Color(sr, sg, sb, int(65 * glow_pulse * alpha)),
)
rl.draw_ring(arc_center, inner_r, outer_r, start_deg, active_end, 32, speed_color)
# Rounded start cap & bright glowing tip pip
s_rad = math.radians(start_deg)
e_rad = math.radians(active_end)
rl.draw_circle(int(arc_center.x + math.cos(s_rad) * mid_r), int(arc_center.y + math.sin(s_rad) * mid_r), cap_r, speed_color)
tip_x = arc_center.x + math.cos(e_rad) * mid_r
tip_y = arc_center.y + math.sin(e_rad) * mid_r
rl.draw_circle_gradient(
rl.Vector2(tip_x, tip_y),
14.0,
rl.Color(255, 255, 255, int(140 * glow_pulse * alpha)),
rl.Color(sr, sg, sb, 0),
)
rl.draw_circle(int(tip_x), int(tip_y), cap_r + 1.5, rl.Color(255, 255, 255, int(235 * alpha)))
def render_corner_badge(self, rect: rl.Rectangle, snap: DrivingSnapshot, alpha: float) -> None:
"""Subtle top-left Set-Speed / engagement pill visible during normal hero-face mode."""
if alpha < 0.01:
return
t = rl.get_time()
_, set_speed = display_speed_and_set_speed(snap)
sr, sg, sb = self._speed_color(snap)
dot_pulse = 0.72 + 0.28 * math.sin(t * 3.0)
x = rect.x + 16.0
y = rect.y + 12.0
if set_speed is not None:
text = str(set_speed)
sz = measure_text_cached(self._font_semi_bold, text, self.BADGE_SPEED_FONT_SIZE)
pill_w = sz.x + 48.0
pill_h = 38.0
pill_rec = rl.Rectangle(x, y, pill_w, pill_h)
rl.draw_rectangle_rounded(pill_rec, 0.5, 14, rl.Color(255, 255, 255, int(22 * alpha)))
rl.draw_rectangle_rounded_lines_ex(pill_rec, 0.5, 14, 1.5, rl.Color(255, 255, 255, int(35 * alpha)))
rl.draw_circle(int(x + 16), int(y + pill_h / 2.0), 5.0, rl.Color(sr, sg, sb, int(235 * dot_pulse * alpha)))
rl.draw_text_ex(
self._font_semi_bold,
text,
rl.Vector2(x + 28.0, y + (pill_h - sz.y) / 2.0),
self.BADGE_SPEED_FONT_SIZE,
0,
rl.Color(255, 255, 255, int(210 * alpha)),
)
else:
rl.draw_circle(int(x + 10), int(y + 12), 5.5, rl.Color(sr, sg, sb, int(200 * dot_pulse * alpha)))
@@ -44,8 +44,7 @@ class UIStateSP:
self.is_sp_release: bool = self.params.get_bool("IsReleaseSpBranch")
self.sm_services_ext = [
"modelManagerSP", "selfdriveStateSP", "longitudinalPlanSP", "backupManagerSP",
"lateralTorqueParameters", "carStateSP", "liveMapDataSP", "carParamsSP", "lateralDelay", "modelDataV2SP",
"gyroscope",
"lateralTorqueParameters", "carStateSP", "liveMapDataSP", "carParamsSP", "lateralDelay", "modelDataV2SP"
]
self.sunnylink_state = SunnylinkState()
@@ -61,7 +60,6 @@ class UIStateSP:
self.custom_interactive_timeout: int = 0
self.developer_ui = None
self.hide_v_ego_ui: bool = False
self.mici_robotic_ui: bool = self.params.get_bool("MiciRoboticUI")
self.onroad_brightness: int = 0
self.onroad_brightness_timer: int = 0
self.onroad_brightness_timer_param: int = 0
@@ -186,7 +184,6 @@ class UIStateSP:
self.custom_interactive_timeout = self.params.get("InteractivityTimeout", return_default=True)
self.developer_ui = self.params.get("DevUIInfo")
self.hide_v_ego_ui = self.params.get_bool("HideVEgoUI")
self.mici_robotic_ui = self.params.get_bool("MiciRoboticUI")
self.onroad_brightness = int(float(self.params.get("OnroadScreenOffBrightness", return_default=True)))
self.onroad_brightness_timer_param = self.params.get("OnroadScreenOffTimer", return_default=True)
self.rainbow_path = self.params.get_bool("RainbowMode")
+1 -106
View File
@@ -1,13 +1,10 @@
import os
import threading
import time
import wave
from openpilot.common.test import OpenpilotTestCase
from openpilot.cereal import log, messaging
from openpilot.cereal.messaging import SubMaster, PubMaster
from openpilot.selfdrive.ui.soundd import SAMPLE_RATE, SELFDRIVE_STATE_TIMEOUT, Soundd, check_selfdrive_timeout_alert
from openpilot.sunnypilot.selfdrive.ui.robotic_sounds import ROBOTIC_SOUND_FILES, ROBOTIC_SOUNDS_DIR, VARIANTS_PER_SOUND, RoboticSoundPack
from openpilot.selfdrive.ui.soundd import SELFDRIVE_STATE_TIMEOUT, check_selfdrive_timeout_alert
AudibleAlert = log.SelfdriveState.AudibleAlert
@@ -59,106 +56,4 @@ class TestSoundd(OpenpilotTestCase):
assert check_selfdrive_timeout_alert(sm)
def test_robotic_sound_pack_wav_formats(self):
for alert_id, filenames in ROBOTIC_SOUND_FILES.items():
assert len(filenames) == VARIANTS_PER_SOUND
for filename in filenames:
path = os.path.join(ROBOTIC_SOUNDS_DIR, filename)
assert os.path.exists(path), f"Missing robotic sound for {alert_id}: {path}"
with wave.open(path, "r") as wf:
assert wf.getnchannels() == 1, f"{filename} must be mono"
assert wf.getsampwidth() == 2, f"{filename} must be 16-bit PCM"
assert wf.getframerate() == SAMPLE_RATE, f"{filename} must be {SAMPLE_RATE} Hz"
assert wf.getnframes() > 0, f"{filename} must not be empty"
def test_robotic_sound_pack_switching_and_quiet_mode(self):
class _FakeParams:
def __init__(self):
self.vals = {"MiciRoboticUI": False, "QuietMode": False}
def get_bool(self, key: str) -> bool:
return self.vals.get(key, False)
fake_params = _FakeParams()
pack = RoboticSoundPack(fake_params, SAMPLE_RATE)
pack.load()
assert set(ROBOTIC_SOUND_FILES).issubset(pack.sounds)
soundd = Soundd.__new__(Soundd)
soundd.params = fake_params
soundd.enabled = False
soundd._frame = 0
soundd.robotic_sound_pack = pack
soundd.load_sounds()
soundd.current_alert = AudibleAlert.engage
soundd.current_volume = 1.0
soundd.current_sound_frame = 0
soundd.pending_stop = False
# Default buffer used when MiciRoboticUI is False
buf_default = soundd.robotic_sound_pack.get_buffer(AudibleAlert.engage, soundd.loaded_sounds)
assert buf_default is soundd.loaded_sounds[AudibleAlert.engage]
# Switching MiciRoboticUI to True swaps buffer to robotic sound
fake_params.vals["MiciRoboticUI"] = True
assert pack.refresh_param() is True
buf_robotic = soundd.robotic_sound_pack.get_buffer(AudibleAlert.engage, soundd.loaded_sounds)
assert buf_robotic is pack.sounds[AudibleAlert.engage]
assert buf_robotic is not buf_default
# QuietMode still suppresses non-critical robotic engage chirp
soundd.enabled = True
assert not soundd.should_play_sound(AudibleAlert.engage)
assert soundd.should_play_sound(AudibleAlert.warningImmediateUser)
assert soundd.should_play_sound(AudibleAlert.warningImmediateSystem)
def test_robotic_sound_pack_reactive_chirp_only_on_bookmark(self):
from types import SimpleNamespace
from openpilot.sunnypilot.selfdrive.ui.robotic_sounds import CHIRP_BOOKMARK, REACTIVE_CHIRP_IDS
class _FakeParams:
def get_bool(self, key: str) -> bool:
return key == "MiciRoboticUI"
pack = RoboticSoundPack(_FakeParams(), SAMPLE_RATE)
pack.load()
assert REACTIVE_CHIRP_IDS == {CHIRP_BOOKMARK}
assert CHIRP_BOOKMARK in pack.sounds and len(pack.sounds[CHIRP_BOOKMARK]) > 0
class _FakeSM:
def __init__(self, bookmark=False, v_cruise=100.0, a_ego=0.0, blinker=False):
self.updated = {"userBookmark": bookmark, "bookmarkButton": False}
self._cs = SimpleNamespace(vCruiseCluster=v_cruise, leftBlinker=blinker, rightBlinker=False, standstill=False, aEgo=a_ego)
def __getitem__(self, key):
return self._cs
# No chirp for set-speed changes, blinkers or acceleration events
assert pack.detect_reactive_chirp(_FakeSM(v_cruise=110.0), now=10.0) is None
assert pack.detect_reactive_chirp(_FakeSM(v_cruise=90.0), now=11.0) is None
assert pack.detect_reactive_chirp(_FakeSM(a_ego=-3.5), now=11.5) is None
assert pack.detect_reactive_chirp(_FakeSM(a_ego=2.6, blinker=True), now=11.8) is None
assert pack.detect_reactive_chirp(_FakeSM(bookmark=True), now=12.0) == CHIRP_BOOKMARK
assert pack.detect_reactive_chirp(_FakeSM(bookmark=True), now=12.1) is None
def test_robotic_sound_pack_varies_every_alert_start(self):
class _FakeParams:
def get_bool(self, key: str) -> bool:
return key == "MiciRoboticUI"
pack = RoboticSoundPack(_FakeParams(), SAMPLE_RATE)
pack.load()
pack._rng.seed(20261129)
indices = []
for _ in range(VARIANTS_PER_SOUND * 3):
pack.start_alert(AudibleAlert.engage)
buffer = pack.get_buffer(AudibleAlert.engage, {})
assert buffer is not None and len(buffer) > 0
indices.append(pack._last_index[AudibleAlert.engage])
# A repeated alert never reuses the previous variant, and the pool is actually used
assert all(a != b for a, b in zip(indices, indices[1:], strict=False))
assert set(indices) == set(range(VARIANTS_PER_SOUND))
# TODO: add test with micd for checking that soundd actually outputs sounds
-3
View File
@@ -4,8 +4,6 @@ import sys
import threading
import time
import raylib_nb as rl
from openpilot.cereal import messaging
from openpilot.common.hardware import COMMA_HARDWARE
from openpilot.common.realtime import Priority, config_realtime_process
@@ -38,7 +36,6 @@ def main():
# a thread waiting for the GIL takes it from the one holding it after this long
sys.setswitchinterval(0.001)
rl.set_config_flags(rl.ConfigFlags.FLAG_MSAA_4X_HINT)
gui_app.init_window("UI")
if BIG_UI:
MainLayout()
+9 -32
View File
@@ -18,12 +18,6 @@ MIN_SPEED = 5.0 # m/s
LINE_STD = (0.2, 0.6)
POINT_STD = 0.1
YIELD = (0.2, 0.45)
CURVE_ACCEL = (0.3, 0.9) # m/s^2, lane curvature lateral accel for full curve authority
PLAN_SHARE_CURVE = 0.65 # plan y share at full curve authority; straights keep the 0.3-0.5 ramp
MANEUVER_OFFSET = (0.55, 0.75) # m, |plan offset from usual| where extra curve authority is withheld
TRUST_RISE = (1.5, 0.6) # s, trust recovery time on straights and in curves
MAX_ADDED_LAT_ACCEL = 1.0 # m/s^2, cap on Blendful's own curvature contribution
DK_RATE = 1e-3 # 1/(m*s), max dk change per second while trust falls
X_IDXS = np.array(ModelConstants.X_IDXS)
@@ -44,10 +38,6 @@ class Blendful:
self.model_curvature = 0.0
self.smooth = 0.0 # smooths the correction target below .53 lat accel
self.curvature = 0.0
self.lane_curvature = 0.0
self.curve_gate = 0.0
self.maneuver_free = 1.0
self.plan_share = 0.0
def update(self, model_output: dict[str, np.ndarray], v_ego: float, active: bool, model_curvature: float, enabled: bool = True) -> float:
self.l_prob = self.r_prob = 0.0
@@ -63,14 +53,11 @@ class Blendful:
self.lane_width.initialized = False
self.going_around = False
target = 0.0 if fading else self._target(model_output, v_ego, model_curvature)
curve_lat_accel = max(abs(model_curvature), abs(self.lane_curvature)) * v_ego ** 2
target = self.smooth = self.smooth + (target - self.smooth) * DT_MDL / (DT_MDL + np.interp(curve_lat_accel, [0.18, 0.53], [0.5, 0.0]))
target = self.smooth = self.smooth + (target - self.smooth) * DT_MDL / (DT_MDL + np.interp(abs(model_curvature) * v_ego ** 2, [0.18, 0.53], [0.5, 0.0]))
build = 0.5 / max(v_ego, 1.0) ** 2 * DT_MDL # jerk over 1 second
release = (0.5 if fading else 2.0) / max(v_ego, 1.0) ** 2 * DT_MDL # lets go fast, but past zero it builds like any other pull
k = self.curvature
self.curvature = float(np.clip(target, max(k - release, -build) if k > 0 else k - build, min(k + release, build) if k < 0 else k + build))
cap = MAX_ADDED_LAT_ACCEL / max(v_ego, 1.0) ** 2
self.curvature = float(np.clip(self.curvature, -cap, cap))
return self.curvature
def _target(self, model_output: dict[str, np.ndarray], v_ego: float, model_curvature: float) -> float:
@@ -118,6 +105,12 @@ class Blendful:
center = (r_var * (lines[1, win] + half_width) + l_var * (lines[2, win] - half_width)) / (l_var + r_var)
weight = 1.0 / (l_var * r_var / (l_var + r_var) + POINT_STD ** 2)
# Fit curvature to place the plant in center: e ~ dk x^2 / 2
plan_x = np.interp(x, model_output['plan'][0, :, 0], model_output['plan'][0, :, 1])
plan_share = np.interp(abs(model_curvature) * lookahead ** 2 / 2, [0.5, 2.0], [0.3, 0.5]) # up to 50% plan y vs curvature parabola in sharp curves
error = np.clip(center - ((1 - plan_share) * model_curvature * x ** 2 / 2 + plan_share * plan_x), -1.0, 1.0)
dk = 2.0 * np.sum(weight * error * x ** 2) / np.sum(weight * x ** 4)
# A model planning to end up further from its usual spot in the lane than the plant is now is likely going around something
hw_now = np.clip(lines[2, 0] - lines[1, 0], *LANE_WIDTH_CLIP) / 2 if l_prob * r_prob > 0.5 else self.lane_width.x / 2
center_now = (l_prob * (lines[1, 0] + hw_now) + r_prob * (lines[2, 0] - hw_now)) / (l_prob + r_prob)
@@ -140,29 +133,13 @@ class Blendful:
self.usual_offset.update_alpha(20.0 if self.going_around else 10.0)
self.usual_offset.update(offset)
# Curves seen by the lane fit, not only by the model's own curvature (which can under-read a curve it is cutting).
self.lane_curvature = float(lane_curvature)
self.curve_gate = float(np.interp(abs(lane_curvature) * v_ego ** 2, CURVE_ACCEL, [0.0, 1.0]))
# Hold the extra curve authority while the model is settled in its lane. A large deviation from its usual spot is a maneuver.
self.maneuver_free = 0.0 if self.going_around else float(np.interp(abs(offset - usual), MANEUVER_OFFSET, [1.0, 0.0]))
# Fit curvature to place the plant in center: e ~ dk x^2 / 2
plan_x = np.interp(x, model_output['plan'][0, :, 0], model_output['plan'][0, :, 1])
base_share = np.interp(abs(model_curvature) * lookahead ** 2 / 2, [0.5, 2.0], [0.3, 0.5]) # up to 50% plan y vs curvature parabola in sharp curves
self.plan_share = base_share + (PLAN_SHARE_CURVE - base_share) * self.curve_gate * self.maneuver_free
error = np.clip(center - ((1 - self.plan_share) * model_curvature * x ** 2 / 2 + self.plan_share * plan_x), -1.0, 1.0)
dk = 2.0 * np.sum(weight * error * x ** 2) / np.sum(weight * x ** 4)
if inside_curve:
lane_trust *= np.interp(abs(offset) - abs(center_now) - 0.25 * abs(model_curvature) * lookahead ** 2 / 2, (0.5, 1.0), [1.0, 0.0])
else:
lane_trust *= np.interp(swerve, (YIELD[0] / 2, YIELD[0]), [1.0, 0.0]) if self.going_around else np.interp(away, YIELD, [1.0, 0.0])
# While trust falls, move dk at a bounded rate instead of clipping it to its previous sign. The old clip could pin dk at
# zero and block a needed correction or sign reversal (seen as 1.5 s dead spots in sharp curves).
if lane_trust < self.trust:
dk = self.dk + float(np.clip(dk - self.dk, -DK_RATE * DT_MDL, DK_RATE * DT_MDL))
trust_tau = TRUST_RISE[0] + (TRUST_RISE[1] - TRUST_RISE[0]) * self.curve_gate
self.trust = lane_trust if lane_trust < self.trust else self.trust + (lane_trust - self.trust) * DT_MDL / (trust_tau + DT_MDL)
dk = float(np.clip(dk, min(self.dk, 0.0), max(self.dk, 0.0)))
self.trust = lane_trust if lane_trust < self.trust else self.trust + (lane_trust - self.trust) * DT_MDL / (1.5 + DT_MDL)
self.dk = dk
return float(self.trust * dk)
@@ -8,7 +8,7 @@ import numpy as np
from openpilot.common.realtime import DT_MDL
from openpilot.common.test import OpenpilotTestCase
from openpilot.sunnypilot.modeld_v2.blendful import Blendful, DK_RATE, MAX_ADDED_LAT_ACCEL
from openpilot.sunnypilot.modeld_v2.blendful import Blendful
from openpilot.sunnypilot.modeld_v2.constants import ModelConstants
X = np.array(ModelConstants.X_IDXS)
@@ -95,7 +95,7 @@ class TestBlendful(OpenpilotTestCase):
p = 0.9 - 0.02 * i
self.bf.update(frame(center=0.3, plan=-0.02 * i, probs=(p, p)), 20.0, True, 0.0)
if self.bf.trust < trust:
assert abs(self.bf.dk - dk) <= DK_RATE * DT_MDL + 1e-12
assert abs(self.bf.dk) <= abs(dk) + 1e-12
def test_toggle_off_returns_zero_and_resets(self):
drive(self.bf, 5.0, center=0.5)
@@ -110,48 +110,3 @@ class TestBlendful(OpenpilotTestCase):
assert self.bf.trust == 0.0
assert abs(out[0]) < abs(start)
assert abs(out[-1]) < 1e-6
def test_trust_fall_allows_sign_reversal(self):
drive(self.bf, 5.0, center=0.4)
assert self.bf.dk > 0
# Keep trust falling every frame while the lane moves to the other side. The old sign-preserving clip pinned dk at 0.
for i in range(300):
p = max(0.45, 0.9 - 0.0015 * i)
self.bf.update(frame(center=-0.4, probs=(p, p)), 20.0, True, 0.0)
assert self.bf.dk < 0
def test_curve_gate_opens_on_lane_curvature(self):
# The model under-reads the curve: lane lines curve, model_curvature stays 0.
for _ in range(400):
self.bf.update(frame(k=0.003, center=0.2), 25.0, True, 0.0)
assert self.bf.curve_gate > 0.9
assert self.bf.plan_share >= 0.6
straight = Blendful()
for _ in range(400):
straight.update(frame(), 25.0, True, 0.0)
assert straight.curve_gate < 0.05
def test_trust_recovers_faster_in_curves(self):
curve, straight = Blendful(), Blendful()
for bf, k in ((curve, 0.004), (straight, 0.0)):
drive(bf, 2.0, v=25.0, k=k)
bf.trust = 0.0
for _ in range(30):
bf.update(frame(k=k), 25.0, True, k)
assert curve.curve_gate > 0.9 and straight.curve_gate < 0.05
assert curve.trust > straight.trust + 0.1
def test_maneuver_gate_holds_extra_share(self):
drive(self.bf, 5.0, k=0.003, center=0.2)
self.bf.usual_offset.x = -0.2
self.bf.usual_offset.initialized = True
for _ in range(20):
self.bf.update(frame(k=0.003, center=0.2, plan=1.2), 25.0, True, 0.003)
assert self.bf.maneuver_free < 0.1
assert self.bf.plan_share < 0.55
def test_added_curvature_is_capped(self):
self.bf.curvature = 1.0
self.bf.update(frame(), 30.0, True, 0.0)
assert abs(self.bf.curvature) <= MAX_ADDED_LAT_ACCEL / 30.0 ** 2 + 1e-9
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:5ba40ef3804aaeafc84ef09e564e6cfcfb56748a16973615534fd1835cc7b1e8
size 28462
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:8174a45b747a5cc030ab2500c00663c953fb05ee338fac05ce3b1164d32874a3
size 28804
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:7e284f2d8e34fa95a12750c601c99f7d6864c87a7ce7abac87801cedb918c398
size 27454
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:8e4dccf5348b27a734b06f76d0324d7fce49d269cc1dfed52027d8dd89a450c2
size 29254
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:85eae44542a74a6d07ea51b544f14650623ad136f63293a9236503c6dbfddb93
size 31368
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:8ecc0664843bcad20a95ba91325c6542f8a185480345a23cdc3396781969db0a
size 32232
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:03e1a38f2edf23955e0a13059400c683fb24789f7b40dcc01fda061e10943ded
size 31942
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:320b7b845fd236ea1618cb446ea5b3511d71b288955a9b7048a605db38acb9db
size 30674
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:6cef95c9dd44320633694ccea53163f49e1704e0a278e748403afe2f7a3780d0
size 33184
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:c96f14f8130206b90828320ad1298189abd01bbd134b09653ad6ed053893a2a9
size 34878
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:d40e10f36b66d7547bc52043a1734707e818dd9ff86fd0d1e498d0270dd43a11
size 33566
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:814f3b021e30008c6d8488e7d2b2685e42c5e07d7d35aab1ce6057611fc5e9b6
size 33130
@@ -1,146 +0,0 @@
#!/usr/bin/env python3
"""Generate the mici robotic voice: formant-synthesised syllables, four variants per event.
Run after changing any event plan or voice parameter:
python3 openpilot/sunnypilot/selfdrive/assets/sounds/robotic/generate_robotic_sounds.py
"""
import random
import wave
from pathlib import Path
import numpy as np
SAMPLE_RATE = 48000
N_VARIANTS = 4
PEAK = 0.891 # -1 dBFS
MAX_DURATION_S = 0.7
OUT_DIR = Path(__file__).resolve().parent
# (base name, syllables) — syllable: (vowel, duration, f0 start, f0 end, vibrato Hz, vibrato depth)
EVENTS: list[tuple[str, list[tuple[str, float, float, float, float, float]]]] = [
("engage", [("e", 0.085, 560, 720, 0.0, 0.0), ("i", 0.075, 720, 900, 0.0, 0.0),
("i", 0.160, 900, 1180, 24.0, 0.030)]),
("disengage", [("o", 0.110, 820, 620, 0.0, 0.0), ("u", 0.200, 600, 400, 14.0, 0.020)]),
("refuse", [("u", 0.100, 430, 330, 0.0, 0.0), ("u", 0.160, 360, 250, 0.0, 0.0)]),
("prompt", [("e", 0.100, 700, 920, 0.0, 0.0), ("a", 0.130, 920, 720, 18.0, 0.020)]),
("prompt_repeat", [("e", 0.085, 760, 980, 0.0, 0.0), ("a", 0.100, 980, 820, 0.0, 0.0),
("a", 0.120, 900, 740, 16.0, 0.020)]),
("prompt_distracted", [("i", 0.090, 860, 1060, 0.0, 0.0), ("e", 0.130, 1060, 880, 12.0, 0.015)]),
("pre_alert", [("o", 0.170, 640, 900, 20.0, 0.020)]),
("warning_soft", [("a", 0.085, 900, 1120, 0.0, 0.0), ("a", 0.085, 900, 1120, 0.0, 0.0),
("o", 0.140, 1080, 800, 14.0, 0.020)]),
("warning_immediate_system", [("a", 0.075, 1050, 1240, 0.0, 0.0), ("a", 0.075, 1050, 1240, 0.0, 0.0),
("e", 0.150, 1240, 1520, 22.0, 0.025)]),
("warning_immediate_user", [("a", 0.070, 1120, 1320, 0.0, 0.0), ("a", 0.070, 1120, 1320, 0.0, 0.0),
("a", 0.070, 1120, 1320, 0.0, 0.0), ("i", 0.140, 1350, 1600, 26.0, 0.030)]),
("chirp_bookmark", [("i", 0.070, 940, 1220, 0.0, 0.0), ("i", 0.070, 1180, 1520, 0.0, 0.0),
("e", 0.110, 1520, 1280, 18.0, 0.020)]),
]
# (F, bandwidth, amplitude) — classic sung-vowel formant tables
VOWELS = {
"a": ((800.0, 90.0, 1.00), (1200.0, 100.0, 0.70), (2500.0, 140.0, 0.35), (3500.0, 200.0, 0.15)),
"e": ((500.0, 80.0, 1.00), (1900.0, 100.0, 0.65), (2500.0, 130.0, 0.35), (3500.0, 200.0, 0.15)),
"i": ((300.0, 60.0, 1.00), (2300.0, 110.0, 0.55), (3000.0, 140.0, 0.30), (3600.0, 200.0, 0.12)),
"o": ((500.0, 80.0, 1.00), (900.0, 90.0, 0.75), (2400.0, 140.0, 0.25), (3400.0, 200.0, 0.10)),
"u": ((320.0, 60.0, 1.00), (800.0, 80.0, 0.60), (2300.0, 140.0, 0.18), (3400.0, 200.0, 0.08)),
}
def _formant_gain(freqs: np.ndarray, vowel: str, scale: float) -> np.ndarray:
gain = np.zeros_like(freqs)
for center, bandwidth, amp in VOWELS[vowel]:
gain += amp / (1.0 + ((freqs - center * scale) / (bandwidth * 0.5)) ** 2)
return gain
def _noise_burst(n: int, gen: np.random.Generator, gain: float) -> np.ndarray:
noise = gen.standard_normal(n)
spec = np.fft.rfft(noise)
freqs = np.fft.rfftfreq(n, 1.0 / SAMPLE_RATE)
spec *= ((freqs > 1500.0) & (freqs < 6500.0)) * 0.35
shaped = np.fft.irfft(spec, n)
return shaped * np.exp(-np.arange(n) / (0.006 * SAMPLE_RATE)) * gain
def _envelope(n: int) -> np.ndarray:
attack = max(1, int(0.008 * SAMPLE_RATE))
release = max(1, int(0.25 * n))
env = np.ones(n, dtype=np.float64)
env[:attack] = np.linspace(0.0, 1.0, attack) ** 1.5
env[-release:] *= np.linspace(1.0, 0.0, release) ** 1.2
return env
def render_syllable(vowel: str, duration: float, f0_start: float, f0_end: float,
vibrato_hz: float, vibrato_depth: float, rng: random.Random) -> np.ndarray:
n = max(8, int(duration * SAMPLE_RATE))
gen = np.random.default_rng(rng.randrange(1 << 30))
t = np.arange(n) / SAMPLE_RATE
progress = t / duration
glide = progress * progress * (3.0 - 2.0 * progress)
f0 = f0_start + (f0_end - f0_start) * glide
if vibrato_hz > 0.0:
f0 = f0 * (1.0 + vibrato_depth * np.sin(2.0 * np.pi * vibrato_hz * t))
jitter = np.convolve(gen.standard_normal(n), np.ones(32) / 32.0, mode="same")
f0 = f0 * (1.0 + 0.004 * jitter)
phase = 2.0 * np.pi * np.cumsum(f0) / SAMPLE_RATE
n_harmonics = int(min(40, max(3, (SAMPLE_RATE * 0.42) / max(60.0, f0_start, f0_end))))
harmonic = np.arange(1, n_harmonics + 1)[:, None]
freqs = f0[None, :] * harmonic
amps = _formant_gain(freqs, vowel, 1.0 + rng.uniform(-0.04, 0.04))
amps *= 1.0 / harmonic ** 0.85
voice = np.sum(amps * np.sin(harmonic * phase[None, :]), axis=0)
peak = float(np.max(np.abs(voice))) + 1e-9
voice = voice / peak
voice += _noise_burst(n, gen, 0.06)
return (voice * _envelope(n)).astype(np.float64)
def render_event(base: str, syllables, variant: int) -> np.ndarray:
rng = random.Random(f"{base}:{variant}")
semitones = [-2.0, -1.0, 1.0, 2.0][variant % 4]
pitch_scale = 2.0 ** (semitones / 12.0)
parts: list[np.ndarray] = []
for vowel, duration, f0a, f0b, vib_hz, vib_depth in syllables:
dur = duration * (1.0 + rng.uniform(-0.06, 0.06))
vib = vib_hz * (1.0 + rng.uniform(-0.15, 0.15)) if vib_hz > 0.0 else 0.0
parts.append(render_syllable(vowel, dur, f0a * pitch_scale, f0b * pitch_scale, vib, vib_depth, rng))
parts.append(np.zeros(int(rng.uniform(0.012, 0.028) * SAMPLE_RATE)))
out = np.concatenate(parts[:-1])
return out[:int(MAX_DURATION_S * SAMPLE_RATE)]
def write_wav(path: Path, samples: np.ndarray) -> None:
audio = np.asarray(samples, dtype=np.float64)
fade_in = max(1, int(0.003 * SAMPLE_RATE))
fade_out = min(len(audio) // 2, max(1, int(0.012 * SAMPLE_RATE)))
audio[:fade_in] *= np.linspace(0.0, 1.0, fade_in)
audio[-fade_out:] *= np.linspace(1.0, 0.0, fade_out)
peak = float(np.max(np.abs(audio))) + 1e-9
audio = np.clip(audio / peak * PEAK, -1.0, 1.0)
pcm = (audio * 32767.0).astype(np.int16)
with wave.open(str(path), "wb") as wf:
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(SAMPLE_RATE)
wf.writeframes(pcm.tobytes())
def build_all_sounds() -> None:
existing = {p.name for p in OUT_DIR.glob("*.wav")}
written: set[str] = set()
for base, syllables in EVENTS:
for variant in range(1, N_VARIANTS + 1):
name = f"{base}_{variant}.wav"
write_wav(OUT_DIR / name, render_event(base, syllables, variant - 1))
written.add(name)
for stale in existing - written:
(OUT_DIR / stale).unlink()
print(f"Generated {len(written)} robotic WAV files in {OUT_DIR}")
if __name__ == "__main__":
build_all_sounds()
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:017f19683e38c05266b3f4dfd142d402ef9631fbb769339b258e844cb6c3de34
size 16516
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:8a86c48b7b2d36de2ba5687741eec2353cc0a311337a857726c266aadbc58753
size 15576
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:aa1c0b213057883dc5b1a3b74811eeb3030d8b165f4c76aa920e8e063e0d3f65
size 15552
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:76fa668e3f943a8c5664a9f5c6921a69cd912255a6c69fc34d22cfdb015312ce
size 15550
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:c5f0feac6c324fda47fb3a4f344297dd87d3643350fe198029f139f5151ea2ec
size 24256
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:f3d159fc5eaf2226721b774aaed4dcec0a051b370bc04139450423b8f1fdebaf
size 25162
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:0c65f1e0e2e1f24b09e891333d18d97f9191ef65fe4a0a7b2f9b23bdd5fc295a
size 24080
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:214a450f84cf4e1964179d6cff9252dabbf3796796bf2cc10ca0ec8b48fb6177
size 23738
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:e932cd466a0120f29b13abc00e3e6393a7ed2cbf1b9bd304a50dc477376a40f6
size 23970
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:896ba333933393368425cbf8837fa96b3ecb5855a699b75debc69051b30bb840
size 22724
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:3c066f44489a398330cef308386a4887b9ca71ab583f884bea3283fa88bd817f
size 23174
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:64aeff1381fa0f9e9e0d45f9ab93f45a3677b2650d7d5f59b20ae91582f65e8d
size 23248
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:a85649d6e7fe8cd73488360bf57a9edcd158c1960f838d2c88c50e32664ebdcc
size 32848
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:755247a2755500e37a3dd0bd983919ddd0c2793482acf276ad9a44aaeb853748
size 33854
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:7276495c128a7bd99fafc509e43e33ed4551cc5b92089232e2436c9b79a1148b
size 32760
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:4a60f53d3c0b82cab538dbc893a94f583060eac21cc3ccf7764d3ff44aad904f
size 34312
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:384d04af5e44a90b81507c567f20e83dcbb4d644c621bc102482f13b0ce24282
size 26880
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:8b16c31da14307367a296516ee33356999b6ce5bdfe3a9db4a86e880458ff1c4
size 27190
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:d29bf7624a20e0c0f2692fa02a1ec223248e557a9c5e3131c8e49b0e69472a8d
size 26034
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:904073e29dd5980c5e98dd17b61e61991af536ea0ddd3b0d6a1c57b167f9bd8a
size 26662
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:a74bf7ac36da84a30f8227e10abbd03e2deaec2f889b7ea018b427da6a956a50
size 33240
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:2f0c8ec68a728c1a162daadf45d0644e5f9e68614d620a90c614b4766cc85fda
size 31884
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:80f86e56640c19d9317141061f8998fbcbcdc3c52339d451c65fc150b56a9d2c
size 32466
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:fb1f68c678233d517abb7011983c1a90910f4c5a4072b474f0d343218a19c29f
size 33108
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:4ae20f9b841c605e5216cf38510a8c33b8681ddd6d0925d2709e9f2f63c1052c
size 39846
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:cf200d84088a4e085d58f66f33a24713745d16540c71e771f0b2b49a5d85f713
size 39072
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:c6d7480cf627701637c8eb4804c31a49af15aa491220f69c11b69f18fb65d675
size 39384
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:e7bf895959123787ddd824297fcc6ebf52dc8f0fa08f2dc35a593ae180f7974f
size 38860
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:38e89e4eb124e3a36d3b092133ca8592d6e41812aa745e35431a28ff9fe2edc8
size 32990
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:996031b5da89c011745d879ee67fc73a9c2bfe535a71483b8e4c9ad25c550efc
size 34390
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:e33eead4c640ccadee16b14259a036e55f404a45832d20d98cae4987c89bd05a
size 32922
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:e1f29e44ac78dcf15c002b0c718f987ecaf83cfd27ad7de5891a50597cd4fb7e
size 32662
@@ -5,7 +5,6 @@ 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 openpilot.cereal.messaging as messaging
from openpilot.cereal import log, custom
from opendbc.car import structs
@@ -24,15 +23,10 @@ class CarSpecificEventsSP:
self.CP_SP = CP_SP
self.low_speed_alert = False
self.sm = messaging.SubMaster(['carStateSP'])
def update(self, CS: structs.CarState, events: Events):
events_sp = EventsSP()
self.sm.update(0)
if self.sm['carStateSP'].stockSteerIntervention:
events_sp.add(EventNameSP.stockSteerIntervention)
if self.CP.brand == 'chrysler':
if self.CP.carFingerprint in RAM_DT:
# remove belowSteerSpeed event from CarSpecificEvents as RAM_DT uses a different logic
@@ -11,7 +11,6 @@ from opendbc.car.interfaces import CarInterfaceBase
from openpilot.common.params import Params
from openpilot.common.swaglog import cloudlog
from openpilot.sunnypilot.selfdrive.controls.lib.nnlc.helpers import get_nn_model_path
from openpilot.sunnypilot.selfdrive.controls.lib.pidd import PIDD_VERSION
from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.helpers import set_speed_limit_assist_availability
from openpilot.sunnypilot.sunnylink.statsd import STATSLOGSP
@@ -56,18 +55,10 @@ def _initialize_intelligent_cruise_button_management(CP: structs.CarParams, CP_S
CP_SP.pcmCruiseSpeed = False
def _initialize_torque_lateral_control(CI: CarInterfaceBase, CP: structs.CarParams, enforce_torque: bool, nnlc_enabled: bool,
params: Params | None = None) -> None:
if params is None:
params = Params()
def _initialize_torque_lateral_control(CI: CarInterfaceBase, CP: structs.CarParams, enforce_torque: bool, nnlc_enabled: bool) -> None:
if nnlc_enabled or enforce_torque:
CI.configure_torque_tune(CP.carFingerprint, CP.lateralTuning)
if enforce_torque and not nnlc_enabled and CP.steerControlType == structs.CarParams.SteerControlType.torque \
and params.get("TorqueControlTune") == PIDD_VERSION:
CP.lateralTuning.init('pid')
def _cleanup_unsupported_params(CP: structs.CarParams, CP_SP: structs.CarParamsSP, params: Params | None = None) -> None:
if params is None:
@@ -101,7 +92,7 @@ def setup_interfaces(CI: CarInterfaceBase, params: Params | None = None) -> None
enforce_torque = _enforce_torque_lateral_control(CI.CP, params)
nnlc_enabled = _initialize_neural_network_lateral_control(CI.CP, CI.CP_SP, params)
_initialize_intelligent_cruise_button_management(CI.CP, CI.CP_SP, params)
_initialize_torque_lateral_control(CI, CI.CP, enforce_torque, nnlc_enabled, params)
_initialize_torque_lateral_control(CI, CI.CP, enforce_torque, nnlc_enabled)
_cleanup_unsupported_params(CI.CP, CI.CP_SP)
try:
@@ -114,8 +105,6 @@ def setup_interfaces(CI: CarInterfaceBase, params: Params | None = None) -> None
def initialize_params(params) -> list[dict[str, Any]]:
keys: list = []
keys.append("RadarTracks")
# hyundai
keys.extend([
"HyundaiLongitudinalTuning",
@@ -137,6 +126,7 @@ def initialize_params(params) -> list[dict[str, Any]]:
keys.extend([
"ToyotaEnforceStockLongitudinal",
"ToyotaStopAndGoHack",
"ToyotaEnhancedBsm",
"ToyotaTSS2Smooth",
])
@@ -6,8 +6,6 @@ See the LICENSE.md file in the root directory for more details.
"""
import time
import numpy as np
import openpilot.cereal.messaging as messaging
from openpilot.cereal import log, custom
@@ -19,27 +17,6 @@ from openpilot.sunnypilot.livedelay.helpers import get_lat_delay
from openpilot.sunnypilot.modeld_v2.modeld_base import ModelStateBase
from openpilot.sunnypilot.selfdrive.controls.lib.blinker_pause_lateral import BlinkerPauseLateral
from openpilot.sunnypilot.selfdrive.controls.lib.latcontrol_torque_v0 import LatControlTorque as LatControlTorqueV0
from openpilot.sunnypilot.selfdrive.controls.lib.pidd import LatControlPidd, pidd_selected
PATH_CURVATURE_PREVIEW_START = 15.0 # m ahead of the car
PATH_CURVATURE_PREVIEW_END = 45.0 # m ahead of the car
PATH_CURVATURE_MIN_SPEED = 1.0 # m/s
def path_curvature_ahead(model_v2) -> float:
vx = np.asarray(model_v2.velocity.x, dtype=np.float64)
if len(vx) < 3 or vx[0] < PATH_CURVATURE_MIN_SPEED:
return 0.0
# averaged over a fixed distance ahead, so the preview does not shrink with speed
position = model_v2.position
distance = np.concatenate([[0.0], np.cumsum(np.hypot(np.diff(position.x), np.diff(position.y)))])
start = min(int(np.searchsorted(distance, PATH_CURVATURE_PREVIEW_START)), len(distance) - 1)
end = min(max(int(np.searchsorted(distance, PATH_CURVATURE_PREVIEW_END)), start + 1), len(distance))
oz = np.asarray(model_v2.orientationRate.z, dtype=np.float64)[start:end]
return float(np.mean(oz / np.maximum(vx[start:end], PATH_CURVATURE_MIN_SPEED)))
class ControlsExt(ModelStateBase):
@@ -53,15 +30,11 @@ class ControlsExt(ModelStateBase):
cloudlog.info("controlsd_ext is waiting for CarParamsSP")
self.CP_SP = messaging.log_from_bytes(params.get("CarParamsSP", block=True), custom.CarParamsSP)
cloudlog.info("controlsd_ext got CarParamsSP")
self.pidd: LatControlPidd | None = None
self.sm_services_ext = ['radarState', 'selfdriveStateSP']
self.pm_services_ext = ['carControlSP']
def initialize_lateral_control(self, lac, CI, dt):
if pidd_selected(self.CP):
self.pidd = LatControlPidd(self.CP, self.CP_SP, CI, dt)
return self.pidd
enforce_torque_control = self.params.get_bool("EnforceTorqueControl")
torque_versions = self.params.get("TorqueControlTune")
if not enforce_torque_control:
@@ -131,8 +104,6 @@ class ControlsExt(ModelStateBase):
CC_SP.intelligentCruiseButtonManagement.sendButton = icbm_src.sendButton
CC_SP.intelligentCruiseButtonManagement.vTarget = icbm_src.vTarget
CC_SP.pathCurvature = path_curvature_ahead(sm['modelV2'])
return CC_SP
@staticmethod
@@ -143,13 +114,6 @@ class ControlsExt(ModelStateBase):
pm.send('carControlSP', cc_sp_send)
def update_pidd_torque_params(self, sm: messaging.SubMaster) -> None:
torque_params = sm['lateralTorqueParameters']
if self.pidd is not None and sm.all_checks(['lateralTorqueParameters']) and torque_params.useParams:
self.pidd.update_torque_parameters(torque_params.latAccelFactorFiltered, torque_params.latAccelOffsetFiltered,
torque_params.frictionCoefficientFiltered)
def run_ext(self, sm: messaging.SubMaster, pm: messaging.PubMaster) -> None:
self.update_pidd_torque_params(sm)
CC_SP = self.state_control_ext(sm)
self.publish_ext(CC_SP, sm, pm)
@@ -1,7 +1,4 @@
{
"pidd": {
"version": "2.0"
},
"v1.0": {
"version": "1.0"
},
@@ -1,180 +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 math
import numpy as np
from collections import deque
from opendbc.car.interfaces import get_torque_params
from opendbc.car.vehicle_model import VehicleModel
from openpilot.cereal import log
from openpilot.common.constants import ACCELERATION_DUE_TO_GRAVITY
from openpilot.common.filter_simple import FirstOrderFilter
from openpilot.common.pid import PIDController
from openpilot.selfdrive.controls.lib.latcontrol import LatControl
# gains are in lateral acceleration, scaled to torque per degree by each car's vehicle model and latAccelFactor
PIDD_VERSION = 2.0
INTERP_SPEEDS = [1.0, 1.5, 2.0, 3.0, 5.0, 7.5, 10.0, 15.0, 30.0]
KP_INTERP = [250.0, 120.0, 65.0, 30.0, 11.5, 5.5, 3.5, 2.0, 0.8]
TD_INTERP = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.15, 0.2]
HIGH_SPEED_BP = [25.0, 29.0]
TURN_RATE_BP = [5.0, 20.0]
TURN_LAT_ACCEL_BP = [0.18, 0.53]
DESIRED_ANGLE_BUFFER_SECONDS = 1.0
LIVE_LAT_ACCEL_FACTOR_RANGE = [1.0, 2.0]
LIVE_FRICTION_RANGE = [0.5, 2.0]
SWING_CAP_FRICTION = 1.3
def pidd_selected(CP):
return CP.steerControlType == 'torque' and CP.lateralTuning.which() == 'pid' and len(CP.lateralTuning.pid.kpBP) == 0 and \
CP.carFingerprint in get_torque_params()
def filter_rc(hz):
return 1 / (2 * math.pi * hz)
def lat_accel_per_deg(VM, v_ego):
return VM.calc_curvature(math.radians(1.0), v_ego, 0.0) * v_ego**2
class LatControlPidd(LatControl):
def __init__(self, CP, CP_SP, CI, dt):
super().__init__(CP, CP_SP, CI, dt)
torque_params = get_torque_params()[CP.carFingerprint]
self.VM = VehicleModel(CP)
self.pid = PIDController(0.0, 0.0, 0.0, pos_limit=self.steer_max, neg_limit=-self.steer_max)
self.offline_lat_accel_factor, self.offline_friction = float(torque_params['LAT_ACCEL_FACTOR']), float(torque_params['FRICTION'])
self.lat_accel_factor = self.friction = None
self.update_torque_parameters(self.offline_lat_accel_factor, 0.0, self.offline_friction)
self.error_filter = FirstOrderFilter(0.0, filter_rc(1.0), dt)
self.request_filter = FirstOrderFilter(0.0, filter_rc(3.0), dt, initialized=False)
self.error_rate_filter = FirstOrderFilter(0.0, 0.0354, dt)
self.wheel_angle_filter = FirstOrderFilter(0.0, filter_rc(10.0), dt, initialized=False)
self.wheel_rate_filter = FirstOrderFilter(0.0, 0.005, dt)
self.request_rate_ref = FirstOrderFilter(0.0, filter_rc(1.0), dt)
self.break_rate = FirstOrderFilter(0.0, filter_rc(0.5), dt)
self.break_rate2 = FirstOrderFilter(0.0, filter_rc(0.5), dt)
self.break_error = FirstOrderFilter(0.0, filter_rc(1.0), dt)
self.command_slow = FirstOrderFilter(0.0, filter_rc(0.5), dt, initialized=False)
self.last_error = 0.0
self.wheel_angle_held = None
self.swing = 0.0
buffer_len = int(DESIRED_ANGLE_BUFFER_SECONDS / dt)
self.desired_angle_buffer = deque([0.0] * buffer_len, maxlen=buffer_len)
self.delay_frames = int(np.clip(CP.steerActuatorDelay / dt + 1, 1, buffer_len))
self.rate_span_frames = max(1, int(0.1 / dt))
def update_torque_parameters(self, latAccelFactor, latAccelOffset, friction):
# a learned factor below the offline one would raise every gain
latAccelFactor = float(np.clip(latAccelFactor, *(r * self.offline_lat_accel_factor for r in LIVE_LAT_ACCEL_FACTOR_RANGE)))
friction = float(np.clip(friction, *(r * self.offline_friction for r in LIVE_FRICTION_RANGE)))
if (latAccelFactor, friction) == (self.lat_accel_factor, self.friction):
return
self.lat_accel_factor, self.friction = latAccelFactor, friction
self.kp = [kp * lat_accel_per_deg(self.VM, v) / latAccelFactor for kp, v in zip(KP_INTERP, INTERP_SPEEDS, strict=True)]
self.pid._k_p = (INTERP_SPEEDS, self.kp)
self.pid._k_i = (INTERP_SPEEDS, [kp / 6.0 for kp in self.kp])
self.pid._k_d = (INTERP_SPEEDS, [kp * td for kp, td in zip(self.kp, TD_INTERP, strict=True)])
def reset(self):
super().reset()
self.pid.reset()
self.swing = self.last_error = 0.0
self.command_slow.initialized = False
for f in (self.error_filter, self.error_rate_filter, self.wheel_rate_filter, self.request_rate_ref, self.break_error, self.break_rate, self.break_rate2):
f.x = 0.0
def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, calibrated_pose, curvature_limited, lat_delay):
pid_log = log.ControlsState.LateralPIDState.new_message()
pid_log.steeringAngleDeg = float(CS.steeringAngleDeg)
pid_log.steeringRateDeg = float(CS.steeringRateDeg)
high_speed = float(np.interp(CS.vEgo, HIGH_SPEED_BP, [0.0, 1.0]))
angle_steers_des_no_offset = self.request_filter.update(math.degrees(VM.get_steer_from_curvature(-desired_curvature, CS.vEgo, params.roll)))
angle_steers_des = angle_steers_des_no_offset + params.angleOffsetDeg
self.desired_angle_buffer.append(angle_steers_des)
expected_angle = self.desired_angle_buffer[-self.delay_frames]
request_rate = (self.desired_angle_buffer[-1] - self.desired_angle_buffer[-1 - self.rate_span_frames]) / (self.rate_span_frames * self.dt)
request_rate_ref = self.request_rate_ref.update(request_rate)
break_rate = self.break_rate2.update(self.break_rate.update(request_rate))
# a 1 Hz error filter lags enough for P to pump a 2 Hz wheel swing, so it opens up only while the request turns the wheel
error_filter_hz = float(np.interp(abs(request_rate_ref), TURN_RATE_BP, [1.0, 3.0]))
self.error_filter.update_alpha(filter_rc(float(np.interp(CS.vEgo, HIGH_SPEED_BP, [error_filter_hz, 1.0]))))
error = self.error_filter.update(expected_angle - CS.steeringAngleDeg)
# at highway speed, ignore the angle sensor toggling one count
held = self.wheel_angle_held if self.wheel_angle_held is not None else CS.steeringAngleDeg
wheel_backlash = 0.08 * high_speed
self.wheel_angle_held = held = CS.steeringAngleDeg - float(np.clip(CS.steeringAngleDeg - held, -wheel_backlash, wheel_backlash))
wheel_angle_last = self.wheel_angle_filter.x if self.wheel_angle_filter.initialized else held
wheel_rate = self.wheel_rate_filter.update((self.wheel_angle_filter.update(held) - wheel_angle_last) / self.dt)
wheel_swing = 0.0 if CS.steeringPressed else min(abs(wheel_rate - request_rate_ref), 60.0)
self.swing = max(wheel_swing, self.swing * (1.0 - self.dt))
pid_log.steeringAngleDesiredDeg = float(angle_steers_des)
pid_log.angleError = float(error)
if not active:
output_torque = 0.0
pid_log.active = False
self.reset()
else:
error_rate = self.error_rate_filter.update((error - self.last_error) / self.dt)
self.last_error = error
error_rate += high_speed * (-wheel_rate - error_rate)
ff = angle_steers_des_no_offset * lat_accel_per_deg(VM, CS.vEgo) / self.lat_accel_factor
ff += 0.4 * params.roll * ACCELERATION_DUE_TO_GRAVITY / self.lat_accel_factor
# break rack friction as soon as the request moves, before the error builds up
error_deadzone = error - float(np.clip(error, -0.3, 0.3))
turn_lat_accel = abs(desired_curvature) * max(CS.vEgo, 8.0) ** 2
friction_scale = float(np.interp(turn_lat_accel, TURN_LAT_ACCEL_BP, [0.6, 1.0]))
friction = self.friction * (friction_scale + high_speed * (0.1 - friction_scale))
friction_rate_gain = 0.75 - 0.25 * high_speed
ff += friction * float(np.tanh((error_deadzone + friction_rate_gain * request_rate) * 0.1887))
kp = float(np.interp(CS.vEgo, INTERP_SPEEDS, self.kp))
# damp the wheel toward the request's rate; the rack rings near 2 Hz without it
wheel_damp = 0.0 if CS.steeringPressed else (1.0 - high_speed) * kp * 0.05 * (wheel_rate - request_rate_ref)
ff -= wheel_damp
# half P on a straight, flat road; the cut goes through the feedforward so the integrator still holds a crown
kp_load = max(float(np.interp(turn_lat_accel, TURN_LAT_ACCEL_BP, [0.0, 1.0])),
float(np.interp(abs(params.roll) * ACCELERATION_DUE_TO_GRAVITY, [0.35, 0.7], [0.0, 1.0])))
kp_scale = 0.5 + 0.5 * kp_load
ff -= (1.0 - float(np.interp(CS.vEgo, [12.0, 18.0], [kp_scale, 1.0]))) * kp * error
ff += high_speed * 0.325 * self.friction * float(np.tanh((self.break_error.update(error) + 0.35 * break_rate) / 0.5))
freeze_integrator = steer_limited_by_safety or CS.steeringPressed or CS.vEgo < 5
error_rate_clean = error_rate - float(np.clip(error_rate, -0.3, 0.3))
output_torque = self.pid.update(error, error_rate=error_rate_clean, feedforward=ff, speed=CS.vEgo, freeze_integrator=freeze_integrator)
# a swing the request isn't asking for: pass only the command's slow part
command = output_torque + wheel_damp
self.command_slow.update(command)
if CS.steeringPressed:
self.command_slow.x = command
swing_gate = float(np.interp(self.swing, [16.0, 30.0], [0.0, 1.0])) * float(np.interp(CS.vEgo, [3.0, 5.0, 10.0, 14.0], [0.0, 1.0, 1.0, 0.0]))
swing_gate *= 1.0 - float(np.interp(abs(request_rate_ref), TURN_RATE_BP, [0.0, 1.0]))
swing_gate *= 1.0 - float(np.interp(turn_lat_accel, TURN_LAT_ACCEL_BP, [0.0, 1.0]))
swing_gate *= 1.0 - float(np.interp(abs(error), [3.0, 6.0], [0.0, 1.0]))
if not (CS.steeringPressed or CS.leftBlinker or CS.rightBlinker):
cap = SWING_CAP_FRICTION * self.friction
output_torque += swing_gate * float(np.clip(self.command_slow.x - command, -cap, cap))
output_torque = float(np.clip(output_torque, -self.steer_max, self.steer_max))
pid_log.active = True
pid_log.p = float(self.pid.p)
pid_log.i = float(self.pid.i)
pid_log.f = float(self.pid.f)
pid_log.output = float(output_torque)
pid_log.saturated = bool(self._check_saturation(self.steer_max - abs(output_torque) < 1e-3, CS, steer_limited_by_safety, curvature_limited))
return output_torque, angle_steers_des, pid_log
@@ -1,126 +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 math
from types import SimpleNamespace
import numpy as np
from opendbc.car.car_helpers import interfaces
from opendbc.car.honda.values import CAR as HONDA
from opendbc.car.hyundai.values import CAR as HYUNDAI
from opendbc.car.interfaces import get_torque_params
from opendbc.car.nissan.values import CAR as NISSAN
from opendbc.car.structs import car
from opendbc.car.toyota.values import CAR as TOYOTA
from opendbc.car.vehicle_model import VehicleModel
from openpilot.cereal import log
from openpilot.common.mock.generators import generate_deviceMotion
from openpilot.common.params import Params
from openpilot.common.realtime import DT_CTRL
from openpilot.common.test import OpenpilotTestCase
from openpilot.selfdrive.car.helpers import convert_to_capnp
from openpilot.selfdrive.locationd.helpers import Pose
from openpilot.selfdrive.locationd.torqued import TorqueEstimator
from openpilot.sunnypilot.selfdrive.car import interfaces as sunnypilot_interfaces
from openpilot.sunnypilot.selfdrive.controls.controlsd_ext import ControlsExt
from openpilot.sunnypilot.selfdrive.controls.lib.pidd import LatControlPidd, PIDD_VERSION
def setup_car(car_name):
CarInterface = interfaces[car_name]
CP = CarInterface.get_non_essential_params(car_name)
CP_SP = CarInterface.get_non_essential_params_sp(CP, car_name)
CI = CarInterface(CP, CP_SP)
sunnypilot_interfaces.setup_interfaces(CI)
return CI
def make_controller(CI):
return LatControlPidd(CI.CP.as_reader(), convert_to_capnp(CI.CP_SP).as_reader(), CI, DT_CTRL)
def drive(controller, CS, VM, angles, curvature=0.0):
params = log.VehicleParameters.new_message()
pose = Pose.from_device_motion(generate_deviceMotion().deviceMotion)
return [controller.update(True, CS, VM, params, False, curvature, pose, False, 0.2)[0] for CS.steeringAngleDeg in angles]
class TestPidd(OpenpilotTestCase):
def setup_method(self):
self.params = Params()
self.params.put_bool("EnforceTorqueControl", True, block=True)
self.params.put("TorqueControlTune", PIDD_VERSION, block=True)
def test_selected_on_any_torque_car(self):
for car_name in (HONDA.HONDA_CIVIC, TOYOTA.TOYOTA_RAV4, HYUNDAI.KIA_NIRO_EV):
assert setup_car(car_name).CP.lateralTuning.which() == 'pid'
def test_needs_enforce_torque(self):
self.params.remove("EnforceTorqueControl")
assert setup_car(HYUNDAI.KIA_NIRO_EV).CP.lateralTuning.which() == 'torque'
def test_not_on_angle_cars(self):
CI = setup_car(NISSAN.NISSAN_LEAF)
assert CI.CP.steerControlType == car.CarParams.SteerControlType.angle
assert not self.params.get_bool("EnforceTorqueControl")
def test_controlsd_builds_it(self):
CI = setup_car(HYUNDAI.KIA_NIRO_EV)
ext = SimpleNamespace(params=self.params, CP=CI.CP.as_reader(), CP_SP=convert_to_capnp(CI.CP_SP).as_reader())
assert isinstance(ControlsExt.initialize_lateral_control(ext, None, CI, DT_CTRL), LatControlPidd)
def test_selection_follows_car_params(self):
# params changing after card picked pidd must not leave controlsd with a pid that has no gains
CI = setup_car(HYUNDAI.KIA_NIRO_EV)
self.params.remove("EnforceTorqueControl")
self.params.put("TorqueControlTune", 1.0, block=True)
ext = SimpleNamespace(params=self.params, CP=CI.CP.as_reader(), CP_SP=convert_to_capnp(CI.CP_SP).as_reader())
assert isinstance(ControlsExt.initialize_lateral_control(ext, None, CI, DT_CTRL), LatControlPidd)
def test_damps_wheel_swing(self):
CI = setup_car(HONDA.HONDA_CIVIC)
VM = VehicleModel(CI.CP)
corr = {}
for pressed in (False, True):
controller = make_controller(CI)
CS = car.CarState.new_message(vEgo=8.0, steeringPressed=pressed)
angles = [2.0 * math.sin(2 * math.pi * 2.0 * i * DT_CTRL) for i in range(300)]
out = drive(controller, CS, VM, angles)[100:]
rate = [math.cos(2 * math.pi * 2.0 * i * DT_CTRL) for i in range(100, 300)]
corr[pressed] = float(np.corrcoef(out, rate)[0, 1])
assert corr[False] < corr[True] - 0.3
def test_output_within_steer_max(self):
CI = setup_car(HYUNDAI.KIA_NIRO_EV)
controller = make_controller(CI)
controller.pid.update = lambda *args, **kwargs: controller.steer_max
CS = car.CarState.new_message(vEgo=8.0)
out = drive(controller, CS, VehicleModel(CI.CP), [2.0 * math.sin(2 * math.pi * 2.5 * i * DT_CTRL) for i in range(500)])
assert max(abs(x) for x in out) <= controller.steer_max
def test_reset_clears_swing_gate(self):
CI = setup_car(HYUNDAI.KIA_NIRO_EV)
controller = make_controller(CI)
drive(controller, car.CarState.new_message(vEgo=8.0), VehicleModel(CI.CP), [30.0] * 200, curvature=-0.02)
controller.reset()
assert not controller.command_slow.initialized
def test_live_torque_params_rescale_gains(self):
controller = make_controller(setup_car(HYUNDAI.KIA_NIRO_EV))
kp = list(controller.kp)
controller.update_torque_parameters(2 * controller.lat_accel_factor, 0.0, controller.friction)
assert np.allclose(controller.kp, [k / 2 for k in kp])
assert np.allclose(controller.pid._k_p[1], controller.kp)
controller.update_torque_parameters(0.5 * controller.offline_lat_accel_factor, 0.0, 0.0)
assert np.allclose(controller.kp, kp)
def test_torqued_learns_under_pidd(self):
estimator = TorqueEstimator(setup_car(HYUNDAI.KIA_NIRO_EV).CP.as_reader())
offline = get_torque_params()[HYUNDAI.KIA_NIRO_EV]
self.assertAlmostEqual(estimator.offline_latAccelFactor, offline['LAT_ACCEL_FACTOR'])
self.assertAlmostEqual(estimator.offline_friction, offline['FRICTION'])
assert estimator.max_lataccel_factor > estimator.min_lataccel_factor

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