github-actions[bot] commited on
Commit
b2004ce
·
1 Parent(s): d3ceecd

Automated Deploy: 001e0f3089bb38a4e8b7c1c85891b38e75a77ec7

Browse files
config/runtime.py CHANGED
@@ -6,7 +6,7 @@ ENABLE_FLOOR_MASK_CLEANUP = config_bool("ENABLE_FLOOR_MASK_CLEANUP", "runtime",
6
  ENABLE_DEPTH_ESTIMATION = config_bool("ENABLE_DEPTH_ESTIMATION", "runtime", "enable_depth_estimation", "1")
7
  ENABLE_PLANE_FIT = config_bool("ENABLE_PLANE_FIT", "runtime", "enable_plane_fit", "1")
8
  ENABLE_MULTI_PLANE_SURFACES = config_bool("ENABLE_MULTI_PLANE_SURFACES", "runtime", "enable_multi_plane_surfaces", "1")
9
- ENABLE_WALL_SEGMENTS = config_bool("ENABLE_WALL_SEGMENTS", "runtime", "enable_wall_segments", "0")
10
  ENABLE_INTRINSIC_SHADING = config_bool("ENABLE_INTRINSIC_SHADING", "runtime", "enable_intrinsic_shading", "0")
11
  ENABLE_SHADING_TRANSFER = config_bool("ENABLE_SHADING_TRANSFER", "runtime", "enable_shading_transfer", "1")
12
  ENABLE_FAST_SHADOW_TRANSFER = config_bool(
@@ -44,6 +44,16 @@ ROOM_UPLOAD_JPEG_QUALITY = min(95, max(50, int(config_value(
44
  "ROOM_UPLOAD_JPEG_QUALITY", "runtime", "room_upload_jpeg_quality", "85",
45
  ))))
46
 
 
 
 
 
 
 
 
 
 
 
47
  DEBUG_ARTIFACTS_ENABLED = config_bool(
48
  "DEBUG_ARTIFACTS_ENABLED", "runtime", "debug_artifacts_enabled", "1",
49
  )
 
6
  ENABLE_DEPTH_ESTIMATION = config_bool("ENABLE_DEPTH_ESTIMATION", "runtime", "enable_depth_estimation", "1")
7
  ENABLE_PLANE_FIT = config_bool("ENABLE_PLANE_FIT", "runtime", "enable_plane_fit", "1")
8
  ENABLE_MULTI_PLANE_SURFACES = config_bool("ENABLE_MULTI_PLANE_SURFACES", "runtime", "enable_multi_plane_surfaces", "1")
9
+ ENABLE_WALL_SEGMENTS = config_bool("ENABLE_WALL_SEGMENTS", "runtime", "enable_wall_segments", "1")
10
  ENABLE_INTRINSIC_SHADING = config_bool("ENABLE_INTRINSIC_SHADING", "runtime", "enable_intrinsic_shading", "0")
11
  ENABLE_SHADING_TRANSFER = config_bool("ENABLE_SHADING_TRANSFER", "runtime", "enable_shading_transfer", "1")
12
  ENABLE_FAST_SHADOW_TRANSFER = config_bool(
 
44
  "ROOM_UPLOAD_JPEG_QUALITY", "runtime", "room_upload_jpeg_quality", "85",
45
  ))))
46
 
47
+ # Deflate level for the .vizbundle zip. Its payload is raw float/uint surface
48
+ # arrays, which are highly compressible: on a 1200x1600 room, level 6 takes the
49
+ # bundle from 12.7 MB to 1.0 MB for about 170 ms of CPU. That matters because a
50
+ # 12.7 MB body is exactly what fails to reach a browser through a dev tunnel.
51
+ # 0 stores uncompressed (the old behaviour); 1 is ~6x for 37 ms; 9 buys almost
52
+ # nothing over 6 and costs 5x the time.
53
+ BUNDLE_COMPRESSION_LEVEL = max(0, min(9, int(config_value(
54
+ "BUNDLE_COMPRESSION_LEVEL", "runtime", "bundle_compression_level", "6",
55
+ ))))
56
+
57
  DEBUG_ARTIFACTS_ENABLED = config_bool(
58
  "DEBUG_ARTIFACTS_ENABLED", "runtime", "debug_artifacts_enabled", "1",
59
  )
