File size: 34,066 Bytes
1d4b965
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
#!/usr/bin/env python
"""Generate SyncLight relighting pairs from the per-light base files.

Every scene in the dataset was rendered (Infinigen, BlenderKit) or photographed (real)
once per light source. Because light is additive, the image of the scene under any
combination of lights, intensities and colours is a weighted sum of those per-light
images:

    image(state) = tonemap( sum_i  intensity_i * colour_i * light_i )

This script samples pairs of light states that differ in exactly one light (the
"edit"), renders them for every camera of a rig, and writes them in the layout the
SyncLight training code reads:

    <output>/<scene>/<output_subdir>/
        cam_<rig>_<cam>_<idx>_{0,1}_guide.png      reference view, before / after the edit
        cam_<rig>_<cam>_<idx>_{0,1}.png            every other view of the rig, before / after
        cam_<rig>_<cam>_<idx>_0_to_1_lightmap.png  the edit, drawn in the reference view
        cam_<rig>_<cam>_<idx>_1_to_0_lightmap.png  the reverse edit (when stored)
        transforms.json                            list of pairs + relative camera poses

All sampling and rendering options live in a YAML config (see configs/). Every
option can also be overridden on the command line with --set key=value.

Usage:
    python synclight_generate.py --config configs/infinigen.yaml \
        --input synclight_raw/infinigen/train --output synclight_pairs/infinigen/train --workers 8

    # count what a config would produce without rendering anything
    python synclight_generate.py --config configs/blenderkit.yaml --input ... --dry-run

    # more colourful edits, 10 samples per light
    python synclight_generate.py --config configs/blenderkit.yaml --input ... --output ... \
        --set colors.palette=colorful pairs.per_light=10
"""

import argparse
import colorsys
import copy
import json
import os
import re
import sys
import time
import zlib
from concurrent.futures import ProcessPoolExecutor, as_completed
from glob import glob

os.environ.setdefault("OMP_NUM_THREADS", "1")
import cv2  # noqa: E402
import numpy as np  # noqa: E402
import yaml  # noqa: E402

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from lightmap_io import encode_lightmap_png_bytes  # noqa: E402

# --------------------------------------------------------------------------------------
# Configuration
# --------------------------------------------------------------------------------------

DEFAULTS = {
    "source": "infinigen",          # infinigen | blenderkit | real
    "output_subdir": "png_simple",  # folder written inside each output scene folder
    "seed": 0,
    "pairs": {
        "per_light": 5,             # random-combination samples per editable light, per reference camera
        "max_per_scene": None,      # cap on pairs per scene; samples are randomly dropped to fit (null = no cap)
        "reverse": True,            # also store the reverse edit (after -> before) of random samples
        "target_views": "all",      # other views rendered per sample: "all" or an integer
        "min_cameras": 2,           # rigs with fewer cameras are skipped (no other view to propagate to)
    },
    "solo_sweep": {                 # each visible light alone over the ambient light, in a fixed list of colours
        "enabled": True,
        "vivid": ["red", "orange", "yellow", "green", "cyan", "blue", "purple", "magenta"],
        "n_temperatures": 5,        # plus this many colour temperatures drawn from `temperatures`
        "temperatures": [2700, 3000, 3500, 4000, 4500, 5000, 5500, 6000, 6500, 7000, 7500],
        "intensity": 1.0,
        "reverse_first": 3,         # only the first N colours of each light also store the reverse pair
    },
    "lights": {                     # random 'before' state
        "p_ambient_on": 0.8,        # each ambient (never visible) light
        "p_visible_on": 0.6,        # each light visible from some camera
        "on_intensity": [0.4, 1.0], # uniform range for lights that are on
    },
    "edits": {                      # what happens to the edited light; weights are normalised
        "toggle": 0.7,              # on -> off, or off -> on at full intensity
        "intensity": 0.3,           # bright -> dim, dim -> bright, or off -> partially on
        "color": 0.0,               # new colour (switching the light on if it was off)
        "dim_to": [0.2, 0.5],
        "brighten_to": [0.7, 1.0],
        "partial_on": [0.5, 1.0],
        "bright_threshold": 0.6,    # lights above this intensity get dimmed, below it brightened
    },
    "colors": {
        "palette": None,            # optional preset (see PALETTES) applied before the fields below
        "scene": {"white": 0.7, "temperature": 0.18, "vivid": 0.12},  # colour shared by all lights in a sample
        "per_light": False,         # true: every light draws its own colour instead of sharing one
        "edit": {"white": 0.0, "temperature": 0.7, "vivid": 0.3},     # new colour for 'color' edits
        "temperatures": [2700, 3000, 3500, 4000, 5000, 5500, 6500, 7500],  # Kelvin values to pick from...
        "temperature_range": None,  # ...or a continuous [min, max] range in Kelvin
        "vivid": {
            "mode": "jitter",       # named: exact named hues | jitter: hue/sat/value ranges per name | any: any hue
            "names": ["red", "orange", "yellow", "green", "cyan", "blue", "purple", "magenta"],
            "saturation": [0.7, 1.0],   # used by mode 'any'
            "value": [0.7, 1.0],        # used by mode 'any'
        },
    },
    "tonemap": {
        "operator": "reinhard",     # reinhard | reinhard_white | aces | hable | clip
        "white": 4.0,               # white point of reinhard_white
        "exposure": 1.0,            # multiplier applied to linear radiance before the operator
        "auto_exposure": None,      # {percentile: 99, target: 0.9}: per-sample exposure from the reference 'before' image
        "gamma": 2.2,               # display gamma, or "srgb"
        "quantize": "floor",        # floor (as in the original release) | round
    },
    "output": {
        "max_side": None,           # downscale outputs so the longest side is at most this (null = native)
        "resize_inputs": False,     # downscale base images before mixing (much faster for RAW; small differences at bright edges)
        "lightmap": "png16",        # png16 (16-bit RGBA, see lightmap_io.py) | npy (float32, original format)
        "lightmap_size": "image",   # image: same size as the output images | native: size of the light-position maps
        "lightmap_threshold": 0.098,  # light-position map value above which a pixel belongs to the light
        "png_compression": 3,
        "precision": "float32",     # float32 (fast) | float64 (bit-exact with the original scripts)
    },
}

