File size: 11,744 Bytes
bf3194a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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
"""Level source-supported floors without changing radiance, opacity or XY covariance."""
import argparse
import gc
import json
import shutil
from pathlib import Path

import numpy as np
from scipy import ndimage as ndi
from scipy.spatial import cKDTree
from scipy.spatial.transform import Rotation
from pxr import Sdf, Usd, UsdGeom, UsdPhysics, UsdShade, Vt
from sharpa11_build import OUT, ROOT, save

WORK = ROOT / 'outputs/sharpa11_20261107_work'


def repair(directory):
    if (directory / 'floor_repair.json').exists():
        return
    backup = WORK / directory.name / 'before_flat_floor.usdc'
    backup.parent.mkdir(parents=True, exist_ok=True)
    if not backup.exists():
        shutil.copy2(directory / 'scene.usdc', backup)
    stage = Usd.Stage.Open(str(directory / 'scene.usdc'))
    field = stage.GetPrimAtPath('/World/Scan/Gaussians')
    M = np.asarray(UsdGeom.XformCache().GetLocalToWorldTransform(field))
    A, t = M[:3, :3], M[3, :3]
    x = np.asarray(field.GetAttribute('positions').Get()).copy()
    scales = np.asarray(field.GetAttribute('scales').Get()).copy()
    quat = np.asarray(field.GetAttribute('orientations').Get()).copy()
    opacity = np.asarray(field.GetAttribute('opacities').Get())
    sh = np.asarray(field.GetAttribute('radiance:sphericalHarmonicsCoefficients').Get())
    world = x @ A + t
    views = json.loads((directory / 'candidate_cameras.json').read_text())
    eyes = np.array([v['eye'] for v in views])
    low = eyes[:, :2].min(0) - 2.0
    high = eyes[:, :2].max(0) + 2.0
    resolution = .04
    shape = np.ceil((high-low)/resolution).astype(int)+2
    ij = np.floor((world[:, :2]-low)/resolution).astype(np.int32)
    inside = ((ij >= 0) & (ij < shape)).all(1)
    def lookup(grid, points):
        indices = np.floor((points-low)/resolution).astype(np.int32)
        valid = ((indices >= 0) & (indices < shape)).all(1)
        result = np.zeros(len(points), bool)
        result[valid] = grid[indices[valid, 0], indices[valid, 1]]
        return result
    obstacle = np.zeros(shape, bool)
    elevated = inside & (world[:, 2] > .22) & (world[:, 2] < 1.1) & (opacity > .35) & (scales.max(1) < .2)
    counts = np.zeros(shape, np.int32)
    np.add.at(counts, (ij[elevated, 0], ij[elevated, 1]), 1)
    obstacle = ndi.binary_dilation(counts >= 3, iterations=1)
    protected = np.zeros(len(x), bool)
    protected[inside] = obstacle[ij[inside, 0], ij[inside, 1]]
    up = np.zeros(len(x), np.float32)
    for start in range(0, len(x), 200000):
        sl = slice(start, start+200000)
        R = Rotation.from_quat(quat[sl]).as_matrix()
        normal = R[np.arange(len(R)), :, scales[sl].argmin(1)] @ A
        up[sl] = abs(normal[:, 2])
    ratio = scales.min(1) / np.maximum(scales.max(1), 1e-10)
    # Reliable horizontal surfels seed the floor. Protect feet and low furniture.
    seed = inside & ~protected & (abs(world[:, 2]) < .09) & (up > .85) & (ratio < .4) & (scales.max(1) < .4) & (opacity > .025)
    ids = np.flatnonzero(seed)
    assert len(ids) > 2000, (directory.name, len(ids))
    tree = cKDTree(world[ids, :2])
    possible = np.flatnonzero(inside & ~protected & ~seed & (world[:, 2] > -.30) & (world[:, 2] < .20) &
                             (up > .7) & (ratio < .55) & (scales.max(1) < .4) & (opacity > .025))
    d, nearest = tree.query(world[possible, :2], k=4, workers=8)
    rgb = np.clip(sh*.28209479177387814+.5, 0, 1.3)
    expected = np.median(rgb[ids[nearest]], axis=1)
    match = np.linalg.norm(rgb[possible] - expected, axis=1) < .32
    flat = seed.copy()
    flat[possible[(d[:, 0] < .12) & match]] = True
    ids = np.flatnonzero(flat)
    before = world[ids, 2].copy()
    max_covariance_error = 0.
    for start in range(0, len(ids), 150000):
        ii = ids[start:start+150000]
        R = Rotation.from_quat(quat[ii]).as_matrix()
        Rw = A.T @ R
        C = (Rw*scales[ii, None, :]**2) @ Rw.transpose(0, 2, 1)
        values, axes = np.linalg.eigh(C[:, :2, :2])
        basis = np.zeros((len(ii), 3, 3))
        basis[:, :2, :2] = axes
        basis[:, 2, 2] = 1.
        negative = np.linalg.det(basis) < 0
        basis[negative, :, 0] *= -1
        new_scales = np.c_[np.sqrt(np.maximum(values, 1e-12)), np.full(len(ii), .00045)]
        restored = (basis*new_scales[:, None, :]**2) @ basis.transpose(0, 2, 1)
        max_covariance_error = max(max_covariance_error, float(abs(restored[:, :2, :2]-C[:, :2, :2]).max()))
        scales[ii] = new_scales
        quat[ii] = Rotation.from_matrix(A @ basis).as_quat()
    world[ids, 2] = 0.
    x[ids] = (world[ids]-t) @ A.T
    field.GetAttribute('positions').Set(Vt.Vec3fArray.FromNumpy(x))
    field.GetAttribute('scales').Set(Vt.Vec3fArray.FromNumpy(scales))
    field.GetAttribute('orientations').Set(Vt.QuatfArray.FromNumpy(quat))
    # Observed footprint only; small holes under occluding furniture may be closed.
    footprint = np.zeros(shape, bool)
    near_floor = inside & (abs(world[:, 2]) < .20) & (up > .8) & (ratio < .5) & (opacity > .05)
    footprint[ij[near_floor, 0], ij[near_floor, 1]] = True
    footprint = ndi.binary_closing(ndi.binary_dilation(footprint, iterations=1), iterations=2)
    filled = ndi.binary_fill_holes(footprint)
    labels, _ = ndi.label(filled & ~footprint)
    sizes = np.bincount(labels.ravel())
    small = sizes < int(1.0/resolution**2); small[0] = False
    footprint |= small[labels]
    # Lower rough scan triangles in open floor to the same exact plane.
    moved_mesh_vertices = 0
    for prim in stage.GetPrimAtPath('/World/Scan/Collisions').GetChildren():
        geom = UsdGeom.Mesh(prim)
        v = np.asarray(geom.GetPointsAttr().Get()).copy()
        w = v @ A + t
        mask = lookup(footprint, w[:, :2]) & ~lookup(obstacle, w[:, :2]) & (w[:, 2] > -.40) & (w[:, 2] < .20)
        w[mask, 2] = -.001  # planar top is the unique walking surface
        v[mask] = (w[mask]-t) @ A.T
        faces = np.asarray(geom.GetFaceVertexIndicesAttr().Get()).reshape(-1, 3)
        triangles = v[faces]
        cross = np.cross(triangles[:, 1]-triangles[:, 0], triangles[:, 2]-triangles[:, 0])
        faces = faces[np.linalg.norm(cross, axis=1) > 1e-10]
        geom.GetPointsAttr().Set(Vt.Vec3fArray.FromNumpy(v))
        geom.GetFaceVertexCountsAttr().Set(Vt.IntArray.FromNumpy(np.full(len(faces), 3, np.int32)))
        geom.GetFaceVertexIndicesAttr().Set(Vt.IntArray.FromNumpy(faces.ravel().astype(np.int32)))
        moved_mesh_vertices += int(mask.sum())
    # Extrude a closed finite grid. Every upper vertex is exactly z=0.
    cells = np.argwhere(footprint)
    grid_ids = -np.ones((shape[0]+1, shape[1]+1), np.int32)
    corners = np.concatenate([cells, cells+[1, 0], cells+[1, 1], cells+[0, 1]])
    corners = np.unique(corners, axis=0)
    grid_ids[corners[:, 0], corners[:, 1]] = np.arange(len(corners))
    xy = low + corners*resolution
    N = len(corners)
    points = np.r_[np.c_[xy, np.zeros(N)], np.c_[xy, np.full(N, -.12)]].astype('f')
    quads = np.column_stack([grid_ids[cells[:, 0], cells[:, 1]], grid_ids[cells[:, 0]+1, cells[:, 1]],
                            grid_ids[cells[:, 0]+1, cells[:, 1]+1], grid_ids[cells[:, 0], cells[:, 1]+1]])
    faces = [quads, quads[:, ::-1]+N]
    for edge, delta in enumerate([[-1, 0], [0, -1], [1, 0], [0, 1]]):
        neighbors = cells + delta
        present = np.zeros(len(cells), bool)
        valid = ((neighbors >= 0) & (neighbors < shape)).all(1)
        present[valid] = footprint[neighbors[valid, 0], neighbors[valid, 1]]
        # left, bottom, right, top in the cell's CCW corner sequence
        a, b = [(3, 0), (0, 1), (1, 2), (2, 3)][edge]
        q = quads[~present]
        faces.append(np.c_[q[:, b], q[:, a], q[:, a]+N, q[:, b]+N])
    faces = np.concatenate(faces).astype(np.int32)
    geom = UsdGeom.Mesh.Define(stage, '/World/FlatFloorCollision')
    geom.CreatePointsAttr(Vt.Vec3fArray.FromNumpy(points))
    geom.CreateFaceVertexCountsAttr(Vt.IntArray.FromNumpy(np.full(len(faces), 4, np.int32)))
    geom.CreateFaceVertexIndicesAttr(Vt.IntArray.FromNumpy(faces.ravel()))
    geom.CreateSubdivisionSchemeAttr('none')
    geom.CreateVisibilityAttr('invisible')
    geom.CreatePurposeAttr('guide')
    geom.CreateDoubleSidedAttr(True)
    UsdPhysics.CollisionAPI.Apply(geom.GetPrim()).CreateCollisionEnabledAttr(True)
    UsdPhysics.MeshCollisionAPI.Apply(geom.GetPrim()).CreateApproximationAttr('none')
    geom.GetPrim().AddAppliedSchema('PhysxCollisionAPI')
    geom.GetPrim().CreateAttribute('physxCollision:contactOffset', Sdf.ValueTypeNames.Float).Set(.004)
    UsdShade.MaterialBindingAPI.Apply(geom.GetPrim()).Bind(UsdShade.Material(stage.GetPrimAtPath('/World/PhysicsMaterial')), materialPurpose='physics')
    stage.GetRootLayer().Save()
    # Validate against an independent original stage, including all untouched points.
    original = Usd.Stage.Open(str(backup)).GetPrimAtPath('/World/Scan/Gaussians')
    # Retain stage lifetime while inspecting its prim.
    original_stage = Usd.Stage.Open(str(backup))
    original = original_stage.GetPrimAtPath('/World/Scan/Gaussians')
    for attr in ['opacities', 'radiance:sphericalHarmonicsCoefficients']:
        assert np.array_equal(np.asarray(field.GetAttribute(attr).Get()), np.asarray(original.GetAttribute(attr).Get())), attr
    for attr in ['positions', 'scales', 'orientations']:
        b = np.asarray(original.GetAttribute(attr).Get())
        a = np.asarray(field.GetAttribute(attr).Get())
        assert np.array_equal(a[~flat], b[~flat]), attr
    old_world = np.asarray(original.GetAttribute('positions').Get())[ids] @ A + t
    new_world = np.asarray(field.GetAttribute('positions').Get())[ids] @ A + t
    xy_error = float(abs(new_world[:, :2]-old_world[:, :2]).max())
    z_error = float(abs(new_world[:, 2]).max())
    assert xy_error < 5e-6 and z_error < 5e-6 and max_covariance_error < 1e-8
    np.savez_compressed(directory / 'floor_repair_indices.npz', leveled_source_indices=ids,
                        footprint_cells=cells, footprint_origin=low, footprint_resolution=resolution)
    report = dict(scene=directory.name, leveled_gaussians=len(ids), floor_world_z_m=0.,
        normal_sigma_m=.00045, original_floor_z_quantiles_m=np.quantile(before, [0, .01, .5, .99, 1]).tolist(),
        maximum_floor_plane_error_m=z_error, maximum_world_xy_change_m=xy_error,
        maximum_xy_covariance_change_m2=max_covariance_error, all_radiance_and_opacity_exactly_preserved=True,
        nonfloor_gaussian_arrays_exactly_preserved=True, protected_furniture_footprints=True,
        collision_floor_area_m2=float(len(cells)*resolution**2), collision_floor_top_exact_z_m=0.,
        collision_scan_vertices_leveled=moved_mesh_vertices, footprint_resolution_m=resolution,
        appearance_method='flatten source floor means and normal covariance; preserve world XY means/covariance and every source color/opacity; no replacement materials or textures',
        validated=True)
    save(directory / 'floor_repair.json', report)
    build = json.loads((directory / 'build.json').read_text())
    build['original_gaussian_arrays_preserved'] = 'radiance and opacity exact; nonfloor geometry exact; floor geometry leveled with XY footprint/covariance preserved'
    build['flat_floor_repair'] = 'floor_repair.json'
    save(directory / 'build.json', build)
    print('FLAT', directory.name, len(ids), 'points', report['collision_floor_area_m2'], 'm2', flush=True)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(); parser.add_argument('scenes', nargs='*'); args = parser.parse_args()
    for directory in sorted(OUT.iterdir()):
        if directory.is_dir() and (not args.scenes or directory.name in args.scenes):
            repair(directory)
            gc.collect()