"""Shading map construction, smoothing, and luminance-based lighting maps.""" from __future__ import annotations import cv2 import numpy as np from config.lighting import ( SHADE_MAP_MAX, SHADE_MAP_MIN, ) from config.runtime import FAST_SHADOW_MAX_DIMENSION from services.lighting.luminance import ( encode_relative_map, image_linear_luminance, inpaint_surface_values, masked_gaussian_blur, normalize_relative_field, ) # --------------------------------------------------------------------------- # Smoothing # --------------------------------------------------------------------------- def smooth_relative_lighting( relative_shading: np.ndarray, surface_mask: np.ndarray, fill_outside: bool = False, ) -> np.ndarray | None: """Keep room and cast-shadow illumination while rejecting old material detail. Uses a reduced broad-blur sigma and a higher local-detail blend (85 %) compared to the original (70 %) so that contact shadows and sharp light boundaries are preserved rather than smeared into vague gradients. """ min_side = min(surface_mask.shape[:2]) broad_sigma = max(8.0, min_side / 52.0) local_sigma = max(2.0, min_side / 180.0) bounded = np.clip(relative_shading.astype(np.float32), 0.04, 4.0) broad = masked_gaussian_blur(bounded, surface_mask, broad_sigma) local = masked_gaussian_blur(bounded, surface_mask, local_sigma) broad_relative = normalize_relative_field(broad, surface_mask) if broad_relative is None: return None local_contrast = local / np.maximum(broad, 1e-4) local_log = np.log(np.maximum(local_contrast, 1e-4)) local_log = np.clip(local_log, np.log(0.50), np.log(1.08)) combined = broad_relative * np.exp(local_log * 0.35) normalized = normalize_relative_field(combined, surface_mask) if normalized is None: return None normalized = np.clip(normalized, SHADE_MAP_MIN, 1.08) if fill_outside: # Continue the surface's own light past its edge rather than neutral 1.0: the # renderer samples this low-resolution map linearly, so a neutral outside # would brighten the edge into a halo (and pixels the mask gained later, # such as wall between stems, would get no shading at all). outside = surface_mask == 0 normalized[outside] = masked_gaussian_blur(normalized, surface_mask, broad_sigma)[outside] normalized = np.clip(normalized, SHADE_MAP_MIN, 1.08) else: normalized[surface_mask == 0] = 1.0 return normalized # --------------------------------------------------------------------------- # Replaced-material suppression # --------------------------------------------------------------------------- def suppress_replaced_material_lighting( relative: np.ndarray, surface_mask: np.ndarray, replaced_material_mask: np.ndarray | None, ) -> np.ndarray: """Replace rug/carpet appearance with lighting extrapolated from nearby hard floor.""" if replaced_material_mask is None or replaced_material_mask.shape != surface_mask.shape: return relative replacement = (replaced_material_mask > 0) & (surface_mask > 0) if not replacement.any(): return relative known_surface = (surface_mask > 0) & (~replacement) known_values = relative[known_surface] known_values = known_values[np.isfinite(known_values) & (known_values > 1e-6)] output = relative.astype(np.float32).copy() if known_values.size < 64: output[replacement] = 1.0 output[surface_mask == 0] = 1.0 return output median = float(np.median(known_values)) source = output.copy() source[~np.isfinite(source)] = median source[surface_mask == 0] = median radius = max(3.0, min(surface_mask.shape[:2]) / 120.0) extrapolated = cv2.inpaint( source.astype(np.float32), replacement.astype(np.uint8), radius, cv2.INPAINT_TELEA, ) sigma = max(8.0, min(surface_mask.shape[:2]) / 48.0) extrapolated = masked_gaussian_blur(extrapolated, surface_mask, sigma) output[replacement] = extrapolated[replacement] output = np.clip(output, SHADE_MAP_MIN, 1.08) output[surface_mask == 0] = 1.0 return output # --------------------------------------------------------------------------- # Luminance-based lighting maps # --------------------------------------------------------------------------- def build_fast_shadow_lighting_maps( img_np: np.ndarray, surface_mask: np.ndarray, replaced_material_mask: np.ndarray | None = None, fill_outside: bool = False, ) -> dict[str, np.ndarray | None] | None: """Extract broad room shadows on a bounded working image. Unlike the legacy lighting path, this does not run intrinsic inference, calculate reflections, or process several full-resolution float maps. The resulting low-resolution shade texture is sampled linearly by the renderer. """ if not surface_mask.any(): return None source_h, source_w = surface_mask.shape[:2] scale = min(1.0, FAST_SHADOW_MAX_DIMENSION / float(max(source_h, source_w))) work_w = max(1, int(round(source_w * scale))) work_h = max(1, int(round(source_h * scale))) if (work_w, work_h) == (source_w, source_h): work_image = img_np work_mask = surface_mask.astype(np.uint8) work_replaced_mask = replaced_material_mask else: work_image = cv2.resize(img_np, (work_w, work_h), interpolation=cv2.INTER_AREA) work_mask = cv2.resize( surface_mask.astype(np.uint8), (work_w, work_h), interpolation=cv2.INTER_NEAREST, ) work_replaced_mask = ( cv2.resize( replaced_material_mask.astype(np.uint8), (work_w, work_h), interpolation=cv2.INTER_NEAREST, ) if replaced_material_mask is not None else None ) luminance = image_linear_luminance(work_image) floor_values = luminance[work_mask > 0] floor_values = floor_values[np.isfinite(floor_values) & (floor_values > 1e-6)] if floor_values.size < max(64, int(work_h * work_w * 0.002)): return None median_lum = float(np.median(floor_values)) if median_lum < 1e-3: return None relative = luminance / median_lum relative[~np.isfinite(relative)] = 1.0 relative[work_mask == 0] = 1.0 relative = suppress_replaced_material_lighting( relative, work_mask, work_replaced_mask, ) shade = smooth_relative_lighting(relative, work_mask, fill_outside=fill_outside) if shade is None: return None return { "shadeMap": encode_relative_map(shade, SHADE_MAP_MIN, SHADE_MAP_MAX), "showroomShadeMap": None, "reflectionMap": None, } def build_luminance_lighting_maps( img_np: np.ndarray, surface_mask: np.ndarray, replaced_material_mask: np.ndarray | None = None, ) -> dict[str, np.ndarray | None] | None: if not surface_mask.any(): return None mask = surface_mask.astype(np.uint8) luminance = image_linear_luminance(img_np) h, w = mask.shape[:2] floor_values = luminance[mask > 0] if floor_values.size < max(256, int(h * w * 0.002)): return None median_lum = float(np.median(floor_values)) if median_lum < 1e-3: return None filled = inpaint_surface_values(luminance, mask, median_lum) relative = filled / median_lum relative[~np.isfinite(relative)] = 1.0 relative = suppress_replaced_material_lighting( relative, mask, replaced_material_mask, ) shade = smooth_relative_lighting(relative, mask) if shade is None: return None from services.lighting.showroom import build_showroom_shade_map_from_relative from services.lighting.reflection import build_reflection_map return { "shadeMap": encode_relative_map(shade, SHADE_MAP_MIN, SHADE_MAP_MAX), "showroomShadeMap": build_showroom_shade_map_from_relative(shade, mask), "reflectionMap": build_reflection_map( img_np, surface_mask, None, replaced_material_mask, ), } # --------------------------------------------------------------------------- # Statistics # --------------------------------------------------------------------------- def lighting_map_statistics(encoded: np.ndarray | None, surface_mask: np.ndarray) -> dict | None: if encoded is None: return None if encoded.shape[:2] != surface_mask.shape[:2]: surface_mask = cv2.resize( surface_mask.astype(np.uint8), (encoded.shape[1], encoded.shape[0]), interpolation=cv2.INTER_NEAREST, ) decoded = SHADE_MAP_MIN + (encoded.astype(np.float32) / 255.0) * (SHADE_MAP_MAX - SHADE_MAP_MIN) values = decoded[surface_mask > 0] if values.size == 0: return None percentiles = np.percentile(values, [1, 5, 50, 95, 99]) return { "minimum": round(float(values.min()), 4), "p01": round(float(percentiles[0]), 4), "p05": round(float(percentiles[1]), 4), "median": round(float(percentiles[2]), 4), "p95": round(float(percentiles[3]), 4), "p99": round(float(percentiles[4]), 4), "maximum": round(float(values.max()), 4), } def preserve_observed_lighting( intrinsic_relative: np.ndarray, observed_relative: np.ndarray, surface_mask: np.ndarray, ) -> np.ndarray: """Keep observed room shadows and highlights from being weakened by intrinsic decomposition.""" fused = intrinsic_relative.astype(np.float32).copy() shadow_pixels = (surface_mask > 0) & (observed_relative < 1.0) highlight_pixels = (surface_mask > 0) & (observed_relative > 1.0) fused[shadow_pixels] = np.minimum( fused[shadow_pixels], observed_relative[shadow_pixels], ) fused[highlight_pixels] = np.maximum( fused[highlight_pixels], observed_relative[highlight_pixels], ) fused = np.clip(fused, SHADE_MAP_MIN, 1.20) fused[surface_mask == 0] = 1.0 return fused