PALETTES = {
    # Mostly white and natural colour temperatures; no saturated colours.
    "neutral": {"scene": {"white": 0.5, "temperature": 0.5, "vivid": 0.0},
                "edit": {"white": 0.2, "temperature": 0.8, "vivid": 0.0},
                "temperature_range": [3000, 6500], "temperatures": None},
    # Warm (tungsten) light only.
    "warm": {"scene": {"white": 0.2, "temperature": 0.8, "vivid": 0.0},
             "edit": {"white": 0.0, "temperature": 1.0, "vivid": 0.0},
             "temperature_range": [2200, 4000], "temperatures": None},
    # Cool (daylight / fluorescent) light only.
    "cool": {"scene": {"white": 0.2, "temperature": 0.8, "vivid": 0.0},
             "edit": {"white": 0.0, "temperature": 1.0, "vivid": 0.0},
             "temperature_range": [5000, 9000], "temperatures": None},
    # More saturated colours, still anchored on the 8 named hues.
    "colorful": {"scene": {"white": 0.4, "temperature": 0.3, "vivid": 0.3},
                 "edit": {"white": 0.0, "temperature": 0.4, "vivid": 0.6},
                 "vivid": {"mode": "jitter"}},
    # Any hue, every light its own colour.
    "wild": {"scene": {"white": 0.1, "temperature": 0.2, "vivid": 0.7},
             "edit": {"white": 0.0, "temperature": 0.1, "vivid": 0.9},
             "per_light": True,
             "vivid": {"mode": "any", "saturation": [0.6, 1.0], "value": [0.6, 1.0]}},
}

VIVID_NAMED = {  # exact hues used by the solo sweep and by mode 'named'
    "red": (0.0, 0.9, 0.9), "orange": (0.08, 0.9, 0.9), "yellow": (0.15, 0.85, 0.95),
    "green": (0.33, 0.85, 0.8), "cyan": (0.5, 0.85, 0.85), "blue": (0.6, 0.9, 0.8),
    "purple": (0.75, 0.8, 0.8), "magenta": (0.88, 0.85, 0.85),
}
VIVID_RANGES = {  # hue / saturation / value ranges used by mode 'jitter'
    "red": ((0.0, 0.05), (0.8, 1.0), (0.8, 1.0)), "orange": ((0.05, 0.12), (0.8, 1.0), (0.8, 1.0)),
    "yellow": ((0.12, 0.18), (0.7, 1.0), (0.9, 1.0)), "green": ((0.25, 0.40), (0.7, 1.0), (0.7, 1.0)),
    "cyan": ((0.45, 0.55), (0.7, 1.0), (0.8, 1.0)), "blue": ((0.55, 0.65), (0.8, 1.0), (0.7, 1.0)),
    "purple": ((0.70, 0.80), (0.7, 1.0), (0.7, 1.0)), "magenta": ((0.80, 0.95), (0.8, 1.0), (0.8, 1.0)),
}


