@rulecad/topopt 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 JoniBach and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,104 @@
1
- # Temporary Holding Version
1
+ # @rulecad/topopt
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Topology optimisation for flat parts (2D) and solid ones (3D): where to put a fixed amount of material in a region so
4
+ the part is as stiff as possible under its loads. Give it the space a part may fill, the bosses it must keep, the
5
+ holes it must avoid, where it's held and how it's loaded. It returns outlines ready to extrude (2D), or a closed surface
6
+ ready to print (3D). No dependencies but
7
+ [@rulecad/fea](../fea); runs in browsers and Node.
8
+
9
+ ```js
10
+ import { discretise, optimise, outlines } from '@rulecad/topopt';
11
+
12
+ const spec = discretise({
13
+ space: { at: [60, 0], size: [140, 40] }, // where material may go (mm)
14
+ keep: [{ at: [0, 0], r: 6 }, { at: [120, 0], r: 5 }], // must stay solid
15
+ avoid: [{ at: [0, 0], r: 2.8 }, { at: [120, 0], r: 2.3 }], // must stay empty
16
+ supports: [{ at: [0, 0], r: 2.8 }], // held here
17
+ loads: [{ at: [120, 0], r: 2.3, force: [0, -20], case: 'down' }], // pushed here (N)
18
+ material: { E: 2680, nu: 0.36 }, thickness: 6, cell: 1, volume: 0.5, filter: 2.5,
19
+ });
20
+ const result = optimise(spec, { onStep: (s) => console.log(s.step, s.compliance) });
21
+ result.cases; // [{ name: 'down', deflection (mm along the load), stiffness (N/mm) }]
22
+ const loops = outlines(spec.grid, result.density, spec.origin); // closed loops, solid on the left
23
+ ```
24
+
25
+ ### In 3D
26
+
27
+ Regions take a z. A region can be a box (`size`), a cylinder (`r`, `length`, `axis`), a ball (`r`), or a closed
28
+ triangle mesh (`triangles`). A cylinder along x or y can be a teardrop (`teardrop: '-z'` for a boss, `'+z'` for a
29
+ hole): it gets a 45° point, so it prints without support. Supports and loads can be any region.
30
+
31
+ ```js
32
+ const spec = discretise({
33
+ space: { at: [10, 0, 43], size: [40, 40, 86] },
34
+ keep: [{ at: [10, 0, 80], r: 5, length: 16, axis: 'x', teardrop: '-z' }],
35
+ supports: [{ at: [10, 0, 1], size: [40, 40, 2] }],
36
+ loads: [{ at: [10, 0, 80], r: 2.4, length: 16, axis: 'x', force: [0, -20, 0] }],
37
+ material: { E: 2680, nu: 0.36 }, cell: 2.5, volume: 0.2, filter: 5,
38
+ overhang: '+z', // printable standing this way up: no supports
39
+ });
40
+ const result = optimise(spec); // multigrid solves each step
41
+ const { vertices, faces } = surface(spec.grid, result.density, spec.origin);
42
+ ```
43
+
44
+ ## How it works
45
+
46
+ The density method (SIMP: solid isotropic material with penalisation). Each cell has a density from 0 to 1, starting
47
+ even. On each step:
48
+
49
+ 1. **Analyse** the part (@rulecad/fea).
50
+ 2. **Work out each cell's effect on the compliance.** Compliance is how much the part gives under its loads, so lower
51
+ is stiffer; each cell's effect is its gradient.
52
+ 3. **Move material** towards the cells that stiffen the part most, keeping the total fixed (the optimality criteria
53
+ update).
54
+
55
+ Stiffness grows as density cubed, so part-solid cells are poor value and the result settles into solid and empty.
56
+ Two more steps shape the result:
57
+
58
+ - **A density filter** averages each cell with its neighbours. It sets the thinnest member and prevents chequerboard
59
+ patterns.
60
+ - **Heaviside projection** sharpens the result, more on each pass, until cells are solid or empty.
61
+ - **The overhang filter** (optional, after Langelaar 2017) applies the printer's limit. Layer by layer from the bed, a
62
+ cell can only be as solid as the material under it: the cell below and its neighbours, so nothing overhangs more
63
+ than 45°. The result prints without supports in that direction.
64
+
65
+ Several load cases are optimised together by weight. A case weighted 0 is solved only at the end, for its figures.
66
+ `model(spec)` exposes the analysis and its gradient, for other update methods.
67
+
68
+ `outlines` traces a 2D result's edges at density 0.5 (marching squares), smooths them (Taubin, which keeps the size),
69
+ and drops holes and islands smaller than `minArea`.
70
+
71
+ `surface` does the same for a 3D result: a closed triangle mesh at density 0.5, by marching tetrahedra. Every cube
72
+ is split along the same diagonal, so neighbouring cubes cut their shared faces the same way and the surface has no
73
+ gaps. Then it's smoothed.
74
+
75
+ ## Checked against the published code
76
+
77
+ With projection off, it matches a line-by-line port of the 88-line MATLAB code (`reference/top88.py`) step for step:
78
+
79
+ - **The MBB beam** (60 × 20, volume 0.5): 127 steps to a compliance of 218.80.
80
+ - **A short cantilever** (48 × 24, volume 0.4): 100 steps to 99.49.
81
+
82
+ In 3D it matches a port of Liu and Tovar's top3d (`reference/top3d.py`) step for step: a cantilever of 24 × 8 × 8
83
+ cubes, 145 steps to 4906.73. The overhang filter's gradient agrees with finite differences.
84
+
85
+ Its gradients agree with finite differences through the filter and the projection.
86
+
87
+ ## Glossary
88
+
89
+ - **Compliance:** the load times how far it moves (N·mm); the inverse of stiffness.
90
+ - **Volume:** the share of the space the result fills, 0 to 1.
91
+ - **Filter radius:** about the thinnest member, in mm.
92
+
93
+ ## Sources
94
+
95
+ - Bendsøe, Sigmund (2003). *Topology Optimization: Theory, Methods and Applications*. Springer.
96
+ - Andreassen, Clausen, Schevenels, Lazarov, Sigmund (2011). Efficient topology optimization in MATLAB using 88 lines
97
+ of code. *Structural and Multidisciplinary Optimization* 43, 1–16.
98
+ - Wang, Lazarov, Sigmund (2011). On projection methods, convergence and robust formulations in topology optimization.
99
+ *Structural and Multidisciplinary Optimization* 43, 767–784.
100
+ - Liu, Tovar (2014). An efficient 3D topology optimization code written in Matlab. *Structural and Multidisciplinary
101
+ Optimization* 50, 1175–1196.
102
+ - Langelaar (2017). An additive manufacturing filter for topology optimization of print-ready designs. *Structural and
103
+ Multidisciplinary Optimization* 55, 871–883.
104
+ - Taubin (1995). A signal processing approach to fair surface design. *SIGGRAPH '95*, 351–358.
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@rulecad/topopt",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
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
+ "type": "module",
6
+ "exports": {
7
+ "types": "./topopt.d.mts",
8
+ "default": "./topopt.mjs"
9
+ },
10
+ "files": [
11
+ "topopt.mjs",
12
+ "topopt.d.mts",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "license": "MIT",
17
+ "keywords": [
18
+ "topology-optimization",
19
+ "generative-design",
20
+ "simp",
21
+ "3d-printing"
22
+ ],
23
+ "engines": {
24
+ "node": ">=20"
25
+ },
26
+ "sideEffects": false,
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/JoniBach/rulecad.git",
30
+ "directory": "packages/topopt"
31
+ },
32
+ "scripts": {
33
+ "test": "node --test"
34
+ },
35
+ "dependencies": {
36
+ "@rulecad/fea": "^0.2.0"
37
+ },
38
+ "types": "./topopt.d.mts"
39
+ }
package/topopt.d.mts ADDED
@@ -0,0 +1,279 @@
1
+ /**
2
+ * @typedef {{ at: number[], r: number } | { at: number[], size: number[] } | { at: number[], r: number, length: number, axis?: 'x' | 'y' | 'z', teardrop?: '-z' | '+z' } | { points: [number, number][] } | { triangles: number[][][] }} Region
3
+ * in mm: a circle (2D) or sphere (3D) at, r; a box at (its centre), size; a cylinder at (its centre), r, length,
4
+ * along axis (default z; teardrop '-z' or '+z': along x or y, with a 45° point that way, so it prints); a polygon (2D);
5
+ * or a closed triangle mesh (3D: a design's part)
6
+ */
7
+ /** @typedef {Region & { fix?: string }} Support holds the nodes in the region (on material): fix the directions, 'xy' or 'xyz' (default all) */
8
+ /** @typedef {Region & { force: number[], case?: string }} Load a force in N, shared by the nodes in the region */
9
+ /**
10
+ * @typedef {object} Problem
11
+ * @property {Region | Region[]} space where material may go
12
+ * @property {Region[]} [keep] must stay solid (bosses round bolt holes)
13
+ * @property {Region[]} [avoid] must stay empty (the holes, clearances); avoid wins over keep
14
+ * @property {Support[]} supports
15
+ * @property {Load[]} loads each in its load case (default "load"); cases are optimised together
16
+ * @property {Record<string, number>} [cases] each case's weight (default 1)
17
+ * @property {{ E: number, nu: number }} material
18
+ * @property {number} [thickness] mm, for a 2D problem
19
+ * @property {number} cell the grid's cell size, mm
20
+ * @property {number} volume the share of the space to fill, 0 to 1 (keep regions count towards it)
21
+ * @property {number} [filter] the filter radius in mm: about the thinnest member (default 1.5 cells)
22
+ * @property {number} [penal] the penalty (default 3)
23
+ * @property {boolean} [projection] sharpen with Heaviside projection (default true)
24
+ * @property {string} [overhang] printed this way up ('+z', '-y', …): only material supported from below at 45° or less
25
+ * @property {number} [steps] at most this many steps (default 300)
26
+ */
27
+ /**
28
+ * A problem described in shapes, on a grid: each cell inside the space (or a keep region) is free, kept or avoided;
29
+ * supports and loads go on the nodes in or near them that touch material that may be solid. A 3D grid's sides are
30
+ * rounded up to a multiple of 2, 4 or 8 cells (extra cells are outside the space), so multigrid can halve it.
31
+ * @param {Problem} p
32
+ * @returns {object} a spec for optimise(), with origin (the grid's lowest corner, mm) and regions
33
+ */
34
+ export function discretise(p: Problem): object;
35
+ /**
36
+ * The density filter: each cell's filtered density is the weighted average of the cells within radius (weights
37
+ * falling linearly to 0 at the radius). apply filters densities; adjoint carries sensitivities back through it.
38
+ * @param {{ nx: number, ny: number, nz?: number }} size @param {number} radius in cells
39
+ */
40
+ export function densityFilter({ nx, ny, nz }: {
41
+ nx: number;
42
+ ny: number;
43
+ nz?: number;
44
+ }, radius: number): {
45
+ apply(x: any, out: any): any;
46
+ adjoint(x: any, out: any): any;
47
+ };
48
+ /**
49
+ * The overhang filter (Langelaar 2017): printed layer by layer from the bed, a cell can only be as solid as the
50
+ * material under it: the cell itself and its neighbours along each side, in the layer below (3 cells in 2D, 5 in 3D,
51
+ * so nothing overhangs by more than 45°). Smooth minimum and maximum keep it differentiable. apply gives the printable
52
+ * densities; adjoint carries sensitivities back through it.
53
+ * @param {{ nx: number, ny: number, nz?: number }} size @param {string} up the build direction: '+z', '-x', …
54
+ */
55
+ export function overhangFilter({ nx, ny, nz }: {
56
+ nx: number;
57
+ ny: number;
58
+ nz?: number;
59
+ }, up: string): {
60
+ apply(x: any, out: any): any;
61
+ adjoint(g: any, out: any): any;
62
+ };
63
+ /**
64
+ * The problem as a function of the design densities x (one per cell, 0 to 1), at projection sharpness beta:
65
+ * physical(x, beta) gives the densities the part is made of (filtered, printable, projected, kept and avoided cells
66
+ * set); evaluate(x, beta) analyses it and gives the compliance (summed over the load cases by weight, N·mm) and its
67
+ * gradient with respect to x (dc), with the gradient of the material used (dv). Cases weighted 0 are only solved with
68
+ * evaluate(x, beta, { all: true }).
69
+ * @param {ReturnType<typeof discretise>} spec
70
+ * @param {{ method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend }} [options]
71
+ */
72
+ export function model(spec: ReturnType<typeof discretise>, { method, backend }?: {
73
+ method?: "direct" | "cg" | "mg";
74
+ backend?: typeof jsBackend;
75
+ }): {
76
+ physical: (x: any, beta: any) => Float64Array<ArrayBuffer>;
77
+ evaluate: (x: any, beta: any, { all }?: {
78
+ all?: boolean;
79
+ }) => {
80
+ compliance: number;
81
+ dc: Float64Array<ArrayBuffer>;
82
+ dv: Float64Array<ArrayBuffer>;
83
+ u: any;
84
+ cases: any;
85
+ };
86
+ cells: number;
87
+ passive: any;
88
+ };
89
+ /**
90
+ * The optimisation: from an even spread, step by step, until the densities stop changing (less than tol per step)
91
+ * with projection at full sharpness, or steps run out.
92
+ * @param {ReturnType<typeof discretise>} spec
93
+ * @param {{ onStep?: (s: { step: number, steps: number, compliance: number, change: number, beta: number, density: Float64Array }) => void, method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend, tol?: number, move?: number }} [options]
94
+ * @returns {{ density: Float64Array, compliance: number, cases: { name: string, compliance: number, deflection: number, stiffness: number }[], volume: number, steps: number, converged: boolean, history: number[], seconds: number }}
95
+ * each case's deflection is along its load (mm, compliance over the load's size), stiffness the load over that (N/mm)
96
+ */
97
+ export function optimise(spec: ReturnType<typeof discretise>, { onStep, method, backend, tol, move }?: {
98
+ onStep?: (s: {
99
+ step: number;
100
+ steps: number;
101
+ compliance: number;
102
+ change: number;
103
+ beta: number;
104
+ density: Float64Array;
105
+ }) => void;
106
+ method?: "direct" | "cg" | "mg";
107
+ backend?: typeof jsBackend;
108
+ tol?: number;
109
+ move?: number;
110
+ }): {
111
+ density: Float64Array;
112
+ compliance: number;
113
+ cases: {
114
+ name: string;
115
+ compliance: number;
116
+ deflection: number;
117
+ stiffness: number;
118
+ }[];
119
+ volume: number;
120
+ steps: number;
121
+ converged: boolean;
122
+ history: number[];
123
+ seconds: number;
124
+ };
125
+ /**
126
+ * How many dimensions a region has: 2 or 3.
127
+ * @param {Region} r
128
+ * @returns {2 | 3}
129
+ */
130
+ export function dimension(r: Region): 2 | 3;
131
+ /**
132
+ * A region's bounding box: [min x, min y, (min z), max x, max y, (max z)] in mm.
133
+ * @param {Region} r
134
+ * @returns {number[]}
135
+ */
136
+ export function bounds(r: Region): number[];
137
+ /**
138
+ * The edges of a result at density 0.5 as closed loops in mm (marching squares on the densities averaged to the
139
+ * cells' corners), solid on the left: outer edges counter-clockwise, holes clockwise. Smoothed (Taubin, which keeps
140
+ * the size), simplified, and with loops smaller than minArea (mm²) dropped.
141
+ * @param {{ nx: number, ny: number, h: number }} size @param {ArrayLike<number>} density @param {[number, number]} origin
142
+ * @param {{ smooth?: number, minArea?: number, tolerance?: number }} [options]
143
+ * @returns {[number, number][][]}
144
+ */
145
+ export function outlines({ nx, ny, h }: {
146
+ nx: number;
147
+ ny: number;
148
+ h: number;
149
+ }, density: ArrayLike<number>, origin?: [number, number], { smooth, minArea, tolerance }?: {
150
+ smooth?: number;
151
+ minArea?: number;
152
+ tolerance?: number;
153
+ }): [number, number][][];
154
+ /**
155
+ * The area of a closed loop in mm², positive if counter-clockwise.
156
+ * @param {[number, number][]} loop
157
+ * @returns {number}
158
+ */
159
+ export function area(loop: [number, number][]): number;
160
+ /**
161
+ * A 3D result's surface at density 0.5: a closed triangle mesh in mm, outward-facing, smoothed (Taubin, which keeps
162
+ * the size). The densities are averaged to the cells' corners, with a layer of empty corners round the outside so the
163
+ * surface closes, and each cube between corners is split into six tetrahedra, all along the same diagonal, so
164
+ * neighbouring cubes cut their shared faces the same way and the surface has no gaps (marching tetrahedra).
165
+ * @param {{ nx: number, ny: number, nz: number, h: number }} size @param {ArrayLike<number>} density @param {number[]} origin
166
+ * 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
167
+ * base on the bed) keeps that face flat, and the walls rising from it don't lean out.
168
+ * @param {{ smooth?: number, iso?: number }} [options] iso: the density the surface is drawn at (0.5)
169
+ * @returns {{ vertices: number[][], faces: number[][] }}
170
+ */
171
+ export function surface({ nx, ny, nz, h }: {
172
+ nx: number;
173
+ ny: number;
174
+ nz: number;
175
+ h: number;
176
+ }, density: ArrayLike<number>, origin?: number[], { smooth, iso }?: {
177
+ smooth?: number;
178
+ iso?: number;
179
+ }): {
180
+ vertices: number[][];
181
+ faces: number[][];
182
+ };
183
+ export { jsBackend };
184
+ export function inside(r: Region, pt: number[]): boolean;
185
+ /**
186
+ * in mm: a circle (2D) or sphere (3D) at, r; a box at (its centre), size; a cylinder at (its centre), r, length,
187
+ * along axis (default z; teardrop '-z' or '+z': along x or y, with a 45° point that way, so it prints); a polygon (2D);
188
+ * or a closed triangle mesh (3D: a design's part)
189
+ */
190
+ export type Region = {
191
+ at: number[];
192
+ r: number;
193
+ } | {
194
+ at: number[];
195
+ size: number[];
196
+ } | {
197
+ at: number[];
198
+ r: number;
199
+ length: number;
200
+ axis?: "x" | "y" | "z";
201
+ teardrop?: "-z" | "+z";
202
+ } | {
203
+ points: [number, number][];
204
+ } | {
205
+ triangles: number[][][];
206
+ };
207
+ /**
208
+ * holds the nodes in the region (on material): fix the directions, 'xy' or 'xyz' (default all)
209
+ */
210
+ export type Support = Region & {
211
+ fix?: string;
212
+ };
213
+ /**
214
+ * a force in N, shared by the nodes in the region
215
+ */
216
+ export type Load = Region & {
217
+ force: number[];
218
+ case?: string;
219
+ };
220
+ export type Problem = {
221
+ /**
222
+ * where material may go
223
+ */
224
+ space: Region | Region[];
225
+ /**
226
+ * must stay solid (bosses round bolt holes)
227
+ */
228
+ keep?: Region[];
229
+ /**
230
+ * must stay empty (the holes, clearances); avoid wins over keep
231
+ */
232
+ avoid?: Region[];
233
+ supports: Support[];
234
+ /**
235
+ * each in its load case (default "load"); cases are optimised together
236
+ */
237
+ loads: Load[];
238
+ /**
239
+ * each case's weight (default 1)
240
+ */
241
+ cases?: Record<string, number>;
242
+ material: {
243
+ E: number;
244
+ nu: number;
245
+ };
246
+ /**
247
+ * mm, for a 2D problem
248
+ */
249
+ thickness?: number;
250
+ /**
251
+ * the grid's cell size, mm
252
+ */
253
+ cell: number;
254
+ /**
255
+ * the share of the space to fill, 0 to 1 (keep regions count towards it)
256
+ */
257
+ volume: number;
258
+ /**
259
+ * the filter radius in mm: about the thinnest member (default 1.5 cells)
260
+ */
261
+ filter?: number;
262
+ /**
263
+ * the penalty (default 3)
264
+ */
265
+ penal?: number;
266
+ /**
267
+ * sharpen with Heaviside projection (default true)
268
+ */
269
+ projection?: boolean;
270
+ /**
271
+ * printed this way up ('+z', '-y', …): only material supported from below at 45° or less
272
+ */
273
+ overhang?: string;
274
+ /**
275
+ * at most this many steps (default 300)
276
+ */
277
+ steps?: number;
278
+ };
279
+ import { jsBackend } from '@rulecad/fea';
package/topopt.mjs ADDED
@@ -0,0 +1,599 @@
1
+ // Topology optimisation: where to put a fixed amount of material in a region so the part is as stiff as possible
2
+ // under its loads, for flat parts (2D, a plate loaded in its own plane) and solid ones (3D, on cubes). The density
3
+ // method (SIMP: solid isotropic material with penalisation): every cell has a density from 0 to 1, stiffness grows as
4
+ // density cubed (so part-solid cells are poor value and the result settles into solid and empty), and each step moves
5
+ // material towards the cells that stiffen the part most. With a density filter (it sets the thinnest member), an
6
+ // optional overhang filter (only material a printer can build without supports), and Heaviside projection (it sharpens
7
+ // the result). After Andreassen et al. (2011), "Efficient topology optimization in MATLAB using 88 lines of code",
8
+ // Wang, Lazarov and Sigmund (2011), and Langelaar (2017), "An additive manufacturing filter for topology optimization
9
+ // of print-ready designs". No dependencies but @rulecad/fea; runs in browsers and Node. Millimetres, newtons, MPa.
10
+ //
11
+ // optimise(spec) the method itself, on a grid: densities, supports and loads by dof
12
+ // discretise(problem) a problem in shapes (a region, bosses to keep, holes to avoid, loads at points) to a spec
13
+ // outlines(result) a 2D result's edges as closed loops in mm, solid on the left, smoothed: ready to extrude
14
+ // surface(result) a 3D result's surface as a closed triangle mesh in mm, smoothed: ready to print
15
+ import { grid as makeGrid, cellStiffness, solve, positions, jsBackend } from '@rulecad/fea';
16
+
17
+ export { jsBackend };
18
+
19
+ /**
20
+ * @typedef {{ at: number[], r: number } | { at: number[], size: number[] } | { at: number[], r: number, length: number, axis?: 'x' | 'y' | 'z', teardrop?: '-z' | '+z' } | { points: [number, number][] } | { triangles: number[][][] }} Region
21
+ * in mm: a circle (2D) or sphere (3D) at, r; a box at (its centre), size; a cylinder at (its centre), r, length,
22
+ * along axis (default z; teardrop '-z' or '+z': along x or y, with a 45° point that way, so it prints); a polygon (2D);
23
+ * or a closed triangle mesh (3D: a design's part)
24
+ */
25
+ /** @typedef {Region & { fix?: string }} Support holds the nodes in the region (on material): fix the directions, 'xy' or 'xyz' (default all) */
26
+ /** @typedef {Region & { force: number[], case?: string }} Load a force in N, shared by the nodes in the region */
27
+ /**
28
+ * @typedef {object} Problem
29
+ * @property {Region | Region[]} space where material may go
30
+ * @property {Region[]} [keep] must stay solid (bosses round bolt holes)
31
+ * @property {Region[]} [avoid] must stay empty (the holes, clearances); avoid wins over keep
32
+ * @property {Support[]} supports
33
+ * @property {Load[]} loads each in its load case (default "load"); cases are optimised together
34
+ * @property {Record<string, number>} [cases] each case's weight (default 1)
35
+ * @property {{ E: number, nu: number }} material
36
+ * @property {number} [thickness] mm, for a 2D problem
37
+ * @property {number} cell the grid's cell size, mm
38
+ * @property {number} volume the share of the space to fill, 0 to 1 (keep regions count towards it)
39
+ * @property {number} [filter] the filter radius in mm: about the thinnest member (default 1.5 cells)
40
+ * @property {number} [penal] the penalty (default 3)
41
+ * @property {boolean} [projection] sharpen with Heaviside projection (default true)
42
+ * @property {string} [overhang] printed this way up ('+z', '-y', …): only material supported from below at 45° or less
43
+ * @property {number} [steps] at most this many steps (default 300)
44
+ */
45
+
46
+ /**
47
+ * A problem described in shapes, on a grid: each cell inside the space (or a keep region) is free, kept or avoided;
48
+ * supports and loads go on the nodes in or near them that touch material that may be solid. A 3D grid's sides are
49
+ * rounded up to a multiple of 2, 4 or 8 cells (extra cells are outside the space), so multigrid can halve it.
50
+ * @param {Problem} p
51
+ * @returns {object} a spec for optimise(), with origin (the grid's lowest corner, mm) and regions
52
+ */
53
+ export function discretise(p) {
54
+ const space = [p.space].flat(), keep = p.keep || [], avoid = p.avoid || [], dim = dimension(space[0]);
55
+ if (!(p.cell > 0)) throw new Error('the cell size must be more than 0 mm');
56
+ for (const r of [...space, ...keep, ...avoid]) if (dimension(r) !== dim) throw new Error(`a ${dimension(r)}D region in a ${dim}D problem: give every region ${dim === 3 ? 'x, y and z' : 'x and y'}`);
57
+ const all = [...space, ...keep].map(bounds), lo = [], n = [];
58
+ for (let a = 0; a < dim; a++) {
59
+ lo.push(Math.min(...all.map((b) => b[a])));
60
+ n.push(Math.max(1, Math.round((Math.max(...all.map((b) => b[dim + a])) - lo[a]) / p.cell)));
61
+ }
62
+ if (dim === 3) { // whole numbers of 2, 4 or 8 cells along every side, for multigrid
63
+ const q = Math.min(...n) >= 16 ? 8 : Math.min(...n) >= 8 ? 4 : 2;
64
+ for (let a = 0; a < 3; a++) n[a] = Math.ceil(n[a] / q) * q;
65
+ }
66
+ const size = dim === 3 ? { nx: n[0], ny: n[1], nz: n[2], h: p.cell } : { nx: n[0], ny: n[1], h: p.cell };
67
+ const g = makeGrid(size), origin = lo, h = p.cell;
68
+ // Each cell by its centre: 1 kept, -1 avoided, -2 outside (which doesn't count towards the volume), 0 free
69
+ const passive = new Int8Array(g.cells), test = (rs) => { const f = rs.map(insider); return (c) => f.some((t) => t(c)); };
70
+ const inSpace = test(space), inKeep = test(keep), inAvoid = test(avoid);
71
+ for (let e = 0; e < g.cells; e++) {
72
+ const i = e % n[0], j = Math.floor(e / n[0]) % n[1], k = dim === 3 ? Math.floor(e / (n[0] * n[1])) : 0;
73
+ const c = [origin[0] + (i + 0.5) * h, origin[1] + (j + 0.5) * h, ...(dim === 3 ? [origin[2] + (k + 0.5) * h] : [])];
74
+ const kept = inKeep(c), within = kept || inSpace(c);
75
+ passive[e] = !within ? -2 : inAvoid(c) ? -1 : kept ? 1 : 0;
76
+ }
77
+ const at = positions(g).map((q) => q.map((v, a) => v + origin[a]));
78
+ // A node is on material if a cell it's a corner of may be solid
79
+ const onMaterial = new Uint8Array(g.nodes), corners = 1 << dim;
80
+ for (let e = 0; e < g.cells; e++) if (passive[e] >= 0) for (let k = 0; k < corners; k++) onMaterial[g.edof[e * g.cellDofs + dim * k] / dim] = 1;
81
+ // The nodes a support or load acts on: within r (and three quarters of a cell) of a point, or in a region grown by as much
82
+ const select = (r, what) => {
83
+ const grown = grow(r, h * 0.75), within = r.size || r.points || r.triangles || r.length != null ? insider(grown) : (q) => dist(q, r.at) <= (r.r || 0) + h * 0.75;
84
+ const found = [];
85
+ for (let m = 0; m < g.nodes; m++) if (onMaterial[m] && within(at[m])) found.push(m);
86
+ if (!found.length) throw new Error(`${what}${r.at ? ` at ${r.at.map(fmt).join(', ')}` : ''} isn't on any material: move it onto the space or a keep region, or make it bigger`);
87
+ return found;
88
+ };
89
+ const axes = 'xyz'.slice(0, dim), fixed = new Uint8Array(g.dofs);
90
+ for (const s of p.supports || []) for (const m of select(s, 'a support')) for (let a = 0; a < dim; a++) if ((s.fix || axes).includes(axes[a])) fixed[dim * m + a] = 1;
91
+ const names = [...new Set((p.loads || []).map((l) => l.case || 'load'))];
92
+ if (!names.length) throw new Error('a problem needs at least one load');
93
+ const loads = names.map((name) => {
94
+ const f = new Float64Array(g.dofs), mine = p.loads.filter((x) => (x.case || 'load') === name), total = new Array(dim).fill(0);
95
+ for (const l of mine) {
96
+ if (l.force.length !== dim) throw new Error(`the load "${name}" needs a force with ${dim} parts (${axes.split('').join(', ')})`);
97
+ const ns = select(l, `the load "${name}"`);
98
+ for (const m of ns) for (let a = 0; a < dim; a++) f[dim * m + a] += l.force[a] / ns.length;
99
+ for (let a = 0; a < dim; a++) total[a] += l.force[a];
100
+ }
101
+ return { name, force: f, weight: p.cases?.[name] ?? 1, size: Math.hypot(...total) };
102
+ });
103
+ return {
104
+ grid: size, origin, passive, fixed, loads,
105
+ material: p.material, thickness: p.thickness, volume: p.volume,
106
+ filter: p.filter ?? p.cell * 1.5, penal: p.penal ?? 3, projection: p.projection ?? true, steps: p.steps ?? 300,
107
+ ...(p.overhang ? { overhang: p.overhang } : {}),
108
+ regions: { keep, avoid },
109
+ };
110
+ }
111
+
112
+ /**
113
+ * The density filter: each cell's filtered density is the weighted average of the cells within radius (weights
114
+ * falling linearly to 0 at the radius). apply filters densities; adjoint carries sensitivities back through it.
115
+ * @param {{ nx: number, ny: number, nz?: number }} size @param {number} radius in cells
116
+ */
117
+ export function densityFilter({ nx, ny, nz = 1 }, radius) {
118
+ const reach = Math.ceil(radius) - 1, cells = nx * ny * nz, rz = nz > 1 ? reach : 0;
119
+ // Each cell's neighbours and their weights, as flat arrays (row r's are at start[r] to start[r + 1])
120
+ const start = new Int32Array(cells + 1), index = [], weight = [], total = new Float64Array(cells);
121
+ for (let k = 0; k < nz; k++) for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) {
122
+ const e = (k * ny + j) * nx + i;
123
+ for (let c = Math.max(0, k - rz); c <= Math.min(nz - 1, k + rz); c++) for (let b = Math.max(0, j - reach); b <= Math.min(ny - 1, j + reach); b++) for (let a = Math.max(0, i - reach); a <= Math.min(nx - 1, i + reach); a++) {
124
+ const w = radius - Math.hypot(a - i, b - j, c - k);
125
+ if (w > 0) { index.push((c * ny + b) * nx + a); weight.push(w); total[e] += w; } // total: fewer neighbours at the edges
126
+ }
127
+ start[e + 1] = index.length;
128
+ }
129
+ const at = Int32Array.from(index), w = Float64Array.from(weight), scaled = new Float64Array(cells);
130
+ return {
131
+ apply(x, out) {
132
+ for (let e = 0; e < cells; e++) { let s = 0; for (let k = start[e]; k < start[e + 1]; k++) s += w[k] * x[at[k]]; out[e] = s / total[e]; }
133
+ return out;
134
+ },
135
+ adjoint(x, out) {
136
+ for (let e = 0; e < cells; e++) scaled[e] = x[e] / total[e];
137
+ for (let e = 0; e < cells; e++) { let s = 0; for (let k = start[e]; k < start[e + 1]; k++) s += w[k] * scaled[at[k]]; out[e] = s; }
138
+ return out;
139
+ },
140
+ };
141
+ }
142
+
143
+ /**
144
+ * The overhang filter (Langelaar 2017): printed layer by layer from the bed, a cell can only be as solid as the
145
+ * material under it: the cell itself and its neighbours along each side, in the layer below (3 cells in 2D, 5 in 3D,
146
+ * so nothing overhangs by more than 45°). Smooth minimum and maximum keep it differentiable. apply gives the printable
147
+ * densities; adjoint carries sensitivities back through it.
148
+ * @param {{ nx: number, ny: number, nz?: number }} size @param {string} up the build direction: '+z', '-x', …
149
+ */
150
+ export function overhangFilter({ nx, ny, nz = 1 }, up) {
151
+ const n = nz > 1 ? [nx, ny, nz] : [nx, ny], dim = n.length, ax = 'xyz'.indexOf(up.at(-1)), sign = up[0] === '-' ? -1 : 1;
152
+ 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})`);
153
+ const cells = n.reduce((p, c) => p * c, 1), stride = [1, nx, nx * ny];
154
+ const P = 40, eps = 1e-4, xi0 = 0.5;
155
+ // Layers in build order, and each cell's supports: the cell below it and that cell's neighbours along each other axis
156
+ const layer = (e) => { const c = Math.floor(e / stride[ax]) % n[ax]; return sign > 0 ? c : n[ax] - 1 - c; };
157
+ const order = Array.from({ length: cells }, (_, e) => e).sort((a, b) => layer(a) - layer(b));
158
+ const supports = new Array(cells);
159
+ for (let e = 0; e < cells; e++) {
160
+ if (layer(e) === 0) { supports[e] = null; continue; }
161
+ const below = e - sign * stride[ax], list = [below];
162
+ for (let a = 0; a < dim; a++) if (a !== ax) {
163
+ const c = Math.floor(below / stride[a]) % n[a];
164
+ if (c > 0) list.push(below - stride[a]);
165
+ if (c < n[a] - 1) list.push(below + stride[a]);
166
+ }
167
+ supports[e] = Int32Array.from(list);
168
+ }
169
+ const printed = new Float64Array(cells), dSum = new Float64Array(cells), dX = new Float64Array(cells), sums = new Float64Array(cells);
170
+ return {
171
+ apply(x, out) {
172
+ for (const e of order) {
173
+ const sup = supports[e];
174
+ if (!sup) { printed[e] = x[e]; dX[e] = 1; continue; }
175
+ let s = 0;
176
+ for (const q of sup) s += Math.pow(printed[q], P);
177
+ if (s < 1e-200) s = 0; // nothing worth the name below (and no denormals for the gradient to blow up on)
178
+ const Q = P + Math.log(sup.length) / Math.log(xi0), smax = s > 0 ? Math.pow(s, 1 / Q) : 0;
179
+ sums[e] = s;
180
+ const d = x[e] - smax, root = Math.sqrt(d * d + eps);
181
+ printed[e] = 0.5 * (x[e] + smax - root + Math.sqrt(eps));
182
+ dX[e] = 0.5 * (1 - d / root); dSum[e] = 0.5 * (1 + d / root); // d printed / d x, d printed / d smax
183
+ }
184
+ out.set(printed);
185
+ return out;
186
+ },
187
+ // Back from the last layer: each cell's sensitivity, plus what it passes on to the cells it supports
188
+ adjoint(g, out) {
189
+ const lambda = Float64Array.from(g);
190
+ for (let t = cells - 1; t >= 0; t--) {
191
+ const e = order[t], sup = supports[e];
192
+ if (!sup || !sums[e]) continue;
193
+ 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;
194
+ for (const q of sup) lambda[q] += common * Math.pow(printed[q], P - 1);
195
+ }
196
+ for (let e = 0; e < cells; e++) out[e] = lambda[e] * dX[e];
197
+ return out;
198
+ },
199
+ };
200
+ }
201
+
202
+ /**
203
+ * The problem as a function of the design densities x (one per cell, 0 to 1), at projection sharpness beta:
204
+ * physical(x, beta) gives the densities the part is made of (filtered, printable, projected, kept and avoided cells
205
+ * set); evaluate(x, beta) analyses it and gives the compliance (summed over the load cases by weight, N·mm) and its
206
+ * gradient with respect to x (dc), with the gradient of the material used (dv). Cases weighted 0 are only solved with
207
+ * evaluate(x, beta, { all: true }).
208
+ * @param {ReturnType<typeof discretise>} spec
209
+ * @param {{ method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend }} [options]
210
+ */
211
+ export function model(spec, { method, backend = jsBackend } = {}) {
212
+ const g = makeGrid(spec.grid), dim = g.dim, cells = g.cells, m = g.cellDofs, ke = cellStiffness(spec.material.nu, dim);
213
+ const { passive, penal } = spec, E = spec.material.E, Emin = E * 1e-9, eta = 0.5, size = dim === 3 ? g.h : spec.thickness;
214
+ const solver = method || (dim === 3 ? 'mg' : 'direct'), tol = solver === 'direct' ? undefined : 1e-6;
215
+ const filter = densityFilter(spec.grid, spec.filter / spec.grid.h), print = spec.overhang ? overhangFilter(spec.grid, spec.overhang) : null;
216
+ const tilde = new Float64Array(cells), made = new Float64Array(cells), phys = new Float64Array(cells), scale = new Float64Array(cells), back = new Float64Array(cells);
217
+ const fixedValue = (p) => (p === 1 ? 1 : 0);
218
+ // Heaviside projection about eta: steeper as beta grows, so densities are pushed to 0 or 1 (Wang, Lazarov, Sigmund 2011)
219
+ const denominator = (beta) => Math.tanh(beta * eta) + Math.tanh(beta * (1 - eta));
220
+ const project = (t, beta) => (spec.projection ? (Math.tanh(beta * eta) + Math.tanh(beta * (t - eta))) / denominator(beta) : t);
221
+ const slope = (t, beta) => (spec.projection ? (beta * (1 - Math.tanh(beta * (t - eta)) ** 2)) / denominator(beta) : 1);
222
+ const physical = (x, beta) => {
223
+ filter.apply(x, tilde);
224
+ if (print) print.apply(tilde, made); else made.set(tilde);
225
+ for (let e = 0; e < cells; e++) phys[e] = passive[e] ? fixedValue(passive[e]) : project(made[e], beta);
226
+ return phys;
227
+ };
228
+ let last = null;
229
+ // Each step solves only the load cases it optimises for (weight above 0); every case is solved when all is set
230
+ const evaluate = (x, beta, { all = false } = {}) => {
231
+ physical(x, beta);
232
+ for (let e = 0; e < cells; e++) scale[e] = size * (Emin + Math.pow(phys[e], penal) * (E - Emin));
233
+ const active = spec.loads.map((l, c) => (all || l.weight > 0 ? c : -1)).filter((c) => c >= 0);
234
+ const solved = 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 } : {}) }).u;
235
+ const u = spec.loads.map((_, c) => (active.includes(c) ? solved[active.indexOf(c)] : last?.[c] || null));
236
+ last = u;
237
+ // Compliance, and its gradient with respect to each cell's physical density: −p ρ^(p−1) (E − Emin) size · uₑᵀ kₑ uₑ
238
+ // (the load is fixed, so the adjoint is the displacement itself)
239
+ let compliance = 0;
240
+ const dc = new Float64Array(cells), dv = new Float64Array(cells);
241
+ spec.loads.forEach((l, c) => {
242
+ const w = l.weight, uc = u[c];
243
+ if (!w || !active.includes(c)) return;
244
+ for (let e = 0; e < cells; e++) {
245
+ let ce = 0;
246
+ const o = e * m;
247
+ for (let a = 0; a < m; a++) { let s = 0; for (let b = 0; b < m; b++) s += ke[a * m + b] * uc[g.edof[o + b]]; ce += uc[g.edof[o + a]] * s; }
248
+ compliance += w * scale[e] * ce;
249
+ dc[e] -= w * penal * Math.pow(phys[e], penal - 1) * (E - Emin) * size * ce;
250
+ }
251
+ });
252
+ // Back through the projection, the overhang filter and the density filter to the design densities; kept and
253
+ // avoided cells don't change
254
+ for (let e = 0; e < cells; e++) { const s = passive[e] ? 0 : slope(made[e], beta); dc[e] *= s; dv[e] = s; }
255
+ if (print) { print.adjoint(dc, back); dc.set(back); print.adjoint(dv, back); dv.set(back); }
256
+ filter.adjoint(dc, back); dc.set(back);
257
+ filter.adjoint(dv, back); dv.set(back);
258
+ const cases = spec.loads.map((l, c) => {
259
+ if (!u[c]) return { name: l.name, compliance: NaN, deflection: NaN, stiffness: NaN };
260
+ const ci = jsBackend.dot(l.force, u[c]), deflection = l.size ? ci / l.size : 0;
261
+ return { name: l.name, compliance: ci, deflection, stiffness: deflection ? l.size / deflection : Infinity };
262
+ });
263
+ return { compliance, dc, dv, u, cases };
264
+ };
265
+ return { physical, evaluate, cells, passive };
266
+ }
267
+
268
+ /**
269
+ * The optimisation: from an even spread, step by step, until the densities stop changing (less than tol per step)
270
+ * with projection at full sharpness, or steps run out.
271
+ * @param {ReturnType<typeof discretise>} spec
272
+ * @param {{ onStep?: (s: { step: number, steps: number, compliance: number, change: number, beta: number, density: Float64Array }) => void, method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend, tol?: number, move?: number }} [options]
273
+ * @returns {{ density: Float64Array, compliance: number, cases: { name: string, compliance: number, deflection: number, stiffness: number }[], volume: number, steps: number, converged: boolean, history: number[], seconds: number }}
274
+ * each case's deflection is along its load (mm, compliance over the load's size), stiffness the load over that (N/mm)
275
+ */
276
+ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01, move = 0.2 } = {}) {
277
+ const started = Date.now(), m = model(spec, { method, backend }), { cells, passive } = m;
278
+ const inSpace = passive.reduce((s, p) => s + (p !== -2 ? 1 : 0), 0), kept = passive.reduce((s, p) => s + (p === 1 ? 1 : 0), 0);
279
+ const free = passive.reduce((s, p) => s + (p === 0 ? 1 : 0), 0), target = spec.volume * inSpace;
280
+ if (!(spec.volume > 0 && spec.volume <= 1)) throw new Error(`the volume is a share of the space, from 0 to 1 (got ${spec.volume})`);
281
+ if (kept > target) throw new Error(`the keep regions alone fill ${fmt((kept / inSpace) * 100)}% of the space, more than the volume (${fmt(spec.volume * 100)}%): raise the volume`);
282
+ if (!free) throw new Error('no free cells: the keep and avoid regions cover the whole space');
283
+
284
+ const betaMax = spec.projection ? 16 : 1, fixedValue = (p) => (p === 1 ? 1 : 0);
285
+ const x = new Float64Array(cells), xnew = new Float64Array(cells);
286
+ for (let e = 0; e < cells; e++) x[e] = passive[e] ? fixedValue(passive[e]) : (target - kept) / free;
287
+ const history = [];
288
+ let step = 0, change = 1, converged = false, beta = 1, sinceBeta = 0;
289
+ while (step < spec.steps) {
290
+ step++; sinceBeta++;
291
+ const { compliance, dc, dv } = m.evaluate(x, beta);
292
+ history.push(compliance);
293
+ // Optimality criteria: scale each cell by √(−dc/dv/λ), within the move limit, finding λ by bisection so the
294
+ // physical densities fill exactly the volume
295
+ // A sharper projection magnifies each change, so the move limit shrinks with it (else the design flickers)
296
+ const limit = move * Math.min(1, 2 / beta);
297
+ let lo = 0, hi = 1e9;
298
+ while ((hi - lo) / (hi + lo) > 1e-3) { // as the 88-line code
299
+ const mid = (lo + hi) / 2;
300
+ for (let e = 0; e < cells; e++) {
301
+ if (passive[e]) { xnew[e] = fixedValue(passive[e]); continue; }
302
+ const b = Math.sqrt(Math.max(0, -dc[e]) / Math.max(1e-30, dv[e]) / mid);
303
+ xnew[e] = Math.max(0, Math.max(x[e] - limit, Math.min(1, Math.min(x[e] + limit, x[e] * b))));
304
+ }
305
+ const filled = m.physical(xnew, beta).reduce((s, v) => s + v, 0);
306
+ if (filled > target) lo = mid; else hi = mid;
307
+ }
308
+ change = 0;
309
+ for (let e = 0; e < cells; e++) change = Math.max(change, Math.abs(xnew[e] - x[e]));
310
+ x.set(xnew);
311
+ onStep?.({ step, steps: spec.steps, compliance, change, beta, density: m.physical(x, beta) });
312
+ // Sharpen: double the projection's steepness when the design settles (or every 50 steps), until it's at its sharpest
313
+ if (beta < betaMax && (change < tol || sinceBeta >= 50)) { beta *= 2; sinceBeta = 0; continue; }
314
+ // Done when nothing moves, or at full sharpness the compliance has stopped improving (within 0.1% over 10 steps)
315
+ const settled = spec.projection && history.length > 10 && beta >= betaMax && sinceBeta > 10 && Math.abs(history.at(-11) - compliance) <= 1e-3 * compliance;
316
+ if (beta >= betaMax && (change < tol || settled)) { converged = true; break; }
317
+ }
318
+ // The final design, analysed as it is
319
+ const final = m.evaluate(x, beta, { all: true }), phys = Float64Array.from(m.physical(x, beta));
320
+ return {
321
+ density: phys, compliance: final.compliance, cases: final.cases,
322
+ volume: phys.reduce((s, v, e) => s + (passive[e] !== -2 ? v : 0), 0) / inSpace, steps: step, converged, history, seconds: (Date.now() - started) / 1000,
323
+ };
324
+ }
325
+
326
+ /**
327
+ * How many dimensions a region has: 2 or 3.
328
+ * @param {Region} r
329
+ * @returns {2 | 3}
330
+ */
331
+ export function dimension(r) {
332
+ if (r.triangles || r.length != null) return 3;
333
+ if (r.points) return 2;
334
+ return (r.size || r.at).length === 3 ? 3 : 2;
335
+ }
336
+
337
+ /**
338
+ * Whether point pt is inside a region.
339
+ * @param {Region} r @param {number[]} pt
340
+ * @returns {boolean}
341
+ */
342
+ export const inside = (r, pt) => insider(r)(pt);
343
+
344
+ // A test for points inside a region (a closed mesh's is built once: its triangles binned by x and y, then a ray
345
+ // straight up from the point crosses the mesh an odd number of times if the point is inside)
346
+ const meshTests = new WeakMap();
347
+ function insider(r) {
348
+ if (r.triangles) {
349
+ if (!meshTests.has(r.triangles)) meshTests.set(r.triangles, meshInside(r.triangles));
350
+ return meshTests.get(r.triangles);
351
+ }
352
+ if (r.points) return (pt) => {
353
+ let c = false; // even-odd ray crossing
354
+ const P = r.points, [x, y] = pt;
355
+ for (let i = 0, j = P.length - 1; i < P.length; j = i++) {
356
+ if ((P[i][1] > y) !== (P[j][1] > y) && x < ((P[j][0] - P[i][0]) * (y - P[i][1])) / (P[j][1] - P[i][1]) + P[i][0]) c = !c;
357
+ }
358
+ return c;
359
+ };
360
+ if (r.size) return (pt) => r.size.every((s, a) => Math.abs(pt[a] - r.at[a]) <= s / 2);
361
+ if (r.length != null) {
362
+ const ax = 'xyz'.indexOf(r.axis || 'z'), others = [0, 1, 2].filter((a) => a !== ax);
363
+ // A teardrop: a cylinder across the build (along x or y) with a 45° point below it (a boss) or above it (a hole),
364
+ // so it prints unsupported
365
+ const point = r.teardrop && ax !== 2 ? (r.teardrop === '+z' ? 1 : -1) : 0, side = others.find((a) => a !== 2);
366
+ return (pt) => {
367
+ if (Math.abs(pt[ax] - r.at[ax]) > r.length / 2) return false;
368
+ if (Math.hypot(pt[others[0]] - r.at[others[0]], pt[others[1]] - r.at[others[1]]) <= r.r) return true;
369
+ const out = point * (pt[2] - r.at[2]);
370
+ return point !== 0 && out > 0 && Math.abs(pt[side] - r.at[side]) + out <= r.r * Math.SQRT2;
371
+ };
372
+ }
373
+ return (pt) => dist(pt, r.at) <= r.r;
374
+ }
375
+ function meshInside(triangles) {
376
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
377
+ for (const t of triangles) for (const [x, y] of t) { x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); }
378
+ const B = Math.max(1, Math.ceil(Math.sqrt(triangles.length / 4))), sx = (x1 - x0) / B || 1, sy = (y1 - y0) / B || 1;
379
+ const bins = Array.from({ length: B * B }, () => []), bin = (v, lo, s) => Math.min(B - 1, Math.max(0, Math.floor((v - lo) / s)));
380
+ triangles.forEach((t, n) => {
381
+ const xs = t.map((p) => p[0]), ys = t.map((p) => p[1]);
382
+ for (let j = bin(Math.min(...ys), y0, sy); j <= bin(Math.max(...ys), y0, sy); j++) for (let i = bin(Math.min(...xs), x0, sx); i <= bin(Math.max(...xs), x0, sx); i++) bins[j * B + i].push(n);
383
+ });
384
+ return ([px, py, pz]) => {
385
+ if (px < x0 || px > x1 || py < y0 || py > y1) return false;
386
+ const x = px + 1e-7 * Math.SQRT2, y = py + 1e-7 * Math.PI; // off-centre, so the ray meets no edge exactly
387
+ let crossings = 0;
388
+ for (const n of bins[bin(x, x0, sx) + B * bin(y, y0, sy)]) {
389
+ const [a, b, c] = triangles[n], d = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
390
+ if (!d) continue;
391
+ const w0 = ((b[0] - x) * (c[1] - y) - (b[1] - y) * (c[0] - x)) / d, w1 = ((c[0] - x) * (a[1] - y) - (c[1] - y) * (a[0] - x)) / d, w2 = 1 - w0 - w1;
392
+ if (w0 < 0 || w1 < 0 || w2 < 0) continue;
393
+ if (w0 * a[2] + w1 * b[2] + w2 * c[2] > pz) crossings++;
394
+ }
395
+ return crossings % 2 === 1;
396
+ };
397
+ }
398
+
399
+ // A region grown by d all round (a polygon or mesh as it is)
400
+ function grow(r, d) {
401
+ if (r.triangles || r.points) return r;
402
+ if (r.size) return { ...r, size: r.size.map((s) => s + 2 * d) };
403
+ if (r.length != null) return { ...r, r: r.r + d, length: r.length + 2 * d };
404
+ return { ...r, r: (r.r || 0) + d };
405
+ }
406
+ const dist = (a, b) => Math.hypot(...a.map((v, i) => v - b[i]));
407
+
408
+ /**
409
+ * A region's bounding box: [min x, min y, (min z), max x, max y, (max z)] in mm.
410
+ * @param {Region} r
411
+ * @returns {number[]}
412
+ */
413
+ export function bounds(r) {
414
+ const dim = dimension(r);
415
+ if (r.triangles) {
416
+ const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];
417
+ for (const t of r.triangles) for (const p of t) for (let a = 0; a < 3; a++) { lo[a] = Math.min(lo[a], p[a]); hi[a] = Math.max(hi[a], p[a]); }
418
+ return [...lo, ...hi];
419
+ }
420
+ if (r.points) { const xs = r.points.map((p) => p[0]), ys = r.points.map((p) => p[1]); return [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)]; }
421
+ const half = r.size ? r.size.map((s) => s / 2) : r.length != null ? [0, 1, 2].map((a) => (a === 'xyz'.indexOf(r.axis || 'z') ? r.length / 2 : r.r)) : new Array(dim).fill(r.r);
422
+ const lo = r.at.map((c, a) => c - half[a]);
423
+ const hi = r.at.map((c, a) => c + half[a]);
424
+ if (r.teardrop && r.length != null && (r.axis || 'z') !== 'z') { if (r.teardrop === '+z') hi[2] = r.at[2] + r.r * Math.SQRT2; else lo[2] = r.at[2] - r.r * Math.SQRT2; } // its point
425
+ return [...lo, ...hi];
426
+ }
427
+
428
+ // ---------- shapes from results ----------
429
+ // (Everything above decides the densities; everything below only draws them, so results can be kept by the code above)
430
+
431
+ /**
432
+ * The edges of a result at density 0.5 as closed loops in mm (marching squares on the densities averaged to the
433
+ * cells' corners), solid on the left: outer edges counter-clockwise, holes clockwise. Smoothed (Taubin, which keeps
434
+ * the size), simplified, and with loops smaller than minArea (mm²) dropped.
435
+ * @param {{ nx: number, ny: number, h: number }} size @param {ArrayLike<number>} density @param {[number, number]} origin
436
+ * @param {{ smooth?: number, minArea?: number, tolerance?: number }} [options]
437
+ * @returns {[number, number][][]}
438
+ */
439
+ export function outlines({ nx, ny, h }, density, origin = [0, 0], { smooth = 4, minArea = 0, tolerance = h * 0.05 } = {}) {
440
+ // Corner values, with a ring of empty corners round the outside so every loop closes
441
+ const W = nx + 3, H = ny + 3, v = new Float64Array(W * H);
442
+ for (let j = 0; j <= ny; j++) for (let i = 0; i <= nx; i++) {
443
+ let s = 0;
444
+ for (const [a, b] of [[i - 1, j - 1], [i, j - 1], [i - 1, j], [i, j]]) if (a >= 0 && a < nx && b >= 0 && b < ny) s += density[b * nx + a];
445
+ v[(j + 1) * W + i + 1] = s / 4;
446
+ }
447
+ const iso = 0.5, pos = (i, j) => [origin[0] + (i - 1) * h, origin[1] + (j - 1) * h];
448
+ // Edge keys: horizontal edge from corner (i, j) to (i + 1, j) is "h i j", vertical from (i, j) to (i, j + 1) "v i j"
449
+ const point = new Map(), next = new Map();
450
+ const cross = (key, a, b, pa, pb) => {
451
+ if (!point.has(key)) { const t = (iso - a) / (b - a); point.set(key, [pa[0] + t * (pb[0] - pa[0]), pa[1] + t * (pb[1] - pa[1])]); }
452
+ return key;
453
+ };
454
+ for (let j = 0; j < H - 1; j++) for (let i = 0; i < W - 1; i++) {
455
+ const c = [[i, j], [i + 1, j], [i + 1, j + 1], [i, j + 1]], val = c.map(([a, b]) => v[b * W + a]), inn = val.map((x) => x >= iso);
456
+ const edges = [`h ${i} ${j}`, `v ${i + 1} ${j}`, `h ${i} ${j + 1}`, `v ${i} ${j}`]; // bottom, right, top, left: counter-clockwise
457
+ const crossings = [];
458
+ for (let k = 0; k < 4; k++) {
459
+ const a = k, b = (k + 1) % 4;
460
+ if (inn[a] !== inn[b]) crossings.push({ key: cross(edges[k], val[a], val[b], pos(...c[a]), pos(...c[b])), out: inn[a] });
461
+ }
462
+ if (!crossings.length) continue;
463
+ // Each crossing leaving the solid (going counter-clockwise round the cell) joins the next one entering it; at a
464
+ // saddle, which pairs depends on the middle: solid there joins the two solid corners
465
+ const middle = val.reduce((s, x) => s + x, 0) / 4 >= iso;
466
+ for (let k = 0; k < crossings.length; k++) if (crossings[k].out) {
467
+ const m = crossings.length;
468
+ const to = crossings.length === 4 && !middle ? crossings[(k + m - 1) % m] : crossings[(k + 1) % m];
469
+ next.set(crossings[k].key, to.key);
470
+ }
471
+ }
472
+ const loops = [], seen = new Set();
473
+ for (const start of next.keys()) {
474
+ if (seen.has(start)) continue;
475
+ const loop = [];
476
+ for (let k = start; !seen.has(k); k = next.get(k)) { seen.add(k); loop.push(point.get(k)); }
477
+ loops.push(loop);
478
+ }
479
+ return loops.map((l) => simplify(taubin(l, smooth), tolerance)).filter((l) => l.length >= 3 && Math.abs(area(l)) >= minArea);
480
+ }
481
+
482
+ /**
483
+ * The area of a closed loop in mm², positive if counter-clockwise.
484
+ * @param {[number, number][]} loop
485
+ * @returns {number}
486
+ */
487
+ export function area(loop) {
488
+ let s = 0;
489
+ for (let i = 0; i < loop.length; i++) { const [x0, y0] = loop[i], [x1, y1] = loop[(i + 1) % loop.length]; s += x0 * y1 - x1 * y0; }
490
+ return s / 2;
491
+ }
492
+
493
+ // Taubin smoothing on a closed loop: a shrinking step then a growing one, so corners round without the loop shrinking
494
+ function taubin(loop, passes, lambda = 0.5, mu = -0.53) {
495
+ let p = loop;
496
+ for (let k = 0; k < passes * 2; k++) {
497
+ const f = k % 2 ? mu : lambda, n = p.length;
498
+ p = p.map((q, i) => { const a = p[(i + n - 1) % n], b = p[(i + 1) % n]; return [q[0] + f * ((a[0] + b[0]) / 2 - q[0]), q[1] + f * ((a[1] + b[1]) / 2 - q[1])]; });
499
+ }
500
+ return p;
501
+ }
502
+
503
+ // Drop points that lie within tolerance of the line through their neighbours (one pass, then repeat while it helps)
504
+ function simplify(loop, tolerance) {
505
+ let p = loop, dropped = true;
506
+ while (dropped && p.length > 3) {
507
+ dropped = false;
508
+ const out = [];
509
+ for (let i = 0; i < p.length; i++) {
510
+ const a = out.length ? out[out.length - 1] : p[(i + p.length - 1) % p.length], q = p[i], b = p[(i + 1) % p.length];
511
+ const len = Math.hypot(b[0] - a[0], b[1] - a[1]), off = len ? Math.abs((b[0] - a[0]) * (a[1] - q[1]) - (a[0] - q[0]) * (b[1] - a[1])) / len : 0;
512
+ if (off < tolerance && p.length - (i - out.length) > 3) { dropped = true; continue; }
513
+ out.push(q);
514
+ }
515
+ p = out;
516
+ }
517
+ return p;
518
+ }
519
+
520
+ /**
521
+ * A 3D result's surface at density 0.5: a closed triangle mesh in mm, outward-facing, smoothed (Taubin, which keeps
522
+ * the size). The densities are averaged to the cells' corners, with a layer of empty corners round the outside so the
523
+ * surface closes, and each cube between corners is split into six tetrahedra, all along the same diagonal, so
524
+ * neighbouring cubes cut their shared faces the same way and the surface has no gaps (marching tetrahedra).
525
+ * @param {{ nx: number, ny: number, nz: number, h: number }} size @param {ArrayLike<number>} density @param {number[]} origin
526
+ * 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
527
+ * base on the bed) keeps that face flat, and the walls rising from it don't lean out.
528
+ * @param {{ smooth?: number, iso?: number }} [options] iso: the density the surface is drawn at (0.5)
529
+ * @returns {{ vertices: number[][], faces: number[][] }}
530
+ */
531
+ export function surface({ nx, ny, nz, h }, density, origin = [0, 0, 0], { smooth = 4, iso = 0.5 } = {}) {
532
+ const W = nx + 3, H = ny + 3, D = nz + 3, v = new Float64Array(W * H * D), id = (i, j, k) => (k * H + j) * W + i;
533
+ // Each corner: the average of the cubes round it that are in the grid (on the grid's faces, only those inside it, so
534
+ // material reaching a face reads as solid there, not half)
535
+ for (let k = 0; k <= nz; k++) for (let j = 0; j <= ny; j++) for (let i = 0; i <= nx; i++) {
536
+ let s = 0, count = 0;
537
+ for (let c = k - 1; c <= k; c++) for (let b = j - 1; b <= j; b++) for (let a = i - 1; a <= i; a++) if (a >= 0 && a < nx && b >= 0 && b < ny && c >= 0 && c < nz) { s += density[(c * ny + b) * nx + a]; count++; }
538
+ v[id(i + 1, j + 1, k + 1)] = s / count;
539
+ }
540
+ const corner = [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]];
541
+ const tets = [[0, 1, 2, 6], [0, 2, 3, 6], [0, 3, 7, 6], [0, 7, 4, 6], [0, 4, 5, 6], [0, 5, 1, 6]];
542
+ const pos = (n) => { const i = n % W, j = Math.floor(n / W) % H, k = Math.floor(n / (W * H)); return [origin[0] + (i - 1) * h, origin[1] + (j - 1) * h, origin[2] + (k - 1) * h]; };
543
+ const vertices = [], faces = [], onEdge = new Map();
544
+ const crossing = (a, b) => { // the point where the density crosses iso on the edge between corners a and b, shared
545
+ const key = a < b ? a * W * H * D + b : b * W * H * D + a;
546
+ let n = onEdge.get(key);
547
+ if (n === undefined) {
548
+ const t = Math.min(0.999, Math.max(0.001, (iso - v[a]) / (v[b] - v[a]))), pa = pos(a), pb = pos(b);
549
+ n = vertices.length; vertices.push([0, 1, 2].map((q) => pa[q] + t * (pb[q] - pa[q]))); onEdge.set(key, n);
550
+ }
551
+ return n;
552
+ };
553
+ // A triangle, turned to face away from the solid: its normal pointing from an inside corner towards an outside one
554
+ const emit = (a, b, c, from, to) => {
555
+ const [p, q, r] = [vertices[a], vertices[b], vertices[c]], pf = pos(from), pt = pos(to);
556
+ const n = [(q[1] - p[1]) * (r[2] - p[2]) - (q[2] - p[2]) * (r[1] - p[1]), (q[2] - p[2]) * (r[0] - p[0]) - (q[0] - p[0]) * (r[2] - p[2]), (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0])];
557
+ faces.push(n[0] * (pt[0] - pf[0]) + n[1] * (pt[1] - pf[1]) + n[2] * (pt[2] - pf[2]) >= 0 ? [a, b, c] : [a, c, b]);
558
+ };
559
+ for (let k = 0; k < D - 1; k++) for (let j = 0; j < H - 1; j++) for (let i = 0; i < W - 1; i++) {
560
+ const cube = corner.map(([a, b, c]) => id(i + a, j + b, k + c));
561
+ if (cube.every((n) => v[n] < iso) || cube.every((n) => v[n] >= iso)) continue;
562
+ for (const t of tets) {
563
+ const p = t.map((q) => cube[q]), inn = p.filter((n) => v[n] >= iso), out = p.filter((n) => v[n] < iso);
564
+ if (inn.length === 1 || inn.length === 3) { // one corner apart from the other three: a triangle round it
565
+ const [lone, rest, from, to] = inn.length === 1 ? [inn[0], out, inn[0], out[0]] : [out[0], inn, inn[0], out[0]];
566
+ emit(crossing(lone, rest[0]), crossing(lone, rest[1]), crossing(lone, rest[2]), from, to);
567
+ } else if (inn.length === 2) { // two and two: a quad, as two triangles
568
+ const [a, b] = inn, [c, d] = out, q = [crossing(a, c), crossing(a, d), crossing(b, d), crossing(b, c)];
569
+ emit(q[0], q[1], q[2], a, c); emit(q[0], q[2], q[3], a, c);
570
+ }
571
+ }
572
+ }
573
+ // Where material reaches the grid's face, the surface closes in the empty layer outside it: those crossings come
574
+ // back onto the face, so it's flat there, and every vertex on a face stays where it is
575
+ const lo = origin, hi = [origin[0] + nx * h, origin[1] + ny * h, origin[2] + nz * h], near = h * 0.01;
576
+ const pinned = vertices.map((p) => p.map((x, q) => (x < lo[q] + near ? lo[q] : x > hi[q] - near ? hi[q] : null)));
577
+ for (let n = 0; n < vertices.length; n++) for (let q = 0; q < 3; q++) if (pinned[n][q] !== null) vertices[n][q] = pinned[n][q];
578
+ // ... and holds still: one on the bed that moved sideways would tip the wall above it out over the edge
579
+ const held = pinned.map((p) => p.some((x) => x !== null));
580
+ // Taubin smoothing: each vertex moves towards its neighbours' average, then back a little further, so the surface
581
+ // rounds off its steps without shrinking
582
+ const nb = vertices.map(() => new Set());
583
+ for (const [a, b, c] of faces) { nb[a].add(b).add(c); nb[b].add(a).add(c); nb[c].add(a).add(b); }
584
+ const ring = nb.map((s) => Int32Array.from(s));
585
+ let pts = vertices;
586
+ for (let pass = 0; pass < smooth * 2; pass++) {
587
+ const f = pass % 2 ? -0.53 : 0.5;
588
+ pts = pts.map((p, n) => {
589
+ const r = ring[n];
590
+ if (!r.length) return p;
591
+ const avg = [0, 0, 0];
592
+ for (const m of r) for (let q = 0; q < 3; q++) avg[q] += pts[m][q] / r.length;
593
+ return held[n] ? p : p.map((x, q) => Math.min(hi[q], Math.max(lo[q], x + f * (avg[q] - x))));
594
+ });
595
+ }
596
+ return { vertices: pts, faces };
597
+ }
598
+
599
+ const fmt = (n) => String(Number(n.toFixed(2)));