"""Segment dict construction for the visualization bundle.""" from __future__ import annotations import numpy as np from config.lighting import ( LIGHTING_TRANSFER_VERSION, REFLECTION_MAP_MAX, REFLECTION_MAP_MIN, SHADE_MAP_ENCODING, SHADE_MAP_MAX, SHADE_MAP_MIN, SHOWROOM_SHADE_MAP_MAX, SHOWROOM_SHADE_MAP_MIN, ) from config.runtime import ( ENABLE_FAST_SHADOW_TRANSFER, ENABLE_MULTI_PLANE_SURFACES, ENABLE_PLANE_FIT, ENABLE_SAM_REFINEMENT, ENABLE_SHADING_TRANSFER, ) from config.surface import SURFACE_UV_WALL_MIN_COVERAGE from models.segmentation import segmenter_metadata_name from state import class_ids, class_name_for_id from services.geometry.uv_mapping import build_surface_uv_mapping from services.lighting.shading import build_luminance_lighting_maps from services.wall.plane import estimate_wall_plane from enums import SurfaceType, TextureMappingMode from utils import encode_b64 def build_floor_segment( *, surface_indices: np.ndarray, occlusion_indices: np.ndarray, homography, plane: dict | None, surface_mapping: dict | None, use_surface_uv: bool, shade_map: np.ndarray | None, showroom_shade_map: np.ndarray | None, reflection_map: np.ndarray | None, floor_mask: np.ndarray, surface_mask: np.ndarray, replaced_material_mask: np.ndarray, occlusion_mask: np.ndarray, floor_direction: dict, sam_metadata: dict, edge_metadata: dict, mapping_metadata: dict, shade_statistics: dict | None, lighting_source: str | None, intrinsic_lighting_used: bool, models: dict, depth, geometry: dict, ) -> dict: return { "id": 0, "className": SurfaceType.FLOOR, "mask": encode_b64(surface_indices), "occlusionMask": encode_b64(occlusion_indices) if len(occlusion_indices) else None, "homography": homography, "floorTransform": plane.get("floorTransform") if plane else None, "plane": plane, # Pass raw numpy arrays for lazy assets — packaging writes them directly # to disk, avoiding the costly base64 encode/decode round-trip. "surfaceUv": ( surface_mapping["uv"].astype(np.float32) if use_surface_uv else None ), "surfacePlaneIds": ( surface_mapping["planeIds"].astype(np.uint8) if use_surface_uv else None ), "surfacePlanes": surface_mapping["planes"] if surface_mapping is not None else None, "shadeMap": shade_map, "showroomShadeMap": showroom_shade_map, "reflectionMap": reflection_map, "metadata": { "segmenter": segmenter_metadata_name(), "segmentationModel": models["segmentation"]["name"], "floorPixels": int(floor_mask.sum()), "surfacePixels": int(surface_mask.sum()), "replacedSoftFloorPixels": int(replaced_material_mask.sum()), "occlusionPixels": int(occlusion_mask.sum()), "floorDirection": floor_direction, **sam_metadata, **edge_metadata, **mapping_metadata, "depthEnabled": depth is not None, "shadingEnabled": shade_map is not None, "planeFitEnabled": ENABLE_PLANE_FIT, "multiPlaneSurfacesEnabled": ENABLE_MULTI_PLANE_SURFACES, "multiPlaneSurfaceCount": len(surface_mapping["planes"]) if surface_mapping is not None else 0, "multiPlaneNormalsReliable": ( bool(surface_mapping.get("normalsReliable")) if surface_mapping is not None else False ), "multiPlaneFitModes": ( [p.get("fitMode") for p in surface_mapping["planes"]] if surface_mapping is not None else [] ), "shadingTransferEnabled": ENABLE_SHADING_TRANSFER or ENABLE_FAST_SHADOW_TRANSFER, "fastShadowTransferEnabled": ENABLE_FAST_SHADOW_TRANSFER, "lightingSource": lighting_source, "lightingTransferVersion": LIGHTING_TRANSFER_VERSION, "shadeMapEncoding": SHADE_MAP_ENCODING, "shadeMapStatistics": shade_statistics, "shadeMapRange": [SHADE_MAP_MIN, SHADE_MAP_MAX], "shadeMapSize": ( [int(shade_map.shape[1]), int(shade_map.shape[0])] if shade_map is not None else None ), "showroomShadeMapRange": [SHOWROOM_SHADE_MAP_MIN, SHOWROOM_SHADE_MAP_MAX], "renderPresetDefaults": { "preset": "realistic", "shadingStrength": 0.30, "reflectionTransfer": True, "edgeFeatherPixels": 2, }, "reflectionTransferEnabled": reflection_map is not None, "reflectionMapRange": [REFLECTION_MAP_MIN, REFLECTION_MAP_MAX], "geometryConfidence": plane.get("geometryConfidence", 0.0) if plane else 0.0, "metricGeometry": bool(plane and plane.get("floorTransform")), "geometryProvider": ( plane.get("geometryProvider", geometry.get("provider")) if plane else geometry.get("provider") ), "geometryModel": models["geometry"]["name"], }, } def build_wall_segment( wall_index: int, component_mask: np.ndarray, wall_protected_mask: np.ndarray, geometry: dict, img_np: np.ndarray, wall_components: list, models: dict, precomputed_lighting: dict | None = None, up_vector=None, ) -> dict | None: wall_homography, wall_plane = estimate_wall_plane(component_mask, geometry) if wall_homography is None or wall_plane is None: return None wall_lighting_maps = precomputed_lighting if precomputed_lighting is not None else build_luminance_lighting_maps(img_np, component_mask) wall_indices = np.flatnonzero(component_mask.ravel()).astype(np.uint32) # Only objects sitting on *this* wall occlude it. Shipping the global # protected mask made every wall claim every mirror, cabinet and door in the # room, so the renderer punched other walls' furniture through this one. # Intersecting with the component also excludes barrier classes for free, # because a refined component never contains them. wall_occlusion_mask = (wall_protected_mask > 0) & (component_mask > 0) wall_occlusion_indices = np.flatnonzero(wall_occlusion_mask.ravel()).astype(np.uint32) # Per-pixel UV, exactly as the floor gets it. Walls previously shipped a # single homography, so tile scale came from the wall's bounding box rather # than from measured geometry. mark_floor=False keeps the UV basis # gravity-aligned: v runs up the wall, u runs along it. wall_mapping = build_surface_uv_mapping( component_mask, wall_indices, geometry, mark_floor=False, min_coverage=SURFACE_UV_WALL_MIN_COVERAGE, fill_missing_from_plane=True, # True vertical, taken from the floor. Geometry providers work in # camera coordinates, so assuming +Y is up rotates every wall's tile # grid by the camera's tilt. vertical_ref=up_vector, ) use_wall_uv = bool(wall_mapping and wall_mapping.get("useSurfaceUv")) wall_mapping_metadata = wall_mapping["metadata"] if wall_mapping is not None else {} wall_shade_map = wall_lighting_maps.get("shadeMap") if wall_lighting_maps else None wall_showroom = wall_lighting_maps.get("showroomShadeMap") if wall_lighting_maps else None wall_reflection = wall_lighting_maps.get("reflectionMap") if wall_lighting_maps else None return { "id": wall_index + 1, "className": SurfaceType.WALL, "surfaceType": SurfaceType.WALL, "mask": encode_b64(wall_indices), "occlusionMask": encode_b64(wall_occlusion_indices) if len(wall_occlusion_indices) else None, "homography": wall_homography, "floorTransform": wall_plane.get("floorTransform"), "surfaceTransform": wall_plane.get("surfaceTransform"), "plane": wall_plane, # Raw numpy arrays; packaging writes them straight to disk as lazy assets. "surfaceUv": wall_mapping["uv"].astype(np.float32) if use_wall_uv else None, "surfacePlaneIds": wall_mapping["planeIds"].astype(np.uint8) if use_wall_uv else None, "surfacePlanes": wall_mapping["planes"] if wall_mapping is not None else None, "shadeMap": wall_shade_map, "showroomShadeMap": wall_showroom, "reflectionMap": wall_reflection, "metadata": { "segmenter": segmenter_metadata_name(), "segmentationModel": models["segmentation"]["name"], "wallPixels": int(component_mask.sum()), "wallComponent": wall_index, "wallComponentCount": len(wall_components), "protectedPixels": int(wall_occlusion_mask.sum()), "shadingEnabled": wall_shade_map is not None, "reflectionTransferEnabled": wall_reflection is not None, # Spread first so the explicit mode below wins: the UV analyzer # reports REGULARIZED_FLOOR_PLANE when it declines, which is not a # meaningful value for a wall. **wall_mapping_metadata, "surfaceUvEnabled": use_wall_uv, "textureMappingMode": ( TextureMappingMode.SURFACE_UV if use_wall_uv else TextureMappingMode.WALL_PLANE if wall_plane.get("surfaceTransform") else TextureMappingMode.WALL_CONTOUR_HOMOGRAPHY ), "geometryConfidence": wall_plane.get("geometryConfidence", 0.0), "geometryProvider": wall_plane.get("geometryProvider"), "surfaceWidthMeters": wall_plane.get("surfaceWidthMeters"), "surfaceHeightMeters": wall_plane.get("surfaceHeightMeters"), "lightingTransferVersion": LIGHTING_TRANSFER_VERSION, "shadeMapEncoding": SHADE_MAP_ENCODING, "shadeMapRange": [SHADE_MAP_MIN, SHADE_MAP_MAX], "showroomShadeMapRange": [SHOWROOM_SHADE_MAP_MIN, SHOWROOM_SHADE_MAP_MAX], "reflectionMapRange": [REFLECTION_MAP_MIN, REFLECTION_MAP_MAX], }, } def build_fallback_segments( seg_map: np.ndarray, depth, models: dict, ) -> list[dict]: segments = [] flat_seg = seg_map.ravel() for seg_id, class_id in enumerate(np.unique(flat_seg)): indices = np.where(flat_seg == class_id)[0].astype(np.uint32) if len(indices) < 1000: continue segments.append({ "id": int(seg_id), "className": class_name_for_id(int(class_id)), "mask": encode_b64(indices), "homography": None, "plane": None, "shadeMap": None, "showroomShadeMap": None, "reflectionMap": None, "metadata": { "segmenter": segmenter_metadata_name(), "segmentationModel": models["segmentation"]["name"], "depthEnabled": depth is not None, "shadingEnabled": False, "planeFitEnabled": ENABLE_PLANE_FIT, "samRefinementEnabled": ENABLE_SAM_REFINEMENT, "shadingTransferEnabled": ENABLE_SHADING_TRANSFER, "reflectionTransferEnabled": False, }, }) return segments