Files
2026-09-24 10:40:57 +08:00

65 lines
3.1 KiB
Python

"""Orthographic CAD snapshots with per-pixel depth testing and no mesh grid.
A painter-sorted triangle collection can expose back edges through the front
wall of a hollow part. A z-buffer makes visibility independent of triangle order.
"""
import io
import numpy as np
from PIL import Image, ImageDraw
from .depth_edges import shade_depth_edges
_VIEWS = {'iso': (25, -60), 'front': (0, -90), 'back': (0, 90),
'top': (90, -90), 'bottom': (-90, -90), 'side': (0, 0), 'right': (0, 0), 'left': (0, 180)}
def render_shape_png(shape, view='iso', size=1000):
if view not in _VIEWS:
raise ValueError(f'Unknown view: {view}')
from .meshing import ensure_mesh
ensure_mesh(shape, .05, .15)
vertices, triangles = shape.tessellate(0.05, 0.15)
pts = np.array([list(v) for v in vertices], dtype=float)
if not len(pts) or not triangles:
raise ValueError('Cannot render empty geometry')
faces = pts[np.asarray(triangles)]
elevation, azimuth = np.deg2rad(_VIEWS[view])
toward = np.array([np.cos(elevation)*np.cos(azimuth), np.cos(elevation)*np.sin(azimuth), np.sin(elevation)])
right = np.array([-np.sin(azimuth), np.cos(azimuth), 0])
up = np.cross(toward, right)
projected = pts @ np.array([right, up, toward]).T
mins, maxs = projected[:, :2].min(axis=0), projected[:, :2].max(axis=0)
center = (mins+maxs)/2
scale = size*.84 / max(float((maxs-mins).max()), 1e-6)
projected[:, 0] = (projected[:, 0]-center[0])*scale+size/2
projected[:, 1] = -(projected[:, 1]-center[1])*scale+size*.53
depth = np.full((size,size), -np.inf)
pixels = np.full((size,size,3), [245,246,248], dtype=np.uint8)
normals = np.cross(faces[:,1]-faces[:,0], faces[:,2]-faces[:,0])
normals /= np.maximum(np.linalg.norm(normals,axis=1)[:,None],1e-12)
light = toward*.65 + up*.55 - right*.35
light /= np.linalg.norm(light)
brightness = .4+.55*np.maximum(normals@light,0)
colors = (np.array([180,199,214])[None,:]*brightness[:,None]).astype(np.uint8)
for indices, color in zip(triangles,colors):
a,b,c=projected[list(indices)]
x0=max(0,int(np.floor(min(a[0],b[0],c[0])))); x1=min(size-1,int(np.ceil(max(a[0],b[0],c[0]))))
y0=max(0,int(np.floor(min(a[1],b[1],c[1])))); y1=min(size-1,int(np.ceil(max(a[1],b[1],c[1]))))
if x0>x1 or y0>y1: continue
denom=(b[1]-c[1])*(a[0]-c[0])+(c[0]-b[0])*(a[1]-c[1])
if abs(denom)<1e-9: continue
yy,xx=np.mgrid[y0:y1+1,x0:x1+1]
xx=xx+.5; yy=yy+.5
wa=((b[1]-c[1])*(xx-c[0])+(c[0]-b[0])*(yy-c[1]))/denom
wb=((c[1]-a[1])*(xx-c[0])+(a[0]-c[0])*(yy-c[1]))/denom
wc=1-wa-wb
z=wa*a[2]+wb*b[2]+wc*c[2]
region=depth[y0:y1+1,x0:x1+1]
visible=(wa>=-1e-7)&(wb>=-1e-7)&(wc>=-1e-7)&(z>region)
region[visible]=z[visible]
pixels[y0:y1+1,x0:x1+1][visible]=color
image=Image.fromarray(shade_depth_edges(pixels,depth,scale))
draw=ImageDraw.Draw(image)
draw.text((size/2,12),f'{view.upper()} | world XYZ | mm',fill='#17212e',anchor='mt',font_size=16)
buffer=io.BytesIO(); image.save(buffer,format='PNG')
return buffer.getvalue()