def deep_update(base, upd):
    for k, v in upd.items():
        if isinstance(v, dict) and isinstance(base.get(k), dict):
            deep_update(base[k], v)
        else:
            base[k] = v
    return base


def load_config(path, overrides):
    cfg = copy.deepcopy(DEFAULTS)
    if path:
        with open(path) as f:
            deep_update(cfg, yaml.safe_load(f) or {})
    sets = {}
    for item in overrides or []:
        key, _, val = item.partition("=")
        node = sets
        *parents, leaf = key.split(".")
        for p in parents:
            node = node.setdefault(p, {})
        node[leaf] = yaml.safe_load(val)
    deep_update(cfg, sets)
    palette = cfg["colors"].get("palette")
    if palette:
        if palette not in PALETTES:
            raise SystemExit(f"unknown palette {palette}; choose from {sorted(PALETTES)}")
        colors = copy.deepcopy(cfg["colors"])
        deep_update(colors, copy.deepcopy(PALETTES[palette]))
        # explicit --set colors.* values still win over the preset
        deep_update(colors, sets.get("colors", {}))
        cfg["colors"] = colors
    return cfg


# --------------------------------------------------------------------------------------
# Colours
# --------------------------------------------------------------------------------------

def kelvin_to_rgb(temp_k):
    """Approximate RGB in [0, 1] of a black body at temp_k (Tanner Helland's fit)."""
    t = temp_k / 100.0
    r = 1.0 if t <= 66 else np.clip(1.292936186 * ((t - 60) ** -0.1332047592), 0, 1)
    if t <= 66:
        g = np.clip(0.39008157876 * np.log(t) - 0.631841444, 0, 1)
    else:
        g = np.clip(1.129890861 * ((t - 60) ** -0.0755148492), 0, 1)
    if t >= 66:
        b = 1.0
    elif t <= 19:
        b = 0.0
    else:
        b = np.clip(0.543206789 * np.log(t - 10) - 1.196254089, 0, 1)
    return np.array([r, g, b], dtype=np.float64)


def hsv(h, s, v):
    return np.array(colorsys.hsv_to_rgb(h, s, v), dtype=np.float64)


class ColorSampler:
    def __init__(self, ccfg, rng):
        self.c, self.rng = ccfg, rng

    def temperature(self):
        rng_k = self.c.get("temperature_range")
        if rng_k:
            return kelvin_to_rgb(self.rng.uniform(*rng_k))
        return kelvin_to_rgb(self.rng.choice(self.c["temperatures"]))

    def vivid(self):
        v = self.c["vivid"]
        if v["mode"] == "any":
            return hsv(self.rng.uniform(0, 1), self.rng.uniform(*v["saturation"]), self.rng.uniform(*v["value"]))
        name = self.rng.choice(v["names"])
        if v["mode"] == "named":
            return hsv(*VIVID_NAMED[name])
        (h, s, val) = VIVID_RANGES[name]
        return hsv(self.rng.uniform(*h), self.rng.uniform(*s), self.rng.uniform(*val))

    def draw(self, weights):
        kinds = [k for k in ("white", "temperature", "vivid") if weights.get(k, 0) > 0]
        p = np.array([weights[k] for k in kinds], dtype=np.float64)
        kind = kinds[self.rng.choice(len(kinds), p=p / p.sum())]
        return np.ones(3) if kind == "white" else self.temperature() if kind == "temperature" else self.vivid()


# --------------------------------------------------------------------------------------
# Light-state sampling
# --------------------------------------------------------------------------------------

def solo_sweep(vis, cfg, rng):
    """Each visible light alone (over the ambient lights) in a fixed list of colours."""
    sc = cfg["solo_sweep"]
    nonvis = [i for i, v in enumerate(vis) if v == "nonvis"]
    camvis = [i for i, v in enumerate(vis) if v == "camvis"]
    if not sc["enabled"] or not nonvis:
        return []
    colours = [hsv(*VIVID_NAMED[n]) for n in sc["vivid"]]
    if sc["n_temperatures"]:
        temps = rng.choice(sc["temperatures"], size=sc["n_temperatures"], replace=False)
        colours += [kelvin_to_rgb(t) for t in temps]
    n = len(vis)
    out = []
    for light in camvis:
        for k, col in enumerate(colours):
            i_in, c_in = np.zeros(n), np.ones((n, 3))
            i_in[nonvis] = 1.0
            i_out, c_out = i_in.copy(), c_in.copy()
            i_out[light], c_out[light] = sc["intensity"], col
            out.append((i_in, i_out, c_in, c_out, k < sc["reverse_first"]))
    return out