config/surface.py CHANGED
@@ -78,3 +78,12 @@ SURFACE_PLANE_NORMAL_MIN_COS = float(config_value(
78
  SURFACE_PLANE_FILTER_MIN_KEEP_RATIO = float(config_value(
79
  "SURFACE_PLANE_FILTER_MIN_KEEP_RATIO", "surface_mapping", "plane_filter_min_keep_ratio", "0.45",
80
  ))
 
 
 
 
 
 
 
 
 
 
78
  SURFACE_PLANE_FILTER_MIN_KEEP_RATIO = float(config_value(
79
  "SURFACE_PLANE_FILTER_MIN_KEEP_RATIO", "surface_mapping", "plane_filter_min_keep_ratio", "0.45",
80
  ))
81
+
82
+ # Walls tile *behind* mounted objects, so a wall surface legitimately
83
+ # contains pixels with no valid wall geometry (a TV, a mirror, a cabinet).
84
+ # Holding walls to the floor's 0.995 makes every wall fail the gate as
85
+ # 'incomplete-surface-uv'. The shortfall is exactly the occluded pixels,
86
+ # which the occlusion mask repaints anyway, so it is not a defect.
87
+ SURFACE_UV_WALL_MIN_COVERAGE = float(config_value(
88
+ "SURFACE_UV_WALL_MIN_COVERAGE", "surface_mapping", "uv_wall_min_coverage", "0.90",
89
+ ))
services/debug/overlays.py CHANGED
@@ -19,6 +19,38 @@ def debug_mask_overlay(
19
  return output
20
 
21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  def debug_segmentation_overlay(image_rgb: np.ndarray, seg_map: np.ndarray) -> np.ndarray:
23
  labels = seg_map.astype(np.int32)
24
  hsv = np.zeros((*labels.shape, 3), dtype=np.uint8)
@@ -31,6 +63,18 @@ def debug_segmentation_overlay(image_rgb: np.ndarray, seg_map: np.ndarray) -> np
31
 
32
  def debug_scalar_map(values: np.ndarray, mask: np.ndarray | None = None) -> np.ndarray:
33
  scalar = values.astype(np.float32)
 
 
 
 
 
 
 
 
 
 
 
 
34
  finite = np.isfinite(scalar)
35
  if mask is not None:
36
  finite &= mask.astype(bool)
 
19
  return output
20
 
21
 
22
+ WALL_COMPONENT_COLORS = (
23
+ (255, 96, 96), (96, 200, 255), (140, 240, 140), (255, 200, 80),
24
+ (210, 140, 255), (255, 140, 200), (120, 255, 230), (200, 200, 120),
25
+ )
26
+
27
+
28
+ def debug_wall_components_overlay(image_rgb: np.ndarray, components) -> np.ndarray:
29
+ """Tint each wall component a distinct colour and label it.
30
+
31
+ `components` is the list of (area, mask) pairs returned by
32
+ wall_surface_components(). Distinct colours are what make it obvious when
33
+ two physically separate walls have been merged into one component, or when
34
+ a single wall has been split across a corner.
35
+ """
36
+ output = image_rgb.copy()
37
+ for index, item in enumerate(components):
38
+ mask = item[1] if isinstance(item, (tuple, list)) else item
39
+ valid = mask.astype(bool)
40
+ if not valid.any():
41
+ continue
42
+ color = WALL_COMPONENT_COLORS[index % len(WALL_COMPONENT_COLORS)]
43
+ overlay = np.empty_like(output)
44
+ overlay[:] = color
45
+ output[valid] = cv2.addWeighted(output, 0.42, overlay, 0.58, 0)[valid]
46
+ ys, xs = np.where(valid)
47
+ center = (int(xs.mean()) - 42, int(ys.mean()))
48
+ label = f"Wall {index + 1}"
49
+ cv2.putText(output, label, center, cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 0), 5, cv2.LINE_AA)
50
+ cv2.putText(output, label, center, cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 255), 2, cv2.LINE_AA)
51
+ return output
52
+
53
+
54
  def debug_segmentation_overlay(image_rgb: np.ndarray, seg_map: np.ndarray) -> np.ndarray:
55
  labels = seg_map.astype(np.int32)
56
  hsv = np.zeros((*labels.shape, 3), dtype=np.uint8)
 
63
 
64
  def debug_scalar_map(values: np.ndarray, mask: np.ndarray | None = None) -> np.ndarray:
65
  scalar = values.astype(np.float32)
66
+ if mask is not None and mask.shape[:2] != scalar.shape[:2]:
67
+ # The map and the mask it was measured against need not share a shape.
68
+ # The fast-shadow path bounds its shade map to FAST_SHADOW_MAX_DIMENSION
69
+ # and the renderer samples it linearly, so for anything larger than that
70
+ # the map arrives smaller than the surface mask. Match the mask to the
71
+ # map rather than the reverse: the map is what is being visualised, and
72
+ # upscaling it here would invent detail the pipeline never produced.
73
+ mask = cv2.resize(
74
+ mask.astype(np.uint8),
75
+ (scalar.shape[1], scalar.shape[0]),
76
+ interpolation=cv2.INTER_NEAREST,
77
+ )
78
  finite = np.isfinite(scalar)
79
  if mask is not None:
80
  finite &= mask.astype(bool)
services/geometry/multi_plane.py CHANGED
@@ -4,7 +4,7 @@ import numpy as np
4
 
5
  from enums import PlaneFitMode
6
  from config.models import DEPTH_MODEL_NAME
7
- from config.runtime import ENABLE_MULTI_PLANE_SURFACES
8
  from config.surface import (
9
  SURFACE_MAX_PLANES,
10
  SURFACE_MIN_PLANE_PIXELS,
@@ -92,7 +92,8 @@ def geometry_point_maps(mask: np.ndarray, geometry: dict | None):
92
  }
93
 
94
 
95
- def fit_multi_surface_planes(points: np.ndarray, normals: np.ndarray, normals_reliable: bool = True):
 
96
  if len(points) < SURFACE_MIN_PLANE_PIXELS:
97
  return []
98
 
@@ -150,18 +151,189 @@ def fit_multi_surface_planes(points: np.ndarray, normals: np.ndarray, normals_re
150
 
151
  planes = _prune_weak_secondary_planes(planes)
152
 
 
 
 
 
 
153
  floor_id = int(np.argmax([
154
  plane["inlierCount"] * max(0.1, abs(float(plane["normal"][1])))
155
  for plane in planes
156
- ]))
157
  for idx, plane in enumerate(planes):
158
- plane["isFloor"] = idx == floor_id
159
- u_axis, v_axis = plane_basis(plane["normal"], plane["isFloor"])
160
  plane["uAxis"] = u_axis
161
  plane["vAxis"] = v_axis
162
  return planes
163
 
164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  def assign_points_to_surface_planes(
166
  points: np.ndarray,
167
  normals: np.ndarray,
 
4
 
5
  from enums import PlaneFitMode
6
  from config.models import DEPTH_MODEL_NAME
7
+ from config.runtime import DEBUG_ARTIFACTS_ENABLED, ENABLE_MULTI_PLANE_SURFACES
8
  from config.surface import (
9
  SURFACE_MAX_PLANES,
10
  SURFACE_MIN_PLANE_PIXELS,
 
92
  }
93
 
94
 
95
+ def fit_multi_surface_planes(points: np.ndarray, normals: np.ndarray, normals_reliable: bool = True,
96
+ mark_floor: bool = True, vertical_ref: np.ndarray | None = None):
97
  if len(points) < SURFACE_MIN_PLANE_PIXELS:
98
  return []
99
 
 
151
 
152
  planes = _prune_weak_secondary_planes(planes)
153
 
154
+ # On a wall-only surface every normal is near-horizontal, so this argmax
155
+ # would still crown one of them "the floor" and hand it floor-style axes
156
+ # (an arbitrary horizontal reference) instead of gravity-aligned ones —
157
+ # tiles on that wall would come out rotated. Callers working a non-floor
158
+ # surface pass mark_floor=False.
159
  floor_id = int(np.argmax([
160
  plane["inlierCount"] * max(0.1, abs(float(plane["normal"][1])))
161
  for plane in planes
162
+ ])) if mark_floor else -1
163
  for idx, plane in enumerate(planes):
164
+ plane["isFloor"] = bool(mark_floor and idx == floor_id)
165
+ u_axis, v_axis = plane_basis(plane["normal"], plane["isFloor"], vertical_ref)
166
  plane["uAxis"] = u_axis
167
  plane["vAxis"] = v_axis
168
  return planes
169
 
170
 
171
+ def merge_planes_by_point_consistency(
172
+ points: np.ndarray,
173
+ assignment: np.ndarray,
174
+ planes: list[dict],
175
+ distance_threshold: float,
176
+ angle_degrees: float = 20.0,
177
+ tolerance_scale: float = 1.5,
178
+ ) -> tuple[np.ndarray, list[dict]]:
179
+ """Merge planes whose assigned points actually lie on one another's plane.
180
+
181
+ Comparing two fitted planes to each other does not work reliably here.
182
+ RANSAC peels a plane off, removes its inliers, then fits the *remainder* --
183
+ so on a single flat wall the leftover tails produce a plane that is both
184
+ tilted and offset relative to the first, even though every point involved
185
+ belongs to the same physical surface. Threshold the plane parameters and you
186
+ either fail to merge (wall sliced into vertical depth-slab strips) or merge
187
+ surfaces that are genuinely apart.
188
+
189
+ Measuring the points instead is unambiguous: if plane B's pixels sit within
190
+ tolerance of plane A, they are the same wall. On a sample living room the
191
+ two halves of each wall sat 0.018 m and 0.035 m apart, while the protruding
192
+ chimney breast was 0.155 m from its neighbours -- a clean gap with nothing
193
+ in between.
194
+
195
+ Returns (remapped_assignment, merged_planes).
196
+ """
197
+ if len(planes) <= 1:
198
+ return assignment, planes
199
+
200
+ cos_limit = float(np.cos(np.deg2rad(angle_degrees)))
201
+ limit = float(distance_threshold) * tolerance_scale
202
+ parent = list(range(len(planes)))
203
+
204
+ def find(index: int) -> int:
205
+ while parent[index] != index:
206
+ parent[index] = parent[parent[index]]
207
+ index = parent[index]
208
+ return index
209
+
210
+ def offset_of(plane: dict) -> tuple[np.ndarray, float]:
211
+ normal = np.asarray(plane["normal"], dtype=np.float32)
212
+ origin = np.asarray(plane["origin"], dtype=np.float32)
213
+ return normal, float(-origin @ normal)
214
+
215
+ def spread(subject: int, reference: int) -> float:
216
+ """How far the subject plane's points sit from the reference plane."""
217
+ member = points[assignment == subject]
218
+ if member.size == 0:
219
+ return float("inf")
220
+ normal, offset = offset_of(planes[reference])
221
+ return float(np.percentile(np.abs(member @ normal + offset), 90))
222
+
223
+ for a in range(len(planes)):
224
+ for b in range(a + 1, len(planes)):
225
+ normal_a = np.asarray(planes[a]["normal"], dtype=np.float32)
226
+ normal_b = np.asarray(planes[b]["normal"], dtype=np.float32)
227
+ if abs(float(normal_a @ normal_b)) < cos_limit:
228
+ continue
229
+ worst = max(spread(b, a), spread(a, b))
230
+ # One line per plane pair, so up to ten per wall region per
231
+ # conversion now that max_planes is 5. Useful when working out why
232
+ # two walls merged; noise in a production log.
233
+ if DEBUG_ARTIFACTS_ENABLED:
234
+ print(
235
+ f"[PLANE_MERGE] plane {a} vs {b}: "
236
+ f"angle={np.degrees(np.arccos(min(1.0, abs(float(normal_a @ normal_b))))):.1f}deg "
237
+ f"p90Distance={worst:.3f}m limit={limit:.3f}m "
238
+ f"{'MERGE' if worst <= limit else 'keep separate'}",
239
+ flush=True,
240
+ )
241
+ if worst <= limit:
242
+ root_a, root_b = find(a), find(b)
243
+ if root_a != root_b:
244
+ parent[max(root_a, root_b)] = min(root_a, root_b)
245
+
246
+ roots = sorted({find(index) for index in range(len(planes))})
247
+ if len(roots) == len(planes):
248
+ return assignment, planes
249
+
250
+ remap = {root: new for new, root in enumerate(roots)}
251
+ merged_assignment = np.full_like(assignment, -1)
252
+ merged_planes = []
253
+ for root in roots:
254
+ members = [index for index in range(len(planes)) if find(index) == root]
255
+ # Keep the largest contributor's orientation; it is the best-supported fit.
256
+ dominant = max(members, key=lambda index: int(planes[index]["inlierCount"]))
257
+ plane = dict(planes[dominant])
258
+ plane["inlierCount"] = sum(int(planes[index]["inlierCount"]) for index in members)
259
+ plane["id"] = remap[root]
260
+ merged_planes.append(plane)
261
+ for index in members:
262
+ merged_assignment[assignment == index] = remap[root]
263
+
264
+ return merged_assignment, merged_planes
265
+
266
+
267
+ def merge_coplanar_planes(planes: list[dict], distance_threshold: float,
268
+ angle_degrees: float = 15.0,
269
+ vertical_ref: np.ndarray | None = None) -> list[dict]:
270
+ """Fuse fitted planes that describe the same physical surface.
271
+
272
+ fit_multi_surface_planes peels planes off one at a time with RANSAC. On a
273
+ large flat wall with noisy normals — which is what back-projected depth
274
+ gives you — the first pass often claims only part of the wall and a later
275
+ pass fits a second, geometrically near-identical plane to the remainder.
276
+
277
+ Left alone that splits one wall into several segments, each with its own
278
+ transform, so the tile grid breaks visibly at the seam. Raising inference
279
+ resolution makes it worse, because finer normals give RANSAC more excuses to
280
+ subdivide: a 1600px run split one living-room wall into three.
281
+
282
+ Two planes are the same surface when their normals are near-parallel and
283
+ each origin lies within `distance_threshold` of the other's plane.
284
+ """
285
+ if len(planes) <= 1:
286
+ return planes
287
+
288
+ cos_limit = float(np.cos(np.deg2rad(angle_degrees)))
289
+ merged: list[dict] = []
290
+ for plane in sorted(planes, key=lambda item: -int(item["inlierCount"])):
291
+ normal = np.asarray(plane["normal"], dtype=np.float64)
292
+ origin = np.asarray(plane["origin"], dtype=np.float64)
293
+ target = None
294
+ for candidate in merged:
295
+ candidate_normal = np.asarray(candidate["normal"], dtype=np.float64)
296
+ candidate_origin = np.asarray(candidate["origin"], dtype=np.float64)
297
+ if abs(float(normal @ candidate_normal)) < cos_limit:
298
+ continue
299
+ if abs(float((origin - candidate_origin) @ candidate_normal)) > distance_threshold:
300
+ continue
301
+ target = candidate
302
+ break
303
+
304
+ if target is None:
305
+ merged.append(dict(plane))
306
+ continue
307
+
308
+ # Inlier-weighted average, so the dominant plane keeps its orientation.
309
+ target_normal = np.asarray(target["normal"], dtype=np.float64)
310
+ if float(normal @ target_normal) < 0:
311
+ normal = -normal # opposite-facing fits of one surface
312
+ weight_a = float(target["inlierCount"])
313
+ weight_b = float(plane["inlierCount"])
314
+ total = max(weight_a + weight_b, 1.0)
315
+ fused_normal = (target_normal * weight_a + normal * weight_b) / total
316
+ norm = float(np.linalg.norm(fused_normal))
317
+ if norm > 1e-6:
318
+ fused_normal /= norm
319
+ else:
320
+ fused_normal = target_normal
321
+ fused_origin = (
322
+ np.asarray(target["origin"], dtype=np.float64) * weight_a + origin * weight_b
323
+ ) / total
324
+ target["normal"] = fused_normal.astype(np.float32)
325
+ target["origin"] = fused_origin.astype(np.float32)
326
+ target["offset"] = float(-fused_origin @ fused_normal)
327
+ target["inlierCount"] = int(weight_a + weight_b)
328
+
329
+ for index, plane in enumerate(merged):
330
+ plane["id"] = index
331
+ u_axis, v_axis = plane_basis(plane["normal"], bool(plane.get("isFloor")), vertical_ref)
332
+ plane["uAxis"] = u_axis
333
+ plane["vAxis"] = v_axis
334
+ return merged
335
+
336
+
337
  def assign_points_to_surface_planes(
338
  points: np.ndarray,
339
  normals: np.ndarray,
services/geometry/plane_fitting.py CHANGED
@@ -34,7 +34,18 @@ def refine_plane(points: np.ndarray, normals: np.ndarray | None = None):
34
  return centroid, normal
35
 
36
 
37
- def plane_basis(normal: np.ndarray, is_floor: bool):
 
 
 
 
 
 
 
 
 
 
 
38
  normal = normal.astype(np.float32)
39
  normal /= max(float(np.linalg.norm(normal)), 1e-6)
40
  if is_floor:
@@ -46,11 +57,21 @@ def plane_basis(normal: np.ndarray, is_floor: bool):
46
  u_axis /= max(float(np.linalg.norm(u_axis)), 1e-6)
47
  v_axis = np.cross(normal, u_axis)
48
  else:
49
- vertical_ref = np.array([0.0, 1.0, 0.0], dtype=np.float32)
50
- v_axis = vertical_ref - normal * float(vertical_ref @ normal)
 
 
 
 
 
 
 
 
 
 
51
  if float(np.linalg.norm(v_axis)) < 1e-5:
52
- vertical_ref = np.array([0.0, 0.0, 1.0], dtype=np.float32)
53
- v_axis = vertical_ref - normal * float(vertical_ref @ normal)
54
  v_axis /= max(float(np.linalg.norm(v_axis)), 1e-6)
55
  u_axis = np.cross(v_axis, normal)
56
  u_axis /= max(float(np.linalg.norm(u_axis)), 1e-6)
@@ -72,6 +93,7 @@ def fit_metric_floor_transform(
72
  intrinsics: np.ndarray | None = None,
73
  provider: str = GeometryProvider.METRIC_DEPTH,
74
  surface_kind: str = "floor",
 
75
  ):
76
  # Import here to avoid circular dependency with ransac module
77
  from services.geometry.ransac import ransac_plane_fit
@@ -133,7 +155,7 @@ def fit_metric_floor_transform(
133
 
134
  # Use local horizontal/vertical axes for walls and horizontal/depth axes
135
  # for floors. This keeps physical tile dimensions stable across surfaces.
136
- u_axis, v_axis = plane_basis(normal, is_floor=surface_kind != "wall")
137
 
138
  projected_points, _ = project_points_to_plane(points[keep], centroid, normal)
139
  floor_points = projected_points - centroid
@@ -202,6 +224,7 @@ def estimate_metric_floor_transform(
202
  provider: str = GeometryProvider.DEPTH_ANYTHING,
203
  intrinsics: np.ndarray | None = None,
204
  surface_kind: str = "floor",
 
205
  ):
206
  from config.models import DEPTH_MODEL_NAME
207
  from config.runtime import ENABLE_PLANE_FIT
@@ -219,6 +242,7 @@ def estimate_metric_floor_transform(
219
  intrinsics=pixel_intrinsics,
220
  provider=provider,
221
  surface_kind=surface_kind,
 
222
  )
223
  if result is not None:
224
  result["depthScale"] = depth_scale
 
34
  return centroid, normal
35
 
36
 
37
+ def plane_basis(normal: np.ndarray, is_floor: bool, vertical_ref: np.ndarray | None = None):
38
+ """Build (u, v) axes for a plane.
39
+
40
+ For a non-floor surface v is world-up projected onto the plane, so tiles run
41
+ up the wall. `vertical_ref` is which direction "up" actually is.
42
+
43
+ It defaults to +Y, but geometry providers return points in *camera*
44
+ coordinates, so +Y is camera-up rather than gravity-up. Any camera tilt then
45
+ rotates every wall's tile grid by that same angle. Callers that know the
46
+ floor plane should pass its normal: a floor is horizontal by definition, so
47
+ its normal is true vertical in whatever frame the points are expressed in.
48
+ """
49
  normal = normal.astype(np.float32)
50
  normal /= max(float(np.linalg.norm(normal)), 1e-6)
51
  if is_floor:
 
57
  u_axis /= max(float(np.linalg.norm(u_axis)), 1e-6)
58
  v_axis = np.cross(normal, u_axis)
59
  else:
60
+ camera_up = np.array([0.0, 1.0, 0.0], dtype=np.float32)
61
+ if vertical_ref is None:
62
+ up = camera_up
63
+ else:
64
+ up = np.asarray(vertical_ref, dtype=np.float32).copy()
65
+ length = float(np.linalg.norm(up))
66
+ up = camera_up if length < 1e-6 else up / length
67
+ # A plane normal has arbitrary sign; keep the axis pointing the same
68
+ # way as before so tile orientation does not flip.
69
+ if float(up @ camera_up) < 0:
70
+ up = -up
71
+ v_axis = up - normal * float(up @ normal)
72
  if float(np.linalg.norm(v_axis)) < 1e-5:
73
+ up = np.array([0.0, 0.0, 1.0], dtype=np.float32)
74
+ v_axis = up - normal * float(up @ normal)
75
  v_axis /= max(float(np.linalg.norm(v_axis)), 1e-6)
76
  u_axis = np.cross(v_axis, normal)
77
  u_axis /= max(float(np.linalg.norm(u_axis)), 1e-6)
 
93
  intrinsics: np.ndarray | None = None,
94
  provider: str = GeometryProvider.METRIC_DEPTH,
95
  surface_kind: str = "floor",
96
+ vertical_ref: np.ndarray | None = None,
97
  ):
98
  # Import here to avoid circular dependency with ransac module
99
  from services.geometry.ransac import ransac_plane_fit
 
155
 
156
  # Use local horizontal/vertical axes for walls and horizontal/depth axes
157
  # for floors. This keeps physical tile dimensions stable across surfaces.
158
+ u_axis, v_axis = plane_basis(normal, is_floor=surface_kind != "wall", vertical_ref=vertical_ref)
159
 
160
  projected_points, _ = project_points_to_plane(points[keep], centroid, normal)
161
  floor_points = projected_points - centroid
 
224
  provider: str = GeometryProvider.DEPTH_ANYTHING,
225
  intrinsics: np.ndarray | None = None,
226
  surface_kind: str = "floor",
227
+ vertical_ref: np.ndarray | None = None,
228
  ):
229
  from config.models import DEPTH_MODEL_NAME
230
  from config.runtime import ENABLE_PLANE_FIT
 
242
  intrinsics=pixel_intrinsics,
243
  provider=provider,
244
  surface_kind=surface_kind,
245
+ vertical_ref=vertical_ref,
246
  )
247
  if result is not None:
248
  result["depthScale"] = depth_scale
services/geometry/uv_mapping.py CHANGED
@@ -19,6 +19,7 @@ from services.geometry.multi_plane import (
19
  assign_points_to_surface_planes,
20
  fit_multi_surface_planes,
21
  geometry_point_maps,
 
22
  )
23
  from services.geometry.plane_fitting import project_points_to_plane, surface_distance_threshold
24
 
@@ -28,6 +29,7 @@ def analyze_surface_uv_quality(
28
  surface_indices: np.ndarray,
29
  uv_by_mask: np.ndarray,
30
  plane_ids: np.ndarray,
 
31
  ) -> dict:
32
  total_pixels = int(len(surface_indices))
33
  finite_uv = np.isfinite(uv_by_mask).all(axis=1) if total_pixels else np.zeros(0, dtype=bool)
@@ -59,7 +61,7 @@ def analyze_surface_uv_quality(
59
  if total_pixels == 0:
60
  quality["textureMappingReason"] = TextureMappingReason.EMPTY_SURFACE
61
  return quality
62
- if coverage < SURFACE_UV_MIN_COVERAGE:
63
  quality["textureMappingReason"] = TextureMappingReason.INCOMPLETE_SURFACE_UV
64
  return quality
65
  h, w = surface_mask.shape[:2]
@@ -128,6 +130,22 @@ def build_surface_uv_mapping(
128
  geometry: dict | None,
129
  *,
130
  geometry_maps: dict | None = None,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  ):
132
  total_started = time.perf_counter()
133
  phase_started = total_started
@@ -185,7 +203,15 @@ def build_surface_uv_mapping(
185
  )
186
 
187
  phase_started = time.perf_counter()
188
- planes = fit_multi_surface_planes(points, normals, normals_reliable)
 
 
 
 
 
 
 
 
189
  plane_fit_ms = (time.perf_counter() - phase_started) * 1000
190
  if not planes:
191
  print(
@@ -236,6 +262,59 @@ def build_surface_uv_mapping(
236
  plane_ids[assigned_positions] = plane_idx
237
  plane["assignedCount"] = int(assigned_keep.sum())
238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  serializable_planes = []
240
  for plane in planes:
241
  assigned_plane_uv = uv_by_mask[plane_ids == int(plane["id"])]
@@ -266,7 +345,10 @@ def build_surface_uv_mapping(
266
 
267
  phase_started = time.perf_counter()
268
  finite_uv = np.isfinite(uv_by_mask).all(axis=1)
269
- uv_quality = analyze_surface_uv_quality(surface_mask, surface_indices, uv_by_mask, plane_ids)
 
 
 
270
  quality_ms = (time.perf_counter() - phase_started) * 1000
271
  uv_quality["surfaceUvPlaneDistanceLimitMeters"] = float(assignment_distance_limit)
272
  uv_quality["surfaceUvRejectedByPlaneDistance"] = int(rejected_by_distance)
 
19
  assign_points_to_surface_planes,
20
  fit_multi_surface_planes,
21
  geometry_point_maps,
22
+ merge_coplanar_planes,
23
  )
24
  from services.geometry.plane_fitting import project_points_to_plane, surface_distance_threshold
25
 
 
29
  surface_indices: np.ndarray,
30
  uv_by_mask: np.ndarray,
31
  plane_ids: np.ndarray,
32
+ min_coverage: float = SURFACE_UV_MIN_COVERAGE,
33
  ) -> dict:
34
  total_pixels = int(len(surface_indices))
35
  finite_uv = np.isfinite(uv_by_mask).all(axis=1) if total_pixels else np.zeros(0, dtype=bool)
 
61
  if total_pixels == 0:
62
  quality["textureMappingReason"] = TextureMappingReason.EMPTY_SURFACE
63
  return quality
64
+ if coverage < min_coverage:
65
  quality["textureMappingReason"] = TextureMappingReason.INCOMPLETE_SURFACE_UV
66
  return quality
67
  h, w = surface_mask.shape[:2]
 
130
  geometry: dict | None,
131
  *,
132
  geometry_maps: dict | None = None,
133
+ mark_floor: bool = True,
134
+ min_coverage: float | None = None,
135
+ # Depth is noisy exactly where a surface is hardest to see -- at grazing
136
+ # angles, in corners, behind furniture -- so a minority of pixels always
137
+ # sits too far off the fitted plane to be assigned a UV from their own 3D
138
+ # points. Left unfilled they keep NaN, coverage drops below the gate, and
139
+ # the whole per-pixel mapping is discarded for a single homography. For a
140
+ # floor that means the regularized-plane quad, a straight-edged trapezoid
141
+ # that under-covers the mask at the corners.
142
+ #
143
+ # The plane and the camera are both known, so a UV exists regardless of
144
+ # depth: intersect the pixel's ray with the plane. Defaulted on because
145
+ # that is the right answer for any surface -- it was off only because the
146
+ # fill was written for walls and floors were left on the old path.
147
+ fill_missing_from_plane: bool = True,
148
+ vertical_ref: np.ndarray | None = None,
149
  ):
150
  total_started = time.perf_counter()
151
  phase_started = total_started
 
203
  )
204
 
205
  phase_started = time.perf_counter()
206
+ planes = fit_multi_surface_planes(points, normals, normals_reliable, mark_floor=mark_floor,
207
+ vertical_ref=vertical_ref)
208
+ if not mark_floor:
209
+ # One flat wall attracts several near-identical RANSAC planes when
210
+ # normals are noisy. Distinct plane ids mean distinct UV origins, so
211
+ # the tile grid would restart mid-wall. Floors keep the original
212
+ # behaviour untouched.
213
+ planes = merge_coplanar_planes(planes, surface_distance_threshold(points),
214
+ vertical_ref=vertical_ref)
215
  plane_fit_ms = (time.perf_counter() - phase_started) * 1000
216
  if not planes:
217
  print(
 
262
  plane_ids[assigned_positions] = plane_idx
263
  plane["assignedCount"] = int(assigned_keep.sum())
264
 
265
+ if fill_missing_from_plane and planes:
266
+ # Pixels with no usable depth still belong to the surface: on a wall they
267
+ # are the TV, the mirror, the cabinet standing in front of it. Their 3D
268
+ # points describe the *object*, not the wall, so plane assignment leaves
269
+ # them without UV and coverage collapses (0.78 on one living-room wall).
270
+ #
271
+ # We know the plane and the camera, so a UV exists regardless of depth:
272
+ # intersect each pixel's camera ray with the plane. That both restores
273
+ # coverage and makes the tile grid continue correctly behind the object,
274
+ # which is what tiling *behind* an occluder is supposed to look like.
275
+ missing = ~np.isfinite(uv_by_mask).all(axis=1)
276
+ if missing.any():
277
+ dominant_idx = int(np.argmax([
278
+ int(plane.get("assignedCount", 0)) or int(plane["inlierCount"])
279
+ for plane in planes
280
+ ]))
281
+ dominant = planes[dominant_idx]
282
+ width = surface_mask.shape[1]
283
+ flat = surface_indices[missing].astype(np.int64)
284
+ pixel_y = (flat // width).astype(np.float32)
285
+ pixel_x = (flat % width).astype(np.float32)
286
+ intrinsics = np.asarray(maps["intrinsics"], dtype=np.float32)
287
+ fx = float(intrinsics[0, 0]) or 1.0
288
+ fy = float(intrinsics[1, 1]) or 1.0
289
+ cx, cy = float(intrinsics[0, 2]), float(intrinsics[1, 2])
290
+ rays = np.column_stack((
291
+ (pixel_x - cx) / fx,
292
+ (pixel_y - cy) / fy,
293
+ np.ones(len(pixel_x), dtype=np.float32),
294
+ )).astype(np.float32)
295
+ normal = np.asarray(dominant["normal"], dtype=np.float32)
296
+ origin = np.asarray(dominant["origin"], dtype=np.float32)
297
+ denominator = rays @ normal
298
+ usable = np.abs(denominator) > 1e-6
299
+ distances = np.zeros(len(rays), dtype=np.float32)
300
+ distances[usable] = float(origin @ normal) / denominator[usable]
301
+ usable &= distances > 0 # plane behind the camera is not a hit
302
+ if usable.any():
303
+ hit = rays[usable] * distances[usable, None]
304
+ delta = hit - origin
305
+ filled_uv = np.column_stack((
306
+ delta @ np.asarray(dominant["uAxis"], dtype=np.float32),
307
+ delta @ np.asarray(dominant["vAxis"], dtype=np.float32),
308
+ )).astype(np.float32)
309
+ target = np.where(missing)[0][usable]
310
+ uv_by_mask[target] = filled_uv
311
+ plane_ids[target] = dominant_idx
312
+ print(
313
+ f"[SURFACE_MAPPING] ray-plane filled {int(usable.sum())} "
314
+ f"occluded pixels from plane {dominant_idx}",
315
+ flush=True,
316
+ )
317
+
318
  serializable_planes = []
319
  for plane in planes:
320
  assigned_plane_uv = uv_by_mask[plane_ids == int(plane["id"])]
 
345
 
346
  phase_started = time.perf_counter()
347
  finite_uv = np.isfinite(uv_by_mask).all(axis=1)
348
+ uv_quality = analyze_surface_uv_quality(
349
+ surface_mask, surface_indices, uv_by_mask, plane_ids,
350
+ min_coverage=SURFACE_UV_MIN_COVERAGE if min_coverage is None else min_coverage,
351
+ )
352
  quality_ms = (time.perf_counter() - phase_started) * 1000
353
  uv_quality["surfaceUvPlaneDistanceLimitMeters"] = float(assignment_distance_limit)
354
  uv_quality["surfaceUvRejectedByPlaneDistance"] = int(rejected_by_distance)
services/image/edge_snap.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pull a mask boundary onto the nearest real edge in the photograph.
2
+
3
+ Why
4
+ ---
5
+ Surface masks pass through several morphological stages -- closing gaps, opening
6
+ away noise, dilating to cover the wall/floor join. Those kernels are ellipses,
7
+ and pushing a straight architectural line through a few ellipse close/open/dilate
8
+ passes scallops it. On a 1200x1600 photo the cumulative rounding radius is
9
+ 10-15 px, which reads as a wobbly boundary along what should be a dead-straight
10
+ wall/ceiling or wall/floor join. Floors get it worst, having the largest kernels.
11
+
12
+ Shrinking the kernels is not the answer: they exist to close holes and cover
13
+ joins, and making them smaller trades wobble for gaps.
14
+
15
+ How
16
+ ---
17
+ A guided filter (He et al., "Guided Image Filtering") using the photo itself as
18
+ the guide. Where the image has an edge, the filter's local linear model follows
19
+ it and the mask boundary snaps onto it; where the image is flat, it just
20
+ smooths. That both removes the morphological scalloping and improves accuracy,
21
+ and it needs no per-surface tuning because the photo supplies the geometry.
22
+
23
+ Implemented with box filters rather than cv2.ximgproc.guidedFilter, which lives
24
+ in opencv-contrib and is not in opencv-python-headless.
25
+
26
+ Limits
27
+ ------
28
+ It can only snap to an edge that is visible. A white wall meeting a white
29
+ ceiling has almost no gradient, so the boundary there is smoothed but not
30
+ relocated. Callers must still re-apply their own exclusions afterwards: the
31
+ filter knows about image edges, not about semantics, so nothing stops it
32
+ drifting a few pixels into a neighbouring class.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import cv2
38
+ import numpy as np
39
+
40
+
41
+ def guided_filter(guide: np.ndarray, source: np.ndarray, radius: int, eps: float) -> np.ndarray:
42
+ """Single-channel guided filter. `guide` and `source` are float32 in [0, 1]."""
43
+ window = (radius, radius)
44
+ mean_guide = cv2.boxFilter(guide, -1, window)
45
+ mean_source = cv2.boxFilter(source, -1, window)
46
+ mean_guide_source = cv2.boxFilter(guide * source, -1, window)
47
+ covariance = mean_guide_source - mean_guide * mean_source
48
+
49
+ mean_guide_sq = cv2.boxFilter(guide * guide, -1, window)
50
+ variance = mean_guide_sq - mean_guide * mean_guide
51
+
52
+ scale = covariance / (variance + eps)
53
+ offset = mean_source - scale * mean_guide
54
+ return cv2.boxFilter(scale, -1, window) * guide + cv2.boxFilter(offset, -1, window)
55
+
56
+
57
+ def snap_mask_to_image_edges(
58
+ mask: np.ndarray,
59
+ image_rgb: np.ndarray | None,
60
+ radius_ratio: float = 0.05,
61
+ eps: float = 1e-4,
62
+ threshold: float = 0.5,
63
+ ) -> np.ndarray:
64
+ """Return `mask` with its boundary pulled onto nearby edges in `image_rgb`.
65
+
66
+ Interior pixels are untouched -- the filter only moves boundaries, so a
67
+ reclaimed television sitting well inside the mask stays filled even though
68
+ it has strong edges of its own.
69
+
70
+ Returns the mask unchanged when no image is supplied, so callers that lack
71
+ one keep working.
72
+
73
+ radius_ratio is the important parameter and it must exceed the wobble it is
74
+ meant to remove -- the filter can only move a boundary about `radius` px.
75
+ Measured on a synthetic straight edge with a +/-6 px wobble, boundary
76
+ std-dev came out at:
77
+
78
+ ratio 0.01 (r=5) 3.69 px barely better than the 3.88 px input
79
+ ratio 0.03 (r=13) 2.11 px
80
+ ratio 0.05 (r=21) 0.24 px lands exactly on the true edge
81
+ ratio 0.08 (r=33) 0.00 px
82
+
83
+ A large radius does not cost detail, because detail that matters has an
84
+ image edge for the filter to follow: a 40 px doorframe notch survived
85
+ intact at every ratio up to 0.08. eps barely matters between 1e-6 and 1e-4.
86
+ """
87
+ mask_u8 = mask.astype(np.uint8, copy=False)
88
+ if image_rgb is None or not mask_u8.any() or mask_u8.all():
89
+ return mask_u8
90
+
91
+ height, width = mask_u8.shape[:2]
92
+ if image_rgb.shape[:2] != (height, width):
93
+ return mask_u8
94
+
95
+ radius = max(4, int(round(min(height, width) * radius_ratio))) | 1
96
+ guide = cv2.cvtColor(image_rgb.astype(np.uint8), cv2.COLOR_RGB2GRAY).astype(np.float32) / 255.0
97
+ filtered = guided_filter(guide, mask_u8.astype(np.float32), radius, eps)
98
+ return (filtered > threshold).astype(np.uint8)
services/pipeline/builder.py CHANGED
@@ -254,7 +254,7 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
254
  if ENABLE_WALL_SEGMENTS:
255
  t0 = time.perf_counter()
256
  wall_components, wall_protected_mask = wall_surface_components(
257
- seg_map, min_floor_area, geometry,
258
  )
259
  _log_stage("Wall Discovery", t0, f"components={len(wall_components)}")
260
 
@@ -267,8 +267,21 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
267
  def _compute_wall_lighting(component_mask):
268
  return build_luminance_lighting_maps(img_np, component_mask)
269
 
 
 
 
 
 
 
 
 
 
270
  wall_lighting_futures: list[Future] = []
271
- wall_executor = ThreadPoolExecutor(max_workers=max(1, len(wall_components))) if wall_components else None
 
 
 
 
272
  if wall_executor:
273
  for _, cm in wall_components:
274
  wall_lighting_futures.append(wall_executor.submit(_compute_wall_lighting, cm))
@@ -338,13 +351,33 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
338
  edge_metadata=edge_metadata, mapping_metadata=mapping_metadata,
339
  shade_statistics=shade_statistics, lighting_source=lighting_source,
340
  intrinsic_lighting_used=intrinsic_lighting_used, models=models, depth=depth, geometry=geometry))
 
 
 
 
 
 
 
 
 
 
 
 
341
  for wi, (_, cm) in enumerate(wall_components):
342
  ws = build_wall_segment(
343
  wi, cm, wall_protected_mask, geometry, img_np, wall_components, models,
344
  precomputed_lighting=wall_lighting_results[wi] if wi < len(wall_lighting_results) else None,
 
 
345
  )
346
  if ws:
347
  segments.append(ws)
 
 
 
 
 
 
348
  if not segments:
349
  segments = build_fallback_segments(seg_map, depth, models)
350
 
 
254
  if ENABLE_WALL_SEGMENTS:
255
  t0 = time.perf_counter()
256
  wall_components, wall_protected_mask = wall_surface_components(
257
+ seg_map, min_floor_area, geometry, image_rgb=img_np,
258
  )
259
  _log_stage("Wall Discovery", t0, f"components={len(wall_components)}")
260
 
 
267
  def _compute_wall_lighting(component_mask):
268
  return build_luminance_lighting_maps(img_np, component_mask)
269
 
270
+ # Walls had no lighting switch at all: this ran for every component however
271
+ # the floor's flags were set, so a run with lighting off was still lit.
272
+ # Gated on *any* path being enabled rather than on shading transfer alone,
273
+ # because the GPU profile already has that false while relying on fast
274
+ # shadow -- keying off it would have silently unlit production walls.
275
+ wall_lighting_enabled = (
276
+ ENABLE_INTRINSIC_SHADING or ENABLE_FAST_SHADOW_TRANSFER or ENABLE_SHADING_TRANSFER
277
+ )
278
+
279
  wall_lighting_futures: list[Future] = []
280
+ wall_executor = (
281
+ ThreadPoolExecutor(max_workers=max(1, len(wall_components)))
282
+ if wall_components and wall_lighting_enabled
283
+ else None
284
+ )
285
  if wall_executor:
286
  for _, cm in wall_components:
287
  wall_lighting_futures.append(wall_executor.submit(_compute_wall_lighting, cm))
 
351
  edge_metadata=edge_metadata, mapping_metadata=mapping_metadata,
352
  shade_statistics=shade_statistics, lighting_source=lighting_source,
353
  intrinsic_lighting_used=intrinsic_lighting_used, models=models, depth=depth, geometry=geometry))
