Datasets:
Download code/robohome/src/balcony_window_revision.py from RoboParty/RoboHome: direct link, hf CLI and curl.
- Browser
- Download file 20.5 kB
-
https://huggingface.co/datasets/RoboParty/RoboHome/resolve/main/code/robohome/src/balcony_window_revision.py
- Command line
-
hf download hf://datasets/RoboParty/RoboHome/code/robohome/src/balcony_window_revision.py
-
curl -L -o balcony_window_revision.py https://huggingface.co/datasets/RoboParty/RoboHome/resolve/main/code/robohome/src/balcony_window_revision.py
20.5 kB
| """Apply the requested balcony/lounge/window revision to an already open scene. | |
| The caller owns loading/saving. Imported furniture is cloned in full from the | |
| existing scene with its native mesh/material data and unit scale intact. | |
| """ | |
| import copy | |
| import hashlib | |
| import json | |
| import math | |
| from pathlib import Path | |
| import sys | |
| SMALL_PLANT_ID = 'balcony__outdoor_greenery__01' | |
| REMOVED_IDS = ('balcony__outdoor_surface__01', 'balcony__outdoor_seating__01', 'balcony__outdoor_seating__02') | |
| FURNITURE = ( | |
| ('living__additional_seating__01', 'balcony__lounge_seating__01', 'armchair', (11.65, 13.40), -15.), | |
| ('bedroom_2_nightstand', 'balcony__side_table__01', 'side_table', (10.85, 13.48), 0.), | |
| ) | |
| def midrail_regions(bay_edges, glass_bottom, glass_top, sill, head): | |
| """Four measured clear bays, a 40 mm center rail, and eight solid panes.""" | |
| center=(sill+head)/2;thickness=.04;low=center-thickness/2;high=center+thickness/2 | |
| if len(bay_edges)!=4 or not glass_bottom<low<high<glass_top: | |
| raise ValueError('Expected four balcony bays and room for a middle rail') | |
| rails=[];panes=[] | |
| for column,(left,right) in enumerate(bay_edges): | |
| if right<=left:raise ValueError('Nonpositive clear pane width') | |
| rails.append(dict(column=column,x_interval_m=[left,right],z_interval_m=[low,high])) | |
| for row,interval in enumerate(([glass_bottom,low],[high,glass_top])): | |
| panes.append(dict(column=column,row=row,x_interval_m=[left,right],z_interval_m=interval)) | |
| return dict(center_z_m=center,thickness_m=thickness,rails=rails,panes=panes, | |
| maximum_pane_area_m2=max((p['x_interval_m'][1]-p['x_interval_m'][0])*(p['z_interval_m'][1]-p['z_interval_m'][0]) for p in panes)) | |
| def apply(bpy, manifest, tree): | |
| """Mutate bpy/manifest in memory and return measured revision evidence.""" | |
| from mathutils import Matrix, Vector | |
| tree = Path(tree) | |
| code = tree/'engine/source/scripts/internal/scene_generation' | |
| sys.path[:0] = [str(tree), str(tree/'engine'), str(code), str(code/'real_assets')] | |
| import window_rules | |
| import presentation_windows | |
| from asset_import import material_record | |
| plan = manifest['floor_plan'] | |
| windows = plan['windows'] | |
| window = next(w for w in windows if w['window_id']=='window__balcony__n') | |
| wid = window['window_id'] | |
| entities = {e['entity_id']: e for e in manifest['entities']} | |
| if any(new in entities for _,new,_,_,_ in FURNITURE): | |
| raise ValueError('Balcony revision already applied') | |
| if not set(REMOVED_IDS).issubset(entities): | |
| raise ValueError('Expected original balcony table and two dining chairs') | |
| def objects(eid): | |
| return [o for o in bpy.context.scene.objects if o.type=='MESH' and o.get('entity_id')==eid] | |
| def bounds(obs): | |
| vs = [o.matrix_world@v.co for o in obs for v in o.data.vertices] | |
| if not vs: raise ValueError('Empty mesh group') | |
| return [[min(v[i] for v in vs) for i in range(3)], [max(v[i] for v in vs) for i in range(3)]] | |
| 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)) | |
| def mesh_hash(o): | |
| from array import array | |
| co=array('f',[0.])*(3*len(o.data.vertices));o.data.vertices.foreach_get('co',co) | |
| return hashlib.sha256(co.tobytes()+repr([(tuple(p.vertices),p.material_index) for p in o.data.polygons]).encode()).hexdigest() | |
| def object_fingerprint(o): | |
| return (tuple(tuple(r) for r in o.matrix_world),o.hide_render,mesh_hash(o) if o.type=='MESH' else None, | |
| tuple(s.material.name if s.material else None for s in o.material_slots)) | |
| allowed = {o.name for o in bpy.context.scene.objects if o.get('entity_id') in (*REMOVED_IDS,SMALL_PLANT_ID) or | |
| wid in o.name or o.get('delivery_window_id')} | |
| stable = {o.name:object_fingerprint(o) for o in bpy.context.scene.objects if o.name not in allowed} | |
| removed = [] | |
| for eid in REMOVED_IDS: | |
| obs=[o for o in bpy.context.scene.objects if o.get('entity_id')==eid] | |
| if not obs: raise ValueError('Missing balcony entity '+eid) | |
| removed.append(dict(entity_id=eid,asset_id=entities[eid]['asset_id'],objects=[o.name for o in obs])) | |
| for o in obs:bpy.data.objects.remove(o,do_unlink=True) | |
| manifest['entities'][:]=[e for e in manifest['entities'] if e['entity_id'] not in REMOVED_IDS] | |
| room=next(r for r in plan['rooms'] if r['room_id']=='balcony') | |
| half=plan['wall_thickness_m']/2 | |
| x0,y0,x1,y1=room['bounds_m'];inner=[x0+half,y0+half,x1-half,y1-half] | |
| # Clear the requested entrance strip, including the inherited tiny planter. | |
| # The large marked plant in the NW corner stays in the stable object set. | |
| plant=entities[SMALL_PLANT_ID];plant_objects=objects(SMALL_PLANT_ID) | |
| plant_before=copy.deepcopy(plant['world_bbox_m']);box=bounds(plant_objects) | |
| dy=12.98-(box[0][1]+box[1][1])/2 | |
| for o in plant_objects:o.matrix_world=Matrix.Translation((0.,dy,0.))@o.matrix_world | |
| bpy.context.view_layer.update();plant['world_bbox_m']=bounds(plant_objects) | |
| for key in ('center_xy_m','actual_center_xy_m'):plant[key][1]+=dy | |
| for q in plant['visual_footprint_polygon_xy_m']:q[1]+=dy | |
| for key in ('_adaptive_relations','layout_slot_id','real_dimension_layout','measured_wall_mount', | |
| 'floor_body_geometry_evidence','functional_fit_corrections','wall_fit_correction_xy_m', | |
| 'wall_fit_remaining_gap_m','operation_space_xy_m','wall_anchor','placement_side'): | |
| plant.pop(key,None) | |
| plant['layout_authority']='explicit_balcony_entrance_strip_clearance' | |
| assert plant['world_bbox_m'][0][1]>=12.85 | |
| assert not any(overlaps(plant['world_bbox_m'],bounds([o])) for o in bpy.context.scene.objects | |
| if o.type=='MESH' and o.get('entity_id')!=SMALL_PLANT_ID and not o.get('delivery_visual_only') | |
| and o.get('kind')!='door_swing_keepout_v9') | |
| plant_move=dict(entity_id=SMALL_PLANT_ID,old_bbox_m=plant_before,new_bbox_m=plant['world_bbox_m'], | |
| translation_m=[0.,dy,0.],native_geometry_and_materials_preserved=True) | |
| added=[] | |
| for source_id,eid,category,target,angle in FURNITURE: | |
| source=entities[source_id];src=objects(source_id) | |
| assert src and all(o.parent is None for o in src), 'Expected flat native furniture hierarchy' | |
| runtime=Path(source['runtime_path']) | |
| assert hashlib.sha256(runtime.read_bytes()).hexdigest()==source['runtime_sha256'] | |
| box=bounds(src);pivot=[(box[0][i]+box[1][i])/2 for i in (0,1)] | |
| rotation=Matrix.Rotation(math.radians(angle),4,'Z') | |
| transform=Matrix.Translation((*target,0))@rotation@Matrix.Translation((-pivot[0],-pivot[1],-box[0][2])) | |
| cloned=[] | |
| for original in src: | |
| o=original.copy();o.name=original.name.replace(source_id,eid) | |
| o['entity_id']=eid;o['source_node_entity_id']=eid | |
| bpy.context.scene.collection.objects.link(o);o.matrix_world=transform@original.matrix_world;cloned.append(o) | |
| assert o.data is original.data and mesh_hash(o)==mesh_hash(original) | |
| assert [s.material for s in o.material_slots]==[s.material for s in original.material_slots] | |
| bpy.context.view_layer.update();box=bounds(cloned) | |
| e=copy.deepcopy(source) | |
| retired={k:e.pop(k) for k in list(e) if k in { | |
| '_adaptive_relations','front_target_entity_id','layout_relation','layout_slot_id','real_dimension_layout', | |
| 'measured_wall_mount','floor_body_geometry_evidence','functional_fit_corrections','wall_fit_correction_xy_m', | |
| 'wall_fit_remaining_gap_m','operation_space_xy_m','front_clearance_box_xy_m','wall_anchor','placement_side', | |
| 'selected_support_surface','support_height_hypothesis','binding_semantic_key','pool_candidate_key'}} | |
| def point(q):return list((transform@Vector((*q,0)))[:2]) | |
| e.update(entity_id=eid,room_id='balcony',category=category,role=category,normalized_category=category, | |
| furnishing_function='outdoor_seating' if category=='armchair' else 'outdoor_surface', | |
| center_xy_m=point(source['center_xy_m']),actual_center_xy_m=point(source['actual_center_xy_m']), | |
| world_bbox_m=box,base_z_m=box[0][2],yaw_deg=source['yaw_deg']+angle, | |
| contract_yaw_deg=source['contract_yaw_deg']+angle,room_inner_bounds_m=inner, | |
| layout_authority='explicit_balcony_lounge_revision', | |
| visual_footprint_polygon_xy_m=[point(q) for q in source['visual_footprint_polygon_xy_m']]) | |
| front=list((rotation@Vector((*source['world_front_vector_xy'],0)))[:2]) | |
| e['world_front_vector_xy']=e['applied_world_front_vector_xy']=front | |
| e['balcony_clone_provenance']=dict(source_entity_id=source_id,source_asset_id=source['asset_id'], | |
| native_scale_preserved=True,source_geometry_and_materials_preserved=True,retired_layout_fields=sorted(retired)) | |
| assert inner[0]<=box[0][0]<box[1][0]<=inner[2] and 12.85<=box[0][1]<box[1][1]<=inner[3], box | |
| assert abs(box[0][2])<1e-5 | |
| physical=[o for o in bpy.context.scene.objects if o.type=='MESH' and o.get('entity_id')!=eid | |
| and not o.get('delivery_visual_only') and o.get('kind')!='door_swing_keepout_v9'] | |
| conflicts=[o.name for o in physical if overlaps(box,bounds([o]))] | |
| assert not conflicts, ('Balcony furniture overlaps',eid,conflicts) | |
| manifest['entities'].append(e) | |
| added.append(dict(entity_id=eid,source_entity_id=source_id,asset_id=e['asset_id'],runtime_sha256=e['runtime_sha256'], | |
| native_scale=e['uniform_scale'],world_bbox_m=box,mesh_objects=[o.name for o in cloned], | |
| source_mesh_sha256=[mesh_hash(o) for o in cloned], | |
| material_signatures={s.material.name:material_record(s.material)['signature_sha256'] | |
| for o in cloned for s in o.material_slots if s.material}, | |
| floor_contact=True,clear_of_geometry=True,clear_entrance_to_y_m=12.85)) | |
| old_window=copy.deepcopy(window) | |
| window['sill_height_m'],window['head_height_m']=window_rules.vertical('balcony',plan.get('wall_height_m',3.)) | |
| window['glazing']=window_rules.glazing(window) | |
| lo,hi=window['window_interval_m'];sill=window['sill_height_m'];head=window['head_height_m'];width=hi-lo | |
| def fit(o,low,high): | |
| current=bounds([o]);scale=[(high[i]-low[i])/(current[1][i]-current[0][i]) for i in range(3)] | |
| mat=Matrix.Translation(Vector(low))@Matrix.Diagonal((*scale,1.))@Matrix.Translation(-Vector(current[0])) | |
| o.matrix_world=mat@o.matrix_world | |
| bpy.context.view_layer.update() | |
| for name,z0,z1 in [('wall__window_sill_infill__',0.,sill),('wall__window_lintel_infill__',head,plan.get('wall_height_m',3.))]: | |
| o=bpy.data.objects[name+wid];b=bounds([o]);b[0][2]=z0;b[1][2]=z1;fit(o,*b) | |
| glass=bpy.data.objects['glass__'+wid];b=bounds([glass]);b[0][2]=sill;b[1][2]=head;fit(glass,*b) | |
| prefix='frame__'+wid+'__' | |
| for o in [o for o in bpy.context.scene.objects if o.name.startswith(prefix)]: | |
| part=o.name[len(prefix):] | |
| if part.startswith('mullion') or part=='transom':continue | |
| b=bounds([o]) | |
| if part in ('left','right'):b[0][2]=sill-.04;b[1][2]=head+.04 | |
| else: | |
| z=sill if part=='bottom' else head;dz=(b[1][2]-b[0][2])/2;b[0][2]=z-dz;b[1][2]=z+dz | |
| fit(o,*b) | |
| mullion_source=bpy.data.objects[prefix+'mullion1'] | |
| mullion_bounds=bounds([mullion_source]);mid=(mullion_bounds[0][1]+mullion_bounds[1][1])/2 | |
| template=mullion_source.copy();template.data=mullion_source.data | |
| for o in list(bpy.context.scene.objects): | |
| if o.name.startswith(prefix+'mullion') or o.name==prefix+'transom':bpy.data.objects.remove(o,do_unlink=True) | |
| for i in range(1,window['glazing']['leaves']): | |
| x=lo+width*i/window['glazing']['leaves'];o=template.copy();o.name=prefix+'mullion'+str(i) | |
| bpy.context.scene.collection.objects.link(o) | |
| fit(o,[x-.03,mid-.03,sill],[x+.03,mid+.03,head]) | |
| bpy.data.objects.remove(template,do_unlink=True) | |
| # Use the *actual* vertical frame edges, so each horizontal rail ends at | |
| # a stile/mullion instead of overlaying its visible face. Eight disconnected | |
| # glass solids share the established glass object for scenery compatibility. | |
| vertical=[bpy.data.objects[prefix+'left']]+[bpy.data.objects[prefix+'mullion'+str(i)] for i in range(1,4)]+[bpy.data.objects[prefix+'right']] | |
| vertical_boxes=[bounds([o]) for o in vertical] | |
| bay_edges=[(vertical_boxes[i][1][0],vertical_boxes[i+1][0][0]) for i in range(4)] | |
| split=midrail_regions(bay_edges,bounds([bpy.data.objects[prefix+'bottom']])[1][2], | |
| bounds([bpy.data.objects[prefix+'top']])[0][2],sill,head) | |
| for i,region in enumerate(split['rails']): | |
| o=bpy.data.objects[prefix+'mullion1'].copy();o.name=prefix+'transom'+str(i+1) | |
| bpy.context.scene.collection.objects.link(o);left,right=region['x_interval_m'];zlow,zhigh=region['z_interval_m'] | |
| fit(o,[left,mid-.03,zlow],[right,mid+.03,zhigh]) | |
| o['window_id']=wid;o['window_component']='middle_transom_segment';o['bay_index']=i | |
| region['object_name']=o.name;region['actual_bbox_m']=bounds([o]) | |
| assert not any(overlaps(region['actual_bbox_m'],b) for b in vertical_boxes),('Rail overlaps vertical frame',o.name) | |
| old_mesh=glass.data;original_slots=[(slot.material,slot.link) for slot in glass.material_slots] | |
| glass_bounds=bounds([glass]);ymin,ymax=glass_bounds[0][1],glass_bounds[1][1];inverse=glass.matrix_world.inverted() | |
| vertices=[];faces=[];cube_faces=[(0,3,2,1),(4,5,6,7),(0,1,5,4),(1,2,6,5),(2,3,7,6),(3,0,4,7)] | |
| for index,region in enumerate(split['panes']): | |
| left,right=region['x_interval_m'];zlow,zhigh=region['z_interval_m'];offset=len(vertices) | |
| points=[(left,ymin,zlow),(right,ymin,zlow),(right,ymax,zlow),(left,ymax,zlow), | |
| (left,ymin,zhigh),(right,ymin,zhigh),(right,ymax,zhigh),(left,ymax,zhigh)] | |
| vertices.extend(inverse@Vector(q) for q in points) | |
| faces.extend(tuple(offset+i for i in face) for face in cube_faces) | |
| region.update(pane_index=index,vertex_indices=list(range(offset,offset+8)),face_indices=list(range(index*6,index*6+6)), | |
| expected_bbox_m=[[left,ymin,zlow],[right,ymax,zhigh]]) | |
| mesh=bpy.data.meshes.new(old_mesh.name+'__eight_separate_panes');mesh.from_pydata(vertices,[],faces);mesh.update() | |
| for material in old_mesh.materials:mesh.materials.append(material) | |
| attribute=mesh.attributes.new(name='window_pane_index',type='INT',domain='FACE') | |
| for i,value in enumerate(attribute.data):value.value=i//6 | |
| glass.data=mesh | |
| for slot,(material,link) in zip(glass.material_slots,original_slots):slot.link=link;slot.material=material | |
| if old_mesh.users==0:bpy.data.meshes.remove(old_mesh) | |
| glass['window_pane_count']=8;glass['window_pane_rows']=2;glass['window_pane_columns']=4 | |
| glass['window_pane_regions_json']=json.dumps(split['panes']) | |
| bpy.context.view_layer.update() | |
| # Actual disconnected-component count and independent BVH rays distinguish | |
| # real split glazing from an unchanged whole sheet covered by a dark line. | |
| from verify_scene_geometry import mesh_record | |
| graph={v.index:set() for v in glass.data.vertices} | |
| for edge in glass.data.edges: | |
| a,b=edge.vertices;graph[a].add(b);graph[b].add(a) | |
| pending=set(graph);components=[] | |
| while pending: | |
| todo=[pending.pop()];component=set(todo) | |
| while todo: | |
| for index in graph[todo.pop()]: | |
| if index in pending:pending.remove(index);component.add(index);todo.append(index) | |
| components.append(component) | |
| assert len(components)==8 and all(len(component)==8 for component in components) | |
| glass_mesh=mesh_record([glass]);frame_mesh=mesh_record([o for o in bpy.context.scene.objects if o.name.startswith(prefix) and o.type=='MESH']) | |
| ray_checks=[] | |
| for region in split['panes']: | |
| pp=[glass.matrix_world@glass.data.vertices[i].co for i in region['vertex_indices']] | |
| actual=[[min(v[i] for v in pp) for i in range(3)],[max(v[i] for v in pp) for i in range(3)]] | |
| assert max(abs(x-y) for a,b in zip(actual,region['expected_bbox_m']) for x,y in zip(a,b))<3e-5 | |
| region['actual_bbox_m']=actual;x=sum(region['x_interval_m'])/2;z=sum(region['z_interval_m'])/2 | |
| origin=Vector((x,mid-.20,z));direction=Vector((0,1,0)) | |
| assert glass_mesh['bvh'].ray_cast(origin,direction,.4)[0] is not None | |
| assert frame_mesh['bvh'].ray_cast(origin,direction,.4)[0] is None | |
| ray_checks.append(dict(pane_index=region['pane_index'],glass_hit=True,frame_hit=False)) | |
| for region in split['rails']: | |
| x=sum(region['x_interval_m'])/2;origin=Vector((x,mid-.20,split['center_z_m']));direction=Vector((0,1,0)) | |
| assert frame_mesh['bvh'].ray_cast(origin,direction,.4)[0] is not None | |
| assert glass_mesh['bvh'].ray_cast(origin,direction,.4)[0] is None | |
| ray_checks.append(dict(rail_object=region['object_name'],frame_hit=True,glass_hit=False)) | |
| split.update(disconnected_glass_components=8,glass_object=glass.name,glass_materials_preserved=True, | |
| frame_junction_positive_volume_overlap=False,actual_geometry_ray_checks=ray_checks) | |
| light=bpy.data.objects.get('pmp20_window_'+wid) | |
| if light: | |
| light.location.z=(sill+head)/2 | |
| if light.data.type=='AREA':light.data.size=width;light.data.size_y=head-sill | |
| frame_receipt=presentation_windows.apply_window_frame_materials(bpy,{'windows':[window]}) | |
| # Explicitly reprepare the old plates because their assignment and balcony | |
| # height change; images are hash-verified and packed by the native routine. | |
| old_scenery=[] | |
| for o in list(bpy.context.scene.objects): | |
| if o.get('delivery_window_id'): | |
| old_scenery.append(json.loads(o['delivery_window_record'])) | |
| bpy.data.objects.remove(o,do_unlink=True) | |
| scenery=presentation_windows.create(bpy,plan,tree/'window_scenery.json',persistent=True,seed=manifest['seed']) | |
| scenery_audit=presentation_windows.audit_window_scenery(bpy,plan,scenery) | |
| window_rules.annotate_plan(plan) | |
| # This explicit saved-scene design overrides the unchanged native default. | |
| window['glazing'].update(transom_height_m=head-split['center_z_m'],transom_center_z_m=split['center_z_m'], | |
| transom_thickness_m=split['thickness_m'],pane_count=8,pane_rows=2, | |
| pane_area_m2=round(split['maximum_pane_area_m2'],3), | |
| safety_reasons=[reason for reason in window['glazing']['safety_reasons'] if reason!='pane_area_over_1.5_m2'], | |
| explicit_saved_scene_override='four_equal_columns_two_rows_middle_transom') | |
| for name,fp in stable.items(): | |
| assert name in bpy.data.objects and object_fingerprint(bpy.data.objects[name])==fp, ('Unrelated object changed',name) | |
| # Carry the new scenery receipt in every active delivery metadata location. | |
| for key in ('rhg_scene_delivery',): | |
| raw=bpy.context.scene.get(key) | |
| if raw: | |
| data=json.loads(raw) if isinstance(raw,str) else dict(raw) | |
| if 'window_scenery' in data:data['window_scenery']=scenery | |
| if 'window_frames' in data: | |
| frames=data['window_frames'] | |
| frames['records']=[r for r in frames.get('records',[]) if r['window_id']!=wid]+frame_receipt['records'] | |
| frames['frame_object_count']=sum(len(r['objects']) for r in frames['records']) | |
| bpy.context.scene[key]=json.dumps(data) | |
| evidence=dict(schema='rhg.balcony-window-revision.v1',passed=True,removed=removed,added=added, | |
| moved_existing_plant=plant_move,midrail_glazing=split,window_before=old_window,window_after=copy.deepcopy(window),window_frames=frame_receipt, | |
| window_geometry={o.name:bounds([o]) for o in bpy.context.scene.objects if o.type=='MESH' and wid in o.name}, | |
| scenery=scenery,scenery_audit=scenery_audit,previous_scenery=old_scenery, | |
| furniture_count={'armchair':1,'side_table':1,'dining_chair':0,'dining_table':0}, | |
| entrance_strip_y_m=[11.95,12.85],unchanged_other_objects=len(stable),wholehouse_physics_qualified=False) | |
| manifest['balcony_window_revision']=evidence | |
| bpy.context.scene['rhg_balcony_window_revision_json']=json.dumps(evidence) | |
| return evidence | |