diff --git a/.github/workflows/pr_discord_reminder.yaml b/.github/workflows/pr_discord_reminder.yaml index 8a307beb49..6074f8e023 100644 --- a/.github/workflows/pr_discord_reminder.yaml +++ b/.github/workflows/pr_discord_reminder.yaml @@ -36,8 +36,9 @@ jobs: REPO = "StarPilotHQ/StarPilot" MARKER = "" BODY = ("Thank you for your PR! Once CI passes on your PR against `stable`, " - "please open a report describing it in the StarPilot Discord at " - "[https://firestar.link/discord](https://firestar.link/discord)\n\n" + MARKER) + "please open a ticket describing it in the StarPilot Discord at " + "[https://firestar.link/discord](https://firestar.link/discord). Follow the " + "[ticket instructions](https://firestar.link/logs).\n\n" + MARKER) def remind(event, request): if event.get("action") != "opened" or "pull_request" not in event: diff --git a/openpilot/selfdrive/ui/mici/onroad/__init__.py b/openpilot/selfdrive/ui/mici/onroad/__init__.py index 0af3b4676e..55e6a9c6a9 100644 --- a/openpilot/selfdrive/ui/mici/onroad/__init__.py +++ b/openpilot/selfdrive/ui/mici/onroad/__init__.py @@ -3,6 +3,18 @@ from openpilot.starpilot.ui.raylib import rl SIDE_PANEL_WIDTH = 60 +def confidence_colors(value: float, *, engaged: bool, overriding: bool) -> tuple[rl.Color, rl.Color]: + if overriding: + return rl.WHITE, rl.Color(82, 82, 82, 255) + if not engaged: + return rl.Color(50, 50, 50, 255), rl.Color(13, 13, 13, 255) + if value > 0.5: + return rl.Color(0, 255, 204, 255), rl.Color(0, 255, 38, 255) + if value > 0.2: + return rl.Color(255, 200, 0, 255), rl.Color(255, 115, 0, 255) + return rl.Color(255, 0, 21, 255), rl.Color(255, 0, 89, 255) + + def blend_colors(a: rl.Color, b: rl.Color, f: float) -> rl.Color: h0, s0, v0 = (hsv0 := rl.color_to_hsv(a)).x, hsv0.y, hsv0.z h1, s1, v1 = (hsv1 := rl.color_to_hsv(b)).x, hsv1.y, hsv1.z diff --git a/openpilot/selfdrive/ui/mici/onroad/confidence_ball.py b/openpilot/selfdrive/ui/mici/onroad/confidence_ball.py index f6ed031c27..15a8324e14 100644 --- a/openpilot/selfdrive/ui/mici/onroad/confidence_ball.py +++ b/openpilot/selfdrive/ui/mici/onroad/confidence_ball.py @@ -1,6 +1,6 @@ import math from openpilot.starpilot.ui.raylib import rl -from openpilot.selfdrive.ui.mici.onroad import SIDE_PANEL_WIDTH +from openpilot.selfdrive.ui.mici.onroad import SIDE_PANEL_WIDTH, confidence_colors from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus from openpilot.system.ui.widgets import Widget from openpilot.system.ui.lib.application import gui_app @@ -64,26 +64,10 @@ class ConfidenceBall(Widget): dot_height = (1 - self._confidence_filter.x) * (content_rect.height - 2 * status_dot_radius) + status_dot_radius dot_height = self._rect.y + dot_height - # confidence zones - if ui_state.status == UIStatus.ENGAGED or self._demo or \ - (ui_state.status == UIStatus.DISENGAGED and self._render_lateral_active): - if self._confidence_filter.x > 0.5: - top_dot_color = rl.Color(0, 255, 204, 255) - bottom_dot_color = rl.Color(0, 255, 38, 255) - elif self._confidence_filter.x > 0.2: - top_dot_color = rl.Color(255, 200, 0, 255) - bottom_dot_color = rl.Color(255, 115, 0, 255) - else: - top_dot_color = rl.Color(255, 0, 21, 255) - bottom_dot_color = rl.Color(255, 0, 89, 255) - - elif ui_state.status == UIStatus.OVERRIDE: - top_dot_color = rl.Color(255, 255, 255, 255) - bottom_dot_color = rl.Color(82, 82, 82, 255) - - else: - top_dot_color = rl.Color(50, 50, 50, 255) - bottom_dot_color = rl.Color(13, 13, 13, 255) + engaged = ui_state.status == UIStatus.ENGAGED or self._demo or ( + ui_state.status == UIStatus.DISENGAGED and self._render_lateral_active) + top_dot_color, bottom_dot_color = confidence_colors( + self._confidence_filter.x, engaged=engaged, overriding=not engaged and ui_state.status == UIStatus.OVERRIDE) draw_circle_gradient(content_rect.x + content_rect.width - status_dot_radius, dot_height, status_dot_radius, diff --git a/openpilot/starpilot/galaxy/setting_descriptions.py b/openpilot/starpilot/galaxy/setting_descriptions.py index f3659a3ca2..44bd1a30f7 100644 --- a/openpilot/starpilot/galaxy/setting_descriptions.py +++ b/openpilot/starpilot/galaxy/setting_descriptions.py @@ -407,10 +407,10 @@ def purpose(row): 'braking': 'Sets braking response at this speed. Higher values allow stronger braking.'}[category] if key.startswith(('Aggressive', 'Standard', 'Relaxed', 'Traffic')): if key == 'TrafficFollow': - return 'Sets following time at low speeds in Traffic mode, blending toward Relaxed as speed rises.' + return 'Sets following time at low speeds in Traffic mode, blending toward Aggressive as speed rises.' suffix = next((name for name in VALUE_HELP if key.endswith(name)), None) value = VALUE_HELP.get(suffix) - return value + ' Blends toward Relaxed as speed rises in Traffic mode.' if value and key.startswith('Traffic') else value + return value + ' Blends toward Aggressive as speed rises in Traffic mode.' if value and key.startswith('Traffic') else value if key in SLC_OFFSET_KEYS: return 'Adds or subtracts this offset from the accepted speed limit within the displayed speed range.' if key.startswith('long_repair:'): diff --git a/openpilot/starpilot/galaxy/tests/test_settings.mjs b/openpilot/starpilot/galaxy/tests/test_settings.mjs index e393ad8054..a890127bb0 100644 --- a/openpilot/starpilot/galaxy/tests/test_settings.mjs +++ b/openpilot/starpilot/galaxy/tests/test_settings.mjs @@ -152,7 +152,7 @@ assert.match(SettingsPage.template, /:initial-panel="state\.layoutPanel" @target assert.doesNotMatch(SettingsPage.template, /Use Colors & Layout to arrange widgets and change colors/) assert.match(SettingsPage.template, /Configure lane-change assistance, signal timing, steering pace and following gap\./) assert.match(SettingsPage.template, /Adjust acceleration, braking and following for each driving personality\./) -assert.match(SettingsPage.template, /Tune low-speed following and jerk, blending toward Relaxed at higher speeds\./) +assert.match(SettingsPage.template, /Tune low-speed following and jerk, blending toward Aggressive at higher speeds\./) const app = (await import('node:fs')).readFileSync(new URL('../web/js/app.js', import.meta.url), 'utf8') assert.match(app, /:initial-panel="route\.path === '\/appearance' \? 'display' : 'widgets'"/) const pageRows = SettingsPage.computed.visibleRows.call({ state: { data: { rows: [ diff --git a/openpilot/starpilot/galaxy/web/js/settings.js b/openpilot/starpilot/galaxy/web/js/settings.js index 622d0ec8c4..3a81a01209 100644 --- a/openpilot/starpilot/galaxy/web/js/settings.js +++ b/openpilot/starpilot/galaxy/web/js/settings.js @@ -547,7 +547,7 @@ export const SettingsPage = {

Configure lane-change assistance, signal timing, steering pace and following gap.

Choose when to switch between Chill and End to End. Applies on supported vehicles when StarPilot controls acceleration and braking.

Adjust acceleration, braking and following for each driving personality.

-

Tune low-speed following and jerk, blending toward Relaxed at higher speeds.

+

Tune low-speed following and jerk, blending toward Aggressive at higher speeds.

Keep steering assistance active independently of cruise control.

Tune how StarPilot applies steering torque.

Adjust supported steering parameters.

