@rulecad/topopt 0.2.7 → 0.3.0

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.
Files changed (4) hide show
  1. package/README.md +37 -1
  2. package/package.json +5 -1
  3. package/topopt.d.mts +120 -12
  4. package/topopt.mjs +232 -33
package/README.md CHANGED
@@ -58,7 +58,9 @@ Stiffness grows as density cubed, so part-solid cells are poor value and the res
58
58
  Two more steps shape the result:
59
59
 
60
60
  - **A density filter** averages each cell with its neighbours. It sets the thinnest member and prevents chequerboard
61
- patterns.
61
+ patterns. A member thinner than four cells is analysed too stiff (two cells: about 11%; one: about
62
+ 32%; see @rulecad/fea, How fine a grid), so pick a cell small enough that the thinnest member the filter allows is
63
+ four cells across, or a result full of thin members looks better than it is.
62
64
  - **Heaviside projection** sharpens the result, more on each pass, until cells are solid or empty.
63
65
  - **The overhang filter** (optional, after Langelaar 2017) applies the printer's limit. Layer by layer from the bed, a
64
66
  cell can only be as solid as the material under it: the cell below and its neighbours, so nothing overhangs more
@@ -127,6 +129,37 @@ falls by 46%. Two things to know:
127
129
  with that margin in mind.
128
130
  - **It may not settle within its steps.** This one ran its 1,000 steps with the peak hovering 5% over the limit.
129
131
 
132
+ ## Mechanisms
133
+
134
+ A compliant mechanism is a part that moves by bending: push here, and there moves, with no joints. Give the problem an
135
+ `output` (where it should move, along one axis, against a spring) and the first load becomes the input (with
136
+ `input_spring`, a spring it pushes against); the optimiser then makes the layout that moves the output furthest
137
+ (Sigmund 1997), by the method of moving asymptotes under the volume.
138
+
139
+ ```js
140
+ const spec = discretise({
141
+ space: { at: [20, 10], size: [40, 20] }, cell: 1, volume: 0.3, filter: 1.5, material: { E: 1, nu: 0.3 }, thickness: 1,
142
+ supports: [{ at: [0.5, 0.5], size: [1, 1] }, { at: [0.5, 19.5], size: [1, 1] }],
143
+ loads: [{ at: [0.5, 10], size: [1, 2], force: [1, 0] }], input_spring: 0.1, // pushed to the right at the left edge
144
+ output: { at: [39.5, 10], size: [1, 2], direction: [-1, 0], spring: 0.1 }, // the right edge should move left
145
+ });
146
+ const result = optimise(spec);
147
+ result.mechanism; // { travel (mm, the output along its direction), input (mm, the input along the push), advantage (travel / input) }
148
+ ```
149
+
150
+ That one is the force inverter, the classic test: a block pushed at its left edge whose right edge moves the other
151
+ way. The springs matter: the output's stands for what the mechanism works against, the input's for what pushes it;
152
+ softer springs give more travel and a smaller advantage. The travel's gradient (an adjoint solve with the output's
153
+ direction as the load) agrees with finite differences.
154
+
155
+ Left to itself, mechanism synthesis makes point hinges: a joint one cell wide and half empty is the most compliant
156
+ there is, and no printer makes it. So a mechanism is optimised robustly (Wang, Lazarov and Sigmund 2011): its travel
157
+ on an eroded copy of the design (projected at a threshold of 0.7), its volume on a dilated one (0.3), the design as
158
+ made between them. A hinge that survives erosion has real width, and the result is one piece, cell to cell. The
159
+ price: the design as made is stiffer than the eroded copy it was optimised on, by a hinge width's worth of
160
+ stiffness (which goes as the width cubed), so `result.mechanism` reports what the design as made does, and it moves
161
+ less than the run's progress figures suggested.
162
+
130
163
  ## Checked against the published code
131
164
 
132
165
  With projection off, it matches a line-by-line port of the 88-line MATLAB code (`reference/top88.py`) step for step:
@@ -149,6 +182,9 @@ Its gradients agree with finite differences through the filter and the projectio
149
182
 
150
183
  ## Sources
151
184
 
185
+ - Sigmund, O., "On the design of compliant mechanisms using topology optimization", *Mechanics of Structures and Machines* 25(4), 1997: the output-travel objective and its adjoint.
186
+ - Wang, F., Lazarov, B. S., and Sigmund, O., "On projection methods, convergence and robust formulations in topology optimization", *Structural and Multidisciplinary Optimization* 43, 2011: the eroded, intermediate and dilated designs.
187
+
152
188
  - Bendsøe, Sigmund (2003). *Topology Optimization: Theory, Methods and Applications*. Springer.
153
189
  - Andreassen, Clausen, Schevenels, Lazarov, Sigmund (2011). Efficient topology optimization in MATLAB using 88 lines
154
190
  of code. *Structural and Multidisciplinary Optimization* 43, 1–16.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/topopt",
3
- "version": "0.2.7",
3
+ "version": "0.3.0",
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": {
@@ -29,6 +29,10 @@
29
29
  "url": "git+https://github.com/JoniBach/rulecad.git",
30
30
  "directory": "packages/topopt"
31
31
  },
32
+ "homepage": "https://github.com/JoniBach/rulecad/tree/main/packages/topopt#readme",
33
+ "bugs": {
34
+ "url": "https://github.com/JoniBach/rulecad/issues"
35
+ },
32
36
  "scripts": {
33
37
  "test": "node --test"
34
38
  },
package/topopt.d.mts CHANGED
@@ -22,6 +22,9 @@
22
22
  * @property {number} [penal] the penalty (default 3)
23
23
  * @property {boolean} [projection] sharpen with Heaviside projection (default true)
24
24
  * @property {string} [overhang] printed this way up ('+z', '-y', …): only material supported from below at 45° or less
25
+ * @property {{ at: number[], r?: number, size?: number[], direction: number[], spring?: number }} [output] a mechanism's output:
26
+ * where it should move, along one axis, against a spring (N/mm); the first load is then its input
27
+ * @property {number} [input_spring] with output, a spring the input pushes against (N/mm)
25
28
  * @property {number} [bridge] with overhang, the widest gap the printer bridges (mm): material may also be held up by a run
26
29
  * of solid cells along its own layer, half that long, ending on a held cell
27
30
  * @property {number} [steps] at most this many steps (default 300)
