File size: 12,901 Bytes
532466c
 
8e53f1d
 
532466c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e1a674
532466c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e53f1d
 
532466c
8e53f1d
 
 
 
532466c
 
 
 
 
 
 
 
 
 
 
 
8e53f1d
 
532466c
 
8e53f1d
532466c
 
 
 
8e53f1d
 
532466c
 
 
 
 
 
 
 
 
 
 
8e53f1d
 
 
 
 
 
532466c
8e53f1d
532466c
 
 
 
 
 
 
 
 
8e53f1d
3e1a674
8e53f1d
532466c
 
 
 
 
 
 
 
 
8e53f1d
532466c
8e53f1d
 
 
532466c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e53f1d
532466c
8e53f1d
532466c
3e1a674
8e53f1d
532466c
 
8e53f1d
 
 
 
 
 
 
 
 
 
532466c
 
 
 
 
 
 
8e53f1d
 
 
 
 
532466c
 
 
 
 
 
 
 
 
 
 
 
 
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
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
from __future__ import annotations

import time

import numpy as np

from enums import TextureMappingMode, TextureMappingReason, PlaneFitMode
from config.surface import (
    SURFACE_MIN_PLANE_PIXELS,
    SURFACE_PLANE_DISTANCE_METERS,
    SURFACE_RANSAC_DISTANCE,
    SURFACE_UV_ABSOLUTE_JUMP_METERS,
    SURFACE_UV_MAX_BAD_NEIGHBOR_RATIO,
    SURFACE_UV_MAX_JUMP_RATIO,
    SURFACE_UV_MIN_COVERAGE,
)
from config.runtime import ENABLE_MULTI_PLANE_SURFACES
from services.geometry.multi_plane import (
    assign_points_to_surface_planes,
    fit_multi_surface_planes,
    geometry_point_maps,
)
from services.geometry.plane_fitting import project_points_to_plane, surface_distance_threshold


