@rulecad/topopt 0.2.4 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,6 +18,7 @@ const spec = discretise({
18
18
  material: { E: 2680, nu: 0.36 }, thickness: 6, cell: 1, volume: 0.5, filter: 2.5,
19
19
  });
20
20
  const result = optimise(spec, { onStep: (s) => console.log(s.step, s.compliance) });
21
+ result.unsupported; // with overhang: the share of the kept regions' material nothing holds up (0: all held up)
21
22
  result.cases; // [{ name: 'down', deflection (mm along the load), stiffness (N/mm) }]; a twist (forces adding
22
23
  // to nothing): { name, moment (N·mm), angle (radians), torsion (N·mm a radian) }
23
24
  const loops = outlines(spec.grid, result.density, spec.origin); // closed loops, solid on the left
@@ -61,7 +62,10 @@ Two more steps shape the result:
61
62
  - **Heaviside projection** sharpens the result, more on each pass, until cells are solid or empty.
62
63
  - **The overhang filter** (optional, after Langelaar 2017) applies the printer's limit. Layer by layer from the bed, a
63
64
  cell can only be as solid as the material under it: the cell below and its neighbours, so nothing overhangs more
64
- than 45°. The result prints without supports in that direction.
65
+ than 45°. The result prints without supports in that direction. Kept regions must print too: a kept cell that
66
+ nothing holds up costs the optimiser as much as the whole part's compliance (shared over the kept cells), so it grows
67
+ what holds it up; `result.unsupported` says how much of the kept material is still left hanging, which means there
68
+ wasn't material enough to stand it on.
65
69
 
66
70
  Several load cases are optimised together by weight. A case weighted 0 is solved only at the end, for its figures.
67
71
  `model(spec)` exposes the analysis and its gradient, for other update methods.
@@ -71,7 +75,15 @@ and drops holes and islands smaller than `minArea`.
71
75
 
72
76
  `surface` does the same for a 3D result: a closed triangle mesh at density 0.5, by marching tetrahedra. Every cube
73
77
  is split along the same diagonal, so neighbouring cubes cut their shared faces the same way and the surface has no
74
- gaps. Then it's smoothed.
78
+ gaps. Then it's smoothed. With `overhang`, the smoothed surface is made printable: faces left steeper than the limit
79
+ are tipped back to it, and tips left hanging in mid-air (the lowest point of a dip under an edge, which a printer has
80
+ nothing to lay down on) are lifted level with their neighbours, in turn until neither finds any.
81
+
82
+ `printable` makes a result printable before it's drawn, the hard way: built up layer by layer from the bed, a cell
83
+ stays only if something holds it up (a cell in the layer below, straight under it or diagonally next to that; or,
84
+ within `reach` cells along its own layer, one that is: a short bridge); kept regions always stay. Whatever's left
85
+ hanging is emptied, and with it, layer by layer, whatever rested on it. It's what `cad optimise` does to every 3D
86
+ result with a build direction.
75
87
 
76
88
  ## Stress limits
77
89
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/topopt",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "description": "Topology optimisation for flat and solid parts: the stiffest layout of a fixed amount of material, printable without supports if asked, as outlines or a surface ready to print.",
5
5
  "type": "module",
