Datasets:
File size: 13,124 Bytes
3f15e9f | 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 | """Verify production window preparation in a new scene and render every declared window."""
import argparse
from array import array
import hashlib
import json
import os
import subprocess
from pathlib import Path
import sys
import time
def sha(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def save(path, value):
Path(path).write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n')
def geometry(bpy):
records = {}
for obj in bpy.context.scene.objects:
if obj.type != 'MESH':
continue
co = array('f', [0.]) * (3 * len(obj.data.vertices))
vi = array('i', [0]) * len(obj.data.loops)
obj.data.vertices.foreach_get('co', co)
obj.data.loops.foreach_get('vertex_index', vi)
records[obj.name] = {
'mesh_sha256': hashlib.sha256(co.tobytes() + vi.tobytes()).hexdigest(),
'matrix': [list(row) for row in obj.matrix_world],
'materials': [s.material.name if s.material else None for s in obj.material_slots],
}
return records
def verify_frames(bpy, receipt, windows):
assert receipt['assigned_window_count'] == len(windows)
assert {r['window_id'] for r in receipt['records']} == {w['window_id'] for w in windows}
expected_rgb = [((v/255+.055)/1.055)**2.4 for v in (59, 64, 69)] + [1.]
names = set()
for row in receipt['records']:
assert row['objects']
for name in row['objects']:
obj = bpy.data.objects[name]
assert name.startswith('frame__' + row['window_id'] + '__')
names.add(name)
assert obj.material_slots
for slot in obj.material_slots:
mat = slot.material
assert mat and mat.name == 'rhg_window_frame_dark_gray_aluminum_v1'
shader = next(n for n in mat.node_tree.nodes if n.type == 'BSDF_PRINCIPLED')
assert all(abs(a-b) < 1e-6 for a,b in zip(shader.inputs['Base Color'].default_value, expected_rgb))
for key, value in [('Metallic', .85), ('Roughness', .30), ('Coat Weight', .12)]:
assert abs(shader.inputs[key].default_value-value) < 1e-6
assert len(names) == receipt['frame_object_count']
return names
def window_camera(bpy, row, window, room, entities):
"""Frame each actual window from inside its room without moving furniture."""
from mathutils import Vector
target = Vector([sum(v[i] for v in row['vertices_m'])/4 for i in range(3)])
axis = 1 if window['wall_orientation'] == 'H' else 0
tangent, sign = 1-axis, 1 if window['side'] in ('N', 'E') else -1
bounds = room['bounds_m']
width = window['window_width_m']
height = window['head_height_m'] - window['sill_height_m']
preferred = max(1.7, width*.85)
boxes = [e['world_bbox_m'] for e in entities if e['room_id'] == row['room_id']]
graph = bpy.context.evaluated_depsgraph_get()
allowed = {row['object'], row['glass_object']}
candidates = []
for distance in [preferred, preferred+.5, preferred-.5, 1., 1.5, 2., 2.5, 3.]:
for offset in [0., -.4, .4, -.8, .8]:
eye = target.copy()
eye[axis] -= sign*distance
eye[tangent] += offset
eye.z = 1.6
if not all(bounds[i]+.22 <= eye[i] <= bounds[i+2]-.22 for i in (0,1)):
continue
if any(all(lo[i]-.08 < eye[i] < hi[i]+.08 for i in range(3)) for lo, hi in boxes):
continue
visible = 0
for x in [-.32, 0., .32]:
for z in [-.25, .25]:
point = target.copy(); point[tangent] += x*width; point.z += z*height
direction = point-eye
hit, _, _, _, obj, _ = bpy.context.scene.ray_cast(graph, eye, direction.normalized(), distance=direction.length+.15)
if not hit or obj.name in allowed or obj.name.startswith('frame__'+window['window_id']+'__'):
visible += 1
candidates.append(((visible, -abs(offset), -abs(distance-preferred)), eye))
if not candidates:
raise ValueError('No in-room camera for ' + row['window_id'])
score, eye = max(candidates, key=lambda item: item[0])
depth = abs(target[axis]-eye[axis])
lens = min(32., 36*depth/(width*1.25), (36*720/1280)*depth/(height*1.25))
return {'name': window['window_id'], 'room_id': row['room_id'], 'window_id': window['window_id'],
'projection': 'PERSP', 'location': list(eye), 'target': list(target),
'lens_mm': max(10., lens), 'sensor_width_mm': 36., 'sensor_fit': 'HORIZONTAL',
'shift_y': 0., 'clip_start': .04, 'clip_end': 100., 'visible_window_probe_count': score[0]}
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--code-root', type=Path, required=True)
parser.add_argument('--scene', type=Path, required=True)
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args(sys.argv[sys.argv.index('--') + 1:])
root, source, output = args.code_root.resolve(), args.scene.resolve(), args.output.resolve()
if output == source or source in output.parents:
raise ValueError('Require a separate new output directory')
output.mkdir(parents=True, exist_ok=False)
native_code = root / 'engine/source/scripts/internal/scene_generation/real_assets'
for path in [root, root / 'engine', root / 'engine/source', native_code.parent, native_code.parent / 'base', native_code]:
sys.path.insert(0, str(path))
import bpy
from mathutils import Vector
from scene_delivery import prepare
from presentation_windows import create, show_for_view, apply_window_frame_materials, audit_window_scenery
from real_test import render_wholehouse as renderer
composition = json.loads((source / 'composition_manifest.runtime.json').read_text())
native_manifest = json.loads((source / 'SceneManifest.v16.json').read_text())
blend = source / (composition['scene_id'] + '.blend')
source_hash = sha(blend)
# The controller and Blender use different Python builds. Execute the
# production policy in its controller environment, just as prepare() does.
command = ('import json; from residential_profile import load_profile, apply_policy; '
'runtime={"window_scenery":None}; '
'receipt=apply_policy({},runtime,load_profile(),{}); '
'print(json.dumps({"runtime":runtime,"policy":receipt}))')
env = dict(os.environ, PYTHONPATH=str(root / 'engine/supervisor_site') + ':' + str(root))
resolved = json.loads(subprocess.check_output(
['/usr/bin/python3', '-B', '-c', command], cwd=root, env=env, text=True))
runtime, policy = resolved['runtime'], resolved['policy']
save(output / 'effective_residential_policy.json', policy)
save(output / 'runtime.json', runtime)
started = time.monotonic()
bpy.ops.wm.open_mainfile(filepath=str(blend))
original = geometry(bpy)
original_delivery = json.loads(bpy.context.scene['rhg_scene_delivery'])
delivery = prepare(bpy, composition, native_manifest, runtime['window_scenery'], lighting=False)
delivery['lighting'] = original_delivery.get('lighting')
bpy.context.scene['rhg_scene_delivery'] = json.dumps(delivery, ensure_ascii=False)
frame_receipt = delivery.get('window_frames')
assert frame_receipt and frame_receipt['complete'], 'Missing all-window dark aluminum frame delivery'
records = delivery['window_scenery']['records']
windows = composition['floor_plan']['windows']
assert len(records) == len(windows) > 0
assert {r['window_id'] for r in records} == {w['window_id'] for w in windows}
frame_names = verify_frames(bpy, frame_receipt, windows)
after = geometry(bpy)
for name, before in original.items():
assert after[name]['mesh_sha256'] == before['mesh_sha256'], 'Original mesh changed: ' + name
assert after[name]['matrix'] == before['matrix'], 'Original transform changed: ' + name
if name not in frame_names:
assert after[name]['materials'] == before['materials'], 'Non-window material changed: ' + name
assert set(after) - set(original) == {r['object'] for r in records}
for row in records:
obj = bpy.data.objects[row['object']]
images = [n.image for n in obj.data.materials[0].node_tree.nodes if n.type == 'TEX_IMAGE']
assert images and all(im.packed_file for im in images), 'Exterior texture was not packed'
assert not obj.hide_render
assert bpy.data.objects[row['glass_object']].hide_render == (not row['preserve_frosted_glass'])
repeated = create(bpy, composition['floor_plan'], runtime['window_scenery'], persistent=True)
assert apply_window_frame_materials(bpy, composition['floor_plan']) == frame_receipt
assert audit_window_scenery(bpy, composition['floor_plan'], repeated)['complete']
show_for_view(bpy, repeated, {})
assert geometry(bpy) == after
assert verify_frames(bpy, frame_receipt, windows) == frame_names
for row in repeated['records']:
assert bpy.data.objects[row['glass_object']].hide_render == (not row['preserve_frosted_glass'])
scene_dir = output / 'scene'
scene_dir.mkdir()
for name in ['composition_manifest.runtime.json', 'SceneManifest.v16.json']:
(scene_dir / name).write_bytes((source / name).read_bytes())
save(scene_dir / 'scene_delivery.json', delivery)
new_blend = scene_dir / blend.name
bpy.ops.wm.save_as_mainfile(filepath=str(new_blend), check_existing=False, relative_remap=False)
bpy.ops.wm.open_mainfile(filepath=str(new_blend))
saved = json.loads(bpy.context.scene['rhg_scene_delivery'])['window_scenery']
assert saved == json.loads(json.dumps(delivery['window_scenery']))
for row in saved['records']:
obj = bpy.data.objects[row['object']]
assert all(n.image.packed_file for n in obj.data.materials[0].node_tree.nodes if n.type == 'TEX_IMAGE')
assert geometry(bpy) == after
assert verify_frames(bpy, frame_receipt, windows) == frame_names
assert audit_window_scenery(bpy, composition['floor_plan'], saved)['complete']
receipt = {
'schema': 'rhg.residential-window-regression.v1', 'source_checks_passed': True,
'render_checks_passed': False,
'source_blend': str(blend), 'source_sha256': source_hash,
'generated_blend': str(new_blend), 'generated_sha256': sha(new_blend),
'windows': len(records), 'packed_texture_windows': len(records),
'window_frames': frame_receipt,
'window_scenery_coverage': delivery['window_scenery']['coverage'],
'unchanged_non_frame_material_objects': len(original)-len(frame_names),
'preserved_frosted_windows': [r['window_id'] for r in records if r['preserve_frosted_glass']],
'original_meshes_unchanged': len(original), 'layout_unchanged': True,
'reload_and_idempotence_passed': True,
'window_prepare_save_reload_seconds': round(time.monotonic() - started, 3),
'physical_qualification': 'not_rerun; r8_known_failures_not_resolved', 'renders': [],
}
save(output / 'verification.json', receipt)
render_dir = output / 'renders'
render_dir.mkdir()
render_args = renderer.parse_args(['--scene', str(scene_dir), '--output', str(render_dir),
'--device', 'CPU', '--width', '1280', '--height', '720', '--samples', '32'])
plan = renderer.resolve_plan(render_args, composition, sha(new_blend), sha(scene_dir / 'composition_manifest.runtime.json'))
renderer.configure(bpy, render_args, plan)
scene = bpy.context.scene
scene.render.use_compositing = False
rooms = {r['room_id']: r for r in composition['floor_plan']['rooms']}
window_map = {w['window_id']: w for w in windows}
bpy.context.view_layer.update()
for index, row in enumerate(records):
spec = window_camera(bpy, row, window_map[row['window_id']], rooms[row['room_id']], composition['entities'])
data = bpy.data.cameras.new('window_check_camera_data')
obj = bpy.data.objects.new('window_check_camera', data)
scene.collection.objects.link(obj)
renderer.configure_camera(data, spec)
obj.location = spec['location']
obj.rotation_euler = (Vector(spec['target']) - obj.location).to_track_quat('-Z', 'Y').to_euler()
scene.camera = obj
target = render_dir / ('window_%03d_%s.png' % (index, row['room_id']))
scene.render.filepath = str(target)
bpy.ops.render.render(write_still=True)
receipt['renders'].append({'camera': spec, 'path': str(target), 'sha256': sha(target)})
save(output / 'verification.json', receipt)
assert sha(blend) == source_hash
assert sha(new_blend) == receipt['generated_sha256']
receipt.update(source_unchanged=True, render_checks_passed=True, elapsed_s=round(time.monotonic()-started, 3))
save(output / 'verification.json', receipt)
print('WINDOW_VERIFICATION', json.dumps(receipt), flush=True)
if __name__ == '__main__':
main()
|