def random_combinations(vis, cfg, rng):
    """Random 'before' states; the 'after' state changes exactly one camera-visible light."""
    lc, ec, pc = cfg["lights"], cfg["edits"], cfg["pairs"]
    colors = ColorSampler(cfg["colors"], rng)
    n = len(vis)
    camvis = [i for i, v in enumerate(vis) if v == "camvis"]
    visible = [i for i, v in enumerate(vis) if v in ("camvis", "rigvis")]
    nonvis = [i for i, v in enumerate(vis) if v == "nonvis"]
    kinds = [k for k in ("toggle", "intensity", "color") if ec[k] > 0]
    pk = np.array([ec[k] for k in kinds], dtype=np.float64)
    pk /= pk.sum()
    out = []
    for target in camvis:
        for _ in range(pc["per_light"]):
            if cfg["colors"]["per_light"]:
                c_in = np.stack([colors.draw(cfg["colors"]["scene"]) for _ in range(n)])
            else:
                c_in = np.tile(colors.draw(cfg["colors"]["scene"]), (n, 1))
            i_in = np.zeros(n)
            for i in nonvis:
                if rng.random() < lc["p_ambient_on"]:
                    i_in[i] = 1.0
            for i in visible:
                if rng.random() < lc["p_visible_on"]:
                    i_in[i] = rng.uniform(*lc["on_intensity"])
            if i_in.sum() == 0:
                i_in[rng.choice(nonvis or visible)] = 1.0

            i_out, c_out = i_in.copy(), c_in.copy()
            cur = i_in[target]
            kind = kinds[rng.choice(len(kinds), p=pk)]
            if kind == "toggle":
                i_out[target] = 0.0 if cur > 0 else 1.0
            elif kind == "intensity":
                if cur > 0:
                    i_out[target] = rng.uniform(*(ec["dim_to"] if cur > ec["bright_threshold"] else ec["brighten_to"]))
                else:
                    i_out[target] = rng.uniform(*ec["partial_on"])
            else:
                if cur == 0:
                    i_out[target] = 1.0
                c_out[target] = colors.draw(cfg["colors"]["edit"])
            out.append((i_in, i_out, c_in, c_out, bool(pc["reverse"])))
    return out


def valid(sample):
    i_in, i_out, c_in, c_out, _ = sample
    if np.allclose(i_in, i_out) and np.allclose(c_in, c_out):
        return False
    return not np.all(i_out == 0)


# --------------------------------------------------------------------------------------
# Lightmaps
# --------------------------------------------------------------------------------------

def rgb_to_lab_normalized(rgb):
    """sRGB colour in [0, 1] -> (L, a, b) with every channel scaled to [-1, 1]."""
    rgb = np.asarray(rgb, dtype=np.float64)
    lin = np.where(rgb > 0.04045, ((rgb + 0.055) / 1.055) ** 2.4, rgb / 12.92)
    m = np.array([[0.4124564, 0.3575761, 0.1804375],
                  [0.2126729, 0.7151522, 0.0721750],
                  [0.0193339, 0.1191920, 0.9503041]])
    xyz = lin @ m.T / np.array([0.95047, 1.0, 1.08883])
    d = 6 / 29
    f = np.where(xyz > d ** 3, xyz ** (1 / 3), xyz / (3 * d ** 2) + 4 / 29)
    L, a, b = 116 * f[1] - 16, 500 * (f[0] - f[1]), 200 * (f[1] - f[2])
    return np.array([L / 50 - 1, np.clip(a / 128, -1, 1), np.clip(b / 128, -1, 1)])


def differential_lightmap(masks, vis, i_in, i_out, c_in, c_out):
    """(H, W, 4) map of the edit: [activation, L, a, b]; see lightmap_io.py for the encoding."""
    lm = np.zeros(masks.shape[1:] + (4,), dtype=np.float32)
    for k, mask in enumerate(masks):
        if vis[k] != "camvis" or not mask.any():
            continue
        on_in, on_out = i_in[k] > 0, i_out[k] > 0
        if not on_in and not on_out:
            continue
        if on_in and not on_out:
            lm[mask] = (-1.0, 0.0, 0.0, 0.0)
        elif (not on_in) or not np.isclose(i_in[k], i_out[k], atol=1e-6) or not np.allclose(c_in[k], c_out[k], atol=1e-6):
            lab = rgb_to_lab_normalized(c_out[k])
            lm[mask] = (1.0, i_out[k] * 2 - 1, lab[1], lab[2])
    return lm