6
6
  "exports": {
package/topopt.d.mts CHANGED
@@ -108,18 +108,17 @@ export function overhangFilter({ nx, ny, nz }: {
108
108
  apply(x: any, out: any): any;
109
109
  adjoint(g: any, out: any): any;
110
110
  };
111
- /**
112
- * The problem as a function of the design densities x (one per cell, 0 to 1), at projection sharpness beta:
113
- * physical(x, beta) gives the densities the part is made of (filtered, printable, projected, kept and avoided cells
114
- * set); evaluate(x, beta) analyses it and gives the compliance (summed over the load cases by weight, N·mm) and its
115
- * gradient with respect to x (dc), with the gradient of the material used (dv). Cases weighted 0 are only solved with
116
- * evaluate(x, beta, { all: true }).
117
- * @param {ReturnType<typeof discretise>} spec
118
- * @param {{ method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend }} [options]
119
- */
120
- export function model(spec: ReturnType<typeof discretise>, { method, backend }?: {
121
- method?: "direct" | "cg" | "mg";
122
- backend?: typeof jsBackend;
111
+ export function model(spec: any, { method, backend }?: {
112
+ backend?: {
113
+ name: string;
114
+ precision: number;
115
+ operator: (g: import("@rulecad/fea").Grid, ke: Float64Array | null, cellMatrices?: Float64Array) => {
116
+ multiply: (scale: Float64Array | null, x: Float64Array, y: Float64Array) => void;
117
+ diagonal: (scale: Float64Array | null, d: Float64Array) => void;
118
+ };
119
+ dot: (a: Float64Array, b: Float64Array) => number;
120
+ axpy: (a: number, x: Float64Array, y: Float64Array) => void;
121
+ };
123
122
  }): {
124
123
  physical: (x: any, beta: any) => Float64Array<ArrayBuffer>;
125
124
  evaluate: (x: any, beta: any, { all, multipliers }?: {
@@ -134,27 +133,12 @@ export function model(spec: ReturnType<typeof discretise>, { method, backend }?:
134
133
  compliance: number;
135
134
  dc: Float64Array<ArrayBuffer>;
136
135
  dv: Float64Array<ArrayBuffer>;
137
- u: any[];
138
- cases: ({
139
- name: any;
140
- compliance: number;
141
- deflection: number;
142
- stiffness: number;
143
- moment?: undefined;
144
- angle?: undefined;
145
- torsion?: undefined;
146
- } | {
147
- name: any;
148
- compliance: number;
149
- moment: number;
150
- angle: number;
151
- torsion: number;
152
- deflection?: undefined;
153
- stiffness?: undefined;
154
- })[];
136
+ u: any;
137
+ cases: any;
138
+ unsupported: number;
155
139
  };
156
140
  cells: number;
157
- passive: Int8Array<ArrayBuffer>;
141
+ passive: any;
158
142
  limits: number;
159
143
  };
160
144
  /**
@@ -176,6 +160,7 @@ export function mma({ n, m, xmin, xmax, move }: {
176
160
  * @param {ReturnType<typeof discretise>} spec
177
161
  * @param {{ onStep?: (s: { step: number, steps: number, compliance: number, change: number, beta: number, density: Float64Array }) => void, method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend, tol?: number, move?: number }} [options]
178
162
  * @returns {{ density: Float64Array, compliance: number, cases: { name: string, compliance: number, deflection: number, stiffness: number }[], volume: number, steps: number, converged: boolean, history: number[], seconds: number }}
163
+ * unsupported: with a build direction, the share of the kept regions' material nothing holds up (0: all held up);
179
164
  * each case's deflection is along its load (mm, compliance over the load's size), stiffness the load over that (N/mm);
180
165
  * a twist (forces adding to nothing) has instead its moment (N·mm), the angle it turns (radians) and torsion (N·mm a radian)
181
166
  */
@@ -271,6 +256,31 @@ export function surface({ nx, ny, nz, h }: {
271
256
  vertices: number[][];
272
257
  faces: number[][];
273
258
  };
259
+ /**
260
+ * A result made printable before it's drawn. Built up layer by layer from the bed, a cell denser than iso stays only if
261
+ * something holds it up: a cell kept in the layer below, straight under it or diagonally next to that (so nothing
262
+ * overhangs by more than 45°), or, within reach cells along its own layer, one that is (a short bridge). Kept regions
263
+ * always stay, and hold up what's above them. Whatever's left hanging (an icicle, a loose bit, a sheet hanging under an
264
+ * edge) is emptied, and with it, layer by layer, whatever rested on it. The optimiser's overhang filter does the same
265
+ * smoothly, on the densities as they're optimised; this is the hard version, on the result as it'll be drawn.
266
+ * @param {{ nx: number, ny: number, nz?: number }} size @param {ArrayLike<number>} density
267
+ * @param {{ up: string, iso?: number, keep?: ArrayLike<number>, reach?: number }} options up: the build direction ('+z',
268
+ * '-y', …); keep: cells that always stay (non-zero); reach: how many cells a bridge may run out from what holds it
269
+ * @returns {{ density: Float64Array, emptied: number }} the densities, and how many cells were emptied
270
+ */
271
+ export function printable({ nx, ny, nz }: {
272
+ nx: number;
273
+ ny: number;
274
+ nz?: number;
275
+ }, density: ArrayLike<number>, { up, iso, keep, reach }: {
276
+ up: string;
277
+ iso?: number;
278
+ keep?: ArrayLike<number>;
279
+ reach?: number;
280
+ }): {
281
+ density: Float64Array;
282
+ emptied: number;
283
+ };
274
284
  export { jsBackend };
275
285
  export function inside(r: Region, pt: number[]): boolean;
276
286
  /**
package/topopt.mjs CHANGED
@@ -197,19 +197,19 @@ export function overhangFilter({ nx, ny, nz = 1 }, up) {
197
197
  }
198
198
  supports[e] = Int32Array.from(list);
199
199
  }
200
- const printed = new Float64Array(cells), dSum = new Float64Array(cells), dX = new Float64Array(cells), sums = new Float64Array(cells);
200
+ const printed = new Float64Array(cells), powP = new Float64Array(cells), dSum = new Float64Array(cells), dX = new Float64Array(cells), sums = new Float64Array(cells);
201
201
  return {
202
202
  apply(x, out) {
203
203
  for (const e of order) {
204
204
  const sup = supports[e];
205
- if (!sup) { printed[e] = x[e]; dX[e] = 1; continue; }
205
+ if (!sup) { printed[e] = x[e]; powP[e] = Math.pow(x[e], P); dX[e] = 1; continue; }
206
206
  let s = 0;
207
- for (const q of sup) s += Math.pow(printed[q], P);
207
+ for (const q of sup) s += powP[q]; // (each cell's printed^P, worked out once as it's printed)
208
208
  if (s < 1e-200) s = 0; // nothing worth the name below (and no denormals for the gradient to blow up on)
209
209
  const Q = P + Math.log(sup.length) / Math.log(xi0), smax = s > 0 ? Math.pow(s, 1 / Q) : 0;
210
210
  sums[e] = s;
211
211
  const d = x[e] - smax, root = Math.sqrt(d * d + eps);
212
- printed[e] = 0.5 * (x[e] + smax - root + Math.sqrt(eps));
212
+ printed[e] = 0.5 * (x[e] + smax - root + Math.sqrt(eps)); powP[e] = Math.pow(printed[e], P);
213
213
  dX[e] = 0.5 * (1 - d / root); dSum[e] = 0.5 * (1 + d / root); // d printed / d x, d printed / d smax
214
214
  }
215
215
  out.set(printed);
@@ -222,7 +222,7 @@ export function overhangFilter({ nx, ny, nz = 1 }, up) {
222
222
  const e = order[t], sup = supports[e];
223
223
  if (!sup || !sums[e]) continue;
224
224
  const Q = P + Math.log(sup.length) / Math.log(xi0), common = lambda[e] * dSum[e] * (1 / Q) * Math.pow(sums[e], 1 / Q - 1) * P;
225
- for (const q of sup) lambda[q] += common * Math.pow(printed[q], P - 1);
225
+ for (const q of sup) if (printed[q] > 0) lambda[q] += (common * powP[q]) / printed[q];
226
226
  }
227
227
  for (let e = 0; e < cells; e++) out[e] = lambda[e] * dX[e];
228
228
  return out;
@@ -239,6 +239,8 @@ export function overhangFilter({ nx, ny, nz = 1 }, up) {
239
239
  * @param {ReturnType<typeof discretise>} spec
240
240
  * @param {{ method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend }} [options]
241
241
  */
242
+ const SUPPORT = 10; // what a kept cell nothing holds up costs, in the part's compliances, over the kept cells
243
+
242
244
  export function model(spec, { method, backend = jsBackend } = {}) {
243
245
  const g = makeGrid(spec.grid), dim = g.dim, cells = g.cells, m = g.cellDofs, ke = cellStiffness(spec.material.nu, dim);
244
246
  const { passive, penal } = spec, E = spec.material.E, Emin = E * 1e-9, eta = 0.5, size = dim === 3 ? g.h : spec.thickness;
@@ -250,12 +252,22 @@ export function model(spec, { method, backend = jsBackend } = {}) {
250
252
  const denominator = (beta) => Math.tanh(beta * eta) + Math.tanh(beta * (1 - eta));
251
253
  const project = (t, beta) => (spec.projection ? (Math.tanh(beta * eta) + Math.tanh(beta * (t - eta))) / denominator(beta) : t);
252
254
  const slope = (t, beta) => (spec.projection ? (beta * (1 - Math.tanh(beta * (t - eta)) ** 2)) / denominator(beta) : 1);
255
+ // Kept and avoided cells are set before the overhang filter as well as after it: a kept cell holds up what's above
256
+ // it, an avoided cell holds up nothing, and a kept cell is printed (made) only as far as what's below holds it up,
257
+ // which is what the kept regions' support cost (below) is measured on. The part is analysed with every kept cell solid.
253
258
  const physical = (x, beta) => {
254
259
  filter.apply(x, tilde);
260
+ for (let e = 0; e < cells; e++) if (passive[e]) tilde[e] = fixedValue(passive[e]);
255
261
  if (print) print.apply(tilde, made); else made.set(tilde);
256
262
  for (let e = 0; e < cells; e++) phys[e] = passive[e] ? fixedValue(passive[e]) : project(made[e], beta);
257
263
  return phys;
258
264
  };
265
+ // Kept regions must print. With a build direction, how much of the kept material nothing holds up (0 to 1), and its
266
+ // cost: a kept cell nothing holds up costs SUPPORT times the part's compliance, shared over the kept cells, so the
267
+ // optimiser puts material in under it. The cost's gradient goes back through the overhang filter to the cells that
268
+ // would hold it up.
269
+ const keptCells = Int32Array.from(Array.from(passive).flatMap((p, e) => (p === 1 ? [e] : [])));
270
+ const unsupported = (beta) => (print && keptCells.length ? keptCells.reduce((t, e) => t + 1 - project(made[e], beta), 0) / keptCells.length : 0);
259
271
  let last = null;
260
272
  // Each step solves only the load cases it optimises for (weight above 0); every case is solved when all is set
261
273
  const evaluate = (x, beta, { all = false, multipliers } = {}) => {
@@ -282,8 +294,14 @@ export function model(spec, { method, backend = jsBackend } = {}) {
282
294
  });
283
295
  // Back through the projection, the overhang filter and the density filter to the design densities; kept and
284
296
  // avoided cells don't change
297
+ const lack = unsupported(beta);
285
298
  for (let e = 0; e < cells; e++) { const s = passive[e] ? 0 : slope(made[e], beta); dc[e] *= s; dv[e] = s; }
286
- const toDesign = (d) => { if (print) { print.adjoint(d, back); d.set(back); } filter.adjoint(d, back); d.set(back); };
299
+ if (print && keptCells.length) { const w = (SUPPORT * Math.max(compliance, 1e-12)) / keptCells.length; for (const e of keptCells) dc[e] = -w * slope(made[e], beta); }
300
+ const toDesign = (d) => {
301
+ if (print) { print.adjoint(d, back); d.set(back); }
302
+ for (let e = 0; e < cells; e++) if (passive[e]) d[e] = 0;
303
+ filter.adjoint(d, back); d.set(back);
304
+ };
287
305
  toDesign(dc); toDesign(dv);
288
306
  const stress = Ss ? stressLimits(u, active, run.again, multipliers || { lam: active.map(() => new Float64Array(cells * Ss.length)), mu: 1 }) : null;
289
307
  const cases = spec.loads.map((l, c) => {
@@ -295,7 +313,7 @@ export function model(spec, { method, backend = jsBackend } = {}) {
295
313
  return { name: l.name, compliance: ci, deflection, stiffness: deflection ? l.size / deflection : Infinity };
296
314
  });
297
315
  if (stress) { for (let e = 0; e < cells; e++) stress.d[e] *= passive[e] ? 0 : slope(made[e], beta); toDesign(stress.d); }
298
- return { compliance, dc, dv, u, cases, ...(stress ? { stress } : {}) };
316
+ return { compliance, dc, dv, u, cases, unsupported: lack, ...(stress ? { stress } : {}) };
299
317
  };
300
318
  // Stress limits on every cell (Senhora, Giraldo-Londoño, Menezes, Paulino 2020): each cell's von Mises stress at its
301
319
  // centre, as if solid, over the limit, less 1, times the cell's density, so an empty cell's limit vanishes. They're
@@ -497,6 +515,7 @@ function gauss(A) {
497
515
  * @param {ReturnType<typeof discretise>} spec
498
516
  * @param {{ onStep?: (s: { step: number, steps: number, compliance: number, change: number, beta: number, density: Float64Array }) => void, method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend, tol?: number, move?: number }} [options]
499
517
  * @returns {{ density: Float64Array, compliance: number, cases: { name: string, compliance: number, deflection: number, stiffness: number }[], volume: number, steps: number, converged: boolean, history: number[], seconds: number }}
518
+ * unsupported: with a build direction, the share of the kept regions' material nothing holds up (0: all held up);
500
519
  * each case's deflection is along its load (mm, compliance over the load's size), stiffness the load over that (N/mm);
501
520
  * a twist (forces adding to nothing) has instead its moment (N·mm), the angle it turns (radians) and torsion (N·mm a radian)
502
521
  */
@@ -523,6 +542,7 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
523
542
  const multipliers = lightest ? { lam: spec.loads.filter((l) => l.weight > 0).map(() => new Float64Array(m.limits)), mu: 10 } : undefined;
524
543
  const xf = new Float64Array(n), pick = (d) => Float64Array.from(freeCells, (e) => d[e]);
525
544
  let step = 0, change = 1, converged = false, beta = 1, sinceBeta = 0, peak = null;
545
+ const tried = new Float64Array(cells); // the last design the bisection analysed, and how much it filled
526
546
  while (step < spec.steps) {
527
547
  step++; sinceBeta++;
528
548
  const { compliance, dc, dv, stress } = m.evaluate(x, beta, { multipliers });
@@ -546,16 +566,20 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
546
566
  history.push(compliance);
547
567
  // Optimality criteria: scale each cell by √(−dc/dv/λ), within the move limit, finding λ by bisection so the
548
568
  // physical densities fill exactly the volume
549
- let lo = 0, hi = 1e9;
569
+ let lo = 0, hi = 1e9, triedFilled = NaN;
570
+ tried.fill(-1);
550
571
  while ((hi - lo) / (hi + lo) > 1e-3) { // as the 88-line code
551
572
  const mid = (lo + hi) / 2;
573
+ let same = true;
552
574
  for (let e = 0; e < cells; e++) {
553
575
  if (passive[e]) { xnew[e] = fixedValue(passive[e]); continue; }
554
576
  const b = Math.sqrt(Math.max(0, -dc[e]) / Math.max(1e-30, dv[e]) / mid);
555
577
  xnew[e] = Math.max(0, Math.max(x[e] - limit, Math.min(1, Math.min(x[e] + limit, x[e] * b))));
578
+ if (xnew[e] !== tried[e]) same = false;
556
579
  }
557
- const filled = m.physical(xnew, beta).reduce((s, v) => s + v, 0);
558
- if (filled > target) lo = mid; else hi = mid;
580
+ // (far from the answer every cell is at its move limit, the same design as the last try: not analysed again)
581
+ if (!same) { triedFilled = m.physical(xnew, beta).reduce((s, v) => s + v, 0); tried.set(xnew); }
582
+ if (triedFilled > target) lo = mid; else hi = mid;
559
583
  }
560
584
  }
561
585
  change = 0;
@@ -575,8 +599,9 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
575
599
  }
576
600
  // The final design, analysed as it is
577
601
  const final = m.evaluate(x, beta, { all: true }), phys = Float64Array.from(m.physical(x, beta));
602
+ // (the final physical call is after evaluate's, so unsupported comes from the evaluation of this design)
578
603
  return {
579
- density: phys, compliance: final.compliance, cases: final.cases, ...(final.stress ? { stress: { peak: final.stress.peak, limit: spec.stress } } : {}),
604
+ density: phys, compliance: final.compliance, cases: final.cases, unsupported: final.unsupported, ...(final.stress ? { stress: { peak: final.stress.peak, limit: spec.stress } } : {}),
580
605
  volume: phys.reduce((s, v, e) => s + (passive[e] !== -2 ? v : 0), 0) / inSpace, steps: step, converged, history, seconds: (Date.now() - started) / 1000,
581
606
  };
582
607
  }
@@ -854,7 +879,9 @@ export function surface({ nx, ny, nz, h }, density, origin = [0, 0, 0], { smooth
854
879
  return held[n] ? p : p.map((x, q) => Math.min(hi[q], Math.max(lo[q], x + f * (avg[q] - x))));
855
880
  });
856
881
  }
857
- if (overhang) steepen(pts, faces, held, overhang, lo, hi);
882
+ // Printable: faces past the limit tipped back, and tips lifted, in turn until neither finds any (each can make work for
883
+ // the other: a lifted tip leaves a face sloping more, a tipped face can leave a corner lowest)
884
+ if (overhang) for (let round = 0; round < 20; round++) { const tipped = steepen(pts, faces, held, overhang, lo, hi), lifted = lift(pts, faces, held, overhang, lo); if (!tipped && !lifted) break; }
858
885
  return { vertices: pts, faces };
859
886
  }
860
887
 
@@ -884,9 +911,90 @@ function steepen(pts, faces, held, { up, angle }, lo, hi, passes = 200) {
884
911
  move[m] += c[q] + k * (ga * (v[a] - c[a]) + gb * (v[b] - c[b])) - v[q]; count[m]++;
885
912
  }
886
913
  }
887
- if (!left) break;
914
+ if (!left) return pass > 0;
888
915
  for (let m = 0; m < pts.length; m++) if (count[m] && !held[m]) pts[m][q] = Math.min(hi[q], Math.max(lo[q], pts[m][q] + move[m] / count[m]));
889
916
  }
917
+ return true;
918
+ }
919
+
920
+ // Tips lifted: a corner lower than every corner round it (along the build direction), on faces facing down, starts in
921
+ // mid-air, where a printer has nothing to lay it on. Smoothing leaves these under edges and bridges. Each is raised level
922
+ // with its lowest neighbour, which leaves a small flat underside (bridged), until none are left. The bed's corners and
923
+ // those held on the grid's sides stay.
924
+ function lift(pts, faces, held, { up }, lo, passes = 50) {
925
+ const q = 'xyz'.indexOf(up[1]), s = up[0] === '-' ? -1 : 1, near = pts.map(() => new Set()), facing = new Float64Array(pts.length);
926
+ for (const f of faces) {
927
+ for (let i = 0; i < 3; i++) { near[f[i]].add(f[(i + 1) % 3]); near[f[i]].add(f[(i + 2) % 3]); }
928
+ const [p, r, t] = f.map((n) => pts[n]), u = [0, 1, 2].map((x) => r[x] - p[x]), w = [0, 1, 2].map((x) => t[x] - p[x]);
929
+ const nq = [u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]][q];
930
+ for (const m of f) facing[m] += s * nq;
931
+ }
932
+ const bed = s > 0 ? lo[q] : null, height = (v) => s * v[q];
933
+ for (let pass = 0; pass < passes; pass++) {
934
+ let moved = 0;
935
+ for (let m = 0; m < pts.length; m++) {
936
+ if (held[m] || !near[m].size || facing[m] >= 0 || (bed !== null && Math.abs(pts[m][q] - bed) < 1e-9)) continue;
937
+ let lowest = Infinity;
938
+ for (const n of near[m]) lowest = Math.min(lowest, height(pts[n]));
939
+ if (height(pts[m]) < lowest - 1e-6) { pts[m][q] = s * lowest; moved++; }
940
+ }
941
+ if (!moved) return pass > 0;
942
+ }
943
+ return true;
944
+ }
945
+
946
+ /**
947
+ * A result made printable before it's drawn. Built up layer by layer from the bed, a cell denser than iso stays only if
948
+ * something holds it up: a cell kept in the layer below, straight under it or diagonally next to that (so nothing
949
+ * overhangs by more than 45°), or, within reach cells along its own layer, one that is (a short bridge). Kept regions
950
+ * always stay, and hold up what's above them. Whatever's left hanging (an icicle, a loose bit, a sheet hanging under an
951
+ * edge) is emptied, and with it, layer by layer, whatever rested on it. The optimiser's overhang filter does the same
952
+ * smoothly, on the densities as they're optimised; this is the hard version, on the result as it'll be drawn.
953
+ * @param {{ nx: number, ny: number, nz?: number }} size @param {ArrayLike<number>} density
954
+ * @param {{ up: string, iso?: number, keep?: ArrayLike<number>, reach?: number }} options up: the build direction ('+z',
955
+ * '-y', …); keep: cells that always stay (non-zero); reach: how many cells a bridge may run out from what holds it
956
+ * @returns {{ density: Float64Array, emptied: number }} the densities, and how many cells were emptied
957
+ */
958
+ export function printable({ nx, ny, nz = 1 }, density, { up, iso = 0.5, keep, reach = 0 }) {
959
+ const n = nz > 1 ? [nx, ny, nz] : [nx, ny], dim = n.length, ax = 'xyz'.indexOf(up.at(-1)), sign = up[0] === '-' ? -1 : 1;
960
+ if (ax < 0 || ax >= dim) throw new Error(`printable: the build direction is ${dim === 3 ? '+x, -x, +y, -y, +z or -z' : '+x, -x, +y or -y'} (got ${up})`);
961
+ const stride = [1, nx, nx * ny], other = [0, 1, 2].slice(0, dim).filter((a) => a !== ax), cells = n.reduce((p, c) => p * c, 1);
962
+ const ok = new Uint8Array(cells), out = Float64Array.from(density);
963
+ const solid = (e) => density[e] >= iso || (keep && keep[e]);
964
+ const coord = (e, a) => Math.floor(e / stride[a]) % n[a];
965
+ // The cells of each layer, in build order
966
+ const layers = Array.from({ length: n[ax] }, () => []);
967
+ for (let e = 0; e < cells; e++) { const c = coord(e, ax); layers[sign > 0 ? c : n[ax] - 1 - c].push(e); }
968
+ const near = (e) => { // a cell's neighbours in its own layer, along each other axis
969
+ const list = [];
970
+ for (const a of other) { const c = coord(e, a); if (c > 0) list.push(e - stride[a]); if (c < n[a] - 1) list.push(e + stride[a]); }
971
+ return list;
972
+ };
973
+ layers.forEach((layer, L) => {
974
+ const queue = [], dist = new Map();
975
+ for (const e of layer) {
976
+ if (!solid(e)) continue;
977
+ let held = L === 0 || (keep && keep[e]);
978
+ if (!held) {
979
+ const below = e - sign * stride[ax], under = [below];
980
+ // and its neighbours along each other axis, and diagonally (in 3D)
981
+ const offs = other.map((a) => [-stride[a], 0, stride[a]].filter((d, i) => { const c = coord(below, a); return (i === 0 && c > 0) || i === 1 || (i === 2 && c < n[a] - 1); }));
982
+ if (offs.length === 1) for (const d of offs[0]) under.push(below + d);
983
+ else for (const d0 of offs[0]) for (const d1 of offs[1]) under.push(below + d0 + d1);
984
+ held = under.some((q) => ok[q]);
985
+ }
986
+ if (held) { ok[e] = 1; dist.set(e, 0); queue.push(e); }
987
+ }
988
+ // Short bridges: solid cells within reach of a held one, along the layer
989
+ for (let i = 0; i < queue.length; i++) {
990
+ const e = queue[i], d = dist.get(e);
991
+ if (d >= reach) continue;
992
+ for (const f of near(e)) if (!ok[f] && solid(f)) { ok[f] = 1; dist.set(f, d + 1); queue.push(f); }
993
+ }
994
+ });
995
+ let emptied = 0;
996
+ for (let e = 0; e < cells; e++) if (!ok[e] && density[e] >= iso) { out[e] = 0; emptied++; }
997
+ return { density: out, emptied };
890
998
  }
891
999
 
892
1000
  const fmt = (n) => String(Number(n.toFixed(2)));