"""Wall stage of the conversion pipeline: one bundle segment per physical wall. Functions --------- build_wall_segments - discover walls and build their bundle segments Designed to run in a background thread alongside the floor stages: all analysis is at working resolution, and full-resolution work is limited to each wall's own pixels (mask upscale, index encoding). Each wall's texture mapping is an exact 3x3 plane transform, so no per-pixel UV is shipped. """ from __future__ import annotations import time from dataclasses import dataclass, field, replace import cv2 import numpy as np from config.runtime import ENABLE_FAST_SHADOW_TRANSFER, ENABLE_SHADING_TRANSFER from config.surface import WALL_UV_MIN_COVERAGE from services.geometry.camera import backproject_depth, pixel_intrinsics_from_model from services.geometry.plane_uv import plane_to_image_transform, ray_plane_uv, upright_plane_basis from services.lighting.shading import build_fast_shadow_lighting_maps, build_luminance_lighting_maps from services.pipeline.bundle_assembly import build_wall_segment from services.wall.components import WallComponent, WallDiscovery, discover_wall_components from services.wall.edges import matte_wall_decor from services.wall.plane import estimate_wall_plane # Wall pixels at least this covered (of 255) count as pure wall when measuring its light. PURE_WALL_ALPHA = 230 # Pixels sampled per wall to measure plane coverage and size. MAPPING_SAMPLE_PIXELS = 20000 @dataclass class WallResult: segments: list[dict] = field(default_factory=list) timings_ms: dict[str, float] = field(default_factory=dict) @property def detail(self) -> str: parts = [f"walls={len(self.segments)}"] parts += [f"{name}={ms:.0f}ms" for name, ms in self.timings_ms.items()] return " ".join(parts) def build_wall_segments( img_np: np.ndarray, seg_map: np.ndarray, geometry: dict | None, min_area: int, segmentation_model: str, first_segment_id: int = 1, ) -> WallResult: """Discover walls and return their bundle segments (ids start at first_segment_id).""" result = WallResult() started = time.perf_counter() discovery = discover_wall_components(seg_map, geometry, min_area) result.timings_ms["discovery"] = (time.perf_counter() - started) * 1000 if not discovery.components: return result started = time.perf_counter() full_h, full_w = seg_map.shape[:2] intrinsics = ( pixel_intrinsics_from_model(geometry.get("intrinsics"), full_w, full_h) if geometry is not None else None ) work_h, work_w = discovery.components[0].work_mask.shape[:2] work_image = cv2.resize(img_np, (work_w, work_h), interpolation=cv2.INTER_AREA) for index, component in enumerate(discovery.components): segment = _build_segment( component, discovery, index=index, segment_id=first_segment_id + index, intrinsics=intrinsics, geometry=geometry, img_np=img_np, seg_map=seg_map, work_image=work_image, segmentation_model=segmentation_model, ) if segment is not None: result.segments.append(segment) for segment in result.segments: segment["metadata"]["wallComponentCount"] = len(result.segments) result.timings_ms["segments"] = (time.perf_counter() - started) * 1000 return result def _build_segment( component: WallComponent, discovery: WallDiscovery, *, index: int, segment_id: int, intrinsics: np.ndarray | None, geometry: dict | None, img_np: np.ndarray, seg_map: np.ndarray, work_image: np.ndarray, segmentation_model: str, ) -> dict | None: # Wallpaper between the stems of flowers and plants in front of the wall. points = _full_points(geometry, intrinsics, component.mask.shape) mask, alpha = matte_wall_decor(img_np, seg_map, component.mask, points, component.plane) if alpha is not None: component = replace(component, mask=mask, area=int(mask.sum())) wall_indices = np.flatnonzero(component.mask.ravel()).astype(np.uint32) mapping = _wall_plane_mapping(component, discovery.vertical, wall_indices, intrinsics) # With an exact plane mapping, skip estimate_wall_plane's second RANSAC fit # and keep only its cheap contour quad as a fallback homography. homography, plane = estimate_wall_plane(component.mask, None if mapping else geometry) if homography is None or plane is None: return None if mapping: plane.update(mapping) plane["geometryProvider"] = (geometry or {}).get("provider") return build_wall_segment( wall_id=segment_id, wall_index=index, wall_indices=wall_indices, homography=homography, plane=plane, lighting_maps=_wall_lighting(component, img_np, work_image, alpha), segmentation_model=segmentation_model, edge_alpha=alpha.ravel()[wall_indices] if alpha is not None else None, ) def _full_points(geometry: dict | None, intrinsics: np.ndarray | None, shape: tuple[int, int]) -> np.ndarray | None: """Camera-space 3D point per pixel (the frame the wall planes were fitted in), or None.""" if geometry is None: return None points = geometry.get("points") if points is not None and points.shape[:2] == shape: return points depth = geometry.get("depth") if depth is None or intrinsics is None or depth.shape[:2] != shape: return None return backproject_depth(depth.astype(np.float32), intrinsics) def _wall_plane_mapping( component: WallComponent, vertical: np.ndarray, wall_indices: np.ndarray, intrinsics: np.ndarray | None, ) -> dict | None: """Exact metric plane mapping for the wall, or None to use the contour homography. Coverage and the wall's size in metres are measured on a pixel sample; the renderer gets the 3x3 surfaceTransform, which is exact for every pixel. """ if component.plane is None or intrinsics is None or not len(wall_indices): return None u_axis, v_axis = upright_plane_basis(component.plane.normal, vertical) sample = wall_indices[:: max(1, len(wall_indices) // MAPPING_SAMPLE_PIXELS)] uv, hit = ray_plane_uv( sample, component.mask.shape[1], intrinsics, component.plane.origin, component.plane.normal, u_axis, v_axis, ) coverage = float(hit.mean()) if coverage < WALL_UV_MIN_COVERAGE: return None uv_min = np.nanmin(uv, axis=0) uv_max = np.nanmax(uv, axis=0) top_v, up_sign = wall_top(uv[:, 1], sample // component.mask.shape[1]) transform = plane_to_image_transform( intrinsics, component.plane.origin, component.plane.normal, u_axis, v_axis, ).flatten().tolist() return { "floorTransform": transform, "surfaceTransform": transform, "surfaceUAxis": u_axis.astype(float).tolist(), "surfaceVAxis": v_axis.astype(float).tolist(), "planeNormal": component.plane.normal.astype(float).tolist(), "planeOrigin": component.plane.origin.astype(float).tolist(), "surfaceWidthMeters": float(max(uv_max[0] - uv_min[0], 0.05)), "surfaceHeightMeters": float(max(uv_max[1] - uv_min[1], 0.05)), # Murals hang from here: the plane-v (metres) of the wall's visible top # edge, and whether +v points up (1) or down (-1) on the wall. "wallTopV": top_v, "wallUpSign": up_sign, # The renderer treats the transform as metric at >= 0.35 confidence. "geometryConfidence": coverage, } def wall_top(v: np.ndarray, rows: np.ndarray) -> tuple[float, int]: """The plane-v of the wall's top edge and the sign of "up" along v. v is gravity-aligned (upright_plane_basis), so the top edge is one v value. "Up" is whichever v direction the image rows go up in. A high percentile rather than the extreme keeps stray mask pixels from setting the top. """ valid = np.isfinite(v) v, rows = v[valid].astype(np.float64), rows[valid].astype(np.float64) if len(v) < 2 or float(np.std(rows)) < 1e-6: return float(np.nanmax(v)) if len(v) else 0.0, 1 up_sign = -1 if float(np.corrcoef(rows, v)[0, 1]) > 0 else 1 top = np.percentile(v, 99.5) if up_sign > 0 else np.percentile(v, 0.5) return float(top), up_sign def _wall_lighting( component: WallComponent, img_np: np.ndarray, work_image: np.ndarray, alpha: np.ndarray | None = None, ) -> dict | None: """Same lighting switches as the floor; the fast path runs at working resolution. The light is measured on pure wall only (never on stems or objects the wall shows between) and continues past the wall's edge, so no halo forms there. """ if ENABLE_FAST_SHADOW_TRANSFER: work_h, work_w = work_image.shape[:2] pure = component.mask if alpha is None else (alpha >= PURE_WALL_ALPHA).astype(np.uint8) work_mask = (cv2.resize(pure.astype(np.float32), (work_w, work_h), interpolation=cv2.INTER_AREA) > 0.99) maps = build_fast_shadow_lighting_maps(work_image, work_mask.astype(np.uint8), fill_outside=True) if maps and maps.get("shadeMap") is not None: return maps if ENABLE_SHADING_TRANSFER: return build_luminance_lighting_maps(img_np, component.mask) return None