@rulecad/cad 0.8.0 → 0.10.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.
Files changed (102) hide show
  1. package/AGENTS.md +45 -16
  2. package/CHANGELOG.md +724 -0
  3. package/EXAMPLES.md +61 -54
  4. package/README.md +376 -98
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2664 -541
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1883 -435
  9. package/lib/beams.mjs +256 -52
  10. package/lib/belts.mjs +66 -15
  11. package/lib/board-work.mjs +12 -0
  12. package/lib/bought.mjs +309 -53
  13. package/lib/buildpage.mjs +179 -29
  14. package/lib/cache-file.mjs +105 -0
  15. package/lib/carried.mjs +201 -0
  16. package/lib/clone.mjs +194 -42
  17. package/lib/code-text.mjs +28 -0
  18. package/lib/design-imports.mjs +127 -0
  19. package/lib/design.mjs +871 -147
  20. package/lib/designshapes.mjs +142 -0
  21. package/lib/drive.mjs +187 -63
  22. package/lib/edit.mjs +922 -192
  23. package/lib/errors.mjs +16 -3
  24. package/lib/estimates.mjs +51 -0
  25. package/lib/explain.mjs +62 -13
  26. package/lib/fasten.mjs +2708 -507
  27. package/lib/fe-key.mjs +29 -0
  28. package/lib/fittings.mjs +721 -122
  29. package/lib/fixings.mjs +38 -13
  30. package/lib/framebuild.mjs +790 -175
  31. package/lib/framecheck.mjs +1901 -368
  32. package/lib/framegen.mjs +108 -22
  33. package/lib/frameheat.mjs +225 -42
  34. package/lib/frameprint.mjs +513 -108
  35. package/lib/frames.mjs +86 -18
  36. package/lib/framesize.mjs +719 -120
  37. package/lib/frametip.mjs +235 -0
  38. package/lib/gait.mjs +135 -23
  39. package/lib/grip.mjs +62 -13
  40. package/lib/guides.mjs +1403 -230
  41. package/lib/host.mjs +129 -23
  42. package/lib/inplace.mjs +171 -36
  43. package/lib/jigs.mjs +360 -78
  44. package/lib/joins.mjs +697 -118
  45. package/lib/jsonedit.mjs +88 -26
  46. package/lib/kept.mjs +84 -0
  47. package/lib/kit.mjs +439 -69
  48. package/lib/layout.mjs +2 -1
  49. package/lib/links.mjs +149 -42
  50. package/lib/list.mjs +334 -64
  51. package/lib/live-guard.mjs +68 -0
  52. package/lib/live-shape.mjs +96 -24
  53. package/lib/live.mjs +189 -59
  54. package/lib/loads.mjs +597 -136
  55. package/lib/machine.mjs +372 -74
  56. package/lib/magnets.mjs +162 -44
  57. package/lib/measured.mjs +1080 -117
  58. package/lib/mesh.mjs +526 -119
  59. package/lib/meshcmd.mjs +215 -60
  60. package/lib/motors.mjs +1002 -214
  61. package/lib/motorsvg.mjs +114 -32
  62. package/lib/names.mjs +18 -1
  63. package/lib/optimise.mjs +991 -287
  64. package/lib/order.mjs +515 -114
  65. package/lib/panels.mjs +482 -94
  66. package/lib/parts.mjs +81 -23
  67. package/lib/pins.mjs +163 -44
  68. package/lib/plates.mjs +223 -35
  69. package/lib/player.mjs +37 -9
  70. package/lib/power.mjs +64 -13
  71. package/lib/preview.mjs +83 -16
  72. package/lib/profilemeasure.mjs +572 -129
  73. package/lib/rules.mjs +17 -6
  74. package/lib/sandbox-hooks.mjs +179 -27
  75. package/lib/sandbox-lock.mjs +225 -0
  76. package/lib/sandbox-preload.mjs +2 -2
  77. package/lib/sandbox-run.mjs +122 -25
  78. package/lib/sandbox.mjs +667 -75
  79. package/lib/schema.mjs +42 -11
  80. package/lib/seats.mjs +227 -49
  81. package/lib/services.mjs +261 -52
  82. package/lib/sheet.mjs +963 -179
  83. package/lib/slotnuts.mjs +213 -34
  84. package/lib/targets/gist.mjs +4 -1
  85. package/lib/targets.mjs +22 -4
  86. package/lib/task.mjs +376 -79
  87. package/lib/versions.mjs +285 -39
  88. package/lib/wires.mjs +228 -45
  89. package/lib/workspace.mjs +200 -14
  90. package/package.json +19 -19
  91. package/schemas/assembly.schema.json +2 -2
  92. package/schemas/project.schema.json +6 -0
  93. package/templates/coupons/MEASURE.md +109 -0
  94. package/templates/coupons/assemblies/fixings-test.json +20 -0
  95. package/templates/coupons/assemblies/slot-test.json +11 -0
  96. package/templates/coupons/objects/fixings-coupon.js +88 -0
  97. package/templates/coupons/objects/fixings-coupon.json +26 -0
  98. package/templates/coupons/objects/holds-coupon.js +130 -0
  99. package/templates/coupons/objects/holds-coupon.json +42 -0
  100. package/templates/coupons/objects/slot-coupon.js +89 -0
  101. package/templates/coupons/objects/slot-coupon.json +29 -0
  102. package/templates/coupons/project.json +10 -0
package/lib/optimise.mjs CHANGED
@@ -9,19 +9,41 @@ import path from 'node:path';
9
9
  import crypto from 'node:crypto';
10
10
  import { AsyncLocalStorage } from 'node:async_hooks';
11
11
  import { host, readJson } from './host.mjs';
12
- import { paths, printerOf } from './workspace.mjs';
12
+ import { writeCacheFile, readCacheJson } from './cache-file.mjs';
13
+ import { paths, printerOf, noLinksOut } from './workspace.mjs';
13
14
  import { plainName } from './names.mjs';
14
- import { resolve, evaluate } from './rules.mjs';
15
+ import { resolve, evaluate, fmt } from './rules.mjs';
15
16
  import { located } from './errors.mjs';
16
- import { discretise, optimise, outlines, surface, area, bounds, resultant, printable, refine, despike, reduce, undercuts, voids, grey, featureCells, thin } from '@rulecad/topopt';
17
+ import {
18
+ discretise,
19
+ optimise,
20
+ outlines,
21
+ surface,
22
+ area,
23
+ bounds,
24
+ resultant,
25
+ printable,
26
+ refine,
27
+ despike,
28
+ reduce,
29
+ undercuts,
30
+ voids,
31
+ grey,
32
+ featureCells,
33
+ thin,
34
+ inside,
35
+ } from '@rulecad/topopt';
17
36
  import { islands } from '@rulecad/printcheck';
18
37
  import { turn, mul, inv, placeItems, jointValues } from '@rulecad/model-link';
19
38
  import { section, loops, slabLevels } from './mesh.mjs';
39
+ import { codeOnly } from './code-text.mjs';
20
40
  import { threadsBackend } from '@rulecad/fea/threads'; // the solver's products shared over the machine's cores
21
41
  import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
22
42
 
23
- const VERSION = 2, source = (m) => fs.readFileSync(new URL(import.meta.resolve(m)), 'utf8'); // the solver's code: a change remakes results
24
- export const problemFile = (project, name) => path.join(paths.project(project), 'problems', `${plainName(name, 'problem name')}.json`); // (a name from a design's file: never ../)
43
+ const VERSION = 2,
44
+ source = (m) => fs.readFileSync(new URL(import.meta.resolve(m)), 'utf8'); // the solver's code: a change remakes results
45
+ export const problemFile = (project, name) =>
46
+ path.join(paths.project(project), 'problems', `${plainName(name, 'problem name')}.json`); // (a name from a design's file: never ../)
25
47
  export const hasProblem = (project, ref) => host.exists(problemFile(project, String(ref).split(':')[0]));
26
48
 
