@rulecad/topopt 0.2.7 → 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 +37 -1
  2. package/package.json +1 -1
  3. package/topopt.d.mts +120 -12
  4. package/topopt.mjs +216 -31
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.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,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)
@@ -133,10 +136,25 @@ export function discretise(p) {
133
136
  const { size, moment } = resultant(mine);
134
137
  return { name, force: f, weight: p.cases?.[name] ?? 1, size, ...(moment ? { moment } : {}) };
135
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
+ }
136
152
  return {
137
- grid: size, origin, passive, fixed, loads,
153
+ grid: size, origin, passive, fixed, loads, ...(output ? { output, springs } : {}),
138
154
  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),
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),
140
158
  ...(p.overhang ? { overhang: p.overhang } : {}), ...(p.bridge ? { bridge: p.bridge } : {}), ...(p.stress ? { stress: p.stress } : {}),
141
159
  regions: { keep, avoid },
142
160
  };
@@ -251,6 +269,7 @@ export function overhangFilter({ nx, ny, nz = 1 }, up, reach = 0) {
251
269
  for (let t = run.length - 1; t >= 0; t--) { v = smin(v, x[run[t]]); m[run.length - t] = v; }
252
270
  s += Math.pow(v, P); count++;
253
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)
254
273
  sums[e] = s; support[e] = smax(s, count);
255
274
  const d = x[e] - support[e], root = Math.sqrt(d * d + eps);
256
275
  printed[e] = 0.5 * (x[e] + support[e] - root) + halfRootEps; powP[e] = Math.pow(printed[e], P);
@@ -311,41 +330,58 @@ export function overhangFilter({ nx, ny, nz = 1 }, up, reach = 0) {
311
330
  * @param {{ method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend }} [options]
312
331
  */
313
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
314
334
 
315
335
  export function model(spec, { method, backend = jsBackend } = {}) {
316
336
  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;
337
+ const { passive, penal } = spec, E = spec.material.E, Emin = E * 1e-9, ETA = 0.5, size = dim === 3 ? g.h : spec.thickness;
318
338
  const solver = method || (dim === 3 ? 'mg' : 'direct'), tol = solver === 'direct' ? undefined : 1e-6;
319
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;
320
340
  const tilde = new Float64Array(cells), made = new Float64Array(cells), phys = new Float64Array(cells), scale = new Float64Array(cells), back = new Float64Array(cells);
321
341
  const fixedValue = (p) => (p === 1 ? 1 : 0);
322
342
  // 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);
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);
326
347
  // Kept and avoided cells are set before the overhang filter as well as after it: a kept cell holds up what's above
327
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,
328
349
  // 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) => {
350
+ const physical = (x, beta, eta = ETA) => {
330
351
  filter.apply(x, tilde);
331
352
  for (let e = 0; e < cells; e++) if (passive[e]) tilde[e] = fixedValue(passive[e]);
332
353
  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);
354
+ for (let e = 0; e < cells; e++) phys[e] = passive[e] ? fixedValue(passive[e]) : project(made[e], beta, eta);
334
355
  return phys;
335
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
+ };
336
365
  // Kept regions must print. With a build direction, how much of the kept material nothing holds up (0 to 1), and its
337
366
  // cost: a kept cell nothing holds up costs SUPPORT times the part's compliance, shared over the kept cells, so the
338
367
  // optimiser puts material in under it. The cost's gradient goes back through the overhang filter to the cells that
339
368
  // would hold it up.
340
369
  const keptCells = Int32Array.from(Array.from(passive).flatMap((p, e) => (p === 1 ? [e] : [])));
341
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
+ };
342
378
  let last = null;
343
379
  // 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);
