"""Assemble the print set (only parts the manifest places, plus the stamp) and test each file for printability: watertight, sitting on the bed, no layer that starts in mid-air, and how much steep overhang it has.""" import os, shutil, json, numpy as np, trimesh from trimesh import creation from shapely.geometry import Polygon, LineString from shapely.ops import unary_union import geom as G, manifest as M from paths import STL_SRC, OUT as _OUT, WORK SRC = str(STL_SRC); OUT = str(_OUT / 'stl') def brow_strip(L=G.STRIP_L): """Thin heat-formable brow strip: 2.4 mm plate, bark ridges 1.2 mm proud, low knobs. Same outline the guide draws.""" outline = G.strip_poly(L) parts = [creation.extrude_polygon(outline, 2.4)] x = np.linspace(-L/2, L/2, 240); ridges = [] for k in range(6): ys = -8 + k*3.2 + 1.8*np.sin(x*0.09 + k) + 0.8*np.sin(x*0.31 + 2*k) ridges.append(LineString(list(zip(x, ys))).buffer(0.55, cap_style=1)) rp = unary_union(ridges).intersection(outline.buffer(-1.0)) for g in (rp.geoms if rp.geom_type == 'MultiPolygon' else [rp]): if g.area > 2: parts.append(creation.extrude_polygon(g, 3.6)) for kx, s in [(-52, 4.2), (-26, 5.0), (-5, 3.8), (16, 5.0), (40, 4.2), (58, 3.4)]: k = creation.icosphere(2, s); k.apply_scale([1.5, 1, 0.5]); k.apply_translation([kx, 0, 2.4]); parts.append(k) m = trimesh.boolean.union(parts, engine='manifold') cut = creation.box([L+40, 80, 10]); cut.apply_translation([0, 0, -5]); m = m.difference(cut) m.apply_translation([-m.bounds[0][0], -m.bounds[0][1], -m.bounds[0][2]]); return m def acorn(h, r, cap_frac=0.42): """Acorn along z: cap and stem at z<=0 end, nut tip at z=h. Cap scales are teardrops pointing at the nut tip, so when the acorn is printed standing on its tip each scale grows out of the wall instead of starting in mid-air.""" t = np.linspace(0, 1, 50); rr = r*np.sqrt(np.clip(1-((t-0.30)/0.74)**2, 0, 1)); rr[0] = rr[-1] = 0 nut = creation.revolve(np.column_stack([rr, t*h]), sections=64) ch = h*cap_frac prof = np.array([[0, -2.5], [r*0.55, -2.5], [r*1.05, -0.5], [r*1.19, ch*0.45], [r*1.16, ch*0.85], [r*1.0, ch], [0, ch]]) parts = [nut, creation.revolve(prof, sections=64)] for i in range(5): zz = -1.0 + ch*(0.08 + 0.70*i/4); rad = np.interp(zz, prof[1:-1, 1], prof[1:-1, 0]); n = int(round(2*np.pi*rad/(r*0.30))) for j in range(n): ang = 2*np.pi*(j + 0.5*(i % 2))/n b = creation.icosphere(subdivisions=1, radius=r*0.17); v = b.vertices.copy(); v[v[:, 2] > 0, 2] *= 2.4; b.vertices = v b.apply_translation([rad*np.cos(ang), rad*np.sin(ang), zz]); parts.append(b) stem = creation.cylinder(radius=r*0.2, height=5, sections=20); stem.apply_translation([0, 0, -4.5]); parts.append(stem) return trimesh.boolean.union(parts, engine='manifold') def _floor(m): cut = creation.box([400, 400, 100]); cut.apply_translation([0, 0, -50]); m = m.difference(cut) m.apply_translation([-m.bounds[0][0], -m.bounds[0][1], -m.bounds[0][2]]); m.merge_vertices(); m.fix_normals(); return m def acorn_half(h, r): m = acorn(h, r); m.apply_transform(trimesh.transformations.rotation_matrix(np.pi/2, [1, 0, 0])); return _floor(m) def acorn_full(h=28, r=10, cut=4.0): m = acorn(h, r); m.apply_transform(trimesh.transformations.rotation_matrix(np.pi, [1, 0, 0])) # nut tip down, stem up m.apply_translation([0, 0, -m.bounds[0][2] - cut]); return _floor(m) GEN = {'brow_strip.stl': brow_strip, 'acorn_large_half.stl': lambda: acorn_half(30, 11), 'acorn_small_half.stl': lambda: acorn_half(22, 8), 'acorn_full.stl': acorn_full} FILES = { # kit file name -> (source, part id) 'brow_strip.stl': (None, 'STRIP'), 'bark_knot.stl': ('bark_knot.stl', 'KNOT'), 'twig_forked.stl': ('twig_forked_flat.stl', 'TWIG'), 'acorn_large_half.stl': ('acorn_large_halfback.stl', 'AL'), 'acorn_small_half.stl': ('acorn_small_halfback.stl', 'AS'), 'acorn_full.stl': ('acorn_full_upright.stl', 'AF'), 'tendril_spiral.stl': ('tendril_spiral_small_flat.stl', 'SPIRAL'), 'leaf_vein_stamp.stl': ('leaf_vein_stamp.stl', 'STAMP'), } def check(m, layer=0.2): r = dict(extents=[round(float(v), 1) for v in m.extents], watertight=bool(m.is_watertight), zmin=round(float(m.bounds[0][2]), 3), volume_cm3=round(float(m.volume)/1000, 2)) # bed contact: area of the first layer def layer_poly(z): sec = m.section(plane_origin=[0, 0, z], plane_normal=[0, 0, 1]) if sec is None: return None pl, _ = sec.to_2D(to_2D=np.eye(4)) polys = [p for p in pl.polygons_full if p.area > 0.02] return unary_union(polys) if polys else None first = layer_poly(layer/2) r['bed_contact_mm2'] = round(first.area, 0) if first is not None else 0 # unsupported material: in each layer, whatever lies more than 0.7 mm sideways beyond the layer below has # nothing under it (0.7 mm per 0.4 mm of height = a 60 degree overhang, the most PLA bridges reliably) unsup, worst, prev, z = 0.0, 0.0, first, layer*1.5 top = m.bounds[1][2] while z < top: cur = layer_poly(z) if cur is not None and prev is not None: hang = cur.difference(prev.buffer(0.7)) a_ = sum(g.area for g in (hang.geoms if hasattr(hang, 'geoms') else [hang]) if g.area > 0.25) unsup += a_; worst = max(worst, a_) if cur is not None: prev = cur z += layer*2 r['midair_mm2'] = round(unsup, 1); r['midair_worst_layer_mm2'] = round(worst, 1) # steep overhang: downward faces more than 55 degrees from vertical, above the first layers n = m.face_normals; cz = m.triangles_center[:, 2] steep = (n[:, 2] < -np.sin(np.radians(55))) & (cz > 0.5) r['overhang_mm2'] = round(float(m.area_faces[steep].sum()), 0) why = [w for w, bad in (('not watertight', not r['watertight']), ('not on the bed', abs(r['zmin']) > 0.01), ('prints in mid-air', r['midair_mm2'] > 12), ('too little bed contact', r['bed_contact_mm2'] < 20)) if bad] r['verdict'] = ('FAIL: ' + ', '.join(why)) if why else ('ok, supports optional' if r['midair_mm2'] > 3 else 'ok, no supports') return r def build(): ml = M.make_list(); report = {} for name, (src, pid) in FILES.items(): if name in GEN: m = GEN[name](); m.export(f'{OUT}/{name}') else: shutil.copy(f'{SRC}/{src}', f'{OUT}/{name}'); m = trimesh.load(f'{OUT}/{name}') r = check(m); r['qty'] = 1 if pid == 'STAMP' else ml[pid]['total']; r['part'] = pid; report[name] = r print(f"{name:24s} x{r['qty']} {str(r['extents']):22s} bed {r['bed_contact_mm2']:6.0f} mm2 mid-air {r['midair_mm2']:5.1f} steep overhang {r['overhang_mm2']:5.0f} {r['verdict']}") # every printed part in the manifest has a file, and no file is for an unplaced part need = {k for k, v in ml.items() if v['kind'] == 'print'}; have = {pid for _, pid in FILES.values()} - {'STAMP'} assert need == have, (need ^ have) # control: the two files that failed on the printer must fail this test for bad in ('tendril_spiral_small.stl', 'tendril_spiral.stl', 'twig_forked.stl'): rb = check(trimesh.load(f'{SRC}/{bad}')); print(f"control {bad:28s} mid-air {rb['midair_mm2']:6.1f} {rb['verdict']}"); assert rb['verdict'].startswith('FAIL'), 'the test must reject the files that failed on the printer' json.dump(report, open(WORK / 'stl_report.json', 'w'), indent=1) return report if __name__ == '__main__': build()