354
+ # A floor is horizontal by definition, so its normal is true vertical in
355
+ # whatever frame the point cloud uses. Walls need that rather than +Y,
356
+ # which is camera-up and tilts the tile grid with the camera.
357
+ floor_up = None
358
+ if surface_mapping is not None:
359
+ for candidate in (surface_mapping.get('planes') or []):
360
+ if candidate.get('isFloor'):
361
+ floor_up = np.asarray(candidate['normal'], dtype=np.float32)
362
+ break
363
+ if floor_up is not None:
364
+ print(f'[WALL_UP] using floor normal as vertical: {floor_up.round(3).tolist()}', flush=True)
365
+ wall_segments = []
366
  for wi, (_, cm) in enumerate(wall_components):
367
  ws = build_wall_segment(
368
  wi, cm, wall_protected_mask, geometry, img_np, wall_components, models,
369
  precomputed_lighting=wall_lighting_results[wi] if wi < len(wall_lighting_results) else None,
370
+ up_vector=floor_up,
371
+ lighting_enabled=wall_lighting_enabled,
372
  )
373
  if ws:
374
  segments.append(ws)
375
+ wall_segments.append(ws)
376
+ # Only when wall discovery actually ran. With ENABLE_WALL_SEGMENTS off
377
+ # there is no protected mask and nothing to report.
378
+ if d and ENABLE_WALL_SEGMENTS:
379
+ debug_stages.record_walls(d, img_np, wall_mask, wall_protected_mask, wall_components,
380
+ wall_segments, (time.perf_counter() - t0) * 1000)
381
  if not segments:
