Datasets:
File size: 10,784 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 | """Add four place plates and practical kitchen assets to a reviewed scene."""
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 sys
from pathlib import Path
import bpy
from mathutils import Vector
def main():
parser = argparse.ArgumentParser()
for key in ('tree', 'scene', 'output', 'sources', 'materials', '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'
before_files = snapshot(args.scene)
mp = args.scene / 'composition_manifest.runtime.json'
manifest = json.loads(mp.read_text())
source = args.scene / (manifest['scene_id'] + '.blend')
parent_receipt = json.loads((args.scene / 'home_revision_receipt.json').read_text())
assert parent_receipt['passed']
assert parent_receipt['source_blend_sha256'] == digest(source)
assert parent_receipt['source_manifest_sha256'] == digest(mp)
plan = json.loads(args.plan.read_text())
sources = {k: Path(v) for k, v in rhg_paths.resolve(json.loads(args.sources.read_text())).items()}
prepared = json.loads(args.materials.read_text())
bpy.ops.wm.open_mainfile(filepath=str(source))
changed = {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_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}
original_entities = copy.deepcopy([e for e in manifest['entities'] if e['entity_id'] not in changed])
entities = {e['entity_id']: e for e in manifest['entities']}
additions, moves, support_checks = [], [], []
def meshes(eid):
return [o for o in bpy.context.scene.objects if o.type == 'MESH' and o.get('entity_id') == eid]
def support_height(eid, xy):
group = meshes(eid)
box = mesh_bounds(group)
point, normal, _, _ = tree_for(group).ray_cast(Vector((*xy, box[1][2] + .03)), Vector((0, 0, -1)), .20)
assert point is not None and normal.z > .7, ('No horizontal support', eid, xy)
return point.z
for spec in plan['move']:
group = meshes(spec['id'])
old_box = mesh_bounds(group)
box = place_bottom_center(group, spec['xy'], support_height(spec['support'], spec['xy']) + .0015, spec['yaw'])
row = entities[spec['id']]
row.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=spec['support'], supplemental_yaw_delta_deg=spec['yaw'])
moves.append(dict(entity_id=spec['id'], before=old_box, after=box, support=spec['support']))
for spec in plan['add']:
assert spec['id'] not in entities
group = import_asset(spec['source'], spec['id'], prepared, sources=sources)
if 'chair' in spec:
chair = mesh_bounds(meshes(spec['chair']))
table = mesh_bounds(meshes('dining_table'))
x = (chair[0][0] + chair[1][0]) / 2
north = sum(chair[i][1] for i in (0, 1)) > sum(table[i][1] for i in (0, 1))
xy = [x, table[1][1] - .22 if north else table[0][1] + .22]
else:
xy = spec['xy']
box = place_bottom_center(group, xy, support_height(spec['support'], xy) + .0015, spec.get('yaw', 0))
asset_path = sources[spec['source']]
row = dict(entity_id=spec['id'], asset_id='tabletop:' + spec['source'],
category=spec['category'], role=spec['category'], room_id=spec['room'],
canonical_path=str(asset_path), runtime_path=str(asset_path),
asset_sha256=digest(asset_path), runtime_sha256=digest(asset_path),
world_bbox_m=box, center_xy_m=xy, base_z_m=box[0][2],
dimensions_m=[box[1][i] - box[0][i] for i in range(3)],
uniform_scale=1., supported_by_entity_id=spec['support'],
paired_chair_entity_id=spec.get('chair'),
source_mesh_object_names=[o.name for o in group])
for obj in group:
obj['category'] = spec['category']
obj['role'] = spec['category']
obj['room_id'] = spec['room']
additions.append(row)
manifest['entities'].append(row)
entities[spec['id']] = row
target_ids = [s['id'] for s in plan['add'] + plan['move']]
def verify():
bpy.context.view_layer.update()
assert all(name in bpy.data.objects and fingerprint(bpy.data.objects[name]) == h
for name, h in protected.items()), 'Unrelated object changed'
assert all(material_record(bpy.data.materials[name])['signature_sha256'] == h
for name, h in original_materials.items()), 'Existing material changed'
assert original_entities == [e for e in manifest['entities'] if e['entity_id'] not in changed | set(r['entity_id'] for r in additions)]
assert len(additions) == 11 and len({e['paired_chair_entity_id'] for e in additions if e['category'] == 'dinner_plate'}) == 4
groups = {}
for obj in bpy.context.scene.objects:
if obj.type == 'MESH' and not obj.hide_render:
groups.setdefault(obj.get('entity_id', 'structure:' + obj.name), []).append(obj)
boxes = {eid: mesh_bounds(group) for eid, group in groups.items()}
trees = {}
def tree(eid):
if eid not in trees:
trees[eid] = tree_for(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))
support_checks.clear()
for eid in target_ids:
row = entities[eid]
box = boxes[eid]
assert max(abs(box[j][i] - row['world_bbox_m'][j][i]) for j in (0, 1) for i in range(3)) < 1e-5
support_id = row['supported_by_entity_id']
support = boxes[support_id]
assert all(support[0][i] + .015 < box[0][i] and box[1][i] < support[1][i] - .015 for i in (0, 1)), ('Overhang', eid)
gaps = []
# Sample the entire footprint, including corners, to reject holes and edges.
for u in (.05, .5, .95):
for v in (.05, .5, .95):
xy = [box[0][0] + u * (box[1][0] - box[0][0]), box[0][1] + v * (box[1][1] - box[0][1])]
z = support_height(support_id, xy)
gap = box[0][2] - z
assert -.0001 <= gap <= .004, ('Unsupported footprint', eid, xy, gap)
gaps.append(gap)
support_checks.append(dict(entity_id=eid, support=support_id, sampled_gaps_m=gaps))
for other, other_box in boxes.items():
if other == eid or not overlaps(box, other_box):
continue
assert not tree(eid).overlap(tree(other)), ('Geometry intersection', eid, other)
root = bpy.data.objects['refrigerator__assembly']
hinge = bpy.data.objects['refrigerator__door_hinge']
original_angle = root['open_angle_deg']
door = [o for o in groups['refrigerator'] if 'fridge_door' in o.get('source_mesh_name', '')]
for angle in (0, 30, 70, 90):
root['open_angle_deg'] = float(angle)
root.update_tag()
bpy.context.view_layer.update()
assert abs(math.degrees(hinge.rotation_euler.z) - angle) < 1e-4
door_box = mesh_bounds(door)
door_tree = tree_for(door)
for eid in target_ids:
if overlaps(door_box, boxes[eid]):
assert not door_tree.overlap(tree(eid)), ('Refrigerator door collision', angle, eid)
root['open_angle_deg'] = original_angle
root.update_tag()
bpy.context.view_layer.update()
assert all(fingerprint(bpy.data.objects[name]) == h for name, h in protected.items())
for eid in target_ids:
for obj in groups[eid]:
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', eid, image)
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) == before_files
receipt = dict(schema='rhg.kitchen-tabletop.v1', passed=True,
parent_blend_sha256=digest(source), parent_manifest_sha256=digest(mp),
source_scene_unchanged=True, saved_reopen_passed=True,
protected_object_count=len(protected), existing_materials_preserved=True,
original_entities_preserved=True, additions=[e['entity_id'] for e in additions],
moves=moves, support_checks=support_checks, native_scale_preserved=True,
triangle_intersections_checked=True, refrigerator_angles_checked=[0, 30, 70, 90],
physics_simulation_tested=False,
sources_sha256=digest(args.sources), plan_sha256=digest(args.plan),
materials_sha256=digest(args.materials))
manifest['kitchen_tabletop_revision'] = receipt.copy()
(args.output / 'composition_manifest.runtime.json').write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + '\n')
receipt['source_blend_sha256'] = digest(out)
receipt['source_manifest_sha256'] = digest(args.output / 'composition_manifest.runtime.json')
for name in ('kitchen_tabletop_receipt.json', 'home_revision_receipt.json'):
(args.output / name).write_text(json.dumps(receipt, ensure_ascii=False, indent=2) + '\n')
print(json.dumps(dict(passed=True, output=str(out), added=len(additions), moved=len(moves), protected=len(protected))), flush=True)
if __name__ == '__main__':
main()
|