def analyze_surface_uv_quality(
    surface_mask: np.ndarray,
    surface_indices: np.ndarray,
    uv_by_mask: np.ndarray,
    plane_ids: np.ndarray,
) -> dict:
    total_pixels = int(len(surface_indices))
    finite_uv = np.isfinite(uv_by_mask).all(axis=1) if total_pixels else np.zeros(0, dtype=bool)
    finite_pixels = int(finite_uv.sum())
    coverage = float(finite_pixels / max(total_pixels, 1))
    active_plane_ids = sorted({
        int(plane_id)
        for plane_id in np.unique(plane_ids[finite_uv])
        if int(plane_id) != 255
    })

    quality = {
        "surfaceUvEnabled": False,
        "textureMappingMode": TextureMappingMode.REGULARIZED_FLOOR_PLANE,
        "textureMappingReason": TextureMappingReason.SURFACE_UV_UNAVAILABLE,
        "surfaceUvCoverage": coverage,
        "surfaceUvFinitePixels": finite_pixels,
        "surfaceUvTotalPixels": total_pixels,
        "surfaceUvNeighborCount": 0,
        "surfaceUvMedianNeighborDelta": None,
        "surfaceUvP95NeighborDelta": None,
        "surfaceUvP99NeighborDelta": None,
        "surfaceUvJumpLimit": None,
        "surfaceUvBadNeighborRatio": None,
        "surfaceUvPlaneBoundaryRatio": None,
        "surfaceUvAssignedPlaneCount": len(active_plane_ids),
    }

    if total_pixels == 0:
        quality["textureMappingReason"] = TextureMappingReason.EMPTY_SURFACE
        return quality
    if coverage < SURFACE_UV_MIN_COVERAGE:
        quality["textureMappingReason"] = TextureMappingReason.INCOMPLETE_SURFACE_UV
        return quality
    h, w = surface_mask.shape[:2]
    uv_grid = np.full((h * w, 2), np.nan, dtype=np.float32)
    plane_grid = np.full(h * w, 255, dtype=np.uint8)
    uv_grid[surface_indices[finite_uv]] = uv_by_mask[finite_uv]
    plane_grid[surface_indices[finite_uv]] = plane_ids[finite_uv]
    uv_grid = uv_grid.reshape(h, w, 2)
    plane_grid = plane_grid.reshape(h, w)
    finite_grid = np.isfinite(uv_grid).all(axis=2)
    surface_bool = surface_mask.astype(bool)

    right = surface_bool[:, :-1] & surface_bool[:, 1:] & finite_grid[:, :-1] & finite_grid[:, 1:]
    down = surface_bool[:-1, :] & surface_bool[1:, :] & finite_grid[:-1, :] & finite_grid[1:, :]
    right_plane_boundary = right & (plane_grid[:, :-1] != plane_grid[:, 1:])
    down_plane_boundary = down & (plane_grid[:-1, :] != plane_grid[1:, :])
    same_right = right & ~right_plane_boundary
    same_down = down & ~down_plane_boundary

    deltas = []
    if same_right.any():
        deltas.append(np.linalg.norm(uv_grid[:, 1:][same_right] - uv_grid[:, :-1][same_right], axis=1))
    if same_down.any():
        deltas.append(np.linalg.norm(uv_grid[1:, :][same_down] - uv_grid[:-1, :][same_down], axis=1))

    neighbor_count = int(right.sum() + down.sum())
    plane_boundary_count = int(right_plane_boundary.sum() + down_plane_boundary.sum())
    quality["surfaceUvNeighborCount"] = neighbor_count
    quality["surfaceUvPlaneBoundaryRatio"] = float(plane_boundary_count / max(neighbor_count, 1))

    if not deltas:
        quality["textureMappingReason"] = TextureMappingReason.INSUFFICIENT_UV_NEIGHBORS
        return quality

    all_deltas = np.concatenate(deltas).astype(np.float32)
    median_delta = float(np.median(all_deltas))
    p95_delta = float(np.percentile(all_deltas, 95))
    p99_delta = float(np.percentile(all_deltas, 99))
    jump_limit = max(SURFACE_UV_ABSOLUTE_JUMP_METERS, median_delta * SURFACE_UV_MAX_JUMP_RATIO)
    bad_ratio = float((all_deltas > jump_limit).mean())

    quality.update({
        "surfaceUvMedianNeighborDelta": median_delta,
        "surfaceUvP95NeighborDelta": p95_delta,
        "surfaceUvP99NeighborDelta": p99_delta,
        "surfaceUvJumpLimit": float(jump_limit),
        "surfaceUvBadNeighborRatio": bad_ratio,
    })

    if bad_ratio > SURFACE_UV_MAX_BAD_NEIGHBOR_RATIO:
        quality["textureMappingReason"] = TextureMappingReason.NOISY_SURFACE_UV
        return quality
    quality["surfaceUvEnabled"] = True
    quality["textureMappingMode"] = TextureMappingMode.SURFACE_UV
    quality["textureMappingReason"] = (
        TextureMappingReason.SURFACE_UV_QUALITY_OK
        if len(active_plane_ids) <= 1
        else TextureMappingReason.MULTI_PLANE_SURFACE_UV_QUALITY_OK
    )
    return quality