382
  segments = build_fallback_segments(seg_map, depth, models)
383
 
services/pipeline/bundle_assembly.py CHANGED
@@ -21,8 +21,10 @@ from config.runtime import (
21
  ENABLE_SAM_REFINEMENT,
22
  ENABLE_SHADING_TRANSFER,
23
  )
 
24
  from models.segmentation import segmenter_metadata_name
25
  from state import class_ids, class_name_for_id
 
26
  from services.lighting.shading import build_luminance_lighting_maps
27
  from services.wall.plane import estimate_wall_plane
28
  from enums import SurfaceType, TextureMappingMode
@@ -141,13 +143,53 @@ def build_wall_segment(
141
  wall_components: list,
142
  models: dict,
143
  precomputed_lighting: dict | None = None,
 
 
144
  ) -> dict | None:
145
- wall_homography, wall_plane = estimate_wall_plane(component_mask, geometry)
 
 
 
 
 
 
 
146
  if wall_homography is None or wall_plane is None:
147
  return None
148
- wall_lighting_maps = precomputed_lighting if precomputed_lighting is not None else build_luminance_lighting_maps(img_np, component_mask)
 
 
 
 
 
 
 
 
 
149
  wall_indices = np.flatnonzero(component_mask.ravel()).astype(np.uint32)
150
- wall_occlusion_indices = np.flatnonzero(wall_protected_mask.ravel()).astype(np.uint32)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  wall_shade_map = wall_lighting_maps.get("shadeMap") if wall_lighting_maps else None
152
  wall_showroom = wall_lighting_maps.get("showroomShadeMap") if wall_lighting_maps else None
153
  wall_reflection = wall_lighting_maps.get("reflectionMap") if wall_lighting_maps else None
@@ -161,9 +203,10 @@ def build_wall_segment(
161
  "floorTransform": wall_plane.get("floorTransform"),
162
  "surfaceTransform": wall_plane.get("surfaceTransform"),
163
  "plane": wall_plane,
164
- "surfaceUv": None,
165
- "surfacePlaneIds": None,
166
- "surfacePlanes": None,
 
167
  "shadeMap": wall_shade_map,
168
  "showroomShadeMap": wall_showroom,
169
  "reflectionMap": wall_reflection,
@@ -173,11 +216,18 @@ def build_wall_segment(
173
  "wallPixels": int(component_mask.sum()),
174
  "wallComponent": wall_index,
175
  "wallComponentCount": len(wall_components),
176
- "protectedPixels": int(wall_protected_mask.sum()),
177
  "shadingEnabled": wall_shade_map is not None,
178
  "reflectionTransferEnabled": wall_reflection is not None,
 
 
 
 
 
179
  "textureMappingMode": (
180
- TextureMappingMode.WALL_PLANE if wall_plane.get("surfaceTransform") else TextureMappingMode.WALL_CONTOUR_HOMOGRAPHY
 
 
181
  ),
182
  "geometryConfidence": wall_plane.get("geometryConfidence", 0.0),
183
  "geometryProvider": wall_plane.get("geometryProvider"),
 
21
  ENABLE_SAM_REFINEMENT,
22
  ENABLE_SHADING_TRANSFER,
23
  )
24
+ from config.surface import SURFACE_UV_WALL_MIN_COVERAGE
25
  from models.segmentation import segmenter_metadata_name
26
  from state import class_ids, class_name_for_id
27
+ from services.geometry.uv_mapping import build_surface_uv_mapping
28
  from services.lighting.shading import build_luminance_lighting_maps
29
  from services.wall.plane import estimate_wall_plane
30
  from enums import SurfaceType, TextureMappingMode
 
143
  wall_components: list,
144
  models: dict,
145
  precomputed_lighting: dict | None = None,
146
+ up_vector=None,
147
+ lighting_enabled: bool = True,
148
  ) -> dict | None:
149
+ # True vertical, taken from the floor, reaches the plane fit as well as the
150
+ # UV mapping below. The plane's basis is what the renderer falls back to
151
+ # when there is no per-pixel UV, and its extents are what tile density is
152
+ # computed from, so a camera-aligned basis here tilts and mis-scales the
153
+ # grid even when the UV path is gravity-aligned.
154
+ wall_homography, wall_plane = estimate_wall_plane(
155
+ component_mask, geometry, vertical_ref=up_vector
156
+ )
157
  if wall_homography is None or wall_plane is None:
