"""Render matched CASTAIGNE25 views with explicitly labelled USD diagnostics. The overlays project actual composed geometry, joint frames and missing source components into the fixed camera. They are diagnostic diagrams, not simulated motion or calibrated measurements. """ import argparse import fcntl import hashlib from importlib.metadata import version import json from pathlib import Path import random import time import traceback REVISION = '4763fbfaa4f8e97658e68b57d01b4c86659e08b5' CAMERAS = { 'R01': (1.05, -1.3, .65), 'R02': (1.3, -.9, .75), 'R03': (1.05, -1.35, .75), 'R04': (1.1, -1.3, 1.8), 'R05': (1.2, -1.5, .75), 'R06': (1.25, -1.0, .7), 'R07': (1.3, -1.2, .8), 'R08': (1.3, -.85, .8), 'R09': (1.15, -1.4, .72), 'R10': (1.2, -1.4, .8), 'R11': (1.5, -.9, .65), 'R12': (1.1, -1.3, 1.25), 'R13': (1.15, -1.5, .8), 'R14': (.9, -1.0, 1.7), 'R15': (.9, -1.0, 1.7), 'R16': (1.15, -1.4, .72), 'R17': (1.15, -1.3, .7), 'R18': (1.3, -1.0, .7), 'R19': (.8, -1.0, 1.7), 'R20': (1.8, -.9, .8), 'R21': (1.15, -1.0, 1.3), 'R22': (1.3, -1.1, .65), 'R23': (1.25, -1.2, .8), 'R24': (1.2, -1.45, .8), 'R25': (1.25, -1.4, .9), } JOINTS = { 'R01': ['piston_02_joint_01', 'support_01'], 'R02': ['rail_01', 'rail_03', 'drawer_02', 'drawer_05'], 'R03': ['arm_02'], 'R04': ['sm_roller17_', 'sm_roller47_', 'sm_roller68_'], 'R05': ['topladder_', 'middleladder_'], 'R06': ['dripStand_01', 'dripStand_02', 'lowSlider_02'], 'R07': ['table_01', 'plate_01'], 'R08': ['door_01', 'rack_01', 'rack_02'], 'R09': ['sm_frontwheel2_', 'sm_rotatingpart_'], 'R10': ['part_01', 'wheel_02'], 'R11': ['blade_01', 'frame_01'], 'R12': ['slidingJaw_01', 'screw_01'], 'R13': ['body_01'], 'R14': ['jaw_01', 'hanlde_02'], 'R15': ['jaw_01', 'knurl_01'], 'R16': ['wheelPin_01', 'wheel_03'], 'R17': ['tireBase_02'], 'R18': ['lockerDoor_04'], 'R19': ['blade_01'], 'R20': ['caliper_01'], 'R21': ['lid_01'], } MISSING = { 'R03': 'handle_02_', 'R04': 'sm_roller03_', 'R13': 'handDrill_01_', 'R17': 'tire_01_', 'R18': 'lockerDoor_01_', 'R22': 'glass_01_', 'R23': 'sm_pallet_wood_recycled_a03_', 'R25': 'engine_02_', } COLLIDERS = { 'R01': 'arm_01_', 'R02': 'body_01_', 'R05': 'mainladder_', 'R08': 'body_01_', 'R10': 'body_01_', 'R11': 'frame_01_', 'R12': 'slidingJaw_01_', 'R14': 'jaw_01_', 'R15': 'body_01_', 'R19': 'body_01_', 'R20': 'caliper_01_', 'R21': 'body_01_', 'R24': 'sm_drum_a02_', } def digest(path): with Path(path).open('rb') as stream: return hashlib.file_digest(stream, 'sha256').hexdigest() def save(path, data): path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(data, indent=2) + '\n') def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--manifest', type=Path, required=True) parser.add_argument('--input-root', type=Path, required=True) parser.add_argument('--output', type=Path, required=True) parser.add_argument('--case', default='all') parser.add_argument('--width', type=int, default=1280) parser.add_argument('--height', type=int, default=720) parser.add_argument('--wait-inputs', type=int, default=900) args = parser.parse_args() output = args.output.resolve() output.mkdir(parents=True, exist_ok=True) cases = json.loads(args.manifest.read_text())['cases'] cases = [c for c in cases if args.case in ('all', c['case_id'])] inventory = {'schema': 'simrepairbench-preview-images-v1', 'source_revision': REVISION, 'cases': [], 'completed': False, 'scope': 'Matched rendered asset views; labelled overlays show authored USD diagnostics, not simulated motion'} app = None lock = open('/dev/shm/simready-global-gpu.lock', 'a') try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) random.seed(1729) import numpy as np np.random.seed(1729) from isaacsim import SimulationApp app = SimulationApp({'headless': True, 'width': args.width, 'height': args.height, 'renderer': 'RaytracedLighting', 'extra_args': ['--/app/extensions/registryEnabled=false']}) import carb import omni.usd import omni.timeline import omni.replicator.core as rep from pxr import Gf, Sdf, Usd, UsdGeom, UsdLux, UsdPhysics from PIL import Image, ImageDraw, ImageFont from scipy.spatial import ConvexHull carb.settings.get_settings().set('/rtx/post/histogram/enabled', False) rep.orchestrator.set_capture_on_play(False) renderer = {'name': 'Isaac Sim RaytracedLighting', 'isaacsim_version': version('isaacsim'), 'usd_version': list(Usd.GetVersion()), 'auto_exposure': False, 'driver_sha256': digest(__file__)} font_path = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf' font = ImageFont.truetype(font_path, 24) if Path(font_path).exists() else ImageFont.load_default() small = ImageFont.truetype(font_path, 17) if Path(font_path).exists() else ImageFont.load_default() def find_body(stage, token): return next((p for p in stage.Traverse(Usd.TraverseInstanceProxies()) if p.HasAPI(UsdPhysics.RigidBodyAPI) and token.lower() in p.GetName().lower()), None) def joint_data(stage, tokens): cache = UsdGeom.XformCache() rows = [] for p in stage.Traverse(Usd.TraverseInstanceProxies()): if not p.IsA(UsdPhysics.Joint) or not any(t.lower() in p.GetName().lower() for t in tokens): continue axis = {'X': 0, 'Y': 1, 'Z': 2}.get(str(p.GetAttribute('physics:axis').Get()), 0) anchors, axes, unresolved = [], [], [] for side in (0, 1): targets = p.GetRelationship(f'physics:body{side}').GetTargets() target = stage.GetPrimAtPath(targets[0]) if targets else None if targets and (not target or not target.IsActive()): anchors.append(None);axes.append(None);unresolved.append(str(targets[0]));continue matrix = cache.GetLocalToWorldTransform(target) if target else Gf.Matrix4d(1) pos = p.GetAttribute(f'physics:localPos{side}').Get() or Gf.Vec3f(0) rot = p.GetAttribute(f'physics:localRot{side}').Get() or Gf.Quatf(1) anchors.append(list(matrix.Transform(Gf.Vec3d(*pos)))) local = [0., 0., 0.]; local[axis] = 1. direction = matrix.TransformDir(Gf.Rotation(rot).TransformDir(Gf.Vec3d(*local))) axes.append(list(direction.GetNormalized())) rows.append({'path': str(p.GetPath()), 'name': p.GetName(), 'anchors': anchors, 'axes': axes, 'unresolved_targets': unresolved}) return rows def body_bounds(stage, body): b = UsdGeom.BBoxCache(Usd.TimeCode.Default(), ['default', 'render']).ComputeWorldBound(body).ComputeAlignedRange() lo, hi = np.asarray(b.GetMin()), np.asarray(b.GetMax()) return np.array([[x, y, z] for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])]) def explicit_mass(stage, body): root_mass = UsdPhysics.MassAPI(body) if root_mass and root_mass.GetMassAttr().HasAuthoredValueOpinion() and root_mass.GetMassAttr().Get() > 0: return float(root_mass.GetMassAttr().Get()) return sum(float(UsdPhysics.MassAPI(p).GetMassAttr().Get()) for p in Usd.PrimRange(body, Usd.TraverseInstanceProxies()) if p.HasAPI(UsdPhysics.MassAPI) and UsdPhysics.MassAPI(p).GetMassAttr().HasAuthoredValueOpinion() and UsdPhysics.MassAPI(p).GetMassAttr().Get() > 0) for case in cases: cid, asset = case['case_id'], case['source']['asset_id'] folder = args.input_root / cid marker = folder / 'READY.json' waited = 0 while not marker.exists(): if waited >= args.wait_inputs: raise TimeoutError('Inputs not staged for ' + cid) time.sleep(2); waited += 2 request = json.loads(marker.read_text()) source, broken = Path(request['source']), Path(request['broken']) if digest(source) != request['original_asset_sha256'] or digest(broken) != request['broken_asset_sha256']: raise ValueError('Input digest mismatch: ' + cid) reference = Usd.Stage.Open(str(source.resolve())) bounds = UsdGeom.BBoxCache(Usd.TimeCode.Default(), ['default', 'render']).ComputeWorldBound(reference.GetDefaultPrim()).ComputeAlignedRange() low, high = np.asarray(bounds.GetMin()), np.asarray(bounds.GetMax()) center, dimensions = (low + high)/2, high-low span = float(max(dimensions)) placement = np.array([-center[0], -center[1], .025-low[2]]) target = np.array([0., 0., dimensions[2]*.48+.025]) direction = np.asarray(CAMERAS[cid]); direction /= np.linalg.norm(direction) # Fit the source once, including space for the diagnostic labels. # Reusing this exact camera for the broken stage reveals placement # differences instead of hiding them through independent refitting. corners=np.array([[x,y,z] for x in (low[0],high[0]) for y in (low[1],high[1]) for z in (low[2],high[2])])+placement focal = args.width*35./36. def camera_at(distance): position=target+direction*distance matrix=Gf.Matrix4d().SetLookAt(Gf.Vec3d(*position),Gf.Vec3d(*target),Gf.Vec3d(0,0,1)).GetInverse() cp=np.c_[corners,np.ones(8)]@np.linalg.inv(np.asarray(matrix));depth=-cp[:,2] xy=np.c_[args.width/2+focal*cp[:,0]/depth,args.height/2-focal*cp[:,1]/depth] fits=bool((depth>span*.05).all() and xy[:,0].min()>=50 and xy[:,0].max()<=args.width-50 and xy[:,1].min()>=112 and xy[:,1].max()<=args.height-62) return position,matrix,xy,fits near,far=span*.5,span*10 for _ in range(35): middle=(near+far)/2 if camera_at(middle)[3]:far=middle else:near=middle distance=far*1.08 eye,camera_matrix,fitted_pixels,fit_ok=camera_at(distance) if not fit_ok:raise ValueError('Source does not fit the fixed preview camera: '+cid) inverse = np.linalg.inv(np.asarray(camera_matrix)) def project(points): points = np.asarray(points) camera_points = np.c_[points, np.ones(len(points))] @ inverse depth = -camera_points[:,2] return np.c_[args.width/2 + focal*camera_points[:,0]/depth, args.height/2 - focal*camera_points[:,1]/depth], depth settings = {'resolution': [args.width, args.height], 'seed': 1729, 'camera_to_world_rows': [[float(v) for v in row] for row in camera_matrix], 'camera_position': eye.tolist(), 'camera_target': target.tolist(), 'focal_length_mm': 35., 'horizontal_aperture_mm': 36., 'source_bounds': [low.tolist(), high.tolist()], 'source_bounds_projected_pixels': [fitted_pixels.min(axis=0).tolist(),fitted_pixels.max(axis=0).tolist()], 'placement_translation': placement.tolist(), 'dome_intensity': 350., 'key_intensity': 2200., 'key_rotation_degrees': [0., 72., -60.], 'capture_subframes_each': 12, 'capture_passes': 3, 'timeline_delta_time': 0.0} entry = {'case_id': cid, 'asset_id': asset, 'source_revision': REVISION, 'renderer': renderer, 'settings': settings, 'diagnostic_overlay': {'labelled': True, 'joint_tokens': JOINTS.get(cid, []), 'missing_component_token': MISSING.get(cid), 'collision_component_token': COLLIDERS.get(cid), 'scope': 'Projected authored joint frames, collider meshes/hulls or source component bounds; no simulated motion'}, 'rendered': {}} source_joints = source_missing_bounds = None for role, path in [('original', source), ('broken', broken)]: if not omni.usd.get_context().open_stage(str(path.resolve())): raise ValueError('Could not open ' + role + ' ' + cid) for _ in range(20): app.update() stage = omni.usd.get_context().get_stage() stage.SetEditTarget(stage.GetSessionLayer()) root = stage.GetDefaultPrim() x = UsdGeom.Xformable(root) original_root_transform = x.GetLocalTransformation() x.MakeMatrixXform().Set(original_root_transform*Gf.Matrix4d().SetTranslate(Gf.Vec3d(*placement))) ground = UsdGeom.Mesh.Define(stage, '/PreviewGround') ground.CreatePointsAttr([(-span*5,-span*5,0),(span*5,-span*5,0),(span*5,span*5,0),(-span*5,span*5,0)]) ground.CreateFaceVertexCountsAttr([4]);ground.CreateFaceVertexIndicesAttr([0,1,2,3]) ground.CreateDisplayColorAttr([(.16,.18,.20)]) dome = UsdLux.DomeLight.Define(stage, '/PreviewDome');dome.CreateIntensityAttr(350.) key = UsdLux.DistantLight.Define(stage, '/PreviewKey');key.CreateIntensityAttr(2200.);key.CreateAngleAttr(.53) UsdGeom.Xformable(key).AddTransformOp().Set(Gf.Matrix4d().SetRotate(Gf.Rotation(Gf.Vec3d(0,1,0),72))*Gf.Matrix4d().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1),-60))) camera_schema = UsdGeom.Camera.Define(stage, '/PreviewCamera') camera_schema.CreateFocalLengthAttr(35.);camera_schema.CreateHorizontalApertureAttr(36.) camera_schema.CreateVerticalApertureAttr(36.*args.height/args.width) camera_schema.CreateClippingRangeAttr((.001, max(100., span*20))) UsdGeom.Xformable(camera_schema).AddTransformOp().Set(camera_matrix) product=rep.create.render_product('/PreviewCamera',(args.width,args.height),force_new=True) rgb_annotator=rep.AnnotatorRegistry.get_annotator('rgb');rgb_annotator.attach([product]) timeline=omni.timeline.get_timeline_interface();time_before=timeline.get_current_time() for _ in range(settings['capture_passes']): rep.orchestrator.step(rt_subframes=settings['capture_subframes_each'],pause_timeline=True,delta_time=0.0) data=rgb_annotator.get_data();rgba=np.asarray(data['data'] if isinstance(data,dict) else data) if rgba.shape not in ((args.height,args.width,4),(args.height,args.width,3)) or rgba.dtype!=np.uint8 or not rgba.max(): raise ValueError('Unreadable camera output: '+cid+' '+role+' '+repr((rgba.shape,str(rgba.dtype)))) time_after=timeline.get_current_time() if abs(time_after-time_before)>1e-8:raise ValueError('Static preview advanced simulation time') entry['rendered'].setdefault(role,{})['timeline_time_before_after']=[time_before,time_after] raw = Image.fromarray(rgba[:,:,:3]); raw.save(output/(cid+'-'+role+'-raw.png')) image = raw.convert('RGBA'); overlay = Image.new('RGBA',image.size,(0,0,0,0));draw=ImageDraw.Draw(overlay) joints = joint_data(stage, JOINTS.get(cid,[])) entry['rendered'].setdefault(role,{})['joint_frames'] = joints if role == 'original': source_joints = joints def line(points, color, width=3): xy, depth = project(points) if (depth > .0001).all() and np.isfinite(xy).all(): draw.line([tuple(p) for p in xy],fill=color,width=width) def cross(point,color=(255,75,55,255),size=9): xy,depth=project([point]);px,py=xy[0] if depth[0]>.0001: draw.line([(px-size,py-size),(px+size,py+size)],fill=color,width=4) draw.line([(px-size,py+size),(px+size,py-size)],fill=color,width=4) for joint in joints: if joint['unresolved_targets']: continue a=np.asarray(joint['anchors']);axis=np.asarray(joint['axes']) line(a,(255,110,55,240) if role=='broken' else (60,180,255,230),4) for side,color in [(0,(60,185,255,255)),(1,(80,240,170,255))]: line([a[side]-axis[side]*span*.045,a[side]+axis[side]*span*.045],color,4) xy,depth=project([a[side]]) if depth[0]>.0001: px,py=xy[0];draw.ellipse((px-5,py-5,px+5,py+5),fill=color) if role=='broken': present={j['path'] for j in joints} unresolved_paths={j['path'] for j in joints if j['unresolved_targets']} for j in source_joints: if j['path'] not in present or j['path'] in unresolved_paths: cross(np.mean(j['anchors'],axis=0)) missing = MISSING.get(cid) if missing: body=find_body(stage,missing) if role=='original': source_missing_bounds=body_bounds(stage,body) visible = bool(body and any(p.IsA(UsdGeom.Mesh) and UsdGeom.Imageable(p).ComputeVisibility()!='invisible' for p in Usd.PrimRange(body,Usd.TraverseInstanceProxies()))) if source_missing_bounds is not None: color=(70,185,255,180) if role=='original' else (255,85,55,230) for a,b in [(0,1),(0,2),(0,4),(1,3),(1,5),(2,3),(2,6),(3,7),(4,5),(4,6),(5,7),(6,7)]:line(source_missing_bounds[[a,b]],color,2) if not visible: cross(source_missing_bounds.mean(axis=0),size=12) entry['rendered'].setdefault(role,{})['selected_component_visible']=visible entry['rendered'][role]['source_component_bounds_world']=source_missing_bounds.tolist() if source_missing_bounds is not None else None collision=COLLIDERS.get(cid) if collision: body=find_body(stage,collision) edges=[] if body: for p in Usd.PrimRange(body,Usd.TraverseInstanceProxies()): if not p.IsA(UsdGeom.Mesh) or not p.HasAPI(UsdPhysics.CollisionAPI) or not UsdPhysics.CollisionAPI(p).GetCollisionEnabledAttr().Get():continue m=UsdGeom.Mesh(p);points=np.asarray(m.GetPointsAttr().Get());world=np.c_[points,np.ones(len(points))]@np.asarray(UsdGeom.XformCache().GetLocalToWorldTransform(p));world=world[:,:3] approximation=UsdPhysics.MeshCollisionAPI(p).GetApproximationAttr().Get() if p.HasAPI(UsdPhysics.MeshCollisionAPI) else None if approximation=='convexHull': hull=ConvexHull(world);pairs=sorted({tuple(sorted((int(a),int(b)))) for tri in hull.simplices for a,b in [(tri[0],tri[1]),(tri[1],tri[2]),(tri[2],tri[0])]}) else: counts=m.GetFaceVertexCountsAttr().Get();indices=m.GetFaceVertexIndicesAttr().Get();pairs=[];offset=0 stride=max(1,len(counts)//150) for fi,count in enumerate(counts): face=indices[offset:offset+count];offset+=count if fi%stride==0:pairs.extend((int(face[i]),int(face[(i+1)%count])) for i in range(count)) for a,b in pairs[:650]:line(world[[a,b]],(255,165,65,150) if role=='broken' else (75,175,255,110),2) edges.append({'prim':str(p.GetPath()),'approximation':str(approximation),'drawn_edges':min(len(pairs),650)}) entry['rendered'].setdefault(role,{})['collider_overlays']=edges title=f"{cid} {case['title']} | {'Original' if role=='original' else 'Broken'}" draw.rectangle((0,0,args.width,78),fill=(12,19,27,225));draw.text((22,11),title,font=font,fill=(245,248,250,255)) label='Joint / collision diagnostic overlay' if joints or collision else 'Missing geometry diagnostic' if missing else 'Rendered asset view' if cid=='R24': body=find_body(stage,'sm_drum_a02_');label=f'Authored mass diagnostic: drum {explicit_mass(stage,body):.3g} kg | Collider overlay' draw.text((22,47),label,font=small,fill=(190,215,235,255)) if joints or collision or missing: draw.rectangle((0,args.height-31,args.width,args.height),fill=(12,19,27,215)) draw.text((22,args.height-25),'Diagnostic projections from composed USD; not simulated motion',font=small,fill=(205,220,231,255)) image=Image.alpha_composite(image,overlay).convert('RGB') final=output/(cid+'-'+role+'.png');image.save(final,compress_level=5) entry[role]={'path':'previews/'+final.name,'sha256':digest(final),'asset_sha256':digest(path)} rgb_annotator.detach([product]) if hasattr(product,'destroy'):product.destroy() elif isinstance(product,str):stage.RemovePrim(product) print(json.dumps({'case_id':cid,'role':role,'image':str(final)}),flush=True) omni.usd.get_context().new_stage() for _ in range(5):app.update() inventory['cases'].append(entry) save(output/(cid+'.json'),entry);save(output/'manifest.json',inventory) save(folder/'DONE.json',{'case_id':cid,'completed':True}) inventory['completed']=True except Exception as exc: inventory['error']={'type':type(exc).__name__,'message':str(exc)} traceback.print_exc() finally: save(output/'manifest.json',inventory) print(json.dumps({'completed':inventory['completed'],'cases':len(inventory['cases']),'error':inventory.get('error')}),flush=True) if app:app.close() lock.close() return 0 if inventory['completed'] else 1 if __name__=='__main__': raise SystemExit(main())