380
+ const evaluate = (x, beta, { all = false, multipliers, eta = ETA } = {}) => {
381
+ physical(x, beta, eta);
346
382
  for (let e = 0; e < cells; e++) scale[e] = size * (Emin + Math.pow(phys[e], penal) * (E - Emin));
347
383
  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;
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;
349
385
  const u = spec.loads.map((_, c) => (active.includes(c) ? solved[active.indexOf(c)] : last?.[c] || null));
350
386
  last = u;
351
387
  // Compliance, and its gradient with respect to each cell's physical density: −p ρ^(p−1) (E − Emin) size · uₑᵀ kₑ uₑ
@@ -366,15 +402,26 @@ export function model(spec, { method, backend = jsBackend } = {}) {
366
402
  // Back through the projection, the overhang filter and the density filter to the design densities; kept and
367
403
  // avoided cells don't change
368
404
  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; }
405
+ for (let e = 0; e < cells; e++) { const s = passive[e] ? 0 : slope(made[e], beta, eta); dc[e] *= s; dv[e] = s; }
370
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); }
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
407
  toDesign(dc); toDesign(dv);
377
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
+ }
378
425
  const cases = spec.loads.map((l, c) => {
379
426
  if (!u[c]) return { name: l.name, compliance: NaN, deflection: NaN, stiffness: NaN };
380
427
  const ci = jsBackend.dot(l.force, u[c]);
@@ -384,7 +431,7 @@ export function model(spec, { method, backend = jsBackend } = {}) {
384
431
  return { name: l.name, compliance: ci, deflection, stiffness: deflection ? l.size / deflection : Infinity };
385
432
  });
386
433
  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 } : {}) };
434
+ return { compliance, dc, dv, u, cases, unsupported: lack, ...(stress ? { stress } : {}), ...(mechanism ? { mechanism } : {}) };
388
435
  };
389
436
  // Stress limits on every cell (Senhora, Giraldo-Londoño, Menezes, Paulino 2020): each cell's von Mises stress at its
390
437
  // 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 +475,7 @@ export function model(spec, { method, backend = jsBackend } = {}) {
428
475
  });
429
476
  return { J, d, h, peak };
430
477
  };
431
- return { physical, evaluate, cells, passive, limits: Ss ? cells * Ss.length : 0 };
478
+ return { physical, evaluate, volumeGradient, cells, passive, limits: Ss ? cells * Ss.length : 0 };
432
479
  }
433
480
 
434
481
  /**
@@ -595,7 +642,7 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
595
642
  const inSpace = passive.reduce((s, p) => s + (p !== -2 ? 1 : 0), 0), kept = passive.reduce((s, p) => s + (p === 1 ? 1 : 0), 0);
596
643
  const free = passive.reduce((s, p) => s + (p === 0 ? 1 : 0), 0);
597
644
  // 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;
645
+ const lightest = spec.stress > 0, mechanism = !!spec.output;
599
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');
600
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})`);
601
648
  const target = lightest ? 0 : spec.volume * inSpace;
@@ -609,14 +656,19 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
609
656
  // The lightest layout: the method of moving asymptotes on the material used plus the stress limits' augmented
610
657
  // Lagrangian term, its multipliers raised every INNER steps (λ += μ h) and its penalty grown (μ × 1.1, at most 10⁴)
611
658
  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;
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;
613
661
  const multipliers = lightest ? { lam: spec.loads.filter((l) => l.weight > 0).map(() => new Float64Array(m.limits)), mu: 10 } : undefined;
614
662
  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;
663
+ let step = 0, change = 1, converged = false, beta = 1, sinceBeta = 0, peak = null, targetD = target;
616
664
  const tried = new Float64Array(cells); // the last design the bisection analysed, and how much it filled
617
665
  while (step < spec.steps) {
618
666
  step++; sinceBeta++;
619
- 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 } : {}) });
620
672
  // A sharper projection magnifies each change, so the move limit shrinks with it (else the design flickers)
621
673
  const limit = move * Math.min(1, 2 / beta);
622
674
  if (lightest) {
@@ -633,6 +685,16 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
633
685
  multipliers.lam.forEach((l, k) => { for (let j = 0; j < l.length; j++) l[j] += multipliers.mu * stress.h[k][j]; });
634
686
  multipliers.mu = Math.min(1.1 * multipliers.mu, 1e4);
635
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]; });
636
698
  } else {
637
699
  history.push(compliance);
638
700
  // Optimality criteria: scale each cell by √(−dc/dv/λ), within the move limit, finding λ by bisection so the
@@ -656,7 +718,7 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
656
718
  change = 0;
657
719
  for (let e = 0; e < cells; e++) change = Math.max(change, Math.abs(xnew[e] - x[e]));
658
720
  x.set(xnew);
659
- 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 } : {}) });
660
722
  if (lightest) {
661
723
  // Sharper every 25 rounds of the multipliers
662
724
  if (beta < betaMax && sinceBeta >= 25 * INNER) { beta *= 2; sinceBeta = 0; }
@@ -665,14 +727,16 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
665
727
  // Sharpen: double the projection's steepness when the design settles (or every 50 steps), until it's at its sharpest
666
728
  if (beta < betaMax && (change < tol || sinceBeta >= 50)) { beta *= 2; sinceBeta = 0; continue; }
667
729
  // 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;
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);
669
732
  if (beta >= betaMax && (change < tol || settled)) { converged = true; break; }
670
733
  }
671
734
  // The final design, analysed as it is
672
735
  const final = m.evaluate(x, beta, { all: true }), phys = Float64Array.from(m.physical(x, beta));
673
736
  // (the final physical call is after evaluate's, so unsupported comes from the evaluation of this design)
674
737
  return {
675
- 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 } } : {}),
676
740
  volume: phys.reduce((s, v, e) => s + (passive[e] !== -2 ? v : 0), 0) / inSpace, steps: step, converged, history, seconds: (Date.now() - started) / 1000,
677
741
  };
678
742
  }
@@ -880,9 +944,11 @@ function simplify(loop, tolerance) {
880
944
  * @param {{ nx: number, ny: number, nz: number, h: number }} size @param {ArrayLike<number>} density @param {number[]} origin
881
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
882
946
  * 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.
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).
886
952
  * @returns {{ vertices: number[][], faces: number[][] }}
887
953
  */
