File size: 31,282 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
870b85a
 
 
 
 
3f15e9f
 
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
870b85a
 
 
 
 
 
 
 
3f15e9f
 
870b85a
 
3f15e9f
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Render source-bound whole-house visibility evidence, without saving the scene.

Usage (launch is deliberately left to the caller):
  blender --background --python-exit-code 1 --python render_wholehouse.py -- \
    --scene SAVED_SCENE --output NEW_DIRECTORY --device CPU [--plan FINAL_PLAN]

The output contains wholehouse_visibility_evidence.json, visibility_plan.json,
visibility_audit.json and RGB PNG / raw float depth, object-index and
material-index EXR files. Room floor regions are validated against saved mesh
geometry before their transient, shader-preserving material IDs are assigned.
files_sha256 paths are relative to the output directory. The manifest hash is
over composition_manifest.runtime.json bytes, not reserialized JSON. A supplied
plan controls resolution and exact cameras; its source bindings and geometry
must agree with the saved scene. Cycles object/material-index pixels with
measured depth establish sampled entity/room-floor visibility. No cutaways, new lights or geometry repairs
are applied. An outer process timeout is still needed for a blocked Blender op.
"""
from __future__ import annotations

import argparse
from array import array
import hashlib
import importlib.util
import json
import math
import os
from pathlib import Path
import subprocess
import sys
import time
import traceback

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from visibility_plan import INTERIOR_RENDER_PROFILE, audit_visibility, build_visibility_plan


EVIDENCE_NAME = 'wholehouse_visibility_evidence.json'


def parse_args(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--scene', type=Path, required=True)
    parser.add_argument('--output', type=Path, required=True)
    parser.add_argument('--plan', type=Path)
    parser.add_argument('--device', choices=('CPU', 'GPU'), default='CPU')
    parser.add_argument('--gpu-backend', choices=('OPTIX', 'CUDA', 'HIP', 'METAL', 'ONEAPI'), default='OPTIX')
    parser.add_argument('--width', type=int, default=INTERIOR_RENDER_PROFILE['width'])
    parser.add_argument('--height', type=int, default=INTERIOR_RENDER_PROFILE['height'])
    parser.add_argument('--samples', type=int, default=INTERIOR_RENDER_PROFILE['samples'])
    parser.add_argument('--denoise', action=argparse.BooleanOptionalAction, default=True)
    parser.add_argument('--diagnostic-overviews', action='store_true',
                        help='Also render optional top/oblique diagnostics; primary views stay interior')
    parser.add_argument('--time-budget-s', type=float, default=INTERIOR_RENDER_PROFILE['time_budget_s'])
    if argv is None:
        argv = sys.argv[sys.argv.index('--')+1:] if '--' in sys.argv else sys.argv[1:]
    args = parser.parse_args(argv)
    if min(args.width, args.height, args.samples) <= 0:
        parser.error('width, height and samples must be positive')
    if not math.isfinite(args.time_budget_s) or args.time_budget_s <= 0:
        parser.error('time-budget-s must be positive and finite')
    return args


def digest(path):
    value = hashlib.sha256()
    with Path(path).open('rb') as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b''):
            value.update(block)
    return value.hexdigest()


def save(path, value):
    # Replace only our own receipt, so interrupted writes retain the last receipt.
    temporary = path.with_suffix(path.suffix+'.tmp')
    temporary.write_text(json.dumps(value, indent=2, allow_nan=False)+'\n', encoding='utf-8')
    temporary.replace(path)


def snapshot(scene):
    return {p.relative_to(scene).as_posix(): digest(p)
            for p in sorted(scene.rglob('*')) if p.is_file()}


def load_inputs(args):
    scene = args.scene.resolve()
    manifest_path = scene/'composition_manifest.runtime.json'
    manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
    scene_id = manifest.get('scene_id')
    if not isinstance(scene_id, str) or not scene_id or Path(scene_id).name != scene_id:
        raise ValueError('Manifest requires a safe scene_id')
    blend = (scene/(scene_id+'.blend')).resolve()
    if blend.parent != scene or not blend.is_file():
        raise ValueError('Saved source blend missing or outside scene')
    return manifest_path, manifest, blend


def resolve_plan(args, manifest, blend_sha, manifest_sha):
    for key, actual in (('source_sha256', blend_sha), ('blend_sha256', blend_sha),
                        ('source_manifest_sha256', manifest_sha)):
        if manifest.get(key) is not None and manifest[key] != actual:
            raise ValueError('Manifest source hash differs: '+key)
    bound = dict(manifest, source_sha256=blend_sha, source_manifest_sha256=manifest_sha)
    if args.plan:
        plan = json.loads(args.plan.read_text(encoding='utf-8'))
        if not isinstance(plan, dict):
            raise ValueError('Visibility plan must be an object')
        expected = build_visibility_plan(bound, width=plan.get('width'), height=plan.get('height'))
        # Manifest binding is optional for older saved plans. Cameras and all
        # geometric/target parameters must still match exactly; never refit them.
        for key, value in expected.items():
            if key == 'floor_region_room_ids' and key not in plan:
                # Rebind the new explicit region order from this exact source
                # manifest; sorted JSON object keys cannot encode native slots.
                plan[key] = value
            if key == 'source_manifest_sha256' and plan.get(key) is None:
                continue
            if plan.get(key) != value:
                raise ValueError('Visibility plan differs from source: '+key)
        return plan
    return build_visibility_plan(bound, width=args.width, height=args.height)


def measure_rgb(values, width, height, channels):
    if channels not in (3, 4) or len(values) != width*height*channels:
        raise ValueError('Decoded RGB buffer size differs')
    low, high = [math.inf]*3, [-math.inf]*3
    for start in range(0, len(values), channels):
        for channel in range(3):
            value = values[start+channel]
            if not math.isfinite(value):
                raise ValueError('Nonfinite RGB pixels')
            low[channel] = min(low[channel], value)
            high[channel] = max(high[channel], value)
    variation = max(b-a for a, b in zip(low, high))
    return dict(nonblank=max(high) >= .005 and variation >= .005,
                spatial_range=variation, channel_min=low, channel_max=high)


def measure_passes(indices, depths, width, height, index_map, clip_end):
    if len(indices) != width*height or len(depths) != len(indices):
        raise ValueError('Decoded pass buffer sizes differ')
    counts = {target: 0 for target in index_map}
    by_index = {index: target for target, index in index_map.items()}
    if len(by_index) != len(index_map):
        raise ValueError('Ambiguous object indices')
    valid, minimum, maximum = 0, math.inf, 0.
    for raw, depth in zip(indices, depths):
        if not math.isfinite(raw) or raw < 0 or raw != round(raw):
            raise ValueError('Noninteger or nonfinite object-index pixels')
        index = int(raw)
        if index and index not in by_index:
            raise ValueError('Unmapped object-index pixels')
        # Blender Z background can be infinity or a large finite sentinel.
        hit = math.isfinite(depth) and 0 < depth <= clip_end
        if math.isnan(depth) or depth <= 0 or (index and not hit):
            raise ValueError('Invalid depth for object-index pixels')
        if hit:
            valid += 1
            minimum, maximum = min(minimum, depth), max(maximum, depth)
            if index:
                counts[by_index[index]] += 1
    return dict(target_pixels=counts, depth=dict(valid_pixels=valid,
                min_m=minimum if valid else None, max_m=maximum if valid else None))


def decode(bpy, path, width, height, *, scalar=False):
    image = bpy.data.images.load(str(path), check_existing=False)
    try:
        if scalar:
            image.colorspace_settings.name = 'Non-Color'
        dimensions = list(image.size)
        if dimensions != [width, height]:
            raise ValueError('Decoded image dimensions differ: '+str(path))
        channels = image.channels
        values = array('f', [0.])*len(image.pixels)
        image.pixels.foreach_get(values)
        if not values or len(values) != width*height*channels:
            raise ValueError('Decoded image has incomplete pixels')
        receipt = dict(decoded=True, dimensions=dimensions, sha256=digest(path))
        if scalar:
            return receipt, values[::channels]
        receipt.update(measure_rgb(values, width, height, channels))
        return receipt, None
    finally:
        bpy.data.images.remove(image)


def configure(bpy, args, plan):
    scene = bpy.context.scene
    if not math.isclose(scene.unit_settings.scale_length, 1., rel_tol=0., abs_tol=1e-9):
        raise ValueError('Saved scene units must match metre-based visibility plan')
    scene.render.engine = 'CYCLES'
    scene.cycles.device = args.device
    scene.cycles.samples = args.samples
    scene.cycles.use_denoising = getattr(args, 'denoise', True)
    device_receipt = dict(device=args.device, backend='CPU', devices=[])
    if args.device == 'GPU':
        preferences = bpy.context.preferences.addons['cycles'].preferences
        preferences.compute_device_type = args.gpu_backend
        preferences.get_devices()
        devices = [d for d in preferences.devices if d.type == args.gpu_backend]
        if not devices:
            raise RuntimeError('Requested Cycles GPU backend unavailable')
        for device in preferences.devices:
            device.use = device.type == args.gpu_backend
        device_receipt.update(backend=args.gpu_backend, devices=[d.name for d in devices])
    scene.render.resolution_x, scene.render.resolution_y = plan['width'], plan['height']
    scene.render.resolution_percentage = 100
    scene.render.pixel_aspect_x = scene.render.pixel_aspect_y = 1
    scene.render.use_border = False
    scene.render.use_multiview = False
    scene.render.use_sequencer = False
    scene.render.use_compositing = True
    scene.render.use_file_extension = True
    scene.render.use_motion_blur = False
    if hasattr(scene.render.image_settings, 'media_type'):
        scene.render.image_settings.media_type = 'IMAGE'
    scene.render.image_settings.file_format = 'PNG'
    scene.render.image_settings.color_mode = 'RGB'
    scene.render.image_settings.color_depth = '8'
    layer = bpy.context.view_layer
    for other in scene.view_layers:
        other.use = other == layer
    layer.use_pass_z = True
    layer.use_pass_object_index = True
    layer.use_pass_material_index = True
    layer.pass_alpha_threshold = .5
    layer.material_override = None
    bpy.context.view_layer.update()
    return dict(device_receipt, samples=scene.cycles.samples,
                denoise=scene.cycles.use_denoising, pass_alpha_threshold=.5)


def assign_indices(bpy, plan):
    meshes = {target: [] for target in plan['target_ids']}
    for obj in bpy.context.scene.objects:
        obj.pass_index = 0
        if obj.type != 'MESH':
            continue
        # Follow explicit parent metadata for multi-part imported assets. Names
        # alone cannot establish entity identity.
        parent, target = obj, None
        while parent is not None and target is None:
            target = parent.get('entity_id')
            parent = parent.parent
        if target is not None and target not in meshes:
            raise ValueError('Mesh has undeclared entity_id: '+str(target))
        if target is not None:
            meshes[target].append(obj)
    if len(meshes) > 32767:
        raise ValueError('Object-index capacity exceeded')
    mapping, objects = {}, {}
    for index, (target, parts) in enumerate(sorted(meshes.items()), 1):
        if not parts:
            continue
        mapping[target] = index
        objects[target] = sorted(obj.name for obj in parts)
        for obj in parts:
            obj.pass_index = index
    return mapping, objects



def assign_room_indices(bpy, plan, floor_plan, binding):
    """Validate saved native top faces before adding transient material pass IDs.

    Copies preserve every RGB shader; only floor top material slots receive IDs.
    No scene is saved, and shared furniture/source materials remain unindexed.
    """
    mapping = {rid: index for index, rid in enumerate(plan['room_ids'], 1)}
    if len(mapping) > 32767:
        raise ValueError('Room material-index capacity exceeded')
    regions, assignments = {}, []
    slab = bpy.data.objects.get('floor__whole_house')
    if slab is not None:
        helper = Path(__file__).resolve().parents[1]/'source/scripts/internal/scene_generation/floor_slab.py'
        spec = importlib.util.spec_from_file_location('_visibility_native_floor_slab', helper)
        native = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(native)
        report = native.audit_floor_slab(bpy, floor_plan)
        if (report['room_ids'] != plan['floor_region_room_ids']
                or any(getattr(m, 'show_render', True) for m in slab.modifiers)):
            raise ValueError('Floor slab room identities or render modifiers differ')
        for slot, rid in enumerate(report['room_ids'], 1):
            faces = sum(p.normal.z >= .999999 and p.material_index == slot for p in slab.data.polygons)
            regions[rid] = dict(object_name=slab.name, material_slots=[slot], index=mapping[rid],
                top_face_count=faces, top_face_area_m2=report['room_top_face_area_m2'][rid])
            assignments.append((slab, slot, rid))
        geometry_schema = 'rhg.continuous-room-partitioned-floor.v1'
    else:
        geometry_schema = 'rhg.legacy-room-floor.v1'
        # Native legacy floors are one rectangular top quad at z=0 with explicit
        # room_id. Names select candidates; metadata and world geometry bind them.
        for rid, box in plan['room_bounds_m'].items():
            obj = bpy.data.objects.get('floor__'+rid)
            if (obj is None or obj.type != 'MESH' or obj.get('room_id') != rid
                    or any(getattr(m, 'show_render', True) for m in obj.modifiers)):
                raise ValueError('Legacy floor room identity or modifiers differ: '+rid)
            top = [p for p in obj.data.polygons if p.normal.z >= .999999]
            lo, hi = box
            corners = {(round(x,5),round(y,5)) for x in (lo[0],hi[0]) for y in (lo[1],hi[1])}
            if len(top) != 1:
                raise ValueError('Legacy floor requires its authored rectangular top: '+rid)
            points = [obj.matrix_world @ obj.data.vertices[i].co for i in top[0].vertices]
            if (len(points) != 4 or any(abs(p.z) > 1e-6 for p in points)
                    or {(round(p.x,5),round(p.y,5)) for p in points} != corners):
                raise ValueError('Legacy floor top geometry differs from room bounds: '+rid)
            original_slot = top[0].material_index
            if not 0 <= original_slot < len(obj.material_slots):
                raise ValueError('Legacy floor top material missing: '+rid)
            # Detach the mesh before changing top slot assignments; shared mesh
            # data must not spread room IDs to another object.
            obj.data = obj.data.copy()
            source = obj.material_slots[original_slot].material
            if source is None:
                raise ValueError('Legacy floor top material missing: '+rid)
            material = source.copy()
            material.pass_index = mapping[rid]
            slot = len(obj.data.materials)
            obj.data.materials.append(material)
            for polygon in obj.data.polygons:
                if polygon.normal.z >= .999999:
                    polygon.material_index = slot
            regions[rid] = dict(object_name=obj.name, material_slots=[slot], index=mapping[rid],
                top_face_count=1, top_face_area_m2=(hi[0]-lo[0])*(hi[1]-lo[1]))
    # Reset saved indices before attaching isolated top-face copies.
    for material in bpy.data.materials:
        material.pass_index = 0
    if slab is None:
        for rid, region in regions.items():
            obj = bpy.data.objects.get(region['object_name'])
            obj.data.materials[region['material_slots'][0]].pass_index = mapping[rid]
    for obj, slot, rid in assignments:
        source = obj.material_slots[slot].material
        if source is None:
            raise ValueError('Room floor material missing: '+rid)
        material = source.copy()
        material.pass_index = mapping[rid]
        obj.material_slots[slot].link = 'OBJECT'
        obj.material_slots[slot].material = material
    return mapping, dict(schema='rhg.room-floor-index.v1', passed=True,
        geometry_schema=geometry_schema, room_bounds_m=plan['room_bounds_m'],
        region_room_ids=plan['floor_region_room_ids'],
        regions=regions, **binding)


def compositor(bpy, directory):
    scene = bpy.context.scene
    if hasattr(scene, 'compositing_node_group'):
        tree = bpy.data.node_groups.new('WholehouseEvidence', 'CompositorNodeTree')
        scene.compositing_node_group = tree
        tree.interface.new_socket(name='Image', in_out='OUTPUT', socket_type='NodeSocketColor')
        output = tree.nodes.new('NodeGroupOutput')
    else:
        scene.use_nodes = True
        tree = scene.node_tree
        tree.nodes.clear()
        output = tree.nodes.new('CompositorNodeComposite')
    layers = tree.nodes.new('CompositorNodeRLayers')
    layers.layer = bpy.context.view_layer.name
    tree.links.new(layers.outputs['Image'], output.inputs['Image'])
    for name, socket_names in (('depth', ('Depth',)), ('object_index', ('Object Index', 'IndexOB')),
                               ('material_index', ('Material Index', 'IndexMA'))):
        folder = directory/name
        folder.mkdir()
        node = tree.nodes.new('CompositorNodeOutputFile')
        if hasattr(node, 'file_output_items'):
            node.directory = str(folder)
            node.file_name = name
            node.format.media_type = 'IMAGE'
            node.file_output_items.clear()
            item = node.file_output_items.new('FLOAT', name)
            item.override_node_format = False
            item.save_as_render = False
            node.save_as_render = False
        else:
            node.base_path = str(folder)
            node.file_slots[0].path = name
            node.file_slots[0].save_as_render = False
        node.format.file_format = 'OPEN_EXR'
        node.format.color_depth = '32'
        node.format.color_mode = 'BW'
        node.format.exr_codec = 'ZIP'
        socket = next((layers.outputs.get(s) for s in socket_names if layers.outputs.get(s) is not None), None)
        if socket is None:
            raise RuntimeError('Cycles render pass unavailable: '+name)
        tree.links.new(socket, node.inputs[0])


def configure_camera(data, camera):
    projection = camera.get('projection')
    if projection not in ('PERSP', 'ORTHO'):
        raise ValueError('Unsupported camera projection')
    fields = ['clip_start', 'clip_end'] + (
        ['lens_mm', 'sensor_width_mm'] if projection == 'PERSP' else ['ortho_scale'])
    if any(type(camera.get(k)) not in (int, float) or not math.isfinite(camera[k])
           or camera[k] <= 0 for k in fields):
        raise ValueError('Invalid finite camera optics')
    if camera['clip_start'] >= camera['clip_end']:
        raise ValueError('Reversed camera clipping interval')
    if projection == 'PERSP':
        shift = camera.get('shift_y', 0.)
        if (camera.get('sensor_fit') != 'HORIZONTAL' or type(shift) not in (int, float)
                or not math.isfinite(shift) or abs(shift) > 1):
            raise ValueError('Invalid perspective sensor or lens shift')
        data.lens = camera['lens_mm']
        data.sensor_width = camera['sensor_width_mm']
        data.sensor_fit = 'HORIZONTAL'
        data.shift_y = shift
    else:
        data.ortho_scale = camera['ortho_scale']
        data.sensor_fit = 'AUTO'
    data.type = projection
    data.clip_start, data.clip_end = camera['clip_start'], camera['clip_end']


def view_time_budget(remaining_s, remaining_views):
    if (type(remaining_s) not in (int, float) or not math.isfinite(remaining_s)
            or remaining_s <= 0 or type(remaining_views) is not int or remaining_views <= 0):
        raise ValueError('Positive finite per-view render budget required')
    return remaining_s/remaining_views


def render_view(bpy, camera, directory, plan, index_map, binding, remaining_s, room_index_map=None):
    from mathutils import Vector
    directory.mkdir()
    scene = bpy.context.scene
    data = bpy.data.cameras.new('wholehouse_'+camera['camera_id'])
    obj = bpy.data.objects.new(data.name, data)
    scene.collection.objects.link(obj)
    obj.location = camera['location']
    obj.rotation_euler = (Vector(camera['target'])-obj.location).to_track_quat('-Z', 'Y').to_euler()
    configure_camera(data, camera)
    scene.camera = obj
    compositor(bpy, directory)
    rgb = directory/'rgb.png'
    scene.render.filepath = str(rgb)
    scene.cycles.time_limit = max(.001, remaining_s)
    bpy.context.view_layer.update()
    started = time.monotonic()
    rendered = bpy.ops.render.render(write_still=True)
    if 'FINISHED' not in rendered:
        raise RuntimeError('Blender render did not finish')
    paths = {'image': rgb}
    for name in ('depth', 'object_index', 'material_index'):
        matches = list((directory/name).glob('*.exr'))
        if len(matches) != 1:
            raise ValueError('Expected exactly one saved '+name+' pass')
        paths[name] = matches[0]
    image, _ = decode(bpy, rgb, plan['width'], plan['height'])
    depth, depths = decode(bpy, paths['depth'], plan['width'], plan['height'], scalar=True)
    instance, indices = decode(bpy, paths['object_index'], plan['width'], plan['height'], scalar=True)
    measured = measure_passes(indices, depths, plan['width'], plan['height'], index_map, data.clip_end)
    room_pass, room_indices = decode(bpy, paths['material_index'], plan['width'], plan['height'], scalar=True)
    rooms = measure_passes(room_indices, depths, plan['width'], plan['height'], room_index_map or {}, data.clip_end)
    depth.update(measured['depth'])
    view = dict(camera_id=camera['camera_id'], camera=camera, rendered=True,
                image=image, depth=depth, object_index=instance, material_index=room_pass,
                room_mask_source='material_index', room_pixels=rooms['target_pixels'],
                mask_source='object_index', target_pixels=measured['target_pixels'],
                render_elapsed_s=time.monotonic()-started, **binding)
    for key, path in paths.items():
        view[key]['path'] = path.relative_to(directory.parent).as_posix()
    bpy.data.objects.remove(obj, do_unlink=True)
    bpy.data.cameras.remove(data)
    return view


def camera_schedule(plan, diagnostic_overviews=False):
    return sorted(((i, camera) for i, camera in enumerate(plan['cameras'])
                   if diagnostic_overviews or camera.get('purpose') != 'diagnostic'),
                  key=lambda row: not row[1]['required'])


def write_review_artifacts(output):
    # Blender need not bundle Pillow. Postprocess measured images on the host;
    # this subprocess never opens the source scene or launches another render.
    script = (
        'import importlib,json,sys; from pathlib import Path; '
        'root=Path(sys.argv[1]); sys.path.insert(0,str(root.parent)); '
        'write_interior_contact_sheet=importlib.import_module(root.name+".real_test.remote_gpu_render").write_interior_contact_sheet; '
        'print(json.dumps(write_interior_contact_sheet(Path(sys.argv[2]), '
        'render_directory=Path(sys.argv[2]))))')
    environment = dict(os.environ)
    from source.scripts.internal.scene_generation.real_assets.stage_checkpoint import subprocess_timeout
    if environment.get('RHG_REVIEW_SITE'):
        environment['PYTHONPATH'] = environment['RHG_REVIEW_SITE']
    completed = subprocess.run(
        [environment.get('RHG_REVIEW_PYTHON', sys.executable), '-B', '-c', script,
         str(Path(__file__).resolve().parents[1]), str(output)],
        capture_output=True, text=True, timeout=subprocess_timeout('RHG_REVIEW_ARTIFACT_TIMEOUT_S'),
        check=True, env=environment)
    return json.loads(completed.stdout)


def run(args):
    scene, output = args.scene.resolve(), args.output.resolve()
    if scene == output or scene in output.parents or output in scene.parents:
        raise ValueError('Render output must be isolated outside source scene')
    output.mkdir(parents=True, exist_ok=False)
    started = time.monotonic()
    receipt = dict(schema='rhg.wholehouse-visibility-evidence.v1', passed=False,
                   renderer='BLENDER_CYCLES', source_unchanged=False, render_completed=False, views=[],
                   files_sha256={}, physical_qualified=False, whole_task_acceptance=False)
    before, blend, plan = None, None, None
    try:
        before = snapshot(scene)
        receipt['source_files_sha256'] = before
        manifest_path, manifest, blend = load_inputs(args)
        receipt.update(scene_id=manifest['scene_id'], source_blend=str(blend),
                       source_sha256=digest(blend), source_manifest_sha256=digest(manifest_path))
        plan = resolve_plan(args, manifest, receipt['source_sha256'], receipt['source_manifest_sha256'])
        save(output/'visibility_plan.json', plan)
        if args.plan:
            receipt['input_plan_sha256'] = digest(args.plan)
        save(output/EVIDENCE_NAME, receipt)
        import bpy
        bpy.ops.wm.open_mainfile(filepath=str(blend))
        receipt['blender_version'] = bpy.app.version_string
        receipt['execution'] = configure(bpy, args, plan)
        receipt['object_index_map'], receipt['entity_objects'] = assign_indices(bpy, plan)
        budget = min(args.time_budget_s, plan['time_budget_s'])
        binding = {key: receipt[key] for key in ('scene_id', 'source_sha256', 'source_manifest_sha256')}
        receipt['room_index_map'], receipt['room_structure'] = assign_room_indices(
            bpy, plan, manifest.get('floor_plan', manifest), binding)
        overviews = getattr(args, 'diagnostic_overviews', False)
        ordered = camera_schedule(plan, overviews)
        for position, (index, camera) in enumerate(ordered):
            if not camera['required'] and not (overviews and camera.get('purpose') == 'diagnostic'):
                interim = {k: v for k, v in receipt.items() if k not in ('passed', 'render_completed')}
                interim.update(source_unchanged=True, source_sha256_after=receipt['source_sha256'])
                if camera['camera_id'] not in audit_visibility(plan, interim)['alternative_camera_ids']:
                    continue
            remaining = budget-(time.monotonic()-started)
            if remaining <= 0:
                raise TimeoutError('Wholehouse rendering time budget exhausted')
            receipt['active_camera_id'] = camera['camera_id']
            save(output/EVIDENCE_NAME, receipt)
            required_left = sum(c['required'] for _, c in ordered[position:])
            view = render_view(bpy, camera, output/('view_%03d' % index), plan,
                receipt['object_index_map'], binding,
                view_time_budget(remaining, max(1, required_left)), receipt['room_index_map'])
            receipt['views'].append(view)
            for key in ('image', 'depth', 'object_index', 'material_index'):
                item = view[key]
                receipt['files_sha256'][item['path']] = item['sha256']
            save(output/EVIDENCE_NAME, receipt)
            if time.monotonic()-started > budget:
                raise TimeoutError('Wholehouse render exceeded time budget')
        receipt.pop('active_camera_id', None)
        receipt['render_completed'] = True
    except Exception as error:
        receipt['execution_error'] = dict(type=type(error).__name__, message=str(error))
        receipt.update(error_type=type(error).__name__, error=str(error))
        (output/'failure_traceback.txt').write_text(traceback.format_exc(), encoding='utf-8')
    finally:
        try:
            receipt['source_unchanged'] = before is not None and snapshot(scene) == before
            if blend is not None:
                receipt['source_sha256_after'] = digest(blend)
            if not receipt['source_unchanged']:
                receipt['source_integrity_error'] = dict(
                    type='SourceIntegrityError', message='Source scene files changed')
                receipt.update(error_type='SourceIntegrityError', error='Source scene files changed')
        except OSError as error:
            receipt['source_integrity_error'] = dict(type=type(error).__name__, message=str(error))
            receipt.update(source_unchanged=False, error_type=type(error).__name__, error=str(error))
        # Include every produced data file even when decoding failed partway.
        receipt['files_sha256'] = {p.relative_to(output).as_posix(): digest(p)
                                    for p in sorted(output.rglob('*'))
                                    if p.is_file() and p.suffix in ('.png', '.exr')}
        if plan is not None:
            provisional = {k: v for k, v in receipt.items() if k != 'passed'}
            audit = audit_visibility(plan, provisional)
            receipt['passed'] = audit['passed'] and receipt.get('render_completed') is True
            save(output/'visibility_audit.json', audit)
        receipt['elapsed_s'] = round(time.monotonic()-started, 3)
        save(output/EVIDENCE_NAME, receipt)
        if any(v.get('camera', {}).get('purpose') == 'interior_human_eye'
               for v in receipt['views']):
            try:
                receipt['interior_contact_sheet'] = write_review_artifacts(output)
                names = ('selectedroomviews.json', 'interior_contact_sheet.png')
                receipt['review_artifacts_sha256'] = {name: digest(output/name) for name in names}
                receipt['files_sha256']['interior_contact_sheet.png'] = digest(output/'interior_contact_sheet.png')
            except Exception as error:
                receipt['review_artifacts_error'] = str(error)
                if not receipt.get('error_type'):
                    receipt.update(error_type=type(error).__name__, error='Room review artifacts failed: '+str(error))
            save(output/EVIDENCE_NAME, receipt)
    return receipt


def main(argv=None):
    result = run(parse_args(argv))
    print(json.dumps(result, allow_nan=False), flush=True)
    # Coverage failures are valid evidence for the caller's auditor and repair
    # loop. Reserve a failed command for incomplete execution or changed source.
    completed = (result.get('render_completed') is True
                 and result.get('source_unchanged') is True
                 and not result.get('error_type'))
    return 0 if completed else 1


if __name__ == '__main__':
    raise SystemExit(main())