File size: 10,439 Bytes
d926d03 | 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 | import blenderproc as bproc
# Local research renderer. This is a measured BOP-style reconstruction, NOT a
# claim that the unpublished original HANDAL lighting/material recipe is known.
import argparse
import hashlib
import json
import os
from pathlib import Path
import random
import time
import bpy
import numpy as np
def sha(path):
h=hashlib.sha256()
with Path(path).open('rb') as f:
for b in iter(lambda:f.read(8*1024*1024),b''):h.update(b)
return h.hexdigest()
def choose_device(name):
prefs=bpy.context.preferences.addons['cycles'].preferences
prefs.compute_device_type='OPTIX';prefs.refresh_devices()
choices=[d for d in prefs.devices if d.type=='OPTIX']
indices=[i for i,d in enumerate(choices) if d.name==name]
if len(indices)!=1:raise ValueError('Requested GPU name must match exactly one OptiX device')
bproc.renderer.set_render_devices(desired_gpu_device_type='OPTIX',desired_gpu_ids=indices)
for device in prefs.devices:
device.use = device.type=='OPTIX' and device.name==name
selected=[d.name for d in prefs.devices if d.use]
if selected!=[name]:raise ValueError(f'Wrong render devices: {selected}')
return selected
def main():
p=argparse.ArgumentParser()
p.add_argument('--assets',type=Path,required=True);p.add_argument('--out',type=Path,required=True)
p.add_argument('--target-id',type=int,choices=[2,12,37,40],default=40)
p.add_argument('--seed',type=int,required=True);p.add_argument('--frames',type=int,default=25)
p.add_argument('--gpu-name',default='NVIDIA GeForce RTX 4090')
p.add_argument('--config',type=Path,required=True)
a=p.parse_args();cfg=json.loads(a.config.read_text());a.assets=a.assets.resolve();a.out=a.out.resolve()
if not 1<=a.frames<=25:raise ValueError('one physical layout, at most 25 views per invocation')
if a.out.exists():raise FileExistsError('use a fresh attempt directory; do not overwrite rendered data')
a.out.mkdir(parents=True)
started=time.time();random.seed(a.seed);np.random.seed(a.seed)
bproc.init();devices=choose_device(a.gpu_name)
bpy.context.scene.render.threads_mode='FIXED';bpy.context.scene.render.threads=6
# Control objects use the observed source support 1..39. New obj40 is
# conditioned into the set, never into a fixed pose or camera centre.
candidates=[i for i in range(1,40) if i!=a.target_id]
ids=[a.target_id]+np.random.choice(candidates,size=19,replace=False).tolist()
np.random.shuffle(ids)
targets=bproc.loader.load_bop_objs(str(a.assets/'bop/handal'),obj_ids=ids,object_model_unit='mm',move_origin_to_x_y_plane=False)
distractors=[];distractor_ids={}
for dataset,model_type in [('tless','cad'),('hb',''),('tyol','')]:
folder=a.assets/'bop'/dataset
info=folder/('models_cad' if model_type else 'models')/'models_info.json'
available=sorted(map(int,json.loads(info.read_text())))
chosen=np.random.choice(available,2,replace=False).tolist();distractor_ids[dataset]=chosen
distractors+=bproc.loader.load_bop_objs(str(folder),obj_ids=chosen,model_type=model_type,object_model_unit='mm')
all_objects=targets+distractors;np.random.shuffle(all_objects)
info=json.loads((a.assets/'bop/handal/models/models_info.json').read_text())
geometry={};asset_hashes={};material_samples=[]
for obj in all_objects:
obj.set_shading_mode('auto')
model_path=Path(obj.get_cp('model_path'));asset_hashes[str(model_path)]=sha(model_path)
if obj.get_cp('bop_dataset_name')=='handal':
oid=obj.get_cp('category_id');v=np.asarray([v.co[:] for v in obj.blender_obj.data.vertices])*np.asarray(obj.get_scale())
extent=np.ptp(v,axis=0)*1000;expected=[info[str(oid)][f'size_{x}'] for x in 'xyz']
if not np.allclose(extent,expected,atol=1.,rtol=.01):raise ValueError(f'CAD units/frame mismatch {oid}')
geometry[str(oid)]={'extent_mm':extent.tolist(),'local_centroid_m':v.mean(axis=0).tolist(),'uv_layers':len(obj.blender_obj.data.uv_layers)}
if not obj.blender_obj.data.uv_layers:raise ValueError('HANDAL texture UVs missing')
for mat in obj.blender_obj.data.materials:
for node in mat.node_tree.nodes:
if node.type=='TEX_IMAGE' and node.image:asset_hashes[node.image.filepath]=sha(node.image.filepath)
mat=obj.get_materials()[0]
if obj.get_cp('bop_dataset_name')=='tless':
grey=float(np.random.uniform(.1,.9));mat.set_principled_shader_value('Base Color',[grey,grey,grey,1])
rough=float(np.random.uniform(0,1));spec=float(np.random.uniform(0,1))
mat.set_principled_shader_value('Roughness',rough);mat.set_principled_shader_value('Specular IOR Level',spec)
material_samples.append({'dataset':obj.get_cp('bop_dataset_name'),'id':obj.get_cp('category_id'),'roughness':rough,'specular_ior_level':spec})
obj.enable_rigidbody(True,mass=1.,friction=100.,linear_damping=.99,angular_damping=.99)
planes=[bproc.object.create_primitive('PLANE',scale=[2,2,1]),
bproc.object.create_primitive('PLANE',scale=[2,2,1],location=[0,-2,2],rotation=[-np.pi/2,0,0]),
bproc.object.create_primitive('PLANE',scale=[2,2,1],location=[0,2,2],rotation=[np.pi/2,0,0]),
bproc.object.create_primitive('PLANE',scale=[2,2,1],location=[2,0,2],rotation=[0,-np.pi/2,0]),
bproc.object.create_primitive('PLANE',scale=[2,2,1],location=[-2,0,2],rotation=[0,np.pi/2,0])]
for plane in planes:plane.enable_rigidbody(False,collision_shape='BOX',mass=1.,friction=100.,linear_damping=.99,angular_damping=.99)
materials=bproc.loader.load_ccmaterials(str(a.assets/'cctextures'))
if len(materials)<8:raise ValueError('pilot material inventory incomplete')
room_material=np.random.choice(materials)
for plane in planes:plane.replace_materials(room_material)
ceiling=bproc.object.create_primitive('PLANE',scale=[3,3,1],location=[0,0,10]);lightmat=bproc.material.create('ceiling_emission')
emission=float(np.random.uniform(3,6));emission_color=np.random.uniform([.5,.5,.5,1],[1,1,1,1]).tolist()
lightmat.make_emissive(emission_strength=emission,emission_color=emission_color);ceiling.replace_materials(lightmat)
light=bproc.types.Light();light.set_energy(200)
light_color=np.random.uniform([.5,.5,.5],[1,1,1]);light.set_color(light_color)
light_position=bproc.sampler.shell(center=[0,0,0],radius_min=1.,radius_max=1.5,elevation_min=5,elevation_max=89);light.set_location(light_position)
def sample_pose(obj):
low=np.random.uniform([-.3,-.3,0],[-.2,-.2,0]);high=np.random.uniform([.2,.2,.4],[.3,.3,.6])
obj.set_location(np.random.uniform(low,high));obj.set_rotation_euler(bproc.sampler.uniformSO3())
bproc.object.sample_poses(objects_to_sample=all_objects,sample_pose_func=sample_pose,max_tries=1000)
bproc.object.simulate_physics_and_fix_final_poses(min_simulation_time=3,max_simulation_time=10,
check_object_interval=1,substeps_per_frame=20,solver_iters=25)
bvh=bproc.object.create_bvh_tree_multi_objects(all_objects)
K=np.asarray(cfg['camera']['K']).reshape(3,3)
bproc.camera.set_intrinsics_from_K_matrix(K,cfg['camera']['width'],cfg['camera']['height'])
poses=[];attempts=0
while len(poses)<a.frames:
attempts+=1
if attempts>20000:raise RuntimeError('camera sampler could not find enough valid views')
pos=bproc.sampler.shell(center=[0,0,0],radius_min=.61,radius_max=1.4,elevation_min=5,elevation_max=89)
poi=bproc.object.compute_poi(np.random.choice(targets,size=15,replace=False))
rot=bproc.camera.rotation_from_forward_vec(poi-pos,inplane_rot=np.random.uniform(-np.pi,np.pi))
pose=bproc.math.build_transformation_mat(pos,rot)
if bproc.camera.perform_obstacle_in_view_check(pose,{'min':.3},bvh):
bproc.camera.add_camera_pose(pose,frame=len(poses));poses.append(np.asarray(pose).tolist())
bpy.context.scene.view_settings.view_transform=cfg['color_management']['view_transform']
bpy.context.scene.view_settings.look=cfg['color_management']['look']
bpy.context.scene.view_settings.exposure=0.;bpy.context.scene.view_settings.gamma=1.
bproc.renderer.set_max_amount_of_samples(cfg['samples']);bproc.renderer.set_denoiser('INTEL')
bproc.renderer.enable_depth_output(activate_antialiasing=False)
scene={'status':'scene_frozen_before_render','recipe_sha256':sha(a.config),'renderer_sha256':sha(Path(__file__)),
'seed':a.seed,'target_id':a.target_id,'target_ids':ids,'distractors':distractor_ids,'frames':a.frames,
'blender_version':bpy.app.version_string,'devices':devices,'geometry':geometry,'asset_sha256':asset_hashes,
'asset_inventory_sha256':sha(a.assets/'pilot_assets.json'),'material_samples':material_samples,
'room_material':room_material.get_name(),'emission':emission,'emission_color':emission_color,
'point_light_position_m':list(light_position),'point_light_color':list(light_color),
'object_world_poses_m':[{'dataset':o.get_cp('bop_dataset_name'),'id':o.get_cp('category_id'),'matrix':np.asarray(o.get_local2world_mat()).tolist()} for o in all_objects],
'camera_world_poses_m':poses,'camera_attempts':attempts,
'provenance':'measured reconstruction; original HANDAL lighting/material asset identity not recovered'}
(a.out/'scene_record.json').write_text(json.dumps(scene,indent=2)+'\n')
render_start=time.time();data=bproc.renderer.render();render_seconds=time.time()-render_start
bproc.writer.write_bop(str(a.out/'bop_data'),target_objects=targets,dataset='handal',
depths=data['depth'],colors=data['colors'],color_file_format='JPEG',jpg_quality=95,
depth_scale=1.,annotation_unit='mm',save_world2cam=True,frames_per_chunk=1000,
calc_mask_info_coco=True,num_worker=2,ignore_dist_thres=10)
receipt={'status':'render_and_bop_write_returned','frames':a.frames,'render_seconds':render_seconds,
'total_seconds':time.time()-started,'target_id':a.target_id,'seed':a.seed,
'note':'Completion requires separate image/mask/projection audit; not yet approved distribution match.'}
(a.out/'render_receipt.json').write_text(json.dumps(receipt,indent=2)+'\n')
print('LOCAL_HANDAL40_RENDER_RETURNED',json.dumps(receipt),flush=True)
if __name__=='__main__':main()
|