27
49
  /**
@@ -31,10 +53,15 @@ export const hasProblem = (project, ref) => host.exists(problemFile(project, Str
31
53
  export async function readProblem(project, ref) {
32
54
  // The problems being read above this one, each with the design it reads that is built from the next: a problem met
33
55
  // again on that chain is refused by name, since each would need the other's result before its own could be made
34
- const name = String(ref).split(':')[0], chain = reading.getStore() || [], key = `${project}/${name}`;
56
+ const name = String(ref).split(':')[0],
57
+ chain = reading.getStore() || [],
58
+ key = `${project}/${name}`;
35
59
  if (chain.some((c) => c.key === key)) {
36
- const from = chain.slice(chain.findIndex((c) => c.key === key)), steps = from.map((c, i) => `${c.name} reads ${c.object}, built from ${(from[i + 1] || { name })?.name}`);
37
- throw new Error(`${name}.json: problems read each other through designs built from them: ${steps.join(', then ')}. Fix one of them to a part or anchor of a design that is not made from the others`);
60
+ const from = chain.slice(chain.findIndex((c) => c.key === key)),
61
+ steps = from.map((c, i) => `${c.name} reads ${c.object}, built from ${(from[i + 1] || { name })?.name}`);
62
+ throw new Error(
63
+ `${name}.json: problems read each other through designs built from them: ${steps.join(', then ')}. Fix one of them to a part or anchor of a design that is not made from the others`,
64
+ );
38
65
  }
39
66
  const link = { key, name, object: null };
40
67
  return reading.run([...chain, link], () => readOne(project, ref, link));
@@ -47,39 +74,67 @@ export async function readProblem(project, ref) {
47
74
  const REDUCE = 0.1;
48
75
  const reading = new AsyncLocalStorage();
49
76
  async function readOne(project, ref, link) {
50
- const [name, variant] = String(ref).split(':'), file = problemFile(project, name);
77
+ const [name, variant] = String(ref).split(':'),
78
+ file = problemFile(project, name);
51
79
  if (!host.exists(file)) throw new Error(`no problem "${name}" (projects/${project}/problems/${name}.json)`);
52
80
  const p = readJson(file);
53
- if (variant && !p.variants?.[variant]) throw new Error(`problem ${name} has no variant "${variant}" (variants: ${Object.keys(p.variants || {}).join(', ') || 'none'})`);
81
+ if (variant && !p.variants?.[variant])
82
+ throw new Error(
83
+ `problem ${name} has no variant "${variant}" (variants: ${Object.keys(p.variants || {}).join(', ') || 'none'})`,
84
+ );
54
85
  const uses = [...new Set([...(p.uses || []), p.material])];
55
86
  let values;
56
- try { ({ values } = resolve({ uses, variables: p.variables || {} }, { set: variant ? p.variants[variant] : {} })); } catch (e) { throw located(e, file, 'var'); }
87
+ try {
88
+ ({ values } = resolve({ uses, variables: p.variables || {} }, { set: variant ? p.variants[variant] : {} }));
89
+ } catch (e) {
90
+ throw located(e, file, 'var');
91
+ }
57
92
  const lookup = (n) => {
58
93
  const v = n.split('.').reduce((o, k) => (o == null ? o : o[k]), values);
59
- if (typeof v !== 'number') throw new Error(`${path.basename(file)}: "${n}" isn't a number here (variables: ${Object.keys(p.variables || {}).join(', ')})`);
94
+ if (typeof v !== 'number')
95
+ throw new Error(
96
+ `${path.basename(file)}: "${n}" isn't a number here (variables: ${Object.keys(p.variables || {}).join(', ')})`,
97
+ );
60
98
  return v;
61
99
  };
62
- const ev = (x) => evaluate(x, lookup), pt = (a) => a.map(ev), flat = p.thickness != null;
100
+ const ev = (x) => evaluate(x, lookup),
101
+ pt = (a) => a.map(ev),
102
+ flat = p.thickness != null;
63
103
  // Another design in the project, built once with its defaults, for its parts and anchors. One whose default is built
64
104
  // from this very problem is refused: it would need the result before the result could be made.
65
105
  const designs = new Map();
66
- const design = (object, what) => { // (the build kept as it starts: regions are read side by side)
67
- if (!designs.has(object)) designs.set(object, (async () => {
68
- const { build, locateIn, readObject } = await import('./design.mjs'), d = locateIn(project, object, `${path.basename(file)}: ${what}`);
69
- const own = Object.entries(readObject(d).variables || {}).find(([, v]) => v.type === 'problem' && String(v.value).split(':')[0] === name);
70
- if (own) throw new Error(`${path.basename(file)}: ${what} is on ${object}, which is built from this problem (its variable ${own[0]}): name a part or anchor of what it is fixed to instead`);
71
- const chain = reading.getStore(); // this problem's place on the chain names the design it reads
72
- return reading.run([...chain.slice(0, -1), { ...link, object }], () => build(d));
73
- })());
106
+ const design = (object, what) => {
107
+ // (the build kept as it starts: regions are read side by side)
108
+ if (!designs.has(object))
109
+ designs.set(
110
+ object,
111
+ (async () => {
112
+ const { build, locateIn, readObject } = await import('./design.mjs'),
113
+ d = locateIn(project, object, `${path.basename(file)}: ${what}`);
114
+ const own = Object.entries(readObject(d).variables || {}).find(
115
+ ([, v]) => v.type === 'problem' && String(v.value).split(':')[0] === name,
116
+ );
117
+ if (own)
118
+ throw new Error(
119
+ `${path.basename(file)}: ${what} is on ${object}, which is built from this problem (its variable ${own[0]}): name a part or anchor of what it is fixed to instead`,
120
+ );
121
+ const chain = reading.getStore(); // this problem's place on the chain names the design it reads
122
+ return reading.run([...chain.slice(0, -1), { ...link, object }], () => build(d));
123
+ })(),
124
+ );
74
125
  return designs.get(object);
75
126
  };
76
127
  // A named part of another design in the project, as triangles (built with its defaults)
77
128
  const parts = new Map();
78
129
  const part = async (ref) => {
79
130
  if (!parts.has(ref)) {
80
- const [object, partName] = ref.split('.'), b = await design(object, `the part "${ref}"`);
131
+ const [object, partName] = ref.split('.'),
132
+ b = await design(object, `the part "${ref}"`);
81
133
  const found = partName ? b.parts.find((q) => q.name === partName) : b.parts.find((q) => q.role !== 'support');
82
- if (!found) throw new Error(`${path.basename(file)}: ${object} has no part "${partName}" (parts: ${b.parts.map((q) => q.name).join(', ')})`);
134
+ if (!found)
135
+ throw new Error(
136
+ `${path.basename(file)}: ${object} has no part "${partName}" (parts: ${b.parts.map((q) => q.name).join(', ')})`,
137
+ );
83
138
  parts.set(ref, found.triangles);
84
139
  }
85
140
  return parts.get(ref);
@@ -90,16 +145,26 @@ async function readOne(project, ref, link) {
90
145
  const anchor = async (ref) => {
91
146
  if (!anchors.has(ref)) {
92
147
  const [object, a, ...more] = String(ref).split('.');
93
- if (!object || !a || more.length) throw new Error(`${path.basename(file)}: name an anchor as <object>.<anchor> (got "${ref}")`);
94
- const b = await design(object, `the anchor "${ref}"`), spec = b.object.anchors?.[a];
95
- if (!spec) throw new Error(`${path.basename(file)}: ${object} has no anchor "${a}" (anchors: ${Object.keys(b.object.anchors || {}).join(', ') || 'none'})`);
96
- const num = (x) => evaluate(x, (n) => {
97
- const v = n.split('.').reduce((o, k) => (o == null ? o : o[k]), b.values);
98
- if (typeof v !== 'number') throw new Error(`${path.basename(file)}: the anchor "${ref}" reads "${n}", which isn't one of ${object}'s numbers`);
99
- return v;
100
- });
148
+ if (!object || !a || more.length)
149
+ throw new Error(`${path.basename(file)}: name an anchor as <object>.<anchor> (got "${ref}")`);
150
+ const b = await design(object, `the anchor "${ref}"`),
151
+ spec = b.object.anchors?.[a];
152
+ if (!spec)
153
+ throw new Error(
154
+ `${path.basename(file)}: ${object} has no anchor "${a}" (anchors: ${Object.keys(b.object.anchors || {}).join(', ') || 'none'})`,
155
+ );
156
+ const num = (x) =>
157
+ evaluate(x, (n) => {
158
+ const v = n.split('.').reduce((o, k) => (o == null ? o : o[k]), b.values);
159
+ if (typeof v !== 'number')
160
+ throw new Error(
161
+ `${path.basename(file)}: the anchor "${ref}" reads "${n}", which isn't one of ${object}'s numbers`,
162
+ );
163
+ return v;
164
+ });
101
165
  // Its axis is its z, as an assembly reads it: turned by its rotate (degrees about x, then y, then z) where it has one
102
- const m = spec.rotate && turn(spec.rotate.map(num)), axis = m ? [m[2], m[6], m[10]].map((c) => (Math.abs(c) < 1e-12 ? 0 : c)) : (spec.axis || [0, 0, 1]).map(num);
166
+ const m = spec.rotate && turn(spec.rotate.map(num)),
167
+ axis = m ? [m[2], m[6], m[10]].map((c) => (Math.abs(c) < 1e-12 ? 0 : c)) : (spec.axis || [0, 0, 1]).map(num);
103
168
  anchors.set(ref, { anchor: ref, at: (spec.at || [0, 0, 0]).map(num), axis });
104
169
  }
105
170
  return anchors.get(ref);
@@ -111,31 +176,57 @@ async function readOne(project, ref, link) {
111
176
  const fileName = path.basename(file);
112
177
  let placing = null;
113
178
  const inAssembly = (what) => {
114
- if (!p.in) throw new Error(`${fileName}: ${what} needs the problem placed in an assembly: "in": { "assembly": "<name>", "item": "<the item it is drawn in>" }`);
179
+ if (!p.in)
180
+ throw new Error(
181
+ `${fileName}: ${what} needs the problem placed in an assembly: "in": { "assembly": "<name>", "item": "<the item it is drawn in>" }`,
182
+ );
115
183
  return (placing ||= (async () => {
116
- const { buildAssembly, assemblyPath } = await import('./assembly.mjs'), { locateIn, readObject } = await import('./design.mjs');
117
- const ref = `${project}/${p.in.assembly}`, overrides = {};
118
- if (!host.exists(assemblyPath(ref))) throw new Error(`${fileName}: no assembly "${p.in.assembly}" to place the problem in (projects/${project}/assemblies/${p.in.assembly}.json)`);
119
- for (const it of readJson(assemblyPath(ref)).items || []) if (typeof it.object === 'string') {
120
- let vars = {};
121
- try { vars = readObject(locateIn(project, it.object.split(/[:@]/)[0])).variables || {}; } catch { continue; }
122
- for (const [k, v] of Object.entries(vars)) if (v.type === 'problem' && (it.id === p.in.item || String(it.set?.[k] ?? v.value).split(':')[0] === name)) (overrides[it.id] ||= {})[k] = 'none';
123
- }
184
+ const { buildAssembly, assemblyPath } = await import('./assembly.mjs'),
185
+ { locateIn, readObject } = await import('./design.mjs');
186
+ const ref = `${project}/${p.in.assembly}`,
187
+ overrides = {};
188
+ if (!host.exists(assemblyPath(ref)))
189
+ throw new Error(
190
+ `${fileName}: no assembly "${p.in.assembly}" to place the problem in (projects/${project}/assemblies/${p.in.assembly}.json)`,
191
+ );
192
+ for (const it of readJson(assemblyPath(ref)).items || [])
193
+ if (typeof it.object === 'string') {
194
+ let vars = {};
195
+ try {
196
+ vars = readObject(locateIn(project, it.object.split(/[:@]/)[0])).variables || {};
197
+ } catch {
198
+ continue;
199
+ }
200
+ for (const [k, v] of Object.entries(vars))
201
+ if (v.type === 'problem' && (it.id === p.in.item || String(it.set?.[k] ?? v.value).split(':')[0] === name))
202
+ (overrides[it.id] ||= {})[k] = 'none';
203
+ }
124
204
  const chain = reading.getStore();
125
- const s = await reading.run([...chain.slice(0, -1), { ...link, object: `the assembly ${p.in.assembly}` }], () => buildAssembly(ref, [], overrides, { pose: p.in.pose, onePose: true }));
205
+ const s = await reading.run([...chain.slice(0, -1), { ...link, object: `the assembly ${p.in.assembly}` }], () =>
206
+ buildAssembly(ref, [], overrides, { pose: p.in.pose, onePose: true }),
207
+ );
126
208
  const k = s.motion.items.findIndex((x) => x[0] === p.in.item);
127
- if (k < 0) throw new Error(`${fileName}: ${p.in.assembly} has no item "${p.in.item}" (items: ${s.motion.items.map((x) => x[0]).join(', ')})`);
209
+ if (k < 0)
210
+ throw new Error(
211
+ `${fileName}: ${p.in.assembly} has no item "${p.in.item}" (items: ${s.motion.items.map((x) => x[0]).join(', ')})`,
212
+ );
128
213
  return { s, k, W0: placeItems(s.motion, s.jointValues) };
129
214
  })());
130
215
  };
131
216
  // A joint of that assembly, where it is in the item's frame: the joint's anchor on the item when the item is one of
132
217
  // its ends (the same in every pose), else the parent's anchor as the pose places it. Its axis is the anchor's z.
133
- const joints = new Map(), clean = (c) => (Math.abs(c) < 1e-9 ? 0 : round(c, 9));
218
+ const joints = new Map(),
219
+ clean = (c) => (Math.abs(c) < 1e-9 ? 0 : round(c, 9));
134
220
  const jointAt = async (id) => {
135
221
  if (!joints.has(id)) {
136
- const { s, k, W0 } = await inAssembly(`the joint "${id}"`), j = s.motion.joints.find((x) => x.id === id);
137
- if (!j) throw new Error(`${fileName}: ${p.in.assembly} has no joint "${id}" (joints: ${s.motion.joints.map((x) => x.id).join(', ') || 'none'})`);
138
- const F = j.child === k ? j.b : j.parent === k ? j.a : mul(inv(W0[k]), j.parent < 0 ? j.a : mul(W0[j.parent], j.a));
222
+ const { s, k, W0 } = await inAssembly(`the joint "${id}"`),
223
+ j = s.motion.joints.find((x) => x.id === id);
224
+ if (!j)
225
+ throw new Error(
226
+ `${fileName}: ${p.in.assembly} has no joint "${id}" (joints: ${s.motion.joints.map((x) => x.id).join(', ') || 'none'})`,
227
+ );
228
+ const F =
229
+ j.child === k ? j.b : j.parent === k ? j.a : mul(inv(W0[k]), j.parent < 0 ? j.a : mul(W0[j.parent], j.a));
139
230
  joints.set(id, { joint: id, at: [F[3], F[7], F[11]].map(clean), axis: [F[2], F[6], F[10]].map(clean) });
140
231
  }
141
232
  return joints.get(id);
@@ -148,67 +239,156 @@ async function readOne(project, ref, link) {
148
239
  // into the plate's top or bottom is kept clear; one only passing over or under it, or touching a face, is not.
149
240
  const sweeps = [];
150
241
  const swept = async (r) => {
151
- const { s, k, W0 } = await inAssembly(`the sweep of "${r.sweep}"`), item = p.in.item, cell = ev(p.cell);
152
- const isNamed = (q, n) => q.name === n || q.leaf === n || q.item === n || q.name.startsWith(`${n}.`), moving = s.parts.filter((q) => isNamed(q, r.sweep));
153
- if (!moving.length) throw new Error(`${fileName}: ${p.in.assembly} has no item or part "${r.sweep}" to sweep (items: ${s.motion.items.map((x) => x[0]).join(', ')})`);
154
- if (moving.some((q) => (q.moves ?? q.item) === item)) throw new Error(`${fileName}: "${r.sweep}" is ${item} itself, the item this problem is in: sweep a part that moves against it`);
155
- const free = s.motion.joints.filter((j) => !j.follow && j.dofs.length), through = [r.through ?? []].flat();
156
- if (!through.length) throw new Error(`${fileName}: the sweep of "${r.sweep}" needs the joint it moves through: "through": "<joint>" (joints: ${free.map((j) => j.id).join(', ') || 'none'})`);
157
- const apply = (M, [x, y, z]) => [M[0] * x + M[1] * y + M[2] * z + M[3], M[4] * x + M[5] * y + M[6] * z + M[7], M[8] * x + M[9] * y + M[10] * z + M[11]];
242
+ const { s, k, W0 } = await inAssembly(`the sweep of "${r.sweep}"`),
243
+ item = p.in.item,
244
+ cell = ev(p.cell);
245
+ const isNamed = (q, n) => q.name === n || q.leaf === n || q.item === n || q.name.startsWith(`${n}.`),
246
+ moving = s.parts.filter((q) => isNamed(q, r.sweep));
247
+ if (!moving.length)
248
+ throw new Error(
249
+ `${fileName}: ${p.in.assembly} has no item or part "${r.sweep}" to sweep (items: ${s.motion.items.map((x) => x[0]).join(', ')})`,
250
+ );
251
+ if (moving.some((q) => (q.moves ?? q.item) === item))
252
+ throw new Error(
253
+ `${fileName}: "${r.sweep}" is ${item} itself, the item this problem is in: sweep a part that moves against it`,
254
+ );
255
+ const free = s.motion.joints.filter((j) => !j.follow && j.dofs.length),
256
+ through = [r.through ?? []].flat();
257
+ if (!through.length)
258
+ throw new Error(
259
+ `${fileName}: the sweep of "${r.sweep}" needs the joint it moves through: "through": "<joint>" (joints: ${free.map((j) => j.id).join(', ') || 'none'})`,
260
+ );
261
+ const apply = (M, [x, y, z]) => [
262
+ M[0] * x + M[1] * y + M[2] * z + M[3],
263
+ M[4] * x + M[5] * y + M[6] * z + M[7],
264
+ M[8] * x + M[9] * y + M[10] * z + M[11],
265
+ ];
158
266
  const idx = moving.map((q) => s.motion.items.findIndex((x) => x[0] === (q.moves ?? q.item)));
159
- const local = moving.map((q, i) => { const L = inv(W0[idx[i]]); return q.triangles.map((t) => t.map((v) => apply(L, v))); }); // each in its own item's frame
160
- const sample = local.map((tris) => { const v = tris.flat(), n = Math.ceil(v.length / 400); return v.filter((_, i) => i % n === 0); }); // (no more than about 400 points a part)
161
- const held = Object.fromEntries(Object.entries(s.jointValues).filter(([id]) => !s.motion.joints.find((x) => x.id === id).follow));
162
- const z = flat ? (p.in.z != null ? ev(p.in.z) : ev(p.thickness) / 2) : null, zlo = flat ? z - ev(p.thickness) / 2 : null, zhi = flat ? z + ev(p.thickness) / 2 : null, out = [];
267
+ const local = moving.map((q, i) => {
268
+ const L = inv(W0[idx[i]]);
269
+ return q.triangles.map((t) => t.map((v) => apply(L, v)));
270
+ }); // each in its own item's frame
271
+ const sample = local.map((tris) => {
272
+ const v = tris.flat(),
273
+ n = Math.ceil(v.length / 400);
274
+ return v.filter((_, i) => i % n === 0);
275
+ }); // (no more than about 400 points a part)
276
+ const held = Object.fromEntries(
277
+ Object.entries(s.jointValues).filter(([id]) => !s.motion.joints.find((x) => x.id === id).follow),
278
+ );
279
+ const z = flat ? (p.in.z != null ? ev(p.in.z) : ev(p.thickness) / 2) : null,
280
+ zlo = flat ? z - ev(p.thickness) / 2 : null,
281
+ zhi = flat ? z + ev(p.thickness) / 2 : null,
282
+ out = [];
163
283
  for (const id of through) {
164
284
  const j = free.find((x) => x.id === id);
165
- if (!j) throw new Error(`${fileName}: ${p.in.assembly} has no joint "${id}" that moves on its own to sweep "${r.sweep}" through (joints: ${free.map((x) => x.id).join(', ') || 'none'})`);
285
+ if (!j)
286
+ throw new Error(
287
+ `${fileName}: ${p.in.assembly} has no joint "${id}" that moves on its own to sweep "${r.sweep}" through (joints: ${free.map((x) => x.id).join(', ') || 'none'})`,
288
+ );
166
289
  j.dofs.forEach(([lo, hi], d) => {
167
- const at = (v) => { const W = placeItems(s.motion, jointValues(s.motion, { ...held, [id]: held[id].map((x, i) => (i === d ? v : x)) })), T = inv(W[k]); return idx.map((m) => mul(T, W[m])); };
168
- let travel = 0, before = at(lo).map((M, m) => sample[m].map((v) => apply(M, v)));
290
+ const at = (v) => {
291
+ const W = placeItems(
292
+ s.motion,
293
+ jointValues(s.motion, { ...held, [id]: held[id].map((x, i) => (i === d ? v : x)) }),
294
+ ),
295
+ T = inv(W[k]);
296
+ return idx.map((m) => mul(T, W[m]));
297
+ };
298
+ let travel = 0,
299
+ before = at(lo).map((M, m) => sample[m].map((v) => apply(M, v)));
169
300
  for (let i = 1; i <= 32; i++) {
170
301
  const now = at(lo + ((hi - lo) * i) / 32).map((M, m) => sample[m].map((v) => apply(M, v)));
171
- travel += Math.max(0, ...now.flatMap((pts, m) => pts.map((q, n) => Math.hypot(...q.map((c, a) => c - before[m][n][a])))));
302
+ travel += Math.max(
303
+ 0,
304
+ ...now.flatMap((pts, m) => pts.map((q, n) => Math.hypot(...q.map((c, a) => c - before[m][n][a])))),
305
+ );
172
306
  before = now;
173
307
  }
174
308
  const what = `${id}${j.dofs.length > 1 ? ` (its value ${d + 1})` : ''}`;
175
- if (!(travel > 1e-6)) throw new Error(`${fileName}: ${what} doesn't move "${r.sweep}" against ${item} (from ${round(lo)} to ${round(hi)}): sweep it through a joint between them`);
309
+ if (!(travel > 1e-6))
310
+ throw new Error(
311
+ `${fileName}: ${what} doesn't move "${r.sweep}" against ${item} (from ${round(lo)} to ${round(hi)}): sweep it through a joint between them`,
312
+ );
176
313
  const steps = r.steps ?? Math.max(1, Math.ceil((2 * travel) / cell));
177
- if (r.steps == null && steps > 360) throw new Error(`${fileName}: sweeping "${r.sweep}" through ${what} would take ${steps} steps on ${cell} mm cells (its farthest point travels ${round(travel, 1)} mm): give the sweep its steps, or larger cells`);
314
+ if (r.steps == null && steps > 360)
315
+ throw new Error(
316
+ `${fileName}: sweeping "${r.sweep}" through ${what} would take ${steps} steps on ${cell} mm cells (its farthest point travels ${round(travel, 1)} mm): give the sweep its steps, or larger cells`,
317
+ );
178
318
  let made = 0;
179
319
  for (let i = 0; i <= steps; i++) {
180
- const v = lo + ((hi - lo) * i) / steps, Ms = at(v);
320
+ const v = lo + ((hi - lo) * i) / steps,
321
+ Ms = at(v);
181
322
  for (const [m, tris] of local.entries()) {
182
323
  const moved = tris.map((t) => t.map((q) => apply(Ms[m], q).map(clean)));
183
- if (!flat) { out.push({ triangles: moved, sweep: r.sweep, joint: id, value: round(v, 6) }); made++; continue; }
324
+ if (!flat) {
325
+ out.push({ triangles: moved, sweep: r.sweep, joint: id, value: round(v, 6) });
326
+ made++;
327
+ continue;
328
+ }
184
329
  // Each section's outlines, each a ring turned solid on its left (an outline counter-clockwise, a hole in it
185
330
  // clockwise), for the design to cut exactly (rings); and for the solver one polygon of them all, each closed and
186
331
  // back to the first one's start, so a point is inside where it is inside an odd number of them (a hole in the
187
332
  // part stays open) and the joins cancel out. A point within 0.001 mm of the line through its neighbours (where a face's diagonal is
188
333
  // cut, or a boolean left a sliver) is dropped, and a section whose corners all lie within 0.01 mm of one already taken at this step is left out.
189
- const same = (a, b) => Math.abs(a[0] - b[0]) < 1e-9 && Math.abs(a[1] - b[1]) < 1e-9, kept = [];
190
- const off = (q, a, b) => { const d = [b[0] - a[0], b[1] - a[1]], L = Math.hypot(...d); return L < 1e-12 ? Math.hypot(q[0] - a[0], q[1] - a[1]) : Math.abs(d[0] * (q[1] - a[1]) - d[1] * (q[0] - a[0])) / L; };
191
- const straight = (ring) => { const l = [...ring]; for (let n = 0; n < l.length && l.length > 3;) if (off(l[n], l[(n + l.length - 1) % l.length], l[(n + 1) % l.length]) < 1e-3) { l.splice(n, 1); n = Math.max(0, n - 1); } else n++; return l; };
334
+ const same = (a, b) => Math.abs(a[0] - b[0]) < 1e-9 && Math.abs(a[1] - b[1]) < 1e-9,
335
+ kept = [];
336
+ const off = (q, a, b) => {
337
+ const d = [b[0] - a[0], b[1] - a[1]],
338
+ L = Math.hypot(...d);
339
+ return L < 1e-12
340
+ ? Math.hypot(q[0] - a[0], q[1] - a[1])
341
+ : Math.abs(d[0] * (q[1] - a[1]) - d[1] * (q[0] - a[0])) / L;
342
+ };
343
+ const straight = (ring) => {
344
+ const l = [...ring];
345
+ for (let n = 0; n < l.length && l.length > 3;)
346
+ if (off(l[n], l[(n + l.length - 1) % l.length], l[(n + 1) % l.length]) < 1e-3) {
347
+ l.splice(n, 1);
348
+ n = Math.max(0, n - 1);
349
+ } else n++;
350
+ return l;
351
+ };
192
352
  for (const h of slabLevels(moved, zlo, zhi, cell)) {
193
- const rings = loops(section(moved, 2, h)).map((l) => straight((same(l[0], l.at(-1)) ? l.slice(0, -1) : l).map((q) => q.map(clean)))).filter((l) => l.length >= 3);
353
+ const rings = loops(section(moved, 2, h))
354
+ .map((l) => straight((same(l[0], l.at(-1)) ? l.slice(0, -1) : l).map((q) => q.map(clean))))
355
+ .filter((l) => l.length >= 3);
194
356
  if (!rings.length) continue;
195
- const within = (q, P) => { let c = false; for (let a = 0, b = P.length - 1; a < P.length; b = a++) if ((P[a][1] > q[1]) !== (P[b][1] > q[1]) && q[0] < ((P[b][0] - P[a][0]) * (q[1] - P[a][1])) / (P[b][1] - P[a][1]) + P[a][0]) c = !c; return c; };
357
+ const within = (q, P) => {
358
+ let c = false;
359
+ for (let a = 0, b = P.length - 1; a < P.length; b = a++)
360
+ if (
361
+ P[a][1] > q[1] !== P[b][1] > q[1] &&
362
+ q[0] < ((P[b][0] - P[a][0]) * (q[1] - P[a][1])) / (P[b][1] - P[a][1]) + P[a][0]
363
+ )
364
+ c = !c;
365
+ return c;
366
+ };
196
367
  const turned = rings.map((l, n) => {
197
- const depth = rings.filter((o, m) => m !== n && within(l[0], o)).length, ccw = l.reduce((t, q, a) => t + q[0] * l[(a + 1) % l.length][1] - l[(a + 1) % l.length][0] * q[1], 0) > 0;
368
+ const depth = rings.filter((o, m) => m !== n && within(l[0], o)).length,
369
+ ccw =
370
+ l.reduce((t, q, a) => t + q[0] * l[(a + 1) % l.length][1] - l[(a + 1) % l.length][0] * q[1], 0) > 0;
198
371
  return ccw === (depth % 2 === 0) ? l : [...l].reverse();
199
372
  });
200
- const near = (l, o) => l.length === o.length && l.every((q) => o.some((w) => Math.hypot(q[0] - w[0], q[1] - w[1]) < 0.01));
201
- if (kept.some((k) => k.length === turned.length && turned.every((l) => k.some((o) => near(l, o))))) continue;
373
+ const near = (l, o) =>
374
+ l.length === o.length && l.every((q) => o.some((w) => Math.hypot(q[0] - w[0], q[1] - w[1]) < 0.01));
375
+ if (kept.some((k) => k.length === turned.length && turned.every((l) => k.some((o) => near(l, o)))))
376
+ continue;
202
377
  kept.push(turned);
203
- const start = turned[0][0], points = turned.flatMap((l, n) => [...l, l[0], ...(n ? [start] : [])]);
204
- out.push({ points, rings: turned, sweep: r.sweep, joint: id, value: round(v, 6) }); made++;
378
+ const start = turned[0][0],
379
+ points = turned.flatMap((l, n) => [...l, l[0], ...(n ? [start] : [])]);
380
+ out.push({ points, rings: turned, sweep: r.sweep, joint: id, value: round(v, 6) });
381
+ made++;
205
382
  }
206
383
  }
207
384
  }
208
385
  sweeps.push({ sweep: r.sweep, through: what, from: round(lo, 6), to: round(hi, 6), steps, regions: made });
209
386
  });
210
387
  }
211
- if (!out.length) throw new Error(`${fileName}: "${r.sweep}" never reaches into the plate (z ${round(zlo)} to ${round(zhi)} mm in ${item}) through ${through.join(', ')}: nothing to keep clear there (set in.z, the plate's middle, if it lies elsewhere)`);
388
+ if (!out.length)
389
+ throw new Error(
390
+ `${fileName}: "${r.sweep}" never reaches into the plate (z ${round(zlo)} to ${round(zhi)} mm in ${item}) through ${through.join(', ')}: nothing to keep clear there (set in.z, the plate's middle, if it lies elsewhere)`,
391
+ );
212
392
  return out;
213
393
  };
214
394
  // The build direction: a direction ('+z'), or a variable holding one
@@ -216,70 +396,218 @@ async function readOne(project, ref, link) {
216
396
  // The sides it is milled from, and a one-way mould's draw, likewise: or a variable holding them ('+z', '+z +x', or
217
397
  // 'none': not milled, not cast), so a variant can switch the process
218
398
  const named = (v) => (typeof v === 'string' && typeof values[v] === 'string' ? values[v] : v);
219
- const millSides = (() => { const v = named(p.mill); if (typeof v !== 'string') return v; const list = v.trim().split(/[\s,]+/).filter(Boolean); return v === 'none' ? null : list.length > 1 ? list : v; })();
220
- const castWay = (() => { const v = named(p.cast); return v === 'none' ? null : v; })();
399
+ const millSides = (() => {
400
+ const v = named(p.mill);
401
+ if (typeof v !== 'string') return v;
402
+ const list = v
403
+ .trim()
404
+ .split(/[\s,]+/)
405
+ .filter(Boolean);
406
+ return v === 'none' ? null : list.length > 1 ? list : v;
407
+ })();
408
+ const castWay = (() => {
409
+ const v = named(p.cast);
410
+ return v === 'none' ? null : v;
411
+ })();
221
412
  // A teardrop's point: a direction, or up or down the build direction (+z, as drawn, when it's free)
222
- const point = (t) => { const up = overhang && overhang !== 'none' ? overhang : '+z'; return t === 'up' ? up : t === 'down' ? (up[0] === '-' ? '+' : '-') + up[1] : t; };
413
+ const point = (t) => {
414
+ const up = overhang && overhang !== 'none' ? overhang : '+z';
415
+ return t === 'up' ? up : t === 'down' ? (up[0] === '-' ? '+' : '-') + up[1] : t;
416
+ };
223
417
  const region = async (r) => {
224
- if (r.sweep != null) throw new Error(`${path.basename(file)}: a swept part ("${r.sweep}") is a region to keep clear: put it under avoid`);
225
- if (r.anchor || r.joint) { // at an anchor, or an assembly's joint: its place (x and y in a flat problem), and a cylinder along its axis unless it names one
226
- const kind = r.anchor ? 'anchor' : 'joint', named = `the ${kind} "${r.anchor || r.joint}"`;
227
- if (r.anchor && r.joint) throw new Error(`${path.basename(file)}: a region is at an anchor or at a joint, not both ("${r.anchor}", "${r.joint}")`);
228
- if (r.at) throw new Error(`${path.basename(file)}: a region at an ${kind} ("${r.anchor || r.joint}") takes no at: the ${kind} places it`);
229
- const a = r.anchor ? await anchor(r.anchor) : await jointAt(r.joint), along = a.axis.map((c) => Math.abs(c) > 1e-9);
230
- if (r.length != null && !r.axis && along.filter(Boolean).length !== 1) throw new Error(`${path.basename(file)}: ${named} points along [${a.axis.map((c) => round(c, 3)).join(', ')}], not along x, y or z: give the cylinder an axis`);
231
- return region({ ...r, anchor: undefined, joint: undefined, at: flat ? a.at.slice(0, 2) : a.at, ...(r.length != null && !r.axis ? { axis: 'xyz'[along.indexOf(true)] } : {}) });
418
+ if (r.sweep != null)
419
+ throw new Error(
420
+ `${path.basename(file)}: a swept part ("${r.sweep}") is a region to keep clear: put it under avoid`,
421
+ );
422
+ if (r.anchor || r.joint) {
423
+ // at an anchor, or an assembly's joint: its place (x and y in a flat problem), and a cylinder along its axis unless it names one
424
+ const kind = r.anchor ? 'anchor' : 'joint',
425
+ named = `the ${kind} "${r.anchor || r.joint}"`;
426
+ if (r.anchor && r.joint)
427
+ throw new Error(
428
+ `${path.basename(file)}: a region is at an anchor or at a joint, not both ("${r.anchor}", "${r.joint}")`,
429
+ );
430
+ if (r.at)
431
+ throw new Error(
432
+ `${path.basename(file)}: a region at an ${kind} ("${r.anchor || r.joint}") takes no at: the ${kind} places it`,
433
+ );
434
+ const a = r.anchor ? await anchor(r.anchor) : await jointAt(r.joint),
435
+ along = a.axis.map((c) => Math.abs(c) > 1e-9);
436
+ if (r.length != null && !r.axis && along.filter(Boolean).length !== 1)
437
+ throw new Error(
438
+ `${path.basename(file)}: ${named} points along [${a.axis.map((c) => round(c, 3)).join(', ')}], not along x, y or z: give the cylinder an axis`,
439
+ );
440
+ return region({
441
+ ...r,
442
+ anchor: undefined,
443
+ joint: undefined,
444
+ at: flat ? a.at.slice(0, 2) : a.at,
445
+ ...(r.length != null && !r.axis ? { axis: 'xyz'[along.indexOf(true)] } : {}),
446
+ });
232
447
  }
233
- if (r.part) { // with where it is (its box's centre), for a load's or support's resultant
234
- const triangles = await part(r.part), lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];
235
- for (const t of triangles) for (const q of t) for (let a = 0; a < 3; a++) { lo[a] = Math.min(lo[a], q[a]); hi[a] = Math.max(hi[a], q[a]); }
448
+ if (r.part) {
449
+ // with where it is (its box's centre), for a load's or support's resultant
450
+ const triangles = await part(r.part),
451
+ lo = [Infinity, Infinity, Infinity],
452
+ hi = [-Infinity, -Infinity, -Infinity];
453
+ for (const t of triangles)
454
+ for (const q of t)
455
+ for (let a = 0; a < 3; a++) {
456
+ lo[a] = Math.min(lo[a], q[a]);
457
+ hi[a] = Math.max(hi[a], q[a]);
458
+ }
236
459
  const at = lo.map((x, a) => (x + hi[a]) / 2);
237
460
  return flat ? { triangles, part: r.part, at: at.slice(0, 2), flat: true } : { triangles, part: r.part, at }; // flat: its section halfway up
238
461
  }
239
462
  if (r.points) return { points: r.points.map(pt) };
240
463
  if (r.size) return { at: pt(r.at), size: r.size.map(ev) };
241
- if (r.length != null) { const axis = r.axis || 'z', t = r.teardrop && point(r.teardrop); return { at: pt(r.at), r: ev(r.r), length: ev(r.length), axis, ...(t && t[1] !== axis ? { teardrop: t } : {}) }; } // along its axis, a teardrop has no point
464
+ if (r.length != null) {
465
+ const axis = r.axis || 'z',
466
+ t = r.teardrop && point(r.teardrop);
467
+ return { at: pt(r.at), r: ev(r.r), length: ev(r.length), axis, ...(t && t[1] !== axis ? { teardrop: t } : {}) };
468
+ } // along its axis, a teardrop has no point
242
469
  return { at: pt(r.at), ...(r.r != null ? { r: ev(r.r) } : {}) };
243
470
  };
244
471
  const regions = (list) => Promise.all([list || []].flat().map(region));
245
472
  const m = values[p.material];
246
- if (typeof m?.modulus !== 'number' || typeof m?.poisson !== 'number') throw new Error(`material ${p.material}: its rule set needs modulus (MPa) and poisson`);
473
+ if (typeof m?.modulus !== 'number' || typeof m?.poisson !== 'number')
474
+ throw new Error(`material ${p.material}: its rule set needs modulus (MPa) and poisson`);
247
475
  // The filter's radius is about the thinnest member: a cell and a half unless the problem gives one, and never under two
248
476
  // of the printer's lines, the thinnest wall it lays solid (so it only binds on cells under 0.56 mm on a 0.42 mm line)
249
- const printer = printerOf(project), line = printer ? resolve({ uses: [printer] }).values[printer]?.line : null, lines = typeof line === 'number' ? 2 * line : 0;
250
- const space = await regions(p.space), dim = flat ? 2 : space[0].triangles || space[0].length != null || (space[0].size || space[0].at)?.length === 3 ? 3 : 2;
477
+ const printer = printerOf(project),
478
+ line = printer ? resolve({ uses: [printer] }).values[printer]?.line : null,
479
+ lines = typeof line === 'number' ? 2 * line : 0;
480
+ const space = await regions(p.space),
481
+ dim = flat
482
+ ? 2
483
+ : space[0].triangles || space[0].length != null || (space[0].size || space[0].at)?.length === 3
484
+ ? 3
485
+ : 2;
251
486
  const problem = {
252
- space, keep: await regions(p.keep), avoid: (await Promise.all([p.avoid || []].flat().map(async (r) => (r.sweep != null ? swept(r) : [await region(r)])))).flat(),
253
- supports: await Promise.all(p.supports.map(async (s) => ({ ...(await region(s)), fix: s.fix || 'xyz'.slice(0, dim) }))),
254
- loads: await Promise.all(p.loads.map(async (l) => ({ ...(await region(l)), force: pt(l.force), case: l.case || 'load' }))),
487
+ space,
488
+ keep: await regions(p.keep),
489
+ avoid: (
490
+ await Promise.all([p.avoid || []].flat().map(async (r) => (r.sweep != null ? swept(r) : [await region(r)])))
491
+ ).flat(),
492
+ supports: await Promise.all(
493
+ p.supports.map(async (s) => ({ ...(await region(s)), fix: s.fix || 'xyz'.slice(0, dim) })),
494
+ ),
495
+ loads: await Promise.all(
496
+ p.loads.map(async (l) => ({ ...(await region(l)), force: pt(l.force), case: l.case || 'load' })),
497
+ ),
255
498
  cases: Object.fromEntries(Object.entries(p.cases || {}).map(([k, w]) => [k, ev(w)])),
256
- material: { E: m.modulus, nu: m.poisson }, ...(dim === 2 ? { thickness: ev(p.thickness) } : {}), cell: ev(p.cell), ...(p.volume != null ? { volume: ev(p.volume) } : {}), ...(p.stress != null ? { stress: ev(p.stress) } : {}), ...(p.strain != null ? { strain: ev(p.strain) } : {}), ...(p.robust ? { robust: true } : {}),
257
- ...(p.filter != null ? { filter: ev(p.filter) } : lines > ev(p.cell) * 1.5 ? { filter: lines } : {}), ...(p.penal != null ? { penal: ev(p.penal) } : {}),
258
- ...(p.projection != null ? { projection: p.projection } : {}), ...(p.steps != null ? { steps: p.steps } : {}),
499
+ material: { E: m.modulus, nu: m.poisson },
500
+ ...(dim === 2 ? { thickness: ev(p.thickness) } : {}),
501
+ cell: ev(p.cell),
502
+ ...(p.volume != null ? { volume: ev(p.volume) } : {}),
503
+ ...(p.stress != null ? { stress: ev(p.stress) } : {}),
504
+ ...(p.strain != null ? { strain: ev(p.strain) } : {}),
505
+ ...(p.robust ? { robust: true } : {}),
506
+ ...(p.filter != null ? { filter: ev(p.filter) } : lines > ev(p.cell) * 1.5 ? { filter: lines } : {}),
507
+ ...(p.penal != null ? { penal: ev(p.penal) } : {}),
508
+ ...(p.projection != null ? { projection: p.projection } : {}),
509
+ ...(p.steps != null ? { steps: p.steps } : {}),
259
510
  ...(overhang && overhang !== 'none' ? { overhang } : {}),
260
511
  // How it's made other than printed: milled from a side, cast in a mould; symmetric, extruded (topopt's filters)
261
- ...(millSides ? { mill: millSides } : {}), ...(castWay ? { cast: typeof castWay === 'string' ? castWay : { draw: castWay.draw, ...(castWay.parting != null ? { parting: ev(castWay.parting) } : {}) } } : {}),
512
+ ...(millSides ? { mill: millSides } : {}),
513
+ ...(castWay
514
+ ? {
515
+ cast:
516
+ typeof castWay === 'string'
517
+ ? castWay
518
+ : { draw: castWay.draw, ...(castWay.parting != null ? { parting: ev(castWay.parting) } : {}) },
519
+ }
520
+ : {}),
262
521
  // (a tool or draft with the process switched off by its variable is left out with it; one with no such process
263
522
  // at all goes on, for topopt to refuse by name)
264
- ...(p.tool != null && (millSides || !p.mill) ? { tool: ev(p.tool) } : {}), ...(p.draft != null && (castWay || !p.cast) ? { draft: ev(p.draft) } : {}), ...(p.voids === 'prevented' ? { voids: 'prevented' } : {}),
523
+ ...(p.tool != null && (millSides || !p.mill) ? { tool: ev(p.tool) } : {}),
524
+ ...(p.draft != null && (castWay || !p.cast) ? { draft: ev(p.draft) } : {}),
525
+ ...(p.voids === 'prevented' ? { voids: 'prevented' } : {}),
265
526
  ...(p.feature != null ? { feature: ev(p.feature) } : {}),
266
- ...(p.symmetry ? { symmetry: p.symmetry } : {}), ...(p.extrude ? { extrude: p.extrude } : {}),
527
+ ...(p.symmetry ? { symmetry: p.symmetry } : {}),
528
+ ...(p.extrude ? { extrude: p.extrude } : {}),
267
529
  // A mechanism: where the output should move, along one axis, against a spring; a spring the input pushes against
268
- ...(p.output ? { output: { ...(await region(p.output)), direction: pt(p.output.direction), ...(p.output.spring != null ? { spring: ev(p.output.spring) } : {}) } } : {}),
530
+ ...(p.output
531
+ ? {
532
+ output: {
533
+ ...(await region(p.output)),
534
+ direction: pt(p.output.direction),
535
+ ...(p.output.spring != null ? { spring: ev(p.output.spring) } : {}),
536
+ },
537
+ }
538
+ : {}),
269
539
  ...(p.input_spring != null ? { input_spring: ev(p.input_spring) } : {}),
270
540
  };
271
- if (dim === 2 && !(problem.thickness > 0)) throw new Error(`${path.basename(file)}: a flat (2D) problem needs a thickness`);
272
- const outline = { smooth: p.outline?.smooth ?? 4, minArea: p.outline?.min_area != null ? ev(p.outline.min_area) : problem.cell ** 2 * 2, fine: p.outline?.fine != null ? ev(p.outline.fine) : 1.25, ...(dim === 3 && p.outline?.reduce !== false ? { reduce: p.outline?.reduce != null ? ev(p.outline.reduce) : REDUCE } : {}) }; // fine: the cells a printable solid is cleaned and drawn on, mm (its own cells if smaller)
541
+ if (dim === 2 && !(problem.thickness > 0))
542
+ throw new Error(`${path.basename(file)}: a flat (2D) problem needs a thickness`);
543
+ const outline = {
544
+ smooth: p.outline?.smooth ?? 4,
545
+ minArea: p.outline?.min_area != null ? ev(p.outline.min_area) : problem.cell ** 2 * 2,
546
+ fine: p.outline?.fine != null ? ev(p.outline.fine) : 1.25,
547
+ ...(dim === 3 && p.outline?.reduce !== false
548
+ ? { reduce: p.outline?.reduce != null ? ev(p.outline.reduce) : REDUCE }
549
+ : {}),
550
+ }; // fine: the cells a printable solid is cleaned and drawn on, mm (its own cells if smaller)
273
551
  // A printable solid's surface is kept within the printer's overhang limit too (smoothing can tip faces past it)
274
552
  // (outline.tip: faces the smoothing left steeper than the limit are tipped back to it too; off unless asked, since
275
553
  // tipped corners leave dips that slice as islands, and the layers step out no further for it)
276
- if (dim === 3 && problem.overhang) { const n = printerOf(project), pr = resolve({ uses: [n] }).values[n]; outline.overhang = { up: problem.overhang, angle: pr?.overhang ?? 45, bridge: pr?.bridge ?? 5, layer: pr?.layer ?? 0.2, line: pr?.line ?? 0.42, ...(p.outline?.tip ? { tip: true } : {}) }; problem.bridge = outline.overhang.bridge; } // (the optimiser bridges half that)
554
+ if (dim === 3 && problem.overhang) {
555
+ const n = printerOf(project),
556
+ pr = resolve({ uses: [n] }).values[n];
557
+ outline.overhang = {
558
+ up: problem.overhang,
559
+ angle: pr?.overhang ?? 45,
560
+ bridge: pr?.bridge ?? 5,
561
+ layer: pr?.layer ?? 0.2,
562
+ line: pr?.line ?? 0.42,
563
+ ...(p.outline?.tip ? { tip: true } : {}),
564
+ };
565
+ problem.bridge = outline.overhang.bridge;
566
+ } // (the optimiser bridges half that)
277
567
  // What the result is made from, for cad why: the rule sets, the problem's own values, the parts and anchors of other
278
568
  // designs it reads, and where its filter came from
279
- const inputs = { uses, variables: Object.fromEntries(Object.keys(p.variables || {}).map((k) => [k, values[k]])), ...(variant ? { set: p.variants[variant] } : {}),
280
- parts: [...parts.keys()].sort(), ...(p.in ? { assembly: { name: p.in.assembly, item: p.in.item, pose: placing ? (await placing).s.pose : p.in.pose ?? null, joints: [...joints.values()].sort((a, b) => (a.joint < b.joint ? -1 : 1)).map(({ joint: j, at }) => ({ joint: j, at: at.map((c) => round(c, 4)) })), sweeps } } : {}), anchors: [...anchors.values()].sort((a, b) => (a.anchor < b.anchor ? -1 : 1)).map(({ anchor: a, at }) => ({ anchor: a, at: at.map((c) => round(c, 4)) })),
281
- filter: p.filter != null ? { value: problem.filter, from: `the problem: ${p.filter}` } : problem.filter ? { value: problem.filter, from: `two of ${printer}'s lines (2 × ${line} mm), more than a cell and a half` } : { value: round(problem.cell * 1.5), from: 'a cell and a half' } };
282
- return { ref, name, variant, file, dim, title: p.title || name, material: { name: p.material, ...m }, problem, outline, critical: !!p.critical, inputs, voids: p.voids || 'allowed' };
569
+ const inputs = {
570
+ uses,
571
+ variables: Object.fromEntries(Object.keys(p.variables || {}).map((k) => [k, values[k]])),
572
+ ...(variant ? { set: p.variants[variant] } : {}),
573
+ parts: [...parts.keys()].sort(),
574
+ ...(p.in
575
+ ? {
576
+ assembly: {
577
+ name: p.in.assembly,
578
+ item: p.in.item,
579
+ pose: placing ? (await placing).s.pose : (p.in.pose ?? null),
580
+ joints: [...joints.values()]
581
+ .sort((a, b) => (a.joint < b.joint ? -1 : 1))
582
+ .map(({ joint: j, at }) => ({ joint: j, at: at.map((c) => round(c, 4)) })),
583
+ sweeps,
584
+ },
585
+ }
586
+ : {}),
587
+ anchors: [...anchors.values()]
588
+ .sort((a, b) => (a.anchor < b.anchor ? -1 : 1))
589
+ .map(({ anchor: a, at }) => ({ anchor: a, at: at.map((c) => round(c, 4)) })),
590
+ filter:
591
+ p.filter != null
592
+ ? { value: problem.filter, from: `the problem: ${p.filter}` }
593
+ : problem.filter
594
+ ? { value: problem.filter, from: `two of ${printer}'s lines (2 × ${line} mm), more than a cell and a half` }
595
+ : { value: round(problem.cell * 1.5), from: 'a cell and a half' },
596
+ };
597
+ return {
598
+ ref,
599
+ name,
600
+ variant,
601
+ file,
602
+ dim,
603
+ title: p.title || name,
604
+ material: { name: p.material, ...m },
605
+ problem,
606
+ outline,
607
+ critical: !!p.critical,
608
+ inputs,
609
+ voids: p.voids || 'allowed',
610
+ };
283
611
  }
284
612
 
285
613
  /**
@@ -292,8 +620,12 @@ async function readOne(project, ref, link) {
292
620
  // Nodes no cell that may be solid touches (the grid's corners outside a shaped space, the inside of avoided pockets)
293
621
  // are held: at the void's near-nothing stiffness they are what the solver crawls through, and they carry no material
294
622
  function holdEmpty(spec) {
295
- const g = makeGrid(spec.grid), dim = spec.grid.nz ? 3 : 2, corners = 1 << dim, on = new Uint8Array(g.nodes);
296
- for (let e = 0; e < g.cells; e++) if (spec.passive[e] >= 0) for (let k = 0; k < corners; k++) on[g.edof[e * g.cellDofs + dim * k] / dim] = 1;
623
+ const g = makeGrid(spec.grid),
624
+ dim = spec.grid.nz ? 3 : 2,
625
+ corners = 1 << dim,
626
+ on = new Uint8Array(g.nodes);
627
+ for (let e = 0; e < g.cells; e++)
628
+ if (spec.passive[e] >= 0) for (let k = 0; k < corners; k++) on[g.edof[e * g.cellDofs + dim * k] / dim] = 1;
297
629
  for (let m = 0; m < g.nodes; m++) if (!on[m]) for (let a = 0; a < dim; a++) spec.fixed[dim * m + a] = 1;
298
630
  return spec;
299
631
  }
@@ -302,43 +634,87 @@ function holdEmpty(spec) {
302
634
  // refused or prevented (a powder bed print, a trapped core), each void left with its volume (mm³, or mm² in 2D) and
303
635
  // where it is, and with prevented that they were
304
636
  function made(r, spec, density) {
305
- const p = r.problem, out = {};
637
+ const p = r.problem,
638
+ out = {};
306
639
  if (p.mill || p.cast) {
307
- const c = spec.cast, from = p.mill || (typeof c === 'string' ? c : c.draw), tool = p.tool ? p.tool / spec.grid.h : undefined;
308
- const u = undercuts(spec.grid, density, { from, ...(c && typeof c === 'object' ? { parting: c.parting } : {}), ...(p.draft ? { draft: p.draft } : {}) });
640
+ const c = spec.cast,
641
+ from = p.mill || (typeof c === 'string' ? c : c.draw),
642
+ tool = p.tool ? p.tool / spec.grid.h : undefined;
643
+ const u = undercuts(spec.grid, density, {
644
+ from,
645
+ ...(c && typeof c === 'object' ? { parting: c.parting } : {}),
646
+ ...(p.draft ? { draft: p.draft } : {}),
647
+ });
309
648
  // With a tool's size: the cells it can't get its end into besides, in the design (none, by construction) and in
310
649
  // avoid regions (a hole narrower than the tool: drilled, or a smaller tool)
311
650
  if (tool) {
312
- const hidden = new Set(u.cells), narrow = undercuts(spec.grid, density, { from, tool }).cells.filter((e) => !hidden.has(e));
313
- out.narrow = { design: narrow.filter((e) => spec.passive[e] === 0).length, avoided: narrow.filter((e) => spec.passive[e] === -1).length };
651
+ const hidden = new Set(u.cells),
652
+ narrow = undercuts(spec.grid, density, { from, tool }).cells.filter((e) => !hidden.has(e));
653
+ out.narrow = {
654
+ design: narrow.filter((e) => spec.passive[e] === 0).length,
655
+ avoided: narrow.filter((e) => spec.passive[e] === -1).length,
656
+ };
314
657
  }
315
658
  // (a draft at the grid: a step out every whole number of layers in 1 / tan, so the angle made is atan of one over it)
316
659
  const every = p.draft ? Math.max(1, Math.floor(1 / Math.tan((p.draft * Math.PI) / 180) + 1e-9)) : 0;
317
- out.process = p.mill ? { mill: p.mill, ...(p.tool ? { tool: p.tool } : {}) } : { cast: typeof c === 'string' ? c : { draw: c.draw, parting: round(c.at, 3) }, ...(every ? { draft: p.draft, every, made: round((Math.atan(1 / every) * 180) / Math.PI, 2) } : {}) };
660
+ out.process = p.mill
661
+ ? { mill: p.mill, ...(p.tool ? { tool: p.tool } : {}) }
662
+ : {
663
+ cast: typeof c === 'string' ? c : { draw: c.draw, parting: round(c.at, 3) },
664
+ ...(every ? { draft: p.draft, every, made: round((Math.atan(1 / every) * 180) / Math.PI, 2) } : {}),
665
+ };
318
666
  out.undercuts = u.count;
319
667
  }
320
668
  if (p.symmetry) out.symmetry = p.symmetry;
321
669
  if (p.extrude) out.extrude = p.extrude;
322
670
  // How grey it came out: a process or a tie can leave no clear part (a 2D section milled from its side)
323
671
  if (p.mill || p.cast || p.symmetry || p.extrude) out.grey = round(grey(density, spec.passive), 3);
324
- if (r.voids === 'refused' || r.voids === 'prevented') out.voids = voids(spec.grid, density, { origin: spec.origin }).map((v) => ({ volume: round(v.volume, 3), at: v.at.map((x) => round(x, 3)) }));
672
+ if (r.voids === 'refused' || r.voids === 'prevented')
673
+ out.voids = voids(spec.grid, density, { origin: spec.origin }).map((v) => ({
674
+ volume: round(v.volume, 3),
675
+ at: v.at.map((x) => round(x, 3)),
676
+ }));
325
677
  if (r.voids === 'prevented') out.vented = true;
326
678
  // The thinnest member asked: the ball's radius on the grid, the width it holds members to (a cell, where the grid
327
679
  // already does), and the solid cells left in members narrower (or on a square outside corner)
328
680
  if (p.feature != null) {
329
- const h = spec.grid.h, cells = featureCells(p.feature, h);
330
- out.feature = { asked: p.feature, cells, holds: round((2 * cells + 1) * h, 3), thin: cells ? thin(spec.grid, density, { radius: cells }).count : 0 };
681
+ const h = spec.grid.h,
682
+ cells = featureCells(p.feature, h);
683
+ out.feature = {
684
+ asked: p.feature,
685
+ cells,
686
+ holds: round((2 * cells + 1) * h, 3),
687
+ thin: cells ? thin(spec.grid, density, { radius: cells }).count : 0,
688
+ };
331
689
  }
332
690
  return out;
333
691
  }
334
692
  const digest = (x) => crypto.createHash('sha256').update(JSON.stringify(x)).digest('hex');
693
+ /**
694
+ * Throws (code workspace.outside, naming the link) where the kept results optimised() reads (.cache/optimise,
695
+ * .cache/densities) hold a link out of the workspace: a cloned workspace may carry a .cache/ of its own. Called before
696
+ * optimised(), as its own text is part of the densities key (densityCode).
697
+ */
698
+ export const ownResults = () => noLinksOut([paths.cache('optimise'), paths.cache('densities')]);
699
+ // The solver's share of topopt's file: the code above this line, which decides the densities (all model() calls, the
700
+ // virtual temperature among them: cache-salts.test.mjs holds it so); below it, only how a shape is drawn from them
701
+ const SHAPES_FROM_RESULTS = '// ---------- shapes from results ----------';
335
702
  /**
336
703
  * The code an optimisation's densities are made by, each piece by name: this file's VERSION, topopt's solver (its file
337
704
  * up to its shapes from results), the FE's code and its threads backend (the solver's products), and cad's own code
338
- * that readies the problem for the solver (holdEmpty). Drawing a shape from the densities is not in it.
705
+ * that readies the problem for the solver (holdEmpty, and optimised, which calls it). Drawing a shape from the
706
+ * densities is not in it. Each is the code without its comment lines and blank lines (codeOnly), so rewording a
707
+ * comment keeps the densities, and any change to the code optimises again.
708
+ * @param {(module: string) => string} [read] reads a module's text by its name (tests read an edited copy)
339
709
  * @returns {{ version: number, solver: string, fea: string, threads: string, cad: string }}
340
710
  */
