@rulecad/topopt 0.0.0-stage → 0.1.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,70 @@
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: 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
6
+ [@rulecad/fea](../fea); runs in browsers and Node.
7
+
8
+ ```js
9
+ import { discretise, optimise, outlines } from '@rulecad/topopt';
10
+
11
+ const spec = discretise({
12
+ space: { at: [60, 0], size: [140, 40] }, // where material may go (mm)
13
+ keep: [{ at: [0, 0], r: 6 }, { at: [120, 0], r: 5 }], // must stay solid
14
+ avoid: [{ at: [0, 0], r: 2.8 }, { at: [120, 0], r: 2.3 }], // must stay empty
15
+ supports: [{ at: [0, 0], r: 2.8 }], // held here
16
+ loads: [{ at: [120, 0], r: 2.3, force: [0, -20], case: 'down' }], // pushed here (N)
17
+ material: { E: 2680, nu: 0.36 }, thickness: 6, cell: 1, volume: 0.5, filter: 2.5,
18
+ });
19
+ const result = optimise(spec, { onStep: (s) => console.log(s.step, s.compliance) });
20
+ result.cases; // [{ name: 'down', deflection (mm along the load), stiffness (N/mm) }]
21
+ const loops = outlines(spec.grid, result.density, spec.origin); // closed loops, solid on the left
22
+ ```
23
+
24
+ ## How it works
25
+
26
+ The density method (SIMP: solid isotropic material with penalisation). Each cell has a density from 0 to 1, starting
27
+ even. On each step:
28
+
29
+ 1. **Analyse** the part (@rulecad/fea).
30
+ 2. **Work out each cell's effect on the compliance.** Compliance is how much the part gives under its loads, so lower
31
+ is stiffer; each cell's effect is its gradient.
32
+ 3. **Move material** towards the cells that stiffen the part most, keeping the total fixed (the optimality criteria
33
+ update).
34
+
35
+ Stiffness grows as density cubed, so part-solid cells are poor value and the result settles into solid and empty.
36
+ Two more steps shape the result:
37
+
38
+ - **A density filter** averages each cell with its neighbours. It sets the thinnest member and prevents chequerboard
39
+ patterns.
40
+ - **Heaviside projection** sharpens the result, more on each pass, until cells are solid or empty.
41
+
42
+ Several load cases are optimised together by weight. `model(spec)` exposes the analysis and its gradient, for other
43
+ update methods.
44
+
45
+ `outlines` traces the result's edges at density 0.5 (marching squares), smooths them (Taubin, which keeps the size),
46
+ and drops holes and islands smaller than `minArea`.
47
+
48
+ ## Checked against the published code
49
+
50
+ With projection off, it matches a line-by-line port of the 88-line MATLAB code (`reference/top88.py`) step for step:
51
+
52
+ - **The MBB beam** (60 × 20, volume 0.5): 127 steps to a compliance of 218.80.
53
+ - **A short cantilever** (48 × 24, volume 0.4): 100 steps to 99.49.
54
+
55
+ Its gradients agree with finite differences through the filter and the projection.
56
+
57
+ ## Glossary
58
+
59
+ - **Compliance:** the load times how far it moves (N·mm); the inverse of stiffness.
60
+ - **Volume:** the share of the space the result fills, 0 to 1.
61
+ - **Filter radius:** about the thinnest member, in mm.
62
+
63
+ ## Sources
64
+
65
+ - Bendsøe, Sigmund (2003). *Topology Optimization: Theory, Methods and Applications*. Springer.
66
+ - Andreassen, Clausen, Schevenels, Lazarov, Sigmund (2011). Efficient topology optimization in MATLAB using 88 lines
67
+ of code. *Structural and Multidisciplinary Optimization* 43, 1–16.
68
+ - Wang, Lazarov, Sigmund (2011). On projection methods, convergence and robust formulations in topology optimization.
69
+ *Structural and Multidisciplinary Optimization* 43, 767–784.
70
+ - 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.1.0",
4
+ "description": "Topology optimisation for flat parts: the stiffest layout of a fixed amount of material, as outlines ready to extrude.",
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.1.0"
37
+ },
38
+ "types": "./topopt.d.mts"
39
+ }
package/topopt.d.mts ADDED
@@ -0,0 +1,219 @@
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 */
4
+ /**
5
+ * @typedef {object} Problem
6
+ * @property {Region | Region[]} space where material may go
7
+ * @property {Region[]} [keep] must stay solid (bosses round bolt holes)
8
+ * @property {Region[]} [avoid] must stay empty (the holes, clearances); avoid wins over keep
9
+ * @property {Support[]} supports
10
+ * @property {Load[]} loads each in its load case (default "load"); cases are optimised together
11
+ * @property {Record<string, number>} [cases] each case's weight (default 1)
12
+ * @property {{ E: number, nu: number }} material
13
+ * @property {number} thickness mm
14
+ * @property {number} cell the grid's cell size, mm
15
+ * @property {number} volume the share of the space to fill, 0 to 1 (keep regions count towards it)
16
+ * @property {number} [filter] the filter radius in mm: about the thinnest member (default 1.5 cells)
17
+ * @property {number} [penal] the penalty (default 3)
18
+ * @property {boolean} [projection] sharpen with Heaviside projection (default true)
19
+ * @property {number} [steps] at most this many steps (default 300)
20
+ */
21
+ /**
22
+ * 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.
24
+ * @param {Problem} p
25
+ * @returns {object} a spec for optimise(), with origin (the grid's lower-left corner, mm) and regions for outlines
26
+ */
27
+ export function discretise(p: Problem): object;
28
+ /**
29
+ * The density filter: each cell's filtered density is the weighted average of the cells within radius (weights
30
+ * 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
32
+ */
33
+ export function densityFilter({ nx, ny }: {
34
+ nx: number;
35
+ ny: number;
36
+ }, radius: number): {
37
+ apply(x: any, out: any): any;
38
+ adjoint(x: any, out: any): any;
39
+ };
40
+ /**
41
+ * 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).
45
+ * @param {ReturnType<typeof discretise>} spec
46
+ * @param {{ method?: 'direct' | 'cg', backend?: typeof jsBackend }} [options]
47
+ */
48
+ export function model(spec: ReturnType<typeof discretise>, { method, backend }?: {
49
+ method?: "direct" | "cg";
50
+ backend?: typeof jsBackend;
51
+ }): {
52
+ physical: (x: any, beta: any) => Float64Array<ArrayBuffer>;
53
+ evaluate: (x: any, beta: any) => {
54
+ compliance: number;
55
+ dc: Float64Array<ArrayBuffer>;
56
+ dv: Float64Array<ArrayBuffer>;
57
+ u: Float64Array<ArrayBufferLike>[];
58
+ cases: any;
59
+ };
60
+ cells: number;
61
+ passive: any;
62
+ };
63
+ /**
64
+ * The optimisation: from an even spread, step by step, until the densities stop changing (less than tol per step)
65
+ * with projection at full sharpness, or steps run out.
66
+ * @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]
68
+ * @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
+ * each case's deflection is along its load (mm, compliance over the load's size), stiffness the load over that (N/mm)
70
+ */
71
+ export function optimise(spec: ReturnType<typeof discretise>, { onStep, method, backend, tol, move }?: {
72
+ onStep?: (s: {
73
+ step: number;
74
+ steps: number;
75
+ compliance: number;
76
+ change: number;
77
+ beta: number;
78
+ density: Float64Array;
79
+ }) => void;
80
+ method?: "direct" | "cg";
81
+ backend?: typeof jsBackend;
82
+ tol?: number;
83
+ move?: number;
84
+ }): {
85
+ density: Float64Array;
86
+ compliance: number;
87
+ cases: {
88
+ name: string;
89
+ compliance: number;
90
+ deflection: number;
91
+ stiffness: number;
92
+ }[];
93
+ volume: number;
94
+ steps: number;
95
+ converged: boolean;
96
+ history: number[];
97
+ seconds: number;
98
+ };
99
+ /**
100
+ * The edges of a result at density 0.5 as closed loops in mm (marching squares on the densities averaged to the
101
+ * cells' corners), solid on the left: outer edges counter-clockwise, holes clockwise. Smoothed (Taubin, which keeps
102
+ * the size), simplified, and with loops smaller than minArea (mm²) dropped.
103
+ * @param {{ nx: number, ny: number, h: number }} size @param {ArrayLike<number>} density @param {[number, number]} origin
104
+ * @param {{ smooth?: number, minArea?: number, tolerance?: number }} [options]
105
+ * @returns {[number, number][][]}
106
+ */
107
+ export function outlines({ nx, ny, h }: {
108
+ nx: number;
109
+ ny: number;
110
+ h: number;
111
+ }, density: ArrayLike<number>, origin?: [number, number], { smooth, minArea, tolerance }?: {
112
+ smooth?: number;
113
+ minArea?: number;
114
+ tolerance?: number;
115
+ }): [number, number][][];
116
+ /**
117
+ * The area of a closed loop in mm², positive if counter-clockwise.
118
+ * @param {[number, number][]} loop
119
+ * @returns {number}
120
+ */
121
+ export function area(loop: [number, number][]): number;
122
+ /**
123
+ * Whether point pt is inside a region.
124
+ * @param {Region} r @param {[number, number]} pt
125
+ * @returns {boolean}
126
+ */
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];
134
+ export { jsBackend };
135
+ /**
136
+ * a circle, a rectangle (centred), or a polygon, in mm
137
+ */
138
+ export type Region = {
139
+ at: [number, number];
140
+ r: number;
141
+ } | {
142
+ at: [number, number];
143
+ size: [number, number];
144
+ } | {
145
+ points: [number, number][];
146
+ };
147
+ /**
148
+ * holds the nodes within r of at (on solid material)
149
+ */
150
+ export type Support = {
151
+ at: [number, number];
152
+ r?: number;
153
+ fix?: "xy" | "x" | "y";
154
+ };
155
+ /**
156
+ * a force in N, shared by the nodes within r of at
157
+ */
158
+ export type Load = {
159
+ at: [number, number];
160
+ r?: number;
161
+ force: [number, number];
162
+ case?: string;
163
+ };
164
+ export type Problem = {
165
+ /**
166
+ * where material may go
167
+ */
168
+ space: Region | Region[];
169
+ /**
170
+ * must stay solid (bosses round bolt holes)
171
+ */
172
+ keep?: Region[];
173
+ /**
174
+ * must stay empty (the holes, clearances); avoid wins over keep
175
+ */
176
+ avoid?: Region[];
177
+ supports: Support[];
178
+ /**
179
+ * each in its load case (default "load"); cases are optimised together
180
+ */
181
+ loads: Load[];
182
+ /**
183
+ * each case's weight (default 1)
184
+ */
185
+ cases?: Record<string, number>;
186
+ material: {
187
+ E: number;
188
+ nu: number;
189
+ };
190
+ /**
191
+ * mm
192
+ */
193
+ thickness: number;
194
+ /**
195
+ * the grid's cell size, mm
196
+ */
197
+ cell: number;
198
+ /**
199
+ * the share of the space to fill, 0 to 1 (keep regions count towards it)
200
+ */
201
+ volume: number;
202
+ /**
203
+ * the filter radius in mm: about the thinnest member (default 1.5 cells)
204
+ */
205
+ filter?: number;
206
+ /**
207
+ * the penalty (default 3)
208
+ */
209
+ penal?: number;
210
+ /**
211
+ * sharpen with Heaviside projection (default true)
212
+ */
213
+ projection?: boolean;
214
+ /**
215
+ * at most this many steps (default 300)
216
+ */
217
+ steps?: number;
218
+ };
219
+ import { jsBackend } from '@rulecad/fea';
package/topopt.mjs ADDED
@@ -0,0 +1,350 @@
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.
8
+ //
9
+ // optimise(spec) the method itself, on a grid: densities, supports and loads by dof
10
+ // 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
12
+ import { grid as makeGrid, cellStiffness, solve, positions, jsBackend } from '@rulecad/fea';
13
+
14
+ export { jsBackend };
15
+
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 {object} Problem
21
+ * @property {Region | Region[]} space where material may go
22
+ * @property {Region[]} [keep] must stay solid (bosses round bolt holes)
23
+ * @property {Region[]} [avoid] must stay empty (the holes, clearances); avoid wins over keep
24
+ * @property {Support[]} supports
25
+ * @property {Load[]} loads each in its load case (default "load"); cases are optimised together
26
+ * @property {Record<string, number>} [cases] each case's weight (default 1)
27
+ * @property {{ E: number, nu: number }} material
28
+ * @property {number} thickness mm
29
+ * @property {number} cell the grid's cell size, mm
30
+ * @property {number} volume the share of the space to fill, 0 to 1 (keep regions count towards it)
31
+ * @property {number} [filter] the filter radius in mm: about the thinnest member (default 1.5 cells)
32
+ * @property {number} [penal] the penalty (default 3)
33
+ * @property {boolean} [projection] sharpen with Heaviside projection (default true)
34
+ * @property {number} [steps] at most this many steps (default 300)
35
+ */
36
+
37
+ /**
38
+ * 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.
40
+ * @param {Problem} p
41
+ * @returns {object} a spec for optimise(), with origin (the grid's lower-left corner, mm) and regions for outlines
42
+ */
43
+ export function discretise(p) {
44
+ const space = [p.space].flat(), keep = p.keep || [], avoid = p.avoid || [];
45
+ 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;
55
+ }
56
+ const at = positions(g).map(([x, y]) => [x + origin[0], y + origin[1]]);
57
+ // 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`);
64
+ return found;
65
+ };
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
+ }
71
+ const names = [...new Set((p.loads || []).map((l) => l.case || 'load'))];
72
+ if (!names.length) throw new Error('a problem needs at least one load');
73
+ 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; }
78
+ }
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])) };
80
+ });
81
+ return {
82
+ grid: { nx, ny, h: p.cell }, origin, passive, fixed, loads,
83
+ material: p.material, thickness: p.thickness, volume: p.volume,
84
+ filter: p.filter ?? p.cell * 1.5, penal: p.penal ?? 3, projection: p.projection ?? true, steps: p.steps ?? 300,
85
+ regions: { keep, avoid },
86
+ };
87
+ }
88
+
89
+ /**
90
+ * The density filter: each cell's filtered density is the weighted average of the cells within radius (weights
91
+ * 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
93
+ */
94
+ export function densityFilter({ nx, ny }, radius) {
95
+ const reach = Math.ceil(radius) - 1, cells = nx * ny;
96
+ // Each cell's neighbours and their weights, as flat arrays (row r's are at start[r] to start[r + 1])
97
+ 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
103
+ }
104
+ start[e + 1] = index.length;
105
+ }
106
+ const at = Int32Array.from(index), w = Float64Array.from(weight), scaled = new Float64Array(cells);
107
+ return {
108
+ apply(x, out) {
109
+ 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]; }
110
+ return out;
111
+ },
112
+ adjoint(x, out) {
113
+ for (let e = 0; e < cells; e++) scaled[e] = x[e] / total[e];
114
+ 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; }
115
+ return out;
116
+ },
117
+ };
118
+ }
119
+
120
+ /**
121
+ * 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).
125
+ * @param {ReturnType<typeof discretise>} spec
126
+ * @param {{ method?: 'direct' | 'cg', backend?: typeof jsBackend }} [options]
127
+ */
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);
133
+ const fixedValue = (p) => (p === 1 ? 1 : 0);
134
+ // Heaviside projection about eta: steeper as beta grows, so densities are pushed to 0 or 1 (Wang, Lazarov, Sigmund 2011)
135
+ const denominator = (beta) => Math.tanh(beta * eta) + Math.tanh(beta * (1 - eta));
136
+ const project = (t, beta) => (spec.projection ? (Math.tanh(beta * eta) + Math.tanh(beta * (t - eta))) / denominator(beta) : t);
137
+ const slope = (t, beta) => (spec.projection ? (beta * (1 - Math.tanh(beta * (t - eta)) ** 2)) / denominator(beta) : 1);
138
+ const physical = (x, beta) => {
139
+ filter.apply(x, tilde);
140
+ for (let e = 0; e < cells; e++) phys[e] = passive[e] ? fixedValue(passive[e]) : project(tilde[e], beta);
141
+ return phys;
142
+ };
143
+ let last = null;
144
+ const evaluate = (x, beta) => {
145
+ 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 });
148
+ last = u;
149
+ // Compliance, and its gradient with respect to each cell's physical density: −p ρ^(p−1) (E − Emin) t · uₑᵀ kₑ uₑ
150
+ // (the load is fixed, so the adjoint is the displacement itself)
151
+ let compliance = 0;
152
+ const dc = new Float64Array(cells), dv = new Float64Array(cells);
153
+ spec.loads.forEach((l, c) => {
154
+ const w = l.weight, uc = u[c];
155
+ for (let e = 0; e < cells; e++) {
156
+ 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; }
158
+ compliance += w * scale[e] * ce;
159
+ dc[e] -= w * penal * Math.pow(phys[e], penal - 1) * (E - Emin) * thickness * ce;
160
+ }
161
+ });
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; }
164
+ filter.adjoint(dc, back); dc.set(back);
165
+ filter.adjoint(dv, back); dv.set(back);
166
+ const cases = spec.loads.map((l, c) => {
167
+ const ci = jsBackend.dot(l.force, u[c]), deflection = l.size ? ci / l.size : 0;
168
+ return { name: l.name, compliance: ci, deflection, stiffness: deflection ? l.size / deflection : Infinity };
169
+ });
170
+ return { compliance, dc, dv, u, cases };
171
+ };
172
+ return { physical, evaluate, cells, passive };
173
+ }
174
+
175
+ /**
176
+ * The optimisation: from an even spread, step by step, until the densities stop changing (less than tol per step)
177
+ * with projection at full sharpness, or steps run out.
178
+ * @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]
180
+ * @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
+ * each case's deflection is along its load (mm, compliance over the load's size), stiffness the load over that (N/mm)
182
+ */
183
+ export function optimise(spec, { onStep, method = 'direct', backend = jsBackend, tol = 0.01, move = 0.2 } = {}) {
184
+ const started = Date.now(), m = model(spec, { method, backend }), { cells, passive } = m;
185
+ const inSpace = passive.reduce((s, p) => s + (p !== -2 ? 1 : 0), 0), kept = passive.reduce((s, p) => s + (p === 1 ? 1 : 0), 0);
186
+ const free = passive.reduce((s, p) => s + (p === 0 ? 1 : 0), 0), target = spec.volume * inSpace;
187
+ 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})`);
188
+ 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`);
189
+ if (!free) throw new Error('no free cells: the keep and avoid regions cover the whole space');
190
+
191
+ const betaMax = spec.projection ? 16 : 1, fixedValue = (p) => (p === 1 ? 1 : 0);
192
+ const x = new Float64Array(cells), xnew = new Float64Array(cells);
193
+ for (let e = 0; e < cells; e++) x[e] = passive[e] ? fixedValue(passive[e]) : (target - kept) / free;
194
+ const history = [];
195
+ let step = 0, change = 1, converged = false, beta = 1, sinceBeta = 0;
196
+ while (step < spec.steps) {
197
+ step++; sinceBeta++;
198
+ const { compliance, dc, dv } = m.evaluate(x, beta);
199
+ history.push(compliance);
200
+ // Optimality criteria: scale each cell by √(−dc/dv/λ), within the move limit, finding λ by bisection so the
201
+ // physical densities fill exactly the volume
202
+ // A sharper projection magnifies each change, so the move limit shrinks with it (else the design flickers)
203
+ const limit = move * Math.min(1, 2 / beta);
204
+ let lo = 0, hi = 1e9;
205
+ while ((hi - lo) / (hi + lo) > 1e-3) { // as the 88-line code
206
+ const mid = (lo + hi) / 2;
207
+ for (let e = 0; e < cells; e++) {
208
+ if (passive[e]) { xnew[e] = fixedValue(passive[e]); continue; }
209
+ const b = Math.sqrt(Math.max(0, -dc[e]) / Math.max(1e-30, dv[e]) / mid);
210
+ xnew[e] = Math.max(0, Math.max(x[e] - limit, Math.min(1, Math.min(x[e] + limit, x[e] * b))));
211
+ }
212
+ const filled = m.physical(xnew, beta).reduce((s, v) => s + v, 0);
213
+ if (filled > target) lo = mid; else hi = mid;
214
+ }
215
+ change = 0;
216
+ for (let e = 0; e < cells; e++) change = Math.max(change, Math.abs(xnew[e] - x[e]));
217
+ x.set(xnew);
218
+ onStep?.({ step, steps: spec.steps, compliance, change, beta, density: m.physical(x, beta) });
219
+ // Sharpen: double the projection's steepness when the design settles (or every 50 steps), until it's at its sharpest
220
+ if (beta < betaMax && (change < tol || sinceBeta >= 50)) { beta *= 2; sinceBeta = 0; continue; }
221
+ // Done when nothing moves, or at full sharpness the compliance has stopped improving (within 0.1% over 10 steps)
222
+ const settled = spec.projection && history.length > 10 && beta >= betaMax && sinceBeta > 10 && Math.abs(history.at(-11) - compliance) <= 1e-3 * compliance;
223
+ if (beta >= betaMax && (change < tol || settled)) { converged = true; break; }
224
+ }
225
+ // The final design, analysed as it is
226
+ const final = m.evaluate(x, beta), phys = Float64Array.from(m.physical(x, beta));
227
+ return {
228
+ density: phys, compliance: final.compliance, cases: final.cases,
229
+ volume: phys.reduce((s, v, e) => s + (passive[e] !== -2 ? v : 0), 0) / inSpace, steps: step, converged, history, seconds: (Date.now() - started) / 1000,
230
+ };
231
+ }
232
+
233
+ /**
234
+ * The edges of a result at density 0.5 as closed loops in mm (marching squares on the densities averaged to the
235
+ * cells' corners), solid on the left: outer edges counter-clockwise, holes clockwise. Smoothed (Taubin, which keeps
236
+ * the size), simplified, and with loops smaller than minArea (mm²) dropped.
237
+ * @param {{ nx: number, ny: number, h: number }} size @param {ArrayLike<number>} density @param {[number, number]} origin
238
+ * @param {{ smooth?: number, minArea?: number, tolerance?: number }} [options]
239
+ * @returns {[number, number][][]}
240
+ */
241
+ export function outlines({ nx, ny, h }, density, origin = [0, 0], { smooth = 4, minArea = 0, tolerance = h * 0.05 } = {}) {
242
+ // Corner values, with a ring of empty corners round the outside so every loop closes
243
+ const W = nx + 3, H = ny + 3, v = new Float64Array(W * H);
244
+ for (let j = 0; j <= ny; j++) for (let i = 0; i <= nx; i++) {
245
+ let s = 0;
246
+ 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];
247
+ v[(j + 1) * W + i + 1] = s / 4;
248
+ }
249
+ const iso = 0.5, pos = (i, j) => [origin[0] + (i - 1) * h, origin[1] + (j - 1) * h];
250
+ // 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"
251
+ const point = new Map(), next = new Map();
252
+ const cross = (key, a, b, pa, pb) => {
253
+ 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])]); }
254
+ return key;
255
+ };
256
+ for (let j = 0; j < H - 1; j++) for (let i = 0; i < W - 1; i++) {
257
+ 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);
258
+ const edges = [`h ${i} ${j}`, `v ${i + 1} ${j}`, `h ${i} ${j + 1}`, `v ${i} ${j}`]; // bottom, right, top, left: counter-clockwise
259
+ const crossings = [];
260
+ for (let k = 0; k < 4; k++) {
261
+ const a = k, b = (k + 1) % 4;
262
+ if (inn[a] !== inn[b]) crossings.push({ key: cross(edges[k], val[a], val[b], pos(...c[a]), pos(...c[b])), out: inn[a] });
263
+ }
264
+ if (!crossings.length) continue;
265
+ // Each crossing leaving the solid (going counter-clockwise round the cell) joins the next one entering it; at a
266
+ // saddle, which pairs depends on the middle: solid there joins the two solid corners
267
+ const middle = val.reduce((s, x) => s + x, 0) / 4 >= iso;
268
+ for (let k = 0; k < crossings.length; k++) if (crossings[k].out) {
269
+ const m = crossings.length;
270
+ const to = crossings.length === 4 && !middle ? crossings[(k + m - 1) % m] : crossings[(k + 1) % m];
271
+ next.set(crossings[k].key, to.key);
272
+ }
273
+ }
274
+ const loops = [], seen = new Set();
275
+ for (const start of next.keys()) {
276
+ if (seen.has(start)) continue;
277
+ const loop = [];
278
+ for (let k = start; !seen.has(k); k = next.get(k)) { seen.add(k); loop.push(point.get(k)); }
279
+ loops.push(loop);
280
+ }
281
+ return loops.map((l) => simplify(taubin(l, smooth), tolerance)).filter((l) => l.length >= 3 && Math.abs(area(l)) >= minArea);
282
+ }
283
+
284
+ /**
285
+ * The area of a closed loop in mm², positive if counter-clockwise.
286
+ * @param {[number, number][]} loop
287
+ * @returns {number}
288
+ */
289
+ export function area(loop) {
290
+ let s = 0;
291
+ 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; }
292
+ return s / 2;
293
+ }
294
+
295
+ // Taubin smoothing on a closed loop: a shrinking step then a growing one, so corners round without the loop shrinking
296
+ function taubin(loop, passes, lambda = 0.5, mu = -0.53) {
297
+ let p = loop;
298
+ for (let k = 0; k < passes * 2; k++) {
299
+ const f = k % 2 ? mu : lambda, n = p.length;
300
+ 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])]; });
301
+ }
302
+ return p;
303
+ }
304
+
305
+ // Drop points that lie within tolerance of the line through their neighbours (one pass, then repeat while it helps)
306
+ function simplify(loop, tolerance) {
307
+ let p = loop, dropped = true;
308
+ while (dropped && p.length > 3) {
309
+ dropped = false;
310
+ const out = [];
311
+ for (let i = 0; i < p.length; i++) {
312
+ const a = out.length ? out[out.length - 1] : p[(i + p.length - 1) % p.length], q = p[i], b = p[(i + 1) % p.length];
313
+ 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;
314
+ if (off < tolerance && p.length - (i - out.length) > 3) { dropped = true; continue; }
315
+ out.push(q);
316
+ }
317
+ p = out;
318
+ }
319
+ return p;
320
+ }
321
+
322
+ /**
323
+ * Whether point pt is inside a region.
324
+ * @param {Region} r @param {[number, number]} pt
325
+ * @returns {boolean}
326
+ */
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;
334
+ }
335
+ return c;
336
+ }
337
+
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)];
348
+ }
349
+
350
+ const fmt = (n) => String(Number(n.toFixed(2)));