From 946a3c84071bacd52c43b62d61bde9a35904d502 Mon Sep 17 00:00:00 2001 From: eastagile-tracker <361865763+eastagile-tracker@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:16:04 +0000 Subject: [PATCH] Add LODBudgetController and runtime LOD distance factor on TerrainLODManager LODBudgetController is a frame-time driven proportional controller (EMA-smoothed, dead band, per-frame step clamp, min/max bounds) that returns an adjusted lod_distance_factor. TerrainLODManager gains a lod_distance_factor property and set_lod_distance_factor(), which recomputes the LOD thresholds and culling range and re-evaluates tiles on the next update() without requiring camera movement. --- rtxpy/__init__.py | 1 + rtxpy/lod.py | 146 ++++++++++++++++++++++ rtxpy/tests/test_lod.py | 235 ++++++++++++++++++++++++++++++++++++ rtxpy/viewer/terrain_lod.py | 58 +++++++-- 4 files changed, 431 insertions(+), 9 deletions(-) diff --git a/rtxpy/__init__.py b/rtxpy/__init__.py index 2be8133..47f337e 100644 --- a/rtxpy/__init__.py +++ b/rtxpy/__init__.py @@ -28,6 +28,7 @@ from .lod import ( compute_lod_level, compute_lod_distances, + LODBudgetController, simplify_mesh, build_lod_chain, ) diff --git a/rtxpy/lod.py b/rtxpy/lod.py index eac7723..a04575e 100644 --- a/rtxpy/lod.py +++ b/rtxpy/lod.py @@ -155,6 +155,152 @@ def compute_tile_roughness(tile_2d): return float(np.nanstd(residuals)) +class LODBudgetController: + """Adjust ``lod_distance_factor`` to hold a target frame time. + + Closes the loop between measured render cost and LOD thresholds. + Each frame the measured frame time is folded into an exponential + moving average (EMA). When the EMA is slower than the target by + more than ``dead_band`` the factor shrinks, pulling LOD transitions + closer to the camera (fewer triangles); when it is faster by more + than ``dead_band`` the factor grows (more detail). Inside the dead + band the factor is left alone so it does not oscillate. + + The step is proportional to the relative error, clamped to + ``max_step`` of the current factor per frame, and the factor is + kept within ``[min_factor, max_factor]``. + + Parameters + ---------- + target_fps : float + Frame rate to aim for. The target frame time is + ``1000 / target_fps`` milliseconds. + min_factor, max_factor : float + Bounds on the returned ``lod_distance_factor``. + alpha : float + EMA smoothing weight for the newest sample, in ``(0, 1]``. + dead_band : float + Fractional tolerance around the target, in ``[0, 1)``. E.g. + 0.1 leaves the factor unchanged while the EMA is within 10%. + step_scale : float + Fractional factor change per unit of relative error. + max_step : float + Largest fractional change applied in a single frame. + initial_factor : float + Starting factor, clamped into ``[min_factor, max_factor]``. + Defaults to 3.0, the ``TerrainLODManager`` default. + + Examples + -------- + >>> ctrl = LODBudgetController(target_fps=30, initial_factor=3.0) + >>> ctrl.update(66.0) < 3.0 # twice the 33 ms budget: less detail + True + """ + + def __init__(self, target_fps=30, min_factor=1.0, max_factor=10.0, + alpha=0.1, dead_band=0.1, step_scale=0.02, max_step=0.05, + initial_factor=3.0): + if not target_fps > 0: + raise ValueError(f"target_fps must be positive, got {target_fps!r}") + if not 0 < min_factor <= max_factor: + raise ValueError( + "require 0 < min_factor <= max_factor, got " + f"min_factor={min_factor!r}, max_factor={max_factor!r}") + if not 0 < alpha <= 1: + raise ValueError(f"alpha must be in (0, 1], got {alpha!r}") + if not 0 <= dead_band < 1: + raise ValueError(f"dead_band must be in [0, 1), got {dead_band!r}") + if not step_scale >= 0: + raise ValueError(f"step_scale must be >= 0, got {step_scale!r}") + if not 0 <= max_step < 1: + raise ValueError(f"max_step must be in [0, 1), got {max_step!r}") + + self._target_ms = 1000.0 / float(target_fps) + self._min_factor = float(min_factor) + self._max_factor = float(max_factor) + self._alpha = float(alpha) + self._dead_band = float(dead_band) + self._step_scale = float(step_scale) + self._max_step = float(max_step) + self._factor = min(max(float(initial_factor), self._min_factor), + self._max_factor) + self._ema = None + self._direction = 0 + self.enabled = True + + @property + def current_factor(self): + """The ``lod_distance_factor`` to apply to LOD managers.""" + return self._factor + + @property + def ema_frame_time(self): + """Smoothed frame time in milliseconds (None before any sample).""" + return self._ema + + @property + def target_frame_time(self): + """Target frame time in milliseconds.""" + return self._target_ms + + @property + def direction(self): + """Last adjustment: +1 more detail, -1 less detail, 0 stable.""" + return self._direction + + def update(self, frame_time_ms): + """Record one frame's render time and return the adjusted factor. + + Call once per frame. Non-finite or non-positive samples are + ignored. While :attr:`enabled` is False the EMA keeps tracking + frame time but the factor stays at its last value. + + Parameters + ---------- + frame_time_ms : float + Measured render time of the last frame, in milliseconds. + + Returns + ------- + float + The (possibly unchanged) ``lod_distance_factor``. + """ + ft = float(frame_time_ms) + if not np.isfinite(ft) or ft <= 0.0: + self._direction = 0 + return self._factor + + if self._ema is None: + self._ema = ft + else: + self._ema = self._alpha * ft + (1.0 - self._alpha) * self._ema + + if not self.enabled: + self._direction = 0 + return self._factor + + rel_err = (self._ema - self._target_ms) / self._target_ms + if abs(rel_err) <= self._dead_band: + self._direction = 0 + return self._factor + + step = min(self._step_scale * abs(rel_err), self._max_step) + if rel_err > 0: + new_factor = self._factor * (1.0 - step) + else: + new_factor = self._factor * (1.0 + step) + new_factor = min(max(new_factor, self._min_factor), self._max_factor) + + if new_factor > self._factor: + self._direction = 1 + elif new_factor < self._factor: + self._direction = -1 + else: + self._direction = 0 + self._factor = new_factor + return self._factor + + def simplify_mesh(vertices, indices, ratio): """Simplify a triangle mesh using quadric decimation. diff --git a/rtxpy/tests/test_lod.py b/rtxpy/tests/test_lod.py index 4de22ab..1fb6e74 100644 --- a/rtxpy/tests/test_lod.py +++ b/rtxpy/tests/test_lod.py @@ -8,6 +8,7 @@ compute_lod_level_with_hysteresis, compute_lod_distances, compute_tile_roughness, + LODBudgetController, simplify_mesh, build_lod_chain, ) @@ -158,6 +159,140 @@ def test_zero_max_lod(self): assert dists == [] +# --------------------------------------------------------------------------- +# LODBudgetController +# --------------------------------------------------------------------------- + +class TestLODBudgetController: + """Tests for the frame-time driven LOD distance factor controller.""" + + def test_defaults(self): + ctrl = LODBudgetController() + assert ctrl.current_factor == pytest.approx(3.0) + assert ctrl.target_frame_time == pytest.approx(1000.0 / 30) + assert ctrl.ema_frame_time is None + assert ctrl.direction == 0 + + def test_first_sample_seeds_ema(self): + ctrl = LODBudgetController(target_fps=30) + ctrl.update(40.0) + assert ctrl.ema_frame_time == pytest.approx(40.0) + + def test_ema_smoothing(self): + ctrl = LODBudgetController(target_fps=30, alpha=0.25) + ctrl.update(40.0) + ctrl.update(80.0) + assert ctrl.ema_frame_time == pytest.approx(0.25 * 80.0 + 0.75 * 40.0) + + def test_slow_frames_reduce_factor(self): + ctrl = LODBudgetController(target_fps=30, initial_factor=3.0) + f = ctrl.update(100.0) + assert f < 3.0 + assert ctrl.direction == -1 + + def test_fast_frames_increase_factor(self): + ctrl = LODBudgetController(target_fps=30, initial_factor=3.0) + f = ctrl.update(5.0) + assert f > 3.0 + assert ctrl.direction == 1 + + def test_dead_band_holds_factor(self): + target = 1000.0 / 30 + for ft in (target, target * 1.09, target * 0.91): + ctrl = LODBudgetController(target_fps=30, dead_band=0.1, + initial_factor=3.0) + assert ctrl.update(ft) == 3.0 + assert ctrl.direction == 0 + + def test_step_proportional_to_error(self): + small = LODBudgetController(target_fps=30, step_scale=0.02) + large = LODBudgetController(target_fps=30, step_scale=0.02) + target = small.target_frame_time + small.update(target * 1.5) + large.update(target * 2.0) + assert large.current_factor < small.current_factor < 3.0 + # step = step_scale * relative error + assert small.current_factor == pytest.approx(3.0 * (1 - 0.02 * 0.5)) + assert large.current_factor == pytest.approx(3.0 * (1 - 0.02 * 1.0)) + + def test_step_clamped_per_frame(self): + ctrl = LODBudgetController(target_fps=30, step_scale=1.0, + max_step=0.05, initial_factor=3.0) + ctrl.update(1000.0) # 30x over budget + assert ctrl.current_factor == pytest.approx(3.0 * 0.95) + + def test_factor_respects_min(self): + ctrl = LODBudgetController(target_fps=30, min_factor=2.5, + initial_factor=3.0) + for _ in range(500): + ctrl.update(500.0) + assert ctrl.current_factor == pytest.approx(2.5) + # Pinned at the floor: no further change is reported + assert ctrl.direction == 0 + + def test_factor_respects_max(self): + ctrl = LODBudgetController(target_fps=30, max_factor=4.0, + initial_factor=3.0) + for _ in range(500): + ctrl.update(1.0) + assert ctrl.current_factor == pytest.approx(4.0) + + def test_initial_factor_clamped(self): + assert LODBudgetController(initial_factor=50.0, + max_factor=10.0).current_factor == 10.0 + assert LODBudgetController(initial_factor=0.1, + min_factor=1.0).current_factor == 1.0 + + @pytest.mark.parametrize("bad", [0.0, -5.0, float('nan'), float('inf')]) + def test_invalid_samples_ignored(self, bad): + ctrl = LODBudgetController(initial_factor=3.0) + assert ctrl.update(bad) == 3.0 + assert ctrl.ema_frame_time is None + + def test_disabled_tracks_ema_but_holds_factor(self): + ctrl = LODBudgetController(target_fps=30, initial_factor=3.0) + ctrl.update(100.0) + held = ctrl.current_factor + ctrl.enabled = False + for _ in range(20): + assert ctrl.update(100.0) == held + assert ctrl.ema_frame_time == pytest.approx(100.0) + assert ctrl.direction == 0 + # Re-enabling resumes from the held value, not the default + ctrl.enabled = True + assert ctrl.update(100.0) < held + + def test_converges_into_dead_band(self): + # Simulated renderer: cost grows with the area covered by fine + # LOD bands, i.e. with factor squared. 60 fps target. + ctrl = LODBudgetController(target_fps=60, initial_factor=8.0) + + def frame_ms(factor): + return 1.5 * factor * factor + + for _ in range(2000): + ctrl.update(frame_ms(ctrl.current_factor)) + target = ctrl.target_frame_time + assert abs(frame_ms(ctrl.current_factor) - target) <= 0.1 * target * 1.01 + assert ctrl.current_factor < 8.0 + + @pytest.mark.parametrize("kwargs", [ + {'target_fps': 0}, + {'target_fps': -30}, + {'min_factor': 0.0}, + {'min_factor': 5.0, 'max_factor': 4.0}, + {'alpha': 0.0}, + {'alpha': 1.5}, + {'dead_band': 1.0}, + {'dead_band': -0.1}, + {'step_scale': -0.01}, + {'max_step': 1.0}, + ]) + def test_invalid_parameters(self, kwargs): + with pytest.raises(ValueError): + LODBudgetController(**kwargs) + + # --------------------------------------------------------------------------- # compute_tile_roughness # --------------------------------------------------------------------------- @@ -1874,3 +2009,103 @@ def test_callbacks_not_called_when_none(self): # Should not raise mgr.update(np.array([128, 128, 100]), rtx, force=True) mgr.update(np.array([10000, 10000, 0]), rtx, force=True) + + +# --------------------------------------------------------------------------- +# TerrainLODManager.set_lod_distance_factor +# --------------------------------------------------------------------------- + +class TestTerrainLODManagerDistanceFactor: + """Runtime adjustment of the LOD distance factor (budget hook).""" + + def _make_terrain(self, H=512, W=512): + y = np.linspace(0, 100, H, dtype=np.float32) + x = np.linspace(0, 100, W, dtype=np.float32) + return y[:, None] + x[None, :] + + def test_property_reports_constructor_value(self): + mgr = TerrainLODManager(self._make_terrain(), tile_size=128, + lod_distance_factor=2.5) + assert mgr.lod_distance_factor == 2.5 + + def test_thresholds_match_fresh_manager(self): + terrain = self._make_terrain() + mgr = TerrainLODManager(terrain, tile_size=128, + pixel_spacing_x=2.0, pixel_spacing_y=3.0, + lod_distance_factor=3.0) + assert mgr.set_lod_distance_factor(5.0) + fresh = TerrainLODManager(terrain, tile_size=128, + pixel_spacing_x=2.0, pixel_spacing_y=3.0, + lod_distance_factor=5.0) + assert mgr.lod_distance_factor == 5.0 + assert mgr._lod_distances == pytest.approx(fresh._lod_distances) + assert mgr._max_dist == pytest.approx(fresh._max_dist) + assert mgr._max_dist_sq == pytest.approx(fresh._max_dist_sq) + assert mgr._streaming_max_dist == pytest.approx( + fresh._streaming_max_dist) + + def test_same_factor_is_noop(self): + terrain = self._make_terrain(128, 128) + rtx = _FakeRTX() + mgr = TerrainLODManager(terrain, tile_size=64, + lod_distance_factor=3.0) + mgr.update(np.array([64, 64, 0]), rtx, force=True) + assert not mgr.set_lod_distance_factor(3.0) + # Still throttled by the movement threshold + assert not mgr.update(np.array([64, 64, 0]), rtx) + + def test_new_factor_reevaluates_without_camera_motion(self): + terrain = self._make_terrain() + rtx = _FakeRTX() + mgr = TerrainLODManager(terrain, tile_size=128, + max_lod=3, lod_distance_factor=1.0) + mgr.per_tick_build_limit = 100 + cam = np.array([0, 0, 0]) + mgr.update(cam, rtx, force=True) + coarse = mgr.tile_lods + assert coarse[(3, 3)] > 0 + + # Push LOD transitions far out: every tile should now get full + # detail on the next update, with the camera standing still. + assert mgr.set_lod_distance_factor(50.0) + assert mgr.update(cam, rtx) + fine = mgr.tile_lods + assert all(lod == 0 for lod in fine.values()) + assert len(fine) == mgr.n_tiles + + def test_smaller_factor_coarsens_lod(self): + terrain = self._make_terrain() + rtx = _FakeRTX() + mgr = TerrainLODManager(terrain, tile_size=128, + max_lod=3, lod_distance_factor=50.0) + mgr.per_tick_build_limit = 100 + cam = np.array([0, 0, 0]) + mgr.update(cam, rtx, force=True) + assert all(lod == 0 for lod in mgr.tile_lods.values()) + + mgr.set_lod_distance_factor(0.5) + mgr.update(cam, rtx) + assert max(mgr.tile_lods.values()) > 0 + + @pytest.mark.parametrize("bad", [0.0, -1.0, float('nan'), float('inf')]) + def test_rejects_invalid_factor(self, bad): + mgr = TerrainLODManager(self._make_terrain(128, 128), tile_size=64, + lod_distance_factor=3.0) + with pytest.raises(ValueError): + mgr.set_lod_distance_factor(bad) + assert mgr.lod_distance_factor == 3.0 + + def test_controller_drives_manager(self): + terrain = self._make_terrain() + rtx = _FakeRTX() + mgr = TerrainLODManager(terrain, tile_size=128, + max_lod=3, lod_distance_factor=3.0) + ctrl = LODBudgetController(target_fps=30, + initial_factor=mgr.lod_distance_factor) + mgr.update(np.array([0, 0, 0]), rtx, force=True) + before = list(mgr._lod_distances) + # Over budget: thresholds should pull in toward the camera + for _ in range(10): + mgr.set_lod_distance_factor(ctrl.update(80.0)) + assert mgr.lod_distance_factor == ctrl.current_factor + assert all(a < b for a, b in zip(mgr._lod_distances, before)) diff --git a/rtxpy/viewer/terrain_lod.py b/rtxpy/viewer/terrain_lod.py index f2f13f8..2820c9d 100644 --- a/rtxpy/viewer/terrain_lod.py +++ b/rtxpy/viewer/terrain_lod.py @@ -118,15 +118,7 @@ def __init__(self, terrain_np, tile_size=128, + (tile_size * pixel_spacing_y) ** 2) self._tile_half_diag_sq = tile_diag_sq * 0.25 self._tile_half_diag = np.sqrt(tile_diag_sq * 0.25) - self._lod_distances = compute_lod_distances( - np.sqrt(tile_diag_sq), factor=lod_distance_factor, - max_lod=max_lod) - max_dist = (self._lod_distances[-1] * 3.0 - if self._lod_distances else float('inf')) - self._max_dist_sq = max_dist * max_dist - self._max_dist = max_dist - self._streaming_max_dist = (self._lod_distances[-1] * 1.5 - if self._lod_distances else max_dist) + self._apply_lod_distance_factor(lod_distance_factor) # Tile world-space dimensions (for streaming radius computation) self._tile_world_x = tile_size * abs(pixel_spacing_x) self._tile_world_y = tile_size * abs(pixel_spacing_y) @@ -291,6 +283,40 @@ def set_base_subsample(self, factor): if self._hf_enabled: self._hf_dirty = True + @property + def lod_distance_factor(self): + """Current multiplier on the tile diagonal for LOD transitions.""" + return self._lod_distance_factor + + def set_lod_distance_factor(self, factor): + """Change how far each LOD band extends. + + Recomputes the LOD distance thresholds and the culling range from + ``factor`` and forces the next :meth:`update` to re-evaluate every + tile, even if the camera has not moved. Cached tile meshes stay + valid — only the LOD assignment changes. Intended to be driven by + :class:`rtxpy.lod.LODBudgetController`. + + Parameters + ---------- + factor : float + New ``lod_distance_factor`` (must be positive and finite). + + Returns + ------- + bool + True if the factor changed. + """ + factor = float(factor) + if not math.isfinite(factor) or factor <= 0.0: + raise ValueError( + f"lod_distance_factor must be positive, got {factor!r}") + if factor == self._lod_distance_factor: + return False + self._apply_lod_distance_factor(factor) + self._last_update_pos = None + return True + def set_offset(self, offset_x, offset_y): """Set world-space offset for tile vertices. @@ -950,6 +976,20 @@ def get_stats(self): # Internal # ------------------------------------------------------------------ + def _apply_lod_distance_factor(self, factor): + """Derive LOD thresholds and culling distances from *factor*.""" + self._lod_distance_factor = factor + tile_diag = math.sqrt((self._tile_size * self._psx) ** 2 + + (self._tile_size * self._psy) ** 2) + self._lod_distances = compute_lod_distances( + tile_diag, factor=factor, max_lod=self._max_lod) + max_dist = (self._lod_distances[-1] * 3.0 + if self._lod_distances else float('inf')) + self._max_dist_sq = max_dist * max_dist + self._max_dist = max_dist + self._streaming_max_dist = (self._lod_distances[-1] * 1.5 + if self._lod_distances else max_dist) + def _compute_all_roughness(self): """Compute roughness scale factors for all in-bounds tiles.