341
- export const densityCode = () => ({ version: VERSION, solver: source('@rulecad/topopt').split('// ---------- shapes from results ----------')[0], fea: source('@rulecad/fea'), threads: source('@rulecad/fea/threads'), cad: `${holdEmpty.toString()}\n${optimised.toString()}` });
711
+ export const densityCode = (read = source) => ({
712
+ version: VERSION,
713
+ solver: codeOnly(read('@rulecad/topopt').split(SHAPES_FROM_RESULTS)[0]),
714
+ fea: codeOnly(read('@rulecad/fea')),
715
+ threads: codeOnly(read('@rulecad/fea/threads')),
716
+ cad: codeOnly(`${holdEmpty.toString()}\n${optimised.toString()}`),
717
+ });
342
718
  /**
343
719
  * The key an optimisation's densities are kept by (.cache/densities/<key>.json): the problem and every piece of
344
720
  * densityCode (cad's own share is holdEmpty and optimised, which readies the problem and calls the solver with its
@@ -346,114 +722,238 @@ export const densityCode = () => ({ version: VERSION, solver: source('@rulecad/t
346
722
  * the folder (scripts/dimension-diff.mjs).
347
723
  * @param {object} problem readProblem's problem @param {ReturnType<typeof densityCode>} [code] @returns {string}
348
724
  */