158
  return None
159
+ # The flag wins over a pre-computed map, so lighting cannot leak back in
160
+ # from a stale hand-off. Checked before the fallback too: skipping only the
161
+ # caller's pre-compute would move this work into packaging rather than
162
+ # remove it, and serially at that.
163
+ if not lighting_enabled:
164
+ wall_lighting_maps = None
165
+ elif precomputed_lighting is not None:
166
+ wall_lighting_maps = precomputed_lighting
167
+ else:
168
+ wall_lighting_maps = build_luminance_lighting_maps(img_np, component_mask)
169
  wall_indices = np.flatnonzero(component_mask.ravel()).astype(np.uint32)
170
+ # Only objects sitting on *this* wall occlude it. Shipping the global
171
+ # protected mask made every wall claim every mirror, cabinet and door in the
172
+ # room, so the renderer punched other walls' furniture through this one.
173
+ # Intersecting with the component also excludes barrier classes for free,
174
+ # because a refined component never contains them.
175
+ wall_occlusion_mask = (wall_protected_mask > 0) & (component_mask > 0)
176
+ wall_occlusion_indices = np.flatnonzero(wall_occlusion_mask.ravel()).astype(np.uint32)
177
+
178
+ # Per-pixel UV, exactly as the floor gets it. Walls previously shipped a
179
+ # single homography, so tile scale came from the wall's bounding box rather
180
+ # than from measured geometry. mark_floor=False keeps the UV basis
181
+ # gravity-aligned: v runs up the wall, u runs along it.
182
+ wall_mapping = build_surface_uv_mapping(
183
+ component_mask, wall_indices, geometry,
184
+ mark_floor=False, min_coverage=SURFACE_UV_WALL_MIN_COVERAGE,
185
+ fill_missing_from_plane=True,
186
+ # True vertical, taken from the floor. Geometry providers work in
187
+ # camera coordinates, so assuming +Y is up rotates every wall's tile
188
+ # grid by the camera's tilt.
189
+ vertical_ref=up_vector,
190
+ )
191
+ use_wall_uv = bool(wall_mapping and wall_mapping.get("useSurfaceUv"))
192
+ wall_mapping_metadata = wall_mapping["metadata"] if wall_mapping is not None else {}
193
  wall_shade_map = wall_lighting_maps.get("shadeMap") if wall_lighting_maps else None
194
  wall_showroom = wall_lighting_maps.get("showroomShadeMap") if wall_lighting_maps else None
195
  wall_reflection = wall_lighting_maps.get("reflectionMap") if wall_lighting_maps else None
 
203
  "floorTransform": wall_plane.get("floorTransform"),
204
  "surfaceTransform": wall_plane.get("surfaceTransform"),
205
  "plane": wall_plane,
206
+ # Raw numpy arrays; packaging writes them straight to disk as lazy assets.
207
+ "surfaceUv": wall_mapping["uv"].astype(np.float32) if use_wall_uv else None,
208
+ "surfacePlaneIds": wall_mapping["planeIds"].astype(np.uint8) if use_wall_uv else None,
209
+ "surfacePlanes": wall_mapping["planes"] if wall_mapping is not None else None,
210
  "shadeMap": wall_shade_map,
211
  "showroomShadeMap": wall_showroom,
212
  "reflectionMap": wall_reflection,
 
216
  "wallPixels": int(component_mask.sum()),
217
  "wallComponent": wall_index,
218
  "wallComponentCount": len(wall_components),
219
+ "protectedPixels": int(wall_occlusion_mask.sum()),
220
  "shadingEnabled": wall_shade_map is not None,
221
  "reflectionTransferEnabled": wall_reflection is not None,
222
+ # Spread first so the explicit mode below wins: the UV analyzer
223
+ # reports REGULARIZED_FLOOR_PLANE when it declines, which is not a
224
+ # meaningful value for a wall.
225
+ **wall_mapping_metadata,
226
+ "surfaceUvEnabled": use_wall_uv,
227
  "textureMappingMode": (
228
+ TextureMappingMode.SURFACE_UV if use_wall_uv
229
+ else TextureMappingMode.WALL_PLANE if wall_plane.get("surfaceTransform")
230
+ else TextureMappingMode.WALL_CONTOUR_HOMOGRAPHY
231
  ),
232
  "geometryConfidence": wall_plane.get("geometryConfidence", 0.0),
233
  "geometryProvider": wall_plane.get("geometryProvider"),
services/pipeline/debug_stages.py CHANGED
@@ -15,6 +15,7 @@ from services.debug.overlays import (
15
  debug_segmentation_overlay,
16
  debug_surface_overlay,
17
  debug_uv_checkerboard,
 
18
  )
19
  from state import class_name_for_id
20
 
@@ -60,6 +61,59 @@ def record_floor_mask(debug: PipelineDebugCapture, img_np, raw_mask, cleaned_mas
60
  )
61
 
62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  def record_geometry(debug: PipelineDebugCapture, depth, floor_mask, geometry, elapsed_ms):
64
  imgs = [("Depth", debug_scalar_map(depth, floor_mask))] if depth is not None else []
65
  debug.record_images(
 
15
  debug_segmentation_overlay,
16
  debug_surface_overlay,
17
  debug_uv_checkerboard,
18
+ debug_wall_components_overlay,
19
  )
20
  from state import class_name_for_id
21
 
 
61
  )
62
 
63
 
64
+ def record_walls(debug: PipelineDebugCapture, img_np, raw_wall_mask, protected_mask,
65
+ components, wall_segments, elapsed_ms):
66
+ """Record wall detection so the wall path is inspectable like the floor path.
67
+
68
+ Three views answer the three ways wall detection goes wrong:
69
+ * Raw wall class - did segmentation find the wall at all?
70
+ * Protected (removed) - what wall_surface_components() strips out before
71
+ splitting (mirrors, doors, windows, curtains,
72
+ paintings, occluders). Holes here become holes in
73
+ the tiled result.
74
+ * Wall components - how the wall was split into renderable regions.
75
+ Followed by one plane overlay per accepted wall segment.
76
+ """
77
+ # The protected mask only exists when wall discovery ran. With walls
78
+ # switched off there is nothing to show, and diagnostics must not be what
79
+ # takes a conversion down -- turning walls off is how the feature gets
80
+ # backed out, so a crash here would break the rollback itself.
81
+ images = [("Raw wall class", debug_mask_overlay(img_np, raw_wall_mask))]
82
+ if protected_mask is not None:
83
+ images.append(
84
+ ("Protected (removed)", debug_mask_overlay(img_np, protected_mask, (220, 80, 80)))
85
+ )
86
+ images.append(("Wall components", debug_wall_components_overlay(img_np, components)))
87
+ for index, segment in enumerate(wall_segments):
88
+ plane = segment.get("plane") if isinstance(segment, dict) else None
89
+ if plane:
90
+ images.append((f"Wall {index + 1} plane", debug_plane_overlay(img_np, plane)))
91
+
92
+ component_pixels = [int(item[1].sum()) for item in components]
93
+ debug.record_images(
94
+ "wall-surfaces", "Wall surfaces",
95
+ "Wall mask, the protected classes removed before splitting, and the resulting "
96
+ "renderable wall components with their fitted planes.",
97
+ images,
98
+ {
99
+ "rawWallPixels": int(raw_wall_mask.sum()),
100
+ "protectedPixels": int(protected_mask.sum()) if protected_mask is not None else 0,
101
+ "componentCount": len(components),
102
+ "componentPixels": component_pixels,
103
+ "acceptedWallSegments": len(wall_segments),
104
+ "textureMappingModes": [
105
+ (s.get("metadata") or {}).get("textureMappingMode")
106
+ for s in wall_segments if isinstance(s, dict)
107
+ ],
108
+ "surfaceUvAvailable": [
109
+ bool(s.get("surfaceUv") is not None)
110
+ for s in wall_segments if isinstance(s, dict)
111
+ ],
112
+ },
113
+ elapsed_ms,
114
+ )
115
+
116
+
117
  def record_geometry(debug: PipelineDebugCapture, depth, floor_mask, geometry, elapsed_ms):
118
  imgs = [("Depth", debug_scalar_map(depth, floor_mask))] if depth is not None else []
119
  debug.record_images(
services/pipeline/packaging.py CHANGED
@@ -12,7 +12,11 @@ import numpy as np
12
  from PIL import Image
13
 
14
  from config.paths import JOB_DIR
15
- from config.runtime import BUNDLE_IMAGE_FORMAT, BUNDLE_IMAGE_QUALITY
 
 
 
 
16
  from state import OCCLUDER_CLASSES, class_ids
17
  from utils import seg_class_mask
18
 
@@ -177,7 +181,15 @@ def build_manifest_segmentation_bundle(
177
  asset_dir.mkdir(parents=True, exist_ok=True)
178
 
179
  buffer = io.BytesIO()
180
- with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_STORED) as archive:
 
 
 
 
 
 
 
 
181
  if include_image:
182
  pixels_mime, pixels = data_url_to_bytes(bundle["pixels"])
183
  image_path = f"image.{bundle_image_extension(pixels_mime)}"
 
12
  from PIL import Image
13
 
14
  from config.paths import JOB_DIR
15
+ from config.runtime import (
16
+ BUNDLE_COMPRESSION_LEVEL,
17
+ BUNDLE_IMAGE_FORMAT,
18
+ BUNDLE_IMAGE_QUALITY,
19
+ )
20
  from state import OCCLUDER_CLASSES, class_ids
21
  from utils import seg_class_mask
22
 
 
181
  asset_dir.mkdir(parents=True, exist_ok=True)
182
 
183
  buffer = io.BytesIO()
184
+ compression = (
185
+ zipfile.ZIP_DEFLATED if BUNDLE_COMPRESSION_LEVEL > 0 else zipfile.ZIP_STORED
186
+ )
187
+ with zipfile.ZipFile(
188
+ buffer,
189
+ "w",
190
+ compression=compression,
191
+ compresslevel=BUNDLE_COMPRESSION_LEVEL or None,
192
+ ) as archive:
193
  if include_image:
194
  pixels_mime, pixels = data_url_to_bytes(bundle["pixels"])
195
  image_path = f"image.{bundle_image_extension(pixels_mime)}"
services/wall/components.py CHANGED
@@ -13,24 +13,122 @@ from services.geometry.multi_plane import (
13
  assign_points_to_surface_planes,
14
  fit_multi_surface_planes,
15
  geometry_point_maps,
 
 
16
  )
17
  from services.geometry.normals import normalize_vectors
 
 
 
18
  from state import OCCLUDER_CLASSES, class_ids
19
  from utils import seg_class_mask
20
 
21
 
22
- def wall_surface_components(seg_map: np.ndarray, min_area: int, geometry: dict | None = None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  """Create clean, independently renderable wall regions.
24
 
25
  Semantic wall predictions often bridge across corners and openings. Removing
26
  protected classes before connected-component analysis prevents one warped
27
  transform from being applied to several physically different walls.
28
  """
29
- wall = seg_class_mask(seg_map, class_ids({"wall"}))
 
 
 
 
 
30
  protected = seg_class_mask(seg_map, class_ids(OCCLUDER_CLASSES | {
31
  "door", "window", "column", "base", "railing", "ceiling",
32
  "building", "painting", "mirror", "curtain",
33
  }))
 
 
 
34
  radius = max(1, int(round(min(seg_map.shape[:2]) * 0.006)))
35
  kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius * 2 + 1, radius * 2 + 1))
36
  protected = cv2.dilate(protected, kernel, iterations=1)