# --------------------------------------------------------------------------------------
# Rendering
# --------------------------------------------------------------------------------------

def tonemap(x, tc, exposure):
    x = np.maximum(x * exposure, 0)
    op = tc["operator"]
    if op == "reinhard":
        y = x / (1 + x)
    elif op == "reinhard_white":
        w2 = tc["white"] ** 2
        y = x * (1 + x / w2) / (1 + x)
    elif op == "aces":  # Narkowicz 2015 fit of the ACES filmic curve
        y = (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14)
    elif op == "hable":  # Uncharted 2 filmic curve, white point 11.2
        def h(v):
            A, B, C, D, E, F = 0.15, 0.50, 0.10, 0.20, 0.02, 0.30
            return ((v * (A * v + C * B) + D * E) / (v * (A * v + B) + D * F)) - E / F
        y = h(2 * x) / h(11.2)
    elif op == "clip":
        y = x
    else:
        raise ValueError(f"unknown tone-mapping operator {op}")
    y = np.clip(y, 0, 1)
    if tc["gamma"] == "srgb":
        y = np.where(y <= 0.0031308, 12.92 * y, 1.055 * np.power(y, 1 / 2.4) - 0.055)
    else:
        y = np.power(y, 1.0 / float(tc["gamma"]))
    y = y * 255
    y = np.floor(y) if tc["quantize"] == "floor" else np.round(y)
    return np.clip(y, 0, 255).astype(np.uint8)


def auto_exposure(linear, tc):
    ae = tc["auto_exposure"]
    lum = linear @ np.array([0.2126, 0.7152, 0.0722], dtype=linear.dtype)
    p = float(np.percentile(lum, ae.get("percentile", 99)))
    return tc["exposure"] * (ae.get("target", 0.9) / p if p > 0 else 1.0)


def mix(stack, intensities, colours, dtype):
    """stack: (L, H, W, 3) per-light linear images -> (H, W, 3) image of one light state."""
    w = (np.asarray(intensities, dtype=np.float64)[:, None] * np.asarray(colours, dtype=np.float64)).astype(dtype)
    if dtype == np.float64:  # same order of operations as the original scripts (bit-exact)
        out = np.zeros(stack.shape[1:], dtype=np.float64)
        for k in range(len(w)):
            out = out + w[k][None, None, :] * stack[k]
        return out
    return np.einsum("lhwc,lc->hwc", stack, w, optimize=True)


def resize_max_side(img, max_side, interp):
    if not max_side:
        return img
    h, w = img.shape[:2]
    if max(h, w) <= max_side:
        return img
    size = (int(w * max_side / h), max_side) if h > w else (max_side, int(h * max_side / w))
    return cv2.resize(img, size, interpolation=interp)


def resize_uint8_lanczos(img, max_side):
    """Resize a tone-mapped image the way the original real-image script did (PIL Lanczos)."""
    if not max_side or max(img.shape[:2]) <= max_side:
        return img
    from PIL import Image
    h, w = img.shape[:2]
    size = (int(w * max_side / h), max_side) if h > w else (max_side, int(h * max_side / w))
    return np.array(Image.fromarray(img).resize(size, Image.LANCZOS))


# --------------------------------------------------------------------------------------
# Scene loading
# --------------------------------------------------------------------------------------

SYN_RE = re.compile(r"camera_(\d+)_(\d+)_(\d+)_([a-z]+)\.exr$")
REAL_RE = re.compile(r"(scene\d+)_(\d+)_(\d+)_([a-z]+)\.(dng|cr2)$", re.I)
VIS_ALIASES = {"camvis": "camvis", "rigvis": "rigvis", "nonvis": "nonvis", "ambient": "nonvis"}


def find_scenes(root, source):
    sub = "captured" if source == "real" else "rendered"
    hits = sorted(set(glob(os.path.join(root, "*", sub)) + glob(os.path.join(root, "*", "*", sub))))
    return [os.path.relpath(os.path.dirname(h), root) for h in hits]