349
- export const densitiesKey = (problem, code = densityCode()) => digest([code.version, problem, code.solver, code.fea, code.threads, code.cad]);
725
+ export const densitiesKey = (problem, code = densityCode()) =>
726
+ digest([code.version, problem, code.solver, code.fea, code.threads, code.cad]);
350
727
  export async function optimised(project, ref, { onStep, onRun, fresh = false } = {}) {
351
- const r = await readProblem(project, ref), topopt = source('@rulecad/topopt');
728
+ const r = await readProblem(project, ref),
729
+ topopt = source('@rulecad/topopt');
352
730
  // Two keeps: the densities, by the problem and the code that decides them (the slow part), and the shape drawn from
353
731
  // them, by everything: a change to how shapes are drawn redraws them without optimising again
354
732
  // The shape's key holds this file too, so a change to how cad draws a result (anchored below) redraws it
355
- const hash = digest([VERSION, r.problem, r.outline, r.voids, topopt, source('@rulecad/fea'), fs.readFileSync(new URL(import.meta.url), 'utf8')]), file = paths.cache('optimise', `${hash}.json`);
356
- if (!fresh && !process.env.CAD_NO_CACHE && host.exists(file)) return { ...JSON.parse(host.readText(file)), cached: true };
357
- const spec = holdEmpty(discretise(r.problem)), densities = paths.cache('densities', `${densitiesKey(r.problem)}.json`);
733
+ const hash = digest([
734
+ VERSION,
735
+ r.problem,
736
+ r.outline,
737
+ r.voids,
738
+ topopt,
739
+ source('@rulecad/fea'),
740
+ fs.readFileSync(new URL(import.meta.url), 'utf8'),
741
+ ]),
742
+ file = paths.cache('optimise', `${hash}.json`);
743
+ const shapeKept = !fresh && !process.env.CAD_NO_CACHE && readCacheJson(file); // (one cut short or spoiled: a miss)
744
+ if (shapeKept) return { ...shapeKept, cached: true };
745
+ const spec = holdEmpty(discretise(r.problem)),
746
+ densities = paths.cache('densities', `${densitiesKey(r.problem)}.json`);
358
747
  // A mark that this problem has been optimised before (by any solver), so a run can say whether it's the solver that changed
359
748
  const seen = paths.cache('densities', `${digest([VERSION, r.problem])}.seen`);
360
- if (!fresh && !process.env.CAD_NO_CACHE && !host.exists(densities)) onRun?.(host.exists(seen) ? 'the solver has changed since its last result' : 'no result yet');
749
+ const densitiesKept = !fresh && !process.env.CAD_NO_CACHE ? readCacheJson(densities) : undefined;
750
+ if (!fresh && !process.env.CAD_NO_CACHE && !densitiesKept)
751
+ onRun?.(host.exists(seen) ? 'the solver has changed since its last result' : 'no result yet');
361
752
  else if (fresh) onRun?.('asked to run afresh');
362
- const o = !fresh && !process.env.CAD_NO_CACHE && host.exists(densities) ? (({ density, ...x }) => ({ ...x, density: Float64Array.from(density) }))(JSON.parse(host.readText(densities))) : optimise(spec, { backend: threadsBackend, onStep: onStep && ((st) => onStep({ ...st, grid: spec.grid })) });
363
- if (!host.exists(densities)) host.writeText(densities, JSON.stringify({ ...o, density: Array.from(o.density) }));
364
- if (!host.exists(seen)) host.writeText(seen, '');
753
+ const o = densitiesKept
754
+ ? (({ density, ...x }) => ({ ...x, density: Float64Array.from(density) }))(densitiesKept)
755
+ : optimise(spec, { backend: threadsBackend, onStep: onStep && ((st) => onStep({ ...st, grid: spec.grid })) });
756
+ if (!host.exists(densities)) writeCacheFile(densities, JSON.stringify({ ...o, density: Array.from(o.density) }));
757
+ if (!host.exists(seen)) writeCacheFile(seen, '');
365
758
  // Regions as data: a part's triangles are named, not copied
366
759
  const named = (list) => list.map(({ triangles, ...x }) => x);
367
- const shape = r.dim === 2 ? (() => {
368
- const loops = outlines(spec.grid, o.density, spec.origin, r.outline);
369
- return { outlines: loops.map((l) => l.map(([x, y]) => [round(x), round(y)])), area: loops.reduce((s, l) => s + area(l), 0) };
370
- })() : (() => {
371
- // The surface's level, found so the solid holds as much material as the optimised densities do (drawn at 0.5,
372
- // thin members come out thinner than they are)
373
- // Printed without supports: before it's drawn at a level, whatever wouldn't print at that level (hanging with nothing
374
- // under it) is emptied (printable, in topopt); kept regions stay. A bridge may run out half the printer's span.
375
- const ov = r.outline.overhang, coarseKeep = Uint8Array.from(spec.passive, (p) => (p === 1 ? 1 : 0)), emptied = new Map();
376
- const cleaned = (grid, density, keep, iso) => {
377
- if (!ov) return density;
378
- const reach = Math.floor(ov.bridge / 2 / grid.h);
379
- // Spikes off the underside first (a hanging cell with few neighbours), then whatever is left hanging, in turn until neither finds any
380
- let d = density, gone = 0;
381
- for (let round = 0; round < 10; round++) {
382
- const sp = despike(grid, d, { up: ov.up, iso, keep }), c = printable(grid, sp.density, { up: ov.up, iso, keep, reach });
383
- d = c.density; gone += sp.emptied + c.emptied;
384
- if (!sp.emptied && !c.emptied) break;
385
- }
386
- emptied.set(iso, gone);
387
- return d;
388
- };
389
- // The surface's level, found so the solid holds as much material as the optimised densities do (drawn at 0.5,
390
- // thin members come out thinner than they are): found on the grid it was optimised on, which is quick
391
- const want = o.density.reduce((t, d) => t + d, 0) * spec.grid.h ** 3, draw = (grid, density, keep, iso) => surface(grid, cleaned(grid, density, keep, iso), spec.origin, { smooth: r.outline.smooth, iso, overhang: ov });
392
- let lo = 0.2, hi = 0.8, best = draw(spec.grid, o.density, coarseKeep, 0.5), iso = 0.5;
393
- for (let k = 0; k < 10 && Math.abs(meshVolume(best.vertices, best.faces) / want - 1) > 0.003; k++) {
394
- if (meshVolume(best.vertices, best.faces) < want) hi = iso; else lo = iso; // a lower level encloses more
395
- iso = (lo + hi) / 2; best = draw(spec.grid, o.density, coarseKeep, iso);
396
- }
397
- // Then drawn on a finer grid (cells no bigger than the outline's fine size, 1 mm), so the cleaning works at nearer
398
- // the printer's resolution: between two coarse cells the surface can dip under the overhang line, which sliced is an
399
- // island; on the fine grid those dips are cells of their own, and go. One correction of the level for the volume.
400
- const cells = spec.grid.nx * spec.grid.ny * spec.grid.nz, factor = ov ? Math.max(1, Math.min(Math.ceil(spec.grid.h / (r.outline.fine ?? 1) - 1e-9), Math.floor(Math.cbrt(2e6 / cells)))) : 1; // and no more than about two million fine cells
401
- const fine = factor > 1 ? refine(spec.grid, o.density, factor, { keep: coarseKeep, smooth: 1 }) : null;
402
- let cleared = 0;
403
- if (fine) {
404
- best = draw(fine.grid, fine.density, fine.keep, iso);
405
- const ratio = meshVolume(best.vertices, best.faces) / want;
406
- if (Math.abs(ratio - 1) > 0.01) { iso = Math.min(0.8, Math.max(0.2, iso + (ratio - 1) * 0.3)); best = draw(fine.grid, fine.density, fine.keep, iso); } // a touch up or down the level
407
- // Then as the printer will see it: sliced into layers, each against the one below. Wherever a layer's region has
408
- // nothing under it (an island, which the printer lays on air), the fine cells it starts from are emptied, the
409
- // cleaning takes whatever hung on them, and it's drawn again, until a slice finds none (each round a redraw)
410
- const { nx, ny, nz, h } = fine.grid, [ox, oy, oz] = spec.origin;
411
- if ('xyz'.indexOf(ov.up[1]) === 2) for (let round = 0; round < 4; round++) { // (the slicer's layers are along z: a part is drawn in its print orientation); a safety net: the drawing leaves none as a rule
412
- const found = islands(best.faces.map((f) => f.map((n) => best.vertices[n])), { layer: ov.layer, overhang: ov.angle, line: ov.line }).islands;
413
- if (!found.length) break;
414
- let hit = 0;
415
- const clear = (i, j, k) => { if (i < 0 || i >= nx || j < 0 || j >= ny || k < 0 || k >= nz) return 0; const e = (k * ny + j) * nx + i; if (fine.density[e] > 0 && !fine.keep[e]) { fine.density[e] = 0; return 1; } return 0; };
416
- for (const isl of found) {
417
- let own = 0;
418
- for (const [x, y] of isl.cells) { const i = Math.floor((x - ox) / h), j = Math.floor((y - oy) / h), k0 = Math.floor((isl.z - oz) / h); own += clear(i, j, k0) + clear(i, j, k0 + 1); } // the cell the island starts in and the one above it
419
- // Its own cells already empty: the island is drawn from the cells round them, so those go too
420
- if (!own) for (const [x, y] of isl.cells) { const i0 = Math.floor((x - ox) / h), j0 = Math.floor((y - oy) / h), k0 = Math.floor((isl.z - oz) / h); for (let k = k0; k <= k0 + 1; k++) for (let j = j0 - 1; j <= j0 + 1; j++) for (let i = i0 - 1; i <= i0 + 1; i++) own += clear(i, j, k); }
421
- hit += own;
422
- }
423
- cleared += hit;
424
- if (!hit) break;
425
- best = draw(fine.grid, fine.density, fine.keep, iso);
426
- }
427
- }
428
- const anchors = [...r.problem.supports, ...r.problem.loads, ...(r.problem.keep || [])].map(bounds);
429
- let { vertices, faces, dropped } = anchored(best, anchors, (fine ?? { grid: spec.grid }).grid.h), reduced = null;
430
- // Fewer triangles, if asked: within outline.reduce mm of the surface as drawn, closed, and no more overhang or tips
431
- if (r.outline.reduce != null) {
432
- const { nx, ny, nz, h } = spec.grid, lo = spec.origin, hi = [lo[0] + nx * h, lo[1] + ny * h, lo[2] + nz * h], before = faces.length;
433
- ({ vertices, faces } = reduce({ vertices, faces }, { tolerance: r.outline.reduce, lo, hi, ...(ov ? { overhang: { up: ov.up, angle: ov.angle } } : {}) }));
434
- reduced = { before, after: faces.length, tolerance: r.outline.reduce };
435
- }
436
- return { mesh: { vertices: vertices.map((v) => v.map((c) => round(c, 3))), faces }, solid: meshVolume(vertices, faces), iso, ...(reduced ? { reduced } : {}), ...(dropped.length ? { dropped } : {}), ...(emptied.get(iso) ? { emptied: emptied.get(iso) } : {}), ...(cleared ? { cleared } : {}) };
437
- })();
760
+ const shape =
761
+ r.dim === 2
762
+ ? (() => {
763
+ const loops = outlines(spec.grid, o.density, spec.origin, r.outline);
764
+ return {
765
+ outlines: loops.map((l) => l.map(([x, y]) => [round(x), round(y)])),
766
+ area: loops.reduce((s, l) => s + area(l), 0),
767
+ };
768
+ })()
769
+ : (() => {
770
+ // The surface's level, found so the solid holds as much material as the optimised densities do (drawn at 0.5,
771
+ // thin members come out thinner than they are)
772
+ // Printed without supports: before it's drawn at a level, whatever wouldn't print at that level (hanging with nothing
773
+ // under it) is emptied (printable, in topopt); kept regions stay. A bridge may run out half the printer's span.
774
+ const ov = r.outline.overhang,
775
+ coarseKeep = Uint8Array.from(spec.passive, (p) => (p === 1 ? 1 : 0)),
776
+ emptied = new Map();
777
+ const cleaned = (grid, density, keep, iso) => {
778
+ if (!ov) return density;
779
+ const reach = Math.floor(ov.bridge / 2 / grid.h);
780
+ // Spikes off the underside first (a hanging cell with few neighbours), then whatever is left hanging, in turn until neither finds any
781
+ let d = density,
782
+ gone = 0;
783
+ for (let round = 0; round < 10; round++) {
784
+ const sp = despike(grid, d, { up: ov.up, iso, keep }),
785
+ c = printable(grid, sp.density, { up: ov.up, iso, keep, reach });
786
+ d = c.density;
787
+ gone += sp.emptied + c.emptied;
788
+ if (!sp.emptied && !c.emptied) break;
789
+ }
790
+ emptied.set(iso, gone);
791
+ return d;
792
+ };
793
+ // The surface's level, found so the solid holds as much material as the optimised densities do (drawn at 0.5,
794
+ // thin members come out thinner than they are): found on the grid it was optimised on, which is quick
795
+ const want = o.density.reduce((t, d) => t + d, 0) * spec.grid.h ** 3,
796
+ draw = (grid, density, keep, iso) =>
797
+ surface(grid, cleaned(grid, density, keep, iso), spec.origin, {
798
+ smooth: r.outline.smooth,
799
+ iso,
800
+ overhang: ov,
801
+ });
802
+ let lo = 0.2,
803
+ hi = 0.8,
804
+ best = draw(spec.grid, o.density, coarseKeep, 0.5),
805
+ iso = 0.5;
806
+ for (let k = 0; k < 10 && Math.abs(meshVolume(best.vertices, best.faces) / want - 1) > 0.003; k++) {
807
+ if (meshVolume(best.vertices, best.faces) < want) hi = iso;
808
+ else lo = iso; // a lower level encloses more
809
+ iso = (lo + hi) / 2;
810
+ best = draw(spec.grid, o.density, coarseKeep, iso);
811
+ }
812
+ // Then drawn on a finer grid (cells no bigger than the outline's fine size, 1 mm), so the cleaning works at nearer
813
+ // the printer's resolution: between two coarse cells the surface can dip under the overhang line, which sliced is an
814
+ // island; on the fine grid those dips are cells of their own, and go. One correction of the level for the volume.
815
+ const cells = spec.grid.nx * spec.grid.ny * spec.grid.nz,
816
+ factor = ov
817
+ ? Math.max(
818
+ 1,
819
+ Math.min(Math.ceil(spec.grid.h / (r.outline.fine ?? 1) - 1e-9), Math.floor(Math.cbrt(2e6 / cells))),
820
+ )
821
+ : 1; // and no more than about two million fine cells
822
+ const fine = factor > 1 ? refine(spec.grid, o.density, factor, { keep: coarseKeep, smooth: 1 }) : null;
823
+ let cleared = 0;
824
+ if (fine) {
825
+ best = draw(fine.grid, fine.density, fine.keep, iso);
826
+ const ratio = meshVolume(best.vertices, best.faces) / want;
827
+ if (Math.abs(ratio - 1) > 0.01) {
828
+ iso = Math.min(0.8, Math.max(0.2, iso + (ratio - 1) * 0.3));
829
+ best = draw(fine.grid, fine.density, fine.keep, iso);
830
+ } // a touch up or down the level
831
+ // Then as the printer will see it: sliced into layers, each against the one below. Wherever a layer's region has
832
+ // nothing under it (an island, which the printer lays on air), the fine cells it starts from are emptied, the
833
+ // cleaning takes whatever hung on them, and it's drawn again, until a slice finds none (each round a redraw)
834
+ const { nx, ny, nz, h } = fine.grid,
835
+ [ox, oy, oz] = spec.origin;
836
+ if ('xyz'.indexOf(ov.up[1]) === 2)
837
+ for (let round = 0; round < 4; round++) {
838
+ // (the slicer's layers are along z: a part is drawn in its print orientation); a safety net: the drawing leaves none as a rule
839
+ const found = islands(
840
+ best.faces.map((f) => f.map((n) => best.vertices[n])),
841
+ { layer: ov.layer, overhang: ov.angle, line: ov.line },
842
+ ).islands;
843
+ if (!found.length) break;
844
+ let hit = 0;
845
+ const clear = (i, j, k) => {
846
+ if (i < 0 || i >= nx || j < 0 || j >= ny || k < 0 || k >= nz) return 0;
847
+ const e = (k * ny + j) * nx + i;
848
+ if (fine.density[e] > 0 && !fine.keep[e]) {
849
+ fine.density[e] = 0;
850
+ return 1;
851
+ }
852
+ return 0;
853
+ };
854
+ for (const isl of found) {
855
+ let own = 0;
856
+ for (const [x, y] of isl.cells) {
857
+ const i = Math.floor((x - ox) / h),
858
+ j = Math.floor((y - oy) / h),
859
+ k0 = Math.floor((isl.z - oz) / h);
860
+ own += clear(i, j, k0) + clear(i, j, k0 + 1);
861
+ } // the cell the island starts in and the one above it
862
+ // Its own cells already empty: the island is drawn from the cells round them, so those go too
863
+ if (!own)
864
+ for (const [x, y] of isl.cells) {
865
+ const i0 = Math.floor((x - ox) / h),
866
+ j0 = Math.floor((y - oy) / h),
867
+ k0 = Math.floor((isl.z - oz) / h);
868
+ for (let k = k0; k <= k0 + 1; k++)
869
+ for (let j = j0 - 1; j <= j0 + 1; j++)
870
+ for (let i = i0 - 1; i <= i0 + 1; i++) own += clear(i, j, k);
871
+ }
872
+ hit += own;
873
+ }
874
+ cleared += hit;
875
+ if (!hit) break;
876
+ best = draw(fine.grid, fine.density, fine.keep, iso);
877
+ }
878
+ }
879
+ const anchors = [...r.problem.supports, ...r.problem.loads, ...(r.problem.keep || [])].map(bounds);
880
+ let { vertices, faces, dropped } = anchored(best, anchors, (fine ?? { grid: spec.grid }).grid.h),
881
+ reduced = null;
882
+ // Fewer triangles, if asked: within outline.reduce mm of the surface as drawn, closed, and no more overhang or tips
883
+ if (r.outline.reduce != null) {
884
+ const { nx, ny, nz, h } = spec.grid,
885
+ lo = spec.origin,
886
+ hi = [lo[0] + nx * h, lo[1] + ny * h, lo[2] + nz * h],
887
+ before = faces.length;
888
+ ({ vertices, faces } = reduce(
889
+ { vertices, faces },
890
+ { tolerance: r.outline.reduce, lo, hi, ...(ov ? { overhang: { up: ov.up, angle: ov.angle } } : {}) },
891
+ ));
892
+ reduced = { before, after: faces.length, tolerance: r.outline.reduce };
893
+ }
894
+ return {
895
+ mesh: { vertices: vertices.map((v) => v.map((c) => round(c, 3))), faces },
896
+ solid: meshVolume(vertices, faces),
897
+ iso,
898
+ ...(reduced ? { reduced } : {}),
899
+ ...(dropped.length ? { dropped } : {}),
900
+ ...(emptied.get(iso) ? { emptied: emptied.get(iso) } : {}),
901
+ ...(cleared ? { cleared } : {}),
902
+ };
903
+ })();
438
904
  const result = {
439
- problem: ref, title: r.title, hash, dim: r.dim, material: r.material.name, ...(r.dim === 2 ? { thickness: r.problem.thickness } : {}),
440
- grid: spec.grid, origin: spec.origin, regions: { keep: named(spec.regions.keep), avoid: named(spec.regions.avoid) }, ...shape,
905
+ problem: ref,
906
+ title: r.title,
907
+ hash,
908
+ dim: r.dim,
909
+ material: r.material.name,
910
+ ...(r.dim === 2 ? { thickness: r.problem.thickness } : {}),
911
+ grid: spec.grid,
912
+ origin: spec.origin,
913
+ regions: { keep: named(spec.regions.keep), avoid: named(spec.regions.avoid) },
914
+ ...shape,
441
915
  ...made(r, spec, o.density),
442
- volume: o.volume, compliance: o.compliance, cases: o.cases, ...(o.unsupported ? { unsupported: o.unsupported } : {}), ...(o.mechanism ? { mechanism: o.mechanism } : {}), ...(o.stress ? { stress: o.stress } : {}), overhang: r.problem.overhang || null,
443
- steps: o.steps, converged: o.converged, seconds: o.seconds, history: o.history, density: Array.from(o.density, (d) => round(d, 3)),
444
- supports: named(r.problem.supports), loads: named(r.problem.loads),
916
+ volume: o.volume,
917
+ compliance: o.compliance,
918
+ cases: o.cases,
919
+ ...(o.unsupported ? { unsupported: o.unsupported } : {}),
920
+ ...(o.mechanism ? { mechanism: o.mechanism } : {}),
921
+ ...(o.stress ? { stress: o.stress } : {}),
922
+ overhang: r.problem.overhang || null,
923
+ steps: o.steps,
924
+ converged: o.converged,
925
+ seconds: o.seconds,
926
+ history: o.history,
927
+ density: Array.from(o.density, (d) => round(d, 3)),
928
+ supports: named(r.problem.supports),
929
+ loads: named(r.problem.loads),
445
930
  };
446
- host.writeText(file, JSON.stringify(result));
931
+ writeCacheFile(file, JSON.stringify(result));
447
932
  return result;
448
933
  }