@@ -39,54 +137,68 @@ def wall_surface_components(seg_map: np.ndarray, min_area: int, geometry: dict |
39
  wall = cv2.morphologyEx(wall, cv2.MORPH_OPEN, kernel)
40
  wall[protected > 0] = 0
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  components = []
43
- if geometry is not None:
44
- maps = geometry_point_maps(wall, geometry)
45
- if maps is not None:
46
- valid = maps["validMask"] & (wall > 0)
47
- ys, xs = np.where(valid)
48
- if len(xs) >= SURFACE_MIN_PLANE_PIXELS:
49
- points = maps["points"][ys, xs].astype(np.float32)
50
- normals = maps["normals"][ys, xs].astype(np.float32)
51
- finite = np.isfinite(points).all(axis=1) & np.isfinite(normals).all(axis=1)
52
- points, normals, ys, xs = points[finite], normals[finite], ys[finite], xs[finite]
53
- if len(points) >= SURFACE_MIN_PLANE_PIXELS:
54
- normals_reliable = np.linalg.norm(normals, axis=1) > 1e-4
55
- if normals_reliable.sum() >= SURFACE_MIN_PLANE_PIXELS:
56
- points = points[normals_reliable]
57
- normals = normalize_vectors(normals[normals_reliable])
58
- ys, xs = ys[normals_reliable], xs[normals_reliable]
59
- planes = fit_multi_surface_planes(points, normals, True)
60
- wall_planes = [
61
- plane for plane in planes
62
- if abs(float(plane["normal"][1])) <= 0.45
63
- ]
64
- if wall_planes:
65
- assignment = assign_points_to_surface_planes(
66
- points, normals, wall_planes, True
67
- )
68
- for plane_index in range(len(wall_planes)):
69
- selected = assignment == plane_index
70
- if int(selected.sum()) < min_area:
71
- continue
72
- plane_mask = np.zeros_like(wall)
73
- plane_mask[ys[selected], xs[selected]] = 1
74
- count, labels, stats, _ = cv2.connectedComponentsWithStats(
75
- plane_mask, connectivity=8
76
- )
77
- for component_id in range(1, count):
78
- area = int(stats[component_id, cv2.CC_STAT_AREA])
79
- if area >= min_area:
80
- components.append((area, (labels == component_id).astype(np.uint8)))
81
-
82
- # Geometry can be unavailable or too noisy. In that case retain the safe
83
- # semantic connected-component fallback instead of emitting no walls.
84
- if not components:
85
- count, labels, stats, _ = cv2.connectedComponentsWithStats(wall, connectivity=8)
86
- for component_id in range(1, count):
87
- area = int(stats[component_id, cv2.CC_STAT_AREA])
88
- if area < min_area:
89
- continue
90
- components.append((area, (labels == component_id).astype(np.uint8)))
91
  components.sort(key=lambda item: item[0], reverse=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  return components, protected
 
13
  assign_points_to_surface_planes,
14
  fit_multi_surface_planes,
15
  geometry_point_maps,
16
+ merge_coplanar_planes,
17
+ merge_planes_by_point_consistency,
18
  )
19
  from services.geometry.normals import normalize_vectors
20
+ from services.geometry.plane_fitting import surface_distance_threshold
21
+ from services.wall.corner import straighten_piece_seams
22
+ from services.wall.mask import refine_wall_component_mask, wall_region_masks
23
  from state import OCCLUDER_CLASSES, class_ids
24
  from utils import seg_class_mask
25
 
26
 
27
+ def split_region_if_not_planar(region: np.ndarray, geometry: dict | None, min_area: int):
28
+ """Return [region] when it is one flat wall, else split it by fitted planes.
29
+
30
+ Connectivity alone is not quite enough: where two walls meet at a corner
31
+ with nothing between them, segmentation bridges the corner and hands us one
32
+ region covering both. Those need separating, or one warped transform gets
33
+ stretched across an angle.
34
+
35
+ So geometry gets a narrow, well-posed job: decide whether this region is
36
+ flat. A single least-squares plane is fitted and the 90th-percentile
37
+ residual measured. A real wall sits within a couple of centimetres of its
38
+ own plane; a region spanning a corner does not come close. Only when the
39
+ region fails that test do we fall back to multi-plane splitting.
40
+ """
41
+ if geometry is None:
42
+ return [region]
43
+ maps = geometry_point_maps(region, geometry)
44
+ if maps is None:
45
+ return [region]
46
+
47
+ valid = maps["validMask"] & (region > 0)
48
+ ys, xs = np.where(valid)
49
+ if len(xs) < SURFACE_MIN_PLANE_PIXELS:
50
+ return [region]
51
+ points = maps["points"][ys, xs].astype(np.float32)
52
+ normals = maps["normals"][ys, xs].astype(np.float32)
53
+ finite = np.isfinite(points).all(axis=1) & np.isfinite(normals).all(axis=1)
54
+ points, normals, ys, xs = points[finite], normals[finite], ys[finite], xs[finite]
55
+ if len(points) < SURFACE_MIN_PLANE_PIXELS:
56
+ return [region]
57
+
58
+ threshold = surface_distance_threshold(points)
59
+ centered = points - points.mean(axis=0)
60
+ # Smallest-eigenvalue eigenvector of the covariance is the plane normal.
61
+ _eigenvalues, eigenvectors = np.linalg.eigh(centered.T @ centered)
62
+ residual = np.abs(centered @ eigenvectors[:, 0].astype(np.float32))
63
+ flatness = float(np.percentile(residual, 90))
64
+ print(
65
+ f"[WALL_REGION] {int(region.sum())} px p90Flatness={flatness:.3f}m "
66
+ f"threshold={threshold:.3f}m {'FLAT (keep whole)' if flatness <= threshold else 'not flat -> split by plane'}",
67
+ flush=True,
68
+ )
69
+ if flatness <= threshold:
70
+ return [region]
71
+
72
+ lengths = np.linalg.norm(normals, axis=1)
73
+ usable = lengths > 1e-4
74
+ if int(usable.sum()) < SURFACE_MIN_PLANE_PIXELS:
75
+ return [region]
76
+ points, ys, xs = points[usable], ys[usable], xs[usable]
77
+ normals = normalize_vectors(normals[usable])
78
+
79
+ planes = fit_multi_surface_planes(points, normals, True, mark_floor=False)
80
+ planes = merge_coplanar_planes(planes, threshold)
81
+ wall_planes = [plane for plane in planes if abs(float(plane["normal"][1])) <= 0.45]
82
+ if len(wall_planes) <= 1:
83
+ return [region]
84
+
85
+ assignment = assign_points_to_surface_planes(points, normals, wall_planes, True)
86
+ assignment, wall_planes = merge_planes_by_point_consistency(
87
+ points, assignment, wall_planes, threshold
88
+ )
89
+ if len(wall_planes) <= 1:
90
+ return [region]
91
+
92
+ pieces = []
93
+ for plane_index in range(len(wall_planes)):
94
+ selected = assignment == plane_index
95
+ if int(selected.sum()) < min_area:
96
+ continue
97
+ piece = np.zeros_like(region)
98
+ piece[ys[selected], xs[selected]] = 1
99
+ pieces.append((plane_index, piece))
100
+ if not pieces:
101
+ return [region]
102
+
103
+ # Per-pixel assignment is the wrong tool for the seam *between* these
104
+ # pieces. At the corner every plane is equidistant, so the score collapses
105
+ # onto blended depth normals and the boundary ends up both biased and
106
+ # ragged. Put each seam back on the line where its two planes actually
107
+ # intersect -- see services/wall/corner.py for the measurements.
108
+ return straighten_piece_seams(pieces, wall_planes, maps.get("intrinsics"), min_area)
109
+
110
+
111
+ def wall_surface_components(seg_map: np.ndarray, min_area: int, geometry: dict | None = None,
112
+ image_rgb: np.ndarray | None = None):
113
  """Create clean, independently renderable wall regions.
114
 
115
  Semantic wall predictions often bridge across corners and openings. Removing
116
  protected classes before connected-component analysis prevents one warped
117
  transform from being applied to several physically different walls.
118
  """
119
+ # Components may occupy the wall itself plus anything mounted on it; those
120
+ # objects are re-drawn over the tile via the segment occlusion mask instead
121
+ # of being cut out of the surface. See services/wall/mask.py.
122
+ wall_raw, barrier_mask, reclaimable_mask = wall_region_masks(seg_map)
123
+
124
+ wall = wall_raw.copy()
125
  protected = seg_class_mask(seg_map, class_ids(OCCLUDER_CLASSES | {
126
  "door", "window", "column", "base", "railing", "ceiling",
127
  "building", "painting", "mirror", "curtain",
128
  }))
129
+ # Wide enough to close the gap a wall-mounted TV or mirror leaves behind,
130
+ # narrow enough that a doorway or a room corner still separates two walls.
131
+ bridge_kernel_size = max(3, int(round(min(seg_map.shape[:2]) * 0.05))) | 1
132
  radius = max(1, int(round(min(seg_map.shape[:2]) * 0.006)))
133
  kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius * 2 + 1, radius * 2 + 1))
134
  protected = cv2.dilate(protected, kernel, iterations=1)
 
137
  wall = cv2.morphologyEx(wall, cv2.MORPH_OPEN, kernel)
138
  wall[protected > 0] = 0
139
 
140
+ # --- Stage 1: connectivity decides what counts as one wall ----------------
141
+ # Geometry used to decide this, by fitting planes over every wall pixel and
142
+ # assigning each pixel to its nearest plane. Per-pixel normals from depth are
143
+ # noisy, so that assignment banded single walls into vertical depth slabs: a
144
+ # living room with three walls produced three planes but five segments, each
145
+ # with its own UV frame, so the tile grid restarted and rotated at every
146
+ # seam. Spatial connectivity is far more reliable for "is this one wall",
147
+ # because walls are separated by corners, which are visible discontinuities.
148
+ bridge = cv2.morphologyEx(
149
+ wall,
150
+ cv2.MORPH_CLOSE,
151
+ cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (bridge_kernel_size, bridge_kernel_size)),
152
+ )
153
+ region_count, region_labels, _region_stats, _ = cv2.connectedComponentsWithStats(
154
+ bridge, connectivity=8
155
+ )
156
+ regions = []
157
+ for region_id in range(1, region_count):
158
+ region = ((region_labels == region_id) & (wall > 0)).astype(np.uint8)
159
+ if int(region.sum()) >= min_area:
160
+ regions.append(region)
161
+ print(f"[WALL_COMPONENTS] {len(regions)} connected wall region(s)", flush=True)
162
+
163
+ # --- Stage 2: geometry only splits a region that is not actually flat -----
164
+ # components is a list of (area, mask) pairs; the repair pass below sorts on
165
+ # the area, so pieces must be paired up rather than appended bare.
166
  components = []
167
+ for region in regions:
168
+ for piece in split_region_if_not_planar(region, geometry, min_area):
169
+ area = int(piece.sum())
170
+ if area >= min_area:
171
+ components.append((area, piece.astype(np.uint8)))
172
+
173
+ # --- Repair pass -------------------------------------------------------
174
+ # Splitting above deliberately runs on the protected-subtracted mask, so one
175
+ # warped transform is never stretched across a corner or an opening. Now
176
+ # that the split is settled, each component reclaims the holes that plane
177
+ # assignment and protection punched through it.
178
+ #
179
+ # Largest first, subtracting whatever earlier components already claimed, so
180
+ # the refined masks stay disjoint — otherwise the edge-repair dilation would
181
+ # let two walls overlap at a corner and that seam would be tiled twice.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
  components.sort(key=lambda item: item[0], reverse=True)
183
+ claimed = np.zeros(wall_raw.shape[:2], dtype=bool)
184
+ refined_components = []
185
+ for _, component_mask in components:
186
+ refined, _metadata = refine_wall_component_mask(
187
+ component_mask, wall_raw, reclaimable_mask, barrier_mask, image_rgb
188
+ )
189
+ refined[claimed] = 0
190
+ area = int(refined.sum())
191
+ if area < min_area:
192
+ continue
193
+ claimed |= refined.astype(bool)
194
+ refined_components.append((area, refined))
195
+
196
+ if refined_components:
197
+ refined_components.sort(key=lambda item: item[0], reverse=True)
198
+ print(
199
+ f"[WALL_COMPONENTS] emitting {len(refined_components)} wall segment(s): "
200
+ f"{[area for area, _ in refined_components]} px",
201
+ flush=True,
202
+ )
203
+ return refined_components, protected
204
  return components, protected
services/wall/plane.py CHANGED
@@ -16,14 +16,29 @@ from services.geometry.plane_fitting import (
16
  fit_metric_floor_transform,
17
  )
18
 
 
 
 
 
 
19
 
20
- def estimate_wall_plane(mask: np.ndarray, geometry: dict | None = None):
 
 
 
 
 
21
  """Return a stable image-space homography for a semantic wall mask.
22
 
23
  Walls do not currently have metric depth fitting, so use the visible wall
24
  contour as the source quad and its bounding rectangle as the planar target.
25
  This preserves perspective convergence while keeping physical tile sizes
26
  deterministic until wall-specific depth calibration is available.
 
 
 
 
 
27
  """
28
  ys, xs = np.where(mask > 0)
29
  if len(xs) < 1000:
@@ -63,6 +78,23 @@ def estimate_wall_plane(mask: np.ndarray, geometry: dict | None = None):
63
  if x2 - x1 < 20 or y2 - y1 < 20:
64
  return None, None
65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  destination = np.float32([[x1, y1], [x2, y1], [x2, y2], [x1, y2]])
67
  homography = cv2.getPerspectiveTransform(ordered, destination).flatten().tolist()
68
  metric_geometry = None
@@ -77,6 +109,7 @@ def estimate_wall_plane(mask: np.ndarray, geometry: dict | None = None):
77
  geometry.get("intrinsics"),
78
  geometry.get("provider", GeometryProvider.METRIC_DEPTH),
79
  surface_kind="wall",
 
