From 09d363244667ced48b3c2e1b5dfa4a344759279a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 18 May 2026 23:12:04 +0100 Subject: [PATCH] Add midpoint Kiyo TAA render view --- docs/implementation-plan.md | 1 + localcast/sensor_fusion/__init__.py | 11 +- localcast/sensor_fusion/spout_output.py | 129 ++++++++++++++++++++---- notes/current-system-map.md | 2 +- scripts/stream_spout.py | 8 +- state/map.yaml | 6 +- tests/test_sensor_fusion.py | 101 +++++++++++++++++++ 7 files changed, 236 insertions(+), 22 deletions(-) diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index 32c6fe8..b1160b4 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -30,6 +30,7 @@ - `scripts/live_sensor_fusion.py` writes fused render frames into `calibration/runs/visual-state.msgpack`. - The live visual producer writes a multi-LOD scene cache with source kind and priority. Real Leap frames are promoted as the highest-priority visual timing/spatial evidence; Leap fallback frames remain lower-priority diagnostics. - `scripts/stream_spout.py` runs the deadline Spout sender loop from the typed cache with typed and JSON heartbeat status. + - The deadline Spout renderer has a named `kiyo-mid-deru` virtual camera preset: eye at the midpoint between the two Kiyo-class cameras and target on the co-streamer body volume. It also applies a renderer-owned point budget with stable high-confidence anchors plus frame-varying remainder samples so downstream TAA/supersampling can accumulate detail without forcing every source claim into every OBS frame. - `docs/obs-spout-streaming.md` documents OBS setup and the Aquarium replacement boundary. - `docs/typed-visual-state.md` documents the CultCache/CultNet visual boundary. - OBS synchronized program surface: diff --git a/localcast/sensor_fusion/__init__.py b/localcast/sensor_fusion/__init__.py index 6538da4..4930e0d 100644 --- a/localcast/sensor_fusion/__init__.py +++ b/localcast/sensor_fusion/__init__.py @@ -78,7 +78,14 @@ from .cultcache_docs import ( put_live_clap_events, put_live_render_frame, ) -from .spout_output import ScreenBrushPacket, SpoutOutputConfig, frame_to_vertex_array, lower_frame_to_screen_brushes +from .spout_output import ( + ScreenBrushPacket, + SpoutOutputConfig, + VirtualCamera, + frame_to_vertex_array, + frame_with_point_budget, + lower_frame_to_screen_brushes, +) __all__ = [ "CameraModel", @@ -128,7 +135,9 @@ __all__ = [ "CultStreamStatus", "ScreenBrushPacket", "SpoutOutputConfig", + "VirtualCamera", "frame_to_vertex_array", + "frame_with_point_budget", "get_live_render_frame", "get_live_clap_events", "make_clap_events_frame", diff --git a/localcast/sensor_fusion/spout_output.py b/localcast/sensor_fusion/spout_output.py index d732d69..1fc67f9 100644 --- a/localcast/sensor_fusion/spout_output.py +++ b/localcast/sensor_fusion/spout_output.py @@ -24,6 +24,30 @@ class SpoutOutputConfig: fps: float = 60.0 point_scale: float = 1.0 demo_point_count: int = 4096 + camera_preset: str = "kiyo-mid-deru" + max_render_points: int = 5000 + + +@dataclass(frozen=True) +class VirtualCamera: + eye: tuple[float, float, float] + target: tuple[float, float, float] + up: tuple[float, float, float] = (0.0, 0.0, 1.0) + fov_degrees: float = 62.0 + near_m: float = 0.05 + far_m: float = 50.0 + + @property + def eye_np(self) -> np.ndarray: + return np.asarray(self.eye, dtype=np.float64) + + @property + def target_np(self) -> np.ndarray: + return np.asarray(self.target, dtype=np.float64) + + @property + def up_np(self) -> np.ndarray: + return np.asarray(self.up, dtype=np.float64) @dataclass(frozen=True) @@ -201,14 +225,52 @@ def frame_to_vertex_array(frame: RenderFramePacket, point_scale: float = 1.0) -> return vertices +def frame_with_point_budget(frame: RenderFramePacket, max_points: int) -> RenderFramePacket: + if max_points <= 0 or len(frame.points) <= max_points: + return frame + priority_count = max(1, int(max_points * 0.55)) + temporal_count = max(0, max_points - priority_count) + priority = sorted( + frame.points, + key=lambda point: (-float(point.confidence), stable_hash(point.stable_key, 0)), + )[:priority_count] + selected_keys = {point.stable_key for point in priority} + remainder = [point for point in frame.points if point.stable_key not in selected_keys] + temporal = sorted( + remainder, + key=lambda point: stable_hash(point.stable_key, frame.frame_id), + )[:temporal_count] + points = priority + temporal + points = sorted(points, key=lambda point: point.stable_key) + return RenderFramePacket( + schema=frame.schema, + frame_id=frame.frame_id, + created_monotonic_ns=frame.created_monotonic_ns, + source_time_min_ns=frame.source_time_min_ns, + source_time_max_ns=frame.source_time_max_ns, + present_time_ns=frame.present_time_ns, + audio_alignment_time_ns=frame.audio_alignment_time_ns, + spout_sender_name=frame.spout_sender_name, + target_width=frame.target_width, + target_height=frame.target_height, + points=tuple(points), + ) + + +def stable_hash(key: str, salt: int) -> int: + digest = hashlib.blake2s(f"{salt}:{key}".encode("utf-8"), digest_size=8).digest() + return int.from_bytes(digest, "little") + + def lower_frame_to_screen_brushes( frame: RenderFramePacket, width: int, height: int, point_scale: float = 1.0, + camera: VirtualCamera | None = None, ) -> tuple[ScreenBrushPacket, ...]: brushes: list[ScreenBrushPacket] = [] - view_proj = camera_matrix(0.0, width / max(1, height)) + view_proj = camera_matrix(0.0, width / max(1, height), camera) for point in frame.points: projected = project_world_to_screen(point.xyz, view_proj, width, height) if projected is None: @@ -229,16 +291,22 @@ def lower_frame_to_screen_brushes( return tuple(sorted(brushes, key=lambda brush: brush.depth, reverse=True)) -def rasterize_frame_rgba(frame: RenderFramePacket, width: int, height: int, point_scale: float = 1.0) -> np.ndarray: +def rasterize_frame_rgba( + frame: RenderFramePacket, + width: int, + height: int, + point_scale: float = 1.0, + camera: VirtualCamera | None = None, +) -> np.ndarray: image = np.zeros((height, width, 4), dtype=np.uint8) image[:, :, 0] = 7 image[:, :, 1] = 10 image[:, :, 2] = 15 image[:, :, 3] = 255 - draw_reconstruction_guides(image) - draw_floor_shadows(image, frame, point_scale) + draw_reconstruction_guides(image, camera) + draw_floor_shadows(image, frame, point_scale, camera) canvas = image.astype(np.float32) / 255.0 - for brush in lower_frame_to_screen_brushes(frame, width, height, point_scale): + for brush in lower_frame_to_screen_brushes(frame, width, height, point_scale, camera): composite_gaussian_brush(canvas, brush) return np.clip(canvas * 255.0, 0.0, 255.0).astype(np.uint8) @@ -303,11 +371,11 @@ def project_world_to_screen( return px, py, float(ndc[2]), float(clip[3]) -def draw_reconstruction_guides(image: np.ndarray) -> None: +def draw_reconstruction_guides(image: np.ndarray, camera: VirtualCamera | None = None) -> None: import cv2 height, width = image.shape[:2] - view_proj = camera_matrix(0.0, width / max(1, height)) + view_proj = camera_matrix(0.0, width / max(1, height), camera) grid_color = (36, 50, 62, 255) wall_color = (24, 36, 50, 255) for x in np.linspace(-1.8, 1.8, 13): @@ -319,11 +387,16 @@ def draw_reconstruction_guides(image: np.ndarray) -> None: for z in np.linspace(0.35, 2.1, 6): draw_world_line(image, view_proj, np.array([-1.8, 1.15, z]), np.array([1.8, 1.15, z]), wall_color, 1) -def draw_floor_shadows(image: np.ndarray, frame: RenderFramePacket, point_scale: float) -> None: +def draw_floor_shadows( + image: np.ndarray, + frame: RenderFramePacket, + point_scale: float, + camera: VirtualCamera | None = None, +) -> None: import cv2 height, width = image.shape[:2] - view_proj = camera_matrix(0.0, width / max(1, height)) + view_proj = camera_matrix(0.0, width / max(1, height), camera) for point in frame.points: xyz = np.asarray(point.xyz, dtype=np.float64) if xyz[2] <= 0.10 or point.stable_key.startswith(("sensor:", "frustum:")): @@ -443,6 +516,7 @@ class OpenGLSpoutPointRenderer: self.vbo = None self.vao = None self.frames_sent = 0 + self.last_render_point_count = 0 def __enter__(self) -> "OpenGLSpoutPointRenderer": self.open() @@ -565,20 +639,23 @@ class OpenGLSpoutPointRenderer: assert self.vbo is not None assert self.vao is not None - vertices = frame_to_vertex_array(frame, self.config.point_scale) + render_frame = frame_with_point_budget(frame, self.config.max_render_points) + self.last_render_point_count = len(render_frame.points) + vertices = frame_to_vertex_array(render_frame, self.config.point_scale) glBindFramebuffer(GL_FRAMEBUFFER, self.fbo) glViewport(0, 0, self.config.width, self.config.height) glClearColor(0.025, 0.035, 0.048, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glUseProgram(self.program) - view_proj = camera_matrix(time.monotonic(), self.config.width / max(1, self.config.height)) + camera = camera_preset(self.config.camera_preset, time.monotonic()) + view_proj = camera_matrix(time.monotonic(), self.config.width / max(1, self.config.height), camera) glUniformMatrix4fv(glGetUniformLocation(self.program, "u_view_proj"), 1, GL_TRUE, view_proj.astype(np.float32)) glUniform2f(glGetUniformLocation(self.program, "u_viewport"), float(self.config.width), float(self.config.height)) glBindVertexArray(self.vao) glBindBuffer(GL_ARRAY_BUFFER, self.vbo) glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_DYNAMIC_DRAW) glDrawArrays(GL_POINTS, 0, len(vertices)) - image = rasterize_frame_rgba(frame, self.config.width, self.config.height, self.config.point_scale) + image = rasterize_frame_rgba(render_frame, self.config.width, self.config.height, self.config.point_scale, camera) glBindTexture(GL_TEXTURE_2D, self.texture) glTexSubImage2D( GL_TEXTURE_2D, @@ -604,11 +681,29 @@ class OpenGLSpoutPointRenderer: self.sender = None -def camera_matrix(now_s: float, aspect: float) -> np.ndarray: - eye = np.array([2.4 * math.sin(now_s * 0.08), -3.4, 1.85 + 0.2 * math.cos(now_s * 0.11)], dtype=np.float64) - target = np.array([0.0, 0.0, 1.15], dtype=np.float64) - up = np.array([0.0, 0.0, 1.0], dtype=np.float64) - return perspective(math.radians(58.0), aspect, 0.05, 50.0) @ look_at(eye, target, up) +def camera_preset(name: str, now_s: float = 0.0) -> VirtualCamera: + if name == "orbit": + return VirtualCamera( + eye=(2.4 * math.sin(now_s * 0.08), -3.4, 1.85 + 0.2 * math.cos(now_s * 0.11)), + target=(0.0, 0.0, 1.15), + fov_degrees=58.0, + ) + if name == "kiyo-mid-deru": + return VirtualCamera( + eye=(0.05, -1.035, 1.64), + target=(0.48, 0.28, 1.24), + fov_degrees=64.0, + ) + raise ValueError(f"unknown camera preset: {name}") + + +def camera_matrix(now_s: float, aspect: float, camera: VirtualCamera | None = None) -> np.ndarray: + view = camera_preset("orbit", now_s) if camera is None else camera + return perspective(math.radians(view.fov_degrees), aspect, view.near_m, view.far_m) @ look_at( + view.eye_np, + view.target_np, + view.up_np, + ) def look_at(eye: np.ndarray, target: np.ndarray, up: np.ndarray) -> np.ndarray: diff --git a/notes/current-system-map.md b/notes/current-system-map.md index a34ac52..eb9eb7b 100644 --- a/notes/current-system-map.md +++ b/notes/current-system-map.md @@ -101,7 +101,7 @@ Ownership: - `localcast.sensor_fusion.cultcache_docs` owns typed visual state documents. - `scripts/live_sensor_fusion.py` currently owns the live producer and writes `localcast.visual.render_frame` into CultCache. - The live producer also writes a multi-LOD scene cache with source kind and priority. Real Leap frames are the highest-priority timing/spatial evidence; Leap fallback frames are tagged as fallback and do not become ground truth. -- `scripts/stream_spout.py` consumes typed CultCache state and publishes Spout. +- `scripts/stream_spout.py` consumes typed CultCache state and publishes Spout. Its presentation camera defaults to `kiyo-mid-deru`: the virtual eye sits halfway between the two Kiyo-class cameras and aims at the co-streamer body target. Its render budget is temporal: high-confidence anchors stay stable while the remaining samples rotate by frame id for TAA/supersampling reconciliation. - CultNet document replication is the intended API boundary for other producers/consumers. Invariant: JSON is not the visual-state authority. The current renderer can still write a JSON heartbeat for human inspection, but live visual state lives in typed CultCache MessagePack documents. Leap outranks camera surfaces only when the frame source is actual Leap capture; diagnostics must stay labeled as diagnostics. diff --git a/scripts/stream_spout.py b/scripts/stream_spout.py index cdb5dc7..25bb657 100644 --- a/scripts/stream_spout.py +++ b/scripts/stream_spout.py @@ -45,6 +45,8 @@ def main() -> None: parser.add_argument("--height", type=int, default=1080) parser.add_argument("--fps", type=float, default=60.0) parser.add_argument("--point-scale", type=float, default=1.0) + parser.add_argument("--camera-preset", choices=["kiyo-mid-deru", "orbit"], default="kiyo-mid-deru") + parser.add_argument("--max-render-points", type=int, default=5000) parser.add_argument("--demo-if-missing", action="store_true") parser.add_argument("--demo-point-count", type=int, default=4096) parser.add_argument("--status", default=str(ROOT / "calibration" / "runs" / "stream-spout-status.json")) @@ -78,6 +80,8 @@ def main() -> None: fps=args.fps, point_scale=args.point_scale, demo_point_count=args.demo_point_count, + camera_preset=args.camera_preset, + max_render_points=args.max_render_points, ) if args.source == "cultcache": source = CultCacheRenderFrameSource( @@ -134,7 +138,7 @@ def main() -> None: status_path, sender_name=config.sender_name, frames_sent=renderer.frames_sent, - point_count=len(frame.points), + point_count=renderer.last_render_point_count, frame_path=Path(frame_source_name), last_error=None if ok else "SpoutGL sendTexture returned false", ) @@ -142,7 +146,7 @@ def main() -> None: status_cache_path, sender_name=config.sender_name, frames_sent=renderer.frames_sent, - point_count=len(frame.points), + point_count=renderer.last_render_point_count, frame_source=frame_source_name, last_error=None if ok else "SpoutGL sendTexture returned false", ) diff --git a/state/map.yaml b/state/map.yaml index d13d1b0..92c6634 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -114,7 +114,11 @@ research: not desktop capture or file polling. LocalCastBridge emits typed render-frame packets with source timestamps, intended presentation time, audio-alignment time, target size, Spout sender name, and point/brush - claims. Aquarium owns GPU rendering and Spout publication. + claims. The deadline Spout sink now defaults to a `kiyo-mid-deru` + virtual camera, with the eye halfway between the two Kiyo-class cameras + and the target on the co-streamer body volume. Its point budget is + temporal: stable high-confidence anchors plus a frame-varying remainder + for TAA/supersampling. Aquarium owns GPU rendering and Spout publication. live_spout_deadline_sink: summary: docs/obs-spout-streaming.md key_decision: > diff --git a/tests/test_sensor_fusion.py b/tests/test_sensor_fusion.py index dc02f87..8eb0395 100644 --- a/tests/test_sensor_fusion.py +++ b/tests/test_sensor_fusion.py @@ -24,8 +24,10 @@ from localcast.sensor_fusion import ( SpoutOutputConfig, TimestampedFrame, TrackCache, + VirtualCamera, detect_clap_events, frame_to_vertex_array, + frame_with_point_budget, dense_stereo_points, get_live_clap_events, get_live_render_frame, @@ -196,6 +198,105 @@ class SensorFusionTests(unittest.TestCase): config = SpoutOutputConfig(sender_name="unit-test", width=128, height=72, fps=30) self.assertEqual("unit-test", config.sender_name) self.assertEqual(128, config.width) + self.assertEqual("kiyo-mid-deru", config.camera_preset) + + def test_kiyo_midpoint_camera_frames_deru_target(self): + frame = RenderFramePacket( + schema="localcast.sensor_fusion.render_frame.v1", + frame_id=1, + created_monotonic_ns=1, + source_time_min_ns=1, + source_time_max_ns=1, + present_time_ns=1, + audio_alignment_time_ns=1, + spout_sender_name="test", + target_width=320, + target_height=180, + points=( + RenderPointPacket( + stable_key="deru-focus", + xyz=np.array([0.48, 0.28, 1.24]), + radius_m=0.06, + color_rgba=(0.2, 1.0, 0.7, 1.0), + confidence=1.0, + source_timestamp_ns=1, + ), + ), + ) + camera = VirtualCamera(eye=(0.05, -1.035, 1.64), target=(0.48, 0.28, 1.24), fov_degrees=64.0) + + brushes = lower_frame_to_screen_brushes(frame, width=320, height=180, camera=camera) + + self.assertEqual(1, len(brushes)) + self.assertAlmostEqual(160, brushes[0].center_px[0], delta=8) + self.assertAlmostEqual(90, brushes[0].center_px[1], delta=8) + + def test_render_point_budget_preserves_high_confidence_claims_and_rotates_remainder(self): + def make_frame(frame_id): + return RenderFramePacket( + schema="localcast.sensor_fusion.render_frame.v1", + frame_id=frame_id, + created_monotonic_ns=1, + source_time_min_ns=1, + source_time_max_ns=1, + present_time_ns=1, + audio_alignment_time_ns=1, + spout_sender_name="test", + target_width=320, + target_height=180, + points=tuple( + RenderPointPacket( + stable_key=f"point-{index}", + xyz=np.array([0.0, 0.0, 1.0 + index * 0.01]), + radius_m=0.02, + color_rgba=(1.0, 1.0, 1.0, 1.0), + confidence=index / 10.0, + source_timestamp_ns=1, + ) + for index in range(10) + ), + ) + + first = frame_with_point_budget(make_frame(1), 4) + second = frame_with_point_budget(make_frame(2), 4) + + self.assertEqual(4, len(first.points)) + self.assertEqual(4, len(second.points)) + self.assertTrue({"point-8", "point-9"}.issubset({point.stable_key for point in first.points})) + self.assertTrue({"point-8", "point-9"}.issubset({point.stable_key for point in second.points})) + self.assertNotEqual( + {point.stable_key for point in first.points}, + {point.stable_key for point in second.points}, + ) + + def test_render_point_budget_keeps_all_points_when_under_budget(self): + frame = RenderFramePacket( + schema="localcast.sensor_fusion.render_frame.v1", + frame_id=1, + created_monotonic_ns=1, + source_time_min_ns=1, + source_time_max_ns=1, + present_time_ns=1, + audio_alignment_time_ns=1, + spout_sender_name="test", + target_width=320, + target_height=180, + points=tuple( + RenderPointPacket( + stable_key=f"point-{index}", + xyz=np.array([0.0, 0.0, 1.0 + index * 0.01]), + radius_m=0.02, + color_rgba=(1.0, 1.0, 1.0, 1.0), + confidence=index / 10.0, + source_timestamp_ns=1, + ) + for index in range(10) + ), + ) + + limited = frame_with_point_budget(frame, 20) + + self.assertIs(frame, limited) def test_rasterizer_uses_gaussian_envelope_not_solid_ellipse(self): frame = RenderFramePacket(