Download ORCASat/ORCASat_CAD/source/export_glb.py from 5PACE/5PACE3Dmodelsatellites: direct link, hf CLI and curl.
- Browser
- Download file 10.8 kB
-
https://huggingface.co/datasets/5PACE/5PACE3Dmodelsatellites/resolve/main/ORCASat/ORCASat_CAD/source/export_glb.py
- Command line
-
hf download hf://datasets/5PACE/5PACE3Dmodelsatellites/ORCASat/ORCASat_CAD/source/export_glb.py
-
curl -L -o export_glb.py https://huggingface.co/datasets/5PACE/5PACE3Dmodelsatellites/resolve/main/ORCASat/ORCASat_CAD/source/export_glb.py
10.8 kB
| #!/usr/bin/env python3 | |
| """Export every reconstructed ORCASat component and solid as binary glTF 2.0. | |
| glTF: metres, +Y along ram, +Z nadir, -X starboard. Right-handed rotation. | |
| Standalone part/solid geometry is centred; manifest preserves satellite placement. | |
| Assembly and module geometry use the satellite origin, not individual origins. | |
| """ | |
| from pathlib import Path | |
| import csv, hashlib, json, struct | |
| import numpy as np | |
| import cadquery as cq | |
| import build_orcasat as b | |
| TOLERANCE_MM=.08 | |
| ANGULAR_TOLERANCE_RAD=.30 | |
| def vector_glb(v): | |
| x,y,z=v | |
| return np.array([-x,z,y],dtype=float)*.001 | |
| def point_glb(v): | |
| return vector_glb((v[0],v[1],v[2]-113.5)) | |
| def tessellate_absolute(shape): | |
| # Absolute linear deflection prevents sub-millimetre spline wires from | |
| # receiving hundreds of thousands of triangles under relative meshing. | |
| from OCP.BRepTools import BRepTools | |
| from OCP.BRepMesh import BRepMesh_IncrementalMesh | |
| from OCP.BRep import BRep_Tool | |
| from OCP.TopLoc import TopLoc_Location | |
| from OCP.TopAbs import TopAbs_Orientation | |
| if not BRepTools.Triangulation_s(shape.wrapped,TOLERANCE_MM): | |
| mesher=BRepMesh_IncrementalMesh(shape.wrapped,TOLERANCE_MM,False,ANGULAR_TOLERANCE_RAD,True) | |
| assert mesher.IsDone(), 'Triangulation failed' | |
| verts=[];tris=[];offset=0 | |
| for face in shape.Faces(): | |
| location=TopLoc_Location();poly=BRep_Tool.Triangulation_s(face.wrapped,location) | |
| if poly is None:continue | |
| transform=location.Transformation() | |
| verts.extend(cq.Vector(poly.Node(i).Transformed(transform)) for i in range(1,poly.NbNodes()+1)) | |
| reverse=face.wrapped.Orientation()==TopAbs_Orientation.TopAbs_REVERSED | |
| for triangle in poly.Triangles(): | |
| a,c,d=triangle.Get() | |
| tris.append((a+offset-1,d+offset-1,c+offset-1) if reverse else (a+offset-1,c+offset-1,d+offset-1)) | |
| offset+=poly.NbNodes() | |
| return verts,tris | |
| def triangulate(shape): | |
| verts,tris=tessellate_absolute(shape) | |
| v=np.array([[q.x,q.y,q.z] for q in verts],dtype=np.float64) | |
| t=np.array(tris,dtype=np.uint32) | |
| if not len(t):raise ValueError('Solid has no triangulation') | |
| face=np.cross(v[t[:,1]]-v[t[:,0]],v[t[:,2]]-v[t[:,0]]) | |
| good=np.linalg.norm(face,axis=1)>1e-12 | |
| t=t[good];face=face[good] | |
| n=np.zeros_like(v) | |
| for k in range(3):np.add.at(n,t[:,k],face) | |
| ll=np.linalg.norm(n,axis=1) | |
| n[ll<1e-15]=(0,0,1);ll[ll<1e-15]=1 | |
| n/=ll[:,None] | |
| # Drop unused vertices left by zero-area OCCT seam triangles. | |
| used,inv=np.unique(t,return_inverse=True) | |
| return v[used],n[used],inv.reshape(-1,3).astype(np.uint32) | |
| def convert_mesh(v,n,t,centre): | |
| q=v-centre | |
| pos=np.column_stack((-q[:,0],q[:,2],q[:,1]))*.001 | |
| nor=np.column_stack((-n[:,0],n[:,2],n[:,1])) | |
| return pos.astype('<f4'),nor.astype('<f4'),t.astype('<u4') | |
| class GLB: | |
| def __init__(self,title): | |
| self.bin=bytearray();self.doc={'asset':{'version':'2.0','generator':'ORCASat reference reconstruction '+b.VERSION+' / CadQuery 2.7','extras':{'units':'metres','upAxis':'+Y','referenceModel':True}},'scene':0,'scenes':[{'name':title,'nodes':[0]}],'nodes':[{'name':title,'children':[]}],'meshes':[],'materials':[],'accessors':[],'bufferViews':[],'buffers':[]} | |
| self.materials={} | |
| def array(self,arr,target,kind): | |
| while len(self.bin)%4:self.bin.append(0) | |
| offset=len(self.bin);raw=arr.tobytes();self.bin.extend(raw) | |
| vi=len(self.doc['bufferViews']);self.doc['bufferViews'].append({'buffer':0,'byteOffset':offset,'byteLength':len(raw),'target':target}) | |
| ac={'bufferView':vi,'componentType':5126 if arr.dtype.kind=='f' else 5125,'count':len(arr),'type':kind} | |
| if kind=='VEC3':ac.update({'min':arr.min(0).astype(float).tolist(),'max':arr.max(0).astype(float).tolist()}) | |
| ai=len(self.doc['accessors']);self.doc['accessors'].append(ac);return ai | |
| def material(self,col): | |
| if col in self.materials:return self.materials[col] | |
| metal=.7 if col in ['al','bright','gold','copper','copperback','battery'] else .05 | |
| rgb=b.COL[col];mat={'name':col,'pbrMetallicRoughness':{'baseColorFactor':[float(c) for c in rgb]+[1.0],'metallicFactor':metal,'roughnessFactor':.45 if metal>.5 else .72}} | |
| idx=len(self.doc['materials']);self.doc['materials'].append(mat);self.materials[col]=idx;return idx | |
| def node(self,name,parent=0,extras=None): | |
| idx=len(self.doc['nodes']);d={'name':name,'children':[]} | |
| if extras:d['extras']=extras | |
| self.doc['nodes'].append(d);self.doc['nodes'][parent]['children'].append(idx);return idx | |
| def mesh(self,name,arrays,col,parent=0,translation=None,extras=None): | |
| pos,nor,tri=arrays | |
| pa=self.array(pos,34962,'VEC3');na=self.array(nor,34962,'VEC3');ia=self.array(tri.reshape(-1),34963,'SCALAR') | |
| idx=len(self.doc['meshes']);self.doc['meshes'].append({'name':name,'primitives':[{'attributes':{'POSITION':pa,'NORMAL':na},'indices':ia,'material':self.material(col),'mode':4}]}) | |
| n=self.node(name,parent,extras);self.doc['nodes'][n]['mesh']=idx | |
| if translation is not None:self.doc['nodes'][n]['translation']=[float(x) for x in translation] | |
| def save(self,path): | |
| path=Path(path);path.parent.mkdir(parents=True,exist_ok=True) | |
| self.doc['buffers']=[{'byteLength':len(self.bin)}] | |
| for node in self.doc['nodes']: | |
| if not node.get('children'):node.pop('children',None) | |
| raw=json.dumps(self.doc,separators=(',',':'),ensure_ascii=True).encode() | |
| raw+=b' '*((-len(raw))%4);self.bin.extend(b'\0'*((-len(self.bin))%4)) | |
| total=12+8+len(raw)+8+len(self.bin) | |
| with path.open('wb') as f: | |
| f.write(struct.pack('<4sII',b'glTF',2,total));f.write(struct.pack('<I4s',len(raw),b'JSON'));f.write(raw);f.write(struct.pack('<I4s',len(self.bin),b'BIN\0'));f.write(self.bin) | |
| def export_all(target): | |
| target=Path(target);target.mkdir(parents=True,exist_ok=True) | |
| cache={};rows=[];files=[];source_count=0 | |
| def finish(path,kind,components,solid_count): | |
| raw=path.read_bytes();files.append({'path':str(path.relative_to(target)),'kind':kind,'components':components,'solids':solid_count,'bytes':len(raw),'sha256':hashlib.sha256(raw).hexdigest()}) | |
| for pi,p in enumerate(b.PARTS): | |
| solids=p.shape.Solids();vv=[];nn=[];tt=[];base=0 | |
| bb=p.shape.BoundingBox();centre=np.array([(bb.xmin+bb.xmax)/2,(bb.ymin+bb.ymax)/2,(bb.zmin+bb.zmax)/2]) | |
| extra={'module':p.group,'state':p.state,'dimensional_status':p.note} | |
| for si,solid in enumerate(solids): | |
| v,n,t=triangulate(solid);vv.append(v);nn.append(n);tt.append(t+base);base+=len(v) | |
| # All physical solids have their own file, including compound contacts. | |
| own=(v.min(0)+v.max(0))/2 | |
| arr=convert_mesh(v,n,t,own) | |
| name=p.name+f'__Solid_{si+1:03d}' | |
| path=target/'solids'/p.group/(name+'.glb') | |
| g=GLB(name);g.mesh(name,arr,p.colour,extras=extra);g.save(path);finish(path,'solid',1,1) | |
| rows.append({'module':p.group,'component':p.name,'state':p.state,'solid':si+1,'path':str(path.relative_to(target)),'origin_gltf_m':point_glb(own).tolist(),'triangles':len(t),'kind':'solid'}) | |
| arr=convert_mesh(np.concatenate(vv),np.concatenate(nn),np.concatenate(tt),centre) | |
| cache[pi]=(arr,centre) | |
| path=target/'parts'/p.group/(p.name+'.glb') | |
| g=GLB(p.name);g.mesh(p.name,arr,p.colour,extras=extra);g.save(path);finish(path,'part',1,len(solids)) | |
| rows.append({'module':p.group,'component':p.name,'state':p.state,'solid':None,'path':str(path.relative_to(target)),'origin_gltf_m':point_glb(centre).tolist(),'triangles':len(arr[2]),'kind':'part'}) | |
| if pi%50==0:print('GLB components',pi+1,'/',len(b.PARTS),flush=True) | |
| def scene(name,state,view,group=None,face=None): | |
| g=GLB(name);groups={};count=0;ns=0 | |
| for pi,p in enumerate(b.PARTS): | |
| if not b.visible(p,state,view) or (group and p.group!=group):continue | |
| if face and not (p.name.startswith(face+'_') and p.group in ['07_Exterior_Panels','08_Sensors_Deployables']):continue | |
| if p.group not in groups:groups[p.group]=g.node(p.group) | |
| arr,centre=cache[pi] | |
| # Exploded placement is a translation; use actual CAD view transform. | |
| original=p.shape.BoundingBox();moved=b.moved(p,view).BoundingBox() | |
| delta=np.array([moved.xmin-original.xmin,moved.ymin-original.ymin,moved.zmin-original.zmin]) | |
| g.mesh(p.name,arr,p.colour,groups[p.group],point_glb(centre+delta),{'state':p.state,'dimensional_status':p.note,'solids':len(p.shape.Solids())}) | |
| count+=1;ns+=len(p.shape.Solids()) | |
| folder='modules' if group else 'panels' if face else 'assemblies' | |
| path=target/folder/(name+'.glb');g.save(path);finish(path,'module' if group else 'panel' if face else 'assembly',count,ns) | |
| for name,state,view in [('ORCASat_Stowed','stowed','full'),('ORCASat_Deployed','deployed','full'),('ORCASat_Internal','stowed','internal'),('ORCASat_Exploded','deployed','exploded')]:scene(name,state,view) | |
| for group in sorted({p.group for p in b.PARTS}): | |
| scene(group,'stowed','full',group=group) | |
| if any(p.group==group and p.state=='deployed' for p in b.PARTS):scene(group+'_Deployed','deployed','full',group=group) | |
| for face in ['Starboard','Port','Nadir','Zenith','Ram','Wake']: | |
| scene(face+'_Panel','stowed','full',face=face) | |
| manifest={'version':b.VERSION,'units':'metres','up_axis':'+Y','coordinate_mapping_from_STEP_body':'glTF=( -STEP_Y, STEP_X, STEP_Z ) / 1000','standalone_origin':'Each part or solid is centred. origin_gltf_m restores the stowed/deployed model placement of that source geometry. Assembly/module/panel scenes already use spacecraft-centred positions.','tessellation':{'absolute_linear_deflection_mm':TOLERANCE_MM,'angular_deflection_radians':ANGULAR_TOLERANCE_RAD},'components_defined':len(b.PARTS),'solids_defined':sum(len(p.shape.Solids()) for p in b.PARTS),'files':files,'items':rows} | |
| (target/'manifest.json').write_text(json.dumps(manifest,indent=2)) | |
| with (target/'placement_manifest.csv').open('w',newline='') as f: | |
| w=csv.writer(f);w.writerow(['kind','module','component','state','solid','path','origin_X_m','origin_Y_m','origin_Z_m','triangles']) | |
| for row in rows:w.writerow([row[k] for k in ['kind','module','component','state','solid','path']]+row['origin_gltf_m']+[row['triangles']]) | |
| print('GLB export complete:',len(files),'files',flush=True) | |
| return manifest | |
| if __name__=='__main__': | |
| import argparse | |
| ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path(__file__).resolve().parent.parent/'EXPORT');args=ap.parse_args() | |
| b.build();export_all(args.out) | |