@rulecad/topopt 0.2.6 → 0.2.11

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 +40 -2
  2. package/package.json +1 -1
  3. package/topopt.d.mts +133 -13
  4. package/topopt.mjs +315 -59
package/README.md CHANGED
@@ -58,11 +58,15 @@ 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
65
- than 45°. The result prints without supports in that direction. Kept regions must print too: a kept cell that
67
+ than 45°. With `bridge` (the widest gap the printer spans, mm), a cell is also held up by a bridge: a run of solid
68
+ cells along its own layer, up to half that long, ending on a held cell. The result prints without supports in that
69
+ direction. Kept regions must print too: a kept cell that
66
70
  nothing holds up costs the optimiser as much as the whole part's compliance (shared over the kept cells), so it grows
67
71
  what holds it up; `result.unsupported` says how much of the kept material is still left hanging, which means there
68
72
  wasn't material enough to stand it on.
@@ -125,6 +129,37 @@ falls by 46%. Two things to know:
125
129
  with that margin in mind.
126
130
  - **It may not settle within its steps.** This one ran its 1,000 steps with the peak hovering 5% over the limit.
127
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
+
128
163
  ## Checked against the published code
129
164
 
130
165
  With projection off, it matches a line-by-line port of the 88-line MATLAB code (`reference/top88.py`) step for step:
@@ -147,6 +182,9 @@ Its gradients agree with finite differences through the filter and the projectio
147
182
 
148
183
  ## Sources
149
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
+
150
188
  - Bendsøe, Sigmund (2003). *Topology Optimization: Theory, Methods and Applications*. Springer.
151
189
  - Andreassen, Clausen, Schevenels, Lazarov, Sigmund (2011). Efficient topology optimization in MATLAB using 88 lines
152
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.6",
3
+ "version": "0.2.11",
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
@@ -22,6 +22,11 @@
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)
28
+ * @property {number} [bridge] with overhang, the widest gap the printer bridges (mm): material may also be held up by a run
29
+ * of solid cells along its own layer, half that long, ending on a held cell
25
30
  * @property {number} [steps] at most this many steps (default 300)
26
31
  */
27
32
  /**
@@ -50,7 +55,21 @@ export function discretise(p: any): {
50
55
  avoid: any;
51
56
  };
52
57
  stress?: any;
58
+ bridge?: any;
53
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>;
54
73
  grid: {
55
74
  nx: number;
56
75
  ny: number;
@@ -72,13 +91,6 @@ export function discretise(p: any): {
72
91
  weight: any;
73
92
  size: number;
74
93
  }[];
75
- material: any;
76
- thickness: any;
77
- volume: any;
78
- filter: any;
79
- penal: any;
80
- projection: any;
81
- steps: any;
82
94
  };
83
95
  /**
84
96
  * The density filter: each cell's filtered density is the weighted average of the cells within radius (weights
@@ -98,13 +110,17 @@ export function densityFilter({ nx, ny, nz }: {
98
110
  * material under it: the cell itself and its neighbours along each side, in the layer below (3 cells in 2D, 5 in 3D,
99
111
  * so nothing overhangs by more than 45°). Smooth minimum and maximum keep it differentiable. apply gives the printable
100
112
  * densities; adjoint carries sensitivities back through it.
113
+ * With reach, a cell is also held up by a bridge: a run of up to reach solid cells along its own layer, each way along
114
+ * each axis, ending on a cell that something below holds up (the run's cells and that cell's support, all through the
115
+ * smooth minimum). That's what a printer spans: give reach as half the printer's bridge, in cells.
101
116
  * @param {{ nx: number, ny: number, nz?: number }} size @param {string} up the build direction: '+z', '-x', …
117
+ * @param {number} [reach] how many cells a bridge may run from a held cell (0: none)
102
118
  */
103
119
  export function overhangFilter({ nx, ny, nz }: {
104
120
  nx: number;
105
121
  ny: number;
106
122
  nz?: number;
107
- }, up: string): {
123
+ }, up: string, reach?: number): {
108
124
  apply(x: any, out: any): any;
109
125
  adjoint(g: any, out: any): any;
110
126
  };