449
934
 
450
935
  // A closed mesh's volume (mm³), by the divergence theorem
451
936
  function meshVolume(vertices, faces) {
452
937
  let v = 0;
453
- for (const [i, j, k] of faces) { const a = vertices[i], b = vertices[j], c = vertices[k]; v += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6; }
938
+ for (const [i, j, k] of faces) {
939
+ const a = vertices[i],
940
+ b = vertices[j],
941
+ c = vertices[k];
942
+ v +=
943
+ (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) /
944
+ 6;
945
+ }
454
946
  return v;
455
947
  }
456
948
 
949
+ // Where a flat problem's region is, to draw its mark and to sum a case's loads about: its place, or a polygon's (which
950
+ // has none) the middle of its box
951
+ const placeOf = (r) => {
952
+ if (r.at) return r.at;
953
+ const b = bounds(r);
954
+ return [(b[0] + b[2]) / 2, (b[1] + b[3]) / 2];
955
+ };
956
+
457
957
  // What a design gets as v.problems[name]: the outlines and regions to build from, and the numbers to report
458
958
  export const forDesign = ({ density, history, ...r }) => r;
459
959
 
@@ -466,68 +966,203 @@ export const forDesign = ({ density, history, ...r }) => r;
466
966
  * @param {{ cell?: number }} [options] cell: a finer cell size than the problem's, to check a final shape
