@rulecad/cad 0.7.6 → 0.7.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -373,7 +373,7 @@ A 3D result keeps only the pieces that touch a support, a load or a kept region.
373
373
  can close into a piece of their own, which would print as a stray bit. `cad optimise` says how many it dropped.
374
374
 
375
375
  `cad optimise <project>/<problem> --watch [port]` runs it afresh and serves a live view at `http://127.0.0.1:8090/`:
376
- the densities as they change (a 3D part from three sides), a chart of its compliance and how much it still changes, with a scrubber to look back at any earlier step, its run time and time left, the machine it runs on, and a button that stops the run. It shows the end for ten minutes after the run finishes.
376
+ the densities as they change (a 3D part as a surface you can turn, and from three sides), a chart of its compliance and how much it still changes, with a scrubber to look back at any earlier step, its run time and time left, the machine it runs on, and a button that stops the run. It shows the end for ten minutes after the run finishes.
377
377
  It listens on this computer only. To watch from elsewhere, reach it through a private network such as Tailscale.
378
378
 
379
379
  A design uses it through a variable of type `problem`, which picks a problem by name:
@@ -433,7 +433,9 @@ the problem, and optionally a limit:
433
433
  `cad check` then reports, for each load case, how far the part moves its load, its stiffness (N/mm) and its peak
434
434
  stress against the material's strength, and the part's volume and weight. With `max_deflection` a case that moves
435
435
  further fails; with `volume` a part whose volume is further than `tolerance` (a share) from it fails. A picture goes in
436
- `.preview/`.
436
+ `.preview/`. A twist (forces that add to nothing, such as four round a rim) has no direction to move along, so it's
437
+ reported as the angle the part turns through, in degrees, under its moment (N·m), and its torsional stiffness (N·m a
438
+ degree).
437
439
 
438
440
  On the problem's own cells the analysis is quick and coarse. A solid part's cubes are filled by the share of each the
439
441
  part takes up, so a wall between cell centres still counts, but thin walls on big cubes still come out too stiff when
