From f1ba60578ebff169fdcfd2e3c9d3a6930615bb93 Mon Sep 17 00:00:00 2001 From: firestarsdog <229254897+firestarsdog@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:17:12 -0500 Subject: [PATCH] Cache text lookups and Settings stars, batch Settings icon drawing --- openpilot/starpilot/ui/presentation.py | 44 ++++++++----------- openpilot/starpilot/ui/settings.py | 5 ++- openpilot/starpilot/ui/settings_assets.py | 12 ++--- openpilot/starpilot/ui/settings_geometry.py | 7 ++- .../starpilot/ui/tests/test_presentation.py | 32 +++++++++----- .../ui/tests/test_settings_resources.py | 12 +++++ 6 files changed, 67 insertions(+), 45 deletions(-) diff --git a/openpilot/starpilot/ui/presentation.py b/openpilot/starpilot/ui/presentation.py index 8cf7193bb3..313eaad644 100644 --- a/openpilot/starpilot/ui/presentation.py +++ b/openpilot/starpilot/ui/presentation.py @@ -115,7 +115,7 @@ class BitmapFonts: self._fonts: dict[str, rl.Font] = {} self._language_fonts: dict[str, rl.Font] = {} self._language_chars: set[str] = set() - self._display_text: dict[tuple[str, str], str] = {} + 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]] = {} @@ -172,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() @@ -180,19 +181,17 @@ class BitmapFonts: rl.set_texture_filter(font.texture, rl.TextureFilter.TEXTURE_FILTER_TRILINEAR) return fonts[language] - def _display(self, text: str, role: FontRole) -> str: - """The translated, font-safe text that is drawn, cached per language.""" - if role == FontRole.BRAND: - return text - if type(text) is not str: # DisplayText is final and would share its source string's cache key - return native_text(tr(text)) - key = multilang.language, text - shown = self._display_text.get(key) - if shown is None: - if len(self._display_text) >= 1024: - self._display_text.clear() - shown = self._display_text[key] = native_text(tr(text)) - return shown + 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: @@ -204,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 = self._display(text, role) - 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 @@ -226,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 = self._display(text, role) + 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) @@ -241,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 = self._display(text, role) + 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. @@ -290,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 = self._display(text, role) - 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 @@ -319,7 +311,7 @@ class BitmapFonts: self._glyph_ink.clear() self._codepoints.clear() self._measurements.clear() - self._display_text.clear() + self._resolved.clear() def __enter__(self): return self 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_presentation.py b/openpilot/starpilot/ui/tests/test_presentation.py index 2901026ecb..da0d7ec27f 100644 --- a/openpilot/starpilot/ui/tests/test_presentation.py +++ b/openpilot/starpilot/ui/tests/test_presentation.py @@ -77,7 +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._display_text = {} + 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) @@ -94,7 +94,7 @@ class TestLocalizedPresentation(unittest.TestCase): fonts = object.__new__(BitmapFonts) fonts.profile = Profile.COMPACT fonts._measurements = {} - fonts._display_text = {} + 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, \ @@ -107,27 +107,32 @@ class TestLocalizedPresentation(unittest.TestCase): fonts.draw('StarPilot', FontRole.BRAND, 20, 10, 20) assert draw.call_args.args[1] == 'StarPilot' - def test_display_text_cache_is_per_language_and_never_retranslates_display_text(self): + 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._display_text = {} + 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._display('Home', FontRole.NORMAL) == 'ホーム' - assert fonts._display('Home', FontRole.NORMAL) == 'ホーム' - assert calls == ['Home'] + 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._display(DisplayText('Home'), FontRole.NORMAL) == 'Home' - assert fonts._display('⠿ Grip', FontRole.NORMAL) == ':: Grip' - assert fonts._display('StarPilot', FontRole.BRAND) == 'StarPilot' + 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._display('Home', FontRole.NORMAL) + fonts._resolve('Home', FontRole.NORMAL) assert calls[before:] == ['Home'] def test_native_language_font_uses_bundled_noto_and_releases_previous(self): @@ -140,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))), \ @@ -158,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))), \ @@ -169,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)