Download finalize_a.py from DenSnoychik/SonnetMakingNewRobloxRig: direct link, hf CLI and curl.
- Browser
- Download file 9.56 kB
-
https://huggingface.co/datasets/DenSnoychik/SonnetMakingNewRobloxRig/resolve/main/finalize_a.py
- Command line
-
hf download hf://datasets/DenSnoychik/SonnetMakingNewRobloxRig/finalize_a.py
-
curl -L -o finalize_a.py https://huggingface.co/datasets/DenSnoychik/SonnetMakingNewRobloxRig/resolve/main/finalize_a.py
9.56 kB
| import pickle, json, numpy as np, scipy.sparse as sp, scipy.sparse.csgraph as cg, os | |
| from scipy.ndimage import binary_closing | |
| from common import * | |
| from fit import Surf | |
| ROOT='..' | |
| res=pickle.load(open('fit_result.pkl','rb')); ref=ref_world() | |
| def clean(V,F,maxedge=None): | |
| if maxedge: | |
| el=np.max([np.linalg.norm(V[F[:,i]]-V[F[:,(i+1)%3]],axis=1) for i in range(3)],axis=0); F=F[el<maxedge] | |
| n=len(V); E=np.vstack([F[:,[0,1]],F[:,[1,2]],F[:,[2,0]]]) | |
| A=sp.coo_matrix((np.ones(len(E)),(E[:,0],E[:,1])),shape=(n,n)); k,lab=cg.connected_components(A,directed=False) | |
| fl=lab[F[:,0]]; cnt=np.bincount(fl,minlength=k) | |
| keep=cnt[fl]>=max(0.04*cnt.max(),30); F=F[keep] | |
| used=np.unique(F); rm=-np.ones(n,int); rm[used]=np.arange(len(used)); return V[used],rm[F] | |
| def vnormals(V,F): | |
| N=np.zeros_like(V); e=[V[F[:,1]]-V[F[:,0]],V[F[:,2]]-V[F[:,1]],V[F[:,0]]-V[F[:,2]]] | |
| fn=np.cross(e[0],-e[2]) | |
| for k in range(3): | |
| a=-e[(k+2)%3]; b=e[k] | |
| ang=np.arccos(np.clip((a*b).sum(1)/np.maximum(np.linalg.norm(a,axis=1)*np.linalg.norm(b,axis=1),1e-12),-1,1)) | |
| nn=fn/np.maximum(np.linalg.norm(fn,axis=1,keepdims=True),1e-12) | |
| np.add.at(N,F[:,k],nn*ang[:,None]) | |
| return N/np.maximum(np.linalg.norm(N,axis=1,keepdims=True),1e-12) | |
| final={} | |
| for n in PART_ORDER: | |
| V,F=clean(*res[n],maxedge=(0.28 if n.endswith(('Hand','Foot')) else 0.5)); final[n]=(V,F) | |
| pickle.dump(final,open('final_parts.pkl','wb')) | |
| # ---- OBJ ---- | |
| lines=['# rugc_reference_boy.obj - R15 mannequin for Roblox UGC accessory fitting','# Units: Roblox studs, Y-up, character front faces -Z (R15 Fixed rest pose, root-relative world coordinates)', | |
| '# Base mesh: MakeHuman hm08 base mesh (CC0), deformed part-by-part onto the ROBLOX Boy (Bundle 109) proportions. See LICENSE_AND_SOURCE.md','mtllib rugc_reference_boy.mtl'] | |
| off=0; vtxt=[];ntxt=[];ftxt=[];tot_v=tot_f=0 | |
| for n in PART_ORDER: | |
| V,F=final[n]; N=vnormals(V,F) | |
| ftxt.append(f'o {n}'); ftxt.append('usemtl Mannequin'); ftxt.append('s 1') | |
| vtxt+= [f'v {x:.4f} {y:.4f} {z:.4f}' for x,y,z in V] | |
| ntxt+= [f'vn {x:.3f} {y:.3f} {z:.3f}' for x,y,z in N] | |
| ftxt+= [f'f {a+off+1}//{a+off+1} {b+off+1}//{b+off+1} {c+off+1}//{c+off+1}' for a,b,c in F] | |
| off+=len(V); tot_v+=len(V); tot_f+=len(F) | |
| # write: all v, vn first then parts | |
| out=lines+vtxt+ntxt+ftxt | |
| open(f'{ROOT}/rugc_reference_boy.obj','w').write('\n'.join(out)+'\n') | |
| open(f'{ROOT}/rugc_reference_boy.mtl','w').write('# rugc_reference_boy.mtl\nnewmtl Mannequin\nKa 0.35 0.30 0.27\nKd 0.82 0.70 0.58\nKs 0.05 0.05 0.05\nNs 10\nd 1.0\nillum 2\n') | |
| print('obj',tot_v,tot_f,os.path.getsize(f'{ROOT}/rugc_reference_boy.obj')/1e6,'MB') | |
| # ---- attachments ---- | |
| def euler(R): | |
| R=np.array(R); sy=np.sqrt(R[0,0]**2+R[1,0]**2) | |
| x=np.arctan2(R[2,1],R[2,2]); y=np.arctan2(-R[2,0],sy); z=np.arctan2(R[1,0],R[0,0]) if sy>1e-6 else 0 | |
| return [round(float(np.degrees(v)),4)+0.0 for v in (x,y,z)] | |
| att={'schema':'roblox-r15-attachments-v1','units':'studs','pose':'R15 Fixed rest pose (arms/legs as in ROBLOX Boy bundle 109)','axes':'Y up, character front = -Z, character Right = +X', | |
| 'note':'Attachment CFrames are the real values stored in the Roblox assets of ROBLOX Boy: bundle 109 package assets 376532000/376530220/376531012/376531300/376531703 (R15Fixed folder) and the Roblox Classic Head asset 2432102561 (Vector3Value attachments). position/orientation are LOCAL to the part origin (partCFrame).','parts':{}} | |
| awx={} | |
| for n in PART_ORDER: | |
| d=ref[n]; t=d['t']; R=d['R'] | |
| pa={'partCFrame':{'position':[round(float(x),5) for x in t],'rotationMatrix':np.round(R,6).tolist()},'attachments':{}} | |
| for a,(Ra,p) in d['att'].items(): | |
| Ra=np.round(np.array(Ra),6)+0.0 | |
| wp=R@p+t; awx[(n,a)]=wp | |
| pa['attachments'][a]={'position':[round(float(x),5) for x in p],'orientationEulerXYZdeg':euler(Ra),'rotationMatrix':Ra.tolist(),'worldPositionInRestPose':[round(float(x),5) for x in wp]} | |
| att['parts'][n]=pa | |
| json.dump(att,open(f'{ROOT}/mannequin_attachments.json','w'),indent=1) | |
| # ---- metrics ---- | |
| def merge(parts,src): | |
| Vs=[];Fs=[];o=0 | |
| for n in parts: | |
| V,F=src[n]; Vs.append(V); Fs.append(F+o); o+=len(V) | |
| return np.vstack(Vs),np.vstack(Fs) | |
| refp={n:(ref[n]['V'],ref[n]['F']) for n in PART_ORDER} | |
| def sample(V,F,n,seed=0): | |
| A=V[F[:,0]];B=V[F[:,1]];C=V[F[:,2]]; ar=np.linalg.norm(np.cross(B-A,C-A),axis=1)/2 | |
| rng=np.random.default_rng(seed); ids=rng.choice(len(F),n,p=ar/ar.sum()); u=rng.random((n,2)); m=u.sum(1)>1; u[m]=1-u[m] | |
| return A[ids]+u[:,:1]*(B-A)[ids]+u[:,1:]*(C-A)[ids] | |
| from scipy.spatial import cKDTree | |
| VIEWS6={'front':(0,1,-1),'back':(0,1,1),'left':(2,1,-1),'right':(2,1,1),'top':(0,2,1),'bottom':(0,2,-1)} | |
| def mask(P,view,lo,hi,res=512): | |
| # orthographic silhouette via splat | |
| ax={'front':(0,1,1),'back':(0,1,-1),'left':(2,1,1),'right':(2,1,-1),'top':(0,2,-1),'bottom':(0,2,1)}[view] | |
| u=P[:,ax[0]]*ax[2]; v=P[:,ax[1]] | |
| # square pixels from global bounds | |
| lo_,hi_=lo,hi | |
| ix=((u-lo_)/(hi_-lo_)*(res-1)).astype(int); iy=((v-lo_)/(hi_-lo_)*(res-1)).astype(int) | |
| ok=(ix>=0)&(ix<res)&(iy>=0)&(iy<res) | |
| M=np.zeros((res,res),bool); M[iy[ok],ix[ok]]=True | |
| return binary_closing(M,iterations=2) | |
| def iou(a,b): return float((a&b).sum()/max((a|b).sum(),1)) | |
| metrics={'parts':{}} | |
| LO,HI=-3.4,3.4 | |
| names=PART_ORDER | |
| for n in names: | |
| mv,mf=final[n]; rv,rf=refp[n] | |
| pm=sample(mv,mf,120000,1); pr=sample(rv,rf,120000,2) | |
| t1=cKDTree(pr); t2=cKDTree(pm); d1=t1.query(pm)[0]; d2=t2.query(pr)[0] | |
| ious={v:round(iou(mask(pm,v,LO,HI),mask(pr,v,LO,HI)),4) for v in VIEWS6} | |
| metrics['parts'][n]={'silhouetteIoU':ious,'meanSilhouetteIoU':round(float(np.mean(list(ious.values()))),4), | |
| 'chamfer_mean_studs':round(float((d1.mean()+d2.mean())/2),4),'surface_dist_95pct_studs':round(float(max(np.percentile(d1,95),np.percentile(d2,95))),4),'hausdorff_studs':round(float(max(d1.max(),d2.max())),4), | |
| 'bboxMine':[np.round(mv.min(0),3).tolist(),np.round(mv.max(0),3).tolist()],'bboxRef':[np.round(rv.min(0),3).tolist(),np.round(rv.max(0),3).tolist()], | |
| 'vertices':int(len(mv)),'triangles':int(len(mf))} | |
| mV,mF=merge(names,final); rV,rF=merge(names,refp) | |
| pm=sample(mV,mF,500000,3); pr=sample(rV,rF,500000,4) | |
| metrics['whole']={'silhouetteIoU':{v:round(iou(mask(pm,v,LO,HI),mask(pr,v,LO,HI)),4) for v in VIEWS6}} | |
| metrics['whole']['meanSilhouetteIoU']=round(float(np.mean(list(metrics['whole']['silhouetteIoU'].values()))),4) | |
| d1=cKDTree(pr).query(pm)[0]; d2=cKDTree(pm).query(pr)[0] | |
| metrics['whole'].update({'chamfer_mean_studs':round(float((d1.mean()+d2.mean())/2),4),'surface_dist_95pct_studs':round(float(max(np.percentile(d1,95),np.percentile(d2,95))),4),'hausdorff_studs':round(float(max(d1.max(),d2.max())),4), | |
| 'heightMine':round(float(mV[:,1].max()-mV[:,1].min()),4),'heightRef':round(float(rV[:,1].max()-rV[:,1].min()),4),'bboxMine':[np.round(mV.min(0),3).tolist(),np.round(mV.max(0),3).tolist()],'bboxRef':[np.round(rV.min(0),3).tolist(),np.round(rV.max(0),3).tolist()],'vertices':int(len(mV)),'triangles':int(len(mF))}) | |
| # ---- attachment fit zones ---- | |
| def ray_first(V,F,o,d): | |
| A=V[F[:,0]];e1=V[F[:,1]]-A;e2=V[F[:,2]]-A | |
| h=np.cross(d,e2); a=(e1*h).sum(1); ok=abs(a)>1e-12; f=np.where(ok,1/np.where(ok,a,1),0) | |
| s=o-A; u=f*(s*h).sum(1); q=np.cross(s,e1); v=f*(q@d); t=f*(e2*q).sum(1) | |
| m=ok&(u>=0)&(v>=0)&(u+v<=1)&(t>1e-5) | |
| return float(t[m].min()) if m.any() else None | |
| RAYS={'BodyFrontAttachment':(0,0,-1),'BodyBackAttachment':(0,0,1),'WaistFrontAttachment':(0,0,-1),'WaistBackAttachment':(0,0,1),'FaceFrontAttachment':(0,0,-1),'FaceCenterAttachment':(0,0,-1), | |
| 'HatAttachment':(0,1,0),'HairAttachment':(0,1,0),'NeckAttachment':(0,1,0),'LeftCollarAttachment':(0,1,0),'RightCollarAttachment':(0,1,0),'LeftShoulderAttachment':(0,1,0),'RightShoulderAttachment':(0,1,0),'LeftGripAttachment':(0,-1,0),'RightGripAttachment':(0,-1,0),'LeftFootAttachment':(0,-1,0),'RightFootAttachment':(0,-1,0)} | |
| mS={n:Surf(*final[n],n=60000) for n in names}; rS={n:Surf(*refp[n],n=60000) for n in names} | |
| fit=[] | |
| for (pn,an),wp in awx.items(): | |
| if an not in RAYS: continue | |
| d=np.array(RAYS[an],float) | |
| # ray against the whole body (all parts) so overlapping parts count | |
| def sgn(V,F): | |
| tp=ray_first(V,F,wp,d); tn=ray_first(V,F,wp,-d) | |
| c=[x for x in (tp,-tn if tn is not None else None) if x is not None] | |
| return tp if tp is not None else (-tn if tn is not None else None) | |
| hm=sgn(mV,mF); hr=sgn(rV,rF) | |
| nm=min(np.linalg.norm(mS[q].project(wp[None])[0]-wp) for q in names); nr=min(np.linalg.norm(rS[q].project(wp[None])[0]-wp) for q in names) | |
| fit.append({'part':pn,'attachment':an,'worldPos':np.round(wp,4).tolist(),'rayDir':list(RAYS[an]),'signedAxisDistanceToSurface_ref':None if hr is None else round(hr,4),'signedAxisDistanceToSurface_mine':None if hm is None else round(hm,4), | |
| 'axisDistanceDelta':None if (hr is None or hm is None) else round(hm-hr,4),'nearestSurface_ref':round(float(nr),4),'nearestSurface_mine':round(float(nm),4)}) | |
| metrics['attachmentFit']=fit | |
| json.dump(metrics,open('metrics_tmp.json','w'),indent=1) | |
| print(json.dumps({k:(v['meanSilhouetteIoU'],v['chamfer_mean_studs'],v['surface_dist_95pct_studs']) for k,v in metrics['parts'].items()},indent=0)) | |
| print(metrics['whole']['silhouetteIoU'],metrics['whole']['chamfer_mean_studs'],metrics['whole']['surface_dist_95pct_studs'],metrics['whole']['hausdorff_studs']) | |
| for f in fit: print(f['part'],f['attachment'],f['signedAxisDistanceToSurface_ref'],f['signedAxisDistanceToSurface_mine'],f['axisDistanceDelta'],f['nearestSurface_ref'],f['nearestSurface_mine']) | |