Datasets:
File size: 19,744 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 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 | """Replace the coffee table and install a measured balcony laundry/leisure layout."""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import rhg_paths
import argparse
import copy
import json
import math
import re
import shutil
import sys
from pathlib import Path
import bpy
from mathutils import Matrix, Vector
from mathutils.bvhtree import BVHTree
def main():
parser = argparse.ArgumentParser()
for key in ('tree', 'scene', 'output', 'plan'):
parser.add_argument('--' + key, type=Path, required=True)
args = parser.parse_args(sys.argv[sys.argv.index('--') + 1:])
sys.path[:0] = [str(args.tree), str(args.tree / 'engine'),
str(args.tree / 'engine/source/scripts/internal/scene_generation/real_assets')]
from supplemental_blender_assets import digest, fingerprint, import_asset, mesh_bounds, place_bottom_center, tree_for
from asset_import import material_record
from real_test.render_wholehouse import snapshot
assert not args.output.exists(), 'Use a new output directory'
source_snapshot = snapshot(args.scene)
manifest_path = args.scene / 'composition_manifest.runtime.json'
manifest = json.loads(manifest_path.read_text())
source = args.scene / (manifest['scene_id'] + '.blend')
parent = json.loads((args.scene / 'home_revision_receipt.json').read_text())
assert parent['passed'] and parent['source_blend_sha256'] == digest(source)
assert parent['source_manifest_sha256'] == digest(manifest_path)
plan = rhg_paths.resolve(json.loads(args.plan.read_text()))
prepared_path = Path(plan['prepared_materials'])
prepared = json.loads(prepared_path.read_text())
sources = {}
for filename in ('coffee_table_sources.json', 'balcony_laundry_sources.json'):
sources.update({k: Path(v) for k, v in rhg_paths.resolve(json.loads((args.tree / filename).read_text())).items()})
bpy.ops.wm.open_mainfile(filepath=str(source))
replaced_ids = {s['id'] for s in plan['assets'] if s.get('replace')}
changed = replaced_ids | {s['id'] for s in plan['move']}
protected = {o.name: fingerprint(o) for o in bpy.context.scene.objects if o.get('entity_id') not in changed}
original_entities = copy.deepcopy([e for e in manifest['entities'] if e['entity_id'] not in changed])
original_materials = {s.material.name: material_record(s.material)['signature_sha256']
for o in bpy.context.scene.objects for s in o.material_slots if s.material}
entities = {e['entity_id']: e for e in manifest['entities']}
retired = {eid: copy.deepcopy(entities[eid]) for eid in replaced_ids}
balcony = next(r['bounds_m'] for r in manifest['floor_plan']['rooms'] if r['room_id'] == 'balcony')
wall_thickness = manifest['floor_plan']['wall_thickness_m']
wall_half = wall_thickness / 2
room = [balcony[0] + wall_half, balcony[1], balcony[2] - wall_half, balcony[3] - wall_half]
groups, roots, placements, native_boxes = {}, {}, {}, {}
rig = None
def current_meshes(eid):
return [o for o in bpy.context.scene.objects if o.type == 'MESH' and o.get('entity_id') == eid]
for spec in plan['assets']:
eid = spec['id']
if eid in replaced_ids:
for obj in list(bpy.context.scene.objects):
if obj.get('entity_id') == eid:
bpy.data.objects.remove(obj, do_unlink=True)
manifest['entities'] = [e for e in manifest['entities'] if e['entity_id'] != eid]
else:
assert eid not in entities
path = sources[spec['source']]
if spec.get('native_laundry'):
before = set(bpy.data.objects)
bpy.ops.wm.usd_import(filepath=str(path))
imported = [o for o in bpy.data.objects if o not in before]
named = {o.name.split('.')[0]: o for o in imported}
root = named['root']
assert root.parent is None
meshes = [o for o in imported if o.type == 'MESH']
from official_mdl_adapter import bind_material
recipe = prepared[spec['source']]
assert recipe['source_sha256'] == digest(path)
replacements = {}
for obj in meshes:
for slot in obj.material_slots:
material = slot.material
key = re.sub(r'\.\d{3}$', '', material.name)
if key in recipe['materials']:
if material.name not in replacements:
replacements[material.name] = bind_material(material, recipe['materials'][key]['result'], bpy)[0]
slot.material = replacements[material.name]
native_boxes[eid] = mesh_bounds(meshes)
root.matrix_world = Matrix.Rotation(math.pi / 2, 4, 'Z') @ Matrix.Diagonal((spec['scale'], spec['scale'], spec['scale'], 1.))
controls = []
for key, node_name, pivot, joint_path in spec['joints']:
hinge = named[node_name]
assert hinge.parent == root and (hinge.location - Vector(pivot)).length < 1e-6
assert max(abs(value) for value in hinge.rotation_euler) < 1e-6
root[key] = 0.
root.id_properties_ui(key).update(min=0., max=90., description='Door opening in degrees')
hinge.rotation_mode = 'XYZ'
driver = hinge.driver_add('rotation_euler', 2).driver
variable = driver.variables.new()
variable.name = 'angle'
variable.targets[0].id = root
variable.targets[0].data_path = '["' + key + '"]'
driver.expression = '-min(90,max(0,angle))*0.017453292519943295'
controls.append(dict(property=key, hinge=hinge, meshes=[o for o in hinge.children_recursive if o.type == 'MESH'], source_joint=joint_path))
for obj in imported:
old_name = obj.name
obj['source_native_name'] = old_name
obj['entity_id'], obj['category'], obj['room_id'] = eid, spec['category'], spec['room']
obj.name = 'entity__' + eid + '__' + old_name
roots[eid] = root
rig = dict(entity_id=eid, root_name=root.name,
controls=[dict(property=c['property'], hinge_name=c['hinge'].name,
mesh_names=[o.name for o in c['meshes']], source_joint=c['source_joint'],
native_joint_limits_deg=[-90, 0], ui_limits_deg=[0, 90]) for c in controls])
else:
meshes = import_asset(spec['source'], eid, {}, sources=sources)
native_boxes[eid] = mesh_bounds(meshes)
scale = spec.get('scale', 1.)
rotation = (Matrix.Rotation(math.radians(spec.get('yaw', 0)), 4, 'Z')
@ Matrix.Rotation(math.radians(spec.get('tilt_x', 0)), 4, 'X')
@ Matrix.Diagonal((scale, scale, scale, 1.)))
for obj in meshes:
obj.matrix_world = rotation @ obj.matrix_world
for obj in meshes:
obj['category'], obj['role'], obj['room_id'] = spec['category'], spec['category'], spec['room']
groups[eid] = meshes
bpy.context.view_layer.update()
def place(eid, xy, bottom):
meshes = groups[eid]
if eid in roots:
box = mesh_bounds(meshes)
delta = Vector((xy[0] - (box[0][0] + box[1][0]) / 2,
xy[1] - (box[0][1] + box[1][1]) / 2, bottom - box[0][2]))
roots[eid].location += delta
bpy.context.view_layer.update()
return mesh_bounds(meshes)
return place_bottom_center(meshes, xy, bottom)
run_start = room[1] + plan['run_south_margin_m']
cursor = run_start
run = []
for eid in plan['laundry_run']:
box = mesh_bounds(groups[eid])
depth, width = box[1][0] - box[0][0], box[1][1] - box[0][1]
back_gap = .04 if eid == rig['entity_id'] else .01
xy = [room[0] + back_gap + depth / 2, cursor + width / 2]
box = place(eid, xy, .0015)
placements[eid] = dict(kind='floor', support='structure:floor__whole_house')
run.append(dict(entity_id=eid, bounds=box, width_m=width, depth_m=depth, back_gap_m=back_gap))
cursor += width + plan['run_gap_m']
assert cursor - plan['run_gap_m'] <= room[3] - .01, ('Laundry run does not fit', cursor, room)
for spec in plan['assets']:
eid = spec['id']
if eid in placements:
continue
if 'above' in spec:
lower = mesh_bounds(groups[spec['above']])
box = mesh_bounds(groups[eid])
xy = [room[0] + .01 + (box[1][0] - box[0][0]) / 2, sum(lower[j][1] for j in (0, 1)) / 2]
z = max(spec['bottom_z'], mesh_bounds(groups[rig['entity_id']])[1][2] + .07)
box = place(eid, xy, z)
placements[eid] = dict(kind='wall', wall_x=room[0], wall_gap_m=.01)
else:
box = place(eid, spec['xy'], .0015)
placements[eid] = dict(kind='floor', support='structure:floor__whole_house')
assert box[1][2] < 2.90
for spec in plan['assets']:
eid, path = spec['id'], sources[spec['source']]
box = mesh_bounds(groups[eid])
row = dict(entity_id=eid, name=spec['name'], category=spec['category'], role=spec['category'], room_id=spec['room'],
asset_id=('artvip:' if spec.get('native_laundry') else 'hssd:') + path.stem,
canonical_path=str(path), runtime_path=str(path), asset_sha256=digest(path), runtime_sha256=digest(path),
world_bbox_m=box, center_xy_m=[sum(box[j][i] for j in (0, 1)) / 2 for i in (0, 1)],
base_z_m=box[0][2], dimensions_m=[box[1][i] - box[0][i] for i in range(3)],
uniform_scale=spec.get('scale', 1.), native_bounds_m=native_boxes[eid],
source_mesh_object_names=[o.name for o in groups[eid]], balcony_coffee_placement=placements[eid])
if spec.get('native_laundry'):
row['articulation'] = rig
row['functions'] = ['washing_machine', 'clothes_dryer']
row['scale_basis'] = 'Uniform calibration to approximately 1.70 m combined appliance height; no axis distortion.'
entities[eid] = row
manifest['entities'].append(row)
print('PLACED', eid, box, flush=True)
for spec in plan['move']:
eid = spec['id']
group = current_meshes(eid)
support = spec.get('support', 'structure:floor__whole_house')
if support.startswith('structure:'):
surface_z = 0.
else:
support_group = current_meshes(support)
box = mesh_bounds(support_group)
point, normal, _, _ = tree_for(support_group).ray_cast(Vector((*spec['xy'], box[1][2] + .02)), Vector((0, 0, -1)), .20)
assert point is not None and normal.z > .7
surface_z = point.z
box = place_bottom_center(group, spec['xy'], surface_z + .0015)
placement = dict(kind='surface' if not support.startswith('structure:') else 'floor', support=support, surface_z=surface_z)
entities[eid].update(world_bbox_m=box, center_xy_m=spec['xy'], base_z_m=box[0][2],
dimensions_m=[box[1][i] - box[0][i] for i in range(3)],
supported_by_entity_id=support, balcony_coffee_placement=placement)
if 'showhome_installation' in entities[eid]:
entities[eid]['showhome_installation'] = placement.copy()
placements[eid] = placement
groups[eid] = group
retained = {s.material.name for o in bpy.context.scene.objects for s in o.material_slots if s.material}
original_materials = {k: v for k, v in original_materials.items() if k in retained}
for spec in plan['assets']:
for obj in groups[spec['id']]:
for slot in obj.material_slots:
record = material_record(slot.material)
for image in record['images']:
assert all(image['size']) and (image['packed'] or Path(image['path']).is_file()), ('Missing texture', spec['id'], image)
added_ids = set(groups) - changed
support_checks, door_checks = [], []
def verify():
bpy.context.view_layer.update()
assert all(name in bpy.data.objects and fingerprint(bpy.data.objects[name]) == value for name, value in protected.items()), 'Unrelated object changed'
assert all(material_record(bpy.data.materials[name])['signature_sha256'] == value for name, value in original_materials.items()), 'Original material changed'
assert original_entities == [e for e in manifest['entities'] if e['entity_id'] not in changed | added_ids]
all_groups = {}
for obj in bpy.context.scene.objects:
if obj.type == 'MESH' and not obj.hide_render:
all_groups.setdefault(obj.get('entity_id', 'structure:' + obj.name), []).append(obj)
boxes = {eid: mesh_bounds(group) for eid, group in all_groups.items()}
trees = {}
def tree(eid):
if eid not in trees:
trees[eid] = tree_for(all_groups[eid])
return trees[eid]
def overlaps(a, b):
return all(min(a[1][i], b[1][i]) - max(a[0][i], b[0][i]) > 1e-5 for i in range(3))
walls = tree_for([o for o in bpy.context.scene.objects if o.type == 'MESH' and o.name.startswith('wall__')])
support_checks.clear()
intersections = set()
for eid, mount in placements.items():
box = boxes[eid]
expected = entities[eid]['world_bbox_m']
assert max(abs(box[j][i] - expected[j][i]) for j in (0, 1) for i in range(3)) < 1e-5
if entities[eid]['room_id'] == 'balcony':
assert room[0] <= box[0][0] < box[1][0] <= room[2]
assert room[1] <= box[0][1] < box[1][1] <= room[3], ('Outside balcony', eid, box, room)
gaps = []
for u in (.05, .5, .95):
for v in (.05, .5, .95):
if mount['kind'] == 'wall':
y, z = [box[0][i] + t * (box[1][i] - box[0][i]) for i, t in zip((1, 2), (u, v))]
hit, normal, _, _ = walls.ray_cast(Vector((box[0][0], y, z)), Vector((-1, 0, 0)), .04)
assert hit is not None and normal.x > .7, ('No mounting wall', eid, y, z)
gaps.append(box[0][0] - hit.x)
else:
x, y = [box[0][i] + t * (box[1][i] - box[0][i]) for i, t in enumerate((u, v))]
z = mount.get('surface_z', 0.)
hit, normal, _, _ = tree(mount['support']).ray_cast(Vector((x, y, z + .02)), Vector((0, 0, -1)), .04)
assert hit is not None and normal.z > .7, ('Unsupported footprint', eid, x, y)
gap = box[0][2] - hit.z
assert -.0001 <= gap <= .004, ('Support gap', eid, gap)
gaps.append(gap)
support_checks.append(dict(entity_id=eid, kind=mount['kind'], gaps_m=gaps))
for other, other_box in boxes.items():
if other != eid and overlaps(box, other_box):
if tree(eid).overlap(tree(other)):
intersections.add(tuple(sorted((eid, other))))
assert not intersections, ('Geometry intersections', sorted(intersections))
for label, box in plan['clear_zones'].items():
vertices = [Vector((x, y, z)) for z in (box[0][2], box[1][2]) for y in (box[0][1], box[1][1]) for x in (box[0][0], box[1][0])]
zone = BVHTree.FromPolygons(vertices, [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)])
for eid, bounds in boxes.items():
if overlaps(box, bounds):
contained = all(box[0][i] <= bounds[0][i] <= bounds[1][i] <= box[1][i] for i in range(3))
assert not contained and not zone.overlap(tree(eid)), ('Blocked operating or passage space', label, eid)
root = bpy.data.objects[rig['root_name']]
door_checks.clear()
for angle in (0, 30, 60, 90):
for control in rig['controls']:
root[control['property']] = float(angle)
root.update_tag()
bpy.context.view_layer.update()
for control in rig['controls']:
hinge = bpy.data.objects[control['hinge_name']]
assert abs(math.degrees(hinge.rotation_euler.z) + angle) < 1e-4
door = [bpy.data.objects[name] for name in control['mesh_names']]
bounds, door_tree = mesh_bounds(door), tree_for(door)
for eid, box in boxes.items():
if eid != rig['entity_id'] and overlaps(bounds, box):
assert not door_tree.overlap(tree(eid)), ('Laundry door collision', control['property'], angle, eid)
door_checks.append(dict(property=control['property'], angle_deg=angle, bounds_m=bounds))
for control in rig['controls']:
root[control['property']] = 0.
root.update_tag()
bpy.context.view_layer.update()
assert all(fingerprint(bpy.data.objects[name]) == value for name, value in protected.items())
assert len(manifest['entities']) == len({e['entity_id'] for e in manifest['entities']})
verify()
args.output.mkdir(parents=True)
out = args.output / source.name
bpy.ops.wm.save_as_mainfile(filepath=str(out), relative_remap=False)
bpy.ops.wm.open_mainfile(filepath=str(out))
verify()
assert snapshot(args.scene) == source_snapshot
structural = args.scene / manifest['structural_material_manifest']['path']
assert digest(structural) == manifest['structural_material_manifest']['sha256']
shutil.copy2(structural, args.output / structural.name)
result = dict(schema='rhg.balcony-coffee.v1', passed=True, parent_blend_sha256=digest(source),
parent_manifest_sha256=digest(manifest_path), source_scene_unchanged=True, saved_reopen_passed=True,
protected_object_count=len(protected), original_materials_preserved=True, replaced=retired,
added=sorted(added_ids), moved=[s['id'] for s in plan['move']], balcony_inner_bounds_m=room,
laundry_run=run, laundry_run_width_m=cursor - plan['run_gap_m'] - run_start,
support_checks=support_checks, triangle_intersections_checked=True,
clear_zones_m=plan['clear_zones'], articulation=rig, door_checks=door_checks,
native_asset_scale=next(s['scale'] for s in plan['assets'] if s.get('native_laundry')),
prepared_materials_path=str(prepared_path), prepared_materials_sha256=digest(prepared_path),
physics_simulation_tested=False, plan_sha256=digest(args.plan))
manifest['balcony_coffee_revision'] = copy.deepcopy(result)
target_manifest = args.output / manifest_path.name
target_manifest.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + '\n')
result.update(source_blend_sha256=digest(out), source_manifest_sha256=digest(target_manifest))
for name in ('balcony_coffee_receipt.json', 'home_revision_receipt.json'):
(args.output / name).write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n')
print(json.dumps(dict(passed=True, output=str(out), protected=len(protected), added=len(added_ids), replaced=len(replaced_ids))), flush=True)
if __name__ == '__main__':
main()
|