Render deadline scene reconstruction to Spout

This commit is contained in:
Meta Vens 2026-05-18 19:16:15 +01:00
commit 9e064f4245
3 changed files with 277 additions and 22 deletions

View file

@ -32,6 +32,7 @@ class ScreenBrushPacket:
radii_px: tuple[int, int]
rotation_deg: float
color_rgba: tuple[int, int, int, int]
depth: float = 0.0
class RenderFrameFileSource:
@ -207,32 +208,37 @@ def lower_frame_to_screen_brushes(
point_scale: float = 1.0,
) -> tuple[ScreenBrushPacket, ...]:
brushes: list[ScreenBrushPacket] = []
view_proj = camera_matrix(0.0, width / max(1, height))
for point in frame.points:
x, y, z = point.xyz
px = int(round((0.5 + float(x) * 0.29) * width))
py = int(round((0.5 - ((float(z) - 1.18) * 0.575 + float(y) * 0.08)) * height))
radius = max(2, int(round(float(point.radius_m) * point_scale * height * 0.75)))
projected = project_world_to_screen(point.xyz, view_proj, width, height)
if projected is None:
continue
px, py, depth, clip_w = projected
radius = max(2, int(round(float(point.radius_m) * point_scale * height * 1.45 / max(0.42, clip_w))))
if px < -radius * 3 or px >= width + radius * 3 or py < -radius * 3 or py >= height + radius * 3:
continue
stable = hashlib.blake2s(point.stable_key.encode("utf-8"), digest_size=4).digest()
angle = int.from_bytes(stable[:2], "little") / 65535.0 * 180.0
stretch = 1.0 + (stable[2] / 255.0) * 1.8
semantic_stretch = 2.8 if point.stable_key.startswith(("frustum:", "ray:", "floor:", "wall:")) else 1.0
stretch = semantic_stretch * (1.0 + (stable[2] / 255.0) * 1.45)
radii = (max(2, int(round(radius * stretch))), radius)
rgba = np.clip(np.asarray(point.color_rgba, dtype=np.float32), 0.0, 1.0)
rgba[3] *= max(0.0, min(1.0, float(point.confidence)))
color = tuple(int(v) for v in (rgba * 255.0)[:4])
brushes.append(ScreenBrushPacket((px, py), radii, angle, color))
return tuple(brushes)
brushes.append(ScreenBrushPacket((px, py), radii, angle, color, depth))
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:
import cv2
image = np.zeros((height, width, 4), dtype=np.uint8)
image[:, :, 0] = 10
image[:, :, 1] = 14
image[:, :, 2] = 20
image[:, :, 0] = 7
image[:, :, 1] = 10
image[:, :, 2] = 15
image[:, :, 3] = 255
draw_reconstruction_guides(image)
draw_floor_shadows(image, frame, point_scale)
for brush in lower_frame_to_screen_brushes(frame, width, height, point_scale):
cv2.ellipse(
image,
@ -248,6 +254,92 @@ def rasterize_frame_rgba(frame: RenderFramePacket, width: int, height: int, poin
return image
def project_world_to_screen(
xyz: np.ndarray,
view_proj: np.ndarray,
width: int,
height: int,
) -> tuple[int, int, float, float] | None:
point = np.ones(4, dtype=np.float64)
point[:3] = np.asarray(xyz, dtype=np.float64)
clip = view_proj @ point
if clip[3] <= 0.001:
return None
ndc = clip[:3] / clip[3]
if ndc[0] < -1.35 or ndc[0] > 1.35 or ndc[1] < -1.35 or ndc[1] > 1.35:
return None
px = int(round((ndc[0] * 0.5 + 0.5) * width))
py = int(round((0.5 - ndc[1] * 0.5) * height))
return px, py, float(ndc[2]), float(clip[3])
def draw_reconstruction_guides(image: np.ndarray) -> None:
import cv2
height, width = image.shape[:2]
view_proj = camera_matrix(0.0, width / max(1, height))
grid_color = (36, 50, 62, 255)
wall_color = (24, 36, 50, 255)
for x in np.linspace(-1.8, 1.8, 13):
draw_world_line(image, view_proj, np.array([x, -1.0, 0.0]), np.array([x, 1.15, 0.0]), grid_color, 1)
for y in np.linspace(-1.0, 1.15, 9):
draw_world_line(image, view_proj, np.array([-1.8, y, 0.0]), np.array([1.8, y, 0.0]), grid_color, 1)
for x in np.linspace(-1.8, 1.8, 9):
draw_world_line(image, view_proj, np.array([x, 1.15, 0.0]), np.array([x, 1.15, 2.2]), wall_color, 1)
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)
sensors = [
(np.array([-0.78, -0.82, 1.34]), np.array([0.10, 0.72, 1.05]), (72, 160, 255, 255)),
(np.array([0.78, -0.82, 1.34]), np.array([-0.10, 0.72, 1.05]), (72, 160, 255, 255)),
(np.array([-0.28, -1.05, 1.62]), np.array([-0.15, 0.45, 1.15]), (255, 160, 72, 255)),
(np.array([0.38, -1.02, 1.66]), np.array([0.20, 0.48, 1.18]), (255, 160, 72, 255)),
(np.array([0.0, -0.18, 0.76]), np.array([0.0, 0.20, 1.05]), (120, 255, 185, 255)),
]
for origin, target, color in sensors:
draw_world_line(image, view_proj, origin, target, color, 2)
projected = project_world_to_screen(origin, view_proj, width, height)
if projected is not None:
cv2.circle(image, projected[:2], 5, color, thickness=-1, lineType=cv2.LINE_AA)
def draw_floor_shadows(image: np.ndarray, frame: RenderFramePacket, point_scale: float) -> None:
import cv2
height, width = image.shape[:2]
view_proj = camera_matrix(0.0, width / max(1, height))
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:")):
continue
shadow = xyz.copy()
shadow[2] = 0.012
projected = project_world_to_screen(shadow, view_proj, width, height)
if projected is None:
continue
px, py, _, clip_w = projected
radius = max(2, int(round(float(point.radius_m) * point_scale * height * 0.9 / max(0.42, clip_w))))
shade = int(18 + 18 * max(0.0, min(1.0, float(point.confidence))))
cv2.ellipse(image, (px, py), (radius * 2, max(1, radius // 2)), 0.0, 0.0, 360.0, (shade // 3, shade // 2, shade, 255), -1, cv2.LINE_AA)
def draw_world_line(
image: np.ndarray,
view_proj: np.ndarray,
start: np.ndarray,
end: np.ndarray,
color: tuple[int, int, int, int],
thickness: int,
) -> None:
import cv2
height, width = image.shape[:2]
a = project_world_to_screen(start, view_proj, width, height)
b = project_world_to_screen(end, view_proj, width, height)
if a is None or b is None:
return
cv2.line(image, a[:2], b[:2], color, thickness=thickness, lineType=cv2.LINE_AA)
def write_status(
path: Path,
*,

View file

@ -2,6 +2,7 @@ import argparse
from pathlib import Path
import sys
import time
from typing import BinaryIO
import numpy as np
@ -14,12 +15,31 @@ from localcast.sensor_fusion import (
FusionConfig,
Observation2D,
RenderBridgeConfig,
RenderFramePacket,
RenderPointPacket,
SensorRig,
put_live_render_frame,
lower_points_to_render_frame,
)
def acquire_runtime_lock(path: Path) -> BinaryIO | None:
import msvcrt
path.parent.mkdir(parents=True, exist_ok=True)
handle = path.open("a+b")
handle.seek(0)
handle.write(b"\0")
handle.flush()
handle.seek(0)
try:
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
except OSError:
handle.close()
return None
return handle
def camera(sensor_id: str, x: float) -> CameraModel:
return CameraModel(
sensor_id=sensor_id,
@ -43,24 +63,129 @@ def synthetic_observations(rig: SensorRig, now_s: float, count: int) -> list[Obs
right = rig.cameras["ps3eye_right"]
timestamp = time.monotonic_ns()
observations: list[Observation2D] = []
for index in range(count):
u = index / max(1, count)
theta = index * 2.399963229728653 + now_s * 0.65
radius = 0.12 + 1.05 * np.sqrt(u)
point = np.array(
[
radius * np.cos(theta),
radius * np.sin(theta),
1.25 + 0.45 * np.sin(index * 0.041 + now_s),
],
dtype=np.float64,
)
targets = reconstruction_targets(now_s, count)
for index, point in enumerate(targets):
marker = f"synthetic-fused-{index}"
observations.append(Observation2D("ps3eye_left", marker, timestamp, left.project_world(point), 0.95))
observations.append(Observation2D("ps3eye_right", marker, timestamp, right.project_world(point), 0.92))
return observations
def reconstruction_targets(now_s: float, count: int) -> list[np.ndarray]:
"""Deadline stand-in for real detections: two people plus tracked room support."""
body_count = max(32, int(count * 0.55))
room_count = max(24, int(count * 0.25))
marker_count = max(8, count - body_count - room_count)
targets: list[np.ndarray] = []
targets.extend(body_points("host", np.array([-0.42, 0.05, 0.0]), now_s, body_count // 2))
targets.extend(body_points("deru", np.array([0.48, 0.28, 0.0]), now_s + 0.7, body_count - body_count // 2))
targets.extend(room_support_points(now_s, room_count))
targets.extend(marker_points(now_s, marker_count))
return targets[: max(1, count)]
def body_points(name: str, origin: np.ndarray, now_s: float, count: int) -> list[np.ndarray]:
points: list[np.ndarray] = []
golden = 2.399963229728653
for index in range(max(1, count)):
u = (index + 0.5) / max(1, count)
theta = index * golden
if u < 0.22:
radius = 0.17 * np.sqrt(u / 0.22)
z = 1.55 + 0.16 * np.sin(theta)
local = np.array([radius * np.cos(theta), radius * np.sin(theta) * 0.72, z])
elif u < 0.72:
v = (u - 0.22) / 0.50
radius = 0.23 * (1.0 - abs(v - 0.52) * 0.55)
z = 0.72 + v * 0.72
sway = 0.035 * np.sin(now_s * 1.4 + (0.0 if name == "host" else 1.2))
local = np.array([radius * np.cos(theta) + sway, radius * np.sin(theta) * 0.52, z])
else:
v = (u - 0.72) / 0.28
side = -1.0 if index % 2 == 0 else 1.0
reach = 0.28 + 0.18 * np.sin(now_s * 1.7 + side)
z = 1.16 - 0.25 * v
local = np.array([side * reach * v, 0.06 * np.sin(theta), z])
points.append(origin + local)
return points
def room_support_points(now_s: float, count: int) -> list[np.ndarray]:
points: list[np.ndarray] = []
for index in range(max(1, count)):
u = (index + 0.5) / max(1, count)
if index % 3 == 0:
x = -1.65 + 3.3 * u
y = -0.85 + 1.75 * ((index * 7) % max(1, count)) / max(1, count)
z = 0.02
elif index % 3 == 1:
x = -1.65 + 3.3 * u
y = 1.05
z = 0.28 + 1.72 * ((index * 5) % max(1, count)) / max(1, count)
else:
x = -1.05 + 2.1 * ((index * 11) % max(1, count)) / max(1, count)
y = -0.65 + 0.12 * np.sin(now_s + index)
z = 0.85 + 0.95 * u
points.append(np.array([x, y, z], dtype=np.float64))
return points
def marker_points(now_s: float, count: int) -> list[np.ndarray]:
points: list[np.ndarray] = []
for index in range(max(1, count)):
theta = now_s * 0.9 + index * 2.399963229728653
ring = 0.28 + 0.52 * ((index % 5) / 4.0)
points.append(
np.array(
[
ring * np.cos(theta),
0.12 + ring * 0.42 * np.sin(theta * 0.7),
1.08 + 0.42 * np.sin(theta + index * 0.37),
],
dtype=np.float64,
)
)
return points
def reconstruction_context_points(now_s: float, timestamp_ns: int) -> tuple[RenderPointPacket, ...]:
points: list[RenderPointPacket] = []
cameras = [
("ps3eye-left", (-0.78, -0.82, 1.34), (0.10, 0.72, 1.05), (0.2, 0.7, 1.0, 0.95)),
("ps3eye-right", (0.78, -0.82, 1.34), (-0.10, 0.72, 1.05), (0.2, 0.7, 1.0, 0.95)),
("kiyo", (-0.28, -1.05, 1.62), (-0.15, 0.45, 1.15), (1.0, 0.62, 0.25, 0.95)),
("kiyo-pro", (0.38, -1.02, 1.66), (0.20, 0.48, 1.18), (1.0, 0.62, 0.25, 0.95)),
("leap", (0.0, -0.18, 0.76), (0.0, 0.20, 1.05), (0.55, 1.0, 0.72, 0.95)),
]
for sensor, origin, target, color in cameras:
origin_np = np.asarray(origin, dtype=np.float64)
target_np = np.asarray(target, dtype=np.float64)
points.append(render_point(f"sensor:{sensor}", origin_np, 0.055, color, 1.0, timestamp_ns))
for ray_index, t in enumerate((0.28, 0.48, 0.68, 0.88)):
p = origin_np + (target_np - origin_np) * t
jitter = np.array([0.04 * np.sin(now_s + ray_index), 0.0, 0.035 * np.cos(now_s * 0.7 + ray_index)])
points.append(render_point(f"frustum:{sensor}:{ray_index}", p + jitter, 0.014, color, 0.72, timestamp_ns))
return tuple(points)
def render_point(
key: str,
xyz: np.ndarray,
radius_m: float,
color: tuple[float, float, float, float],
confidence: float,
timestamp_ns: int,
) -> RenderPointPacket:
return RenderPointPacket(
stable_key=key,
xyz=np.asarray(xyz, dtype=np.float64),
radius_m=radius_m,
color_rgba=color,
confidence=confidence,
source_timestamp_ns=timestamp_ns,
)
def main() -> None:
parser = argparse.ArgumentParser(description="Write live sensor-fusion render frames into typed CultCache state.")
parser.add_argument("--cache", default=str(ROOT / "calibration" / "runs" / "visual-state.msgpack"))
@ -80,6 +205,9 @@ def main() -> None:
start = time.monotonic()
frame_id = 0
cache_path = Path(args.cache)
lock = acquire_runtime_lock(cache_path.with_suffix(".producer.lock"))
if lock is None:
return
while True:
now = time.monotonic()
if args.duration is not None and now - start >= args.duration:
@ -92,6 +220,20 @@ def main() -> None:
frame_id=frame_id,
created_monotonic_ns=time.monotonic_ns(),
)
timestamp_ns = frame.source_time_max_ns
frame = 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(frame.points) + reconstruction_context_points(now, timestamp_ns),
)
put_live_render_frame(cache_path, frame)
frame_id += 1
sleep_for = interval - (time.monotonic() - now)

View file

@ -2,6 +2,7 @@ import argparse
from pathlib import Path
import sys
import time
from typing import BinaryIO
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
@ -18,6 +19,23 @@ from localcast.sensor_fusion.spout_output import (
)
def acquire_runtime_lock(path: Path) -> BinaryIO | None:
import msvcrt
path.parent.mkdir(parents=True, exist_ok=True)
handle = path.open("a+b")
handle.seek(0)
handle.write(b"\0")
handle.flush()
handle.seek(0)
try:
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
except OSError:
handle.close()
return None
return handle
def main() -> None:
parser = argparse.ArgumentParser(description="Publish render-frame packets as a named Spout texture for OBS.")
parser.add_argument("--frame-json", default=str(ROOT / "calibration" / "runs" / "synthetic-render-frame.json"))
@ -50,6 +68,9 @@ def main() -> None:
status_path = Path(args.status)
status_cache_path = Path(args.status_cache)
sync_status_path = Path(args.sync_status)
lock = acquire_runtime_lock(status_path.with_suffix(".sender.lock"))
if lock is None:
return
config = SpoutOutputConfig(
sender_name=args.sender_name,
width=args.width,