def scene_layout(scene_dir, source):
    """{rig: {cam: [(light_id, vis, image_path, light_map_path), ...]}} from file names only."""
    rigs = {}
    if source == "real":
        for f in sorted(os.listdir(os.path.join(scene_dir, "captured"))):
            m = REAL_RE.match(f)
            if not m:
                continue
            _, cam, light, vis = m.group(1), m.group(2), int(m.group(3)), m.group(4).lower()
            base = os.path.join(scene_dir, "captured", f)
            lm = os.path.join(scene_dir, "captured", f.rsplit(".", 1)[0] + "_light_map.png")
            rigs.setdefault("0", {}).setdefault(cam, []).append((light, VIS_ALIASES.get(vis, "camvis"), base, lm))
    else:
        for f in sorted(os.listdir(os.path.join(scene_dir, "rendered"))):
            m = SYN_RE.match(f)
            if not m:
                continue
            rig, cam, light, vis = m.group(1), m.group(2), int(m.group(3)), m.group(4)
            base = os.path.join(scene_dir, "rendered", f)
            lm = os.path.join(scene_dir, "rendered", f"camera_{rig}_{cam}_{m.group(3)}_light_map.png")
            rigs.setdefault(rig, {}).setdefault(cam, []).append((light, VIS_ALIASES.get(vis, "camvis"), base, lm))
    for cams in rigs.values():
        for c in cams:
            cams[c].sort(key=lambda t: t[0])
    return rigs


def load_exr_rgb(path):
    import OpenEXR
    with OpenEXR.File(path) as f:
        ch = f.channels()
        for k in ("RGB", "RGBA", "ViewLayer.Combined", "View Layer.Combined", "Combined"):
            if k in ch:
                return np.ascontiguousarray(ch[k].pixels[..., :3], dtype=np.float32)
    raise ValueError(f"no RGB channels in {path}")


def load_raw_rgb(path):
    import rawpy
    with rawpy.imread(path) as raw:
        rgb = raw.postprocess(use_camera_wb=True, half_size=False, no_auto_bright=True, output_bps=16,
                              gamma=(1, 1), output_color=rawpy.ColorSpace.sRGB)
    return rgb.astype(np.float32) / 65535.0


def load_light_mask(path, shape, threshold):
    if not os.path.exists(path):
        return np.zeros(shape, dtype=bool)
    m = cv2.imread(path, cv2.IMREAD_GRAYSCALE).astype(np.float32) / 255.0
    if m.shape != shape:
        m = cv2.resize(m, (shape[1], shape[0]), interpolation=cv2.INTER_AREA)
    return m > threshold


def relative_pose(transforms, rig, cam_ref, cam_other):
    if not transforms or f"rig_{rig}" not in transforms:
        return [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0, 0, 0, 0]
    from scipy.spatial.transform import Rotation
    r = transforms[f"rig_{rig}"]
    a, b = r.get(f"camera_{rig}_{cam_ref}"), r.get(f"camera_{rig}_{cam_other}")
    if not a or not b:
        return [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0, 0, 0, 0]
    R1, R2 = (Rotation.from_euler("xyz", x["rotation"]).as_matrix() for x in (a, b))
    t1, t2 = (np.array(x["translation"]).reshape(3, 1) for x in (a, b))
    R = R2 @ R1.T
    t = t2 - R @ t1
    return Rotation.from_matrix(R).as_euler("xyz").tolist(), t.flatten().tolist(), b.get("intrinsics", [0, 0, 0, 0])


# --------------------------------------------------------------------------------------
# Planning (cheap: file names + sampling only, no images)
# --------------------------------------------------------------------------------------

def job_rng(cfg, scene, rig, cam):
    return np.random.default_rng([int(cfg["seed"]), zlib.crc32(scene.encode()), int(rig), int(cam)])


def plan_rig(cfg, scene, rig, cams):
    """Samples per reference camera for one rig, before the per-scene cap."""
    plans = {}
    for cam, lights in cams.items():
        vis = [v for _, v, _, _ in lights]
        if "camvis" not in vis:
            continue
        rng = job_rng(cfg, scene, rig, cam)
        samples = [s for s in solo_sweep(vis, cfg, rng) + random_combinations(vis, cfg, rng) if valid(s)]
        plans[cam] = samples
    return plans


def n_targets(cfg, n_cams):
    tv = cfg["pairs"]["target_views"]
    return n_cams - 1 if tv == "all" else min(int(tv), n_cams - 1)


def plan_scene(cfg, input_root, scene):
    rigs = scene_layout(os.path.join(input_root, scene), cfg["source"])
    plan = {}
    for rig, cams in sorted(rigs.items()):
        if len(cams) < cfg["pairs"]["min_cameras"]:
            continue
        counts = [len(v) for v in cams.values()]
        if len(set(counts)) != 1:
            print(f"warning: {scene} rig {rig}: cameras see different numbers of lights {counts}, skipping rig")
            continue
        plan[rig] = plan_rig(cfg, scene, rig, cams)
    # Per-scene cap: keep the same random fraction of samples in every camera.
    cap = cfg["pairs"]["max_per_scene"]
    total = count_pairs(cfg, rigs, plan)[0]
    if cap and total > cap:
        ratio = cap / total
        for r, cams in plan.items():
            for c, s in cams.items():
                keep = max(1, int(len(s) * ratio))
                idx = sorted(job_rng(cfg, scene, r, c).choice(len(s), keep, replace=False))
                cams[c] = [s[i] for i in idx]
    return rigs, plan