467
967
  */
468
968
  export async function analysePart(triangles, project, ref, { cell } = {}) {
469
- const r = await readProblem(project, ref), { problem } = r, h = cell || problem.cell;
470
- if (r.dim === 3) { // kept: a fine analysis of a solid takes minutes
471
- const file = paths.cache('analysis', `${crypto.createHash('sha256').update(JSON.stringify([VERSION, triangles, problem, h, source('@rulecad/topopt'), source('@rulecad/fea'), fs.readFileSync(new URL(import.meta.url), 'utf8')])).digest('hex')}.json`);
472
- if (!process.env.CAD_NO_CACHE && host.exists(file)) { const { density, ...x } = JSON.parse(host.readText(file)); return { ...x, density: Float64Array.from(density) }; }
969
+ const r = await readProblem(project, ref),
970
+ { problem } = r,
971
+ h = cell || problem.cell;
972
+ if (r.dim === 3) {
973
+ // kept: a fine analysis of a solid takes minutes
974
+ const file = paths.cache(
975
+ 'analysis',
976
+ `${crypto
977
+ .createHash('sha256')
978
+ .update(
979
+ JSON.stringify([
980
+ VERSION,
981
+ triangles,
982
+ problem,
983
+ h,
984
+ source('@rulecad/topopt'),
985
+ source('@rulecad/fea'),
986
+ fs.readFileSync(new URL(import.meta.url), 'utf8'),
987
+ ]),
988
+ )
989
+ .digest('hex')}.json`,
990
+ );
991
+ const kept = !process.env.CAD_NO_CACHE && readCacheJson(file);
992
+ if (kept) {
993
+ const { density, ...x } = kept;
994
+ return { ...x, density: Float64Array.from(density) };
995
+ }
473
996
  const out = analyseSolid(triangles, r, h);
474
- host.writeText(file, JSON.stringify({ ...out, density: Array.from(out.density) }));
997
+ writeCacheFile(file, JSON.stringify({ ...out, density: Array.from(out.density) }));
475
998
  return out;
476
999
  }
477
1000
  // The grid covers the part and the problem's space
478
- let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
479
- 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); }
480
- const nx = Math.max(1, Math.ceil((x1 - x0) / h)), ny = Math.max(1, Math.ceil((y1 - y0) / h));
1001
+ let x0 = Infinity,
1002
+ y0 = Infinity,
1003
+ x1 = -Infinity,
1004
+ y1 = -Infinity;
1005
+ for (const t of triangles)
1006
+ for (const [x, y] of t) {
1007
+ x0 = Math.min(x0, x);
1008
+ y0 = Math.min(y0, y);
1009
+ x1 = Math.max(x1, x);
1010
+ y1 = Math.max(y1, y);
1011
+ }
1012
+ const nx = Math.max(1, Math.ceil((x1 - x0) / h)),
1013
+ ny = Math.max(1, Math.ceil((y1 - y0) / h));
481
1014
  const density = fill(triangles, { nx, ny, h, origin: [x0, y0] }, problem.thickness);