diff --git a/openpilot/starpilot/longitudinal/README.md b/openpilot/starpilot/longitudinal/README.md index 46f211b0df..19fef82be8 100644 --- a/openpilot/starpilot/longitudinal/README.md +++ b/openpilot/starpilot/longitudinal/README.md @@ -90,7 +90,7 @@ no profile effect. The acados model and cereal schemas are unchanged. The profile runtime accepts an explicit current Traffic-mode verdict. With Traffic known active, base follow and all five jerk values interpolate over -0–25 m/s from the Traffic value to the Relaxed low-speed value; the frozen +0–25 m/s from the Traffic value to the Aggressive base value at the same speed; the frozen Traffic defaults apply even when Custom Personalities is off. Traffic also uses the frozen seven-point acceleration ceiling and 0.42 m/s² cruise-braking magnitude as its base defaults. Selected acceleration and braking profiles diff --git a/openpilot/starpilot/longitudinal/profile_preferences.py b/openpilot/starpilot/longitudinal/profile_preferences.py index 288597900f..230a93645d 100644 --- a/openpilot/starpilot/longitudinal/profile_preferences.py +++ b/openpilot/starpilot/longitudinal/profile_preferences.py @@ -14,9 +14,9 @@ from openpilot.starpilot.saved_source import read_saved NAMES = ("aggressive", "standard", "relaxed") TRAFFIC_JERK_SUFFIXES = ("JerkAcceleration", "JerkDeceleration", "JerkSpeed", "JerkSpeedDecrease", "JerkDanger") -TRAFFIC_NUMBER_KEYS = ("TrafficFollow", "RelaxedFollow", +TRAFFIC_NUMBER_KEYS = ("TrafficFollow", "AggressiveFollow", "AggressiveFollowHigh", *("Traffic" + suffix for suffix in TRAFFIC_JERK_SUFFIXES), - *("Relaxed" + suffix for suffix in TRAFFIC_JERK_SUFFIXES)) + *("Aggressive" + suffix for suffix in TRAFFIC_JERK_SUFFIXES)) SUFFIXES = ("Follow", "FollowHigh", "JerkAcceleration", "JerkDeceleration", "JerkSpeed", "JerkSpeedDecrease", "JerkDanger") SCALARS = {name: tuple(name.title() + suffix for suffix in SUFFIXES) for name in NAMES} diff --git a/openpilot/starpilot/longitudinal/profile_runtime.py b/openpilot/starpilot/longitudinal/profile_runtime.py index 4c4b50c6b1..253aa72ff8 100644 --- a/openpilot/starpilot/longitudinal/profile_runtime.py +++ b/openpilot/starpilot/longitudinal/profile_runtime.py @@ -43,6 +43,7 @@ class TrafficSettings: profile_enabled: bool follow: tuple[float, float] jerk: tuple[tuple[float, float], ...] + aggressive_follow_high: float | None = None @dataclass(frozen=True) @@ -178,12 +179,13 @@ def read_settings(params) -> ProfileSettings | None: def read_traffic_settings(params) -> TrafficSettings: health = read_traffic_health(params) if not health.valid: - return TrafficSettings(False, health.reason, None, False, (0.75, 1.6), ()) - follow = (health.number('TrafficFollow'), health.number('RelaxedFollow')) + return TrafficSettings(False, health.reason, None, False, (0.75, 1.25), ()) + follow = (health.number('TrafficFollow'), health.number('AggressiveFollow')) jerk = tuple((health.number('Traffic' + suffix) / 100.0, - health.number('Relaxed' + suffix) / 100.0) for suffix in TRAFFIC_JERK_SUFFIXES) + health.number('Aggressive' + suffix) / 100.0) for suffix in TRAFFIC_JERK_SUFFIXES) return TrafficSettings(True, 'valid', health.document if health.master_on else None, - health.profile_enabled if health.master_on else False, follow, jerk) + health.profile_enabled if health.master_on else False, follow, jerk, + health.number('AggressiveFollowHigh') if health.master_on else None) def _traffic_value(points: tuple[float, float], speed: float) -> float: @@ -191,6 +193,15 @@ def _traffic_value(points: tuple[float, float], speed: float) -> float: return float(points[0] + (points[1] - points[0]) * ratio) +def traffic_follow_seconds(settings: TrafficSettings, speed: float) -> float: + low, aggressive = settings.follow + if settings.aggressive_follow_high is not None: + start, end = LEGACY_FOLLOW_BP + ratio = min(max((speed - start) / (end - start), 0.0), 1.0) + aggressive += (settings.aggressive_follow_high - aggressive) * ratio + return _traffic_value((low, aggressive), speed) + + def resolve(settings: ProfileSettings | TrafficSettings | None, personality, v_ego: float, CP, *, traffic_mode: bool | None = False) -> ProfileTuning | None: if settings is None or type(traffic_mode) is not bool or not math.isfinite(v_ego) or v_ego < 0: @@ -199,7 +210,7 @@ def resolve(settings: ProfileSettings | TrafficSettings | None, personality, v_e if traffic_mode: if not isinstance(settings, TrafficSettings) or not settings.valid or len(settings.jerk) != 5: return None - follow = _traffic_value(settings.follow, v_ego) + follow = traffic_follow_seconds(settings, v_ego) acceleration_max = interpolate_accel_profile(v_ego, A_CRUISE_MAX_VALS_TRAFFIC_ALL) cruise_brake_magnitude = TRAFFIC_CRUISE_BRAKE_MAGNITUDE traffic_braking_custom = False diff --git a/openpilot/starpilot/longitudinal/tests/test_profile_runtime.py b/openpilot/starpilot/longitudinal/tests/test_profile_runtime.py index a105cdd647..17db824ac0 100644 --- a/openpilot/starpilot/longitudinal/tests/test_profile_runtime.py +++ b/openpilot/starpilot/longitudinal/tests/test_profile_runtime.py @@ -66,14 +66,15 @@ class ProfileRuntimeTests(unittest.TestCase): settings = read_traffic_settings(self.params) self.assertTrue(settings.valid) self.assertFalse(settings.profile_enabled) - for speed, expected in ((0.0, 0.75), (12.5, 1.175), (25.0, 1.6), (30.0, 1.6)): + for speed, expected in ((0.0, 0.75), (12.5, 1.0), (25.0, 1.25), (30.0, 1.25)): with self.subTest(speed=speed): tuning = resolve(settings, log.LongitudinalPersonality.aggressive, speed, self.cp, traffic_mode=True) assert tuning is not None self.assertEqual(tuning.personality_id, 'traffic') self.assertAlmostEqual(tuning.follow_seconds, expected) + jerk = 1.0 - 0.5 * min(speed / 25.0, 1.0) self.assertEqual((tuning.acceleration_jerk, tuning.deceleration_jerk, tuning.speed_jerk, - tuning.speed_decrease_jerk, tuning.danger_jerk), (1.0,) * 5) + tuning.speed_decrease_jerk, tuning.danger_jerk), (jerk, jerk, jerk, jerk, 1.0)) self.assertAlmostEqual(required_float(tuning.cruise_brake_magnitude), 0.42) for speed, expected in ((0.0, 1.10), (5.0, 0.87), (10.0, 0.67), (12.5, 0.60), (15.0, 0.53), (20.0, 0.44), (25.0, 0.34), (40.0, 0.23)): @@ -83,7 +84,7 @@ class ProfileRuntimeTests(unittest.TestCase): self.assertAlmostEqual(required_float(tuning.acceleration_max), expected) host = ProfileHost(self.params) self.assertAlmostEqual(require_value(host.sample(1_000_000_000, log.LongitudinalPersonality.aggressive, - 12.5, self.cp, traffic_mode=True)).follow_seconds, 1.175) + 12.5, self.cp, traffic_mode=True)).follow_seconds, 1.0) self.assertIsNone(host.sample(1_010_000_000, log.LongitudinalPersonality.aggressive, 12.5, self.cp, traffic_mode=None)) self.assertIsNone(ProfileSmoother().sample(None, log.LongitudinalPersonality.standard, 0.05, traffic_mode=None)) @@ -127,10 +128,13 @@ class ProfileRuntimeTests(unittest.TestCase): def test_traffic_saved_jerk_and_follow_interpolate_on_0_to_25_mps(self): self.params.put_bool('CustomPersonalities', True, block=True) self.params.put('TrafficFollow', 0.9, block=True) - self.params.put('RelaxedFollow', 1.7, block=True) + self.params.put('RelaxedFollow', 2.1, block=True) + self.params.put('AggressiveFollow', 1.7, block=True) + self.params.put('AggressiveFollowHigh', 1.7, block=True) for suffix in ('JerkAcceleration', 'JerkDeceleration', 'JerkSpeed', 'JerkSpeedDecrease', 'JerkDanger'): self.params.put('Traffic' + suffix, 150.0, block=True) - self.params.put('Relaxed' + suffix, 50.0, block=True) + self.params.put('Relaxed' + suffix, 175.0, block=True) + self.params.put('Aggressive' + suffix, 50.0, block=True) settings = read_traffic_settings(self.params) self.assertTrue(settings.valid) for speed, follow, jerk in ((0.0, 0.9, 1.5), (12.5, 1.3, 1.0), @@ -142,6 +146,11 @@ class ProfileRuntimeTests(unittest.TestCase): for component in (tuning.acceleration_jerk, tuning.deceleration_jerk, tuning.speed_jerk, tuning.speed_decrease_jerk, tuning.danger_jerk): self.assertAlmostEqual(component, jerk) + self.params.put('AggressiveFollowHigh', 1.0, block=True) + settings = read_traffic_settings(self.params) + fast = resolve(settings, log.LongitudinalPersonality.relaxed, 40.0, self.cp, traffic_mode=True) + assert fast is not None + self.assertAlmostEqual(fast.follow_seconds, 1.0) profiles = default_personality_profiles(False) profiles['traffic']['following'] = {'preset': 'custom', 'curve': [2.25] * 10} self.params.put('LongitudinalPersonalityProfiles', legacy_document(profiles, enabled=True), block=True) @@ -252,7 +261,7 @@ class ProfileRuntimeTests(unittest.TestCase): self.params.put('TrafficFollow', 0.5, block=True) half_second = host.sample(1_030_000_000, log.LongitudinalPersonality.standard, 12.5, self.cp, traffic_mode=True) assert half_second is not None - self.assertAlmostEqual(half_second.follow_seconds, 1.05) + self.assertAlmostEqual(half_second.follow_seconds, 0.875) def test_traffic_smoother_rejects_invalid_target_and_starts_from_native_personality(self): smoother = ProfileSmoother() @@ -261,7 +270,7 @@ class ProfileRuntimeTests(unittest.TestCase): assert target is not None first = smoother.sample(target, log.LongitudinalPersonality.standard, 0.05, traffic_mode=True) assert first is not None - self.assertAlmostEqual(first.follow_seconds, 1.50) # Ordinary standard starts at 1.45 s. + self.assertAlmostEqual(first.follow_seconds, 1.40) # Ordinary standard starts at 1.45 s. self.assertGreaterEqual(first.follow_seconds, min(1.45, target.follow_seconds)) invalid = ProfileTuning('traffic', 0.49, 1.0, 1.0, 1.0, 1.0, 1.0) self.assertIsNone(smoother.sample(invalid, log.LongitudinalPersonality.standard, 0.05, diff --git a/openpilot/starpilot/ui/feature_profile_edit.py b/openpilot/starpilot/ui/feature_profile_edit.py index 87d55aa521..69cd2dfa40 100644 --- a/openpilot/starpilot/ui/feature_profile_edit.py +++ b/openpilot/starpilot/ui/feature_profile_edit.py @@ -7,7 +7,7 @@ from typing import TYPE_CHECKING from opendbc.car.structs import car from openpilot.starpilot.longitudinal.accel_profile import A_CRUISE_MAX_VALS_TRAFFIC_ALL, interpolate_accel_profile -from openpilot.starpilot.longitudinal.profile_runtime import TRAFFIC_CRUISE_BRAKE_MAGNITUDE +from openpilot.starpilot.longitudinal.profile_runtime import TRAFFIC_CRUISE_BRAKE_MAGNITUDE, read_traffic_settings, traffic_follow_seconds from openpilot.starpilot.longitudinal.profile_document import ( ACCELERATION_PRESETS, ACCELERATION_SPEEDS_MPH, BRAKING_PRESETS, FOLLOWING_PRESETS, CURVE_BOUNDS, DEFAULT_DECELERATION_PROFILE, MAX_EXTRA_STOPPED_GAP_M, default_personality_profiles, initial_custom_curve, @@ -92,12 +92,10 @@ def edit_document(self: FeatureSettingsOwner, key: str, value: str, *, seed_capa elif category == "braking": reference = [round(TRAFFIC_CRUISE_BRAKE_MAGNITUDE, 4)] * len(ACCELERATION_SPEEDS_MPH) else: - source = dict(self.traffic_profiles._sources()[0]) - low, low_valid = self.traffic_profiles._value("TrafficFollow", source["TrafficFollow"]) - high, high_valid = self.traffic_profiles._value("RelaxedFollow", source["RelaxedFollow"]) - if not low_valid or not high_valid or low is None or high is None: + traffic = read_traffic_settings(self.params) + if not traffic.valid: return None - reference = [round(low + (high - low) * min(speed * MPH_TO_MPS / 25.0, 1.0), 4) + reference = [round(traffic_follow_seconds(traffic, speed * MPH_TO_MPS), 4) for speed in FOLLOWING_SPEEDS_MPH] else: low, high = CURVE_BOUNDS[category] diff --git a/openpilot/starpilot/ui/feature_settings_owner.py b/openpilot/starpilot/ui/feature_settings_owner.py index 105ade7da4..962b2c49ad 100644 --- a/openpilot/starpilot/ui/feature_settings_owner.py +++ b/openpilot/starpilot/ui/feature_settings_owner.py @@ -1381,7 +1381,7 @@ class FeatureSettingsOwner: default_curve = [TRAFFIC_CRUISE_BRAKE_MAGNITUDE] * len(ACCELERATION_SPEEDS_MPH) else: low = float(self.params.get_default_value("TrafficFollow")) - high = float(self.params.get_default_value("RelaxedFollow")) + high = float(self.params.get_default_value("AggressiveFollow")) default_curve = [low + (high - low) * min(speed * MPH_TO_MPS / 25.0, 1.0) for speed in FOLLOWING_SPEEDS_MPH] for index, speed in enumerate(range(0, 91, 10)): diff --git a/openpilot/starpilot/ui/onroad_alerts.py b/openpilot/starpilot/ui/onroad_alerts.py index ba08a77bbb..e41588aa7a 100644 --- a/openpilot/starpilot/ui/onroad_alerts.py +++ b/openpilot/starpilot/ui/onroad_alerts.py @@ -64,7 +64,8 @@ class AlertRenderer: text1, text2 = alert.text1, alert.text2 if event_name == 'personalityChanged' and text1.lower().startswith('driving personality: '): text1, text2 = text1[len('driving personality: '):], 'Driving Personality' - alert = replace(alert, text1=DisplayText(tr(text1)), text2=DisplayText(tr(text2))) + if text1 or text2: + alert = replace(alert, text1=DisplayText(tr(text1)), text2=DisplayText(tr(text2))) if self.fonts.profile == Profile.COMPACT: lane_event = event_name in ('preLaneChangeLeft', 'preLaneChangeRight', 'laneChangeBlocked', 'laneChange', 'steerTempUnavailable', 'steerTempUnavailableSilent') diff --git a/openpilot/starpilot/ui/onroad_compact_widgets.py b/openpilot/starpilot/ui/onroad_compact_widgets.py index dc99ed03a3..bb3e9ead83 100644 --- a/openpilot/starpilot/ui/onroad_compact_widgets.py +++ b/openpilot/starpilot/ui/onroad_compact_widgets.py @@ -13,7 +13,7 @@ from openpilot.starpilot.ui.raylib import rl from opendbc.car.structs import car from openpilot.common.filter_simple import FirstOrderFilter -from openpilot.selfdrive.ui.mici.onroad import blend_colors +from openpilot.selfdrive.ui.mici.onroad import confidence_colors from openpilot.starpilot.ui.onroad_customization import offset as widget_offset, placement, rgba, widget_size from openpilot.starpilot.ui.onroad_state import AlertSize, ObservationKind, OnroadState, is_lane_change_notice, manual_slc_confirmation from openpilot.starpilot.ui.onroad_curve import controlling as curve_controlling @@ -103,38 +103,6 @@ def compact_wheel_warning(state: OnroadState) -> bool: return alert.user_prompt or alert.visual_alert == car.CarControl.HUDControl.VisualAlert.steerRequired -class CompactStatusFade: - def __init__(self, time_constant: float): - self._time_constant = time_constant - self.reset() - - def reset(self) -> None: - self._last_ns = self._override_ns = 0 - self._drive_frame: int | None = None - self._amount = 0.0 - - def update(self, state: OnroadState, active: bool) -> float: - now = state.observed_ns - if not active: - self.reset() - return 0.0 - if not now: - return float(not state.driver_override_active) - if state.drive_frame != self._drive_frame or now < self._last_ns: - self.reset() - self._drive_frame = state.drive_frame - if state.driver_override_active: - self._override_ns = now - enabled = not self._override_ns or now - self._override_ns >= 300_000_000 - if not enabled or not self._last_ns: - self._amount = float(enabled) - else: - fade_start = max(self._last_ns, self._override_ns + 300_000_000) if self._override_ns else self._last_ns - self._amount += (1.0 - self._amount) * (1.0 - math.exp(-(now - fade_start) / 1e9 / self._time_constant)) - self._last_ns = now - return self._amount - - class CompactHudRenderer: """Transient compact MAX, detached speed-limit sign and native steering wheel.""" @@ -281,8 +249,8 @@ class MiciSidebarWidgets: def __init__(self, fonts: BitmapFonts | None = None): self.fonts = fonts self.personality = PersonalityWidget(fonts) - self._confidence_filter = FirstOrderFilter(-0.5, 0.5, 1 / 60) - self._confidence_tint = CompactStatusFade(0.1) + from openpilot.system.ui.lib.application import gui_app + self._confidence_filter = FirstOrderFilter(-0.5, 0.5, 1 / gui_app.target_fps) self._confidence_drive_frame: int | None = None self._confidence_stamp_ns: int | None = None @@ -333,13 +301,15 @@ class MiciSidebarWidgets: 'cem_curve': 'curve', 'cem_signal': 'turn', 'cem_speed': 'speed', 'cem_open_road': 'speed', 'cem_speed_limit': 'speed', 'ccm_speed': 'speed'}.get(reason) if family == 'E2E': - icon = {'Lead vehicle': 'lead', 'Curve': 'curve'}.get(state.e2e_slowdown) + icon = {'Lead vehicle': 'lead', 'Curve': 'curve', 'Slowing': 'slowdown'}.get(state.e2e_slowdown) if icon == 'stop': self._stop_icon(center) elif icon == 'lead': self._lead_icon(center) elif icon == 'curve': self._curve_icon(center) + elif icon == 'slowdown': + self._slowdown_icon(center) elif icon == 'turn': self._turn_icon(center, state) elif icon == 'speed': @@ -354,28 +324,19 @@ class MiciSidebarWidgets: def _confidence_ball(self, rect: rl.Rectangle, state: OnroadState) -> None: radius = 18 center_x, center_y = rect.x + rect.width / 2, rect.y + rect.height / 2 - active = (state.lateral_active or state.longitudinal_active) and (state.alert.size == AlertSize.NONE or is_lane_change_notice(state.alert)) stamp = state.stock_confidence_source_stamp_ns if state.stock_confidence_source_fresh else None - if (stamp is None or state.model_confidence is None or state.stock_confidence_drive_frame != self._confidence_drive_frame or - self._confidence_stamp_ns is not None and (stamp < self._confidence_stamp_ns or stamp - self._confidence_stamp_ns > 200_000_000)): + value = state.model_confidence if stamp is not None else None + if (value is None or state.stock_confidence_drive_frame != self._confidence_drive_frame or + self._confidence_stamp_ns is not None and stamp is not None and + (stamp < self._confidence_stamp_ns or stamp - self._confidence_stamp_ns > 200_000_000)): self._confidence_filter.x = -0.5 - self._confidence_tint.reset() self._confidence_drive_frame = state.stock_confidence_drive_frame self._confidence_stamp_ns = stamp - visible = active and stamp is not None and state.model_confidence is not None - tint = self._confidence_tint.update(state, visible) - if visible and state.model_confidence is not None: - confidence = self._confidence_filter.update(state.model_confidence) - if confidence > 0.5: - top, bottom = rl.Color(0, 255, 204, 255), rl.Color(0, 255, 38, 255) - elif confidence > 0.2: - top, bottom = rl.Color(255, 200, 0, 255), rl.Color(255, 115, 0, 255) - else: - top, bottom = rl.Color(255, 0, 21, 255), rl.Color(255, 0, 89, 255) - top = blend_colors(rl.WHITE, top, tint) - bottom = blend_colors(rl.Color(82, 82, 82, 255), bottom, tint) - else: - top, bottom = rl.Color(50, 50, 50, 255), rl.Color(13, 13, 13, 255) + engaged = state.model_confidence_engaged or state.lateral_active + overriding = state.model_confidence_overriding + target = value if value is not None and (engaged or overriding) else -0.5 + confidence = self._confidence_filter.update(target) + top, bottom = confidence_colors(confidence, engaged=value is not None and engaged, overriding=value is not None and overriding) rl.draw_rectangle_gradient_v(int(center_x - radius), int(center_y - radius), 2 * radius, 2 * radius, top, bottom) outer = math.ceil(radius * math.sqrt(2)) + 1 rl.draw_ring(rl.Vector2(int(center_x), int(center_y)), radius, outer, 0, 360, 20, rl.BLACK) @@ -391,9 +352,10 @@ class MiciSidebarWidgets: def _slowdown_icon(self, rect: rl.Rectangle) -> None: cx, cy = rect.x + rect.width / 2, rect.y + rect.height / 2 - blue = rl.Color(112, 192, 216, 255) - _line(cx - 12, cy - 5, cx, cy + 7, blue, 4) - _line(cx, cy + 7, cx + 12, cy - 5, blue, 4) + amber = rl.Color(255, 155, 63, 255) + _line(cx, cy - 13, cx, cy + 13, amber, 4) + _line(cx - 11, cy + 2, cx, cy + 13, amber, 4) + _line(cx, cy + 13, cx + 11, cy + 2, amber, 4) def _stop_icon(self, rect: rl.Rectangle) -> None: draw_stop_light_icon(rect) diff --git a/openpilot/starpilot/ui/onroad_personality.py b/openpilot/starpilot/ui/onroad_personality.py index 37cedd7f69..12072ed575 100644 --- a/openpilot/starpilot/ui/onroad_personality.py +++ b/openpilot/starpilot/ui/onroad_personality.py @@ -56,16 +56,15 @@ class PersonalityWidget: driver_feedback = profile == Profile.LARGE or state.appearance.wheel_pedal_feedback self.draw(rect, personality=state.personality, has_lead=state.lead_detected, longitudinal_active=state.cruise_active, traffic_mode=state.traffic_selected or state.traffic_mode, - gas_override=state.gas_pressed_override and driver_feedback, visible=routine, - white_disengaged=profile == Profile.COMPACT) + gas_override=state.gas_pressed_override and driver_feedback, visible=routine) def draw(self, rect: rl.Rectangle, *, personality: int, has_lead: bool, longitudinal_active: bool, - traffic_mode: bool = False, gas_override: bool = False, visible: bool = True, fit: bool = True, white_disengaged: bool = False) -> None: + traffic_mode: bool = False, gas_override: bool = False, visible: bool = True, fit: bool = True) -> None: self._prepare() assert self._lead_car is not None alpha = self._alpha_filter.update(visible) engaged_lead = has_lead and longitudinal_active - white_target = 0.0 if engaged_lead else (1.0 if has_lead or white_disengaged and not longitudinal_active else 0.35) + white_target = 0.0 if engaged_lead else (1.0 if has_lead else 0.35) white_f, green_f = self._lead_car_filters if not longitudinal_active: white_f.x, green_f.x = white_target, 0.0 diff --git a/openpilot/starpilot/ui/onroad_state.py b/openpilot/starpilot/ui/onroad_state.py index 9e7ae3b434..03ab390800 100644 --- a/openpilot/starpilot/ui/onroad_state.py +++ b/openpilot/starpilot/ui/onroad_state.py @@ -220,6 +220,8 @@ class OnroadState: stock_confidence_source_stamp_ns: int | None = None stock_confidence_drive_frame: int | None = None model_confidence: float | None = None + model_confidence_engaged: bool = False + model_confidence_overriding: bool = False lead_indicator_source_fresh: bool = False force_stop: bool = False # Force Stop is braking for, or holding at, a stop customization: dict = field(default_factory=default_document) diff --git a/openpilot/starpilot/ui/onroad_widget_style.py b/openpilot/starpilot/ui/onroad_widget_style.py index e9d627c285..dad43e0e23 100644 --- a/openpilot/starpilot/ui/onroad_widget_style.py +++ b/openpilot/starpilot/ui/onroad_widget_style.py @@ -31,12 +31,16 @@ def scrim_alpha(y: float) -> int: return round(SCRIM_ALPHA * (1 - t * t * t * (t * (6 * t - 15) + 10))) +_SCRIM_ROWS = [SCRIM_END * i // SCRIM_STEPS for i in range(SCRIM_STEPS + 1)] +_SCRIM_BANDS = tuple((top, bottom - top, rl.Color(0, 0, 0, scrim_alpha(top)), rl.Color(0, 0, 0, scrim_alpha(bottom))) + for top, bottom in zip(_SCRIM_ROWS, _SCRIM_ROWS[1:], strict=False)) + + def draw_top_scrim(rect: rl.Rectangle) -> None: """Darken the top of the camera view so the white HUD reads over bright skies.""" - rows = [SCRIM_END * i // SCRIM_STEPS for i in range(SCRIM_STEPS + 1)] - for top, bottom in zip(rows, rows[1:], strict=False): - rl.draw_rectangle_gradient_v(int(rect.x), int(rect.y) + top, int(rect.width), bottom - top, - rl.Color(0, 0, 0, scrim_alpha(top)), rl.Color(0, 0, 0, scrim_alpha(bottom))) + x, y, width = int(rect.x), int(rect.y), int(rect.width) + for top, height, upper, lower in _SCRIM_BANDS: + rl.draw_rectangle_gradient_v(x, y + top, width, height, upper, lower) def roundness_for(rect: rl.Rectangle, radius: float = CONTROL_RADIUS) -> float: diff --git a/openpilot/starpilot/ui/presentation.py b/openpilot/starpilot/ui/presentation.py index d38aba8cb4..313eaad644 100644 --- a/openpilot/starpilot/ui/presentation.py +++ b/openpilot/starpilot/ui/presentation.py @@ -115,6 +115,7 @@ class BitmapFonts: self._fonts: dict[str, rl.Font] = {} self._language_fonts: dict[str, rl.Font] = {} self._language_chars: set[str] = set() + self._resolved: dict[tuple, tuple[str, rl.Font, float, float]] = {} self._measurements: dict[tuple, TextSize] = {} self._vertical_ink: dict[tuple, tuple[float, float]] = {} self._horizontal_ink: dict[tuple, tuple[float, float]] = {} @@ -171,6 +172,7 @@ class BitmapFonts: rl.unload_font(previous) fonts.clear() self._language_chars = chars + self._resolved.clear() self._measurements.clear() self._vertical_ink.clear() self._horizontal_ink.clear() @@ -179,6 +181,18 @@ class BitmapFonts: rl.set_texture_filter(font.texture, rl.TextureFilter.TEXTURE_FILTER_TRILINEAR) return fonts[language] + def _resolve(self, text: str, role: FontRole, fallback: bool = False) -> tuple[str, rl.Font, float, float]: + """The drawn text, its font and optical style, cached per language until the atlas is rebuilt.""" + key = multilang.language, type(text), text, role, fallback # final DisplayText equals its source string + resolved = self._resolved.get(key) + if resolved is None: + shown = text if role == FontRole.BRAND else native_text(tr(text)) + font = self._text_font(shown, role, fallback) + if len(self._resolved) >= 1024: + self._resolved.clear() + resolved = self._resolved[key] = (shown, font, *self._optical_style(role, fallback)) + return resolved + def _optical_style(self, role: FontRole, fallback: bool = False) -> tuple[float, float]: if fallback: return 1., 0. @@ -189,10 +203,8 @@ class BitmapFonts: return 1., 0. def measure(self, text: str, role: FontRole, size: float, *, spacing: float = 0, fallback: bool = False) -> TextSize: - text = native_text(tr(text)) if role != FontRole.BRAND else text - font = self._text_font(text, role, fallback) + text, font, width_scale, weight = self._resolve(text, role, fallback) spacing = round(spacing, 4) - width_scale, weight = self._optical_style(role, fallback) key = font.texture.id, text, size, spacing, width_scale, weight if key not in self._measurements: measured = rl.measure_text_ex(font, text, size * self.profile.font_scale, spacing) # noqa: TID251 @@ -211,10 +223,9 @@ class BitmapFonts: def vertical_ink(self, text: str, role: FontRole, size: float) -> tuple[float, float]: """Visible glyph top/bottom, independent of the font's padded line box.""" - text = native_text(tr(text)) if role != FontRole.BRAND else text + text, font, _, _ = self._resolve(text, role) key = (text, role, size) if key not in self._vertical_ink: - font = self._text_font(text, role) glyphs = [rl.get_glyph_index(font, ord(char)) for char in text if not char.isspace()] scale = size * self.profile.font_scale / font.baseSize top = min((font.glyphs[index].offsetY for index in glyphs), default=0) @@ -226,11 +237,9 @@ class BitmapFonts: def horizontal_ink(self, text: str, role: FontRole, size: float) -> tuple[float, float]: """Visible glyph left/right from the draw x, without the font's side bearings.""" - text = native_text(tr(text)) if role != FontRole.BRAND else text + text, font, width_scale, weight = self._resolve(text, role) key = (text, role, size) if key not in self._horizontal_ink: - font = self._text_font(text, role) - width_scale, weight = self._optical_style(role) scale = size * self.profile.font_scale / font.baseSize left = right = None x = 0. @@ -275,10 +284,8 @@ class BitmapFonts: def draw(self, text: str, role: FontRole, size: float, x: float, y: float, color: rl.Color = rl.WHITE, *, spacing: float = 0, fallback: bool = False) -> None: - text = native_text(tr(text)) if role != FontRole.BRAND else text - font = self._text_font(text, role, fallback) + text, font, width_scale, weight = self._resolve(text, role, fallback) draw = getattr(rl, "_orig_draw_text_ex", rl.draw_text_ex) - width_scale, weight = self._optical_style(role, fallback) if width_scale == 1. and weight == 0.: draw(font, text, rl.Vector2(x, y), size * self.profile.font_scale, spacing, color) return @@ -304,6 +311,7 @@ class BitmapFonts: self._glyph_ink.clear() self._codepoints.clear() self._measurements.clear() + self._resolved.clear() def __enter__(self): return self diff --git a/openpilot/starpilot/ui/runtime_snapshot.py b/openpilot/starpilot/ui/runtime_snapshot.py index 4b5fd627a5..efd9323b8d 100644 --- a/openpilot/starpilot/ui/runtime_snapshot.py +++ b/openpilot/starpilot/ui/runtime_snapshot.py @@ -892,6 +892,8 @@ class RuntimeSnapshotAdapter: stock_confidence_source_stamp_ns=int(sm.logMonoTime["modelV2"]) if display_model is not None else None, stock_confidence_drive_frame=after if started else None, model_confidence=_model_confidence(display_model), + model_confidence_engaged=bool(getattr(display_selfdrive, 'enabled', False)), + model_confidence_overriding=str(getattr(display_selfdrive, 'state', '')) in ('preEnabled', 'overriding'), lead_indicator_source_fresh=display_model is not None and display_radar is not None, force_stop=bool(display_force_stop is not None and (display_force_stop.forceStopBraking or display_force_stop.forceStopHolding))) diff --git a/openpilot/starpilot/ui/settings.py b/openpilot/starpilot/ui/settings.py index 4e42ae2e6f..c4d2f2b626 100644 --- a/openpilot/starpilot/ui/settings.py +++ b/openpilot/starpilot/ui/settings.py @@ -36,6 +36,7 @@ class SettingsView: def _large(self, state: SettingsState): draw_settings_header(self.fonts, state.sidebar_expanded, "StarPilot", back=True) + icons = [] for (_, title, icon), bounds in zip(TILES, tile_rects(state), strict=True): rect = rl.Rectangle(*bounds) draw_hud_background(rect, ACCENT) @@ -44,8 +45,10 @@ class SettingsView: text_scale = max(0.82, min(1.12, min(rect.width / 360, rect.height / 205))) size = max(44, round(50 * text_scale)) top = rect.y + max(0, (rect.height - ICON_SIZE - 8 - size) / 2) - self.assets.icon(icon, rect.x + (rect.width - ICON_SIZE) / 2, top, ICON_SCALE, ICON_COLOR) + icons.append((icon, rect.x + (rect.width - ICON_SIZE) / 2, top)) self._fit_title(title, rect.x + 16, top + ICON_SIZE + 8, rect.width - 32, size) + # Drawing icons after the titles is safe because the title sits below the icon's box. + self.assets.icons(icons, ICON_SCALE, ICON_COLOR) self.render_rail(state) def _fit_title(self, text, x, y, width, size): diff --git a/openpilot/starpilot/ui/settings_assets.py b/openpilot/starpilot/ui/settings_assets.py index cc3025b08d..edd1bfc096 100644 --- a/openpilot/starpilot/ui/settings_assets.py +++ b/openpilot/starpilot/ui/settings_assets.py @@ -92,14 +92,16 @@ class SettingsAssets: raise self._icons[key] = target - def icon(self, name: str, x: float, y: float, scale: float, color: rl.Color) -> None: - target = self._icons[(name, scale, color.r, color.g, color.b, color.a)] + def icons(self, placed: list[tuple[str, float, float]], scale: float, color: rl.Color) -> None: + """Draw prepared (name, x, y) icons in one premultiplied pass, since each blend change flushes Raylib's batch.""" padding = max(1, math.ceil(3 * scale)) - width, height = target.texture.width, target.texture.height rl.begin_blend_mode(rl.BlendMode.BLEND_ALPHA_PREMULTIPLY) try: - rl.draw_texture_pro(target.texture, rl.Rectangle(0, 0, width, -height), - rl.Rectangle(x - padding, y - padding, width, height), rl.Vector2(0, 0), 0, rl.WHITE) + for name, x, y in placed: + target = self._icons[(name, scale, color.r, color.g, color.b, color.a)] + width, height = target.texture.width, target.texture.height + rl.draw_texture_pro(target.texture, rl.Rectangle(0, 0, width, -height), + rl.Rectangle(x - padding, y - padding, width, height), rl.Vector2(0, 0), 0, rl.WHITE) finally: rl.end_blend_mode() diff --git a/openpilot/starpilot/ui/settings_geometry.py b/openpilot/starpilot/ui/settings_geometry.py index 5f738c6d13..836019954a 100644 --- a/openpilot/starpilot/ui/settings_geometry.py +++ b/openpilot/starpilot/ui/settings_geometry.py @@ -225,7 +225,12 @@ def draw_constellation_nodes( rl.draw_circle(nx, ny, max(1.0, core_r), rl.Color(col.r, col.g, col.b, min(255, ca))) def constellation(title, rect): - rng = random.Random(f"{title}:{int(rect.x)}:{int(rect.y)}") + return _constellation(title, int(rect.x), int(rect.y)) + + +@lru_cache(maxsize=128) +def _constellation(title: str, x: int, y: int) -> tuple[list[dict], list[tuple[int, int]]]: + rng = random.Random(f"{title}:{x}:{y}") return _build_constellation_nodes(rng, 3 + rng.randint(0, 2), _CONST_REGIONS_TILE, r_min=0.05, r_max=0.11, min_sep=0.07, x_margin=0.04, y_margin=0.04) diff --git a/openpilot/starpilot/ui/tests/test_long_indicator.py b/openpilot/starpilot/ui/tests/test_long_indicator.py index bb46691aac..c57dacc0d1 100644 --- a/openpilot/starpilot/ui/tests/test_long_indicator.py +++ b/openpilot/starpilot/ui/tests/test_long_indicator.py @@ -44,10 +44,23 @@ def test_same_selected_bars_and_lead_on_both_profiles(display, profile, personal draws = settle(display, road(personality=personality)) assert draws[1].args[3] > .999 assert all(draws[2 + 2*i].args[3] == pytest.approx(.9 if i <= personality else .35, abs=.001) for i in range(3)) - for has_lead, active, white, green in ((False, True, .35, 0), (True, False, 1, 0), (True, True, 0, 1)): - draws = settle(display, road(lead_detected=has_lead, longitudinal_active=active)) - assert draws[0].args[3] == pytest.approx(white, abs=.001) - assert draws[1].args[3] == pytest.approx(green, abs=.001) + + +@pytest.mark.parametrize('profile', list(Profile)) +@pytest.mark.parametrize(('lateral', 'longitudinal', 'has_lead', 'white', 'green'), ( + pytest.param(False, False, False, .35, 0., id='disengaged-no-lead'), + pytest.param(False, False, True, 1., 0., id='disengaged-lead'), + pytest.param(True, False, False, .35, 0., id='aol-no-lead'), + pytest.param(True, False, True, 1., 0., id='aol-lead'), + pytest.param(True, True, False, .35, 0., id='longitudinal-no-lead'), + pytest.param(True, True, True, 0., 1., id='longitudinal-lead'), +)) +def test_lead_feedback_tracks_detection_and_longitudinal_engagement(display, profile, lateral, longitudinal, has_lead, white, green): + display.fonts.profile = profile + draws = settle(display, road(engaged=lateral or longitudinal, lateral_active=lateral, + longitudinal_active=longitudinal, lead_detected=has_lead)) + assert draws[0].args[3] == pytest.approx(white, abs=.001) + assert draws[1].args[3] == pytest.approx(green, abs=.001) @pytest.mark.parametrize('traffic', (False, True)) @@ -235,7 +248,7 @@ def test_default_compact_lead_and_distance_feedback(display, monkeypatch): settle(display, state) assert display._draw_centered.call_args_list[-8].args[3] == pytest.approx(.35) settle(display, replace(state, longitudinal_active=False)) - assert display._draw_centered.call_args_list[-8].args[3] == pytest.approx(1.) + assert display._draw_centered.call_args_list[-8].args[3] == pytest.approx(.35) settle(display, replace(state, lead_detected=True)) assert display._draw_centered.call_args_list[-7].args[3] == pytest.approx(1., abs=.001) diff --git a/openpilot/starpilot/ui/tests/test_onroad_axes.py b/openpilot/starpilot/ui/tests/test_onroad_axes.py index 96474577b3..544bb3a255 100644 --- a/openpilot/starpilot/ui/tests/test_onroad_axes.py +++ b/openpilot/starpilot/ui/tests/test_onroad_axes.py @@ -409,8 +409,11 @@ class TestOnroadAxes(unittest.TestCase): with patch.multiple(sidebar, **{name: Mock() for name in ('_stop_icon', '_slowdown_icon', '_lead_icon', '_curve_icon', '_chill_icon', '_speed_icon')}): sidebar._conditional(center, state) - getattr(sidebar, expected).assert_called_once() + getattr(sidebar, expected).assert_called_once_with(center) sidebar._speed_icon.assert_not_called() + if expected == '_slowdown_icon': + sidebar._conditional(center, replace(state, alert=OnroadAlert(size=AlertSize.FULL))) + sidebar._slowdown_icon.assert_called_once_with(center) sm.put('modelV2', NS(action=NS(shouldStop=True, desiredAcceleration=-0.5))) sm.valid['modelV2'] = False self.assertIsNone(self.state(True, False).e2e_preview_slowdown) @@ -418,27 +421,38 @@ class TestOnroadAxes(unittest.TestCase): sm['selfdriveState'].experimentalMode = False self.assertIsNone(self.state(True, False).e2e_preview_slowdown) - def test_end_to_end_sidebar_uses_a_moon_until_the_planner_reports_a_specific_reason(self): + def test_end_to_end_sidebar_uses_the_active_slowdown_reason(self): self.ui.params.put('ConditionalModeConfig', json.loads(encode_preferences(SavedPreferences(mode=ModeChoice.STOCK))), block=True) self.ui.sm['selfdriveState'].experimentalMode = True + self.ui.sm['carState'].vEgo, self.ui.sm['carState'].vCruise = 31.0, 97.0 + self.ui.sm['slcState'].hasCeiling = False sidebar = MiciSidebarWidgets(Mock()) center = rl.Rectangle(476, 80, 60, 80) for source, accel, stop, expected in ( ('cruise', 0.0, False, '_chill_icon'), ('cruise', -1.0, False, '_chill_icon'), - ('e2e', -0.24, False, '_chill_icon'), + ('e2e', -0.24, False, '_slowdown_icon'), ('e2e', -0.9, True, '_stop_icon'), ('lead0', -0.5, False, '_lead_icon'), ): with self.subTest(source=source, accel=accel, stop=stop): self.ui.sm.put('longitudinalPlan', NS(aTarget=accel, hasLead=source == 'lead0', shouldStop=stop, longitudinalPlanSource=source)) - with patch.object(sidebar, expected) as icon, patch.object(sidebar, '_speed_icon') as speed, \ - patch.object(sidebar, '_active_icon') as letter: - sidebar._conditional(center, self.state(True, True)) - icon.assert_called_once() - speed.assert_not_called() - letter.assert_not_called() + icons = {name: Mock() for name in ('_chill_icon', '_slowdown_icon', '_stop_icon', + '_lead_icon', '_curve_icon', '_speed_icon', '_active_icon')} + with patch.multiple(sidebar, **icons): + state = self.state(True, True) + sidebar._conditional(center, state) + icons[expected].assert_called_once_with(center) + for name, icon in icons.items(): + if name != expected: + icon.assert_not_called() + if expected == '_slowdown_icon': + self.assertEqual(state.e2e_slowdown, 'Slowing') + self.assertEqual(rgba(axis_status_color(state)), (218, 111, 37, 255)) + sidebar._conditional(center, replace(state, alert=OnroadAlert(size=AlertSize.FULL))) + icons['_chill_icon'].assert_called_once_with(center) + icons[expected].assert_called_once() def test_both_profile_compositions_use_axis_border_and_fixtures_remain_combined(self): engaged_fixture = reference_onroad("onroad_engaged_no_camera") diff --git a/openpilot/starpilot/ui/tests/test_onroad_parity.py b/openpilot/starpilot/ui/tests/test_onroad_parity.py index a9c3a58c4e..f0d87185b9 100644 --- a/openpilot/starpilot/ui/tests/test_onroad_parity.py +++ b/openpilot/starpilot/ui/tests/test_onroad_parity.py @@ -52,6 +52,50 @@ def test_confidence_uses_model_probabilities_and_marks_unknown_as_unknown(): assert gradient.call_args.args[4].r == 50 +def test_stationary_confidence_ball_tracks_native_color_with_no_movement(): + from openpilot.selfdrive.ui.mici.onroad import confidence_ball + from openpilot.system.ui.lib.application import gui_app + + with patch.object(gui_app, '_target_fps', 20): + native = confidence_ball.ConfidenceBall() + widget = MiciSidebarWidgets() + rect = rl.Rectangle(476, 0, 60, 80) + native._rect = rect + model = NS(meta=NS(disengagePredictions=NS(brakeDisengageProbs=[0.05], steerOverrideProbs=[0.05]))) + native_ui = NS(status=UIStatus.ENGAGED, sm={'modelV2': model}) + colors = set() + stamp = 1_000_000_000 + with patch.object(confidence_ball, 'ui_state', native_ui), patch.object(confidence_ball, 'draw_circle_gradient') as moving, \ + patch.object(rl, 'draw_rectangle_gradient_v') as stationary, patch.object(rl, 'draw_ring'): + for status, lateral, brake, steer, count in ( + (UIStatus.ENGAGED, True, 0.05, 0.05, 30), + (UIStatus.OVERRIDE, True, 0.05, 0.05, 10), + (UIStatus.DISENGAGED, False, 0.05, 0.05, 30), + (UIStatus.DISENGAGED, True, 0.6, 0.2, 35), + (UIStatus.ENGAGED, True, 0.8, 0.8, 35), + (UIStatus.ENGAGED, True, 0.05, 0.05, 30)): + native_ui.status = status + native._render_lateral_active = lateral + model.meta.disengagePredictions.brakeDisengageProbs = [brake] + model.meta.disengagePredictions.steerOverrideProbs = [steer] + for _ in range(count): + native._update_state() + native._render(None) + widget._confidence_ball(rect, road(lateral_active=lateral, model_confidence=_model_confidence(model), + stock_confidence_source_fresh=True, stock_confidence_source_stamp_ns=stamp, + stock_confidence_drive_frame=1, model_confidence_engaged=status == UIStatus.ENGAGED, + model_confidence_overriding=status == UIStatus.OVERRIDE)) + assert widget._confidence_filter.x == native._confidence_filter.x + assert stationary.call_args.args[:4] == (488, 22, 36, 36) + color = stationary.call_args.args[4] + rgb = (color.r, color.g, color.b) + stock_color = moving.call_args.args[-2] + assert rgb == (stock_color.r, stock_color.g, stock_color.b) + colors.add(rgb) + stamp += 50_000_000 + assert colors == {(0, 255, 204), (255, 200, 0), (255, 0, 21), (255, 255, 255), (50, 50, 50)} + + def test_aol_model_geometry_uses_fresh_lateral_display_context(monkeypatch): renderer = native_model.ModelRenderer.__new__(native_model.ModelRenderer) renderer._init_markers() diff --git a/openpilot/starpilot/ui/tests/test_presentation.py b/openpilot/starpilot/ui/tests/test_presentation.py index 3fb1127789..da0d7ec27f 100644 --- a/openpilot/starpilot/ui/tests/test_presentation.py +++ b/openpilot/starpilot/ui/tests/test_presentation.py @@ -77,6 +77,7 @@ class TestBitmapFonts(unittest.TestCase): fonts = object.__new__(BitmapFonts) fonts.profile = Profile.COMPACT fonts._fonts = {"Inter-Regular.fnt": SimpleNamespace(texture=SimpleNamespace(id=1))} + fonts._resolved = {} with patch("openpilot.starpilot.ui.presentation.rl._orig_draw_text_ex", create=True) as raw_draw, \ patch("openpilot.starpilot.ui.presentation.rl.draw_text_ex") as scaled_draw: fonts.draw("sample", FontRole.ROMAN, 36, 10, 20) @@ -93,6 +94,7 @@ class TestLocalizedPresentation(unittest.TestCase): fonts = object.__new__(BitmapFonts) fonts.profile = Profile.COMPACT fonts._measurements = {} + fonts._resolved = {} font = SimpleNamespace(texture=SimpleNamespace(id=44)) with patch('openpilot.starpilot.ui.presentation.tr', side_effect=lambda text: {'Home': 'ホーム'}.get(text, text)), \ patch.object(fonts, '_text_font', return_value=font) as select, \ @@ -105,6 +107,34 @@ class TestLocalizedPresentation(unittest.TestCase): fonts.draw('StarPilot', FontRole.BRAND, 20, 10, 20) assert draw.call_args.args[1] == 'StarPilot' + def test_resolved_text_is_cached_per_language_and_never_retranslates_display_text(self): + from openpilot.system.ui.lib.display_translation import DisplayText + fonts = object.__new__(BitmapFonts) + fonts.profile = Profile.LARGE + fonts._resolved = {} + font = SimpleNamespace(texture=SimpleNamespace(id=7)) + calls = [] + def translate(text): + calls.append(text) + return text if isinstance(text, DisplayText) else DisplayText({'Home': 'ホーム'}.get(text, text)) + with patch('openpilot.starpilot.ui.presentation.tr', side_effect=translate), \ + patch.object(fonts, '_text_font', return_value=font) as select, \ + patch('openpilot.starpilot.ui.presentation.multilang') as language: + language.language = 'ja' + assert fonts._resolve('Home', FontRole.NORMAL) == ('ホーム', font, 1., 0.) + assert fonts._resolve('Home', FontRole.NORMAL)[0] == 'ホーム' + assert calls == ['Home'] and select.call_count == 1 + # Final text equal to a cached source string keeps its own value. + assert fonts._resolve(DisplayText('Home'), FontRole.NORMAL)[0] == 'Home' + assert fonts._resolve('⠿ Grip', FontRole.NORMAL)[0] == ':: Grip' + assert fonts._resolve('StarPilot', FontRole.BRAND)[0] == 'StarPilot' + assert fonts._resolve('88', FontRole.SPEED)[2:] == (1.04, .85) + assert fonts._resolve('88', FontRole.SPEED, fallback=True)[2:] == (1., 0.) + before = len(calls) + language.language = 'en' + fonts._resolve('Home', FontRole.NORMAL) + assert calls[before:] == ['Home'] + def test_native_language_font_uses_bundled_noto_and_releases_previous(self): fonts = object.__new__(BitmapFonts) old = SimpleNamespace(texture=SimpleNamespace(id=22), glyphCount=1) @@ -115,6 +145,7 @@ class TestLocalizedPresentation(unittest.TestCase): fonts._measurements = {} fonts._vertical_ink = {} fonts._horizontal_ink = {} + fonts._resolved = {} with patch('openpilot.starpilot.ui.presentation.multilang') as language, \ patch('openpilot.starpilot.ui.presentation.rl.load_font_ex', return_value=new) as load, \ patch('openpilot.starpilot.ui.presentation.rl.get_font_default', return_value=SimpleNamespace(texture=SimpleNamespace(id=99))), \ @@ -133,7 +164,7 @@ class TestLocalizedPresentation(unittest.TestCase): fonts = object.__new__(BitmapFonts) first, grown = (SimpleNamespace(texture=SimpleNamespace(id=i), glyphCount=100) for i in (30, 31)) fonts._language_fonts, fonts._language_chars, fonts._headless_context = {}, set(), False - fonts._measurements, fonts._vertical_ink, fonts._horizontal_ink = {}, {}, {} + fonts._measurements, fonts._vertical_ink, fonts._horizontal_ink, fonts._resolved = {}, {}, {}, {} with patch('openpilot.starpilot.ui.presentation.multilang') as language, \ patch('openpilot.starpilot.ui.presentation.rl.load_font_ex', side_effect=[first, grown]) as load, \ patch('openpilot.starpilot.ui.presentation.rl.get_font_default', return_value=SimpleNamespace(texture=SimpleNamespace(id=99))), \ @@ -144,7 +175,9 @@ class TestLocalizedPresentation(unittest.TestCase): patch('openpilot.starpilot.ui.presentation.rl.set_texture_filter'): language.language = 'en' assert fonts._text_font('72°F', FontRole.NORMAL) is first + fonts._resolved['72°F'] = ('72°F', first, 1., 0.) assert fonts._text_font('Lead — 2 m/s²', FontRole.NORMAL) is grown + assert fonts._resolved == {}, 'cached text must not keep the unloaded atlas' codepoints = set(load.call_args.args[2].tolist()) assert {ord('°'), ord('—'), ord('²')} <= codepoints flush.assert_called_once() diff --git a/openpilot/starpilot/ui/tests/test_settings_resources.py b/openpilot/starpilot/ui/tests/test_settings_resources.py index bedc2b3a4b..5b4079ba73 100644 --- a/openpilot/starpilot/ui/tests/test_settings_resources.py +++ b/openpilot/starpilot/ui/tests/test_settings_resources.py @@ -106,6 +106,18 @@ class TestSettingsResources(unittest.TestCase): calls["end_texture_mode"].assert_called_once() self.assertEqual(assets._icons, {}) + def test_icons_share_one_blend_pass(self): + assets = SettingsAssets(Path("unused")) + color = rl.Color(255, 255, 255, 255) + for name in ("sound", "system"): + assets._icons[(name, 2, 255, 255, 255, 255)] = SimpleNamespace(texture=SimpleNamespace(width=140, height=140)) + with patch(f"{MODULE}.rl.begin_blend_mode") as begin, patch(f"{MODULE}.rl.end_blend_mode") as end, \ + patch(f"{MODULE}.rl.draw_texture_pro") as draw: + assets.icons([("sound", 10, 20), ("system", 300, 20)], 2, color) + begin.assert_called_once_with(rl.BlendMode.BLEND_ALPHA_PREMULTIPLY) + end.assert_called_once() + self.assertEqual([(call.args[2].x, call.args[2].y) for call in draw.call_args_list], [(4, 14), (294, 14)]) + def test_repeated_close_releases_each_owned_image_and_vector_target_once(self): assets = SettingsAssets(Path("unused")) image, target = SimpleNamespace(id=17), SimpleNamespace(id=20) diff --git a/openpilot/starpilot/ui/tests/test_traffic_feature.py b/openpilot/starpilot/ui/tests/test_traffic_feature.py index 75734d92ee..3c1c4ba3cd 100644 --- a/openpilot/starpilot/ui/tests/test_traffic_feature.py +++ b/openpilot/starpilot/ui/tests/test_traffic_feature.py @@ -155,10 +155,12 @@ class TrafficFeatureTests(unittest.TestCase): self.assertEqual(self.owner.snapshot("traffic/braking", parked=True, system_long=True, lateral_context=False, metric=False).rows[1].minimum, 0.35) + self.params.put_bool("CustomPersonalities", True, block=True) self.params.put("TrafficFollow", 0.8, block=True) self.params.put("RelaxedFollow", 1.8, block=True) + self.params.put("AggressiveFollowHigh", 1.1, block=True) following = select("following", "custom") - self.assertEqual((following["curve"][0], following["curve"][-1]), (0.8, 1.8)) + self.assertEqual((following["curve"][0], following["curve"][-1]), (0.8, 1.1)) self.cp.transmissionType = car.CarParams.TransmissionType.direct Path(self.params.get_param_path("LongitudinalPersonalityProfiles")).write_bytes( diff --git a/openpilot/starpilot/ui/tests/test_wheel_feedback.py b/openpilot/starpilot/ui/tests/test_wheel_feedback.py index 4d3baf0431..41cb916788 100644 --- a/openpilot/starpilot/ui/tests/test_wheel_feedback.py +++ b/openpilot/starpilot/ui/tests/test_wheel_feedback.py @@ -413,17 +413,3 @@ def test_compact_steer_warning_tints_the_engaged_wheel_without_covering_full_ale hud.render_steering_wheel(replace(state, alert=replace(alert, size=AlertSize.FULL))) hud.render_steering_wheel(replace(state, lateral_active=False)) draw.assert_not_called() - - -def test_compact_status_tint_holds_through_one_frame_override_gap(): - from openpilot.starpilot.ui.onroad_compact_widgets import CompactStatusFade - - status = CompactStatusFade(.1) - drive = OnroadState(True, True, 10, None, SpeedLimitObservation(), observed_ns=NOW, drive_frame=1) - assert status.update(drive, True) == 1.0 - override = replace(drive, observed_ns=NOW + 10_000_000, driver_override_active=True) - assert status.update(override, True) == 0.0 - assert status.update(replace(drive, observed_ns=NOW + 20_000_000), True) == 0.0 - after = replace(drive, observed_ns=NOW + 320_000_000) - assert 0 < status.update(after, True) < 1 - assert status.update(after, False) == 0.0 diff --git a/openpilot/starpilot/ui/traffic_feature.py b/openpilot/starpilot/ui/traffic_feature.py index e480e7839a..b332bc3ae8 100644 --- a/openpilot/starpilot/ui/traffic_feature.py +++ b/openpilot/starpilot/ui/traffic_feature.py @@ -3,6 +3,7 @@ import math from openpilot.starpilot.longitudinal.profile_document import PERSONALITY_PROFILES_PARAM +from openpilot.starpilot.longitudinal.profile_preferences import TRAFFIC_NUMBER_KEYS from openpilot.starpilot.saved_document import commit_exact from openpilot.starpilot.saved_source import read_saved from openpilot.starpilot.ui.feature_settings_state import FeatureRow, FeatureSettingsRequest @@ -12,9 +13,7 @@ from openpilot.starpilot.ui.long_profile_feature import VALUE_HELP FOLLOW = "TrafficFollow" JERKS = ("TrafficJerkAcceleration", "TrafficJerkDeceleration", "TrafficJerkSpeed", "TrafficJerkSpeedDecrease", "TrafficJerkDanger") -RELAXED = ("RelaxedFollow", "RelaxedJerkAcceleration", "RelaxedJerkDeceleration", "RelaxedJerkSpeed", - "RelaxedJerkSpeedDecrease", "RelaxedJerkDanger") -SOURCES = ("CustomPersonalities", PERSONALITY_PROFILES_PARAM, FOLLOW, *JERKS, *RELAXED) +SOURCES = ("CustomPersonalities", PERSONALITY_PROFILES_PARAM, *TRAFFIC_NUMBER_KEYS) EDIT_KEYS = frozenset((FOLLOW, *JERKS)) LABELS = {FOLLOW: "Low-speed follow", "TrafficJerkAcceleration": "Acceleration jerk", "TrafficJerkDeceleration": "Deceleration jerk", "TrafficJerkSpeed": "Speed jerk", @@ -73,12 +72,12 @@ class TrafficFeature: minimum=0.5 if key == FOLLOW else 25.0, maximum=3.0 if key == FOLLOW else 200.0, unit=unit, available=allowed and valid, - reason=(active_note + ". " + ("Following time at low speeds; blends toward Relaxed as speed rises." if key == FOLLOW else + reason=(active_note + ". " + ("Following time at low speeds; blends toward Aggressive as speed rises." if key == FOLLOW else VALUE_HELP[key.removeprefix("Traffic")]) if valid else "Invalid saved value; original bytes remain unchanged"), vehicle_fingerprint=fingerprint, capability=capability, dependencies=dependencies)) - rows.append(FeatureRow("", "Higher-speed values", "Inherited from Relaxed follow and jerk settings", - reason="With Custom Driving Profiles On, blends toward saved Relaxed values; otherwise defaults apply")) + rows.append(FeatureRow("", "Higher-speed values", "Inherited from Aggressive follow and jerk settings", + reason="With Custom Driving Profiles On, blends toward saved Aggressive values; otherwise defaults apply")) return rows def apply(self, request: FeatureSettingsRequest) -> bool: diff --git a/prebuilt.json b/prebuilt.json index db183e0516..0cff58e4fa 100644 --- a/prebuilt.json +++ b/prebuilt.json @@ -1 +1 @@ -{"protected_inventory_sha256": "a651e62a51c814c922f6e469ddf7d7c00697e7cc28ea32bc7f550ee39c044975", "schema_version": 1} +{"protected_inventory_sha256": "7555533ea8ef13346f8aa54da3706b23f2f384ff89bdf35e3f5f4d255fb1c9f0", "schema_version": 1}