from __future__ import annotations import numpy as np from enums import PlaneFitMode from config.models import DEPTH_MODEL_NAME from config.runtime import ENABLE_MULTI_PLANE_SURFACES from config.surface import ( SURFACE_MAX_PLANES, SURFACE_MIN_PLANE_PIXELS, SURFACE_NORMAL_ANGLE_DEGREES, SURFACE_NORMAL_SMOOTHING_KERNEL, SURFACE_RANSAC_DISTANCE, ) from services.geometry.camera import ( backproject_depth, pixel_intrinsics_from_model, prepare_depth_for_backprojection, ) from services.geometry.normals import compute_normals_from_points, smooth_normal_map from services.geometry.plane_fitting import plane_basis, surface_distance_threshold from services.geometry.ransac import ransac_surface_plane, ransac_surface_plane_by_distance MIN_SECONDARY_PLANE_RATIO = 0.05 def _prune_weak_secondary_planes(planes: list[dict]) -> list[dict]: if not planes: return [] primary_inliers = max(plane["inlierCount"] for plane in planes) retained_planes = [ plane for plane in planes if plane["inlierCount"] >= primary_inliers * MIN_SECONDARY_PLANE_RATIO ] for plane_id, plane in enumerate(retained_planes): plane["id"] = plane_id return retained_planes def geometry_point_maps(mask: np.ndarray, geometry: dict | None): if not ENABLE_MULTI_PLANE_SURFACES or geometry is None: return None h, w = mask.shape[:2] points = geometry.get("points") point_source = "raw-point-map" valid_mask = geometry.get("validMask") intrinsics = geometry.get("intrinsics") depth_scale = None if points is None: depth = geometry.get("depth") if depth is None: return None provider = geometry.get("provider", "") is_metric_depth = "metric" in DEPTH_MODEL_NAME.lower() or "metric" in provider.lower() depth_for_points, depth_scale = prepare_depth_for_backprojection(depth, mask, is_metric_depth) pixel_intrinsics = pixel_intrinsics_from_model(intrinsics, w, h) points = backproject_depth(depth_for_points, pixel_intrinsics) valid_mask = np.isfinite(depth_for_points) & (depth_for_points > 0.05) point_source = f"{provider or 'depth'}-backprojection" else: points = points.astype(np.float32, copy=False) pixel_intrinsics = pixel_intrinsics_from_model(intrinsics, w, h) if valid_mask is None: valid_mask = np.isfinite(points).all(axis=2) & (points[:, :, 2] > 0.05) valid_mask = valid_mask.astype(bool, copy=False) & np.isfinite(points).all(axis=2) & (points[:, :, 2] > 0.05) print( "[FLOOR_3D_POINTS] point map ready for floor mapping " f"source={point_source} provider={geometry.get('provider')} shape={points.shape} " f"validPixels={int(valid_mask.sum())} floorMaskPixels={int(mask.sum())}", flush=True, ) normals = geometry.get("normals") if normals is None or normals.shape[:2] != mask.shape: normals = compute_normals_from_points(points, valid_mask, SURFACE_NORMAL_SMOOTHING_KERNEL) else: normals = smooth_normal_map(normals.astype(np.float32, copy=False), SURFACE_NORMAL_SMOOTHING_KERNEL) normal_valid_mask = np.isfinite(normals).all(axis=2) & (np.linalg.norm(normals, axis=2) > 1e-4) return { "points": points.astype(np.float32, copy=False), "normals": normals.astype(np.float32, copy=False), "normalValidMask": normal_valid_mask, "validMask": valid_mask, "intrinsics": pixel_intrinsics.astype(np.float32), "depthScale": depth_scale, } def fit_multi_surface_planes(points: np.ndarray, normals: np.ndarray, normals_reliable: bool = True, mark_floor: bool = True, vertical_ref: np.ndarray | None = None): if len(points) < SURFACE_MIN_PLANE_PIXELS: return [] distance_threshold = surface_distance_threshold(points) normal_cos = float(np.cos(np.deg2rad(SURFACE_NORMAL_ANGLE_DEGREES))) rng = np.random.default_rng(29) sample_count = min(len(points), 26000) sample_indices = rng.choice(len(points), size=sample_count, replace=False) remaining = np.ones(len(points), dtype=bool) planes = [] for plane_id in range(SURFACE_MAX_PLANES): candidates = sample_indices[remaining[sample_indices]] if len(candidates) < max(300, SURFACE_MIN_PLANE_PIXELS // 6): break fit_mode = PlaneFitMode.NORMAL_AWARE result = None if normals_reliable: result = ransac_surface_plane( points, normals, candidates, remaining, distance_threshold, normal_cos, ) if result is None: fit_mode = "distance-only" result = ransac_surface_plane_by_distance( points, candidates, remaining, distance_threshold, ) if result is None: break origin, normal, inliers = result inlier_count = int(inliers.sum()) if inlier_count < SURFACE_MIN_PLANE_PIXELS: break planes.append({ "id": plane_id, "origin": origin.astype(np.float32), "normal": normal.astype(np.float32), "offset": float(-origin @ normal), "inlierCount": inlier_count, "fitMode": fit_mode, }) remaining[inliers] = False if int(remaining.sum()) < SURFACE_MIN_PLANE_PIXELS: break if not planes: return [] planes = _prune_weak_secondary_planes(planes) # On a wall-only surface every normal is near-horizontal, so this argmax # would still crown one of them "the floor" and hand it floor-style axes # (an arbitrary horizontal reference) instead of gravity-aligned ones — # tiles on that wall would come out rotated. Callers working a non-floor # surface pass mark_floor=False. floor_id = int(np.argmax([ plane["inlierCount"] * max(0.1, abs(float(plane["normal"][1]))) for plane in planes ])) if mark_floor else -1 for idx, plane in enumerate(planes): plane["isFloor"] = bool(mark_floor and idx == floor_id) u_axis, v_axis = plane_basis(plane["normal"], plane["isFloor"], vertical_ref) plane["uAxis"] = u_axis plane["vAxis"] = v_axis return planes def merge_planes_by_point_consistency( points: np.ndarray, assignment: np.ndarray, planes: list[dict], distance_threshold: float, angle_degrees: float = 20.0, tolerance_scale: float = 1.5, ) -> tuple[np.ndarray, list[dict]]: """Merge planes whose assigned points actually lie on one another's plane. Comparing two fitted planes to each other does not work reliably here. RANSAC peels a plane off, removes its inliers, then fits the *remainder* -- so on a single flat wall the leftover tails produce a plane that is both tilted and offset relative to the first, even though every point involved belongs to the same physical surface. Threshold the plane parameters and you either fail to merge (wall sliced into vertical depth-slab strips) or merge surfaces that are genuinely apart. Measuring the points instead is unambiguous: if plane B's pixels sit within tolerance of plane A, they are the same wall. On a sample living room the two halves of each wall sat 0.018 m and 0.035 m apart, while the protruding chimney breast was 0.155 m from its neighbours -- a clean gap with nothing in between. Returns (remapped_assignment, merged_planes). """ if len(planes) <= 1: return assignment, planes cos_limit = float(np.cos(np.deg2rad(angle_degrees))) limit = float(distance_threshold) * tolerance_scale parent = list(range(len(planes))) def find(index: int) -> int: while parent[index] != index: parent[index] = parent[parent[index]] index = parent[index] return index def offset_of(plane: dict) -> tuple[np.ndarray, float]: normal = np.asarray(plane["normal"], dtype=np.float32) origin = np.asarray(plane["origin"], dtype=np.float32) return normal, float(-origin @ normal) def spread(subject: int, reference: int) -> float: """How far the subject plane's points sit from the reference plane.""" member = points[assignment == subject] if member.size == 0: return float("inf") normal, offset = offset_of(planes[reference]) return float(np.percentile(np.abs(member @ normal + offset), 90)) for a in range(len(planes)): for b in range(a + 1, len(planes)): normal_a = np.asarray(planes[a]["normal"], dtype=np.float32) normal_b = np.asarray(planes[b]["normal"], dtype=np.float32) if abs(float(normal_a @ normal_b)) < cos_limit: continue worst = max(spread(b, a), spread(a, b)) print( f"[PLANE_MERGE] plane {a} vs {b}: " f"angle={np.degrees(np.arccos(min(1.0, abs(float(normal_a @ normal_b))))):.1f}deg " f"p90Distance={worst:.3f}m limit={limit:.3f}m " f"{'MERGE' if worst <= limit else 'keep separate'}", flush=True, ) if worst <= limit: root_a, root_b = find(a), find(b) if root_a != root_b: parent[max(root_a, root_b)] = min(root_a, root_b) roots = sorted({find(index) for index in range(len(planes))}) if len(roots) == len(planes): return assignment, planes remap = {root: new for new, root in enumerate(roots)} merged_assignment = np.full_like(assignment, -1) merged_planes = [] for root in roots: members = [index for index in range(len(planes)) if find(index) == root] # Keep the largest contributor's orientation; it is the best-supported fit. dominant = max(members, key=lambda index: int(planes[index]["inlierCount"])) plane = dict(planes[dominant]) plane["inlierCount"] = sum(int(planes[index]["inlierCount"]) for index in members) plane["id"] = remap[root] merged_planes.append(plane) for index in members: merged_assignment[assignment == index] = remap[root] return merged_assignment, merged_planes def merge_coplanar_planes(planes: list[dict], distance_threshold: float, angle_degrees: float = 15.0, vertical_ref: np.ndarray | None = None) -> list[dict]: """Fuse fitted planes that describe the same physical surface. fit_multi_surface_planes peels planes off one at a time with RANSAC. On a large flat wall with noisy normals — which is what back-projected depth gives you — the first pass often claims only part of the wall and a later pass fits a second, geometrically near-identical plane to the remainder. Left alone that splits one wall into several segments, each with its own transform, so the tile grid breaks visibly at the seam. Raising inference resolution makes it worse, because finer normals give RANSAC more excuses to subdivide: a 1600px run split one living-room wall into three. Two planes are the same surface when their normals are near-parallel and each origin lies within `distance_threshold` of the other's plane. """ if len(planes) <= 1: return planes cos_limit = float(np.cos(np.deg2rad(angle_degrees))) merged: list[dict] = [] for plane in sorted(planes, key=lambda item: -int(item["inlierCount"])): normal = np.asarray(plane["normal"], dtype=np.float64) origin = np.asarray(plane["origin"], dtype=np.float64) target = None for candidate in merged: candidate_normal = np.asarray(candidate["normal"], dtype=np.float64) candidate_origin = np.asarray(candidate["origin"], dtype=np.float64) if abs(float(normal @ candidate_normal)) < cos_limit: continue if abs(float((origin - candidate_origin) @ candidate_normal)) > distance_threshold: continue target = candidate break if target is None: merged.append(dict(plane)) continue # Inlier-weighted average, so the dominant plane keeps its orientation. target_normal = np.asarray(target["normal"], dtype=np.float64) if float(normal @ target_normal) < 0: normal = -normal # opposite-facing fits of one surface weight_a = float(target["inlierCount"]) weight_b = float(plane["inlierCount"]) total = max(weight_a + weight_b, 1.0) fused_normal = (target_normal * weight_a + normal * weight_b) / total norm = float(np.linalg.norm(fused_normal)) if norm > 1e-6: fused_normal /= norm else: fused_normal = target_normal fused_origin = ( np.asarray(target["origin"], dtype=np.float64) * weight_a + origin * weight_b ) / total target["normal"] = fused_normal.astype(np.float32) target["origin"] = fused_origin.astype(np.float32) target["offset"] = float(-fused_origin @ fused_normal) target["inlierCount"] = int(weight_a + weight_b) for index, plane in enumerate(merged): plane["id"] = index u_axis, v_axis = plane_basis(plane["normal"], bool(plane.get("isFloor")), vertical_ref) plane["uAxis"] = u_axis plane["vAxis"] = v_axis return merged def assign_points_to_surface_planes( points: np.ndarray, normals: np.ndarray, planes: list[dict], normals_reliable: bool = True, ): plane_normals = np.asarray([plane["normal"] for plane in planes], dtype=np.float32) plane_origins = np.asarray([plane["origin"] for plane in planes], dtype=np.float32) offsets = -np.sum(plane_normals * plane_origins, axis=1) distances = np.abs(points @ plane_normals.T + offsets[None, :]) if not normals_reliable: return np.argmin(distances, axis=1).astype(np.int32) alignments = np.abs(normals @ plane_normals.T) normal_cos = float(np.cos(np.deg2rad(SURFACE_NORMAL_ANGLE_DEGREES))) distance_threshold = float(SURFACE_RANSAC_DISTANCE) * 1.5 denom = max(1.0 - normal_cos, 1e-3) score = distances / max(distance_threshold, 1e-6) + (1.0 - alignments) / denom ok = (distances <= distance_threshold) & (alignments >= normal_cos) score[~ok] = np.inf assignment = np.argmin(score, axis=1).astype(np.int32) has_match = np.isfinite(score[np.arange(len(points)), assignment]) if not has_match.all(): assignment[~has_match] = np.argmin(distances[~has_match], axis=1).astype(np.int32) return assignment