Files
MeltMind/tools/g1_blind_pose.py
T

30 lines
2.5 KiB
Python

"""Proper rigid posing of stored surface geometry; no source archive access."""
import numpy as np
from g1_blind_geometry import surface
def read_surface(path):
lines=path.read_text('ascii').splitlines();n=int(lines[2].split()[-1]);nf=int(lines[6].split()[-1])
expected=['ply','format ascii 1.0',f'element vertex {n}','property double x','property double y','property double z',f'element face {nf}','property list uchar int vertex_indices','end_header']
if lines[:9]!=expected or len(lines)!=9+n+nf:raise ValueError('Unexpected geometry-only PLY schema')
x=np.array([[float(v) for v in s.split()] for s in lines[9:9+n]],dtype=np.float64)
rows=[s.split() for s in lines[9+n:]]
if any(len(v)!=4 or v[0]!='3' for v in rows):raise ValueError('Non-triangle PLY')
f=np.array([[int(v) for v in s[1:]] for s in rows],dtype=np.int64);xx,ff=surface(x,f)
if len(xx)!=n or not np.array_equal(ff,f):raise ValueError('Unexpected unused/reindexed vertices')
return x,f
def pose(x,f,rotation,unit_translation):
r=np.asarray(rotation,dtype=np.float64);u=np.asarray(unit_translation,dtype=np.float64)
if r.shape!=(3,3) or u.shape!=(3,) or not np.isfinite(r).all() or not np.isfinite(u).all():raise ValueError('Invalid pose')
det=float(np.linalg.det(r));orth=float(np.max(np.abs(r.T@r-np.eye(3))))
if abs(det-1)>1e-12 or orth>1e-12:raise ValueError('Only proper orthogonal rotations allowed')
center=(x.max(0)+x.min(0))/2;scale=float(np.linalg.norm(x.max(0)-x.min(0)))
if not np.isfinite(scale) or scale<=0:raise ValueError('Invalid translation scale')
t=scale*u;y=(x-center)@r.T+t
a=x[f];b=y[f];e=np.roll(a,-1,axis=1)-a;ee=np.roll(b,-1,axis=1)-b
edge=float(np.max(np.abs(np.linalg.norm(e,axis=2)-np.linalg.norm(ee,axis=2)))/scale)
area=float(np.max(np.abs(np.linalg.norm(np.cross(a[:,1]-a[:,0],a[:,2]-a[:,0]),axis=1)-np.linalg.norm(np.cross(b[:,1]-b[:,0],b[:,2]-b[:,0]),axis=1)))/scale**2)
if not np.isfinite(y).all() or max(edge,area)>1e-10:raise ValueError('Rigid geometry invariant failed')
transform={'rotation':r.tolist(),'source_center':center.tolist(),'random_translation':t.tolist(),'affine_translation':(t-center@r.T).tolist(),'translation_scale':scale,'formula':'(x-source_center) @ rotation.T + random_translation','determinant':det,'orthogonality_max_abs':orth,'edge_error_over_bbox_diagonal':edge,'double_area_error_over_bbox_diagonal_squared':area,'numerical_tolerance':1e-10,'vertices':len(x),'triangles':len(f)}
return y,transform