@@ -54,6 +57,19 @@ export function discretise(p: any): {
54
57
  stress?: any;
55
58
  bridge?: any;
56
59
  overhang?: any;
60
+ material: any;
61
+ thickness: any;
62
+ volume: any;
63
+ filter: any;
64
+ penal: any;
65
+ projection: any;
66
+ steps: any;
67
+ output?: {
68
+ force: Float64Array<ArrayBuffer>;
69
+ spring: any;
70
+ input: Float64Array<ArrayBuffer>;
71
+ };
72
+ springs?: Float64Array<ArrayBuffer>;
57
73
  grid: {
58
74
  nx: number;
59
75
  ny: number;
@@ -75,13 +91,6 @@ export function discretise(p: any): {
75
91
  weight: any;
76
92
  size: number;
77
93
  }[];
78
- material: any;
79
- thickness: any;
80
- volume: any;
81
- filter: any;
82
- penal: any;
83
- projection: any;
84
- steps: any;
85
94
  };
86
95
  /**
87
96
  * The density filter: each cell's filtered density is the weighted average of the cells within radius (weights
@@ -127,10 +136,16 @@ export function model(spec: any, { method, backend }?: {
127
136
  axpy: (a: number, x: Float64Array, y: Float64Array) => void;
128
137
  };
129
138
  }): {
130
- physical: (x: any, beta: any) => Float64Array<ArrayBuffer>;
131
- evaluate: (x: any, beta: any, { all, multipliers }?: {
139
+ physical: (x: any, beta: any, eta?: number) => Float64Array<ArrayBuffer>;
140
+ evaluate: (x: any, beta: any, { all, multipliers, eta }?: {
132
141
  all?: boolean;
142
+ eta?: number;
133
143
  }) => {
144
+ mechanism?: {
145
+ travel: number;
146
+ input: number;
147
+ d: Float64Array<ArrayBuffer>;
148
+ };
134
149
  stress?: {
135
150
  J: number;
136
151
  d: Float64Array<ArrayBuffer>;
@@ -144,6 +159,7 @@ export function model(spec: any, { method, backend }?: {
144
159
  cases: any;
145
160
  unsupported: number;
146
161
  };
162
+ volumeGradient: (x: any, beta: any, eta?: number) => Float64Array<ArrayBuffer>;
147
163
  cells: number;
148
164
  passive: any;
149
165
  limits: number;
@@ -242,9 +258,11 @@ export function area(loop: [number, number][]): number;
242
258
  * @param {{ nx: number, ny: number, nz: number, h: number }} size @param {ArrayLike<number>} density @param {number[]} origin
243
259
  * Vertices on the grid's outer faces stay where they are as it's smoothed, so a part that fills its space to a face (a
244
260
  * base on the bed) keeps that face flat, and the walls rising from it don't lean out.
245
- * @param {{ smooth?: number, iso?: number, overhang?: { up: string, angle: number } }} [options] iso: the density the
246
- * surface is drawn at (0.5). overhang: the build direction ('+z') and the printer's overhang limit (degrees from
247
- * vertical): faces smoothing left past it are tipped back to it.
261
+ * @param {{ smooth?: number, iso?: number, overhang?: { up: string, angle: number, tip?: boolean } }} [options] iso: the
262
+ * density the surface is drawn at (0.5). overhang: the build direction ('+z') and the printer's overhang limit (degrees
263
+ * from vertical): downward bumps left by smoothing are filled, so nothing starts in mid-air when sliced; with tip, faces
264
+ * past the limit are also tipped back to it (off by default: tipping corners leaves dips that slice as islands, and the
265
+ * layers step out no further for it).
248
266
  * @returns {{ vertices: number[][], faces: number[][] }}
249
267
  */
250
268
  export function surface({ nx, ny, nz, h }: {
@@ -258,11 +276,86 @@ export function surface({ nx, ny, nz, h }: {
258
276
  overhang?: {
259
277
  up: string;
260
278
  angle: number;
279
+ tip?: boolean;
261
280
  };
262
281
  }): {
263
282
  vertices: number[][];
264
283
  faces: number[][];
265
284
  };
285
+ /**
286
+ * A surface made printable in place: faces past the overhang limit tipped back to it, and downward bumps filled to
287
+ * where they join the surface round them, in turn until neither finds any. surface() does this as it draws; call it
288
+ * again after moving a mesh's corners (raising an island off the slicer's view, say).
289
+ * @param {{ vertices: number[][], faces: number[][] }} mesh edited in place
290
+ * @param {{ overhang: { up: string, angle: number }, lo: number[], hi: number[], held?: boolean[] }} o lo, hi: the
291
+ * grid's corners (corners on its faces are pinned); held: corners that must not move (default: those on the faces)
292
+ * @returns {number} how many rounds it took
293
+ */
294
+ export function settle({ vertices: pts, faces }: {
295
+ vertices: number[][];
296
+ faces: number[][];
297
+ }, { overhang, lo, hi, held }: {
298
+ overhang: {
299
+ up: string;
300
+ angle: number;
301
+ };
302
+ lo: number[];
303
+ hi: number[];
304
+ held?: boolean[];
305
+ }): number;
306
+ /**
307
+ * A result's densities on a finer grid, so it can be cleaned and drawn at nearer the printer's resolution: each fine
308
+ * cell takes the density interpolated (trilinear, or bilinear in 2D) between the coarse cells' centres round it, so
309
+ * the surface drawn through it lies where the coarse one would, with the steps between coarse cells resolved. Kept
310
+ * cells become kept blocks.
311
+ * @param {{ nx: number, ny: number, nz?: number, h: number }} size @param {ArrayLike<number>} density
312
+ * @param {number} factor fine cells per coarse cell along each axis (a whole number, 1 for no change)
313
+ * @param {{ keep?: ArrayLike<number>, method?: 'linear' | 'nearest' }} [options] keep: cells that always stay, carried to
314
+ * the fine grid; method: interpolated between coarse centres (linear, default), or each fine cell its coarse cell's
315
+ * value (nearest: the stairs kept exactly, for the smoother to round); smooth: box-blur passes over the fine cells (0)
316
+ * @returns {{ grid: { nx: number, ny: number, nz?: number, h: number }, density: Float64Array, keep?: Uint8Array }}
317
+ */
318
+ export function refine({ nx, ny, nz, h }: {
319
+ nx: number;
320
+ ny: number;
321
+ nz?: number;
322
+ h: number;
323
+ }, density: ArrayLike<number>, factor: number, { keep, method, smooth }?: {
324
+ keep?: ArrayLike<number>;
325
+ method?: "linear" | "nearest";
326
+ }): {
327
+ grid: {
328
+ nx: number;
329
+ ny: number;
330
+ nz?: number;
331
+ h: number;
332
+ };
333
+ density: Float64Array;
334
+ keep?: Uint8Array;
335
+ };
336
+ /**
337
+ * Spikes taken off a result's underside before it's drawn: a solid cell with nothing under it (along the build
338
+ * direction) and too few solid neighbours in its own layer is a hanging point, the start of a jagged edge or an
339
+ * island when sliced; it is emptied, and the layer above is looked at again, until none are left. On a fine grid
340
+ * (refine) this is the printer's own view of the surface. Kept cells stay.
341
+ * @param {{ nx: number, ny: number, nz?: number }} size @param {ArrayLike<number>} density
342
+ * @param {{ up: string, iso?: number, keep?: ArrayLike<number>, thin?: number }} options thin: a hanging cell with
343
+ * fewer solid neighbours than this in its layer is a spike (default 3 of 8 in 3D, 1 of 2 in 2D)
344
+ * @returns {{ density: Float64Array, emptied: number }}
345
+ */
346
+ export function despike({ nx, ny, nz }: {
347
+ nx: number;
348
+ ny: number;
349
+ nz?: number;
350
+ }, density: ArrayLike<number>, { up, iso, keep, thin }: {
351
+ up: string;
352
+ iso?: number;
353
+ keep?: ArrayLike<number>;
354
+ thin?: number;
355
+ }): {
356
+ density: Float64Array;
357
+ emptied: number;
358
+ };
266
359
  /**
267
360
  * A result made printable before it's drawn. Built up layer by layer from the bed, a cell denser than iso stays only if
268
361
  * something holds it up: a cell kept in the layer below, straight under it or diagonally next to that (so nothing
@@ -379,6 +472,21 @@ export type Problem = {
379
472
  * printed this way up ('+z', '-y', …): only material supported from below at 45° or less
380
473
  */
381
474
  overhang?: string;
475
+ /**
476
+ * a mechanism's output:
477
+ * where it should move, along one axis, against a spring (N/mm); the first load is then its input
478
+ */
479
+ output?: {
480
+ at: number[];
481
+ r?: number;
482
+ size?: number[];
483
+ direction: number[];
484
+ spring?: number;
485
+ };
486
+ /**
487
+ * with output, a spring the input pushes against (N/mm)
488
+ */
489
+ input_spring?: number;
382
490
  /**
383
491
  * with overhang, the widest gap the printer bridges (mm): material may also be held up by a run
384
492
  * of solid cells along its own layer, half that long, ending on a held cell
package/topopt.mjs CHANGED
@@ -44,6 +44,9 @@ export { jsBackend };
44
44
  * @property {number} [penal] the penalty (default 3)
45
45
  * @property {boolean} [projection] sharpen with Heaviside projection (default true)
46
46
  * @property {string} [overhang] printed this way up ('+z', '-y', …): only material supported from below at 45° or less
47
+ * @property {{ at: number[], r?: number, size?: number[], direction: number[], spring?: number }} [output] a mechanism's output:
48
+ * where it should move, along one axis, against a spring (N/mm); the first load is then its input
49
+ * @property {number} [input_spring] with output, a spring the input pushes against (N/mm)
47
50
  * @property {number} [bridge] with overhang, the widest gap the printer bridges (mm): material may also be held up by a run
48
51
  * of solid cells along its own layer, half that long, ending on a held cell
49
52
  * @property {number} [steps] at most this many steps (default 300)
@@ -82,8 +85,9 @@ export function discretise(p) {
82
85
  const all = [...space, ...keep].map(bounds), lo = [], hi = [], n = [];
83
86
  for (let a = 0; a < dim; a++) {
84
87
  lo.push(Math.min(...all.map((b) => b[a]))); hi.push(Math.max(...all.map((b) => b[dim + a])));
85
- n.push(Math.max(1, Math.round((hi[a] - lo[a]) / p.cell)));
88
+ n.push(Math.max(1, Math.ceil((hi[a] - lo[a]) / p.cell - 1e-9))); // (up: rounded down, a 40 mm space on 3 mm cells was 39 mm)
86
89
  }
90
+ if (dim === 2) for (let a = 0; a < 2; a++) lo[a] -= (n[a] * p.cell - (hi[a] - lo[a])) / 2; // the padding split evenly round the space
87
91
  if (dim === 3) { // whole numbers of 2, 4 or 8 cells along every side, for multigrid
88
92
  const q = Math.min(...n) >= 16 ? 8 : Math.min(...n) >= 8 ? 4 : 2, build = /^([+-])([xyz])$/.exec(p.overhang ?? '');
89
93
  for (let a = 0; a < 3; a++) {
@@ -133,10 +137,25 @@ export function discretise(p) {
133
137
  const { size, moment } = resultant(mine);
134
138
  return { name, force: f, weight: p.cases?.[name] ?? 1, size, ...(moment ? { moment } : {}) };
135
139
  });
140
+ // A mechanism: the first load is its input, which may push against a spring; the output is a region that should
141
+ // move along a direction (one axis), against its own spring. Both springs sit on the dofs along those axes.
142
+ let output = null, springs = null;
143
+ if (p.output) {
144
+ const o = p.output, dir = o.direction || [];
145
+ if (dir.length !== dim || dir.filter((c) => c).length !== 1) throw new Error(`the output's direction is along one axis: ${dim === 3 ? '[1, 0, 0], [0, -1, 0], …' : '[1, 0], [0, -1], …'}`);
146
+ const ax = dir.findIndex((c) => c), sign = Math.sign(dir[ax]), ns = select(o, 'the output'), L = new Float64Array(g.dofs);
147
+ springs = new Float64Array(g.dofs);
148
+ for (const m of ns) { L[dim * m + ax] += sign / ns.length; springs[dim * m + ax] += (o.spring || 0) / ns.length; }
149
+ const input = p.loads[0], inDir = input.force.findIndex((c) => c), ins = select(input, 'the input');
150
+ if (p.input_spring) for (const m of ins) springs[dim * m + inDir] += p.input_spring / ins.length;
151
+ output = { force: L, spring: o.spring || 0, input: loads[0].force };
152
+ }
136
153
  return {
137
- grid: size, origin, passive, fixed, loads,
154
+ grid: size, origin, passive, fixed, loads, ...(output ? { output, springs } : {}),
138
155
  material: p.material, thickness: p.thickness, volume: p.volume,
139
- filter: p.filter ?? p.cell * 1.5, penal: p.penal ?? 3, projection: p.projection ?? true, steps: p.steps ?? (p.stress ? 1000 : 300),
156
+ // (a solid's default is more: the projection reaches full sharpness about step 200, and every 3D showcase part was
157
+ // still improving at 300: the bin's compliance fell 388 → 265 → 195 over steps 100, 200 and 300)
158
+ filter: p.filter ?? p.cell * 1.5, penal: p.penal ?? 3, projection: p.projection ?? true, steps: p.steps ?? (p.stress ? 1000 : dim === 3 ? 500 : 300),
140
159
  ...(p.overhang ? { overhang: p.overhang } : {}), ...(p.bridge ? { bridge: p.bridge } : {}), ...(p.stress ? { stress: p.stress } : {}),
141
160
  regions: { keep, avoid },
142
161
  };
@@ -251,6 +270,7 @@ export function overhangFilter({ nx, ny, nz = 1 }, up, reach = 0) {
251
270
  for (let t = run.length - 1; t >= 0; t--) { v = smin(v, x[run[t]]); m[run.length - t] = v; }
252
271
  s += Math.pow(v, P); count++;
253
272
  });
273
+ if (s < 1e-200) s = 0; // (again, with the bridges in: a denormal here raised to 1/Q − 1 is infinite, and 0 × that is NaN)
254
274
  sums[e] = s; support[e] = smax(s, count);
255
275
  const d = x[e] - support[e], root = Math.sqrt(d * d + eps);
256
276
  printed[e] = 0.5 * (x[e] + support[e] - root) + halfRootEps; powP[e] = Math.pow(printed[e], P);
@@ -311,41 +331,58 @@ export function overhangFilter({ nx, ny, nz = 1 }, up, reach = 0) {
311
331
  * @param {{ method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend }} [options]
312
332
  */
313
333
  const SUPPORT = 10; // what a kept cell nothing holds up costs, in the part's compliances, over the kept cells
334
+ const ERODE = 0.7, DILATE = 0.3, DILATE_EVERY = 10; // a mechanism's robust formulation: the eroded and dilated copies' thresholds, and how often the dilated volume target follows
314
335
 
315
336
  export function model(spec, { method, backend = jsBackend } = {}) {
316
337
  const g = makeGrid(spec.grid), dim = g.dim, cells = g.cells, m = g.cellDofs, ke = cellStiffness(spec.material.nu, dim);
317
- const { passive, penal } = spec, E = spec.material.E, Emin = E * 1e-9, eta = 0.5, size = dim === 3 ? g.h : spec.thickness;
338
+ const { passive, penal } = spec, E = spec.material.E, Emin = E * 1e-9, ETA = 0.5, size = dim === 3 ? g.h : spec.thickness;
318
339
  const solver = method || (dim === 3 ? 'mg' : 'direct'), tol = solver === 'direct' ? undefined : 1e-6;
319
340
  const filter = densityFilter(spec.grid, spec.filter / spec.grid.h), print = spec.overhang ? overhangFilter(spec.grid, spec.overhang, spec.bridge ? Math.floor(spec.bridge / 2 / spec.grid.h) : 0) : null;
320
341
  const tilde = new Float64Array(cells), made = new Float64Array(cells), phys = new Float64Array(cells), scale = new Float64Array(cells), back = new Float64Array(cells);
321
342
  const fixedValue = (p) => (p === 1 ? 1 : 0);
322
343
  // Heaviside projection about eta: steeper as beta grows, so densities are pushed to 0 or 1 (Wang, Lazarov, Sigmund 2011)
323
- const denominator = (beta) => Math.tanh(beta * eta) + Math.tanh(beta * (1 - eta));
324
- const project = (t, beta) => (spec.projection ? (Math.tanh(beta * eta) + Math.tanh(beta * (t - eta))) / denominator(beta) : t);
325
- const slope = (t, beta) => (spec.projection ? (beta * (1 - Math.tanh(beta * (t - eta)) ** 2)) / denominator(beta) : 1);
344
+ const denominator = (beta, eta = ETA) => Math.tanh(beta * eta) + Math.tanh(beta * (1 - eta));
345
+ // (eta: the threshold; 0.5 for the design as made, less for a dilated copy and more for an eroded one)
346
+ const project = (t, beta, eta = ETA) => (spec.projection ? (Math.tanh(beta * eta) + Math.tanh(beta * (t - eta))) / denominator(beta, eta) : t);
347
+ const slope = (t, beta, eta = ETA) => (spec.projection ? (beta * (1 - Math.tanh(beta * (t - eta)) ** 2)) / denominator(beta, eta) : 1);
326
348
  // Kept and avoided cells are set before the overhang filter as well as after it: a kept cell holds up what's above
327
349
  // it, an avoided cell holds up nothing, and a kept cell is printed (made) only as far as what's below holds it up,
328
350
  // which is what the kept regions' support cost (below) is measured on. The part is analysed with every kept cell solid.
329
- const physical = (x, beta) => {
351
+ const physical = (x, beta, eta = ETA) => {
330
352
  filter.apply(x, tilde);
331
353
  for (let e = 0; e < cells; e++) if (passive[e]) tilde[e] = fixedValue(passive[e]);
332
354
  if (print) print.apply(tilde, made); else made.set(tilde);
333
- for (let e = 0; e < cells; e++) phys[e] = passive[e] ? fixedValue(passive[e]) : project(made[e], beta);
355
+ for (let e = 0; e < cells; e++) phys[e] = passive[e] ? fixedValue(passive[e]) : project(made[e], beta, eta);
334
356
  return phys;
335
357
  };
358
+ // The material's gradient alone (no solve): what a copy of the design at a threshold is worth per design density
359
+ const volumeGradient = (x, beta, eta = ETA) => {
360
+ physical(x, beta, eta);
361
+ const dv = new Float64Array(cells);
362
+ for (let e = 0; e < cells; e++) dv[e] = passive[e] ? 0 : slope(made[e], beta, eta);
363
+ toDesign(dv);
364
+ return dv;
365
+ };
336
366
  // Kept regions must print. With a build direction, how much of the kept material nothing holds up (0 to 1), and its
337
367
  // cost: a kept cell nothing holds up costs SUPPORT times the part's compliance, shared over the kept cells, so the
338
368
  // optimiser puts material in under it. The cost's gradient goes back through the overhang filter to the cells that
339
369
  // would hold it up.
340
370
  const keptCells = Int32Array.from(Array.from(passive).flatMap((p, e) => (p === 1 ? [e] : [])));
341
371
  const unsupported = (beta) => (print && keptCells.length ? keptCells.reduce((t, e) => t + 1 - project(made[e], beta), 0) / keptCells.length : 0);
372
+ // Back through the overhang filter and the density filter to the design densities (kept and avoided cells don't
373
+ // change: their own densities are fixed). Right after the physical() it belongs to.
374
+ const toDesign = (d) => {
375
+ if (print) { print.adjoint(d, back); d.set(back); }
376
+ for (let e = 0; e < cells; e++) if (passive[e]) d[e] = 0;
377
+ filter.adjoint(d, back); d.set(back);
378
+ };
342
379
  let last = null;
343
380
  // Each step solves only the load cases it optimises for (weight above 0); every case is solved when all is set
344
- const evaluate = (x, beta, { all = false, multipliers } = {}) => {
345
- physical(x, beta);
381
+ const evaluate = (x, beta, { all = false, multipliers, eta = ETA } = {}) => {
382
+ physical(x, beta, eta);
346
383
  for (let e = 0; e < cells; e++) scale[e] = size * (Emin + Math.pow(phys[e], penal) * (E - Emin));
347
384
  const active = spec.loads.map((l, c) => (all || l.weight > 0 ? c : -1)).filter((c) => c >= 0);
348
- const run = solve(g, { scale, ke, fixed: spec.fixed, loads: active.map((c) => spec.loads[c].force), method: solver, backend, start: last && active.map((c) => last[c]), ...(tol ? { tol } : {}) }), solved = run.u;
385
+ const run = solve(g, { scale, ke, fixed: spec.fixed, loads: active.map((c) => spec.loads[c].force), ...(spec.springs ? { springs: spec.springs } : {}), method: solver, backend, start: last && active.map((c) => last[c]), ...(tol ? { tol } : {}) }), solved = run.u;
349
386
  const u = spec.loads.map((_, c) => (active.includes(c) ? solved[active.indexOf(c)] : last?.[c] || null));
350
387
  last = u;
351
388
  // Compliance, and its gradient with respect to each cell's physical density: −p ρ^(p−1) (E − Emin) size · uₑᵀ kₑ uₑ
@@ -366,15 +403,26 @@ export function model(spec, { method, backend = jsBackend } = {}) {
366
403
  // Back through the projection, the overhang filter and the density filter to the design densities; kept and
367
404
  // avoided cells don't change
368
405
  const lack = unsupported(beta);
369
- for (let e = 0; e < cells; e++) { const s = passive[e] ? 0 : slope(made[e], beta); dc[e] *= s; dv[e] = s; }
406
+ for (let e = 0; e < cells; e++) { const s = passive[e] ? 0 : slope(made[e], beta, eta); dc[e] *= s; dv[e] = s; }
370
407
  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); }
371
- const toDesign = (d) => {
372
- if (print) { print.adjoint(d, back); d.set(back); }
373
- for (let e = 0; e < cells; e++) if (passive[e]) d[e] = 0;
374
- filter.adjoint(d, back); d.set(back);
375
- };
376
408
  toDesign(dc); toDesign(dv);
377
409
  const stress = Ss ? stressLimits(u, active, run.again, multipliers || { lam: active.map(() => new Float64Array(cells * Ss.length)), mu: 1 }) : null;
410
+ // A mechanism: how far the output moves along its direction under the input (travel), and its gradient: with the
411
+ // adjoint λ from K λ = L (the output's direction), d travel / dρ = −λₑᵀ (dkₑ/dρ) uₑ (Sigmund 1997)
412
+ let mechanism = null;
413
+ if (spec.output && u[0]) {
414
+ const L = spec.output.force, u0 = u[0], travel = jsBackend.dot(L, u0), [lam] = run.again([L]), d = new Float64Array(cells);
415
+ let input = 0; for (let i = 0; i < u0.length; i++) if (spec.output.input[i]) input += spec.output.input[i] * u0[i];
416
+ input /= Math.hypot(...spec.loads[0].force.filter((v) => v)) || 1; // along the input, per unit of it: the input's travel
417
+ for (let e = 0; e < cells; e++) {
418
+ let t = 0;
419
+ const o = e * m;
420
+ for (let a = 0; a < m; a++) { let q = 0; for (let b = 0; b < m; b++) q += ke[a * m + b] * u0[g.edof[o + b]]; t += lam[g.edof[o + a]] * q; }
421
+ d[e] = passive[e] ? 0 : -penal * Math.pow(phys[e], penal - 1) * (E - Emin) * size * t * slope(made[e], beta, eta);
422
+ }
423
+ toDesign(d);
424
+ mechanism = { travel, input, d };
425
+ }
378
426
  const cases = spec.loads.map((l, c) => {
379
427
  if (!u[c]) return { name: l.name, compliance: NaN, deflection: NaN, stiffness: NaN };
380
428
  const ci = jsBackend.dot(l.force, u[c]);
@@ -384,7 +432,7 @@ export function model(spec, { method, backend = jsBackend } = {}) {
384
432
  return { name: l.name, compliance: ci, deflection, stiffness: deflection ? l.size / deflection : Infinity };
385
433
  });
386
434
  if (stress) { for (let e = 0; e < cells; e++) stress.d[e] *= passive[e] ? 0 : slope(made[e], beta); toDesign(stress.d); }
387
- return { compliance, dc, dv, u, cases, unsupported: lack, ...(stress ? { stress } : {}) };
435
+ return { compliance, dc, dv, u, cases, unsupported: lack, ...(stress ? { stress } : {}), ...(mechanism ? { mechanism } : {}) };
388
436
  };
389
437
  // Stress limits on every cell (Senhora, Giraldo-Londoño, Menezes, Paulino 2020): each cell's von Mises stress at its
390
438
  // centre, as if solid, over the limit, less 1, times the cell's density, so an empty cell's limit vanishes. They're
@@ -428,7 +476,7 @@ export function model(spec, { method, backend = jsBackend } = {}) {
428
476
  });
429
477
  return { J, d, h, peak };
430
478
  };
431
- return { physical, evaluate, cells, passive, limits: Ss ? cells * Ss.length : 0 };
479
+ return { physical, evaluate, volumeGradient, cells, passive, limits: Ss ? cells * Ss.length : 0 };
432
480
  }
433
481
 
434
482
  /**
@@ -595,7 +643,7 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
595
643
  const inSpace = passive.reduce((s, p) => s + (p !== -2 ? 1 : 0), 0), kept = passive.reduce((s, p) => s + (p === 1 ? 1 : 0), 0);
596
644
  const free = passive.reduce((s, p) => s + (p === 0 ? 1 : 0), 0);
597
645
  // A stress limit asks for the lightest layout that keeps to it; a volume, for the stiffest that fills it
598
- const lightest = spec.stress > 0;
646
+ const lightest = spec.stress > 0, mechanism = !!spec.output;
599
647
  if (lightest && spec.volume != null) throw new Error('give a volume (the stiffest layout that fills it) or a stress limit (the lightest that keeps to it), not both');
600
648
  if (!lightest && !(spec.volume > 0 && spec.volume <= 1)) throw new Error(`the volume is a share of the space, from 0 to 1 (got ${spec.volume})`);
601
649
  const target = lightest ? 0 : spec.volume * inSpace;
@@ -609,14 +657,19 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
609
657
  // The lightest layout: the method of moving asymptotes on the material used plus the stress limits' augmented
610
658
  // Lagrangian term, its multipliers raised every INNER steps (λ += μ h) and its penalty grown (μ × 1.1, at most 10⁴)
611
659
  const INNER = 5, freeCells = Int32Array.from(Array.from(passive).flatMap((p, e) => (p ? [] : [e]))), n = freeCells.length;
612
- const mmaStep = lightest ? mma({ n, m: 0, xmin: new Float64Array(n), xmax: new Float64Array(n).fill(1) }) : null;
660
+ // A mechanism: the method of moving asymptotes maximising the output's travel (minimising −travel) under the volume
661
+ const mmaStep = lightest ? mma({ n, m: 0, xmin: new Float64Array(n), xmax: new Float64Array(n).fill(1) }) : mechanism ? mma({ n, m: 1, xmin: new Float64Array(n), xmax: new Float64Array(n).fill(1) }) : null;
613
662
  const multipliers = lightest ? { lam: spec.loads.filter((l) => l.weight > 0).map(() => new Float64Array(m.limits)), mu: 10 } : undefined;
614
663
  const xf = new Float64Array(n), pick = (d) => Float64Array.from(freeCells, (e) => d[e]);
615
- let step = 0, change = 1, converged = false, beta = 1, sinceBeta = 0, peak = null;
664
+ let step = 0, change = 1, converged = false, beta = 1, sinceBeta = 0, peak = null, targetD = target;
616
665
  const tried = new Float64Array(cells); // the last design the bisection analysed, and how much it filled
617
666
  while (step < spec.steps) {
618
667
  step++; sinceBeta++;
619
- const { compliance, dc, dv, stress } = m.evaluate(x, beta, { multipliers });
668
+ // A mechanism is optimised robustly (after Wang, Lazarov and Sigmund 2011): its travel on an eroded copy of the
669
+ // design (threshold ERODE), its volume on a dilated one (DILATE), the design as made between them. A hinge that
670
+ // survives erosion has real width, so no hinge is a point. (The design as made is stiffer than the eroded copy
671
+ // it's optimised on, by a hinge width's worth; a worst-of-three objective would close that gap, and is to come.)
672
+ const { compliance, dc, dv, stress, mechanism: mech } = m.evaluate(x, beta, { multipliers, ...(mechanism ? { eta: ERODE } : {}) });
620
673
  // A sharper projection magnifies each change, so the move limit shrinks with it (else the design flickers)
621
674
  const limit = move * Math.min(1, 2 / beta);
622
675
  if (lightest) {
@@ -633,6 +686,16 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
633
686
  multipliers.lam.forEach((l, k) => { for (let j = 0; j < l.length; j++) l[j] += multipliers.mu * stress.h[k][j]; });
634
687
  multipliers.mu = Math.min(1.1 * multipliers.mu, 1e4);
635
688
  }
689
+ } else if (mechanism) {
690
+ history.push(mech.travel);
691
+ // The dilated copy's material, kept to a target that puts the design as made at the volume asked for (the
692
+ // target follows the ratio of the two, re-measured every DILATE_EVERY steps)
693
+ const usedD = m.physical(x, beta, DILATE).reduce((s, v, e) => s + (passive[e] !== -2 ? v : 0), 0), dvD = m.volumeGradient(x, beta, DILATE);
694
+ if (step % DILATE_EVERY === 1) { const usedI = m.physical(x, beta).reduce((s, v, e) => s + (passive[e] !== -2 ? v : 0), 0); targetD = (target * usedD) / Math.max(usedI, 1e-9); }
695
+ xf.set(pick(x));
696
+ mmaStep(xf, -mech.travel, pick(mech.d).map((v) => -v), [usedD / targetD - 1], [pick(dvD).map((v) => v / targetD)], limit); // (minimising −travel)
697
+ xnew.set(x);
698
+ freeCells.forEach((e, k) => { xnew[e] = xf[k]; });
636
699
  } else {
637
700
  history.push(compliance);
638
701
  // Optimality criteria: scale each cell by √(−dc/dv/λ), within the move limit, finding λ by bisection so the
@@ -656,7 +719,7 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
656
719
  change = 0;
657
720
  for (let e = 0; e < cells; e++) change = Math.max(change, Math.abs(xnew[e] - x[e]));
658
721
  x.set(xnew);
659
- onStep?.({ step, steps: spec.steps, compliance, change, beta, density: m.physical(x, beta), ...(lightest ? { stress: peak, volume: history.at(-1) } : {}) });
722
+ onStep?.({ step, steps: spec.steps, compliance, change, beta, density: m.physical(x, beta), ...(lightest ? { stress: peak, volume: history.at(-1) } : {}), ...(mechanism ? { travel: mech.travel } : {}) });
660
723
  if (lightest) {
661
724
  // Sharper every 25 rounds of the multipliers
662
725
  if (beta < betaMax && sinceBeta >= 25 * INNER) { beta *= 2; sinceBeta = 0; }
@@ -665,14 +728,16 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
665
728
  // Sharpen: double the projection's steepness when the design settles (or every 50 steps), until it's at its sharpest
666
729
  if (beta < betaMax && (change < tol || sinceBeta >= 50)) { beta *= 2; sinceBeta = 0; continue; }
667
730
  // Done when nothing moves, or at full sharpness the compliance has stopped improving (within 0.1% over 10 steps)
668
- const settled = spec.projection && history.length > 10 && beta >= betaMax && sinceBeta > 10 && Math.abs(history.at(-11) - compliance) <= 1e-3 * compliance;
731
+ const latest = mechanism ? mech.travel : compliance;
732
+ const settled = spec.projection && history.length > 10 && beta >= betaMax && sinceBeta > 10 && Math.abs(history.at(-11) - latest) <= 1e-3 * Math.abs(latest);
669
733
  if (beta >= betaMax && (change < tol || settled)) { converged = true; break; }
670
734
  }
671
735
  // The final design, analysed as it is
672
736
  const final = m.evaluate(x, beta, { all: true }), phys = Float64Array.from(m.physical(x, beta));
673
737
  // (the final physical call is after evaluate's, so unsupported comes from the evaluation of this design)
674
738
  return {
675
- density: phys, compliance: final.compliance, cases: final.cases, unsupported: final.unsupported, ...(final.stress ? { stress: { peak: final.stress.peak, limit: spec.stress } } : {}),
739
+ density: phys, compliance: final.compliance, cases: final.cases, unsupported: final.unsupported,
740
+ ...(final.mechanism ? { mechanism: { travel: final.mechanism.travel, input: final.mechanism.input, advantage: final.mechanism.travel / (final.mechanism.input || 1) } } : {}), ...(final.stress ? { stress: { peak: final.stress.peak, limit: spec.stress } } : {}),
676
741
  volume: phys.reduce((s, v, e) => s + (passive[e] !== -2 ? v : 0), 0) / inSpace, steps: step, converged, history, seconds: (Date.now() - started) / 1000,
677
742
  };
678
743
  }
@@ -880,9 +945,11 @@ function simplify(loop, tolerance) {
880
945
  * @param {{ nx: number, ny: number, nz: number, h: number }} size @param {ArrayLike<number>} density @param {number[]} origin
881
946
  * Vertices on the grid's outer faces stay where they are as it's smoothed, so a part that fills its space to a face (a
882
947
  * base on the bed) keeps that face flat, and the walls rising from it don't lean out.
883
- * @param {{ smooth?: number, iso?: number, overhang?: { up: string, angle: number } }} [options] iso: the density the
884
- * surface is drawn at (0.5). overhang: the build direction ('+z') and the printer's overhang limit (degrees from
885
- * vertical): faces smoothing left past it are tipped back to it.
948
+ * @param {{ smooth?: number, iso?: number, overhang?: { up: string, angle: number, tip?: boolean } }} [options] iso: the
949
+ * density the surface is drawn at (0.5). overhang: the build direction ('+z') and the printer's overhang limit (degrees
950
+ * from vertical): downward bumps left by smoothing are filled, so nothing starts in mid-air when sliced; with tip, faces
951
+ * past the limit are also tipped back to it (off by default: tipping corners leaves dips that slice as islands, and the
952
+ * layers step out no further for it).
886
953
  * @returns {{ vertices: number[][], faces: number[][] }}
887
954
  */
888
955
  export function surface({ nx, ny, nz, h }, density, origin = [0, 0, 0], { smooth = 4, iso = 0.5, overhang } = {}) {
@@ -952,14 +1019,43 @@ export function surface({ nx, ny, nz, h }, density, origin = [0, 0, 0], { smooth
952
1019
  }
953
1020
  // Printable: faces past the limit tipped back, and tips lifted, in turn until neither finds any (each can make work for
954
1021
  // the other: a lifted tip leaves a face sloping more, a tipped face can leave a corner lowest)
955
- 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; }
956
- return { vertices: pts, faces };
1022
+ if (overhang) settle({ vertices: pts, faces }, { overhang, lo, hi, held });
1023
+ return weld(pts, faces, h * 1e-7);
1024
+ }
1025
+
1026
+ // Corners that ended up in one place (crossings at a grid face, clamped to its corners, then smoothed) merged where a
1027
+ // face joins them (a zero-length edge collapsed), and the triangles that leaves with no area dropped. Only joined
1028
+ // corners are merged: two that merely touch are kept apart, so the mesh stays closed and folds nowhere
1029
+ function weld(pts, faces, tol) {
1030
+ const parent = Int32Array.from(pts.keys()), root = (i) => { while (parent[i] !== i) i = parent[i] = parent[parent[i]]; return i; };
1031
+ const same = (a, b) => Math.abs(pts[a][0] - pts[b][0]) <= tol && Math.abs(pts[a][1] - pts[b][1]) <= tol && Math.abs(pts[a][2] - pts[b][2]) <= tol;
1032
+ for (const f of faces) for (let i = 0; i < 3; i++) { const a = f[i], b = f[(i + 1) % 3]; if (same(a, b)) parent[root(a)] = root(b); }
1033
+ const index = new Map(), out = [];
1034
+ const map = (i) => { const r = root(i); if (!index.has(r)) { index.set(r, out.length); out.push(pts[r]); } return index.get(r); };
1035
+ const kept = faces.map((f) => f.map(map)).filter((f) => f[0] !== f[1] && f[1] !== f[2] && f[0] !== f[2]);
1036
+ return { vertices: out, faces: kept };
1037
+ }
1038
+
1039
+ /**
1040
+ * A surface made printable in place: faces past the overhang limit tipped back to it, and downward bumps filled to
1041
+ * where they join the surface round them, in turn until neither finds any. surface() does this as it draws; call it
1042
+ * again after moving a mesh's corners (raising an island off the slicer's view, say).
1043
+ * @param {{ vertices: number[][], faces: number[][] }} mesh edited in place
1044
+ * @param {{ overhang: { up: string, angle: number }, lo: number[], hi: number[], held?: boolean[] }} o lo, hi: the
1045
+ * grid's corners (corners on its faces are pinned); held: corners that must not move (default: those on the faces)
1046
+ * @returns {number} how many rounds it took
1047
+ */
1048
+ export function settle({ vertices: pts, faces }, { overhang, lo, hi, held }) {
1049
+ const near = 1e-6, pinned = held ?? pts.map((p) => p.some((x, q) => x < lo[q] + near || x > hi[q] - near));
1050
+ let round = 0;
1051
+ for (; round < 20; round++) { const tipped = overhang.tip ? steepen(pts, faces, pinned, overhang, lo, hi) : false, lifted = fill(pts, faces, pinned, overhang, lo); if (!tipped && !lifted) break; }
1052
+ return round;
957
1053
  }
958
1054
 
959
1055
  // Faces past the overhang limit, tipped back to it. Optimised in cubes, a printable slope is a staircase of 45°, and
960
1056
  // smoothing leaves small faces either side of 45°. Each face facing down more steeply than the limit is turned about
961
1057
  // its centre, moving its corners along the build direction only, until it's a little inside the limit: about as much
962
- // material is added as taken away. A corner shared by several such faces moves by their average; it's repeated until
1058
+ // material is added as taken away. (Off by default: a corner moved down is a dip, an island when sliced.) A corner shared by several such faces moves by their average; it's repeated until
963
1059
  // none are left. Flat faces (a bridge) and faces held on the grid's sides stay as they are.
964
1060
  function steepen(pts, faces, held, { up, angle }, lo, hi, passes = 200) {
965
1061
  const q = 'xyz'.indexOf(up[1]), s = up[0] === '-' ? -1 : 1, [a, b] = [0, 1, 2].filter((x) => x !== q);
@@ -988,6 +1084,36 @@ function steepen(pts, faces, held, { up, angle }, lo, hi, passes = 200) {
988
1084
  return true;
989
1085
  }
990
1086
 
1087
+ // Downward bumps filled: on the underside, a dip whose every way out leads up (along the build direction) is a bump the
1088
+ // printer meets from below: its lowest layer has nothing under it, an island. Each such basin is raised to the height
1089
+ // where it joins the surface round it (a flood from the bed, in order of height, as the depressions of a map are filled
1090
+ // to their spill points), which leaves a small flat underside there, bridged. The bed's corners, those held on the
1091
+ // grid's sides, and corners facing up are the sources and stay.
1092
+ function fill(pts, faces, held, { up }, lo) {
1093
+ const q = 'xyz'.indexOf(up[1]), s = up[0] === '-' ? -1 : 1, near = pts.map(() => new Set()), facing = new Float64Array(pts.length);
1094
+ for (const f of faces) {
1095
+ for (let i = 0; i < 3; i++) { near[f[i]].add(f[(i + 1) % 3]); near[f[i]].add(f[(i + 2) % 3]); }
1096
+ 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]);
1097
+ 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];
1098
+ for (const m of f) facing[m] += s * nq;
1099
+ }
1100
+ const height = (v) => s * v[q], level = new Float64Array(pts.length).fill(Infinity), done = new Uint8Array(pts.length);
1101
+ // A heap of corners by their level, lowest first
1102
+ const heap = [], push = (n, l) => { level[n] = l; heap.push([l, n]); let i = heap.length - 1; while (i > 0) { const pa = (i - 1) >> 1; if (heap[pa][0] <= heap[i][0]) break; [heap[pa], heap[i]] = [heap[i], heap[pa]]; i = pa; } };
1103
+ const pop = () => { const top = heap[0], last = heap.pop(); if (heap.length) { heap[0] = last; let i = 0; for (;;) { const a = 2 * i + 1, b = a + 1; let m = i; if (a < heap.length && heap[a][0] < heap[m][0]) m = a; if (b < heap.length && heap[b][0] < heap[m][0]) m = b; if (m === i) break; [heap[m], heap[i]] = [heap[i], heap[m]]; i = m; } } return top; };
1104
+ const bed = s > 0 ? lo[q] : null;
1105
+ for (let m = 0; m < pts.length; m++) if (held[m] || facing[m] >= 0 || (bed !== null && Math.abs(pts[m][q] - bed) < 1e-9) || !near[m].size) push(m, height(pts[m]));
1106
+ let moved = 0;
1107
+ while (heap.length) {
1108
+ const [l, n] = pop();
1109
+ if (done[n]) continue;
1110
+ done[n] = 1;
1111
+ if (height(pts[n]) < l - 1e-9) { pts[n][q] = s * l; moved++; } // in a basin: raised to its spill level
1112
+ for (const m of near[n]) if (!done[m]) { const lm = Math.max(height(pts[m]), l); if (lm < level[m]) push(m, lm); }
1113
+ }
1114
+ return moved > 0;
1115
+ }
1116
+
991
1117
  // Tips lifted: a corner lower than every corner round it (along the build direction), on faces facing down, starts in
992
1118
  // mid-air, where a printer has nothing to lay it on. Smoothing leaves these under edges and bridges. Each is raised level
993
1119
  // with its lowest neighbour, which leaves a small flat underside (bridged), until none are left. The bed's corners and
@@ -1014,6 +1140,79 @@ function lift(pts, faces, held, { up }, lo, passes = 50) {
1014
1140
  return true;
1015
1141
  }
1016
1142
 
1143
+ /**
1144
+ * A result's densities on a finer grid, so it can be cleaned and drawn at nearer the printer's resolution: each fine
1145
+ * cell takes the density interpolated (trilinear, or bilinear in 2D) between the coarse cells' centres round it, so
1146
+ * the surface drawn through it lies where the coarse one would, with the steps between coarse cells resolved. Kept
1147
+ * cells become kept blocks.
1148
+ * @param {{ nx: number, ny: number, nz?: number, h: number }} size @param {ArrayLike<number>} density
1149
+ * @param {number} factor fine cells per coarse cell along each axis (a whole number, 1 for no change)
1150
+ * @param {{ keep?: ArrayLike<number>, method?: 'linear' | 'nearest' }} [options] keep: cells that always stay, carried to
1151
+ * the fine grid; method: interpolated between coarse centres (linear, default), or each fine cell its coarse cell's
1152
+ * value (nearest: the stairs kept exactly, for the smoother to round); smooth: box-blur passes over the fine cells (0)
1153
+ * @returns {{ grid: { nx: number, ny: number, nz?: number, h: number }, density: Float64Array, keep?: Uint8Array }}
1154
+ */
1155
+ export function refine({ nx, ny, nz = 1, h }, density, factor, { keep, method = 'linear', smooth = 0 } = {}) {
1156
+ const f = Math.max(1, Math.round(factor)), dim = nz > 1 ? 3 : 2, n = [nx, ny, nz], m = n.map((c, a) => (a < dim ? c * f : c)), cells = m[0] * m[1] * m[2];
1157
+ const out = new Float64Array(cells), fine = keep ? new Uint8Array(cells) : undefined, at = (i, j, k) => density[(Math.min(nz - 1, Math.max(0, k)) * ny + Math.min(ny - 1, Math.max(0, j))) * nx + Math.min(nx - 1, Math.max(0, i))];
1158
+ for (let k = 0; k < m[2]; k++) for (let j = 0; j < m[1]; j++) for (let i = 0; i < m[0]; i++) {
1159
+ // The fine cell's centre in coarse-cell units, measured from the coarse centres
1160
+ const x = (i + 0.5) / f - 0.5, y = (j + 0.5) / f - 0.5, z = dim === 3 ? (k + 0.5) / f - 0.5 : 0;
1161
+ const i0 = Math.floor(x), j0 = Math.floor(y), k0 = Math.floor(z), tx = x - i0, ty = y - j0, tz = z - k0;
1162
+ let v = 0;
1163
+ if (method === 'nearest') v = at(Math.floor(i / f), Math.floor(j / f), dim === 3 ? Math.floor(k / f) : 0); // each fine cell its coarse cell's value: the stairs kept
1164
+ else for (let c = 0; c <= (dim === 3 ? 1 : 0); c++) for (let b = 0; b <= 1; b++) for (let a = 0; a <= 1; a++) v += at(i0 + a, j0 + b, k0 + c) * (a ? tx : 1 - tx) * (b ? ty : 1 - ty) * (dim === 3 ? (c ? tz : 1 - tz) : 1);
1165
+ const e = (k * m[1] + j) * m[0] + i;
1166
+ out[e] = v;
1167
+ if (fine) fine[e] = keep[(Math.floor(k / (dim === 3 ? f : 1)) * ny + Math.floor(j / f)) * nx + Math.floor(i / f)] ? 1 : 0;
1168
+ }
1169
+ // Smoothed a little (a box over the neighbouring fine cells, smooth passes): the interpolated stairs between coarse
1170
+ // cells bulge under the overhang line at each step, and the blur takes the bulges down
1171
+ let v = out;
1172
+ for (let pass = 0; pass < smooth; pass++) {
1173
+ const next = new Float64Array(cells);
1174
+ for (let k = 0; k < m[2]; k++) for (let j = 0; j < m[1]; j++) for (let i = 0; i < m[0]; i++) {
1175
+ let sum = 0, count = 0;
1176
+ for (let c = dim === 3 ? -1 : 0; c <= (dim === 3 ? 1 : 0); c++) for (let b = -1; b <= 1; b++) for (let a = -1; a <= 1; a++) { const ii = i + a, jj = j + b, kk = k + c; if (ii >= 0 && ii < m[0] && jj >= 0 && jj < m[1] && kk >= 0 && kk < m[2]) { sum += v[(kk * m[1] + jj) * m[0] + ii]; count++; } }
1177
+ next[(k * m[1] + j) * m[0] + i] = sum / count;
1178
+ }
1179
+ v = next;
1180
+ }
1181
+ return { grid: dim === 3 ? { nx: m[0], ny: m[1], nz: m[2], h: h / f } : { nx: m[0], ny: m[1], h: h / f }, density: v, ...(fine ? { keep: fine } : {}) };
1182
+ }
1183
+
1184
+ /**
1185
+ * Spikes taken off a result's underside before it's drawn: a solid cell with nothing under it (along the build
1186
+ * direction) and too few solid neighbours in its own layer is a hanging point, the start of a jagged edge or an
1187
+ * island when sliced; it is emptied, and the layer above is looked at again, until none are left. On a fine grid
1188
+ * (refine) this is the printer's own view of the surface. Kept cells stay.
1189
+ * @param {{ nx: number, ny: number, nz?: number }} size @param {ArrayLike<number>} density
1190
+ * @param {{ up: string, iso?: number, keep?: ArrayLike<number>, thin?: number }} options thin: a hanging cell with
1191
+ * fewer solid neighbours than this in its layer is a spike (default 3 of 8 in 3D, 1 of 2 in 2D)
1192
+ * @returns {{ density: Float64Array, emptied: number }}
1193
+ */
1194
+ export function despike({ nx, ny, nz = 1 }, density, { up, iso = 0.5, keep, thin }) {
1195
+ const n = nz > 1 ? [nx, ny, nz] : [nx, ny], dim = n.length, ax = 'xyz'.indexOf(up.at(-1)), sign = up[0] === '-' ? -1 : 1, least = thin ?? (dim === 3 ? 3 : 1);
1196
+ const stride = [1, nx, nx * ny], other = [0, 1, 2].slice(0, dim).filter((a) => a !== ax), out = Float64Array.from(density), coord = (e, a) => Math.floor(e / stride[a]) % n[a];
1197
+ const solid = (e) => out[e] >= iso || (keep && keep[e]);
1198
+ let emptied = 0, changed = true;
1199
+ for (let pass = 0; pass < 50 && changed; pass++) {
1200
+ changed = false;
1201
+ for (let e = 0; e < out.length; e++) {
1202
+ if (!(out[e] >= iso) || (keep && keep[e])) continue;
1203
+ const c = coord(e, ax);
1204
+ if ((sign > 0 && c === 0) || (sign < 0 && c === n[ax] - 1)) continue; // on the bed
1205
+ if (solid(e - sign * stride[ax])) continue; // something straight under it
1206
+ let around = 0, slots = 0;
1207
+ const offs = other.map((a) => [-stride[a], 0, stride[a]].filter((d, i) => { const q = coord(e, a); return (i === 0 && q > 0) || i === 1 || (i === 2 && q < n[a] - 1); }));
1208
+ if (offs.length === 1) for (const d of offs[0]) { if (d) { slots++; if (solid(e + d)) around++; } }
1209
+ else for (const d0 of offs[0]) for (const d1 of offs[1]) { if (d0 || d1) { slots++; if (solid(e + d0 + d1)) around++; } }
1210
+ if (around < Math.min(least, slots)) { out[e] = 0; emptied++; changed = true; }
1211
+ }
1212
+ }
1213
+ return { density: out, emptied };
1214
+ }
1215
+
1017
1216
  /**
1018
1217
  * A result made printable before it's drawn. Built up layer by layer from the bed, a cell denser than iso stays only if
1019
1218
  * something holds it up: a cell kept in the layer below, straight under it or diagonally next to that (so nothing