Files
NODEDC_MISSION_CORE/simulation/urban-plan-research/multiview/mv_render.py
T
DCCONSTRUCTIONS 69dc566665 feat(research): preserve urban geometry pipelines and qualification suites
Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
2026-10-29 09:10:00 +03:00

78 lines
3.8 KiB
Python

"""Unclipped street-level Gaussian RGB/depth views at original scan positions."""
import time, math, gc
from pathlib import Path
import numpy as np
import torch
from PIL import Image
from plyfile import PlyData
from gsplat import rasterization
from mapping import camera
from coordinate_cache import transformed
from mv_io import RUN, SURVEY, read, write, digest, record, guard
start = time.monotonic()
plan = read(RUN / 'cameras.json')
request = read(SURVEY / 'request.json')
source = Path('/input') / request['source']['ply']
assert digest(source) == request['source']['sha256']
transform = np.asarray(request['source']['source_to_world'], np.float64)
assert transform.shape == (4, 4) and np.allclose(transform[:3, :3].T @ transform[:3, :3], np.eye(3))
data = PlyData.read(source, mmap='r')['vertex'].data
world = transformed(data, transform, str(source), proof_path=RUN / 'coordinate-cache-proof.json')
folder = RUN / 'views'
folder.mkdir(exist_ok=True)
signature = dict(source_sha256=digest(source), camera_sha256=digest(RUN / 'cameras.json'), implementation=digest(__file__))
rest = sorted([n for n in data.dtype.names if n.startswith('f_rest_')], key=lambda n: int(n.split('_')[-1]))
records = []
for station in plan['stations']:
guard()
receipt = folder / (station['id'] + '.json')
if receipt.exists():
old = read(receipt)
if old['inputs'] != signature or any(digest(folder / n) != h for n, h in old['files'].items()):
raise RuntimeError('Stale render cache')
records.append(old)
continue
eye = np.asarray(station['eye'])
mask = (abs(world[:, 0] - eye[0]) <= 35) & (abs(world[:, 1] - eye[1]) <= 35)
d = data[mask].copy()
del mask
if not len(d):
raise ValueError('No Gaussian support at scan station')
def tensor(names):
return torch.tensor(np.column_stack([d[n] for n in names]), device='cuda', dtype=torch.float32)
means = tensor(['x', 'y', 'z'])
quats = tensor([f'rot_{i}' for i in range(4)])
scales = tensor([f'scale_{i}' for i in range(3)]).exp()
opacity = tensor(['opacity']).squeeze(-1).sigmoid()
dc = tensor([f'f_dc_{i}' for i in range(3)])[:, None, :]
sh = torch.cat([dc, tensor(rest).reshape(len(d), 3, -1).transpose(1, 2)], dim=1) if rest else dc
degree = int(math.sqrt(sh.shape[1])) - 1
files = {}
for spec in station['views']:
view, k = camera(spec)
w, h = spec['size']
with torch.inference_mode():
rgbd, alpha, _ = rasterization(means, quats, scales, opacity, sh,
torch.tensor(view @ transform, device='cuda', dtype=torch.float32)[None],
torch.tensor(k, device='cuda')[None], w, h, sh_degree=degree,
camera_model='pinhole', render_mode='RGB+ED', packed=True)
rgbd = rgbd[0].cpu().numpy()
alpha = alpha[0, :, :, 0].cpu().numpy()
rgbd[:, :, :3] += 1 - alpha[:, :, None]
name = spec['id']
Image.fromarray(np.uint8(np.clip(rgbd[:, :, :3], 0, 1) * 255)).save(folder / (name + '.png'))
np.savez_compressed(folder / (name + '.geometry.npz'), depth=rgbd[:, :, 3], alpha=alpha.astype(np.float16), view=view, intrinsics=k)
for suffix in ['.png', '.geometry.npz']:
files[name + suffix] = digest(folder / (name + suffix))
del rgbd, alpha
result = dict(station=station['id'], inputs=signature, files=files, splats=len(d))
write(receipt, result)
records.append(result)
del d, means, quats, scales, opacity, dc, sh
gc.collect()
torch.cuda.empty_cache()
record(dict(stage='render', completed=len(records), stations=len(plan['stations']), elapsed_s=time.monotonic() - start))
write(RUN / 'render-summary.json', dict(stations=len(records), views=sum(len(s['views']) for s in plan['stations']),
source=request['source'], seconds=time.monotonic() - start, inputs=signature))