@rulecad/topopt 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +40 -6
  2. package/package.json +3 -3
  3. package/topopt.d.mts +109 -43
  4. package/topopt.mjs +376 -92
package/README.md CHANGED
@@ -1,8 +1,9 @@
1
1
  # @rulecad/topopt
2
2
 
3
- Topology optimisation for flat parts: where to put a fixed amount of material in a region so the part is as stiff as
4
- possible under its loads. Give it the space a part may fill, the bosses it must keep, the holes it must avoid, where it's
5
- held and how it's loaded, and it returns outlines ready to extrude. No dependencies but
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
6
7
  [@rulecad/fea](../fea); runs in browsers and Node.
7
8
 
8
9
  ```js
@@ -21,6 +22,25 @@ result.cases; // [{ name: 'down', deflection (mm along the load), stiffness
21
22
  const loops = outlines(spec.grid, result.density, spec.origin); // closed loops, solid on the left
22
23
  ```
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 can be a teardrop: `teardrop: '-z'` for a boss, `'+z'` for a hole, or any
29
+ direction across its axis. It gets a 45° point that way, 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, { overhang: { up: '+z', angle: 45 } });
42
+ ```
43
+
24
44
  ## How it works
25
45
 
26
46
  The density method (SIMP: solid isotropic material with penalisation). Each cell has a density from 0 to 1, starting
@@ -38,13 +58,20 @@ Two more steps shape the result:
38
58
  - **A density filter** averages each cell with its neighbours. It sets the thinnest member and prevents chequerboard
39
59
  patterns.
40
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.
41
64
 
42
- Several load cases are optimised together by weight. `model(spec)` exposes the analysis and its gradient, for other
43
- update methods.
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.
44
67
 
45
- `outlines` traces the result's edges at density 0.5 (marching squares), smooths them (Taubin, which keeps the size),
68
+ `outlines` traces a 2D result's edges at density 0.5 (marching squares), smooths them (Taubin, which keeps the size),
46
69
  and drops holes and islands smaller than `minArea`.
47
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
+
48
75
  ## Checked against the published code
49
76
 
50
77
  With projection off, it matches a line-by-line port of the 88-line MATLAB code (`reference/top88.py`) step for step:
@@ -52,6 +79,9 @@ With projection off, it matches a line-by-line port of the 88-line MATLAB code (
52
79
  - **The MBB beam** (60 × 20, volume 0.5): 127 steps to a compliance of 218.80.
53
80
  - **A short cantilever** (48 × 24, volume 0.4): 100 steps to 99.49.
54
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
+
55
85
  Its gradients agree with finite differences through the filter and the projection.
56
86
 
57
87
  ## Glossary
@@ -67,4 +97,8 @@ Its gradients agree with finite differences through the filter and the projectio
67
97
  of code. *Structural and Multidisciplinary Optimization* 43, 1–16.
68
98
  - Wang, Lazarov, Sigmund (2011). On projection methods, convergence and robust formulations in topology optimization.
69
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.
70
104
  - Taubin (1995). A signal processing approach to fair surface design. *SIGGRAPH '95*, 351–358.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@rulecad/topopt",
3
- "version": "0.1.0",
4
- "description": "Topology optimisation for flat parts: the stiffest layout of a fixed amount of material, as outlines ready to extrude.",
3
+ "version": "0.2.1",
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": {
7
7
  "types": "./topopt.d.mts",
@@ -33,7 +33,7 @@
33
33
  "test": "node --test"
34
34
  },
35
35
  "dependencies": {
36
- "@rulecad/fea": "^0.1.0"
36
+ "@rulecad/fea": "^0.2.0"
37
37
  },
38
38
  "types": "./topopt.d.mts"
39
39
  }
package/topopt.d.mts CHANGED
@@ -1,6 +1,11 @@
1
- /** @typedef {{ at: [number, number], r: number } | { at: [number, number], size: [number, number] } | { points: [number, number][] }} Region a circle, a rectangle (centred), or a polygon, in mm */
2
- /** @typedef {{ at: [number, number], r?: number, fix?: 'xy' | 'x' | 'y' }} Support holds the nodes within r of at (on solid material) */
3
- /** @typedef {{ at: [number, number], r?: number, force: [number, number], case?: string }} Load a force in N, shared by the nodes within r of at */
1
+ /**
2
+ * @typedef {{ at: number[], r: number } | { at: number[], size: number[] } | { at: number[], r: number, length: number, axis?: 'x' | 'y' | 'z', teardrop?: string } | { 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', '-y', …: a 45° point that way, across the axis, 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 */
4
9
  /**
5
10
  * @typedef {object} Problem
6
11
  * @property {Region | Region[]} space where material may go
@@ -10,51 +15,72 @@
10
15
  * @property {Load[]} loads each in its load case (default "load"); cases are optimised together
11
16
  * @property {Record<string, number>} [cases] each case's weight (default 1)
12
17
  * @property {{ E: number, nu: number }} material
13
- * @property {number} thickness mm
18
+ * @property {number} [thickness] mm, for a 2D problem
14
19
  * @property {number} cell the grid's cell size, mm
15
20
  * @property {number} volume the share of the space to fill, 0 to 1 (keep regions count towards it)
16
21
  * @property {number} [filter] the filter radius in mm: about the thinnest member (default 1.5 cells)
17
22
  * @property {number} [penal] the penalty (default 3)
18
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
19
25
  * @property {number} [steps] at most this many steps (default 300)
20
26
  */
21
27
  /**
22
28
  * A problem described in shapes, on a grid: each cell inside the space (or a keep region) is free, kept or avoided;
23
- * supports and loads go on the nodes near them that touch material that may be solid.
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.
24
31
  * @param {Problem} p
25
- * @returns {object} a spec for optimise(), with origin (the grid's lower-left corner, mm) and regions for outlines
32
+ * @returns {object} a spec for optimise(), with origin (the grid's lowest corner, mm) and regions
26
33
  */
27
34
  export function discretise(p: Problem): object;
28
35
  /**
29
36
  * The density filter: each cell's filtered density is the weighted average of the cells within radius (weights
30
37
  * falling linearly to 0 at the radius). apply filters densities; adjoint carries sensitivities back through it.
31
- * @param {{ nx: number, ny: number }} size @param {number} radius in cells
38
+ * @param {{ nx: number, ny: number, nz?: number }} size @param {number} radius in cells
32
39
  */
33
- export function densityFilter({ nx, ny }: {
40
+ export function densityFilter({ nx, ny, nz }: {
34
41
  nx: number;
35
42
  ny: number;
43
+ nz?: number;
36
44
  }, radius: number): {
37
45
  apply(x: any, out: any): any;
38
46
  adjoint(x: any, out: any): any;
39
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
+ };
40
63
  /**
41
64
  * The problem as a function of the design densities x (one per cell, 0 to 1), at projection sharpness beta:
42
- * physical(x, beta) gives the densities the part is made of (filtered, projected, kept and avoided cells set);
43
- * evaluate(x, beta) analyses it and gives the compliance (summed over the load cases by weight, N·mm) and its
44
- * gradient with respect to x (dc), with the gradient of the material used (dv).
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 }).
45
69
  * @param {ReturnType<typeof discretise>} spec
46
- * @param {{ method?: 'direct' | 'cg', backend?: typeof jsBackend }} [options]
70
+ * @param {{ method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend }} [options]
47
71
  */
48
72
  export function model(spec: ReturnType<typeof discretise>, { method, backend }?: {
49
- method?: "direct" | "cg";
73
+ method?: "direct" | "cg" | "mg";
50
74
  backend?: typeof jsBackend;
51
75
  }): {
52
76
  physical: (x: any, beta: any) => Float64Array<ArrayBuffer>;
53
- evaluate: (x: any, beta: any) => {
77
+ evaluate: (x: any, beta: any, { all }?: {
78
+ all?: boolean;
79
+ }) => {
54
80
  compliance: number;
55
81
  dc: Float64Array<ArrayBuffer>;
56
82
  dv: Float64Array<ArrayBuffer>;
57
- u: Float64Array<ArrayBufferLike>[];
83
+ u: any;
58
84
  cases: any;
59
85
  };
60
86
  cells: number;
@@ -64,7 +90,7 @@ export function model(spec: ReturnType<typeof discretise>, { method, backend }?:
64
90
  * The optimisation: from an even spread, step by step, until the densities stop changing (less than tol per step)
65
91
  * with projection at full sharpness, or steps run out.
66
92
  * @param {ReturnType<typeof discretise>} spec
67
- * @param {{ onStep?: (s: { step: number, steps: number, compliance: number, change: number, beta: number, density: Float64Array }) => void, method?: 'direct' | 'cg', backend?: typeof jsBackend, tol?: number, move?: number }} [options]
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]
68
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 }}
69
95
  * each case's deflection is along its load (mm, compliance over the load's size), stiffness the load over that (N/mm)
70
96
  */
@@ -77,7 +103,7 @@ export function optimise(spec: ReturnType<typeof discretise>, { onStep, method,
77
103
  beta: number;
78
104
  density: Float64Array;
79
105
  }) => void;
80
- method?: "direct" | "cg";
106
+ method?: "direct" | "cg" | "mg";
81
107
  backend?: typeof jsBackend;
82
108
  tol?: number;
83
109
  move?: number;
@@ -96,6 +122,18 @@ export function optimise(spec: ReturnType<typeof discretise>, { onStep, method,
96
122
  history: number[];
97
123
  seconds: number;
98
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[];
99
137
  /**
100
138
  * The edges of a result at density 0.5 as closed loops in mm (marching squares on the densities averaged to the
101
139
  * cells' corners), solid on the left: outer edges counter-clockwise, holes clockwise. Smoothed (Taubin, which keeps
@@ -120,45 +158,69 @@ export function outlines({ nx, ny, h }: {
120
158
  */
121
159
  export function area(loop: [number, number][]): number;
122
160
  /**
123
- * Whether point pt is inside a region.
124
- * @param {Region} r @param {[number, number]} pt
125
- * @returns {boolean}
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, overhang?: { up: string, angle: number } }} [options] iso: the density the
169
+ * surface is drawn at (0.5). overhang: the build direction ('+z') and the printer's overhang limit (degrees from
170
+ * vertical): faces smoothing left past it are tipped back to it.
171
+ * @returns {{ vertices: number[][], faces: number[][] }}
126
172
  */
127
- export function inside(r: Region, [x, y]: [number, number]): boolean;
128
- /**
129
- * A region's bounding box, [minX, minY, maxX, maxY] in mm.
130
- * @param {Region} r
131
- * @returns {[number, number, number, number]}
132
- */
133
- export function bounds(r: Region): [number, number, number, number];
173
+ export function surface({ nx, ny, nz, h }: {
174
+ nx: number;
175
+ ny: number;
176
+ nz: number;
177
+ h: number;
178
+ }, density: ArrayLike<number>, origin?: number[], { smooth, iso, overhang }?: {
179
+ smooth?: number;
180
+ iso?: number;
181
+ overhang?: {
182
+ up: string;
183
+ angle: number;
184
+ };
185
+ }): {
186
+ vertices: number[][];
187
+ faces: number[][];
188
+ };
134
189
  export { jsBackend };
190
+ export function inside(r: Region, pt: number[]): boolean;
135
191
  /**
136
- * a circle, a rectangle (centred), or a polygon, in mm
192
+ * in mm: a circle (2D) or sphere (3D) at, r; a box at (its centre), size; a cylinder at (its centre), r, length,
193
+ * along axis (default z; teardrop '+z', '-y', …: a 45° point that way, across the axis, so it prints); a polygon (2D);
194
+ * or a closed triangle mesh (3D: a design's part)
137
195
  */
138
196
  export type Region = {
139
- at: [number, number];
197
+ at: number[];
140
198
  r: number;
141
199
  } | {
142
- at: [number, number];
143
- size: [number, number];
200
+ at: number[];
201
+ size: number[];
202
+ } | {
203
+ at: number[];
204
+ r: number;
205
+ length: number;
206
+ axis?: "x" | "y" | "z";
207
+ teardrop?: string;
144
208
  } | {
145
209
  points: [number, number][];
210
+ } | {
211
+ triangles: number[][][];
146
212
  };
147
213
  /**
148
- * holds the nodes within r of at (on solid material)
214
+ * holds the nodes in the region (on material): fix the directions, 'xy' or 'xyz' (default all)
149
215
  */
150
- export type Support = {
151
- at: [number, number];
152
- r?: number;
153
- fix?: "xy" | "x" | "y";
216
+ export type Support = Region & {
217
+ fix?: string;
154
218
  };
155
219
  /**
156
- * a force in N, shared by the nodes within r of at
220
+ * a force in N, shared by the nodes in the region
157
221
  */
158
- export type Load = {
159
- at: [number, number];
160
- r?: number;
161
- force: [number, number];
222
+ export type Load = Region & {
223
+ force: number[];
162
224
  case?: string;
163
225
  };
164
226
  export type Problem = {
@@ -188,9 +250,9 @@ export type Problem = {
188
250
  nu: number;
189
251
  };
190
252
  /**
191
- * mm
253
+ * mm, for a 2D problem
192
254
  */
193
- thickness: number;
255
+ thickness?: number;
194
256
  /**
195
257
  * the grid's cell size, mm
196
258
  */
@@ -211,6 +273,10 @@ export type Problem = {
211
273
  * sharpen with Heaviside projection (default true)
212
274
  */
213
275
  projection?: boolean;
276
+ /**
277
+ * printed this way up ('+z', '-y', …): only material supported from below at 45° or less
278
+ */
279
+ overhang?: string;
214
280
  /**
215
281
  * at most this many steps (default 300)
216
282
  */
package/topopt.mjs CHANGED
@@ -1,21 +1,29 @@
1
- // Topology optimisation for flat parts: where to put a fixed amount of material in a region so the part is as stiff as
2
- // possible under its loads. The density method (SIMP: solid isotropic material with penalisation): every cell has a
3
- // density from 0 to 1, stiffness grows as density cubed (so part-solid cells are poor value and the result settles
4
- // into solid and empty), and each step moves material towards the cells that stiffen the part most. With a density
5
- // filter (it sets the thinnest member) and Heaviside projection (it sharpens the result). After Andreassen et al.
6
- // (2011), "Efficient topology optimization in MATLAB using 88 lines of code", and Wang, Lazarov and Sigmund (2011).
7
- // No dependencies but @rulecad/fea; runs in browsers and Node. Millimetres, newtons, MPa.
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.
8
10
  //
9
11
  // optimise(spec) the method itself, on a grid: densities, supports and loads by dof
10
12
  // discretise(problem) a problem in shapes (a region, bosses to keep, holes to avoid, loads at points) to a spec
11
- // outlines(result) the result's edges as closed loops in mm, solid on the left, smoothed: ready to extrude
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
12
15
  import { grid as makeGrid, cellStiffness, solve, positions, jsBackend } from '@rulecad/fea';
13
16
 
14
17
  export { jsBackend };
15
18
 
16
- /** @typedef {{ at: [number, number], r: number } | { at: [number, number], size: [number, number] } | { points: [number, number][] }} Region a circle, a rectangle (centred), or a polygon, in mm */
17
- /** @typedef {{ at: [number, number], r?: number, fix?: 'xy' | 'x' | 'y' }} Support holds the nodes within r of at (on solid material) */
18
- /** @typedef {{ at: [number, number], r?: number, force: [number, number], case?: string }} Load a force in N, shared by the nodes within r of at */
19
+ /**
20
+ * @typedef {{ at: number[], r: number } | { at: number[], size: number[] } | { at: number[], r: number, length: number, axis?: 'x' | 'y' | 'z', teardrop?: string } | { 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', '-y', …: a 45° point that way, across the axis, 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 */
19
27
  /**
20
28
  * @typedef {object} Problem
21
29
  * @property {Region | Region[]} space where material may go
@@ -25,63 +33,78 @@ export { jsBackend };
25
33
  * @property {Load[]} loads each in its load case (default "load"); cases are optimised together
26
34
  * @property {Record<string, number>} [cases] each case's weight (default 1)
27
35
  * @property {{ E: number, nu: number }} material
28
- * @property {number} thickness mm
36
+ * @property {number} [thickness] mm, for a 2D problem
29
37
  * @property {number} cell the grid's cell size, mm
30
38
  * @property {number} volume the share of the space to fill, 0 to 1 (keep regions count towards it)
31
39
  * @property {number} [filter] the filter radius in mm: about the thinnest member (default 1.5 cells)
32
40
  * @property {number} [penal] the penalty (default 3)
33
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
34
43
  * @property {number} [steps] at most this many steps (default 300)
35
44
  */
36
45
 
37
46
  /**
38
47
  * A problem described in shapes, on a grid: each cell inside the space (or a keep region) is free, kept or avoided;
39
- * supports and loads go on the nodes near them that touch material that may be solid.
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.
40
50
  * @param {Problem} p
41
- * @returns {object} a spec for optimise(), with origin (the grid's lower-left corner, mm) and regions for outlines
51
+ * @returns {object} a spec for optimise(), with origin (the grid's lowest corner, mm) and regions
42
52
  */
43
53
  export function discretise(p) {
44
- const space = [p.space].flat(), keep = p.keep || [], avoid = p.avoid || [];
54
+ const space = [p.space].flat(), keep = p.keep || [], avoid = p.avoid || [], dim = dimension(space[0]);
45
55
  if (!(p.cell > 0)) throw new Error('the cell size must be more than 0 mm');
46
- const box = [...space, ...keep].map(bounds).reduce((a, b) => [Math.min(a[0], b[0]), Math.min(a[1], b[1]), Math.max(a[2], b[2]), Math.max(a[3], b[3])]);
47
- const nx = Math.max(1, Math.round((box[2] - box[0]) / p.cell)), ny = Math.max(1, Math.round((box[3] - box[1]) / p.cell));
48
- const g = makeGrid({ nx, ny, h: p.cell }), origin = [box[0], box[1]];
49
- // Each cell by its centre: 1 kept, -1 avoided or outside (-2 outside, which doesn't count towards the volume), 0 free
50
- const passive = new Int8Array(nx * ny);
51
- for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) {
52
- const c = [origin[0] + (i + 0.5) * p.cell, origin[1] + (j + 0.5) * p.cell];
53
- const inKeep = keep.some((r) => inside(r, c));
54
- passive[j * nx + i] = avoid.some((r) => inside(r, c)) ? (inKeep || space.some((r) => inside(r, c)) ? -1 : -2) : inKeep ? 1 : space.some((r) => inside(r, c)) ? 0 : -2;
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;
55
65
  }
56
- const at = positions(g).map(([x, y]) => [x + origin[0], y + origin[1]]);
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]));
57
78
  // A node is on material if a cell it's a corner of may be solid
58
- const onMaterial = new Uint8Array(g.nodes);
59
- for (let e = 0; e < nx * ny; e++) if (passive[e] >= 0) for (let k = 0; k < 4; k++) onMaterial[g.edof[e * 8 + 2 * k] / 2] = 1;
60
- const near = (pt, r = 0, what) => {
61
- const reach = r + p.cell * 0.75, found = [];
62
- for (let n = 0; n < g.nodes; n++) if (onMaterial[n] && Math.hypot(at[n][0] - pt[0], at[n][1] - pt[1]) <= reach) found.push(n);
63
- if (!found.length) throw new Error(`${what} at ${pt.map(fmt).join(', ')} isn't on any material: move it onto the space or a keep region, or give it a radius`);
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`);
64
87
  return found;
65
88
  };
66
- const fixed = new Uint8Array(g.dofs);
67
- for (const s of p.supports || []) for (const n of near(s.at, s.r, 'a support')) {
68
- if ((s.fix || 'xy').includes('x')) fixed[2 * n] = 1;
69
- if ((s.fix || 'xy').includes('y')) fixed[2 * n + 1] = 1;
70
- }
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;
71
91
  const names = [...new Set((p.loads || []).map((l) => l.case || 'load'))];
72
92
  if (!names.length) throw new Error('a problem needs at least one load');
73
93
  const loads = names.map((name) => {
74
- const f = new Float64Array(g.dofs);
75
- for (const l of p.loads.filter((x) => (x.case || 'load') === name)) {
76
- const ns = near(l.at, l.r, `the load "${name}"`);
77
- for (const n of ns) { f[2 * n] += l.force[0] / ns.length; f[2 * n + 1] += l.force[1] / ns.length; }
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];
78
100
  }
79
- return { name, force: f, weight: p.cases?.[name] ?? 1, size: Math.hypot(...p.loads.filter((x) => (x.case || 'load') === name).reduce((s, l) => [s[0] + l.force[0], s[1] + l.force[1]], [0, 0])) };
101
+ return { name, force: f, weight: p.cases?.[name] ?? 1, size: Math.hypot(...total) };
80
102
  });
81
103
  return {
82
- grid: { nx, ny, h: p.cell }, origin, passive, fixed, loads,
104
+ grid: size, origin, passive, fixed, loads,
83
105
  material: p.material, thickness: p.thickness, volume: p.volume,
84
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 } : {}),
85
108
  regions: { keep, avoid },
86
109
  };
87
110
  }
@@ -89,17 +112,17 @@ export function discretise(p) {
89
112
  /**
90
113
  * The density filter: each cell's filtered density is the weighted average of the cells within radius (weights
91
114
  * falling linearly to 0 at the radius). apply filters densities; adjoint carries sensitivities back through it.
92
- * @param {{ nx: number, ny: number }} size @param {number} radius in cells
115
+ * @param {{ nx: number, ny: number, nz?: number }} size @param {number} radius in cells
93
116
  */
94
- export function densityFilter({ nx, ny }, radius) {
95
- const reach = Math.ceil(radius) - 1, cells = nx * ny;
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;
96
119
  // Each cell's neighbours and their weights, as flat arrays (row r's are at start[r] to start[r + 1])
97
120
  const start = new Int32Array(cells + 1), index = [], weight = [], total = new Float64Array(cells);
98
- for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) {
99
- const e = j * nx + i;
100
- 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++) {
101
- const w = radius - Math.hypot(a - i, b - j);
102
- if (w > 0) { index.push(b * nx + a); weight.push(w); total[e] += w; } // total: fewer neighbours at the edges
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
103
126
  }
104
127
  start[e + 1] = index.length;
105
128
  }
@@ -117,19 +140,80 @@ export function densityFilter({ nx, ny }, radius) {
117
140
  };
118
141
  }
119
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
+
120
202
  /**
121
203
  * The problem as a function of the design densities x (one per cell, 0 to 1), at projection sharpness beta:
122
- * physical(x, beta) gives the densities the part is made of (filtered, projected, kept and avoided cells set);
123
- * evaluate(x, beta) analyses it and gives the compliance (summed over the load cases by weight, N·mm) and its
124
- * gradient with respect to x (dc), with the gradient of the material used (dv).
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 }).
125
208
  * @param {ReturnType<typeof discretise>} spec
126
- * @param {{ method?: 'direct' | 'cg', backend?: typeof jsBackend }} [options]
209
+ * @param {{ method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend }} [options]
127
210
  */
128
- export function model(spec, { method = 'direct', backend = jsBackend } = {}) {
129
- const { nx, ny } = spec.grid, cells = nx * ny, g = makeGrid(spec.grid), ke = cellStiffness(spec.material.nu);
130
- const { passive, penal, thickness } = spec, E = spec.material.E, Emin = E * 1e-9, eta = 0.5;
131
- const filter = densityFilter(spec.grid, spec.filter / spec.grid.h);
132
- const tilde = new Float64Array(cells), phys = new Float64Array(cells), scale = new Float64Array(cells), back = new Float64Array(cells);
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);
133
217
  const fixedValue = (p) => (p === 1 ? 1 : 0);
134
218
  // Heaviside projection about eta: steeper as beta grows, so densities are pushed to 0 or 1 (Wang, Lazarov, Sigmund 2011)
135
219
  const denominator = (beta) => Math.tanh(beta * eta) + Math.tanh(beta * (1 - eta));
@@ -137,33 +221,42 @@ export function model(spec, { method = 'direct', backend = jsBackend } = {}) {
137
221
  const slope = (t, beta) => (spec.projection ? (beta * (1 - Math.tanh(beta * (t - eta)) ** 2)) / denominator(beta) : 1);
138
222
  const physical = (x, beta) => {
139
223
  filter.apply(x, tilde);
140
- for (let e = 0; e < cells; e++) phys[e] = passive[e] ? fixedValue(passive[e]) : project(tilde[e], beta);
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);
141
226
  return phys;
142
227
  };
143
228
  let last = null;
144
- const evaluate = (x, beta) => {
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 } = {}) => {
145
231
  physical(x, beta);
146
- for (let e = 0; e < cells; e++) scale[e] = thickness * (Emin + Math.pow(phys[e], penal) * (E - Emin));
147
- const { u } = solve(g, { scale, ke, fixed: spec.fixed, loads: spec.loads.map((l) => l.force), method, backend, start: last });
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));
148
236
  last = u;
149
- // Compliance, and its gradient with respect to each cell's physical density: −p ρ^(p−1) (E − Emin) t · uₑᵀ kₑ uₑ
237
+ // Compliance, and its gradient with respect to each cell's physical density: −p ρ^(p−1) (E − Emin) size · uₑᵀ kₑ uₑ
150
238
  // (the load is fixed, so the adjoint is the displacement itself)
151
239
  let compliance = 0;
152
240
  const dc = new Float64Array(cells), dv = new Float64Array(cells);
153
241
  spec.loads.forEach((l, c) => {
154
242
  const w = l.weight, uc = u[c];
243
+ if (!w || !active.includes(c)) return;
155
244
  for (let e = 0; e < cells; e++) {
156
245
  let ce = 0;
157
- for (let a = 0; a < 8; a++) { let s = 0; for (let b = 0; b < 8; b++) s += ke[a * 8 + b] * uc[g.edof[e * 8 + b]]; ce += uc[g.edof[e * 8 + a]] * s; }
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; }
158
248
  compliance += w * scale[e] * ce;
159
- dc[e] -= w * penal * Math.pow(phys[e], penal - 1) * (E - Emin) * thickness * ce;
249
+ dc[e] -= w * penal * Math.pow(phys[e], penal - 1) * (E - Emin) * size * ce;
160
250
  }
161
251
  });
162
- // Back through the projection and the filter to the design densities; kept and avoided cells don't change
163
- for (let e = 0; e < cells; e++) { const s = passive[e] ? 0 : slope(tilde[e], beta); dc[e] *= s; dv[e] = s; }
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); }
164
256
  filter.adjoint(dc, back); dc.set(back);
165
257
  filter.adjoint(dv, back); dv.set(back);
166
258
  const cases = spec.loads.map((l, c) => {
259
+ if (!u[c]) return { name: l.name, compliance: NaN, deflection: NaN, stiffness: NaN };
167
260
  const ci = jsBackend.dot(l.force, u[c]), deflection = l.size ? ci / l.size : 0;
168
261
  return { name: l.name, compliance: ci, deflection, stiffness: deflection ? l.size / deflection : Infinity };
169
262
  });
@@ -176,11 +269,11 @@ export function model(spec, { method = 'direct', backend = jsBackend } = {}) {
176
269
  * The optimisation: from an even spread, step by step, until the densities stop changing (less than tol per step)
177
270
  * with projection at full sharpness, or steps run out.
178
271
  * @param {ReturnType<typeof discretise>} spec
179
- * @param {{ onStep?: (s: { step: number, steps: number, compliance: number, change: number, beta: number, density: Float64Array }) => void, method?: 'direct' | 'cg', backend?: typeof jsBackend, tol?: number, move?: number }} [options]
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]
180
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 }}
181
274
  * each case's deflection is along its load (mm, compliance over the load's size), stiffness the load over that (N/mm)
182
275
  */
183
- export function optimise(spec, { onStep, method = 'direct', backend = jsBackend, tol = 0.01, move = 0.2 } = {}) {
276
+ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01, move = 0.2 } = {}) {
184
277
  const started = Date.now(), m = model(spec, { method, backend }), { cells, passive } = m;
185
278
  const inSpace = passive.reduce((s, p) => s + (p !== -2 ? 1 : 0), 0), kept = passive.reduce((s, p) => s + (p === 1 ? 1 : 0), 0);
186
279
  const free = passive.reduce((s, p) => s + (p === 0 ? 1 : 0), 0), target = spec.volume * inSpace;
@@ -223,13 +316,119 @@ export function optimise(spec, { onStep, method = 'direct', backend = jsBackend,
223
316
  if (beta >= betaMax && (change < tol || settled)) { converged = true; break; }
224
317
  }
225
318
  // The final design, analysed as it is
226
- const final = m.evaluate(x, beta), phys = Float64Array.from(m.physical(x, beta));
319
+ const final = m.evaluate(x, beta, { all: true }), phys = Float64Array.from(m.physical(x, beta));
227
320
  return {
228
321
  density: phys, compliance: final.compliance, cases: final.cases,
229
322
  volume: phys.reduce((s, v, e) => s + (passive[e] !== -2 ? v : 0), 0) / inSpace, steps: step, converged, history, seconds: (Date.now() - started) / 1000,
230
323
  };
231
324
  }
232
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 with a 45° point below it (a boss) or above it (a hole), so it prints
364
+ // unsupported. Along the build, it's a plain cylinder.
365
+ const pa = r.teardrop ? 'xyz'.indexOf(r.teardrop[1]) : -1, point = pa >= 0 && pa !== ax ? (r.teardrop[0] === '-' ? -1 : 1) : 0, side = others.find((a) => a !== pa);
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[pa] - r.at[pa]);
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
+ const pa = r.teardrop && r.length != null ? 'xyz'.indexOf(r.teardrop[1]) : -1;
425
+ if (pa >= 0 && pa !== 'xyz'.indexOf(r.axis || 'z')) { if (r.teardrop[0] === '-') lo[pa] = r.at[pa] - r.r * Math.SQRT2; else hi[pa] = r.at[pa] + r.r * Math.SQRT2; } // its point
426
+ return [...lo, ...hi];
427
+ }
428
+
429
+ // ---------- shapes from results ----------
430
+ // (Everything above decides the densities; everything below only draws them, so results can be kept by the code above)
431
+
233
432
  /**
234
433
  * The edges of a result at density 0.5 as closed loops in mm (marching squares on the densities averaged to the
235
434
  * cells' corners), solid on the left: outer edges counter-clockwise, holes clockwise. Smoothed (Taubin, which keeps
@@ -320,31 +519,116 @@ function simplify(loop, tolerance) {
320
519
  }
321
520
 
322
521
  /**
323
- * Whether point pt is inside a region.
324
- * @param {Region} r @param {[number, number]} pt
325
- * @returns {boolean}
522
+ * A 3D result's surface at density 0.5: a closed triangle mesh in mm, outward-facing, smoothed (Taubin, which keeps
523
+ * the size). The densities are averaged to the cells' corners, with a layer of empty corners round the outside so the
524
+ * surface closes, and each cube between corners is split into six tetrahedra, all along the same diagonal, so
525
+ * neighbouring cubes cut their shared faces the same way and the surface has no gaps (marching tetrahedra).
526
+ * @param {{ nx: number, ny: number, nz: number, h: number }} size @param {ArrayLike<number>} density @param {number[]} origin
527
+ * 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
528
+ * base on the bed) keeps that face flat, and the walls rising from it don't lean out.
529
+ * @param {{ smooth?: number, iso?: number, overhang?: { up: string, angle: number } }} [options] iso: the density the
530
+ * surface is drawn at (0.5). overhang: the build direction ('+z') and the printer's overhang limit (degrees from
531
+ * vertical): faces smoothing left past it are tipped back to it.
532
+ * @returns {{ vertices: number[][], faces: number[][] }}
326
533
  */
327
- export function inside(r, [x, y]) {
328
- if ('r' in r) return Math.hypot(x - r.at[0], y - r.at[1]) <= r.r;
329
- if ('size' in r) return Math.abs(x - r.at[0]) <= r.size[0] / 2 && Math.abs(y - r.at[1]) <= r.size[1] / 2;
330
- let c = false; // even-odd ray crossing
331
- const P = r.points;
332
- for (let i = 0, j = P.length - 1; i < P.length; j = i++) {
333
- 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;
534
+ export function surface({ nx, ny, nz, h }, density, origin = [0, 0, 0], { smooth = 4, iso = 0.5, overhang } = {}) {
535
+ 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;
536
+ // Each corner: the average of the cubes round it that are in the grid (on the grid's faces, only those inside it, so
537
+ // material reaching a face reads as solid there, not half)
538
+ for (let k = 0; k <= nz; k++) for (let j = 0; j <= ny; j++) for (let i = 0; i <= nx; i++) {
539
+ let s = 0, count = 0;
540
+ 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++; }
541
+ v[id(i + 1, j + 1, k + 1)] = s / count;
542
+ }
543
+ 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]];
544
+ 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]];
545
+ 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]; };
546
+ const vertices = [], faces = [], onEdge = new Map();
547
+ const crossing = (a, b) => { // the point where the density crosses iso on the edge between corners a and b, shared
548
+ const key = a < b ? a * W * H * D + b : b * W * H * D + a;
549
+ let n = onEdge.get(key);
550
+ if (n === undefined) {
551
+ const t = Math.min(0.999, Math.max(0.001, (iso - v[a]) / (v[b] - v[a]))), pa = pos(a), pb = pos(b);
552
+ n = vertices.length; vertices.push([0, 1, 2].map((q) => pa[q] + t * (pb[q] - pa[q]))); onEdge.set(key, n);
553
+ }
554
+ return n;
555
+ };
556
+ // A triangle, turned to face away from the solid: its normal pointing from an inside corner towards an outside one
557
+ const emit = (a, b, c, from, to) => {
558
+ const [p, q, r] = [vertices[a], vertices[b], vertices[c]], pf = pos(from), pt = pos(to);
559
+ 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])];
560
+ 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]);
561
+ };
562
+ for (let k = 0; k < D - 1; k++) for (let j = 0; j < H - 1; j++) for (let i = 0; i < W - 1; i++) {
563
+ const cube = corner.map(([a, b, c]) => id(i + a, j + b, k + c));
564
+ if (cube.every((n) => v[n] < iso) || cube.every((n) => v[n] >= iso)) continue;
565
+ for (const t of tets) {
566
+ const p = t.map((q) => cube[q]), inn = p.filter((n) => v[n] >= iso), out = p.filter((n) => v[n] < iso);
567
+ if (inn.length === 1 || inn.length === 3) { // one corner apart from the other three: a triangle round it
568
+ const [lone, rest, from, to] = inn.length === 1 ? [inn[0], out, inn[0], out[0]] : [out[0], inn, inn[0], out[0]];
569
+ emit(crossing(lone, rest[0]), crossing(lone, rest[1]), crossing(lone, rest[2]), from, to);
570
+ } else if (inn.length === 2) { // two and two: a quad, as two triangles
571
+ const [a, b] = inn, [c, d] = out, q = [crossing(a, c), crossing(a, d), crossing(b, d), crossing(b, c)];
572
+ emit(q[0], q[1], q[2], a, c); emit(q[0], q[2], q[3], a, c);
573
+ }
574
+ }
575
+ }
576
+ // Where material reaches the grid's face, the surface closes in the empty layer outside it: those crossings come
577
+ // back onto the face, so it's flat there, and every vertex on a face stays where it is
578
+ const lo = origin, hi = [origin[0] + nx * h, origin[1] + ny * h, origin[2] + nz * h], near = h * 0.01;
579
+ const pinned = vertices.map((p) => p.map((x, q) => (x < lo[q] + near ? lo[q] : x > hi[q] - near ? hi[q] : null)));
580
+ 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];
581
+ // ... and holds still: one on the bed that moved sideways would tip the wall above it out over the edge
582
+ const held = pinned.map((p) => p.some((x) => x !== null));
583
+ // Taubin smoothing: each vertex moves towards its neighbours' average, then back a little further, so the surface
584
+ // rounds off its steps without shrinking
585
+ const nb = vertices.map(() => new Set());
586
+ 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); }
587
+ const ring = nb.map((s) => Int32Array.from(s));
588
+ let pts = vertices;
589
+ for (let pass = 0; pass < smooth * 2; pass++) {
590
+ const f = pass % 2 ? -0.53 : 0.5;
591
+ pts = pts.map((p, n) => {
592
+ const r = ring[n];
593
+ if (!r.length) return p;
594
+ const avg = [0, 0, 0];
595
+ for (const m of r) for (let q = 0; q < 3; q++) avg[q] += pts[m][q] / r.length;
596
+ return held[n] ? p : p.map((x, q) => Math.min(hi[q], Math.max(lo[q], x + f * (avg[q] - x))));
597
+ });
334
598
  }
335
- return c;
599
+ if (overhang) steepen(pts, faces, held, overhang, lo, hi);
600
+ return { vertices: pts, faces };
336
601
  }
337
602
 
338
- /**
339
- * A region's bounding box, [minX, minY, maxX, maxY] in mm.
340
- * @param {Region} r
341
- * @returns {[number, number, number, number]}
342
- */
343
- export function bounds(r) {
344
- if ('r' in r) return [r.at[0] - r.r, r.at[1] - r.r, r.at[0] + r.r, r.at[1] + r.r];
345
- if ('size' in r) return [r.at[0] - r.size[0] / 2, r.at[1] - r.size[1] / 2, r.at[0] + r.size[0] / 2, r.at[1] + r.size[1] / 2];
346
- const xs = r.points.map((p) => p[0]), ys = r.points.map((p) => p[1]);
347
- return [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)];
603
+ // Faces past the overhang limit, tipped back to it. Optimised in cubes, a printable slope is a staircase of 45°, and
604
+ // smoothing leaves small faces either side of 45°. Each face facing down more steeply than the limit is turned about
605
+ // its centre, moving its corners along the build direction only, until it's a little inside the limit: about as much
606
+ // material is added as taken away. A corner shared by several such faces moves by their average; it's repeated until
607
+ // none are left. Flat faces (a bridge) and faces held on the grid's sides stay as they are.
608
+ function steepen(pts, faces, held, { up, angle }, lo, hi, passes = 200) {
609
+ const q = 'xyz'.indexOf(up[1]), s = up[0] === '-' ? -1 : 1, [a, b] = [0, 1, 2].filter((x) => x !== q);
610
+ const limit = Math.sin((angle * Math.PI) / 180), slope = 1.03 / Math.tan((angle * Math.PI) / 180);
611
+ for (let pass = 0; pass < passes; pass++) {
612
+ const move = new Float64Array(pts.length), count = new Uint16Array(pts.length);
613
+ let left = 0;
614
+ for (const f of faces) {
615
+ if (held[f[0]] && held[f[1]] && held[f[2]]) continue;
616
+ const [p, r, t] = f.map((n) => pts[n]), u = [r[0] - p[0], r[1] - p[1], r[2] - p[2]], w = [t[0] - p[0], t[1] - p[1], t[2] - p[2]];
617
+ const n = [u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]], len = Math.hypot(...n);
618
+ if (!len || (s * n[q]) / len >= -limit) continue;
619
+ // The face's plane as a height along the build direction over the other two: x_q = c + ga x_a + gb x_b
620
+ const ga = -n[a] / n[q], gb = -n[b] / n[q], g = Math.hypot(ga, gb);
621
+ if (g < 0.05) continue; // flat: a bridge, which turning won't help
622
+ left++;
623
+ const c = [0, 1, 2].map((x) => (p[x] + r[x] + t[x]) / 3), k = slope / g;
624
+ for (const m of f) {
625
+ const v = pts[m];
626
+ move[m] += c[q] + k * (ga * (v[a] - c[a]) + gb * (v[b] - c[b])) - v[q]; count[m]++;
627
+ }
628
+ }
629
+ if (!left) break;
630
+ for (let m = 0; m < pts.length; m++) if (count[m] && !held[m]) pts[m][q] = Math.min(hi[q], Math.max(lo[q], pts[m][q] + move[m] / count[m]));
631
+ }
348
632
  }
349
633
 
350
634
  const fmt = (n) => String(Number(n.toFixed(2)));