482
- const g = makeGrid({ nx, ny, h }), at = positions(g).map(([x, y]) => [x + x0, y + y0]);
483
- // Supports and loads on the nodes near them that touch the part
1015
+ const g = makeGrid({ nx, ny, h }),
1016
+ at = positions(g).map(([x, y]) => [x + x0, y + y0]);
1017
+ // Supports and loads on the nodes of the part inside their regions, read as topopt's discretise reads them for cad
1018
+ // optimise: a box (size) or a point and radius grown by three quarters of a cell, a polygon (points) or another
1019
+ // design's part (its section halfway up) as drawn. (Once a point and a radius only: a box clamping an edge became
1020
+ // one point there and the plate came out nine times too soft, and a polygon crashed the check.)
484
1021
  const onPart = new Uint8Array(g.nodes);
485
- for (let e = 0; e < density.length; e++) if (density[e] >= 0.5) for (let k = 0; k < 4; k++) onPart[g.edof[e * 8 + 2 * k] / 2] = 1;
486
- const near = (p, rr = 0, what) => {
1022
+ for (let e = 0; e < density.length; e++)
1023
+ if (density[e] >= 0.5) for (let k = 0; k < 4; k++) onPart[g.edof[e * 8 + 2 * k] / 2] = 1;
1024
+ const near = (zone, what) => {
1025
+ const d = h * 0.75,
1026
+ grown =
1027
+ zone.points || zone.triangles
1028
+ ? zone
1029
+ : zone.size
1030
+ ? { ...zone, size: zone.size.map((s) => s + 2 * d) }
1031
+ : { ...zone, r: (zone.r || 0) + d };
487
1032
  const found = [];
488
- for (let n = 0; n < g.nodes; n++) if (onPart[n] && Math.hypot(at[n][0] - p[0], at[n][1] - p[1]) <= rr + h * 0.75) found.push(n);
489
- if (!found.length) throw new Error(`${what} at ${p.join(', ')} isn't on the part: is it placed as the problem expects?`);
1033
+ for (let n = 0; n < g.nodes; n++) if (onPart[n] && inside(grown, at[n])) found.push(n);
1034
+ if (!found.length)
1035
+ throw new Error(
1036
+ `${what}${zone.at ? ` at ${zone.at.join(', ')}` : ''} isn't on the part: is it placed as the problem expects?`,
1037
+ );
490
1038
  return found;
491
1039
  };
492
1040
  const fixed = new Uint8Array(g.dofs);
493
- for (const s of problem.supports) for (const n of near(s.at, s.r, 'a support')) { if (s.fix.includes('x')) fixed[2 * n] = 1; if (s.fix.includes('y')) fixed[2 * n + 1] = 1; }
1041
+ for (const s of problem.supports)
1042
+ for (const n of near(s, 'a support')) {
1043
+ if (s.fix.includes('x')) fixed[2 * n] = 1;
1044
+ if (s.fix.includes('y')) fixed[2 * n + 1] = 1;
1045
+ }
494
1046
  const names = [...new Set(problem.loads.map((l) => l.case))];
495
1047
  const loads = names.map((name) => {
496
1048
  const f = new Float64Array(g.dofs);
497
- for (const l of problem.loads.filter((x) => x.case === name)) { const ns = near(l.at, l.r, `the load "${name}"`); for (const n of ns) { f[2 * n] += l.force[0] / ns.length; f[2 * n + 1] += l.force[1] / ns.length; } }
1049
+ for (const l of problem.loads.filter((x) => x.case === name)) {
1050
+ const ns = near(l, `the load "${name}"`);
1051
+ for (const n of ns) {
1052
+ f[2 * n] += l.force[0] / ns.length;
1053
+ f[2 * n + 1] += l.force[1] / ns.length;
1054
+ }
1055
+ }
498
1056
  return f;
499
1057
  });
500
1058
  const a = analyse({ grid: g, density, material: problem.material, thickness: problem.thickness, fixed, loads });
501
1059
  const cases = names.map((name, c) => {
502
- const { size, moment } = resultant(problem.loads.filter((l) => l.case === name));
1060
+ const { size, moment } = resultant(
1061
+ problem.loads.filter((l) => l.case === name).map((l) => ({ ...l, at: placeOf(l) })),
1062
+ );
503
1063
  return measures(name, size, moment, a, c, density, { nx, ny, nz: 1, h }, [x0, y0]);
504
1064
  });
505
- return { problem: ref, dim: 2, material: r.material, critical: r.critical, cases, thin: a.thin, volume: volume(triangles), grid: { nx, ny, h }, origin: [x0, y0], density };
1065
+ return {
1066
+ problem: ref,
1067
+ dim: 2,
1068
+ material: r.material,
1069
+ critical: r.critical,
1070
+ cases,
1071
+ thin: a.thin,
1072
+ volume: volume(triangles),
1073
+ grid: { nx, ny, h },
1074
+ origin: [x0, y0],
1075
+ density,
1076
+ };
506
1077
  }
507
1078
 
508
1079
  // A solid part on the problem's grid: the part itself is the space (keep and avoid regions don't apply), so the
509
1080
  // supports and loads land on it as they would on an optimised layout
510
1081
  function analyseSolid(triangles, r, cell) {
511
- const { problem } = r, spec = discretise({ ...problem, cell, space: { triangles }, keep: [], avoid: [], volume: 1 });
512
- const g = makeGrid(spec.grid), density = solidFill(triangles, spec.grid, spec.origin);
1082
+ const { problem } = r,
1083
+ spec = discretise({ ...problem, cell, space: { triangles }, keep: [], avoid: [], volume: 1 });
1084
+ const g = makeGrid(spec.grid),
1085
+ density = solidFill(triangles, spec.grid, spec.origin);
513
1086
  if (!density.some((d) => d)) throw new Error('the part is smaller than one cell of the problem: use a smaller cell');
514
- const a = analyse({ grid: g, density, material: problem.material, fixed: spec.fixed, loads: spec.loads.map((l) => l.force), backend: threadsBackend });
1087
+ const a = analyse({
1088
+ grid: g,
1089
+ density,
1090
+ material: problem.material,
1091
+ fixed: spec.fixed,
1092
+ loads: spec.loads.map((l) => l.force),
1093
+ backend: threadsBackend,
1094
+ });
515
1095
  const cases = spec.loads.map((l, c) => measures(l.name, l.size, l.moment, a, c, density, spec.grid, spec.origin));
516
- return { problem: r.ref, dim: 3, material: r.material, critical: r.critical, cases, thin: a.thin, volume: volume(triangles), grid: spec.grid, origin: spec.origin, density };
1096
+ return {
1097
+ problem: r.ref,
1098
+ dim: 3,
1099
+ material: r.material,
1100
+ critical: r.critical,
1101
+ cases,
1102
+ thin: a.thin,
1103
+ volume: volume(triangles),
1104
+ grid: spec.grid,
1105
+ origin: spec.origin,
1106
+ density,
1107
+ };
517
1108
  }
518
1109
 
519
1110
  // A load case's numbers: how far the load moves along itself (compliance over force) and the stiffness (a twist: the
520
1111
  // angle it turns, compliance over its moment, and the torsion, N·mm a radian), the largest
521
- // stress in the part and the centre of the cell it's in, and the largest movement of any point of the part and where
1112
+ // stress in the part and the centre of the cell it's in, and the largest movement of any point of the part and where.
1113
+ // The stress is fea's surface stress (analyse().surface): read at the cells' centres, half a cell inside the part, a
1114
+ // bending part's peak reads 10 to 30% low on the cells a part is usually analysed on, and min_safety passed parts
1115
+ // that beam theory fails
522
1116
  function measures(name, force, moment, a, c, density, { nx, ny, h }, origin) {
523
- const deflection = force ? a.compliance[c] / force : 0, angle = moment ? a.compliance[c] / moment : 0;
524
- let most = 0, cellAt = 0;
525
- for (let e = 0; e < density.length; e++) if (density[e] >= 0.5 && a.stress[c][e] > most) { most = a.stress[c][e]; cellAt = e; }
1117
+ const deflection = force ? a.compliance[c] / force : 0,
1118
+ angle = moment ? a.compliance[c] / moment : 0;
1119
+ let most = 0,
1120
+ cellAt = 0;
1121
+ for (let e = 0; e < density.length; e++)
1122
+ if (density[e] >= 0.5 && a.surface[c][e] > most) {
1123
+ most = a.surface[c][e];
1124
+ cellAt = e;
1125
+ }
526
1126
  const index = [cellAt % nx, Math.floor(cellAt / nx) % ny, Math.floor(cellAt / (nx * ny))];
527
- const stressAt = origin.map((o, q) => round(o + (index[q] + 0.5) * h, 2)), d = a.deflection[c];
1127
+ const stressAt = origin.map((o, q) => round(o + (index[q] + 0.5) * h, 2)),
1128
+ d = a.deflection[c];
528
1129
  return {
529
- name, ...(moment ? { moment, angle, torsion: moment / angle } : { force, deflection, stiffness: deflection ? force / deflection : Infinity }), stress: most, stressAt,
530
- movement: d.most, movementAt: d.at.map((x, q) => round(x + origin[q], 2)),
1130
+ name,
1131
+ ...(moment
1132
+ ? { moment, angle, torsion: moment / angle }
1133
+ : { force, deflection, stiffness: deflection ? force / deflection : Infinity }),
1134
+ stress: most,
1135
+ stressAt,
1136
+ movement: d.most,
1137
+ movementAt: d.at.map((x, q) => round(x + origin[q], 2)),
1138
+ };
1139
+ }
1140
+
1141
+ /**
1142
+ * The check of an analysis's check (fea.settled): how much a load case's stiffness and peak stress moved on cells a
1143
+ * quarter bigger. It settles when the stiffness moves 5% or less; when the part is held to a safety factor
1144
+ * (min_safety), the peak stress must too, as the cells can be fine enough for the stiffness while the stress still reads
1145
+ * low. A peak stress at a sharp inside corner, or beside a support or load held at a few points, keeps rising as the
1146
+ * cells shrink (there it has no limit in theory): a fillet, or the hold spread over the face it acts on, is the answer.
1147
+ * @param {string} problem the problem's name @param {string} name the load case's
1148
+ * @param {{ stiffness: number, stress: number, cell: number }} change each as a fraction (0.05 is 5%), cell the coarser cells' size
1149
+ * @param {boolean} strength whether the peak stress is judged too (min_safety was given)
1150
+ * @returns {{ level: 'pass' | 'warn', code: 'fea.settled', values: { stiffness: number, stress: number, cell: number }, text: string }}
1151
+ */
1152
+ export function settledFinding(problem, name, change, strength) {
1153
+ const pct = (x) => `${x >= 0 ? '+' : ''}${fmt(x * 100)}%`,
1154
+ stiff = Math.abs(change.stiffness) <= 0.05,
1155
+ strong = !strength || Math.abs(change.stress) <= 0.05,
1156
+ ok = stiff && strong;
1157
+ return {
1158
+ level: ok ? 'pass' : 'warn',
1159
+ code: 'fea.settled',
1160
+ values: { stiffness: change.stiffness, stress: change.stress, cell: change.cell },
1161
+ text: `${problem} ${name}: stiffness ${pct(change.stiffness)} from ${fmt(change.cell)} mm cells, peak stress ${pct(change.stress)}${
1162
+ ok
1163
+ ? `, settled (${strength ? 'both' : 'the stiffness'} within 5%)`
1164
+ : `: not settled, use a smaller cell${strong ? '' : ' (a peak stress that keeps rising as the cells shrink is where stress concentrates: at a sharp inside corner, round it; at a support or load on a few points, spread it over the face it acts on)'}`
1165
+ }`,
531
1166
  };
532
1167
  }
533
1168
 
