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72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
"""Rendering kernels extracted from the local RoboSnap/Marble pipeline.
No original source files are modified. Camera-gauge normalization and SH0 match
accepted GS renders; foreground uses the original pyrender material settings.
"""
from __future__ import annotations
import json
import math
import os
import sys
from pathlib import Path
from typing import Any
os.environ.setdefault("PYOPENGL_PLATFORM", "egl")
os.environ['PATH'] = str(Path(sys.executable).parent) + os.pathsep + os.environ.get('PATH', '')

class ContractError(ValueError):
    pass

def load_gaussians(path: Path, device: str):
    import numpy as np
    import torch
    from plyfile import PlyData

    vertices = PlyData.read(str(path))["vertex"].data
    names = set(vertices.dtype.names or ())
    required = {
        "x",
        "y",
        "z",
        "f_dc_0",
        "f_dc_1",
        "f_dc_2",
        "opacity",
        "scale_0",
        "scale_1",
        "scale_2",
        "rot_0",
        "rot_1",
        "rot_2",
        "rot_3",
    }
    missing = sorted(required - names)
    if missing:
        raise ValueError(f"{path} is not a Gaussian PLY; missing: {', '.join(missing)}")

    stack = lambda keys: np.column_stack([vertices[key].astype(np.float32, copy=False) for key in keys])
    means_np = stack(["x", "y", "z"])
    scales_np = np.exp(stack(["scale_0", "scale_1", "scale_2"]))
    quats_np = stack(["rot_0", "rot_1", "rot_2", "rot_3"])
    quats_np /= np.clip(np.linalg.norm(quats_np, axis=1, keepdims=True), 1e-12, None)
    opacities_np = 1.0 / (1.0 + np.exp(-vertices["opacity"].astype(np.float32, copy=False)))
    dc = stack(["f_dc_0", "f_dc_1", "f_dc_2"])
    rest_names = sorted(
        (name for name in names if name.startswith("f_rest_")),
        key=lambda name: int(name.rsplit("_", 1)[1]),
    )
    if rest_names:
        rest = stack(rest_names)
        if rest.shape[1] % 3:
            raise ValueError(f"Unexpected SH field count in {path}: {rest.shape[1]}")
        rest = rest.reshape(len(rest), 3, rest.shape[1] // 3)
        harmonics_np = np.concatenate([dc[:, :, None], rest], axis=2).transpose(0, 2, 1)
    else:
        harmonics_np = dc[:, None, :]

    to_device = lambda array: torch.from_numpy(np.ascontiguousarray(array)).to(device=device)
    return {
        "means": to_device(means_np),
        "scales": to_device(scales_np),
        "quats": to_device(quats_np),
        "opacities": to_device(opacities_np),
        "harmonics": to_device(harmonics_np),
        "means_np": means_np,
        "dc_np": dc,
    }

def render_gaussians(gaussians, w2c, k, width: int, height: int, background_color):
    import numpy as np
    import torch
    from gsplat import rasterization

    view = torch.from_numpy(np.asarray(w2c, dtype=np.float32)).to(gaussians["means"].device)[None]
    intrinsics = torch.from_numpy(np.asarray(k, dtype=np.float32)).to(gaussians["means"].device)[None]
    background = torch.tensor(background_color, dtype=torch.float32, device=gaussians["means"].device)[None]
    degree = int(round(gaussians["harmonics"].shape[1] ** 0.5)) - 1
    rendered, alpha, _ = rasterization(
        means=gaussians["means"],
        quats=gaussians["quats"],
        scales=gaussians["scales"],
        opacities=gaussians["opacities"],
        colors=gaussians["harmonics"],
        viewmats=view,
        Ks=intrinsics,
        width=width,
        height=height,
        backgrounds=background,
        render_mode="RGB+ED",
        packed=False,
        sh_degree=degree,
    )
    rgb = rendered[0, :, :, :3].clamp(0.0, 1.0).detach().cpu().numpy()
    depth = rendered[0, :, :, 3].detach().cpu().numpy()
    coverage = alpha[0, :, :, 0].detach().cpu().numpy()
    return rgb, depth, coverage


def load_camera(path: Path, frame_index: int, width: int | None, height: int | None):
    import numpy as np

    data = np.load(path)
    if "w2c_render" not in data:
        raise KeyError(f"w2c_render is missing from {path}")
    intrinsic_key = next(
        (key for key in ("intrinsics_render", "intrinsics_vipe", "intrinsics_da3_pred") if key in data),
        None,
    )
    if intrinsic_key is None:
        raise KeyError(f"No render intrinsics found in {path}")
    w2cs = np.asarray(data["w2c_render"], dtype=np.float64)
    intrinsics = np.asarray(data[intrinsic_key], dtype=np.float64)
    idx = max(0, min(int(frame_index), len(w2cs) - 1))
    w2c = w2cs[idx]
    if w2c.shape == (3, 4):
        padded = np.eye(4, dtype=np.float64)
        padded[:3, :4] = w2c
        w2c = padded
    k = intrinsics[min(idx, len(intrinsics) - 1)].copy()
    source_width = max(1, int(round(2.0 * float(k[0, 2]))))
    source_height = max(1, int(round(2.0 * float(k[1, 2]))))
    target_width = int(width or source_width)
    target_height = int(height or source_height)
    if (target_width, target_height) != (source_width, source_height):
        k[0, :] *= target_width / source_width
        k[1, :] *= target_height / source_height
    return w2c, k, target_width, target_height, idx, intrinsic_key


def load_foreground_intrinsics(path: Path, width: int, height: int):
    import numpy as np

    data = json.loads(path.read_text(encoding="utf-8"))
    if "intrinsic_original_pixels" not in data or "original_size_wh" not in data:
        raise KeyError(f"VGGT original-pixel intrinsics are missing from {path}")
    k = np.asarray(data["intrinsic_original_pixels"], dtype=np.float64).copy()
    source_width, source_height = (int(value) for value in data["original_size_wh"])
    k[0, :] *= width / source_width
    k[1, :] *= height / source_height
    return k, "intrinsic_original_pixels"


def load_gravity_camera(path: Path, w2c_background):
    import numpy as np

    data = json.loads(path.read_text(encoding="utf-8"))
    transform = np.asarray(data["transform_gravity_from_background"], dtype=np.float64)
    return np.asarray(w2c_background, dtype=np.float64) @ np.linalg.inv(transform), data


def render_mesh(path: Path, w2c, k, width: int, height: int):
    import numpy as np
    import pyrender
    import trimesh

    mesh_scene = trimesh.load(str(path), force="scene", process=False)
    if not isinstance(mesh_scene, trimesh.Scene):
        wrapped = trimesh.Scene()
        wrapped.add_geometry(mesh_scene)
        mesh_scene = wrapped
    scene = pyrender.Scene.from_trimesh_scene(
        mesh_scene,
        bg_color=np.array([0.0, 0.0, 0.0, 0.0]),
        ambient_light=np.array([0.75, 0.75, 0.75]),
    )
    camera = pyrender.IntrinsicsCamera(
        fx=float(k[0, 0]),
        fy=float(k[1, 1]),
        cx=float(k[0, 2]),
        cy=float(k[1, 2]),
        znear=0.01,
        zfar=10000.0,
    )
    cv_to_gl = np.diag([1.0, -1.0, -1.0, 1.0])
    camera_pose = np.linalg.inv(w2c) @ cv_to_gl
    scene.add(camera, pose=camera_pose)
    scene.add(pyrender.DirectionalLight(color=np.ones(3), intensity=2.0), pose=camera_pose)
    renderer = pyrender.OffscreenRenderer(viewport_width=width, viewport_height=height)
    try:
        color, depth = renderer.render(
            scene,
            flags=pyrender.RenderFlags.RGBA | pyrender.RenderFlags.SKIP_CULL_FACES,
        )
    finally:
        renderer.delete()
    return color.astype(np.float32) / 255.0, depth.astype(np.float32)


def stack_fields(vertices: Any, names: list[str]) -> Any:
    import numpy as np

    return np.column_stack(
        [vertices[name].astype(np.float32, copy=False) for name in names]
    )


def render_gaussian_vertices(
    vertices: Any,
    w2c: Any,
    intrinsic: Any,
    width: int,
    height: int,
    device: str,
) -> tuple[Any, Any, Any]:
    import numpy as np
    import torch
    from gsplat import rasterization

    means_np = stack_fields(vertices, ["x", "y", "z"])
    scales_np = np.exp(stack_fields(vertices, ["scale_0", "scale_1", "scale_2"]))
    quats_np = stack_fields(vertices, ["rot_0", "rot_1", "rot_2", "rot_3"])
    quat_norm = np.linalg.norm(quats_np, axis=1, keepdims=True)
    if not np.isfinite(means_np).all() or not np.isfinite(scales_np).all():
        raise ContractError("Gaussian means/scales contain non-finite values")
    if np.any(quat_norm <= 1e-12) or not np.isfinite(quat_norm).all():
        raise ContractError("Gaussian quaternion is zero or non-finite")
    quats_np /= quat_norm
    opacity_np = 1.0 / (
        1.0 + np.exp(-vertices["opacity"].astype(np.float32, copy=False))
    )
    harmonics_np = stack_fields(vertices, ["f_dc_0", "f_dc_1", "f_dc_2"])[
        :, None, :
    ]
    to_device = lambda array: torch.from_numpy(np.ascontiguousarray(array)).to(device=device)
    tensors = {
        "means": to_device(means_np),
        "scales": to_device(scales_np),
        "quats": to_device(quats_np),
        "opacities": to_device(opacity_np),
        "colors": to_device(harmonics_np),
    }
    view = torch.from_numpy(np.asarray(w2c, dtype=np.float32))[None].to(device=device)
    k_tensor = torch.from_numpy(np.asarray(intrinsic, dtype=np.float32))[None].to(device=device)
    background = torch.tensor([[0.96, 0.96, 0.96]], dtype=torch.float32, device=device)
    with torch.inference_mode():
        rendered, alpha, _ = rasterization(
            means=tensors["means"],
            quats=tensors["quats"],
            scales=tensors["scales"],
            opacities=tensors["opacities"],
            colors=tensors["colors"],
            viewmats=view,
            Ks=k_tensor,
            width=int(width),
            height=int(height),
            backgrounds=background,
            render_mode="RGB+ED",
            packed=False,
            sh_degree=0,
        )
    output = rendered[0].detach().cpu().numpy()
    coverage = alpha[0, :, :, 0].detach().cpu().numpy()
    rgb = np.clip(output[:, :, :3], 0.0, 1.0)
    depth = output[:, :, 3]
    del tensors, rendered, alpha, output, view, k_tensor, background
    if device.startswith("cuda"):
        torch.cuda.empty_cache()
    return rgb, depth, coverage


def quaternion_multiply_wxyz(first: Any, second: Any) -> Any:
    import numpy as np

    w1, x1, y1, z1 = np.moveaxis(np.asarray(first), -1, 0)
    w2, x2, y2, z2 = np.moveaxis(np.asarray(second), -1, 0)
    return np.column_stack(
        [
            w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2,
            w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
            w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2,
            w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2,
        ]
    )


def normalize_reloaded_output_for_render(
    vertices: Any,
    extrinsic_4x4: Any,
    intrinsic: Any,
    gauge_scale: float,
) -> tuple[Any, dict[str, Any]]:
    """Numerically normalize a reloaded output PLY for an equivalent camera render."""

    import numpy as np
    from scipy.spatial.transform import Rotation

    if not math.isfinite(gauge_scale) or gauge_scale <= 0.0:
        raise ContractError("render normalization requires a finite positive gauge")
    extrinsic = np.asarray(extrinsic_4x4, dtype=np.float64)
    intrinsic = np.asarray(intrinsic, dtype=np.float64)
    normalized = vertices.copy()
    xyz_world = stack_fields(vertices, ["x", "y", "z"]).astype(np.float64)
    xyz_camera = (extrinsic[:3, :3] @ xyz_world.T).T + extrinsic[:3, 3]
    xyz_normalized = xyz_camera / gauge_scale
    for index, name in enumerate(("x", "y", "z")):
        normalized[name] = xyz_normalized[:, index].astype(normalized[name].dtype)

    log_gauge = math.log(gauge_scale)
    for name in ("scale_0", "scale_1", "scale_2"):
        normalized[name] = (
            vertices[name].astype(np.float64) - log_gauge
        ).astype(normalized[name].dtype)

    quaternions_world = stack_fields(
        vertices, ["rot_0", "rot_1", "rot_2", "rot_3"]
    ).astype(np.float64)
    quaternions_world /= np.linalg.norm(
        quaternions_world, axis=1, keepdims=True
    )
    xyzw = Rotation.from_matrix(extrinsic[:3, :3]).as_quat()
    quaternion_camera_from_world = np.asarray(
        [[xyzw[3], xyzw[0], xyzw[1], xyzw[2]]],
        dtype=np.float64,
    )
    quaternions_camera = quaternion_multiply_wxyz(
        quaternion_camera_from_world, quaternions_world
    )
    quaternions_camera /= np.linalg.norm(
        quaternions_camera, axis=1, keepdims=True
    )
    for index, name in enumerate(("rot_0", "rot_1", "rot_2", "rot_3")):
        normalized[name] = quaternions_camera[:, index].astype(
            normalized[name].dtype
        )

    sample = np.linspace(
        0, len(vertices) - 1, min(20000, len(vertices)), dtype=np.int64
    )
    before = xyz_camera[sample]
    after = np.column_stack(
        [
            normalized[name][sample].astype(np.float64)
            for name in ("x", "y", "z")
        ]
    )
    reconstructed = gauge_scale * after
    relative_position_error = np.linalg.norm(
        reconstructed - before, axis=1
    ) / np.maximum(np.linalg.norm(before, axis=1), 1e-8)
    valid = (
        np.isfinite(before).all(axis=1)
        & np.isfinite(after).all(axis=1)
        & (np.abs(before[:, 2]) > 1e-6)
        & (np.abs(after[:, 2]) > 1e-6)
    )
    if int(valid.sum()) < 100:
        raise ContractError("too few finite points for render-normalization proof")

    def project(points: Any) -> Any:
        return np.column_stack(
            [
                intrinsic[0, 0] * points[:, 0] / points[:, 2] + intrinsic[0, 2],
                intrinsic[1, 1] * points[:, 1] / points[:, 2] + intrinsic[1, 2],
            ]
        )

    projection_error = np.linalg.norm(
        project(before[valid]) - project(after[valid]), axis=1
    )
    normalized_quaternions = np.column_stack(
        [
            normalized[name][sample].astype(np.float64)
            for name in ("rot_0", "rot_1", "rot_2", "rot_3")
        ]
    )
    normalized_quaternions /= np.linalg.norm(
        normalized_quaternions, axis=1, keepdims=True
    )
    expected_orientation = np.einsum(
        "ij,njk->nik",
        extrinsic[:3, :3],
        Rotation.from_quat(
            quaternions_world[sample][:, [1, 2, 3, 0]]
        ).as_matrix(),
    )
    actual_orientation = Rotation.from_quat(
        normalized_quaternions[:, [1, 2, 3, 0]]
    ).as_matrix()
    relative_orientation = np.einsum(
        "nij,nkj->nik", expected_orientation, actual_orientation
    )
    orientation_error_deg = np.rad2deg(
        Rotation.from_matrix(relative_orientation).magnitude()
    )
    scale_reconstruction_error = np.max(
        np.abs(
            np.column_stack(
                [
                    normalized[name][sample].astype(np.float64)
                    + log_gauge
                    - vertices[name][sample].astype(np.float64)
                    for name in ("scale_0", "scale_1", "scale_2")
                ]
            )
        ),
        axis=1,
    )
    return normalized, {
        "source": "reloaded aligned output PLY",
        "source_reloaded_after_full_resolution_write": True,
        "normalization": (
            "world means -> camera means / gauge; log-scales -= log(gauge); "
            "quaternions left-multiplied by camera rotation; identity view"
        ),
        "camera_centered_numerical_normalization_scale": gauge_scale,
        "single_view_projection_semantics_changed": False,
        "output_file_modified_by_normalization": False,
        "gaussian_count": len(vertices),
        "sample_count": len(sample),
        "finite_projection_samples": int(valid.sum()),
        "projection_error_p99_px": float(np.quantile(projection_error, 0.99)),
        "projection_error_max_px": float(projection_error.max()),
        "relative_position_error_p99": float(
            np.quantile(relative_position_error, 0.99)
        ),
        "relative_position_error_max": float(relative_position_error.max()),
        "orientation_error_p99_deg": float(
            np.quantile(orientation_error_deg, 0.99)
        ),
        "orientation_error_max_deg": float(orientation_error_deg.max()),
        "log_scale_reconstruction_error_max": float(
            scale_reconstruction_error.max()
        ),
    }