@@ -120,10 +136,16 @@ export function model(spec: any, { method, backend }?: {
120
136
  axpy: (a: number, x: Float64Array, y: Float64Array) => void;
121
137
  };
122
138
  }): {
123
- physical: (x: any, beta: any) => Float64Array<ArrayBuffer>;
124
- 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 }?: {
125
141
  all?: boolean;
142
+ eta?: number;
126
143
  }) => {
144
+ mechanism?: {
145
+ travel: number;
146
+ input: number;
147
+ d: Float64Array<ArrayBuffer>;
148
+ };
127
149
  stress?: {
128
150
  J: number;
129
151
  d: Float64Array<ArrayBuffer>;
@@ -137,6 +159,7 @@ export function model(spec: any, { method, backend }?: {
137
159
  cases: any;
138
160
  unsupported: number;
139
161
  };
162
+ volumeGradient: (x: any, beta: any, eta?: number) => Float64Array<ArrayBuffer>;
140
163
  cells: number;
141
164
  passive: any;
142
165
  limits: number;
@@ -235,9 +258,11 @@ export function area(loop: [number, number][]): number;
235
258
  * @param {{ nx: number, ny: number, nz: number, h: number }} size @param {ArrayLike<number>} density @param {number[]} origin
236
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
237
260
  * base on the bed) keeps that face flat, and the walls rising from it don't lean out.
238
- * @param {{ smooth?: number, iso?: number, overhang?: { up: string, angle: number } }} [options] iso: the density the
239
- * surface is drawn at (0.5). overhang: the build direction ('+z') and the printer's overhang limit (degrees from
240
- * 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).
241
266
  * @returns {{ vertices: number[][], faces: number[][] }}
242
267
  */
243
268
  export function surface({ nx, ny, nz, h }: {
@@ -251,11 +276,86 @@ export function surface({ nx, ny, nz, h }: {
251
276
  overhang?: {
252
277
  up: string;
253
278
  angle: number;
279
+ tip?: boolean;
254
280
  };
255
281
  }): {
256
282
  vertices: number[][];
257
283
  faces: number[][];
258
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
+ };
259
359
  /**
260
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
261
361
  * something holds it up: a cell kept in the layer below, straight under it or diagonally next to that (so nothing
@@ -372,6 +472,26 @@ export type Problem = {
372
472
  * printed this way up ('+z', '-y', …): only material supported from below at 45° or less
373
473
  */
374
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;
490
+ /**
491
+ * with overhang, the widest gap the printer bridges (mm): material may also be held up by a run
492
+ * of solid cells along its own layer, half that long, ending on a held cell
493
+ */
494
+ bridge?: number;
375
495
  /**
376
496
  * at most this many steps (default 300)
377
497
  */
package/topopt.mjs CHANGED
@@ -44,6 +44,11 @@ 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)
50
+ * @property {number} [bridge] with overhang, the widest gap the printer bridges (mm): material may also be held up by a run
51
+ * of solid cells along its own layer, half that long, ending on a held cell
47
52
  * @property {number} [steps] at most this many steps (default 300)
48
53
  */
49
54
 
@@ -131,11 +136,26 @@ export function discretise(p) {
131
136
  const { size, moment } = resultant(mine);
132
137
  return { name, force: f, weight: p.cases?.[name] ?? 1, size, ...(moment ? { moment } : {}) };
133
138
  });
139
+ // A mechanism: the first load is its input, which may push against a spring; the output is a region that should
140
+ // move along a direction (one axis), against its own spring. Both springs sit on the dofs along those axes.
141
+ let output = null, springs = null;
142
+ if (p.output) {
143
+ const o = p.output, dir = o.direction || [];
144
+ 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], …'}`);
145
+ const ax = dir.findIndex((c) => c), sign = Math.sign(dir[ax]), ns = select(o, 'the output'), L = new Float64Array(g.dofs);
146
+ springs = new Float64Array(g.dofs);
147
+ for (const m of ns) { L[dim * m + ax] += sign / ns.length; springs[dim * m + ax] += (o.spring || 0) / ns.length; }
148
+ const input = p.loads[0], inDir = input.force.findIndex((c) => c), ins = select(input, 'the input');
149
+ if (p.input_spring) for (const m of ins) springs[dim * m + inDir] += p.input_spring / ins.length;
150
+ output = { force: L, spring: o.spring || 0, input: loads[0].force };
151
+ }
134
152
  return {
135
- grid: size, origin, passive, fixed, loads,
153
+ grid: size, origin, passive, fixed, loads, ...(output ? { output, springs } : {}),
136
154
  material: p.material, thickness: p.thickness, volume: p.volume,
137
- filter: p.filter ?? p.cell * 1.5, penal: p.penal ?? 3, projection: p.projection ?? true, steps: p.steps ?? (p.stress ? 1000 : 300),
138
- ...(p.overhang ? { overhang: p.overhang } : {}), ...(p.stress ? { stress: p.stress } : {}),
155
+ // (a solid's default is more: the projection reaches full sharpness about step 200, and every 3D showcase part was
156
+ // still improving at 300: the bin's compliance fell 388 → 265 → 195 over steps 100, 200 and 300)
157
+ 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),
158
+ ...(p.overhang ? { overhang: p.overhang } : {}), ...(p.bridge ? { bridge: p.bridge } : {}), ...(p.stress ? { stress: p.stress } : {}),
139
159
  regions: { keep, avoid },
140
160
  };
141
161
  }