80
  )
81
  if metric_geometry is None:
82
  metric_geometry = estimate_metric_floor_transform(
@@ -85,6 +118,7 @@ def estimate_wall_plane(mask: np.ndarray, geometry: dict | None = None):
85
  geometry.get("provider", GeometryProvider.DEPTH_ANYTHING),
86
  geometry.get("intrinsics"),
87
  surface_kind="wall",
 
88
  )
89
 
90
  plane = {
@@ -98,8 +132,10 @@ def estimate_wall_plane(mask: np.ndarray, geometry: dict | None = None):
98
  "floorTransform": None,
99
  "surfaceTransform": None,
100
  "surfaceType": SurfaceType.WALL,
101
- "surfaceWidthMeters": max(0.5, 2.4 * (x2 - x1) / max(y2 - y1, 1.0)),
102
- "surfaceHeightMeters": 2.4,
 
 
103
  "metersPerUnit": None,
104
  "cameraIntrinsics": None,
105
  "camera": {"focalLength": float(max(h, w) * 0.95), "horizonY": y1, "confidence": 0.45},
 
16
  fit_metric_floor_transform,
17
  )
18
 
19
+ # Assumed floor-to-ceiling height, in metres, for a wall with no depth to
20
+ # measure. Only the wall's *aspect* can be recovered from a single view without
21
+ # metric geometry, so this sets the absolute scale; the metric fit overrides
22
+ # both extents whenever it succeeds.
23
+ WALL_HEIGHT_PRIOR_METERS = 2.4
24
 
25
+
26
+ def estimate_wall_plane(
27
+ mask: np.ndarray,
28
+ geometry: dict | None = None,
29
+ vertical_ref: np.ndarray | None = None,
30
+ ):
31
  """Return a stable image-space homography for a semantic wall mask.
32
 
33
  Walls do not currently have metric depth fitting, so use the visible wall
34
  contour as the source quad and its bounding rectangle as the planar target.
35
  This preserves perspective convergence while keeping physical tile sizes
36
  deterministic until wall-specific depth calibration is available.
37
+
38
+ `vertical_ref` is which direction gravity-up points, in the same frame as
39
+ the geometry's points. Geometry providers work in camera coordinates, so
40
+ without it the metric fit assumes camera +Y is up and rotates the wall's
41
+ tile grid by the camera's roll. Callers should pass the floor normal.
42
  """
43
  ys, xs = np.where(mask > 0)
44
  if len(xs) < 1000:
 
78
  if x2 - x1 < 20 or y2 - y1 < 20:
79
  return None, None
80
 
81
+ # Measure the wall along its own edges, averaging opposite pairs.
82
+ #
83
+ # The axis-aligned bounding box was standing in for these, which overstates
84
+ # a tilted wall: a slanted mask falls through to `minAreaRect`, whose
85
+ # corners can sit well outside the image, and the box around that rotated
86
+ # rect is far wider than the wall. Edge lengths are unaffected by the tilt
87
+ # and by corners leaving the frame, and for an axis-aligned quad they are
88
+ # exactly the box dimensions, so only genuinely tilted walls move.
89
+ quad_width = 0.5 * (
90
+ float(np.linalg.norm(ordered[1] - ordered[0]))
91
+ + float(np.linalg.norm(ordered[2] - ordered[3]))
92
+ )
93
+ quad_height = 0.5 * (
94
+ float(np.linalg.norm(ordered[3] - ordered[0]))
95
+ + float(np.linalg.norm(ordered[2] - ordered[1]))
96
+ )
97
+
98
  destination = np.float32([[x1, y1], [x2, y1], [x2, y2], [x1, y2]])
99
  homography = cv2.getPerspectiveTransform(ordered, destination).flatten().tolist()
100
  metric_geometry = None
 
109
  geometry.get("intrinsics"),
110
  geometry.get("provider", GeometryProvider.METRIC_DEPTH),
111
  surface_kind="wall",
112
+ vertical_ref=vertical_ref,
113
  )
114
  if metric_geometry is None:
115
  metric_geometry = estimate_metric_floor_transform(
 
118
  geometry.get("provider", GeometryProvider.DEPTH_ANYTHING),
119
  geometry.get("intrinsics"),
120
  surface_kind="wall",
121
+ vertical_ref=vertical_ref,
122
  )
123
 