package/bin/cad.mjs CHANGED
@@ -112,6 +112,9 @@ function report(findings, about = {}) {
112
112
  const say = (...a) => { if (!opt('json')) console.log(...a); }; // text output that --json leaves out
113
113
 
114
114
  const sig = (n) => (Number.isFinite(n) ? String(Number(n.toPrecision(3))) : String(n)); // three significant figures
115
+ // A case's stiffness, and in words: a twist turns (degrees under N·m, N·m a degree), anything else moves along its load
116
+ const stiffOf = (c) => (c.moment ? c.torsion : c.stiffness);
117
+ const howFar = (c) => (c.moment ? `turns ${sig(c.angle * 180 / Math.PI)}° under ${sig(c.moment / 1000)} N·m, ${sig(c.torsion / 1000 * Math.PI / 180)} N·m a degree` : `moves ${sig(c.deflection)} mm along its load, ${sig(c.stiffness)} N/mm`);
115
118
  // cad optimise: run a problem (with a progress line), then report it and draw it: a 2D layout as an SVG of its
116
119
  // densities, a 3D one as the preview's four views of its surface
117
120
  async function optimiseProblem(ref) {
@@ -136,7 +139,7 @@ async function optimiseProblem(ref) {
136
139
  // The page keeps showing the end for ten minutes (the process waits for it), so a finished run isn't a dead link
137
140
  if (view) { view.close(`finished: ${r.steps} steps${r.converged ? '' : ', not settled'}`, { hold: 10 * 60e3 }); say(`the live view shows the result for ten more minutes (Ctrl-C to stop it)`); }
138
141
  const p = await readProblem(project, name), cells = r.dim === 3 ? `${r.grid.nx} × ${r.grid.ny} × ${r.grid.nz}` : `${r.grid.nx} × ${r.grid.ny}`;
139
- const lines = [`${p.material.name}${r.dim === 2 ? `, ${fmt(r.thickness)} mm thick` : ''}: ${r.cases.map((c) => `${c.name} ${sig(c.deflection)} mm (${sig(c.stiffness)} N/mm)`).join(', ')}`,
142
+ const lines = [`${p.material.name}${r.dim === 2 ? `, ${fmt(r.thickness)} mm thick` : ''}: ${r.cases.map((c) => c.moment ? `${c.name} ${sig(c.angle * 180 / Math.PI)}° (${sig(c.torsion / 1000 * Math.PI / 180)} N·m/°)` : `${c.name} ${sig(c.deflection)} mm (${sig(c.stiffness)} N/mm)`).join(', ')}`,
140
143
  `${fmt(r.volume * 100)}% of the space, ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? '' : ' (stopped: not settled)'}${r.overhang ? `, printable built ${r.overhang}` : ''}${r.stress ? `, peak stress ${sig(r.stress.peak)} MPa (limit ${sig(r.stress.limit)})` : ''}${r.dropped ? `; ${r.dropped.length} loose ${r.dropped.length === 1 ? 'piece' : 'pieces'} dropped (${sig(r.dropped.reduce((t, v) => t + v, 0))} mm³)` : ''}`];
141
144
  let out;
142
145
  if (r.dim === 3) {
@@ -150,7 +153,7 @@ async function optimiseProblem(ref) {
150
153
  }
151
154
  if (opt('json')) return console.log(JSON.stringify((({ density, history, mesh, ...x }) => x)(r), null, 2));
152
155
  console.log(`${r.title}${r.cached ? ' (cached)' : ` (${fmt(r.seconds)} s)`}`);
153
- for (const c of r.cases) console.log(` ${c.name}: moves ${sig(c.deflection)} mm along its load, ${sig(c.stiffness)} N/mm`);
156
+ for (const c of r.cases) console.log(` ${c.name}: ${howFar(c)}`);
154
157
  if (r.stress) console.log(` peak stress ${sig(r.stress.peak)} MPa, the limit ${sig(r.stress.limit)} MPa${r.stress.peak > r.stress.limit * 1.02 ? ': over it (raise the volume, ease the limit, or use a smaller cell)' : ''}`);
155
158
  if (r.dim === 3) console.log(` ${fmt(r.volume * 100)}% of the space filled: ${fmt(r.solid / 1000)} cm³ (${fmt(r.solid / 1000 * (p.material.density || 0))} g of ${p.material.name})${r.overhang ? `, printable built ${r.overhang}` : ''}`);
156
159
  else console.log(` ${fmt(r.volume * 100)}% of the space filled, outline ${fmt(r.area)} mm² (${fmt(r.area * r.thickness / 1000)} cm³ before bosses and holes are made exact)`);
@@ -175,7 +178,7 @@ function place(triangles, [rx, ry, rz], move) {
175
178
  function reportText({ turn, object, title, version, a, r, m, strength, weaker, grid, limit, minSafety, records, found }) {
176
179
  const at = (p) => `(${p.map(fmt).join(', ')})`;
177
180
  const pct = (x) => `${x >= 0 ? '+' : ''}${fmt(x * 100)}%`;
178
- const rows = r.cases.map((c) => `| ${c.name} | ${fmt(c.force)} | ${sig(c.deflection)} | ${sig(c.stiffness)}${c.change ? ` (${pct(c.change.stiffness)})` : ''} | ${sig(c.stress)}${c.change ? ` (${pct(c.change.stress)})` : ''} at ${at(c.stressAt)} | ${strength ? `${sig(strength / c.stress)}×` : '–'}${m.fatigue ? ` (fatigue ${sig(m.fatigue / c.stress)}×)` : ''} | ${sig(c.movement)} at ${at(c.movementAt)} |`);
181
+ const rows = r.cases.map((c) => `| ${c.name} | ${c.moment ? `${sig(c.moment / 1000)} N·m | ${sig(c.angle * 180 / Math.PI)}° | ${sig(c.torsion / 1000 * Math.PI / 180)} N·m/°` : `${fmt(c.force)} | ${sig(c.deflection)} | ${sig(c.stiffness)}`}${c.change ? ` (${pct(c.change.stiffness)})` : ''} | ${sig(c.stress)}${c.change ? ` (${pct(c.change.stress)})` : ''} at ${at(c.stressAt)} | ${strength ? `${sig(strength / c.stress)}×` : '–'}${m.fatigue ? ` (fatigue ${sig(m.fatigue / c.stress)}×)` : ''} | ${sig(c.movement)} at ${at(c.movementAt)} |`);
179
182
  return [
180
183
  `# ${title}: analysed under ${a.problem}`, '',
181
184
  `${object} ${version || ''}. Analysed on ${grid}, ${m.name} (modulus ${fmt(m.modulus)} MPa${strength ? `, strength ${fmt(strength)} MPa${weaker ? ' across its layers' : ''}` : ''}${m.fatigue ? `, fatigue strength ${fmt(m.fatigue)} MPa` : ''}). Positions are in mm, in the problem's frame${turn ? ' (the part turned back from how it prints)' : ''}.${r.cases[0]?.change ? ` In brackets: the change from ${fmt(r.cases[0].change.cell)} mm cells. Stiffness that changes by 5% or less has settled; peak stress at a sharp inside corner keeps rising as cells shrink, so read it with its change.` : ' On the problem\'s own cells: a quick check. Give the analysis a smaller cell to verify it.'}`, '',
@@ -209,7 +212,7 @@ async function analyses(b, d, tag) {
209
212
  // theory it's endless there), so it's reported, not judged.
210
213
  if (cell) {
211
214
  const coarser = await analysePart(turned, d.project, a.problem, { cell: cell * 1.25 });
212
- r.cases.forEach((c, n) => { const o = coarser.cases[n]; c.change = { stiffness: c.stiffness / o.stiffness - 1, stress: c.stress / o.stress - 1, cell: coarser.grid.h }; });
215
+ r.cases.forEach((c, n) => { const o = coarser.cases[n]; c.change = { stiffness: stiffOf(c) / stiffOf(o) - 1, stress: c.stress / o.stress - 1, cell: coarser.grid.h }; });
213
216
  }
214
217
  const limit = a.max_deflection != null ? evaluate(a.max_deflection, lookup) : null;
215
218
  const minSafety = a.min_safety != null ? evaluate(a.min_safety, lookup) : null;
@@ -226,15 +229,15 @@ async function analyses(b, d, tag) {
226
229
  const at = (p) => `(${p.map(fmt).join(', ')})`;
227
230
  const found = r.cases.flatMap((c) => {
228
231
  const safety = strength ? strength / c.stress : null, fatigue = m.fatigue ? m.fatigue / c.stress : null;
229
- const text = `${a.problem} ${c.name}: moves ${sig(c.deflection)} mm under ${fmt(c.force)} N, ${sig(c.stiffness)} N/mm`;
230
- const values = { deflection: c.deflection, force: c.force, stiffness: c.stiffness, stress: c.stress, ...(limit != null ? { limit } : {}) };
232
+ const text = c.moment ? `${a.problem} ${c.name}: ${howFar(c)}` : `${a.problem} ${c.name}: moves ${sig(c.deflection)} mm under ${fmt(c.force)} N, ${sig(c.stiffness)} N/mm`;
233
+ const values = { ...(c.moment ? { angle: c.angle, moment: c.moment, torsion: c.torsion } : { deflection: c.deflection, force: c.force, stiffness: c.stiffness }), stress: c.stress, ...(limit != null ? { limit } : {}) };
231
234
  const refs = { problem: a.problem, part: part.name, ...(out ? { picture: path.relative(WS, out) } : {}) };
232
235
  const strong = `peak stress ${sig(c.stress)} MPa at ${at(c.stressAt)}${safety != null ? `: ${sig(safety)}× under ${m.name}'s ${weaker ? 'strength across its layers' : 'strength'}${fatigue != null ? `, ${sig(fatigue)}× under its fatigue strength` : ''}` : ''}`;
233
236
  const least = Math.min(safety ?? Infinity, fatigue ?? Infinity);
234
237
  const settled = c.change ? [{ level: Math.abs(c.change.stiffness) <= 0.05 ? 'pass' : 'warn', code: 'fea.settled', values: c.change,
235
238
  text: `${a.problem} ${c.name}: stiffness ${c.change.stiffness >= 0 ? '+' : ''}${fmt(c.change.stiffness * 100)}% from ${fmt(c.change.cell)} mm cells${Math.abs(c.change.stiffness) <= 0.05 ? ', settled (within 5%)' : ': not settled, use a smaller cell'}` }] : [];
236
239
  return [
237
- { level: limit == null ? 'info' : c.deflection <= limit ? 'pass' : 'fail', text: limit == null ? text : `${text} (at most ${fmt(limit)})`, code: 'fea.deflection', values, refs }, ...settled,
240
+ { level: limit == null || c.moment ? 'info' : c.deflection <= limit ? 'pass' : 'fail', text: limit == null ? text : `${text} (at most ${fmt(limit)})`, code: 'fea.deflection', values, refs }, ...settled,
238
241
  { level: minSafety == null ? 'info' : least >= minSafety ? 'pass' : 'fail', text: `${a.problem} ${c.name}: ${strong}${minSafety != null ? ` (at least ${fmt(minSafety)}×)` : ''}`, code: 'fea.strength',
239
242
  values: { stress: c.stress, at: c.stressAt, ...(safety != null ? { safety } : {}), ...(fatigue != null ? { fatigue } : {}), ...(minSafety != null ? { min: minSafety } : {}) }, refs },
240
243
  ];
package/lib/live.mjs CHANGED
@@ -5,6 +5,9 @@
5
5
  import fs from 'node:fs';
6
6
  import http from 'node:http';
7
7
  import os from 'node:os';
8
+ import path from 'node:path';
9
+ import { createRequire } from 'node:module';
10
+ import { surface } from '@rulecad/topopt';
8
11
  import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
9
12
 
10
13
  /**
@@ -26,7 +29,10 @@ export function liveView({ port = 8090, host = '127.0.0.1', title }) {
26
29
  step: (s) => {
27
30
  const list = views(s.density, s.grid);
28
31
  const { nx, ny, nz, h } = s.grid;
29
- worker.postMessage({ grid: { nx, ny, nz, h }, step: s.step, steps: s.steps, compliance: s.compliance, change: s.change, beta: s.beta, volume: s.volume, stress: s.stress, views: list }, list.map((v) => v.image.buffer));
32
+ // A 3D grid's densities too, a byte a cell, for its surface (drawn when the page asks for it)
33
+ const cells = nz > 1 ? Uint8Array.from(s.density, (d) => Math.round(d * 255)) : null;
34
+ worker.postMessage({ grid: { nx, ny, nz, h }, step: s.step, steps: s.steps, compliance: s.compliance, change: s.change, beta: s.beta, volume: s.volume, stress: s.stress, views: list, cells },
35
+ [...list.map((v) => v.image.buffer), ...(cells ? [cells.buffer] : [])]);
30
36
  },
31
37
  stopped: () => Atomics.load(flag, 0) === 1,
32
38
  // hold: keep showing the end for this long (ms), for whoever opens the page late
@@ -52,9 +58,9 @@ function views(d, { nx, ny, nz = 1 }) {
52
58
 
53
59
  const page = (title) => `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
54
60
  <title>${title}</title>
55
- <style>body{font:15px system-ui;background:#111;color:#eee;margin:16px;max-width:900px}canvas{background:#000;border-radius:6px}.chart{width:100%}#views{display:flex;gap:8px;align-items:flex-end}figure{flex:1;min-width:0;margin:0;text-align:center}figure canvas{width:100%;height:40vh;object-fit:contain;background:none}figcaption{color:#aaa;font-size:13px;text-align:center}
61
+ <style>body{font:15px system-ui;background:#111;color:#eee;margin:16px;max-width:900px}canvas{background:#000;border-radius:6px}.chart{width:100%}#hint{color:#888;font-size:12px;text-align:center;margin:-4px 0 8px}#model{height:50vh;margin-bottom:8px;border-radius:6px;overflow:hidden;background:#000;cursor:grab;touch-action:none}#views{display:flex;gap:8px;align-items:flex-end}figure{flex:1;min-width:0;margin:0;text-align:center}figure canvas{width:100%;height:40vh;object-fit:contain;background:none}figcaption{color:#aaa;font-size:13px;text-align:center}
56
62
  #chart{height:160px;touch-action:none}#scrub{display:flex;gap:8px;align-items:center}#scrub input{flex:1}#live{background:#357}table{border-collapse:collapse;margin:10px 0;width:100%}td{padding:3px 8px 3px 0;vertical-align:top}td:first-child{color:#999;white-space:nowrap;width:1%}button{font:inherit;padding:8px 16px;border-radius:6px;border:0;background:#d33;color:#fff}button:disabled{background:#555}#state{margin:10px 0}</style>
57
- <h2>${title}</h2><div id="state">waiting for the first step…</div><div id="views"></div><canvas class="chart" id="chart" width="900" height="160"></canvas><div id="scrub"><input type="range" id="at" min="0" max="0" value="0"><button id="live" disabled>Live</button></div><table id="facts"></table>
63
+ <h2>${title}</h2><div id="state">waiting for the first step…</div><div id="model" hidden></div><div id="hint" hidden>drag to turn it · double-tap to stop or start it turning</div><div id="views"></div><canvas class="chart" id="chart" width="900" height="160"></canvas><div id="scrub"><input type="range" id="at" min="0" max="0" value="0"><button id="live" disabled>Live</button></div><table id="facts"></table>
58
64
  <p><button id="stop">Stop the run</button> <span id="note"></span></p>
59
65
  <script>
60
66
  const views = document.getElementById('views'), facts = document.getElementById('facts'), state = document.getElementById('state'), stop = document.getElementById('stop');
@@ -75,6 +81,7 @@ function table() {
75
81
  facts.innerHTML = [...(finished ? [['Result', finished]] : []), ...rows, ...about].map(([k, v]) => '<tr><td>' + esc(k) + '</td><td>' + esc(v) + '</td></tr>').join('');
76
82
  }
77
83
  function draw(f) {
84
+ document.getElementById('model').hidden = document.getElementById('hint').hidden = f.views.length < 3;
78
85
  if (views.children.length !== f.views.length) views.innerHTML = f.views.map((v) => '<figure><canvas></canvas><figcaption>' + v.name + '</figcaption></figure>').join('');
79
86
  f.views.forEach((v, n) => {
80
87
  const c = views.children[n].firstChild; if (c.width !== v.w) { c.width = v.w; c.height = v.h; }
@@ -100,7 +107,8 @@ function plot() {
100
107
  c.font = '12px system-ui'; c.fillStyle = '#6cf'; c.fillText('compliance, N·mm: ' + fig(history.compliance[0]) + ' to ' + fig(history.compliance.at(-1)), 8, 14);
101
108
  c.fillStyle = '#fc6'; c.textAlign = 'right'; c.fillText('change (log scale): ' + fig(history.change[0]) + ' to ' + fig(history.change.at(-1)), w - 8, 14); c.textAlign = 'left';
102
109
  }
103
- function show(f) { draw(f); plot(); table(); }
110
+ function show(f) { draw(f); plot(); table(); window.model3d?.(shown, f.grid); }
111
+ let lastModel = 0; // while following, a new surface at most every two seconds
104
112
  // Scrubbing: any earlier step, fetched when asked for; the newest only while following
105
113
  let asked = 0;
106
114
  async function lookAt(k) {
@@ -118,14 +126,67 @@ events.onmessage = (e) => { const m = JSON.parse(e.data); if (m.about) about = m
118
126
  if (m.done) { finished = m.done; stop.disabled = true; events.close(); }
119
127
  at.max = Math.max(0, history.compliance.length - 1);
120
128
  if (m.frame) newest = m.frame;
121
- if (follow) { shown = Number(at.max); at.value = shown; if (newest) draw(newest); }
129
+ if (follow) { shown = Number(at.max); at.value = shown; if (newest) draw(newest); if (Date.now() - lastModel > 2000 || finished) { lastModel = Date.now(); window.model3d?.(shown, newest.grid); } }
122
130
  if (finished) state.textContent = finished;
123
131
  plot(); table(); };
124
132
  stop.onclick = async () => { stop.disabled = true; await fetch('stop', { method: 'POST' }); document.getElementById('note').textContent = 'stopping after this step'; };
133
+ </script>
134
+ <script type="importmap">{ "imports": { "three": "/three/three.module.js" } }</script>
135
+ <script type="module">
136
+ // The 3D view: the step's surface, turning slowly; drag to turn it, double-tap to stop or start it turning
137
+ import * as THREE from 'three';
138
+ const box = document.getElementById('model');
139
+ let renderer, scene, camera, mesh, yaw = 0.6, tilt = 0.4, spin = true, size = 1, centre = null, busy = false, wanted = null, current = null;
140
+ function setup() {
141
+ renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true }); box.appendChild(renderer.domElement);
142
+ scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(35, 1, 0.1, 1e6); camera.up.set(0, 0, 1);
143
+ scene.add(new THREE.AmbientLight(0xffffff, 0.6));
144
+ const sun = new THREE.DirectionalLight(0xffffff, 2); sun.position.set(-1, -2, 3); scene.add(sun);
145
+ const fill = new THREE.DirectionalLight(0xffffff, 0.8); fill.position.set(2, 1, -1); scene.add(fill);
146
+ const c = renderer.domElement; let last = null;
147
+ c.onpointerdown = (e) => { last = [e.clientX, e.clientY]; spin = false; c.setPointerCapture(e.pointerId); };
148
+ c.onpointermove = (e) => { if (!last) return; yaw -= (e.clientX - last[0]) * 0.01; tilt = Math.max(-1.4, Math.min(1.4, tilt + (e.clientY - last[1]) * 0.01)); last = [e.clientX, e.clientY]; };
149
+ c.onpointerup = () => { last = null; };
150
+ c.ondblclick = () => { spin = !spin; };
151
+ const tick = () => {
152
+ const w = box.clientWidth, h = box.clientHeight;
153
+ if (w && (c.width !== Math.round(w * devicePixelRatio) || c.height !== Math.round(h * devicePixelRatio))) { renderer.setPixelRatio(devicePixelRatio); renderer.setSize(w, h); camera.aspect = w / h; camera.updateProjectionMatrix(); }
154
+ if (spin) yaw += 0.004;
155
+ const d = size / Math.sin(camera.fov * Math.PI / 360) * 0.8; // the part seldom fills its grid's corners camera.position.set(d * Math.cos(tilt) * Math.cos(yaw), d * Math.cos(tilt) * Math.sin(yaw), d * Math.sin(tilt)); camera.lookAt(0, 0, 0);
156
+ renderer.render(scene, camera); requestAnimationFrame(tick);
157
+ };
158
+ tick();
159
+ }
160
+ async function load(n, grid) {
161
+ if (n === current) return;
162
+ if (busy) { wanted = [n, grid]; return; }
163
+ busy = true;
164
+ try {
165
+ const res = await fetch('mesh/' + n);
166
+ if (!res.ok) return;
167
+ const buf = await res.arrayBuffer(), [nv, nf] = new Uint32Array(buf, 0, 2);
168
+ if (!renderer) setup();
169
+ const g = new THREE.BufferGeometry();
170
+ g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(buf, 8, nv * 3), 3)); g.setIndex(new THREE.BufferAttribute(new Uint32Array(buf, 8 + nv * 12, nf * 3), 1));
171
+ g.computeVertexNormals();
172
+ // Framed on the whole grid, so the part stays put as it changes
173
+ if (!centre) { const e = [grid.nx, grid.ny, grid.nz].map((n) => n * grid.h); centre = new THREE.Vector3(e[0] / 2, e[1] / 2, e[2] / 2); size = Math.hypot(...e) / 2; }
174
+ g.translate(-centre.x, -centre.y, -centre.z);
175
+ if (mesh) { scene.remove(mesh); mesh.geometry.dispose(); }
176
+ mesh = new THREE.Mesh(g, new THREE.MeshStandardMaterial({ color: 0xd9d9d9, roughness: 0.55, metalness: 0.05, side: THREE.DoubleSide }));
177
+ scene.add(mesh); current = n;
178
+ } finally {
179
+ busy = false;
180
+ if (wanted != null) { const [w, wg] = wanted; wanted = null; load(w, wg); }
181
+ }
182
+ }
183
+ window.model3d = (n, grid) => { if (!box.hidden && grid) load(n, grid); };
125
184
  </script>`;
126
185
 
186
+ const THREE = path.dirname(createRequire(import.meta.url).resolve('three')); // three's build files, for the 3D view
187
+
127
188
  if (!isMainThread && workerData?.flag) {
128
- const { port, host, title, flag } = workerData, clients = new Set(), history = { compliance: [], change: [] }, frames = [], times = [], t0 = Date.now();
189
+ const { port, host, title, flag } = workerData, clients = new Set(), history = { compliance: [], change: [] }, frames = [], densities = [], meshes = new Map(), times = [], t0 = Date.now();
129
190
  // What a reader might want beside the numbers of each step: what ran it, where and when
130
191
  const cpus = os.cpus(), about = [['Started', new Date(t0).toLocaleString('en-GB')], ['Machine', `${cpus[0]?.model.trim() ?? os.arch()}, ${cpus.length} cores, ${Math.round(os.totalmem() / 2 ** 30)} GB`],
131
192
  ['Software', `@rulecad/cad ${JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version}, Node ${process.versions.node}, ${os.type()}`]];
@@ -138,6 +199,21 @@ if (!isMainThread && workerData?.flag) {
138
199
  send(res, { about, history, ...(latest ? { frame: latest } : {}), ...(done ? { done } : {}) });
139
200
  clients.add(res); req.on('close', () => clients.delete(res));
140
201
  // Any earlier step, for the scrubber: every one is kept (about a byte a pixel of its views)
202
+ } else if (req.url.startsWith('/mesh/') && densities[Number(req.url.slice(6))]) {
203
+ // A step's surface: vertex and face counts, then the vertices (float32 x, y, z) and the faces (uint32 corners).
204
+ // The last few are kept, as the page asks for the same step again while it turns.
205
+ const n = Number(req.url.slice(6));
206
+ if (!meshes.has(n)) {
207
+ const g = frames[n].grid, { vertices, faces } = surface(g, Float64Array.from(densities[n], (d) => d / 255), [0, 0, 0]);
208
+ const buf = Buffer.alloc(8 + vertices.length * 12 + faces.length * 12), out = new DataView(buf.buffer, buf.byteOffset);
209
+ out.setUint32(0, vertices.length, true); out.setUint32(4, faces.length, true);
210
+ vertices.forEach((v, i) => { for (let a = 0; a < 3; a++) out.setFloat32(8 + (i * 3 + a) * 4, v[a], true); });
211
+ faces.forEach((f, i) => { for (let a = 0; a < 3; a++) out.setUint32(8 + vertices.length * 12 + (i * 3 + a) * 4, f[a], true); });
212
+ meshes.set(n, buf); if (meshes.size > 4) meshes.delete(meshes.keys().next().value);
213
+ }
214
+ res.writeHead(200, { 'content-type': 'application/octet-stream' }); res.end(meshes.get(n));
215
+ } else if (req.url.startsWith('/three/') && fs.existsSync(path.join(THREE, path.basename(req.url)))) {
216
+ res.writeHead(200, { 'content-type': 'text/javascript' }); res.end(fs.readFileSync(path.join(THREE, path.basename(req.url))));
141
217
  } else if (req.url.startsWith('/frame/') && frames[Number(req.url.slice(7))]) { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(frames[Number(req.url.slice(7))]));
142
218
  } else if (req.url === '/stop' && req.method === 'POST') { Atomics.store(flag, 0, 1); res.end('stopping'); }
143
219
  else if (req.url === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(page(title)); }
@@ -156,6 +232,7 @@ if (!isMainThread && workerData?.flag) {
156
232
  // Timing: the mean of the last ten steps, and what's left at that pace (at most: it may settle sooner)
157
233
  const now = Date.now(); times.push(now);
158
234
  const last = times.slice(-11), perStep = last.length > 1 ? (last.at(-1) - last[0]) / (last.length - 1) / 1000 : null;
235
+ const { cells, ...rest } = m; m = rest; densities.push(cells);
159
236
  latest = frame({ ...m, elapsed: (now - t0) / 1000, perStep, left: perStep && (m.steps - m.step) * perStep }); frames.push(latest);
160
237
  history.compliance.push(m.compliance); history.change.push(m.change);
161
238
  });
package/lib/optimise.mjs CHANGED
@@ -11,7 +11,7 @@ import { host } from './host.mjs';
11
11
  import { paths, printerOf } from './workspace.mjs';
12
12
  import { resolve, evaluate } from './rules.mjs';
13
13
  import { located } from './errors.mjs';
14
- import { discretise, optimise, outlines, surface, area, bounds } from '@rulecad/topopt';
14
+ import { discretise, optimise, outlines, surface, area, bounds, resultant } from '@rulecad/topopt';
15
15
  import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
16
16
 
17
17
  const VERSION = 2, source = (m) => fs.readFileSync(new URL(import.meta.resolve(m)), 'utf8'); // the solver's code: a change remakes results
@@ -177,8 +177,8 @@ export async function analysePart(triangles, project, ref, { cell } = {}) {
177
177
  });
178
178
  const a = analyse({ grid: g, density, material: problem.material, thickness: problem.thickness, fixed, loads });
179
179
  const cases = names.map((name, c) => {
180
- const size = Math.hypot(...problem.loads.filter((l) => l.case === name).reduce((s, l) => [s[0] + l.force[0], s[1] + l.force[1]], [0, 0]));
181
- return measures(name, size, a, c, density, { nx, ny, nz: 1, h }, [x0, y0]);
180
+ const { size, moment } = resultant(problem.loads.filter((l) => l.case === name));
181
+ return measures(name, size, moment, a, c, density, { nx, ny, nz: 1, h }, [x0, y0]);
182
182
  });
183
183
  return { problem: ref, dim: 2, material: r.material, critical: r.critical, cases, volume: volume(triangles), grid: { nx, ny, h }, origin: [x0, y0], density };
184
184
  }
@@ -190,20 +190,21 @@ function analyseSolid(triangles, r, cell) {
190
190
  const g = makeGrid(spec.grid), density = solidFill(triangles, spec.grid, spec.origin);
191
191
  if (!density.some((d) => d)) throw new Error('the part is smaller than one cell of the problem: use a smaller cell');
192
192
  const a = analyse({ grid: g, density, material: problem.material, fixed: spec.fixed, loads: spec.loads.map((l) => l.force) });
193
- const cases = spec.loads.map((l, c) => measures(l.name, l.size, a, c, density, spec.grid, spec.origin));
193
+ const cases = spec.loads.map((l, c) => measures(l.name, l.size, l.moment, a, c, density, spec.grid, spec.origin));
194
194
  return { problem: r.ref, dim: 3, material: r.material, critical: r.critical, cases, volume: volume(triangles), grid: spec.grid, origin: spec.origin, density };
195
195
  }
196
196
 
197
- // A load case's numbers: how far the load moves along itself (compliance over force) and the stiffness, the largest
197
+ // A load case's numbers: how far the load moves along itself (compliance over force) and the stiffness (a twist: the
198
+ // angle it turns, compliance over its moment, and the torsion, N·mm a radian), the largest
198
199
  // 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
199
- function measures(name, force, a, c, density, { nx, ny, h }, origin) {
200
- const deflection = force ? a.compliance[c] / force : 0;
200
+ function measures(name, force, moment, a, c, density, { nx, ny, h }, origin) {
201
+ const deflection = force ? a.compliance[c] / force : 0, angle = moment ? a.compliance[c] / moment : 0;
201
202
  let most = 0, cellAt = 0;
202
203
  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; }
203
204
  const index = [cellAt % nx, Math.floor(cellAt / nx) % ny, Math.floor(cellAt / (nx * ny))];
204
205
  const stressAt = origin.map((o, q) => round(o + (index[q] + 0.5) * h, 2)), d = a.deflection[c];
205
206
  return {
206
- name, force, deflection, stiffness: deflection ? force / deflection : Infinity, stress: most, stressAt,
207
+ name, ...(moment ? { moment, angle, torsion: moment / angle } : { force, deflection, stiffness: deflection ? force / deflection : Infinity }), stress: most, stressAt,
207
208
  movement: d.most, movementAt: d.at.map((x, q) => round(x + origin[q], 2)),
208
209
  };
209
210
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.6",
3
+ "version": "0.7.8",
4
4
  "description": "The cad command: JSCAD designs from traceable rules, checked for printing and fit, versioned by what fits, shared as links and exported as Bambu 3MF.",
5
5
  "type": "module",
6
6
  "bin": {