def build_surface_uv_mapping(
    surface_mask: np.ndarray,
    surface_indices: np.ndarray,
    geometry: dict | None,
    *,
    geometry_maps: dict | None = None,
):
    total_started = time.perf_counter()
    phase_started = total_started
    maps = geometry_maps if geometry_maps is not None else geometry_point_maps(surface_mask, geometry)
    geometry_maps_ms = (time.perf_counter() - phase_started) * 1000
    if maps is None:
        print(
            "[SURFACE_MAPPING] skipped: no point maps "
            f"enabled={ENABLE_MULTI_PLANE_SURFACES} "
            f"provider={geometry.get('provider') if geometry else None}",
            flush=True,
        )
        return None

    points_map = maps["points"]
    normals_map = maps["normals"]
    valid_mask = maps["validMask"] & (surface_mask > 0)
    valid_flat = np.flatnonzero(valid_mask.ravel()).astype(np.uint32)
    if len(valid_flat) < SURFACE_MIN_PLANE_PIXELS:
        print(
            "[SURFACE_MAPPING] skipped: too few valid surface pixels "
            f"valid={len(valid_flat)} min={SURFACE_MIN_PLANE_PIXELS}",
            flush=True,
        )
        return None

    points = points_map.reshape(-1, 3)[valid_flat]
    normals = normals_map.reshape(-1, 3)[valid_flat]
    good_points = np.isfinite(points).all(axis=1)
    if int(good_points.sum()) < SURFACE_MIN_PLANE_PIXELS:
        print(
            "[SURFACE_MAPPING] skipped: too few finite 3D points "
            f"finitePoints={int(good_points.sum())} min={SURFACE_MIN_PLANE_PIXELS}",
            flush=True,
        )
        return None

    valid_flat = valid_flat[good_points]
    points = points[good_points]
    normals = normals[good_points]
    prepared_normal_valid = maps.get("normalValidMask")
    if prepared_normal_valid is not None and prepared_normal_valid.shape == surface_mask.shape:
        normal_good = prepared_normal_valid.ravel()[valid_flat]
    else:
        normal_good = np.isfinite(normals).all(axis=1) & (np.linalg.norm(normals, axis=1) > 1e-4)
    normals_reliable = int(normal_good.sum()) >= SURFACE_MIN_PLANE_PIXELS
    gather_ms = (time.perf_counter() - phase_started) * 1000 - geometry_maps_ms

    print(
        "[SURFACE_MAPPING] candidates "
        f"surfacePixels={int(surface_mask.sum())} validPixels={len(points)} "
        f"normalPixels={int(normal_good.sum())} normalsReliable={normals_reliable} "
        f"provider={geometry.get('provider') if geometry else None}",
        flush=True,
    )

    phase_started = time.perf_counter()
    planes = fit_multi_surface_planes(points, normals, normals_reliable)
    plane_fit_ms = (time.perf_counter() - phase_started) * 1000
    if not planes:
        print(
            "[SURFACE_MAPPING] skipped: no dominant planes fitted "
            f"validPixels={len(points)} threshold={surface_distance_threshold(points):.4f} "
            f"normalsReliable={normals_reliable}",
            flush=True,
        )
        return None

    phase_started = time.perf_counter()
    assignment = assign_points_to_surface_planes(points, normals, planes, normals_reliable)
    assignment_ms = (time.perf_counter() - phase_started) * 1000

    phase_started = time.perf_counter()
    uv_by_mask = np.full((len(surface_indices), 2), np.nan, dtype=np.float32)
    plane_ids = np.full(len(surface_indices), 255, dtype=np.uint8)
    ordinal = np.full(surface_mask.size, -1, dtype=np.int32)
    ordinal[surface_indices] = np.arange(len(surface_indices), dtype=np.int32)
    positions = ordinal[valid_flat]
    assignment_distance_limit = max(
        float(SURFACE_RANSAC_DISTANCE) * 1.5,
        min(float(SURFACE_PLANE_DISTANCE_METERS), surface_distance_threshold(points) * 1.35),
    )
    rejected_by_distance = 0

    for plane_idx, plane in enumerate(planes):
        assigned = assignment == plane_idx
        if not assigned.any():
            plane["assignedCount"] = 0
            continue
        projected_points, signed_distances = project_points_to_plane(
            points[assigned],
            plane["origin"],
            plane["normal"],
        )
        near_plane = np.abs(signed_distances) <= assignment_distance_limit
        rejected_by_distance += int((~near_plane).sum())
        if not near_plane.any():
            plane["assignedCount"] = 0
            continue
        delta = projected_points[near_plane] - plane["origin"]
        uv = np.column_stack((delta @ plane["uAxis"], delta @ plane["vAxis"])).astype(np.float32)
        assigned_positions = positions[assigned][near_plane]
        assigned_keep = assigned_positions >= 0
        assigned_positions = assigned_positions[assigned_keep]
        uv_by_mask[assigned_positions] = uv[assigned_keep]
        plane_ids[assigned_positions] = plane_idx
        plane["assignedCount"] = int(assigned_keep.sum())

    serializable_planes = []
    for plane in planes:
        assigned_plane_uv = uv_by_mask[plane_ids == int(plane["id"])]
        assigned_plane_uv = assigned_plane_uv[np.isfinite(assigned_plane_uv).all(axis=1)]
        if len(assigned_plane_uv):
            uv_min = np.min(assigned_plane_uv, axis=0)
            uv_max = np.max(assigned_plane_uv, axis=0)
        else:
            uv_min = np.zeros(2, dtype=np.float32)
            uv_max = np.ones(2, dtype=np.float32)
        serializable_planes.append({
            "id": int(plane["id"]),
            "normal": plane["normal"].astype(float).tolist(),
            "origin": plane["origin"].astype(float).tolist(),
            "offset": float(plane["offset"]),
            "uAxis": plane["uAxis"].astype(float).tolist(),
            "vAxis": plane["vAxis"].astype(float).tolist(),
            "inlierCount": int(plane["inlierCount"]),
            "assignedCount": int(plane.get("assignedCount", 0)),
            "isFloor": bool(plane["isFloor"]),
            "fitMode": str(plane.get("fitMode", PlaneFitMode.NORMAL_AWARE)),
            "uvMin": uv_min.astype(float).tolist(),
            "uvMax": uv_max.astype(float).tolist(),
            "uvWidth": float(max(uv_max[0] - uv_min[0], 0.05)),
            "uvHeight": float(max(uv_max[1] - uv_min[1], 0.05)),
        })
    projection_ms = (time.perf_counter() - phase_started) * 1000

    phase_started = time.perf_counter()
    finite_uv = np.isfinite(uv_by_mask).all(axis=1)
    uv_quality = analyze_surface_uv_quality(surface_mask, surface_indices, uv_by_mask, plane_ids)
    quality_ms = (time.perf_counter() - phase_started) * 1000
    uv_quality["surfaceUvPlaneDistanceLimitMeters"] = float(assignment_distance_limit)
    uv_quality["surfaceUvRejectedByPlaneDistance"] = int(rejected_by_distance)
    timing_ms = {
        "geometryMaps": round(geometry_maps_ms, 2),
        "pixelGather": round(gather_ms, 2),
        "planeFit": round(plane_fit_ms, 2),
        "planeAssignment": round(assignment_ms, 2),
        "projection": round(projection_ms, 2),
        "qualityAnalysis": round(quality_ms, 2),
        "total": round((time.perf_counter() - total_started) * 1000, 2),
    }
    uv_quality["surfaceUvTimingMs"] = timing_ms
    print(
        "[SURFACE_MAPPING] success "
        f"planes={len(serializable_planes)} assignedPixels={int(finite_uv.sum())}/{len(surface_indices)} "
        f"fitModes={[plane['fitMode'] for plane in serializable_planes]} "
        f"mode={uv_quality['textureMappingMode']} reason={uv_quality['textureMappingReason']}",
        flush=True,
    )
    print(
        "[SURFACE_MAPPING_TIMING] "
        + " ".join(f"{name}={duration:.2f}ms" for name, duration in timing_ms.items()),
        flush=True,
    )

    return {
        "uv": uv_by_mask,
        "planeIds": plane_ids,
        "planes": serializable_planes,
        "normalMap": normals_map,
        "validMask": valid_mask,
        "intrinsics": maps["intrinsics"],
        "depthScale": maps["depthScale"],
        "normalsReliable": normals_reliable,
        "useSurfaceUv": bool(uv_quality["surfaceUvEnabled"]),
        "metadata": uv_quality,
    }