@@ -176,19 +196,24 @@ export function densityFilter({ nx, ny, nz = 1 }, radius) {
176
196
  * material under it: the cell itself and its neighbours along each side, in the layer below (3 cells in 2D, 5 in 3D,
177
197
  * so nothing overhangs by more than 45°). Smooth minimum and maximum keep it differentiable. apply gives the printable
178
198
  * densities; adjoint carries sensitivities back through it.
199
+ * With reach, a cell is also held up by a bridge: a run of up to reach solid cells along its own layer, each way along
200
+ * each axis, ending on a cell that something below holds up (the run's cells and that cell's support, all through the
201
+ * smooth minimum). That's what a printer spans: give reach as half the printer's bridge, in cells.
179
202
  * @param {{ nx: number, ny: number, nz?: number }} size @param {string} up the build direction: '+z', '-x', …
203
+ * @param {number} [reach] how many cells a bridge may run from a held cell (0: none)
180
204
  */
181
- export function overhangFilter({ nx, ny, nz = 1 }, up) {
205
+ export function overhangFilter({ nx, ny, nz = 1 }, up, reach = 0) {
182
206
  const n = nz > 1 ? [nx, ny, nz] : [nx, ny], dim = n.length, ax = 'xyz'.indexOf(up.at(-1)), sign = up[0] === '-' ? -1 : 1;
183
207
  if (ax < 0 || ax >= dim) throw new Error(`overhang: the build direction is ${dim === 3 ? '+x, -x, +y, -y, +z or -z' : '+x, -x, +y or -y'} (got ${up})`);
184
208
  const cells = n.reduce((p, c) => p * c, 1), stride = [1, nx, nx * ny];
185
- const P = 40, eps = 1e-4, xi0 = 0.5;
209
+ const P = 40, eps = 1e-4, xi0 = 0.5, halfRootEps = 0.5 * Math.sqrt(eps);
186
210
  // Layers in build order, and each cell's supports: the cell below it and that cell's neighbours along each other axis
187
- const layer = (e) => { const c = Math.floor(e / stride[ax]) % n[ax]; return sign > 0 ? c : n[ax] - 1 - c; };
188
- const order = Array.from({ length: cells }, (_, e) => e).sort((a, b) => layer(a) - layer(b));
189
- const supports = new Array(cells);
211
+ const layerOf = (e) => { const c = Math.floor(e / stride[ax]) % n[ax]; return sign > 0 ? c : n[ax] - 1 - c; };
212
+ const layers = Array.from({ length: n[ax] }, () => []);
213
+ for (let e = 0; e < cells; e++) layers[layerOf(e)].push(e);
214
+ const supports = new Array(cells), chains = new Array(cells);
190
215
  for (let e = 0; e < cells; e++) {
191
- if (layer(e) === 0) { supports[e] = null; continue; }
216
+ if (layerOf(e) === 0) { supports[e] = null; chains[e] = []; continue; }
192
217
  const below = e - sign * stride[ax], list = [below];
193
218
  for (let a = 0; a < dim; a++) if (a !== ax) {
194
219
  const c = Math.floor(below / stride[a]) % n[a];
@@ -196,38 +221,103 @@ export function overhangFilter({ nx, ny, nz = 1 }, up) {
196
221
  if (c < n[a] - 1) list.push(below + stride[a]);
197
222
  }
198
223
  supports[e] = Int32Array.from(list);
224
+ // Bridges: along each other axis, each way, the runs of 1 to reach cells (the nearest first)
225
+ const runs = [];
226
+ for (let a = 0; a < dim; a++) if (a !== ax) {
227
+ const c = Math.floor(e / stride[a]) % n[a];
228
+ for (const dir of [-1, 1]) for (let d = 1; d <= reach; d++) {
229
+ if (dir < 0 ? c - d < 0 : c + d >= n[a]) break;
230
+ runs.push(Int32Array.from({ length: d }, (_, k) => e + dir * (k + 1) * stride[a]));
231
+ }
232
+ }
233
+ chains[e] = runs;
199
234
  }
200
- const printed = new Float64Array(cells), powP = new Float64Array(cells), dSum = new Float64Array(cells), dX = new Float64Array(cells), sums = new Float64Array(cells);
235
+ // What's kept from apply for adjoint: each cell's printed density and its P-th power, the sums under the smooth
236
+ // maxima (base: the cells below; support: those and the bridges), the smooth minima's slopes, and each bridge's
237
+ // running minima
238
+ const printed = new Float64Array(cells), powP = new Float64Array(cells), base = new Float64Array(cells), baseSum = new Float64Array(cells);
239
+ const support = new Float64Array(cells), sums = new Float64Array(cells), dSum = new Float64Array(cells), dX = new Float64Array(cells);
240
+ const steps = chains.map((runs) => runs.map((r) => new Float64Array(r.length + 1)));
241
+ let lastX = null;
242
+ const smax = (sum, count) => (sum > 0 ? Math.pow(sum, 1 / (P + Math.log(count) / Math.log(xi0))) : 0);
243
+ const Q = (count) => P + Math.log(count) / Math.log(xi0);
244
+ const smin = (a, b) => { const d = a - b; return 0.5 * (a + b - Math.sqrt(d * d + eps)) + halfRootEps; };
245
+ const dsmin = (a, b) => { const d = a - b, root = Math.sqrt(d * d + eps); return [0.5 * (1 - d / root), 0.5 * (1 + d / root)]; }; // d/da, d/db
201
246
  return {
202
247
  apply(x, out) {
203
- for (const e of order) {
204
- const sup = supports[e];
205
- if (!sup) { printed[e] = x[e]; powP[e] = Math.pow(x[e], P); dX[e] = 1; continue; }
206
- let s = 0;
207
- for (const q of sup) s += powP[q]; // (each cell's printed^P, worked out once as it's printed)
208
- if (s < 1e-200) s = 0; // nothing worth the name below (and no denormals for the gradient to blow up on)
209
- const Q = P + Math.log(sup.length) / Math.log(xi0), smax = s > 0 ? Math.pow(s, 1 / Q) : 0;
210
- sums[e] = s;
211
- const d = x[e] - smax, root = Math.sqrt(d * d + eps);
212
- printed[e] = 0.5 * (x[e] + smax - root + Math.sqrt(eps)); powP[e] = Math.pow(printed[e], P);
213
- dX[e] = 0.5 * (1 - d / root); dSum[e] = 0.5 * (1 + d / root); // d printed / d x, d printed / d smax
248
+ lastX = x;
249
+ for (const layer of layers) {
250
+ // What the layer below holds up, cell by cell (a bridge rests on that, not on another bridge)
251
+ for (const e of layer) {
252
+ const sup = supports[e];
253
+ if (!sup) { printed[e] = x[e]; powP[e] = Math.pow(x[e], P); dX[e] = 1; base[e] = 1; continue; }
254
+ let s = 0;
255
+ for (const q of sup) s += powP[q];
256
+ if (s < 1e-200) s = 0; // nothing worth the name below (and no denormals for the gradient to blow up on)
257
+ baseSum[e] = s; base[e] = smax(s, sup.length);
258
+ }
259
+ for (const e of layer) {
260
+ const sup = supports[e];
261
+ if (!sup) continue;
262
+ // The cell's support: the cells below, and each bridge's running minimum (the run's cells, from the far end's
263
+ // base), all under one smooth maximum
264
+ let s = baseSum[e], count = sup.length;
265
+ chains[e].forEach((run, k) => {
266
+ const m = steps[e][k], far = run[run.length - 1];
267
+ let v = base[far];
268
+ m[0] = v;
269
+ for (let t = run.length - 1; t >= 0; t--) { v = smin(v, x[run[t]]); m[run.length - t] = v; }
270
+ s += Math.pow(v, P); count++;
271
+ });
272
+ 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)
273
+ sums[e] = s; support[e] = smax(s, count);
274
+ const d = x[e] - support[e], root = Math.sqrt(d * d + eps);
275
+ printed[e] = 0.5 * (x[e] + support[e] - root) + halfRootEps; powP[e] = Math.pow(printed[e], P);
276
+ dX[e] = 0.5 * (1 - d / root); dSum[e] = 0.5 * (1 + d / root); // d printed / d x, d printed / d support
277
+ }
214
278
  }
215
279
  out.set(printed);
216
280
  return out;
217
281
  },
218
- // Back from the last layer: each cell's sensitivity, plus what it passes on to the cells it supports
282
+ // Back from the last layer: each cell's sensitivity, plus what it passes on to the cells holding it up
219
283
  adjoint(g, out) {
220
- const lambda = Float64Array.from(g);
221
- for (let t = cells - 1; t >= 0; t--) {
222
- const e = order[t], sup = supports[e];
223
- if (!sup || !sums[e]) continue;
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) if (printed[q] > 0) lambda[q] += (common * powP[q]) / printed[q];
284
+ const lambda = Float64Array.from(g), dBase = new Float64Array(cells);
285
+ out.fill(0);
286
+ for (let L = layers.length - 1; L >= 0; L--) {
287
+ const layer = layers[L];
288
+ dBase.fill(0);
289
+ for (const e of layer) {
290
+ const sup = supports[e];
291
+ if (!sup) { out[e] += lambda[e] * dX[e]; continue; }
292
+ out[e] += lambda[e] * dX[e];
293
+ if (!sums[e]) continue;
294
+ const count = sup.length + chains[e].length, common = lambda[e] * dSum[e] * (1 / Q(count)) * Math.pow(sums[e], 1 / Q(count) - 1) * P;
295
+ for (const q of sup) if (printed[q] > 0) lambda[q] += (common * powP[q]) / printed[q];
296
+ chains[e].forEach((run, k) => {
297
+ const m = steps[e][k], v = m[run.length];
298
+ if (!(v > 0)) return;
299
+ let gv = common * Math.pow(v, P - 1);
300
+ // Back along the run: each step was smin(the running minimum so far, the run cell's density)
301
+ for (let t = 0; t < run.length; t++) {
302
+ const [da, db] = dsmin(m[run.length - t - 1], x_of(run[t]));
303
+ out[run[t]] += gv * db; gv *= da;
304
+ }
305
+ dBase[run[run.length - 1]] += gv;
306
+ });
307
+ }
308
+ // What the bridges asked of this layer's bases: on to the cells below
309
+ for (const e of layer) {
310
+ const sup = supports[e];
311
+ if (!sup || !dBase[e] || !baseSum[e]) continue;
312
+ const common = dBase[e] * (1 / Q(sup.length)) * Math.pow(baseSum[e], 1 / Q(sup.length) - 1) * P;
313
+ for (const q of sup) if (printed[q] > 0) lambda[q] += (common * powP[q]) / printed[q];
314
+ }
226
315
  }
227
- for (let e = 0; e < cells; e++) out[e] = lambda[e] * dX[e];
228
316
  return out;
229
317
  },
230
318
  };
319
+ // (the densities apply was last given: kept for adjoint's bridges)
320
+ function x_of(e) { return lastX[e]; }
231
321
  }
232
322
 
233
323
  /**
@@ -240,41 +330,58 @@ export function overhangFilter({ nx, ny, nz = 1 }, up) {
240
330
  * @param {{ method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend }} [options]
241
331
  */
242
332
  const SUPPORT = 10; // what a kept cell nothing holds up costs, in the part's compliances, over the kept cells
333
+ 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
243
334
 
244
335
  export function model(spec, { method, backend = jsBackend } = {}) {
245
336
  const g = makeGrid(spec.grid), dim = g.dim, cells = g.cells, m = g.cellDofs, ke = cellStiffness(spec.material.nu, dim);
246
- const { passive, penal } = spec, E = spec.material.E, Emin = E * 1e-9, eta = 0.5, size = dim === 3 ? g.h : spec.thickness;
337
+ const { passive, penal } = spec, E = spec.material.E, Emin = E * 1e-9, ETA = 0.5, size = dim === 3 ? g.h : spec.thickness;
247
338
  const solver = method || (dim === 3 ? 'mg' : 'direct'), tol = solver === 'direct' ? undefined : 1e-6;
248
- const filter = densityFilter(spec.grid, spec.filter / spec.grid.h), print = spec.overhang ? overhangFilter(spec.grid, spec.overhang) : null;
339
+ 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;
249
340
  const tilde = new Float64Array(cells), made = new Float64Array(cells), phys = new Float64Array(cells), scale = new Float64Array(cells), back = new Float64Array(cells);
250
341
  const fixedValue = (p) => (p === 1 ? 1 : 0);
251
342
  // Heaviside projection about eta: steeper as beta grows, so densities are pushed to 0 or 1 (Wang, Lazarov, Sigmund 2011)
252
- const denominator = (beta) => Math.tanh(beta * eta) + Math.tanh(beta * (1 - eta));
253
- const project = (t, beta) => (spec.projection ? (Math.tanh(beta * eta) + Math.tanh(beta * (t - eta))) / denominator(beta) : t);
254
- const slope = (t, beta) => (spec.projection ? (beta * (1 - Math.tanh(beta * (t - eta)) ** 2)) / denominator(beta) : 1);
343
+ const denominator = (beta, eta = ETA) => Math.tanh(beta * eta) + Math.tanh(beta * (1 - eta));
344
+ // (eta: the threshold; 0.5 for the design as made, less for a dilated copy and more for an eroded one)
345
+ const project = (t, beta, eta = ETA) => (spec.projection ? (Math.tanh(beta * eta) + Math.tanh(beta * (t - eta))) / denominator(beta, eta) : t);
346
+ const slope = (t, beta, eta = ETA) => (spec.projection ? (beta * (1 - Math.tanh(beta * (t - eta)) ** 2)) / denominator(beta, eta) : 1);
255
347
  // Kept and avoided cells are set before the overhang filter as well as after it: a kept cell holds up what's above
256
348
  // 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
349
  // which is what the kept regions' support cost (below) is measured on. The part is analysed with every kept cell solid.
258
- const physical = (x, beta) => {
350
+ const physical = (x, beta, eta = ETA) => {
259
351
  filter.apply(x, tilde);
260
352
  for (let e = 0; e < cells; e++) if (passive[e]) tilde[e] = fixedValue(passive[e]);
261
353
  if (print) print.apply(tilde, made); else made.set(tilde);
262
- for (let e = 0; e < cells; e++) phys[e] = passive[e] ? fixedValue(passive[e]) : project(made[e], beta);
354
+ for (let e = 0; e < cells; e++) phys[e] = passive[e] ? fixedValue(passive[e]) : project(made[e], beta, eta);
263
355
  return phys;
264
356
  };
357
+ // The material's gradient alone (no solve): what a copy of the design at a threshold is worth per design density
358
+ const volumeGradient = (x, beta, eta = ETA) => {
359
+ physical(x, beta, eta);
360
+ const dv = new Float64Array(cells);
361
+ for (let e = 0; e < cells; e++) dv[e] = passive[e] ? 0 : slope(made[e], beta, eta);
362
+ toDesign(dv);
363
+ return dv;
364
+ };
265
365
  // Kept regions must print. With a build direction, how much of the kept material nothing holds up (0 to 1), and its
266
366
  // cost: a kept cell nothing holds up costs SUPPORT times the part's compliance, shared over the kept cells, so the
267
367
  // optimiser puts material in under it. The cost's gradient goes back through the overhang filter to the cells that
268
368
  // would hold it up.
269
369
  const keptCells = Int32Array.from(Array.from(passive).flatMap((p, e) => (p === 1 ? [e] : [])));
270
370
  const unsupported = (beta) => (print && keptCells.length ? keptCells.reduce((t, e) => t + 1 - project(made[e], beta), 0) / keptCells.length : 0);
371
+ // Back through the overhang filter and the density filter to the design densities (kept and avoided cells don't
372
+ // change: their own densities are fixed). Right after the physical() it belongs to.
373
+ const toDesign = (d) => {
374
+ if (print) { print.adjoint(d, back); d.set(back); }
375
+ for (let e = 0; e < cells; e++) if (passive[e]) d[e] = 0;
376
+ filter.adjoint(d, back); d.set(back);
377
+ };
271
378
  let last = null;
272
379
  // Each step solves only the load cases it optimises for (weight above 0); every case is solved when all is set
273
- const evaluate = (x, beta, { all = false, multipliers } = {}) => {
274
- physical(x, beta);
380
+ const evaluate = (x, beta, { all = false, multipliers, eta = ETA } = {}) => {
381
+ physical(x, beta, eta);
275
382
  for (let e = 0; e < cells; e++) scale[e] = size * (Emin + Math.pow(phys[e], penal) * (E - Emin));
276
383
  const active = spec.loads.map((l, c) => (all || l.weight > 0 ? c : -1)).filter((c) => c >= 0);
277
- 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;
384
+ 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;
278
385
  const u = spec.loads.map((_, c) => (active.includes(c) ? solved[active.indexOf(c)] : last?.[c] || null));
279
386
  last = u;
280
387
  // Compliance, and its gradient with respect to each cell's physical density: −p ρ^(p−1) (E − Emin) size · uₑᵀ kₑ uₑ
@@ -295,15 +402,26 @@ export function model(spec, { method, backend = jsBackend } = {}) {
295
402
  // Back through the projection, the overhang filter and the density filter to the design densities; kept and
296
403
  // avoided cells don't change
297
404
  const lack = unsupported(beta);
298
- for (let e = 0; e < cells; e++) { const s = passive[e] ? 0 : slope(made[e], beta); dc[e] *= s; dv[e] = s; }
405
+ for (let e = 0; e < cells; e++) { const s = passive[e] ? 0 : slope(made[e], beta, eta); dc[e] *= s; dv[e] = s; }
299
406
  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
- };
305
407
  toDesign(dc); toDesign(dv);
306
408
  const stress = Ss ? stressLimits(u, active, run.again, multipliers || { lam: active.map(() => new Float64Array(cells * Ss.length)), mu: 1 }) : null;
409
+ // A mechanism: how far the output moves along its direction under the input (travel), and its gradient: with the
410
+ // adjoint λ from K λ = L (the output's direction), d travel / dρ = −λₑᵀ (dkₑ/dρ) uₑ (Sigmund 1997)
411
+ let mechanism = null;
412
+ if (spec.output && u[0]) {
413
+ const L = spec.output.force, u0 = u[0], travel = jsBackend.dot(L, u0), [lam] = run.again([L]), d = new Float64Array(cells);
414
+ let input = 0; for (let i = 0; i < u0.length; i++) if (spec.output.input[i]) input += spec.output.input[i] * u0[i];
415
+ input /= Math.hypot(...spec.loads[0].force.filter((v) => v)) || 1; // along the input, per unit of it: the input's travel
416
+ for (let e = 0; e < cells; e++) {
417
+ let t = 0;
418
+ const o = e * m;
419
+ 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; }
420
+ d[e] = passive[e] ? 0 : -penal * Math.pow(phys[e], penal - 1) * (E - Emin) * size * t * slope(made[e], beta, eta);
421
+ }
422
+ toDesign(d);
423
+ mechanism = { travel, input, d };
424
+ }
307
425
  const cases = spec.loads.map((l, c) => {
308
426
  if (!u[c]) return { name: l.name, compliance: NaN, deflection: NaN, stiffness: NaN };
309
427
  const ci = jsBackend.dot(l.force, u[c]);
@@ -313,7 +431,7 @@ export function model(spec, { method, backend = jsBackend } = {}) {
313
431
  return { name: l.name, compliance: ci, deflection, stiffness: deflection ? l.size / deflection : Infinity };
314
432
  });
315
433
  if (stress) { for (let e = 0; e < cells; e++) stress.d[e] *= passive[e] ? 0 : slope(made[e], beta); toDesign(stress.d); }
316
- return { compliance, dc, dv, u, cases, unsupported: lack, ...(stress ? { stress } : {}) };
434
+ return { compliance, dc, dv, u, cases, unsupported: lack, ...(stress ? { stress } : {}), ...(mechanism ? { mechanism } : {}) };
317
435
  };
318
436
  // Stress limits on every cell (Senhora, Giraldo-Londoño, Menezes, Paulino 2020): each cell's von Mises stress at its
319
437
  // centre, as if solid, over the limit, less 1, times the cell's density, so an empty cell's limit vanishes. They're
@@ -357,7 +475,7 @@ export function model(spec, { method, backend = jsBackend } = {}) {
357
475
  });
358
476
  return { J, d, h, peak };
359
477
  };
360
- return { physical, evaluate, cells, passive, limits: Ss ? cells * Ss.length : 0 };
478
+ return { physical, evaluate, volumeGradient, cells, passive, limits: Ss ? cells * Ss.length : 0 };
361
479
  }
362
480
 
363
481
  /**
@@ -524,7 +642,7 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
524
642
  const inSpace = passive.reduce((s, p) => s + (p !== -2 ? 1 : 0), 0), kept = passive.reduce((s, p) => s + (p === 1 ? 1 : 0), 0);
525
643
  const free = passive.reduce((s, p) => s + (p === 0 ? 1 : 0), 0);
526
644
  // A stress limit asks for the lightest layout that keeps to it; a volume, for the stiffest that fills it
527
- const lightest = spec.stress > 0;
645
+ const lightest = spec.stress > 0, mechanism = !!spec.output;
528
646
  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');
529
647
  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})`);
530
648
  const target = lightest ? 0 : spec.volume * inSpace;
@@ -538,14 +656,19 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
538
656
  // The lightest layout: the method of moving asymptotes on the material used plus the stress limits' augmented
539
657
  // Lagrangian term, its multipliers raised every INNER steps (λ += μ h) and its penalty grown (μ × 1.1, at most 10⁴)
540
658
  const INNER = 5, freeCells = Int32Array.from(Array.from(passive).flatMap((p, e) => (p ? [] : [e]))), n = freeCells.length;
541
- const mmaStep = lightest ? mma({ n, m: 0, xmin: new Float64Array(n), xmax: new Float64Array(n).fill(1) }) : null;
659
+ // A mechanism: the method of moving asymptotes maximising the output's travel (minimising −travel) under the volume
660
+ 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;
542
661
  const multipliers = lightest ? { lam: spec.loads.filter((l) => l.weight > 0).map(() => new Float64Array(m.limits)), mu: 10 } : undefined;
543
662
  const xf = new Float64Array(n), pick = (d) => Float64Array.from(freeCells, (e) => d[e]);
544
- let step = 0, change = 1, converged = false, beta = 1, sinceBeta = 0, peak = null;
663
+ let step = 0, change = 1, converged = false, beta = 1, sinceBeta = 0, peak = null, targetD = target;
545
664
  const tried = new Float64Array(cells); // the last design the bisection analysed, and how much it filled
546
665
  while (step < spec.steps) {
547
666
  step++; sinceBeta++;
548
- const { compliance, dc, dv, stress } = m.evaluate(x, beta, { multipliers });
667
+ // A mechanism is optimised robustly (after Wang, Lazarov and Sigmund 2011): its travel on an eroded copy of the
668
+ // design (threshold ERODE), its volume on a dilated one (DILATE), the design as made between them. A hinge that
669
+ // survives erosion has real width, so no hinge is a point. (The design as made is stiffer than the eroded copy
670
+ // it's optimised on, by a hinge width's worth; a worst-of-three objective would close that gap, and is to come.)
671
+ const { compliance, dc, dv, stress, mechanism: mech } = m.evaluate(x, beta, { multipliers, ...(mechanism ? { eta: ERODE } : {}) });
549
672
  // A sharper projection magnifies each change, so the move limit shrinks with it (else the design flickers)
550
673
  const limit = move * Math.min(1, 2 / beta);
551
674
  if (lightest) {
@@ -562,6 +685,16 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
562
685
  multipliers.lam.forEach((l, k) => { for (let j = 0; j < l.length; j++) l[j] += multipliers.mu * stress.h[k][j]; });
563
686
  multipliers.mu = Math.min(1.1 * multipliers.mu, 1e4);
564
687
  }
688
+ } else if (mechanism) {
689
+ history.push(mech.travel);
690
+ // The dilated copy's material, kept to a target that puts the design as made at the volume asked for (the
691
+ // target follows the ratio of the two, re-measured every DILATE_EVERY steps)
692
+ const usedD = m.physical(x, beta, DILATE).reduce((s, v, e) => s + (passive[e] !== -2 ? v : 0), 0), dvD = m.volumeGradient(x, beta, DILATE);
693
+ 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); }
694
+ xf.set(pick(x));
695
+ mmaStep(xf, -mech.travel, pick(mech.d).map((v) => -v), [usedD / targetD - 1], [pick(dvD).map((v) => v / targetD)], limit); // (minimising −travel)
696
+ xnew.set(x);
697
+ freeCells.forEach((e, k) => { xnew[e] = xf[k]; });
565
698
  } else {
566
699
  history.push(compliance);
567
700
  // Optimality criteria: scale each cell by √(−dc/dv/λ), within the move limit, finding λ by bisection so the
@@ -585,7 +718,7 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
585
718
  change = 0;
586
719
  for (let e = 0; e < cells; e++) change = Math.max(change, Math.abs(xnew[e] - x[e]));
587
720
  x.set(xnew);
588
- onStep?.({ step, steps: spec.steps, compliance, change, beta, density: m.physical(x, beta), ...(lightest ? { stress: peak, volume: history.at(-1) } : {}) });
721
+ onStep?.({ step, steps: spec.steps, compliance, change, beta, density: m.physical(x, beta), ...(lightest ? { stress: peak, volume: history.at(-1) } : {}), ...(mechanism ? { travel: mech.travel } : {}) });
589
722
  if (lightest) {
590
723
  // Sharper every 25 rounds of the multipliers
591
724
  if (beta < betaMax && sinceBeta >= 25 * INNER) { beta *= 2; sinceBeta = 0; }
@@ -594,14 +727,16 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
594
727
  // Sharpen: double the projection's steepness when the design settles (or every 50 steps), until it's at its sharpest
595
728
  if (beta < betaMax && (change < tol || sinceBeta >= 50)) { beta *= 2; sinceBeta = 0; continue; }
596
729
  // Done when nothing moves, or at full sharpness the compliance has stopped improving (within 0.1% over 10 steps)
597
- const settled = spec.projection && history.length > 10 && beta >= betaMax && sinceBeta > 10 && Math.abs(history.at(-11) - compliance) <= 1e-3 * compliance;
730
+ const latest = mechanism ? mech.travel : compliance;
731
+ const settled = spec.projection && history.length > 10 && beta >= betaMax && sinceBeta > 10 && Math.abs(history.at(-11) - latest) <= 1e-3 * Math.abs(latest);
598
732
  if (beta >= betaMax && (change < tol || settled)) { converged = true; break; }
599
733
  }
600
734
  // The final design, analysed as it is
601
735
  const final = m.evaluate(x, beta, { all: true }), phys = Float64Array.from(m.physical(x, beta));
602
736
  // (the final physical call is after evaluate's, so unsupported comes from the evaluation of this design)
603
737
  return {
604
- density: phys, compliance: final.compliance, cases: final.cases, unsupported: final.unsupported, ...(final.stress ? { stress: { peak: final.stress.peak, limit: spec.stress } } : {}),
738
+ density: phys, compliance: final.compliance, cases: final.cases, unsupported: final.unsupported,
739
+ ...(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 } } : {}),
605
740
  volume: phys.reduce((s, v, e) => s + (passive[e] !== -2 ? v : 0), 0) / inSpace, steps: step, converged, history, seconds: (Date.now() - started) / 1000,
606
741
  };
607
742
  }
@@ -809,9 +944,11 @@ function simplify(loop, tolerance) {
809
944
  * @param {{ nx: number, ny: number, nz: number, h: number }} size @param {ArrayLike<number>} density @param {number[]} origin
810
945
  * 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
811
946
  * base on the bed) keeps that face flat, and the walls rising from it don't lean out.
812
- * @param {{ smooth?: number, iso?: number, overhang?: { up: string, angle: number } }} [options] iso: the density the
813
- * surface is drawn at (0.5). overhang: the build direction ('+z') and the printer's overhang limit (degrees from
814
- * vertical): faces smoothing left past it are tipped back to it.
947
+ * @param {{ smooth?: number, iso?: number, overhang?: { up: string, angle: number, tip?: boolean } }} [options] iso: the
948
+ * density the surface is drawn at (0.5). overhang: the build direction ('+z') and the printer's overhang limit (degrees
949
+ * from vertical): downward bumps left by smoothing are filled, so nothing starts in mid-air when sliced; with tip, faces
950
+ * past the limit are also tipped back to it (off by default: tipping corners leaves dips that slice as islands, and the
951
+ * layers step out no further for it).
815
952
  * @returns {{ vertices: number[][], faces: number[][] }}
816
953
  */
817
954
  export function surface({ nx, ny, nz, h }, density, origin = [0, 0, 0], { smooth = 4, iso = 0.5, overhang } = {}) {
@@ -881,14 +1018,30 @@ export function surface({ nx, ny, nz, h }, density, origin = [0, 0, 0], { smooth
881
1018
  }
882
1019
  // Printable: faces past the limit tipped back, and tips lifted, in turn until neither finds any (each can make work for
883
1020
  // 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; }
1021
+ if (overhang) settle({ vertices: pts, faces }, { overhang, lo, hi, held });
885
1022
  return { vertices: pts, faces };
886
1023
  }
887
1024
 
1025
+ /**
1026
+ * A surface made printable in place: faces past the overhang limit tipped back to it, and downward bumps filled to
1027
+ * where they join the surface round them, in turn until neither finds any. surface() does this as it draws; call it
1028
+ * again after moving a mesh's corners (raising an island off the slicer's view, say).
1029
+ * @param {{ vertices: number[][], faces: number[][] }} mesh edited in place
1030
+ * @param {{ overhang: { up: string, angle: number }, lo: number[], hi: number[], held?: boolean[] }} o lo, hi: the
1031
+ * grid's corners (corners on its faces are pinned); held: corners that must not move (default: those on the faces)
1032
+ * @returns {number} how many rounds it took
1033
+ */
1034
+ export function settle({ vertices: pts, faces }, { overhang, lo, hi, held }) {
1035
+ const near = 1e-6, pinned = held ?? pts.map((p) => p.some((x, q) => x < lo[q] + near || x > hi[q] - near));
1036
+ let round = 0;
1037
+ 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; }
1038
+ return round;
1039
+ }
1040
+
888
1041
  // Faces past the overhang limit, tipped back to it. Optimised in cubes, a printable slope is a staircase of 45°, and
889
1042
  // smoothing leaves small faces either side of 45°. Each face facing down more steeply than the limit is turned about
890
1043
  // its centre, moving its corners along the build direction only, until it's a little inside the limit: about as much
891
- // material is added as taken away. A corner shared by several such faces moves by their average; it's repeated until
1044
+ // 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
892
1045
  // none are left. Flat faces (a bridge) and faces held on the grid's sides stay as they are.
893
1046
  function steepen(pts, faces, held, { up, angle }, lo, hi, passes = 200) {
894
1047
  const q = 'xyz'.indexOf(up[1]), s = up[0] === '-' ? -1 : 1, [a, b] = [0, 1, 2].filter((x) => x !== q);
@@ -917,6 +1070,36 @@ function steepen(pts, faces, held, { up, angle }, lo, hi, passes = 200) {
917
1070
  return true;
918
1071
  }
919
1072
 
1073
+ // Downward bumps filled: on the underside, a dip whose every way out leads up (along the build direction) is a bump the
1074
+ // printer meets from below: its lowest layer has nothing under it, an island. Each such basin is raised to the height
1075
+ // where it joins the surface round it (a flood from the bed, in order of height, as the depressions of a map are filled
1076
+ // to their spill points), which leaves a small flat underside there, bridged. The bed's corners, those held on the
1077
+ // grid's sides, and corners facing up are the sources and stay.
1078
+ function fill(pts, faces, held, { up }, lo) {
1079
+ const q = 'xyz'.indexOf(up[1]), s = up[0] === '-' ? -1 : 1, near = pts.map(() => new Set()), facing = new Float64Array(pts.length);
1080
+ for (const f of faces) {
1081
+ for (let i = 0; i < 3; i++) { near[f[i]].add(f[(i + 1) % 3]); near[f[i]].add(f[(i + 2) % 3]); }
1082
+ 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]);
1083
+ 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];
1084
+ for (const m of f) facing[m] += s * nq;
1085
+ }
1086
+ const height = (v) => s * v[q], level = new Float64Array(pts.length).fill(Infinity), done = new Uint8Array(pts.length);
1087
+ // A heap of corners by their level, lowest first
1088
+ 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; } };
1089
+ 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; };
1090
+ const bed = s > 0 ? lo[q] : null;
1091
+ 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]));
1092
+ let moved = 0;
1093
+ while (heap.length) {
1094
+ const [l, n] = pop();
1095
+ if (done[n]) continue;
1096
+ done[n] = 1;
1097
+ if (height(pts[n]) < l - 1e-9) { pts[n][q] = s * l; moved++; } // in a basin: raised to its spill level
1098
+ for (const m of near[n]) if (!done[m]) { const lm = Math.max(height(pts[m]), l); if (lm < level[m]) push(m, lm); }
1099
+ }
1100
+ return moved > 0;
1101
+ }
1102
+
920
1103
  // Tips lifted: a corner lower than every corner round it (along the build direction), on faces facing down, starts in