def count_pairs(cfg, rigs, plan):
    pairs = images = 0
    for r, cams in plan.items():
        nt = n_targets(cfg, len(rigs[r]))
        for s in cams.values():
            pairs += sum(nt * (1 + x[4]) for x in s)
            images += len(s) * 2 * (1 + nt)
    return pairs, images


# --------------------------------------------------------------------------------------
# Rendering a rig
# --------------------------------------------------------------------------------------

def render_rig(cfg, input_root, output_root, scene, rig, cams, plan):
    oc, tc = cfg["output"], cfg["tonemap"]
    dtype = np.float64 if oc["precision"] == "float64" else np.float32
    out_dir = os.path.join(output_root, scene, cfg["output_subdir"])
    os.makedirs(out_dir, exist_ok=True)
    scene_dir = os.path.join(input_root, scene)
    tf_path = os.path.join(scene_dir, "rendered", "camera_transforms.json")
    transforms = json.load(open(tf_path)) if os.path.exists(tf_path) else None
    is_real = cfg["source"] == "real"
    exact_real = is_real and not oc["resize_inputs"]

    stacks, masks, vis = {}, {}, {}
    for cam, lights in cams.items():
        imgs = []
        for _, _, path, _ in lights:
            img = load_raw_rgb(path) if is_real else load_exr_rgb(path)
            if oc["resize_inputs"]:
                img = resize_max_side(img, oc["max_side"], cv2.INTER_AREA)
            imgs.append(img)
        stacks[cam] = np.stack(imgs).astype(dtype)
        native = stacks[cam].shape[1:3]
        masks[cam] = np.stack([load_light_mask(lm, native, oc["lightmap_threshold"]) for _, _, _, lm in lights])
        vis[cam] = [v for _, v, _, _ in lights]

    def finish(img_u8):
        if exact_real:
            return resize_uint8_lanczos(img_u8, oc["max_side"])
        if oc["resize_inputs"]:
            return img_u8
        return resize_max_side(img_u8, oc["max_side"], cv2.INTER_AREA)

    def save_png(name, img_u8):
        cv2.imwrite(os.path.join(out_dir, name), cv2.cvtColor(img_u8, cv2.COLOR_RGB2BGR),
                    [cv2.IMWRITE_PNG_COMPRESSION, oc["png_compression"]])

    def save_lightmap(stem, lm, size_hw):
        if oc["lightmap_size"] == "image" and lm.shape[:2] != size_hw:
            lm = cv2.resize(lm, (size_hw[1], size_hw[0]), interpolation=cv2.INTER_NEAREST)
        if oc["lightmap"] == "npy":
            name = stem + ".npy"
            np.save(os.path.join(out_dir, name), lm)
        else:
            name = stem + ".png"
            with open(os.path.join(out_dir, name), "wb") as f:
                f.write(encode_lightmap_png_bytes(lm))
        return name

    entries, idx = [], 0
    cam_ids = list(cams)
    for cam, samples in plan.items():
        others = [c for c in cam_ids if c != cam][: n_targets(cfg, len(cam_ids))]
        for i_in, i_out, c_in, c_out, rev in samples:
            lin_in = mix(stacks[cam], i_in, c_in, dtype)
            exposure = auto_exposure(lin_in, tc) if tc.get("auto_exposure") else tc["exposure"]
            g_in = finish(tonemap(lin_in, tc, exposure))
            g_out = finish(tonemap(mix(stacks[cam], i_out, c_out, dtype), tc, exposure))
            stem = f"cam_{rig}_{cam}_{idx:05d}"
            save_png(f"{stem}_0_guide.png", g_in)
            save_png(f"{stem}_1_guide.png", g_out)
            lm_fwd = save_lightmap(f"{stem}_0_to_1_lightmap",
                                   differential_lightmap(masks[cam], vis[cam], i_in, i_out, c_in, c_out), g_in.shape[:2])
            lm_rev = None
            if rev:
                lm_rev = save_lightmap(f"{stem}_1_to_0_lightmap",
                                       differential_lightmap(masks[cam], vis[cam], i_out, i_in, c_out, c_in), g_in.shape[:2])
            for other in others:
                o_stem = f"cam_{rig}_{other}_{idx:05d}"
                save_png(f"{o_stem}_0.png", finish(tonemap(mix(stacks[other], i_in, c_in, dtype), tc, exposure)))
                save_png(f"{o_stem}_1.png", finish(tonemap(mix(stacks[other], i_out, c_out, dtype), tc, exposure)))
                rot, trans, intr = relative_pose(transforms, rig, cam, other)
                entries.append({"input_image": f"{o_stem}_0.png", "target": f"{o_stem}_1.png",
                                "input_guide": f"{stem}_0_guide.png", "target_guide": f"{stem}_1_guide.png",
                                "lightmap": lm_fwd, "relative_rotation": rot, "relative_translation": trans,
                                "intrinsics": intr})
                if rev:
                    entries.append({"input_image": f"{o_stem}_1.png", "target": f"{o_stem}_0.png",
                                    "input_guide": f"{stem}_1_guide.png", "target_guide": f"{stem}_0_guide.png",
                                    "lightmap": lm_rev, "relative_rotation": [-v for v in rot],
                                    "relative_translation": [-v for v in trans], "intrinsics": intr})
            idx += 1
    return entries