888
954
  export function surface({ nx, ny, nz, h }, density, origin = [0, 0, 0], { smooth = 4, iso = 0.5, overhang } = {}) {
@@ -952,14 +1018,30 @@ export function surface({ nx, ny, nz, h }, density, origin = [0, 0, 0], { smooth
952
1018
  }
953
1019
  // Printable: faces past the limit tipped back, and tips lifted, in turn until neither finds any (each can make work for
954
1020
  // 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; }
1021
+ if (overhang) settle({ vertices: pts, faces }, { overhang, lo, hi, held });
956
1022
  return { vertices: pts, faces };
957
1023
  }
958
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
+
959
1041
  // Faces past the overhang limit, tipped back to it. Optimised in cubes, a printable slope is a staircase of 45°, and
960
1042
  // smoothing leaves small faces either side of 45°. Each face facing down more steeply than the limit is turned about
961
1043
  // 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
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
963
1045
  // none are left. Flat faces (a bridge) and faces held on the grid's sides stay as they are.
964
1046
  function steepen(pts, faces, held, { up, angle }, lo, hi, passes = 200) {
965
1047
  const q = 'xyz'.indexOf(up[1]), s = up[0] === '-' ? -1 : 1, [a, b] = [0, 1, 2].filter((x) => x !== q);
@@ -988,6 +1070,36 @@ function steepen(pts, faces, held, { up, angle }, lo, hi, passes = 200) {
988
1070
  return true;
989
1071
  }
990
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
+
991
1103
  // Tips lifted: a corner lower than every corner round it (along the build direction), on faces facing down, starts in
992
1104
  // mid-air, where a printer has nothing to lay it on. Smoothing leaves these under edges and bridges. Each is raised level
993
1105
  // with its lowest neighbour, which leaves a small flat underside (bridged), until none are left. The bed's corners and
@@ -1014,6 +1126,79 @@ function lift(pts, faces, held, { up }, lo, passes = 50) {
1014
1126
  return true;
1015
1127
  }
1016
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
+
1017
1202
  /**
1018
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
1019
1204
  * something holds it up: a cell kept in the layer below, straight under it or diagonally next to that (so nothing