@@ -536,32 +1171,47 @@ function measures(name, force, moment, a, c, density, { nx, ny, h }, origin) {
536
1171
  // through each column of cubes, n × n of them (exact up the column, to within half their spacing across it); each enters the part through a face facing down and leaves through
537
1172
  // one facing up, and the lengths inside each cube are averaged.
538
1173
  export function solidFill(triangles, { nx, ny, nz, h }, origin, n = 4) {
539
- const R = nx * n, hits = Array.from({ length: R * ny * n }, () => []), jx = h * 1e-4 * Math.SQRT2, jy = h * 1e-4 * Math.PI;
1174
+ const R = nx * n,
1175
+ hits = Array.from({ length: R * ny * n }, () => []),
1176
+ jx = h * 1e-4 * Math.SQRT2,
1177
+ jy = h * 1e-4 * Math.PI;
540
1178
  for (const [a, b, c] of triangles) {
541
1179
  const d = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
542
1180
  if (Math.abs(d) < 1e-12) continue; // a wall: the ray runs alongside it
543
- const i0 = Math.max(0, Math.floor(((Math.min(a[0], b[0], c[0]) - origin[0]) / h) * n - 1)), i1 = Math.min(R - 1, Math.ceil(((Math.max(a[0], b[0], c[0]) - origin[0]) / h) * n));
544
- const j0 = Math.max(0, Math.floor(((Math.min(a[1], b[1], c[1]) - origin[1]) / h) * n - 1)), j1 = Math.min(ny * n - 1, Math.ceil(((Math.max(a[1], b[1], c[1]) - origin[1]) / h) * n));
545
- for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) {
546
- const x = origin[0] + ((i + 0.5) / n) * h + jx, y = origin[1] + ((j + 0.5) / n) * h + jy;
547
- 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;
548
- if (w0 < 0 || w1 < 0 || w2 < 0) continue;
549
- hits[j * R + i].push([w0 * a[2] + w1 * b[2] + w2 * c[2], Math.sign(d)]);
550
- }
1181
+ const i0 = Math.max(0, Math.floor(((Math.min(a[0], b[0], c[0]) - origin[0]) / h) * n - 1)),
1182
+ i1 = Math.min(R - 1, Math.ceil(((Math.max(a[0], b[0], c[0]) - origin[0]) / h) * n));
1183
+ const j0 = Math.max(0, Math.floor(((Math.min(a[1], b[1], c[1]) - origin[1]) / h) * n - 1)),
1184
+ j1 = Math.min(ny * n - 1, Math.ceil(((Math.max(a[1], b[1], c[1]) - origin[1]) / h) * n));
1185
+ for (let j = j0; j <= j1; j++)
1186
+ for (let i = i0; i <= i1; i++) {
1187
+ const x = origin[0] + ((i + 0.5) / n) * h + jx,
1188
+ y = origin[1] + ((j + 0.5) / n) * h + jy;
1189
+ const w0 = ((b[0] - x) * (c[1] - y) - (b[1] - y) * (c[0] - x)) / d,
1190
+ w1 = ((c[0] - x) * (a[1] - y) - (c[1] - y) * (a[0] - x)) / d,
1191
+ w2 = 1 - w0 - w1;
1192
+ if (w0 < 0 || w1 < 0 || w2 < 0) continue;
1193
+ hits[j * R + i].push([w0 * a[2] + w1 * b[2] + w2 * c[2], Math.sign(d)]);
1194
+ }
551
1195
  }
552
- const density = new Float64Array(nx * ny * nz), share = 1 / (n * n * h);
1196
+ const density = new Float64Array(nx * ny * nz),
1197
+ share = 1 / (n * n * h);
553
1198
  hits.forEach((list, ray) => {
554
1199
  if (!list.length) return;
555
1200
  list.sort((p, q) => p[0] - q[0]);
556
- const ci = Math.floor((ray % R) / n), cj = Math.floor(Math.floor(ray / R) / n);
557
- let depth = 0, from = 0;
1201
+ const ci = Math.floor((ray % R) / n),
1202
+ cj = Math.floor(Math.floor(ray / R) / n);
1203
+ let depth = 0,
1204
+ from = 0;
558
1205
  for (const [z, sign] of list) {
559
- const was = depth; depth -= sign; // a face facing down (its normal's z below 0, counter-clockwise from above: sign -1) is the way in
1206
+ const was = depth;
1207
+ depth -= sign; // a face facing down (its normal's z below 0, counter-clockwise from above: sign -1) is the way in
560
1208
  if (was <= 0 && depth > 0) from = z;
561
- else if (was > 0 && depth <= 0) for (let k = Math.max(0, Math.floor((from - origin[2]) / h)); k < nz && origin[2] + k * h < z; k++) {
562
- const lo = Math.max(from, origin[2] + k * h), hi = Math.min(z, origin[2] + (k + 1) * h);
563
- if (hi > lo) density[(k * ny + cj) * nx + ci] += (hi - lo) * share;
564
- }
1209
+ else if (was > 0 && depth <= 0)
1210
+ for (let k = Math.max(0, Math.floor((from - origin[2]) / h)); k < nz && origin[2] + k * h < z; k++) {
1211
+ const lo = Math.max(from, origin[2] + k * h),
1212
+ hi = Math.min(z, origin[2] + (k + 1) * h);
1213
+ if (hi > lo) density[(k * ny + cj) * nx + ci] += (hi - lo) * share;
1214
+ }
565
1215
  }
566
1216
  });
567
1217
  return density.map((x) => Math.min(1, x));
@@ -571,19 +1221,28 @@ export function solidFill(triangles, { nx, ny, nz, h }, origin, n = 4) {
571
1221
  // through faces that face down and leaves through faces that face up, so the filled length is the sum of the up
572
1222
  // faces' heights there less the down faces'
573
1223
  function fill(triangles, { nx, ny, h, origin }, thickness) {
574
- const length = new Float64Array(nx * ny), jx = h * 1e-4 * Math.SQRT2, jy = h * 1e-4 * Math.PI; // off-centre, so no ray meets an edge exactly
1224
+ const length = new Float64Array(nx * ny),
1225
+ jx = h * 1e-4 * Math.SQRT2,
1226
+ jy = h * 1e-4 * Math.PI; // off-centre, so no ray meets an edge exactly
575
1227
  for (const [a, b, c] of triangles) {
576
1228
  const nz = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
577
1229
  if (Math.abs(nz) < 1e-12) continue; // a wall: the ray runs alongside it
578
- const lo = [Math.min(a[0], b[0], c[0]), Math.min(a[1], b[1], c[1])], hi = [Math.max(a[0], b[0], c[0]), Math.max(a[1], b[1], c[1])];
579
- const i0 = Math.max(0, Math.floor((lo[0] - origin[0]) / h)), i1 = Math.min(nx - 1, Math.ceil((hi[0] - origin[0]) / h));
580
- const j0 = Math.max(0, Math.floor((lo[1] - origin[1]) / h)), j1 = Math.min(ny - 1, Math.ceil((hi[1] - origin[1]) / h));
581
- for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) {
582
- const x = origin[0] + (i + 0.5) * h + jx, y = origin[1] + (j + 0.5) * h + jy;
583
- const w0 = ((b[0] - x) * (c[1] - y) - (b[1] - y) * (c[0] - x)) / nz, w1 = ((c[0] - x) * (a[1] - y) - (c[1] - y) * (a[0] - x)) / nz, w2 = 1 - w0 - w1;
584
- if (w0 < 0 || w1 < 0 || w2 < 0) continue;
585
- length[j * nx + i] += Math.sign(nz) * (w0 * a[2] + w1 * b[2] + w2 * c[2]);
586
- }
1230
+ const lo = [Math.min(a[0], b[0], c[0]), Math.min(a[1], b[1], c[1])],
1231
+ hi = [Math.max(a[0], b[0], c[0]), Math.max(a[1], b[1], c[1])];
1232
+ const i0 = Math.max(0, Math.floor((lo[0] - origin[0]) / h)),
1233
+ i1 = Math.min(nx - 1, Math.ceil((hi[0] - origin[0]) / h));
1234
+ const j0 = Math.max(0, Math.floor((lo[1] - origin[1]) / h)),
1235
+ j1 = Math.min(ny - 1, Math.ceil((hi[1] - origin[1]) / h));
1236
+ for (let j = j0; j <= j1; j++)
1237
+ for (let i = i0; i <= i1; i++) {
1238
+ const x = origin[0] + (i + 0.5) * h + jx,
1239
+ y = origin[1] + (j + 0.5) * h + jy;
1240
+ const w0 = ((b[0] - x) * (c[1] - y) - (b[1] - y) * (c[0] - x)) / nz,
1241
+ w1 = ((c[0] - x) * (a[1] - y) - (c[1] - y) * (a[0] - x)) / nz,
1242
+ w2 = 1 - w0 - w1;
1243
+ if (w0 < 0 || w1 < 0 || w2 < 0) continue;
1244
+ length[j * nx + i] += Math.sign(nz) * (w0 * a[2] + w1 * b[2] + w2 * c[2]);
1245
+ }
587
1246
  }
588
1247
  return length.map((l) => Math.min(1, Math.max(0, l / thickness)));
589
1248
  }
@@ -591,7 +1250,10 @@ function fill(triangles, { nx, ny, h, origin }, thickness) {
591
1250
  // A closed mesh's volume (mm³), by the divergence theorem
592
1251
  function volume(triangles) {
593
1252
  let v = 0;
594
- for (const [a, b, c] of triangles) v += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6;
1253
+ for (const [a, b, c] of triangles)
1254
+ v +=
1255
+ (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) /
1256
+ 6;
595
1257
  return Math.abs(v);
596
1258
  }
597
1259
 
@@ -604,21 +1266,39 @@ const round = (n, d = 4) => Number(n.toFixed(d));
604
1266
  * @param {{ title?: string, lines?: string[] }} [label]
605
1267
  */
606
1268
  export function picture(r, { title = '', lines = [] } = {}) {
607
- const { nx, ny, h } = r.grid, s = Math.max(2, Math.min(8, Math.floor(1100 / (nx * h)))) , pad = 24, top = 30 + lines.length * 16;
608
- const W = nx * h * s + 2 * pad, H = ny * h * s + pad + top + 12;
609
- const X = (x) => pad + (x - r.origin[0]) * s, Y = (y) => top + (ny * h - (y - r.origin[1])) * s;
1269
+ const { nx, ny, h } = r.grid,
1270
+ s = Math.max(2, Math.min(8, Math.floor(1100 / (nx * h)))),
1271
+ pad = 24,
1272
+ top = 30 + lines.length * 16;
1273
+ const W = nx * h * s + 2 * pad,
1274
+ H = ny * h * s + pad + top + 12;
1275
+ const X = (x) => pad + (x - r.origin[0]) * s,
1276
+ Y = (y) => top + (ny * h - (y - r.origin[1])) * s;
610
1277
  const cells = [];
611
- for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) {
612
- const d = r.density[j * nx + i];
613
- if (d > 0.02) cells.push(`<rect x="${X(r.origin[0] + i * h).toFixed(1)}" y="${Y(r.origin[1] + (j + 1) * h).toFixed(1)}" width="${(h * s + 0.3).toFixed(1)}" height="${(h * s + 0.3).toFixed(1)}" fill-opacity="${d.toFixed(2)}"/>`);
614
- }
615
- const loops = (r.outlines || []).map((l) => `<path d="M${l.map(([x, y]) => `${X(x).toFixed(1)},${Y(y).toFixed(1)}`).join('L')}Z"/>`);
616
- const supports = (r.supports || []).map((p) => `<path d="M${X(p.at[0])},${Y(p.at[1])}l-6,10h12z"/>`);
1278
+ for (let j = 0; j < ny; j++)
1279
+ for (let i = 0; i < nx; i++) {
1280
+ const d = r.density[j * nx + i];
1281
+ if (d > 0.02)
1282
+ cells.push(
1283
+ `<rect x="${X(r.origin[0] + i * h).toFixed(1)}" y="${Y(r.origin[1] + (j + 1) * h).toFixed(1)}" width="${(h * s + 0.3).toFixed(1)}" height="${(h * s + 0.3).toFixed(1)}" fill-opacity="${d.toFixed(2)}"/>`,
1284
+ );
1285
+ }
1286
+ const loops = (r.outlines || []).map(
1287
+ (l) => `<path d="M${l.map(([x, y]) => `${X(x).toFixed(1)},${Y(y).toFixed(1)}`).join('L')}Z"/>`,
1288
+ );
1289
+ const supports = (r.supports || []).map((p) => `<path d="M${X(placeOf(p)[0])},${Y(placeOf(p)[1])}l-6,10h12z"/>`);
617
1290
  const loads = (r.loads || []).map((l) => {
618
- const len = Math.hypot(...l.force) || 1, dx = (l.force[0] / len) * 30, dy = (-l.force[1] / len) * 30, x = X(l.at[0]), y = Y(l.at[1]);
1291
+ const len = Math.hypot(...l.force) || 1,
1292
+ dx = (l.force[0] / len) * 30,
1293
+ dy = (-l.force[1] / len) * 30,
1294
+ x = X(placeOf(l)[0]),
1295
+ y = Y(placeOf(l)[1]);
619
1296
  return `<path d="M${x - dx},${y - dy}L${x},${y}"/><circle cx="${x}" cy="${y}" r="3"/>`;
620
1297
  });
621
- const text = [title, ...lines].map((t, i) => `<text x="${pad}" y="${20 + i * 16}" font-size="${i ? 12 : 14}"${i ? '' : ' font-weight="600"'}>${t.replace(/&/g, '&amp;').replace(/</g, '&lt;')}</text>`);
1298
+ const text = [title, ...lines].map(
1299
+ (t, i) =>
1300
+ `<text x="${pad}" y="${20 + i * 16}" font-size="${i ? 12 : 14}"${i ? '' : ' font-weight="600"'}>${t.replace(/&/g, '&amp;').replace(/</g, '&lt;')}</text>`,
1301
+ );
622
1302
  return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" font-family="system-ui, sans-serif">
623
1303
  <rect width="100%" height="100%" fill="#fff"/>${text.join('')}
624
1304
  <g fill="#2b4c7e">${cells.join('')}</g>
@@ -633,21 +1313,45 @@ export function picture(r, { title = '', lines = [] } = {}) {
633
1313
  // print as a stray bit. Only pieces touching a support, a load or a kept region (within a cell) stay; the volumes of
634
1314
  // the rest, mm³, come back as dropped.
635
1315
  export function anchored({ vertices, faces }, anchors, h) {
636
- const up = vertices.map((_, i) => i), find = (i) => { while (up[i] !== i) i = up[i] = up[up[i]]; return i; };
637
- for (const [a, b, c] of faces) { up[find(a)] = find(b); up[find(b)] = find(c); }
1316
+ const up = vertices.map((_, i) => i),
1317
+ find = (i) => {
1318
+ while (up[i] !== i) i = up[i] = up[up[i]];
1319
+ return i;
1320
+ };
1321
+ for (const [a, b, c] of faces) {
1322
+ up[find(a)] = find(b);
1323
+ up[find(b)] = find(c);
1324
+ }
638
1325
  const pieces = new Map();
639
1326
  for (const f of faces) {
640
- const r = find(f[0]), p = pieces.get(r) ?? { faces: [], lo: [Infinity, Infinity, Infinity], hi: [-Infinity, -Infinity, -Infinity] };
1327
+ const r = find(f[0]),
1328
+ p = pieces.get(r) ?? { faces: [], lo: [Infinity, Infinity, Infinity], hi: [-Infinity, -Infinity, -Infinity] };
641
1329
  p.faces.push(f);
642
- for (const v of f) for (let k = 0; k < 3; k++) { p.lo[k] = Math.min(p.lo[k], vertices[v][k]); p.hi[k] = Math.max(p.hi[k], vertices[v][k]); }
1330
+ for (const v of f)
1331
+ for (let k = 0; k < 3; k++) {
1332
+ p.lo[k] = Math.min(p.lo[k], vertices[v][k]);
1333
+ p.hi[k] = Math.max(p.hi[k], vertices[v][k]);
1334
+ }
643
1335
  pieces.set(r, p);
644
1336
  }
645
1337
  if (pieces.size < 2) return { vertices, faces, dropped: [] };
646
1338
  const touches = (p) => anchors.some((b) => [0, 1, 2].every((k) => p.lo[k] <= b[3 + k] + h && p.hi[k] >= b[k] - h));
647
- const kept = [], dropped = [];
1339
+ const kept = [],
1340
+ dropped = [];
648
1341
  for (const p of pieces.values()) (touches(p) ? kept : dropped).push(p);
649
1342
  if (!kept.length) return { vertices, faces, dropped: [] }; // nothing anchored: keep it all rather than nothing
650
- const index = new Map(), out = [];
651
- const keptFaces = kept.flatMap((p) => p.faces).map((f) => f.map((v) => { if (!index.has(v)) { index.set(v, out.length); out.push(vertices[v]); } return index.get(v); }));
1343
+ const index = new Map(),
1344
+ out = [];
1345
+ const keptFaces = kept
1346
+ .flatMap((p) => p.faces)
1347
+ .map((f) =>
1348
+ f.map((v) => {
1349
+ if (!index.has(v)) {
1350
+ index.set(v, out.length);
1351
+ out.push(vertices[v]);
1352
+ }
1353
+ return index.get(v);
1354
+ }),
1355
+ );
652
1356
  return { vertices: out, faces: keptFaces, dropped: dropped.map((p) => round(meshVolume(vertices, p.faces), 3)) };
653
1357
  }