124
  plane = {
 
132
  "floorTransform": None,
133
  "surfaceTransform": None,
134
  "surfaceType": SurfaceType.WALL,
135
+ "surfaceWidthMeters": max(
136
+ 0.5, WALL_HEIGHT_PRIOR_METERS * quad_width / max(quad_height, 1.0)
137
+ ),
138
+ "surfaceHeightMeters": WALL_HEIGHT_PRIOR_METERS,
139
  "metersPerUnit": None,
140
  "cameraIntrinsics": None,
141
  "camera": {"focalLength": float(max(h, w) * 0.95), "horizonY": y1, "confidence": 0.45},
test_debug_overlays.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Regression checks for debug overlays fed maps that are not full resolution.
2
+
3
+ `build_fast_shadow_lighting_maps` caps its shade map at
4
+ FAST_SHADOW_MAX_DIMENSION, but the pipeline still holds the full-resolution
5
+ surface mask and hands both to `record_lighting`. Before this was handled the
6
+ in-place `finite &= mask` raised
7
+
8
+ operands could not be broadcast together with
9
+ shapes (640,482) (1280,963) (640,482)
10
+
11
+ which failed *every* conversion whenever debug artifacts were enabled --
12
+ including the default, since DEBUG_ARTIFACTS_ENABLED defaults to "1" and only
13
+ the gpu and hf profiles turn it off.
14
+ """
15
+
16
+ import unittest
17
+
18
+ import numpy as np
19
+
20
+ from services.debug.overlays import debug_scalar_map
21
+
22
+
23
+ class DebugScalarMapTests(unittest.TestCase):
24
+ def test_accepts_a_mask_larger_than_the_map(self):
25
+ values = np.linspace(0.4, 1.2, 640 * 482, dtype=np.float32).reshape(640, 482)
26
+ mask = np.zeros((1280, 963), dtype=np.uint8)
27
+ mask[400:1200, 100:900] = 1
28
+
29
+ output = debug_scalar_map(values, mask)
30
+
31
+ # The overlay follows the map it is visualising, not the mask.
32
+ self.assertEqual(output.shape, (640, 482, 3))
33
+
34
+ def test_still_blanks_pixels_outside_the_surface(self):
35
+ # A mask covering only the top half must still black out the bottom
36
+ # half after being resized down onto the map.
37
+ values = np.full((64, 48), 1.0, dtype=np.float32)
38
+ values[:, 0] = 0.2 # give the percentile range something to work with
39
+ mask = np.zeros((128, 96), dtype=np.uint8)
40
+ mask[:64, :] = 1
41
+
42
+ output = debug_scalar_map(values, mask)
43
+
44
+ self.assertTrue((output[-1] == 0).all(), "bottom row should be outside the mask")
45
+ self.assertFalse((output[0] == 0).all(), "top row should be inside the mask")
46
+
47
+ def test_matching_shapes_are_unchanged(self):
48
+ values = np.linspace(0.0, 1.0, 32 * 32, dtype=np.float32).reshape(32, 32)
49
+ mask = np.ones((32, 32), dtype=np.uint8)
50
+
51
+ output = debug_scalar_map(values, mask)
52
+
53
+ self.assertEqual(output.shape, (32, 32, 3))
54
+
55
+ def test_no_mask_is_still_allowed(self):
56
+ values = np.linspace(0.0, 1.0, 16 * 16, dtype=np.float32).reshape(16, 16)
57
+
58
+ output = debug_scalar_map(values, None)
59
+
60
+ self.assertEqual(output.shape, (16, 16, 3))
61
+
62
+
63
+ if __name__ == "__main__":
64
+ unittest.main()
test_debug_stages.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Regression checks for debug recording when a stage did not run.
2
+
3
+ Debug capture is diagnostics. It must never be the thing that fails a
4
+ conversion -- the same lesson as the shade-map/mask shape mismatch in
5
+ services/debug/overlays.py.
6
+
7
+ record_walls is reached whenever debug artifacts are enabled, but wall
8
+ discovery only runs when ENABLE_WALL_SEGMENTS is on, so the protected mask
9
+ it is handed is None on any run with walls switched off. That combination is
10
+ not exotic: DEBUG_ARTIFACTS_ENABLED defaults to "1", and turning walls off is
11
+ the documented way to back the feature out, so the rollback switch was the
12
+ thing that crashed.
13
+ """
14
+
15
+ import unittest
16
+
17
+ import numpy as np
18
+
19
+ from services.pipeline.debug_stages import record_walls
20
+
21
+
22
+ class _FakeCapture:
23
+ """Records what would have been written, without touching disk."""
24
+
25
+ def __init__(self):
26
+ self.calls = []
27
+
28
+ def record_images(self, stage_id, title, description, images, metrics=None, elapsed_ms=None):
29
+ self.calls.append({
30
+ "stage_id": stage_id,
31
+ "images": images,
32
+ "metrics": metrics or {},
33
+ })
34
+
35
+
36
+ class RecordWallsTests(unittest.TestCase):
37
+ def setUp(self):
38
+ self.image = np.zeros((40, 60, 3), dtype=np.uint8)
39
+ self.wall_mask = np.zeros((40, 60), dtype=np.uint8)
40
+ self.wall_mask[5:20, 5:30] = 1
41
+
42
+ def test_survives_a_missing_protected_mask(self):
43
+ # Walls disabled: the pipeline never produced a protected mask.
44
+ capture = _FakeCapture()
45
+
46
+ record_walls(capture, self.image, self.wall_mask, None, [], [], 1.0)
47
+
48
+ self.assertEqual(len(capture.calls), 1)
49
+ self.assertEqual(capture.calls[0]["metrics"]["protectedPixels"], 0)
50
+
51
+ def test_records_the_protected_mask_when_there_is_one(self):
52
+ capture = _FakeCapture()
53
+ protected = np.zeros((40, 60), dtype=np.uint8)
54
+ protected[6:10, 6:10] = 1
55
+
56
+ record_walls(capture, self.image, self.wall_mask, protected, [], [], 1.0)
57
+
58
+ self.assertEqual(capture.calls[0]["metrics"]["protectedPixels"], 16)
59
+
60
+ def test_counts_components_and_segments(self):
61
+ capture = _FakeCapture()
62
+ protected = np.zeros((40, 60), dtype=np.uint8)
63
+ component = np.zeros((40, 60), dtype=np.uint8)
64
+ component[5:15, 5:15] = 1
65
+
66
+ record_walls(
67
+ capture, self.image, self.wall_mask, protected,
68
+ [(100, component)], [{"plane": None, "metadata": {}}], 1.0,
69
+ )
70
+
71
+ metrics = capture.calls[0]["metrics"]
72
+ self.assertEqual(metrics["componentCount"], 1)
73
+ self.assertEqual(metrics["componentPixels"], [100])
74
+ self.assertEqual(metrics["acceptedWallSegments"], 1)
75
+
76
+
77
+ if __name__ == "__main__":
78
+ unittest.main()
test_floor_uv_coverage.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Regression checks for floor per-pixel UV coverage.
2
+
3
+ A floor whose depth is noisy in a small minority of pixels must still ship
4
+ per-pixel UV. Discarding the whole mapping over a couple of percent drops the
5
+ floor onto the regularized-plane homography, whose quad is a straight-edged
6
+ trapezoid: it under-covers the mask at the corners and cannot follow the real
7
+ floor boundary.
8
+ """
9
+
10
+ import unittest
11
+ from unittest import mock
12
+
13
+ import numpy as np
14
+
15
+ from services.geometry import multi_plane
16
+ from services.geometry.uv_mapping import build_surface_uv_mapping
17
+
18
+ HEIGHT, WIDTH = 200, 260
19
+ FX = FY = 300.0
20
+ CX, CY = 130.0, 100.0
21
+ CAMERA_HEIGHT = 1.5
22
+ CY_START = 150 # far enough below the horizon to avoid grazing-angle UV strides
23
+
24
+
25
+ def _floor_scene(off_plane_pixels: int, off_plane_offset: float = 0.30):
26
+ """A planar floor seen from a camera, with a minority of off-plane pixels.
27
+
28
+ Returns (surface_mask, surface_indices, geometry). The off-plane pixels are
29
+ finite and in front of the camera, so they reach plane assignment and are
30
+ rejected there for distance -- which is how real depth noise behaves.
31
+ """
32
+ rows, cols = np.mgrid[0:HEIGHT, 0:WIDTH].astype(np.float32)
33
+ ray = np.stack(((cols - CX) / FX, (rows - CY) / FY, np.ones_like(cols)), axis=2)
34
+
35
+ # Only rows below the principal point look at the floor.
36
+ ray_y = np.clip(ray[:, :, 1], 1e-3, None)
37
+ distance = (CAMERA_HEIGHT / ray_y).astype(np.float32)
38
+ points = (ray * distance[:, :, None]).astype(np.float32)
39
+
40
+ mask = np.zeros((HEIGHT, WIDTH), dtype=np.uint8)
41
+ mask[CY_START:HEIGHT, 10:WIDTH - 10] = 1
42
+
43
+ normals = np.zeros((HEIGHT, WIDTH, 3), dtype=np.float32)
44
+ normals[:, :, 1] = -1.0 # floor faces up, toward the camera
45
+
46
+ # Displace a scattered minority along the plane normal, far enough to fail
47
+ # the assignment distance limit but too few to attract a plane of their own.
48
+ flat = np.flatnonzero(mask)
49
+ generator = np.random.default_rng(7)
50
+ noisy = generator.choice(flat, size=off_plane_pixels, replace=False)
51
+ noisy_rows, noisy_cols = np.unravel_index(noisy, (HEIGHT, WIDTH))
52
+ points[noisy_rows, noisy_cols, 1] -= off_plane_offset
53
+
54
+ geometry = {
55
+ "points": points,
56
+ "normals": normals,
57
+ "validMask": np.ones((HEIGHT, WIDTH), dtype=bool),
58
+ "intrinsics": np.array([[FX, 0.0, CX], [0.0, FY, CY], [0.0, 0.0, 1.0]], dtype=np.float32),
59
+ "provider": "moge-2",
60
+ }
61
+ return mask, np.flatnonzero(mask).astype(np.uint32), geometry
62
+
63
+
64
+
65
+ class FloorUvCoverageTests(unittest.TestCase):
66
+ def test_floor_keeps_per_pixel_uv_despite_a_noisy_minority(self):
67
+ """The whole mapping must not be discarded over a few percent of pixels.
68
+
69
+ Without the ray-plane fill the off-plane pixels keep NaN UV, coverage
70
+ lands near 0.96, and the 0.995 floor gate rejects the mapping outright.
71
+ """
72
+ mask, indices, geometry = _floor_scene(off_plane_pixels=800)
73
+
74
+ mapping = build_surface_uv_mapping(mask, indices, geometry)
75
+
76
+ self.assertIsNotNone(mapping, "expected a mapping for a clean planar floor")
77
+ metadata = mapping["metadata"]
78
+ self.assertGreater(
79
+ metadata["surfaceUvRejectedByPlaneDistance"], 0,
80
+ "test scene should actually exercise distance rejection",
81
+ )
82
+ self.assertEqual(
83
+ metadata["surfaceUvCoverage"], 1.0,
84
+ f"every surface pixel should carry a UV, got {metadata['surfaceUvCoverage']}",
85
+ )
86
+ self.assertTrue(
87
+ mapping["useSurfaceUv"],
88
+ f"floor fell back to {metadata['textureMappingMode']} "
89
+ f"({metadata['textureMappingReason']})",
90
+ )
91
+
92
+ def test_a_clean_floor_still_maps(self):
93
+ """Guards against the fill masking a regression on the easy case."""
94
+ mask, indices, geometry = _floor_scene(off_plane_pixels=0)
95
+
96
+ mapping = build_surface_uv_mapping(mask, indices, geometry)
97
+
98
+ self.assertIsNotNone(mapping)
99
+ self.assertTrue(mapping["useSurfaceUv"])
100
+ self.assertEqual(mapping["metadata"]["surfaceUvCoverage"], 1.0)
101
+
102
+ def test_raising_max_planes_does_not_split_a_flat_floor(self):
103
+ """max_planes went 1 -> 5 to let walls split; the floor must not notice.
104
+
105
+ The cap is shared: it bounds RANSAC for every surface, not just walls.
106
+ Raising it gives a floor room to be fitted as several planes, and a
107
+ flat floor broken into two would tile with a seam across it. A planar
108
+ floor must still come back as exactly one plane, and produce the same
109
+ mapping it did under the old cap of 1.
110
+ """
111
+ mask, indices, geometry = _floor_scene(off_plane_pixels=0)
112
+
113
+ at_five = build_surface_uv_mapping(mask, indices, geometry)
114
+ self.assertEqual(
115
+ at_five["metadata"]["surfaceUvAssignedPlaneCount"], 1,
116
+ "a flat floor was split into multiple planes once the cap was raised",
117
+ )
118
+
119
+ with mock.patch.object(multi_plane, "SURFACE_MAX_PLANES", 1):
120
+ at_one = build_surface_uv_mapping(mask, indices, geometry)
121
+
122
+ self.assertEqual(at_one["useSurfaceUv"], at_five["useSurfaceUv"])
123
+ self.assertEqual(
124
+ at_one["metadata"]["surfaceUvCoverage"],
125
+ at_five["metadata"]["surfaceUvCoverage"],
126
+ "raising the cap changed floor UV coverage",
127
+ )
128
+ self.assertTrue(
129
+ np.allclose(at_one["uv"], at_five["uv"], equal_nan=True),
130
+ "raising the cap moved the floor's texture coordinates",
131
+ )
132
+
133
+
134
+ if __name__ == "__main__":
135
+ unittest.main()
test_wall_lighting_gate.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Checks that wall lighting can actually be switched off.
2
+
3
+ The floor's lighting runs behind a three-way cascade of flags. Walls bypassed
4
+ it entirely: `builder._compute_wall_lighting` submitted
5
+ `build_luminance_lighting_maps` for every wall component unconditionally, and
6
+ `build_wall_segment` computed the same maps inline whenever none were handed
7
+ to it. So with every lighting flag off, walls were still lit -- 0.63s of a
8
+ 5.67s conversion on the GPU box, and no way to stop it.
9
+
10
+ Note the second half: gating only the pre-compute would have moved the work
11
+ into the packaging phase rather than removing it, and serially at that. The
12
+ switch has to reach `build_wall_segment` itself, which is what these pin.
13
+ """
14
+
15
+ import unittest
16
+
17
+ import numpy as np
18
+
19
+ from services.pipeline.bundle_assembly import build_wall_segment
20
+
21
+ HEIGHT, WIDTH = 200, 260
22
+ MODELS = {"segmentation": {"name": "test-segmenter"}}
23
+
24
+
25
+ def _lit_room() -> np.ndarray:
26
+ """A textured image, so luminance lighting has something to find.
27
+
28
+ A flat image can yield a degenerate shade map, which would make the
29
+ "lighting on" guard below pass for the wrong reason.
30
+ """
31
+ rows, cols = np.mgrid[0:HEIGHT, 0:WIDTH].astype(np.float32)
32
+ gradient = 40 + 170 * (cols / WIDTH) * (0.4 + 0.6 * (rows / HEIGHT))
33
+ image = np.stack([gradient, gradient * 0.9, gradient * 0.8], axis=2)
34
+ return np.clip(image, 0, 255).astype(np.uint8)
35
+
36
+
37
+ def _wall_mask() -> np.ndarray:
38
+ mask = np.zeros((HEIGHT, WIDTH), dtype=np.uint8)
39
+ mask[20:180, 20:WIDTH - 20] = 1
40
+ return mask
41
+
42
+
43
+ def _geometry() -> dict:
44
+ """Enough for the plane fit to be attempted and decline harmlessly."""
45
+ return {"points": None, "validMask": None, "normals": None, "intrinsics": None}
46
+
47
+
48
+ def _build(**overrides):
49
+ kwargs = {
50
+ "wall_index": 0,
51
+ "component_mask": _wall_mask(),
52
+ "wall_protected_mask": np.zeros((HEIGHT, WIDTH), dtype=np.uint8),
53
+ "geometry": _geometry(),
54
+ "img_np": _lit_room(),
55
+ "wall_components": [None],
56
+ "models": MODELS,
57
+ "precomputed_lighting": None,
58
+ }
59
+ kwargs.update(overrides)
60
+ return build_wall_segment(**kwargs)
61
+
62
+
63
+ class WallLightingGateTest(unittest.TestCase):
64
+ def test_lighting_is_computed_inline_when_enabled(self):
65
+ """Guard: proves the assertion below can tell the two apart."""
66
+ segment = _build(lighting_enabled=True)
67
+
68
+ self.assertIsNotNone(segment)
69
+ self.assertIsNotNone(segment["shadeMap"])
70
+ self.assertTrue(segment["metadata"]["shadingEnabled"])
71
+
72
+ def test_no_lighting_maps_are_produced_when_disabled(self):
73
+ segment = _build(lighting_enabled=False)
74
+
75
+ self.assertIsNotNone(segment)
76
+ self.assertIsNone(segment["shadeMap"])
77
+ self.assertIsNone(segment["showroomShadeMap"])
78
+ self.assertIsNone(segment["reflectionMap"])
79
+ self.assertFalse(segment["metadata"]["shadingEnabled"])
80
+
81
+ def test_disabling_beats_precomputed_maps(self):
82
+ """The flag must win, so a stale pre-compute cannot leak lighting back."""
83
+ segment = _build(
84
+ lighting_enabled=False,
85
+ precomputed_lighting={"shadeMap": np.ones((HEIGHT, WIDTH), dtype=np.uint8)},
86
+ )
87
+
88
+ self.assertIsNotNone(segment)
89
+ self.assertIsNone(segment["shadeMap"])
90
+
91
+ def test_lighting_defaults_to_on(self):
92
+ """Omitting the flag must not silently darken production."""
93
+ segment = _build()
94
+
95
+ self.assertIsNotNone(segment)
96
+ self.assertIsNotNone(segment["shadeMap"])
97
+
98
+
99
+ if __name__ == "__main__":
100
+ unittest.main()
visualizer.gpu.toml CHANGED
@@ -17,7 +17,7 @@ enable_depth_estimation = true
17
  enable_moge_geometry = true
18
  enable_plane_fit = true
19
  enable_multi_plane_surfaces = true
20
- enable_wall_segments = false
21
  enable_intrinsic_shading = false
22
  enable_shading_transfer = false
23
  enable_fast_shadow_transfer = true
@@ -34,7 +34,7 @@ data_dir = "data"
34
 
35
  [surface_mapping]
36
  ransac_distance_threshold = 0.04
37
- max_planes = 1
38
  normal_angle_threshold_degrees = 35
39
  normal_smoothing_kernel = 5
40
  min_plane_pixels = 1500
 
17
  enable_moge_geometry = true
18
  enable_plane_fit = true
19
  enable_multi_plane_surfaces = true
20
+ enable_wall_segments = true
21
  enable_intrinsic_shading = false
22
  enable_shading_transfer = false
23
  enable_fast_shadow_transfer = true
 
34
 
35
  [surface_mapping]
36
  ransac_distance_threshold = 0.04
37
+ max_planes = 5
38
  normal_angle_threshold_degrees = 35
39
  normal_smoothing_kernel = 5
40
  min_plane_pixels = 1500
visualizer.hf.toml CHANGED
@@ -17,7 +17,7 @@ enable_depth_estimation = true
17
  enable_moge_geometry = true
18
  enable_plane_fit = true
19
  enable_multi_plane_surfaces = true
20
- enable_wall_segments = false
21
  enable_intrinsic_shading = false
22
  enable_shading_transfer = false
23
  enable_fast_shadow_transfer = true
@@ -31,7 +31,7 @@ data_dir = "data"
31
 
32
  [surface_mapping]
33
  ransac_distance_threshold = 0.04
34
- max_planes = 1
35
  normal_angle_threshold_degrees = 35
36
  normal_smoothing_kernel = 5
37
  min_plane_pixels = 1500
 
17
  enable_moge_geometry = true
18
  enable_plane_fit = true
19
  enable_multi_plane_surfaces = true
20
+ enable_wall_segments = true
21
  enable_intrinsic_shading = false
22
  enable_shading_transfer = false
23
  enable_fast_shadow_transfer = true
 
31
 
32
  [surface_mapping]
33
  ransac_distance_threshold = 0.04
34
+ max_planes = 5
35
  normal_angle_threshold_degrees = 35
36
  normal_smoothing_kernel = 5
37
  min_plane_pixels = 1500
visualizer.local.toml CHANGED
@@ -13,7 +13,7 @@ sam2_checkpoint = ""
13
  enable_depth_estimation = false
14
  enable_plane_fit = true
15
  enable_multi_plane_surfaces = true
16
- enable_wall_segments = false
17
  enable_intrinsic_shading = false
18
  enable_shading_transfer = false
19
  enable_fast_shadow_transfer = true
 
13
  enable_depth_estimation = false
14
  enable_plane_fit = true
15
  enable_multi_plane_surfaces = true
16
+ enable_wall_segments = true
17
  enable_intrinsic_shading = false
18
  enable_shading_transfer = false
19
  enable_fast_shadow_transfer = true