def render_scene(cfg, input_root, output_root, scene):
    t0 = time.time()
    rigs, plan = plan_scene(cfg, input_root, scene)
    entries, cameras = [], []
    for rig in sorted(plan):
        cameras.append({rig: sorted(rigs[rig])})
        entries += render_rig(cfg, input_root, output_root, scene, rig, rigs[rig], plan[rig])
    out_dir = os.path.join(output_root, scene, cfg["output_subdir"])
    os.makedirs(out_dir, exist_ok=True)
    with open(os.path.join(out_dir, "transforms.json"), "w") as f:
        json.dump({"images": entries, "cameras": cameras}, f, indent=1)
    with open(os.path.join(out_dir, "generation_config.yaml"), "w") as f:
        yaml.safe_dump(cfg, f, sort_keys=False)
    return scene, len(entries), time.time() - t0


# --------------------------------------------------------------------------------------
# CLI
# --------------------------------------------------------------------------------------

def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--config", help="YAML config (see configs/)")
    ap.add_argument("--input", required=True, help="split folder with the extracted base files, e.g. synclight_raw/infinigen/train")
    ap.add_argument("--output", help="where to write the pairs (mirrors the scene folders of --input)")
    ap.add_argument("--set", nargs="*", default=[], metavar="KEY=VALUE", help="override config values, e.g. pairs.per_light=10")
    ap.add_argument("--scenes", nargs="*", help="only these scenes (relative paths, e.g. Bathroom/10)")
    ap.add_argument("--workers", type=int, default=4)
    ap.add_argument("--dry-run", action="store_true", help="only count the pairs/images each scene would get")
    ap.add_argument("--overwrite", action="store_true", help="regenerate scenes that already have a transforms.json")
    args = ap.parse_args()

    cfg = load_config(args.config, args.set)
    scenes = find_scenes(args.input, cfg["source"])
    if args.scenes:
        scenes = [s for s in scenes if s in args.scenes]
    if not scenes:
        raise SystemExit(f"no {cfg['source']} scenes found in {args.input}")

    if args.dry_run:
        tp = ti = 0
        for s in scenes:
            rigs, plan = plan_scene(cfg, args.input, s)
            p, i = count_pairs(cfg, rigs, plan)
            tp, ti = tp + p, ti + i
            print(f"{s}: {p} pairs, {i} images")
        print(f"total: {len(scenes)} scenes, {tp} pairs, {ti} images")
        return

    if not args.output:
        raise SystemExit("--output is required unless --dry-run")
    todo = [s for s in scenes if args.overwrite or not os.path.exists(
        os.path.join(args.output, s, cfg["output_subdir"], "transforms.json"))]
    print(f"{len(scenes)} scenes, {len(scenes) - len(todo)} already done, generating {len(todo)}", flush=True)
    with ProcessPoolExecutor(args.workers) as ex:
        futs = {ex.submit(render_scene, cfg, args.input, args.output, s): s for s in todo}
        for k, fut in enumerate(as_completed(futs), 1):
            try:
                s, n, dt = fut.result()
                print(f"[{k}/{len(todo)}] {s}: {n} pairs in {dt:.0f}s", flush=True)
            except Exception as e:
                print(f"[{k}/{len(todo)}] {futs[fut]}: FAILED {e!r}", flush=True)


if __name__ == "__main__":
    main()