921
1104
  // mid-air, where a printer has nothing to lay it on. Smoothing leaves these under edges and bridges. Each is raised level
922
1105
  // with its lowest neighbour, which leaves a small flat underside (bridged), until none are left. The bed's corners and
@@ -943,6 +1126,79 @@ function lift(pts, faces, held, { up }, lo, passes = 50) {
943
1126
  return true;
944
1127
  }
945
1128
 
1129
+ /**
1130
+ * A result's densities on a finer grid, so it can be cleaned and drawn at nearer the printer's resolution: each fine
1131
+ * cell takes the density interpolated (trilinear, or bilinear in 2D) between the coarse cells' centres round it, so
1132
+ * the surface drawn through it lies where the coarse one would, with the steps between coarse cells resolved. Kept
1133
+ * cells become kept blocks.
1134
+ * @param {{ nx: number, ny: number, nz?: number, h: number }} size @param {ArrayLike<number>} density
1135
+ * @param {number} factor fine cells per coarse cell along each axis (a whole number, 1 for no change)
1136
+ * @param {{ keep?: ArrayLike<number>, method?: 'linear' | 'nearest' }} [options] keep: cells that always stay, carried to
1137
+ * the fine grid; method: interpolated between coarse centres (linear, default), or each fine cell its coarse cell's
1138
+ * value (nearest: the stairs kept exactly, for the smoother to round); smooth: box-blur passes over the fine cells (0)
1139
+ * @returns {{ grid: { nx: number, ny: number, nz?: number, h: number }, density: Float64Array, keep?: Uint8Array }}
1140
+ */
1141
+ export function refine({ nx, ny, nz = 1, h }, density, factor, { keep, method = 'linear', smooth = 0 } = {}) {
1142
+ 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];
1143
+ 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))];
1144
+ for (let k = 0; k < m[2]; k++) for (let j = 0; j < m[1]; j++) for (let i = 0; i < m[0]; i++) {
1145
+ // The fine cell's centre in coarse-cell units, measured from the coarse centres
1146
+ 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;
1147
+ const i0 = Math.floor(x), j0 = Math.floor(y), k0 = Math.floor(z), tx = x - i0, ty = y - j0, tz = z - k0;
1148
+ let v = 0;
1149
+ 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
1150
+ 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);
1151
+ const e = (k * m[1] + j) * m[0] + i;
1152
+ out[e] = v;
1153
+ if (fine) fine[e] = keep[(Math.floor(k / (dim === 3 ? f : 1)) * ny + Math.floor(j / f)) * nx + Math.floor(i / f)] ? 1 : 0;
1154
+ }
1155
+ // Smoothed a little (a box over the neighbouring fine cells, smooth passes): the interpolated stairs between coarse
1156
+ // cells bulge under the overhang line at each step, and the blur takes the bulges down
1157
+ let v = out;
1158
+ for (let pass = 0; pass < smooth; pass++) {
1159
+ const next = new Float64Array(cells);
1160
+ for (let k = 0; k < m[2]; k++) for (let j = 0; j < m[1]; j++) for (let i = 0; i < m[0]; i++) {
1161
+ let sum = 0, count = 0;
1162
+ 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++; } }
1163
+ next[(k * m[1] + j) * m[0] + i] = sum / count;
1164
+ }
1165
+ v = next;
1166
+ }
1167
+ 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 } : {}) };
1168
+ }
1169
+
1170
+ /**
1171
+ * Spikes taken off a result's underside before it's drawn: a solid cell with nothing under it (along the build
1172
+ * direction) and too few solid neighbours in its own layer is a hanging point, the start of a jagged edge or an
1173
+ * island when sliced; it is emptied, and the layer above is looked at again, until none are left. On a fine grid
1174
+ * (refine) this is the printer's own view of the surface. Kept cells stay.
1175
+ * @param {{ nx: number, ny: number, nz?: number }} size @param {ArrayLike<number>} density
1176
+ * @param {{ up: string, iso?: number, keep?: ArrayLike<number>, thin?: number }} options thin: a hanging cell with
1177
+ * fewer solid neighbours than this in its layer is a spike (default 3 of 8 in 3D, 1 of 2 in 2D)
1178
+ * @returns {{ density: Float64Array, emptied: number }}
1179
+ */
1180
+ export function despike({ nx, ny, nz = 1 }, density, { up, iso = 0.5, keep, thin }) {
1181
+ 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);
1182
+ 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];
1183
+ const solid = (e) => out[e] >= iso || (keep && keep[e]);
1184
+ let emptied = 0, changed = true;
1185
+ for (let pass = 0; pass < 50 && changed; pass++) {
1186
+ changed = false;
1187
+ for (let e = 0; e < out.length; e++) {
1188
+ if (!(out[e] >= iso) || (keep && keep[e])) continue;
1189
+ const c = coord(e, ax);
1190
+ if ((sign > 0 && c === 0) || (sign < 0 && c === n[ax] - 1)) continue; // on the bed
1191
+ if (solid(e - sign * stride[ax])) continue; // something straight under it
1192
+ let around = 0, slots = 0;
1193
+ 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); }));
1194
+ if (offs.length === 1) for (const d of offs[0]) { if (d) { slots++; if (solid(e + d)) around++; } }
1195
+ else for (const d0 of offs[0]) for (const d1 of offs[1]) { if (d0 || d1) { slots++; if (solid(e + d0 + d1)) around++; } }
1196
+ if (around < Math.min(least, slots)) { out[e] = 0; emptied++; changed = true; }
1197
+ }
1198
+ }
1199
+ return { density: out, emptied };
1200
+ }
1201
+
946
1202
  /**
947
1203
  * 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
1204
  * something holds it up: a cell kept in the layer below, straight under it or diagonally next to that (so nothing