File size: 10,222 Bytes
1fe7075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
"""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