@rulecad/cad 0.7.58 → 0.7.60

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/AGENTS.md CHANGED
@@ -195,6 +195,12 @@ variable says which rule it comes from. Follow these steps; they're what makes a
195
195
  hand on a kit of one. `npx cad plates` lays out every printed part by material, with a frame's jigs beside them.
196
196
  A new frame project can start from `npm create rulecad my-frame --machine frame --size 300x300x350 --profile
197
197
  2020-misumi-hfs5`.
198
+ - What holds parts with no steel screw is named in the fit's `fastener`, never typed in a note:
199
+ `{ "pin": "snap pin 4x6", "count": 2 }`, `{ "pin": "dowel 3x12", "fit": "press" }`, or
200
+ `{ "magnet": "disc magnet 8x3", "count": 2, "load": 10 }`, with the holes or pockets drawn by `v.fixings.pinHole(...)`
201
+ and `v.fixings.magnetSeat(...)` under the same name. `cad check` then finds and checks them and `cad list` counts
202
+ them. A bolt to print is a fasten's screw with the word printed (`"M8x20 hex printed"`). Snap pins live in
203
+ `v.fixings` now (`v.flexures.snapPin` still draws the same pin); snap hooks and ratchets stay in `v.flexures`.
198
204
  - A fit with `"fastens": true` is for what holds parts without screws (pins, a press, a clip). An older assembly with
199
205
  a holes fit (`{ "holes": "pcb.board", "into": "case.body", … }`) and a fit that fastens the same parts gets a
200
206
  `fasten.suggest` note from `cad check`: `npx cad add fasten <project>/<assembly> --from-fits` puts the fasten in
package/CHANGELOG.md CHANGED
@@ -5,6 +5,55 @@ print (a hole's diameter, a seat's depth, a part's outline). Each release lists
5
5
  its reason. A **fasten** is an entry in an assembly's `"fasten"` list: one screwed joint, naming the screw by thread
6
6
  and head, the parts it passes through and the part it ends in.
7
7
 
8
+ ## 0.7.60: pins, magnets and printed bolts in assemblies, and the holds coupon (Fixings 4)
9
+
10
+ ### Added
11
+
12
+ - An assembly fit's `fastener` may name pins, `{ "pin": "snap pin 4x6", "count": 2, "fit", "load", "pull" }`, or
13
+ magnets, `{ "magnet": "disc magnet 8x3", "count": 2, "fit", "load", "gap" }` (the schema's `$defs.pins` and
14
+ `$defs.magnets`). `cad check` finds their holes or pockets (`fit.pin`, `fit.magnet`), checks each against the size
15
+ `@rulecad/fixings` draws it from the printer's rules, refuses by name a pin too long or too short for its part, a
16
+ pocket too shallow or with too thin a floor, or fewer holes than the count, and holds their load. `cad list` lists
17
+ pins (printed, cut or bought) and magnets (bought) with their grams; `cad order` names them on their step. The
18
+ free-text form (`"fastener": "push pin"`) works as before.
19
+ - A fasten's `screw` may name a printed bolt, `"M8x20 hex printed"`: it is refused below the printer's smallest
20
+ thread, checked against its load with `printedBoltModel` (no wrench torque is given), and listed as a printed part.
21
+ Into a thread printed in the part it takes half the printer's `thread_gap`; into a nut, a heat-set insert or a
22
+ tapped hole, a standard thread, it takes the whole gap (an M8 in PLA breaks at about 1195 N there, not 1272.7 N).
23
+ Into a pilot it is refused by name: a plastic thread forms no thread in plastic. Its findings say it is printed:
24
+ the length is the shortest that fits (not the shortest sold), the seat says what it takes with no tightening
25
+ torque, and the key is a socket turned by hand.
26
+ - `cad measured` knows the holds coupon's figures with no `--rule`: `x1c.snap_clearance`, `snap_barb`, `pin_press`,
27
+ `pin_slip`, `magnet_press`, `magnet_glue` and `magnet_crush`, each with its prediction read through the model that
28
+ draws from it and refused outside what a fit of its kind can be; and a plastic's `strength_z` from the pull bolt,
29
+ refused above its strength along the layers. `pin_slip` and `magnet_crush` may be 0 (both are past `hole_comp`, so 0
30
+ is a close fit); `snap_clearance` and `snap_barb` must be above 0, and the coupon's snap sockets stay a step above 0.
31
+ - The bench's `holds-coupon` (examples/bench/projects/benchmarks), printed with the fixings coupon on one plate
32
+ (`fixings-test`), and MEASURE.md rows 40 to 47.
33
+
34
+ ### Printed sizes that moved
35
+
36
+ None. The frames door's magnet pocket is drawn 10.2 mm as before; only its line on the shopping list reads
37
+ `disc magnet 10x3 N35`.
38
+
39
+ ### What a workspace should change
40
+
41
+ Nothing is required. An assembly that names pins or magnets in a fit's note can name them in `fastener` instead, so
42
+ they are found, checked and counted.
43
+
44
+ ## 0.7.59: routes kept between builds, assemblies shown as built
45
+
46
+ ### Added
47
+
48
+ - `"show": "built"` on an assembly draws its references (bought parts, boards, a module) solid in `cad preview`
49
+ and on the model page, as the thing built; they still aren't printed or downloaded.
50
+ - The autorouter's results are kept in the workspace's `.cache/routes`, by their exact input (@rulecad/pcb's route
51
+ cache): a board rebuilt for anything but its routing (a change to the library, its finish or its checks) reuses its
52
+ route instead of searching again. `CAD_NO_CACHE` turns it off with the rest of the cache.
53
+
54
+ ### Printed sizes that moved
55
+
56
+ None.
8
57
  ## 0.7.58: frame checks (Frames 3)
9
58
 
10
59
  ### Added
package/README.md CHANGED
@@ -441,6 +441,37 @@ set your own in `rules/packs.json`) with the spares said. `--json` gives each li
441
441
  thread, length, head, grams, mass, packs, buy, spare, from }`, the totals add `fixingsGrams` to the machine's mass,
442
442
  and the build page's list shows the same.
443
443
 
444
+ ### Pins, magnets and printed bolts
445
+
446
+ Two parts held with no steel screw are a fit with `"fastens": true` whose `fastener` names what holds them, in a form
447
+ the schema defines, so it is found, checked and counted as a screw is. Each is sized by `@rulecad/fixings`, which
448
+ draws its hole or pocket from the printer's rules:
449
+
450
+ ```json
451
+ { "a": "lid", "b": "box", "fastens": true, "fastener": { "pin": "snap pin 4x6", "count": 2, "pull": 5 } }
452
+ { "a": "lid", "b": "box", "fastens": true, "fastener": { "pin": "dowel 3x12", "count": 2, "fit": "press", "load": 30 } }
453
+ { "a": "lid", "b": "box", "fastens": true, "fastener": { "magnet": "disc magnet 8x3", "count": 2, "load": 10 } }
454
+ ```
455
+
456
+ - **Pins** (`fit.pin`): a snap pin, a steel dowel, a length of filament or a printed pin. `cad check` finds round holes
457
+ in part a whose axis goes on into part b, holds each to the hole fixings draws for that pin (a snap pin's socket, a
458
+ plain pin's press or slip hole), and measures the parts along the axis: a pin too long or too short for its parts
459
+ fails by name, and so do fewer holes than `count`. `load` (across the joint) and `pull` (along the pins) are held
460
+ to about twice the margin.
461
+ - **Magnets** (`fit.magnet`): round pockets in either part, each matched to a press, glued or ribbed pocket for that
462
+ magnet; a pocket too shallow, a floor too thin to print or the wrong size fails by name. `load` is held against
463
+ their pull, across `gap` where something lies between.
464
+ - **Printed bolts** are a fasten's: `"screw": "M8x20 hex printed"`. Below the printer's smallest thread it is refused
465
+ by name (M5 at 0.2 mm layers names M6); its load is held to the plastic's strength by how it prints, and no wrench
466
+ torque is said, since a printed thread is done up by hand.
467
+
468
+ `cad list` lists pins (printed, cut or bought) and magnets (bought) with their grams, and printed bolts among the
469
+ printed parts; `cad order` names each on its step. A fastener given as text (`"fastener": "push pin"`) is listed as
470
+ written, unchecked. The fits these rest on (`x1c.snap_clearance`, `pin_press`, `pin_slip`, `magnet_press`,
471
+ `magnet_glue`, `magnet_crush`, and a plastic's `strength_z`) are estimates until the holds coupon measures them:
472
+ `examples/bench/projects/benchmarks/MEASURE.md`, rows 40 to 47, and `cad measured benchmarks/fixings-test
473
+ x1c.pin_press=<figure>`, which refuses a figure no fit of its kind can be.
474
+
444
475
  ### Joints and poses
445
476
 
446
477
  Things that move (a lid, a hinged screen, a drawer, a ball head) are one assembly with joints, not one assembly per
package/bin/cad.mjs CHANGED
@@ -751,8 +751,9 @@ async function assembly(cmd, ref) {
751
751
  marks = (await import('../lib/motorsvg.mjs')).workMarks(s);
752
752
  }
753
753
  const size = (await import('@rulecad/printcheck')).bounds(s.triangles).size.map((n) => fmt(n)).join(' × ');
754
- const faint = [...new Set(s.parts.filter((p) => p.role !== 'part').map((p) => `${p.object || p.item}${p.role === 'support' ? ' supports' : ''}`))]; // each kind once
755
- await preview([...s.parts, ...wireTubesOf(s)], { title: check ? `${title}: the motor at work` : title, meta: `${size} mm · ${versions}${faint.length ? ` · faint: ${faint.join(', ')}` : ''}`, out, explode: !!opt('explode'), marks });
754
+ const built = s.a.show === 'built' // (show: built: references drawn solid, as the thing built)
755
+ const faint = [...new Set(s.parts.filter((p) => p.role !== 'part' && !(built && p.role === 'reference')).map((p) => `${p.object || p.item}${p.role === 'support' ? ' supports' : ''}`))]; // each kind once
756
+ await preview([...s.parts, ...wireTubesOf(s)], { title: check ? `${title}: the motor at work` : title, meta: `${size} mm · ${versions}${faint.length ? ` · faint: ${faint.join(', ')}` : ''}`, out, explode: !!opt('explode'), marks, built });
756
757
  // each motor at work beside it: its curve with the working point, and the torque through its train (said before
757
758
  // the picture, which stays the last line, for whatever reads it)
758
759
  if (s.motion?.drives?.length && !pose && !opt('explode') && !check) {
package/lib/assembly.mjs CHANGED
@@ -60,6 +60,7 @@ import { expandServices, serviceFindings } from './services.mjs';
60
60
  import { expandGuides, guideBuilt, guideFindings } from './guides.mjs';
61
61
  import { slotNutChecks } from './slotnuts.mjs';
62
62
  import { frameSquareChecks, frameBuild } from './framebuild.mjs';
63
+ let pinning = null; // lib/pins.mjs, loaded with the first assembly whose fits name pins
63
64
  let fastening = null; // lib/fasten.mjs, loaded with the first assembly that has a fasten: the rest start as fast as before
64
65
 
65
66
  export const assemblyPath = (ref) => { const [project, name] = String(ref).split('/'); return path.join(paths.project(project || ''), 'assemblies', `${name || ''}.json`); };
@@ -310,7 +311,9 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
310
311
  for (const x of a.fits || []) for (const n of [x.a, x.b, x.access].flat()) {
311
312
  if (typeof n === 'string' && beamIds.has(n.split('.')[0]) && n.includes('.') && !/\.body$/.test(n)) motion.address(n, `fit ${x.note || x.label || `${x.a} / ${x.b}`}`);
312
313
  }
314
+ if (a.fits?.some((x) => x.fastener && typeof x.fastener === 'object')) pinning ||= await import('./pins.mjs');
313
315
  for (let x of a.fits || []) {
316
+ if (x.fastener && typeof x.fastener === 'object') x = pinning.pinOfFit(x, project); // (pins or magnets by the schema's form: the fit's pin or magnet, and the fastener's name)
314
317
  if (x.seat != null && x.min == null) x = { ...x, min: -1000 }; // a seat presses, so the pair may overlap
315
318
  if (x.holes) x = { ...x, a: x.holes, b: x.into }; // a holes fit: a board's holes (a) over what its screws go into (b)
316
319
  const star = [x.a, x.b].find((n) => n.includes('*'));
@@ -848,6 +851,8 @@ export function checkAssembly(s) {
848
851
  if (x.silent) continue; // lets a pair overlap, and has nothing to report
849
852
  if (x.engage != null) { engageFit(x); continue; }
850
853
  if (x.seat != null) { seatFit(x, s, f, { placeItems, jointValues, mul, seatSize }); continue; }
854
+ if (x.pin && pinning) pinFit(x); // (and its gap, as any fit's)
855
+ if (x.magnet && pinning) magnetFit(x);
851
856
  if (x.shaft != null) { shaftFit(x, s, f, { placeItems, jointValues, mul, materialName: materialOf(s.project) }); continue; }
852
857
  const A = pickIn(x.a, x), key = x.note || `${x.a} / ${x.b}`;
853
858
  const lo = x.min != null ? x.num(x.min) : -Infinity, hi = x.max != null ? x.num(x.max) : Infinity;
@@ -905,6 +910,10 @@ export function checkAssembly(s) {
905
910
  f(ok ? 'pass' : 'fail', `${label}: ${on > 1e-3 ? `${mm(on)} mm on` : `not on at all (${Math.max(la, lb) - Math.min(ha, hb) < 1e-3 ? 'end to end' : 'apart'})`} along their joint${ok ? '' : `, where it should go ${mm(need)} mm on: its anchor is on the wrong face, or the shaft too short`}`, ok ? null : `${a}: not on ${b}`, { code: 'fit.engage', values: { engaged: on, need }, refs: { a: x.a, b: x.b, joint: j.id } });
906
911
  }
907
912
 
913
+ // Pin fits: the pins a fit names, their holes found in the parts and held to the pins' models (lib/pins.mjs)
914
+ function pinFit(x) { try { pinning.pinFit(x, s, f); } catch (e) { f('fail', `${x.note || `${x.a} to ${x.b}`}: ${e.message}`, null, { code: 'fit.pin', refs: { a: x.a, b: x.b, pin: x.fastener } }); } }
915
+ // Magnet fits: the magnets a fit names, their pockets found in the parts and held to the magnet's seat (lib/magnets.mjs)
916
+ function magnetFit(x) { try { pinning.magnetFit(x, s, f); } catch (e) { f('fail', `${x.note || `${x.a} to ${x.b}`}: ${e.message}`, null, { code: 'fit.magnet', refs: { a: x.a, b: x.b, magnet: x.fastener } }); } }
908
917
  // Holes fits: each mounting hole's screw path, clear into a hole, with material round it
909
918
  function holesFit(x) {
910
919
  const A = pick(x.a), B = pick(x.b), label = x.label || `${x.a} into ${x.b}`;
package/lib/design.mjs CHANGED
@@ -126,6 +126,9 @@ export function variantSet(d, object, set = {}) {
126
126
  }
127
127
 
128
128
  const CACHE = paths.cache('builds'), CACHE_VERSION = 3;
129
+ // The autorouter's results too, by its exact input (@rulecad/pcb reads RULECAD_ROUTE_CACHE): a board rebuilt for anything
130
+ // but its routing (a change to the library, its finish, its checks) reuses its route instead of searching again
131
+ if (!process.env.CAD_NO_CACHE) process.env.RULECAD_ROUTE_CACHE ||= paths.cache('routes');
129
132
  const source = (f) => fs.readFileSync(new URL(f, import.meta.url), 'utf8');
130
133
  // What every build is made with: this code, the shape helpers and JSCAD's version (an upgrade rebuilds everything);
131
134
  // boards also with the board engine (engineId: its code and tscircuit's version), loaded only for boards
package/lib/fasten.mjs CHANGED
@@ -235,7 +235,7 @@ function ring(near, z, radius, from, n = 24) {
235
235
  // Round holes found in a part as drawn, along each of its own three axes: walls that stand along the axis, joined
236
236
  // where they share a corner, kept where their corners lie on one circle and the walls face its centre.
237
237
  const found = new Map();
238
- function holesIn(p) {
238
+ export function holesIn(p) {
239
239
  const key = p.hash ?? p.shape;
240
240
  if (found.has(key)) return found.get(key);
241
241
  const out = [], tris = (p.localTriangles ?? p.triangles).flatMap(fan);
@@ -308,7 +308,7 @@ function accessOf(parts, tool, P, U) {
308
308
 
309
309
  // ---------- the project's fixings ----------
310
310
  const bound = new Map();
311
- function fixingsOf(project) {
311
+ export function fixingsOf(project) {
312
312
  const { context, hash } = fixingsContext({ project, dir: paths.project(project) });
313
313
  if (bound.get(project)?.hash !== hash) bound.set(project, { hash, F: fixingsFor({ ...(Object.keys(context.sets).length ? { sets: context.sets } : {}), ...(context.printer ? { printer: context.printer } : {}) }), material: context.material, printer: context.printer?.name ?? 'x1c' });
314
314
  return bound.get(project);
@@ -500,6 +500,8 @@ export function fastenOf(s, worlds, opts = {}) {
500
500
  let fx;
501
501
  try { fx = F.fixingModel(String(x.screw), {}, { anyLength: true }); } catch (e) { throw new Error(`${what}: ${e.message}`); }
502
502
  if (!['screw', 'thread'].includes(fx.item)) throw new Error(`${what}: "screw" names a screw by its thread and head ("M3 cap", "M4x12 button"): ${x.screw} is ${/^[aeiou]/.test(fx.item) ? 'an' : 'a'} ${fx.item}`);
503
+ // a printed bolt ("M8x20 hex printed"): refused by name where its thread is finer than the printer prints
504
+ if (fx.printed) { try { F.printedBoltModel(fx, { length: fx.length ?? 20, material }); } catch (e) { throw new Error(`${what}: ${e.message.replace(/^printedBoltModel: /, '')}`); } }
503
505
  const form = fx.head?.form ?? (fx.made.heads.includes('cap') ? 'cap' : fx.made.heads[0]);
504
506
  if (!Array.isArray(through)) throw new Error(`${what}: "through" lists the parts the screw passes, in order from under its head (["bracket"])`);
505
507
  if (typeof x.into !== 'string' || !x.into) throw new Error(`${what}: "into" names the part the screw ends in`);
@@ -748,7 +750,9 @@ export function fastenOf(s, worlds, opts = {}) {
748
750
  let threaded = null;
749
751
  if (!hit && end.main.a.loop.shape !== 'round') { try { const t = F.threadModel(fx, { internal: true, length: Math.max(end.depth, fx.pitch * 2) }); if (end.free > fx.major - 2 * fx.pitch && end.free < fx.major + 1) threaded = t; } catch {} }
750
752
  if (bt) say('fasten.end', 'pass', `ends in ${x.into}'s own ${bt.thread} thread, tapped ${mm(end.depth)} mm into its end bore ${bt.bore} (a machined tap, on its cut-and-drill sheet)`, { ...endValues, depth: r3(end.depth) });
751
- else if (hit) {
753
+ else if (hit && fx.printed && hit.kind === 'pilot') { // (a plastic bolt forms no thread in plastic: a pilot is for a bought thread-forming screw)
754
+ say('fasten.end', 'fail', `${x.into}'s hole is ${hit.says} (${mm(end.d)} mm as drawn), and ${fx.name} is a printed bolt: a plastic thread cannot form its own thread in plastic. Print the thread in ${x.into} (v.fixings.hole('${fx.thread}', { kind: 'thread' })), or end it in a nut or a heat-set insert`, endValues); bad = true; return;
755
+ } else if (hit) {
752
756
  end.kind = hit.kind;
753
757
  const basis = hit.hole.basis, trust = basis.kind === 'measured' ? 'measured' : basis.kind === 'spec' ? 'a standard\'s figure' : `${/^[aeiou]/.test(basis.kind) ? 'an' : 'a'} ${basis.kind} figure`;
754
758
  say('fasten.end', 'pass', `ends in ${x.into}, in ${hit.says}: ${mm(end.d)} mm as drawn (${basis.rule}, ${trust}), ${end.blind ? `${mm(end.depth)} mm deep` : `through its ${mm(end.depth)} mm`}`, endValues);
@@ -798,7 +802,7 @@ export function fastenOf(s, worlds, opts = {}) {
798
802
  const wouldDo = pick && pick.length !== L ? `${pick.name} would do` : null;
799
803
  if (given == null) {
800
804
  if (pick && end.slot) say('fasten.length', 'pass', `${pick.name} chosen, the shortest sold that fits: ${under} (${end.slot.part}${washer ? ', the washer' : ''} and ${lipSays(end.slot)}), ${mm2(pick.engaged)} mm into its nut, its tip ${mm2(zTip - end.mouth)} mm into the slot and ${mm2(pick.spare)} mm short of its floor`, { ...lenValues, floor: r3(pick.spare) });
801
- else if (pick) say('fasten.length', 'pass', `${pick.name} chosen, the ${end.motor ? (end.motor.reach ? 'longest sold that goes no further than its maker allows' : 'longest sold that stops short of the end of the thread') : 'shortest sold that fits'}: ${under} and ${mm2(pick.engaged)} mm into ${x.into}${end.kind === 'nut' ? '\'s nut' : ''}${pick.spare != null ? `, ${mm2(pick.spare)} mm short of bottoming out` : ''}`, lenValues);
805
+ else if (pick) say('fasten.length', 'pass', `${pick.name} chosen, the ${end.motor ? (end.motor.reach ? 'longest sold that goes no further than its maker allows' : 'longest sold that stops short of the end of the thread') : fx.printed ? 'shortest that fits (a printed bolt is printed to any whole millimetre)' : 'shortest sold that fits'}: ${under} and ${mm2(pick.engaged)} mm into ${x.into}${end.kind === 'nut' ? '\'s nut' : ''}${pick.spare != null ? `, ${mm2(pick.spare)} mm short of bottoming out` : ''}`, lenValues);
802
806
  else if (none) say('fasten.length', 'fail', `no length chosen: ${none}`, lenValues);
803
807
  else if (form !== 'set') say('fasten.length', 'info', `no length chosen until the far end is one a screw holds in: ${model.name} is drawn`, lenValues);
804
808
  } else if (inEnd <= EPS) say('fasten.length', 'fail', `${model.name} does not reach ${x.into}: it is ${mm2(L)} mm long and there is ${under}${wouldDo ? `. ${wouldDo}` : ''}`, lenValues);
@@ -863,14 +867,15 @@ export function fastenOf(s, worlds, opts = {}) {
863
867
  else {
864
868
  // what the seat takes: the ring under the head as drawn, against the strength of what it sits on
865
869
  let st = null;
866
- if (seatMat.name && seatMat.known) { try { st = F.seating(fx, { head: form, material: seatMat.name, ...(torque != null ? { torque } : {}) }); } catch { st = null; } }
870
+ if (seatMat.name && seatMat.known) { try { st = F.seating(fx, { head: form, material: seatMat.name, ...(torque != null ? { torque } : fx.printed ? { force: 1 } : {}) }); } catch { st = null; } } // (a printed bolt has no proof load to tighten to: only what the seat takes is read)
867
871
  const sunk = zSeat - A.reach[0], where = `a flat seat on ${A.name}${sunk > 0.01 ? `, ${mm(sunk)} mm down its counterbore` : ''}, whole out to the ${washer ? 'washer' : 'head'}'s ${mm(2 * bearR)} mm`;
868
872
  if (!st) say('fasten.seat', 'pass', `${where}${seatMat.name ? ` (no strength is known for ${seatMat.name}, so the pressure under it is not checked)` : ''}`, values);
869
873
  else {
870
874
  const D2 = st.head === 'hex' ? head.across * Math.cos(Math.PI / 6) : head.across, area = (d) => (Math.PI / 4) * (d * d - (2 * boreR) ** 2), bare = area(D2), onWasher = st.washer ? area(st.washer.diameter) : null, mine = washer ? onWasher : bare;
871
875
  const takes = st.limit * mine, K = DEFAULTS.nut_factor.value, torqueOf = (N) => (K * fx.major * N) / 1000, v2 = { ...values, area: +mine.toFixed(2), limit: st.limit, force: +takes.toFixed(1), torque: +torqueOf(takes).toFixed(3) };
872
- sc.most = +torqueOf(takes).toFixed(2); sc.seatForce = takes;
873
- if (torque == null) say('fasten.seat', 'pass', `${where}; on ${st.material} (${mm(st.limit)} MPa) its ${mm(+mine.toFixed(1))} mm² takes ${mm(+takes.toFixed(0))} N, a tightening of ${mm(+torqueOf(takes).toFixed(2))} N m${!washer && onWasher && sunk <= 0.01 ? `: the ${fx.thread} washer would raise that to ${mm(+(st.limit * onWasher).toFixed(0))} N (${mm(+torqueOf(st.limit * onWasher).toFixed(2))} N m)` : ''}`, v2);
876
+ if (!fx.printed) { sc.most = +torqueOf(takes).toFixed(2); sc.seatForce = takes; } // (a printed bolt is done up by hand: no torque to tighten to)
877
+ if (torque == null && fx.printed) say('fasten.seat', 'pass', `${where}; on ${st.material} (${mm(st.limit)} MPa) its ${mm(+mine.toFixed(1))} mm² takes ${mm(+takes.toFixed(0))} N. A printed bolt is done up by hand, with no torque to tighten to`, v2);
878
+ else if (torque == null) say('fasten.seat', 'pass', `${where}; on ${st.material} (${mm(st.limit)} MPa) its ${mm(+mine.toFixed(1))} mm² takes ${mm(+takes.toFixed(0))} N, a tightening of ${mm(+torqueOf(takes).toFixed(2))} N m${!washer && onWasher && sunk <= 0.01 ? `: the ${fx.thread} washer would raise that to ${mm(+(st.limit * onWasher).toFixed(0))} N (${mm(+torqueOf(st.limit * onWasher).toFixed(2))} N m)` : ''}`, v2);
874
879
  else {
875
880
  const p = st.force / mine, within = p <= st.limit + 1e-9, pw = onWasher ? st.force / onWasher : null;
876
881
  if (within) say('fasten.seat', 'pass', `${where}; at ${mm(torque)} N m the screw clamps with ${mm(st.force)} N, ${mm(+p.toFixed(1))} MPa under the ${washer ? 'washer' : 'head'} on ${st.material}, whose strength is ${mm(st.limit)} MPa`, { ...v2, pressure: +p.toFixed(1) });
@@ -895,7 +900,7 @@ export function fastenOf(s, worlds, opts = {}) {
895
900
  }
896
901
  if (end.kind === 'insert' && end.insert) piece('insert', fx.thread, {}, at(end.mouth), up, B, up, ends);
897
902
  // fasten.access: the key's way to the head, along its axis, with every other part in place (said by fastenChecks, with the order)
898
- const tool = toolFor(model, form, fx);
903
+ const tool0 = toolFor(model, form, fx), tool = tool0 && fx.printed ? { ...tool0, name: `${tool0.name} turned by hand` } : tool0; // (a printed bolt takes no wrench's torque)
899
904
  sc.tool = tool?.name ?? null;
900
905
  if (opts.access && tool) sc.access = accessOf(parts, tool, add(A ? at(zHead) : at(zSeat), up, model.top), up);
901
906
  });
@@ -907,8 +912,8 @@ export function fastenOf(s, worlds, opts = {}) {
907
912
  const id = `fasten-${k + 1}-${h.kind}-${sc.index + 1}`, hostIndex = ids.indexOf(h.host.item), hostWorld = rowsToMat4(worlds[hostIndex]);
908
913
  count[h.kind]++;
909
914
  const others = sc.hardware.filter((o) => o !== h).map((o) => `fasten-${k + 1}-${o.kind}-${sc.index + 1}`); // (a screw in its own nut, washer and insert)
910
- const hm = h.shape.model;
911
- hardware.push({ id, kind: h.kind, name: hm.name, thread: fx.thread, fasten: k, screw: sc.index, grams: hm.mass, label, length: hm.length ?? null, head: h.kind === 'screw' ? hm.head : h.kind === 'nut' ? hm.kind : null, shape: h.shape, host: hostIndex, hostItem: h.host.item, with: h.host.object || h.host.item,
915
+ const hm = h.shape.model, bolt = h.kind === 'screw' && fx.printed ? F.printedBoltModel(fx, { length: hm.length, head: hm.head, material, nut: boltMate(sc) }) : null; // (a printed bolt: by its name, in plastic)
916
+ hardware.push({ id, kind: h.kind, name: bolt ? bolt.name : hm.name, thread: fx.thread, fasten: k, screw: sc.index, grams: bolt ? bolt.grams : hm.mass, label, ...(bolt ? { printed: true } : {}), length: hm.length ?? null, head: h.kind === 'screw' ? hm.head : h.kind === 'nut' ? hm.kind : null, shape: h.shape, host: hostIndex, hostItem: h.host.item, with: h.host.object || h.host.item,
912
917
  local: mat4.multiply(mat4.create(), mat4.invert(mat4.create(), hostWorld), h.M), lift: vec3.transform([0, 0, 0], h.lift, mat4.invert(mat4.create(), [...hostWorld.slice(0, 12), 0, 0, 0, 1])), allow: [...h.allow, ...others] });
913
918
  }
914
919
  const names = new Map();
@@ -921,7 +926,7 @@ export function fastenOf(s, worlds, opts = {}) {
921
926
  if (!through.length && lines[0]) fits.push({ a: x.into, b: x.into, silent: true, fasten: k, note: label, ...lines[0] });
922
927
  for (const l of lines.slice(1)) fits.push({ a: through[0] ?? x.into, b: slotAt ? slotAt.item : x.into, silent: true, fasten: k, note: x.note || `${through[0] ?? x.into} fastened to ${x.into}`, ...l });
923
928
  rel.count = count; rel.torque = torque;
924
- rel.load = loadOf(s, worlds, rel, list, { F, fx, ids });
929
+ rel.load = loadOf(s, worlds, rel, list, { F, fx, ids, material });
925
930
  if (rel.load?.tighten != null && torque == null) for (const ft of fits.filter((q) => q.fasten === k && q.tighten)) ft.tighten = { torque: rel.load.tighten, given: false, load: true };
926
931
  relations.push(rel);
927
932
  });
@@ -952,7 +957,7 @@ function beyondOf(s, rel, list, ids) {
952
957
  * hung on them, under the assembly's gravity, and the torque of a motor among them whose reaction it takes; each
953
958
  * screw against its strength (screwLoad). Null where nothing loads the joint (no "loads", no motor beyond it).
954
959
  */
955
- function loadOf(s, worlds, rel, list, { F, fx, ids }) {
960
+ function loadOf(s, worlds, rel, list, { F, fx, ids, material }) {
956
961
  const ok = rel.screws.filter((sc) => sc.dir && sc.at), loads = (s.motion.loads || []).filter((l) => l.mass != null);
957
962
  if (!ok.length || ok.length < rel.screws.length) return null;
958
963
  const beyond = beyondOf(s, rel, list, ids);
@@ -980,16 +985,32 @@ function loadOf(s, worlds, rel, list, { F, fx, ids }) {
980
985
  const screws = ok.map((sc, i) => {
981
986
  const pick = cases.map((gp) => gp.screws[i]).reduce((a, b) => (b.tension > a.tension + 1e-9 || (Math.abs(b.tension - a.tension) <= 1e-9 && b.shear > a.shear) ? b : a));
982
987
  const threaded = ['pilot', 'tap', 'thread'].includes(sc.endKind) && sc.intoMaterial && sc.engaged > 0;
983
- const r = F.screwLoad(fx, { tension: Math.max(0, pick.tension), shear: pick.shear, ...(threaded ? { depth: sc.engaged, material: sc.intoMaterial } : ['insert', 'nut'].includes(sc.endKind) ? { end: sc.endKind } : {}), ...(rel.torque != null ? { torque: rel.torque } : sc.seatForce ? { most: sc.seatForce } : {}) });
988
+ const r = fx.printed ? printedLoad(F, fx, sc, pick, material) : F.screwLoad(fx, { tension: Math.max(0, pick.tension), shear: pick.shear, ...(threaded ? { depth: sc.engaged, material: sc.intoMaterial } : ['insert', 'nut'].includes(sc.endKind) ? { end: sc.endKind } : {}), ...(rel.torque != null ? { torque: rel.torque } : sc.seatForce ? { most: sc.seatForce } : {}) });
984
989
  return { sc, tension: pick.tension, shear: pick.shear, r };
985
990
  });
986
991
  const share = torques.length ? Math.max(...screwGroup(places, { moment: [0, 0, torques.reduce((t, q) => t + q.about, 0)] }).screws.map((x) => x.shear)) : null;
987
992
  const worst = screws.reduce((a, b) => (b.r.margin < a.r.margin ? b : a)), slip = screws.filter((x) => x.r.margins.slip != null).reduce((a, b) => (!a || b.r.margins.slip < a.r.margins.slip ? b : a), null);
988
- const tighten = rel.torque == null ? Math.min(...screws.map((x) => x.r.preload.torque)) : null;
993
+ const tighten = rel.torque == null && !fx.printed ? Math.min(...screws.map((x) => x.r.preload.torque)) : null; // (a printed bolt is done up by hand)
989
994
  const rests = [...new Map(screws.flatMap((x) => x.r.rests).filter((q) => q.kind === 'estimate' || q.kind === 'community').map((q) => [q.name, q])).values()].map((q) => q.name);
990
995
  return { beyond: [...beyond].filter((k) => k >= 0).map((k) => ids[k]), kg, hung: hung.length, force: Fw, torques, share, screws, worst, slip, tighten, rests, line: cases[0].line, turns: cases.map((gp) => gp.turns).find((t) => t != null) ?? null };
991
996
  }
992
997
 
998
+ // A printed bolt under its share of a load, in screwLoad's shape: its breaking load along it (printedBoltModel: the
999
+ // root in tension, the teeth in the nut, the head), and across it its root's section at the plastic's shear strength.
1000
+ // It is done up by hand, so it has no preload and nothing to slip by
1001
+ // What a printed bolt's thread mates with: a thread printed in the part takes half the gap (printed); a nut, a heat-set
1002
+ // insert or a tapped hole is a standard thread, so the bolt takes the whole gap (steel)
1003
+ const boltMate = (sc) => (sc.endKind == null || sc.endKind === 'thread' ? 'printed' : 'steel');
1004
+ function printedLoad(F, fx, sc, pick, material) {
1005
+ const T = Math.max(0, pick.tension), S = pick.shear, b = F.printedBoltModel(fx, { length: sc.length, head: sc.model?.head, material, nut: boltMate(sc), ...(sc.engaged > 0 ? { depth: sc.engaged } : {}) });
1006
+ const across = b.rootArea * b.strip.shear, kT = T > 0 ? b.breaking / T : Infinity, kS = S > 0 ? across / S : Infinity, margin = Math.min(kT, kS), want = DEFAULTS.load_margin.value, k2 = (x) => (x === Infinity ? 'any number of' : mm(+x.toFixed(2)));
1007
+ const level = margin < 1 ? 'fail' : margin < want ? 'warn' : 'pass', governs = kS < kT ? 'shear across its root' : b.governs === 'tension' ? 'its root in tension' : b.governs === 'strip' ? 'its teeth in the nut' : 'its head';
1008
+ const text = `${b.name} in ${b.material}, done up by hand, with ${mm(+T.toFixed(1))} N of pull and ${mm(+S.toFixed(1))} N of shear: it breaks along at about ${mm(b.breaking)} N (${b.governs}) and across at ${mm(+across.toFixed(1))} N (its ${mm(b.rootArea)} mm² root at ${mm(b.strip.shear)} MPa), estimates. ${margin === Infinity ? 'Nothing pulls on it' : `It holds ${k2(margin)} times the load, ${governs} first`}${level === 'pass' ? '' : `, where the kit asks ${want} times`}`;
1009
+ const r2 = (x) => (x === Infinity ? Infinity : +x.toFixed(2));
1010
+ return { thread: fx.thread, tension: T, shear: S, preload: { force: 0, torque: 0, given: false }, proof: null, strip: b.strip.load, margins: { screw: r2(kT), thread: null, slip: null }, margin: r2(margin), governs: 'screw', rests: [...b.rests, { name: 'fixings.load_margin', ...DEFAULTS.load_margin }],
1011
+ findings: [{ level, text, code: 'screwLoad.margin', values: { tension: +T.toFixed(1), shear: +S.toFixed(1), breaking: b.breaking, across: +across.toFixed(1), margin: margin === Infinity ? null : r2(margin) } }] };
1012
+ }
1013
+
993
1014
  /**
994
1015
  * A piece of hardware as a placed part, where its item stands.
995
1016
  * @param {object} h a piece from fastenOf's hardware @param {number[]} hostWorld its item's place (a JSCAD mat4)
@@ -1002,7 +1023,7 @@ export function hardwarePart(h, hostWorld) {
1002
1023
  return { name: `${h.id}.body`, item: h.id, leaf: h.id, object: h.name, role: 'reference', label: `${h.id}: ${h.name}`, part: 'body',
1003
1024
  geometry: jscad.transforms.transform(m, h.shape.geometry), polygons: move(h.shape.polygons), triangles: move(h.shape.triangles),
1004
1025
  shape: `${h.shape.hash}:body`, hash: `${h.shape.hash}:body`, local: h.shape.polygons, localTriangles: h.shape.triangles, m,
1005
- hardware: { kind: h.kind, name: h.name, fasten: h.fasten, screw: h.screw, thread: h.thread, grams: h.grams, from: h.label, length: h.length, head: h.head }, moves: h.hostItem, with: h.with, lift, allow: h.allow };
1026
+ hardware: { kind: h.kind, name: h.name, fasten: h.fasten, screw: h.screw, thread: h.thread, grams: h.grams, from: h.label, length: h.length, head: h.head, ...(h.printed ? { printed: true } : {}) }, moves: h.hostItem, with: h.with, lift, allow: h.allow };
1006
1027
  }
1007
1028
 
1008
1029
  const CODES = ['fasten.holes', 'fasten.slot', 'fasten.clearance', 'fasten.end', 'fasten.length', 'fasten.engagement', 'fasten.seat', 'fasten.access'];
package/lib/links.mjs CHANGED
@@ -89,6 +89,7 @@ export async function assemblyModel(s, { title, versions, filaments: fil = {}, n
89
89
  }
90
90
  const model = {
91
91
  title, version: versions, src: `${s.project}/${s.name}`, // object versions are in version: the file name stays short
92
+ ...(s.a?.show === 'built' ? { show: 'built' } : {}), // its references drawn solid on the page
92
93
  rules: [],
93
94
  ...sheet([...new Map(s.objects.filter((o) => o.built?.entries).map((o) => [o.objName, o.built.entries])).entries()], { noRules }),
94
95
  // Its boards' 2D views (copper, schematic), so one link holds the whole build: tabs over the 3D model
package/lib/list.mjs CHANGED
@@ -1,10 +1,10 @@
1
1
  // What a machine takes to build, in numbers: the bought items by rule set with quantities, every screw, nut, washer and
2
- // insert (fasten.count: from the fasten relations, a motor's mounting screws, and fits that name a fastener), each by
2
+ // insert (fasten.count: from the fasten relations, a motor's mounting screws, and fits that name a fastener or pins), each by
3
3
  // thread, length and head with its mass and the packs it is bought in, wires by gauge, the printed parts with their
4
4
  // grams and an estimate of the minutes, and the beams' cut list (each mark, the bars to buy and the cuts on each:
5
5
  // @rulecad/frames' cutList).
6
6
  import { placeItems, jointValues } from '@rulecad/model-link';
7
- import { screwModel } from '@rulecad/fixings';
7
+ import { screwModel, pinModel, magnetModel } from '@rulecad/fixings';
8
8
  import { peekRuleSet as loadRuleSet } from './rules.mjs';
9
9
  import { motorScrews } from './motors.mjs';
10
10
  import { paths } from './workspace.mjs';
@@ -53,18 +53,28 @@ export function shoppingList(s) {
53
53
  // fasten.count: the hardware a fasten placed (a component's too), one part a piece; a motor's mounting screws; and a fit
54
54
  // that names its fastener by hand. Summed by name, which is the thread, length and head, or the nut's kind
55
55
  const add = (name, n, from, more = {}) => { const line = fasteners.get(name) ?? { fastener: name, qty: 0, from: [], ...more }; line.qty += n; if (!line.from.includes(from)) line.from.push(from); fasteners.set(name, line); };
56
- for (const p of s.parts) if (p.hardware) { const h = p.hardware; add(h.name, 1, h.from ?? h.name, { kind: h.kind, thread: h.thread ?? null, length: h.length ?? null, head: h.head ?? null, grams: h.grams ?? null }); }
56
+ // (a printed bolt is no bought screw: it goes with the printed parts, by its name, with its grams and minutes)
57
+ const bolts = new Map();
58
+ for (const p of s.parts) if (p.hardware?.printed) { const h = p.hardware, b = bolts.get(h.name) ?? { id: h.name, object: null, count: 0, grams: 0, bolt: true, from: [] }; b.count++; b.grams += h.grams ?? 0; if (!b.from.includes(h.from)) b.from.push(h.from); bolts.set(h.name, b); }
59
+ let flow = 12; try { flow = loadRuleSet('x1c').rules.print_flow?.value ?? flow; } catch {}
60
+ for (const b of bolts.values()) { const mm3 = (b.grams / mat.density) * 1000; printed.push({ id: b.id, object: null, volume: n(mm3, 0), grams: n(b.grams), minutes: n(mm3 / flow / 60, 0), count: b.count, bolt: true, from: b.from }); }
61
+ for (const p of s.parts) if (p.hardware && !p.hardware.printed) { const h = p.hardware; add(h.name, 1, h.from ?? h.name, { kind: h.kind, thread: h.thread ?? null, length: h.length ?? null, head: h.head ?? null, grams: h.grams ?? null }); }
57
62
  for (const m of motorScrews(s, { placeItems, jointValues })) {
58
63
  let grams = null; try { grams = screwModel(m.thread, { length: m.length, head: m.head, anyLength: true }).mass; } catch {}
59
64
  add(m.name, m.count, `${m.item} on ${m.other} (its mount, a fit that fastens)`, { kind: 'screw', thread: m.thread, length: m.length, head: m.head, grams });
60
65
  }
61
66
  // what a printed fitting takes besides its screws: a hinge's pin and its nut, a catch's magnet and strike (lib/fittings.mjs)
62
67
  for (const o of s.objects) if (o.fitting?.hardware && !o.unplaced) for (const h of o.fitting.hardware) add(h.name, h.count ?? 1, `${o.id} (${h.why ?? 'its fitting'})`, { kind: h.kind, thread: h.thread ?? null, length: h.length ?? null, head: h.head ?? null, grams: null });
63
- for (const x of s.fits) if (x.fastener && x.fasten == null) add(x.fastener, x.count != null ? x.num(x.count) : 1, x.note || `${x.a} / ${x.b}`);
68
+ // (pins and magnets a fit names by the schema's form: by name, with their mass and whether they are bought, cut from filament or printed)
69
+ for (const x of s.fits) if (x.fastener && x.fasten == null) {
70
+ let more = {}; if (x.pin) try { const m = pinModel(x.fastener, { material: mat.name }); more = { kind: 'pin', made: m.made, thread: null, length: m.length, grams: m.grams }; } catch {}
71
+ if (x.magnet) try { more = { kind: 'magnet', made: 'bought', thread: null, length: null, grams: magnetModel(x.fastener).grams }; } catch {}
72
+ add(x.fastener, x.count != null ? x.num(x.count) : 1, x.note || `${x.a} / ${x.b}`, more);
73
+ }
64
74
  // Rounded up to whole packs (packs.pack), the spares said
65
75
  let pack = null; try { const r = loadRuleSet('packs').rules.pack; pack = { size: r.value, rule: 'packs.pack', kind: r.kind }; } catch {}
66
- const fixings = [...fasteners.values()].map((l) => ({ ...l, ...(l.grams != null ? { grams: n(l.grams, 3), mass: n(l.grams * l.qty, 2) } : {}), ...(l.kind && pack ? { packs: Math.ceil(l.qty / pack.size), buy: Math.ceil(l.qty / pack.size) * pack.size, spare: Math.ceil(l.qty / pack.size) * pack.size - l.qty } : {}) }))
67
- .sort((a, b) => (a.kind ? 0 : 1) - (b.kind ? 0 : 1) || ['screw', 'nut', 'washer', 'insert'].indexOf(a.kind) - ['screw', 'nut', 'washer', 'insert'].indexOf(b.kind) || String(a.thread).localeCompare(String(b.thread)) || (a.length ?? 0) - (b.length ?? 0) || a.fastener.localeCompare(b.fastener));
76
+ const fixings = [...fasteners.values()].map((l) => ({ ...l, ...(l.grams != null ? { grams: n(l.grams, 3), mass: n(l.grams * l.qty, 2) } : {}), ...(l.kind && pack && (l.kind !== 'pin' || l.made === 'bought') ? { packs: Math.ceil(l.qty / pack.size), buy: Math.ceil(l.qty / pack.size) * pack.size, spare: Math.ceil(l.qty / pack.size) * pack.size - l.qty } : {}) }))
77
+ .sort((a, b) => (a.kind ? 0 : 1) - (b.kind ? 0 : 1) || ['screw', 'nut', 'washer', 'insert', 'pin', 'magnet'].indexOf(a.kind) - ['screw', 'nut', 'washer', 'insert', 'pin', 'magnet'].indexOf(b.kind) || String(a.thread).localeCompare(String(b.thread)) || (a.length ?? 0) - (b.length ?? 0) || a.fastener.localeCompare(b.fastener));
68
78
  const rows = s.wires?.length ? wiresFor(s) : [], wires = new Map();
69
79
  for (const w of rows) { const key = w.gauge ?? 'gauge not given', l = wires.get(key) ?? { gauge: w.gauge, conductors: 0, length: 0, runs: [] }; l.length += w.length * w.conductors; l.conductors += w.conductors; l.runs.push(w.id); wires.set(key, l); }
70
80
  const boughtList = [...bought.values()].map((b) => ({ ...b, grams: b.grams != null ? n(b.grams) : null })).sort((a, b) => a.part.localeCompare(b.part) || a.set.localeCompare(b.set) || (b.length ?? 0) - (a.length ?? 0));
@@ -91,7 +101,7 @@ export function listText(ref, l) {
91
101
  if (l.totals.pack) out.push(` (packs of ${l.totals.pack.size}: ${l.totals.pack.rule}, ${/^[aeiou]/.test(l.totals.pack.kind) ? 'an' : 'a'} ${l.totals.pack.kind}; masses are estimates from each piece's outline)`);
92
102
  }
93
103
  if (l.wires.length) { out.push('', 'Wire'); for (const w of l.wires) row([` ${w.length} mm of`, w.gauge ?? 'gauge not given', `in ${w.runs.join(', ')}`]); }
94
- if (l.printed.length) { out.push('', `Printed (${l.totals.material})`); for (const p of l.printed) row([` ${String(p.grams).padStart(7)} g`, `about ${p.minutes} min`, `${p.id}${p.object && p.object !== p.id ? ` (${p.object})` : ''}${p.with ? ` (comes with ${p.with}: printed beside it, screwed into it by hand)` : ''}`]); }
104
+ if (l.printed.length) { out.push('', `Printed (${l.totals.material})`); for (const p of l.printed) row([` ${String(p.grams).padStart(7)} g`, `about ${p.minutes} min`, `${p.id}${p.object && p.object !== p.id ? ` (${p.object})` : ''}${p.with ? ` (comes with ${p.with}: printed beside it, screwed into it by hand)` : ''}${p.bolt ? ` (${p.count} printed bolt${p.count > 1 ? 's' : ''}, standing on ${p.count > 1 ? 'their heads' : 'its head'}: ${p.from.join('; ')})` : ''}`]); }
95
105
  out.push('', `Total: ${l.totals.printedGrams} g printed, about ${l.totals.minutes} min of printing (an estimate from volume and the printer's flow), ${l.totals.fixingsGrams ? `${l.totals.fixingsGrams} g of fixings, ` : ''}${l.totals.machineGrams} g as a machine${l.totals.noMassFor ? ` (no mass given for ${l.totals.noMassFor.join(', ')})` : ''}`);
96
106
  if (l.cost) {
97
107
  const c = l.cost, parts = [];
@@ -0,0 +1,93 @@
1
+ // Magnets in an assembly: a fit whose "fastener" names magnets, { "magnet": "disc magnet 8x3", "count": 2, "load": 10 },
2
+ // is checked from the parts as drawn. The magnets' pockets are found in part a or part b (round holes about the size
3
+ // @rulecad/fixings' magnetSeatModel draws for the magnet and the project's printer, for any fit or the one asked), each
4
+ // measured along its axis: deep enough for the magnet (one standing proud of its face is refused by name), and the floor
5
+ // left under it held to what prints. The magnets' pull is said, and held to the fit's load where it gives one. They go on
6
+ // the shopping list (lib/list.mjs, bought) and the build step (lib/order.mjs) by their names.
7
+ import { jscad } from './design.mjs';
8
+ import { profile, holesIn, fixingsOf } from './fasten.mjs';
9
+
10
+ const { vec3 } = jscad.maths;
11
+
12
+ const mm = (n) => String(Number(Number(n).toFixed(3))), r3 = (x) => +x.toFixed(3);
13
+ const unit = (v) => { const l = Math.hypot(...v); return v.map((c) => c / l); };
14
+ const top = (n) => String(n).split(/[.@]/)[0];
15
+ /** How far a pocket as drawn may be from one the magnet's fits draw and still be taken for it, mm across. */
16
+ const TOL = 0.06;
17
+ /** What a fit's magnets may say: the assembly schema's $defs.magnets. */
18
+ export const MAGNET_KEYS = ['magnet', 'count', 'fit', 'load', 'gap'];
19
+ const FITS = ['press', 'glue', 'ribs'];
20
+
21
+ /**
22
+ * A fit's magnets as the assembly reads them: { magnet, count, fit, load, gap }, which become the fit's magnet and its
23
+ * fastener's name, the magnet's in its one spelling ('disc magnet 8x3 N35'). They fasten the two parts unless the fit
24
+ * says otherwise.
25
+ * @param {object} x a fit as written, its fastener an object with "magnet" @param {object} F the project's fixings (fixingsFor)
26
+ * @returns {object} the fit, with magnet and a fastener's name
27
+ */
28
+ export function magnetOfFit(x, F) {
29
+ const p = x.fastener, label = x.note || x.label || `${x.a} / ${x.b}`;
30
+ if (typeof p.magnet !== 'string' || !p.magnet.trim()) throw new Error(`fit ${label}: fastener as an object names magnets: { "magnet": "disc magnet 8x3", "count": 2 } (got ${JSON.stringify(p)})`);
31
+ const stray = Object.keys(p).filter((k) => !MAGNET_KEYS.includes(k));
32
+ if (stray.length) throw new Error(`fit ${label}: magnets have no "${stray.join('", "')}": a fastener naming magnets takes ${MAGNET_KEYS.join(', ')} (the assembly schema's magnets)`);
33
+ if (x.count != null && p.count != null) throw new Error(`fit ${label}: give the magnets' count once, in the fastener ({ "magnet": ..., "count": 2 })`);
34
+ if (p.fit != null && !FITS.includes(p.fit)) throw new Error(`fit ${label}: a magnet's fit is ${FITS.join(', ')} (got ${JSON.stringify(p.fit)})`);
35
+ let name;
36
+ try { name = F.magnetModel(p.magnet.trim()).name; } catch (e) { throw new Error(`fit ${label}: ${e.message.replace(/^magnetModel: /, '')}`); }
37
+ return { fastens: true, ...x, magnet: { ...p, magnet: p.magnet.trim() }, fastener: name, ...(p.count != null || x.count != null ? { count: p.count ?? x.count } : {}) };
38
+ }
39
+
40
+ /**
41
+ * fit.magnet: the magnets a fit names, their pockets found in the parts as drawn and checked against the magnet's seat.
42
+ * @param {object} x the fit, with magnet (magnetOfFit) @param {object} s the built assembly @param {Function} f the findings' sink, as checkAssembly's
43
+ */
44
+ export function magnetFit(x, s, f) {
45
+ const label = x.note || x.label || `${x.a} to ${x.b}`, code = 'fit.magnet', p = x.magnet, refs = { a: x.a, b: x.b, magnet: x.fastener };
46
+ const fail = (text, short, more = {}) => f('fail', `${label}: ${text}`, short ?? `${label}: magnets`, { code, refs, ...more });
47
+ const { F, material } = fixingsOf(s.project);
48
+ const count = x.count != null ? x.num(x.count) : 1, load = p.load != null ? x.num(p.load) : null, gap = p.gap != null ? x.num(p.gap) : 0;
49
+ if (!(Number.isInteger(count) && count >= 1)) return fail(`count is how many magnets, a whole number from 1 (got ${count})`);
50
+ let seats;
51
+ try { seats = (p.fit ? [p.fit] : FITS).map((fit) => F.magnetSeatModel(p.magnet, { fit, material, gap, count, ...(load != null ? { load } : {}) })); } catch (e) { return fail(e.message.replace(/^magnet\w*: /, '')); }
52
+ const m = seats[0].magnet;
53
+ if (m.shape !== 'disc') return fail(`${m.name}: a block magnet's pocket is not round, and only round pockets are found in the parts here; check its pocket with v.fixings.magnetSeatModel`, `${label}: block magnet`);
54
+ const named = (q, n) => q.name === n || q.leaf === n || q.item === n || q.name.startsWith(`${n}.`);
55
+ const sides = [x.a, x.b].map((n) => ({ name: n, parts: s.parts.filter((q) => !q.hardware && named(q, top(n))) }));
56
+ const missing = sides.find((sd) => !sd.parts.length);
57
+ if (missing) return fail(`no part "${missing.name}"`, `${label}: no part`);
58
+ const R = m.diameter / 2 + 2, wants = seats.map((st) => ({ fit: st.fit, d: st.pocket.diameter, rules: st.pocket.rules }));
59
+ // The pockets: round holes about a fit's pocket, measured along their axis: the hole open at one end, its floor at the other
60
+ const found = [], odd = [];
61
+ for (const sd of sides) for (const q of sd.parts) for (const h of holesIn(q)) {
62
+ const want = wants.find((w) => Math.abs(h.d - w.d) <= TOL), near = !want && Math.abs(h.d - m.diameter) <= 0.6;
63
+ if (!want && !near) continue;
64
+ const O = q.m ? vec3.transform([0, 0, 0], h.at, q.m) : h.at, e = q.m ? vec3.transform([0, 0, 0], h.at.map((c, i) => c + h.axis[i]), q.m) : h.at, D = unit(e.map((c, i) => c - O[i]));
65
+ const segs = profile(q.triangles, O, D, R).segs.filter((g) => g.solid || g.hole);
66
+ const holes = segs.filter((g) => g.hole);
67
+ if (!holes.length) continue;
68
+ // the pocket's run: its hole segments side by side (a lead-in's cone is one of its own), and the floor past one end
69
+ const hole = holes.reduce((a, b) => (b.z1 - b.z0 > a.z1 - a.z0 ? b : a));
70
+ let i0 = segs.indexOf(hole), i1 = i0;
71
+ while (segs[i0 - 1]?.hole && Math.abs(segs[i0 - 1].z1 - segs[i0].z0) < 1e-4) i0--;
72
+ while (segs[i1 + 1]?.hole && Math.abs(segs[i1 + 1].z0 - segs[i1].z1) < 1e-4) i1++;
73
+ const before = segs[i0 - 1], after = segs[i1 + 1], run = { z0: segs[i0].z0, z1: segs[i1].z1 };
74
+ const floorSeg = before?.solid && !after ? before : after?.solid && !before ? after : null; // (blind: material on one side only)
75
+ const where = O.map(r3);
76
+ if (near) { odd.push({ part: sd.name, d: r3(h.d), at: where }); continue; }
77
+ found.push({ part: sd.name, fit: want.fit, rules: want.rules, d: r3(h.d), depth: r3(run.z1 - run.z0), floor: floorSeg ? r3(floorSeg.z1 - floorSeg.z0) : null, at: where });
78
+ }
79
+ for (const o of odd) fail(`${o.part}'s pocket at ${o.at.map(mm).join(', ')} is drawn ${mm(o.d)} mm, and ${m.name} wants ${wants.map((w) => `${mm(w.d)} mm ${w.fit === 'ribs' ? 'with ribs' : `for a ${w.fit} fit`} (${w.rules.join(', ')})`).join(' or ')}: ${o.d < Math.min(...wants.map((w) => w.d)) ? 'too small, it will not go in' : 'too big, it will be loose'}`, `${label}: pocket ${o.d < Math.min(...wants.map((w) => w.d)) ? 'small' : 'big'} in ${o.part}`, { at: o.at, values: { part: o.part, drawn: o.d } });
80
+ if (odd.length) return;
81
+ if (found.length < count) return fail(`${count} × ${m.name} wanted, and ${found.length ? `only ${found.length} pocket${found.length > 1 ? 's' : ''} about its ${wants.map((w) => mm(w.d)).join(' or ')} mm ${found.length > 1 ? 'are' : 'is'}` : 'no pocket about its size is'} drawn in ${x.a} or ${x.b}: draw them with v.fixings.magnetSeat`, `${label}: pockets missing`, { values: { count, found: found.length } });
82
+ let bad = 0;
83
+ for (const k of found) {
84
+ if (k.depth < m.thickness - TOL) { bad++; fail(`${k.part}'s pocket at ${k.at.map(mm).join(', ')} is ${mm(k.depth)} mm deep, and ${m.name} is ${mm(m.thickness)} mm thick: it stands ${mm(r3(m.thickness - k.depth))} mm proud of the face`, `${label}: pocket shallow in ${k.part}`, { at: k.at, values: { depth: k.depth, thickness: m.thickness } }); continue; }
85
+ if (k.floor != null) { try { // (the floor held to fixings.magnet_floor by the seat's own refusal)
86
+ F.magnetSeatModel(p.magnet, { fit: k.fit, material, thickness: r3(k.depth + k.floor), recess: Math.max(0, r3(k.depth - m.thickness)) }); } catch (e) { bad++; fail(`${k.part}'s pocket at ${k.at.map(mm).join(', ')}: ${e.message.replace(/^magnetSeatModel: /, '')}`, `${label}: floor thin in ${k.part}`, { at: k.at, values: { floor: k.floor } }); } }
87
+ }
88
+ if (bad) return;
89
+ const fits = [...new Set(found.map((k) => k.fit))], seat = seats.find((st) => st.fit === fits[0]), parts = [...new Set(found.map((k) => k.part))];
90
+ f('pass', `${label}: ${count} × ${m.name} in ${fits.join(' and ')} pockets drawn ${[...new Set(found.map((k) => mm(k.d)))].join(' and ')} mm (${seat.pocket.rules.join(', ')}) in ${parts.join(' and ')}, each deep enough for the magnet`, null, { code, refs, values: { count, pocket: seat.pocket.diameter, grams: m.grams } });
91
+ const pull = seat.findings.find((g) => g.code === 'magnet.pull'), hold = seat.findings.find((g) => g.code === 'magnet.hold');
92
+ f(hold ? hold.level : 'info', `${label}: ${pull.text}${hold ? `. ${hold.text}` : `. Together ${count} pull ${mm(seat.magnet.total)} N: give load to have it checked`}`, hold && hold.level !== 'pass' ? `${label}: magnets weak` : null, { code: 'fit.magnet.load', refs, values: { pull: seat.magnet.pull, total: seat.magnet.total, ...(hold ? hold.values : {}) } });
93
+ }
package/lib/measured.mjs CHANGED
@@ -8,7 +8,9 @@
8
8
  // out from it, to the rule the spring came from: the joins set (the workspace's copy, started from @rulecad/frames'
9
9
  // estimates), a bought fitting's set, or a printed fitting's share of its finite-element figure. The beam coupon's sag
10
10
  // and the mass it broke at (beam.coupon's <beam>.sag and <beam>.break) write the modulus and strength a printed beam has
11
- // to its plastic's set (beam_modulus, beam_strength; _z standing up).
11
+ // to its plastic's set (beam_modulus, beam_strength; _z standing up). The holds coupon's fits (a snap pin's socket, a
12
+ // plain pin's press and slip, a magnet's press, glue and crush ribs, and the snap pins' barb as a record) need no --rule
13
+ // either, and each is refused outside what a fit of its kind can be; its pull bolt writes the plastic's strength_z.
12
14
  import fs from 'node:fs';
13
15
  import path from 'node:path';
14
16
  import { setAt } from './jsonedit.mjs';
@@ -118,10 +120,49 @@ function fixingsRule(project, set, key) {
118
120
  rule: `Clearance across the flats of a nut pocket let in from a face, on top of hole_comp: the tightest on ${COUPON} a hex nut dropped into by hand and did not turn in as its screw was tightened. A nut pocket's snug fit` };
119
121
  if (key === 'nut_slip') { const t = f().nutTrapModel('M3', { depth: 1 }); return { unit: 'mm', predicted: t.clearance, was: t.rests.find((r) => /slip$/.test(r.name))?.name ?? 'slip', source: COUPON,
120
122
  rule: `Clearance across the flats of a nut slot a nut slides into from the side, on top of hole_comp: the tightest on ${COUPON} a hex nut slid into by hand, stayed in turned over, and did not turn as its screw was tightened. A nut slot's slip fit` }; }
123
+ // The holds coupon's fits (rows 40 to 45): each the printer's rule a pin, a snap pin's socket or a magnet's pocket is
124
+ // drawn from, read through the model that draws it, so the ledger's prediction is what the kit drew; and the snap
125
+ // pins' barb, a record as the flank form is. Each is held to what a fit of its kind can be, so a slip of the pen
126
+ // (a diameter for a clearance) is refused before anything is written
127
+ const fit = HOLDS[key];
128
+ if (fit) {
129
+ const r = fit.model(f()).rests.find((x) => x.name.endsWith(`.${key}`) || x.name.endsWith(`'s ${key}`));
130
+ return { unit: 'mm', predicted: r?.value ?? fit.kit, was: r ? `${r.name}, ${r.kind}` : fit.was, source: HOLDS_COUPON, measuredRule: fit.rule,
131
+ check: (x) => (x < fit.range[0] || x > fit.range[1] || (fit.above && x === 0) ? `is ${fit.above ? 'above' : 'from'} ${fit.range[0]}${fit.above ? ' and up' : ''} to ${fit.range[1]} mm: ${fit.why}` : null) };
132
+ }
121
133
  if (key === 'thread_flank') { const t = f().threadModel('M8', { length: f().holeModel('M8', { kind: 'thread' }).depth, internal: true }); return { unit: '°', predicted: t.overhang.drawn, was: 'flanks: printed, the default', source: COUPON, allowed: [t.overhang.drawn, t.overhang.standard],
122
134
  rule: `The down-facing flank of a printed thread standing upright, as an overhang from upright: ${t.overhang.drawn} is the form laid back to the printer's overhang (flanks: 'printed', the kit's default), ${t.overhang.standard} the standard's own form (flanks: 'standard'). The one on ${COUPON} that held, turned smoothly and printed clean. A record for choosing the default: designs still draw flanks: 'printed' unless they say otherwise` }; }
123
135
  return null;
124
136
  }
137
+ // The holds coupon's fits: the rule each writes once measured, what bounds it, and the model that draws from it
138
+ const HOLDS_COUPON = 'the holds coupon (examples/bench/projects/benchmarks/MEASURE.md)';
139
+ const HOLDS = {
140
+ snap_clearance: { range: [0, 0.5], above: true, model: (f) => f.pinModel('snap pin 4x6'), why: 'its gap is drawn with no hole compensation, so at 0 the printed socket comes out smaller than the peg and pinches it: a press, not a snap. Past half a millimetre a pin rocks; the coupon prints 0.1 to 0.3, and never a socket at 0',
141
+ rule: `Gap round a printed snap pin's peg in its socket, each side, as drawn (no hole compensation): the socket on ${HOLDS_COUPON} a snap pin clicked through by hand and then held without rocking` },
142
+ pin_press: { range: [0, 0.3], model: (f) => f.pinModel('dowel 3x12', { fit: 'press' }), why: 'how much smaller a hole is drawn than the pin it grips, past hole_comp, and more than 0.3 mm splits a printed boss; the coupon prints 0 to 0.1',
143
+ rule: `How much smaller across a printed hole is drawn than a plain pin pressed into it, past hole_comp: the hole on ${HOLDS_COUPON} a 3 mm dowel (or 1.75 mm filament) pressed into by hand or in a vice, stood straight, and could not be pulled out by hand` },
144
+ pin_slip: { range: [0, 0.6], model: (f) => f.pinModel('dowel 3x12', { fit: 'slip' }), why: 'how much larger a hole is drawn than the pin that turns in it, past hole_comp, and past 0.6 mm it is a loose hole. At 0 the hole is the pin and hole_comp, the pin\'s own size once printed: a close slip; the coupon prints 0.1 to 0.3, and 0 once it is centred on 0.1',
145
+ rule: `How much larger across a printed hole is drawn than a plain pin that turns in it, past hole_comp: the tightest hole on ${HOLDS_COUPON} a 3 mm dowel (or 1.75 mm filament) slid into by hand and turned freely in` },
146
+ magnet_press: { range: [0, 0.4], model: (f) => f.magnetSeatModel('disc magnet 8x3', { fit: 'press' }), why: 'how much smaller a pocket is drawn than the magnet it grips, past hole_comp, and more than 0.4 mm splits its wall; the coupon prints 0 to 0.2',
147
+ rule: `How much smaller across a printed pocket is drawn than a disc magnet pressed into it, past hole_comp: the pocket on ${HOLDS_COUPON} a 6x3 and an 8x3 magnet went into with a thumb or a vice, flush, without splitting the wall, and stayed in when the plate was turned over and tapped` },
148
+ magnet_glue: { range: [0, 0.6], model: (f) => f.magnetSeatModel('disc magnet 8x3', { fit: 'glue' }), why: 'room for a film of glue across the pocket, past hole_comp, and past 0.6 mm the magnet sits off centre; the coupon\'s press row shows where a magnet drops in',
149
+ rule: `How much larger across a printed pocket is drawn than a magnet glued into it, past hole_comp: the least on ${HOLDS_COUPON} a magnet dropped into freely, which leaves room for glue` },
150
+ magnet_crush: { range: [0, 0.6], model: (f) => f.magnetSeatModel('disc magnet 8x3', { fit: 'ribs' }), why: 'how far inside the magnet the crush ribs\' tips stand, past hole_comp, and past 0.6 mm a rib no longer crushes but splits. At 0 the ribs\' tips stand at the magnet and hole_comp, a light crush once printed; the coupon prints 0.1 to 0.3, and 0 once it is centred on 0.1',
151
+ rule: `With crush ribs, how much smaller across the ribs' tips stand than the magnet, past hole_comp: the ribbed pocket on ${HOLDS_COUPON} an 8x3 magnet pressed into by hand, flush, and held when the plate was turned over and tapped` },
152
+ snap_barb: { range: [0, 1], above: true, kit: 0.4, was: 'barb 0.4, the default', model: () => ({ rests: [] }), why: 'a snap pin\'s barb past its peg, and past a millimetre the halves cannot close enough to let it through; the coupon prints 0.3 to 0.5',
153
+ rule: `A snap pin's barb past its peg: the one on ${HOLDS_COUPON} that clicked through its socket by hand and held when pulled. A record for choosing the default: pins are still drawn with a 0.4 mm barb unless their name says barb N` }
154
+ };
155
+
156
+ // The pull bolt on the holds coupon (row 46): an M8 printed bolt whose waist breaks across its layers, so it measures
157
+ // how strongly a plastic holds across its layers, which PLA's data sheet does not give. It goes in the plastic's set
158
+ // as strength_z, which a printed bolt standing on its head, and every part pulled across its layers, then reads
159
+ function boltRule(set, key, data) {
160
+ if (key !== 'strength_z' || data.rules?.density == null || typeof data.rules?.strength?.value !== 'number') return null;
161
+ const along = data.rules.strength.value, z = data.rules.strength_z;
162
+ return { unit: 'MPa', predicted: z?.value ?? along, was: z ? `${set}.strength_z, ${z.kind}` : `${set}.strength, along the layers: no figure across them`, source: `${HOLDS_COUPON}, the pull bolt broken on a luggage scale`,
163
+ measuredRule: `Tensile strength of ${set.toUpperCase()} across its printed layers: the pull bolt on ${HOLDS_COUPON}, printed standing, broken on a luggage scale at its 3.5 mm waist (the kilograms × 9.81 over 9.62 mm²). A printed bolt standing on its head, and any part pulled across its layers, takes it before the along-layer strength`,
164
+ check: (x) => (!(x > 0) || x > along ? `is above 0 and no more than ${set}.strength, ${along} MPa: a print holds less across its layers than along them, so read the scale's peak again, and work it as kilograms × 9.81 over the waist's 9.62 mm²` : null) };
165
+ }
125
166
  const printerName = (project) => { try { return fixingsContext({ project, dir: paths.project(project) }).context.printer?.name ?? 'x1c'; } catch { return 'x1c'; } };
126
167
  // A rule the workspace's copy lacks and the kit's own set of that name holds (a set copied before the rule was added)
127
168
  function kitRule(set, key) { try { return JSON.parse(fs.readFileSync(path.join(RULE_DIRS.at(-1), `${set}.json`), 'utf8')).rules?.[key] ?? null; } catch { return null; } }
@@ -142,8 +183,10 @@ export async function recordMeasured(ref, values, { unit, source, rule, date = t
142
183
  // a rule's new value, checked before anything is written (a refusal leaves the rule sets as they were)
143
184
  const writeRule = (k, value, { from = null, unit: u = unit } = {}) => {
144
185
  const { set, rule: key, data, file, text, copied } = ruleFile(k);
145
- const old = data.rules?.[key], known = slotRule(project, set, key, data) ?? rigRule(set, key, data) ?? couponRule(set, key, data) ?? fixingsRule(project, set, key) ?? (old ? null : kitRule(set, key));
186
+ const old = data.rules?.[key], known = slotRule(project, set, key, data) ?? rigRule(set, key, data) ?? couponRule(set, key, data) ?? boltRule(set, key, data) ?? fixingsRule(project, set, key) ?? (old ? null : kitRule(set, key));
146
187
  if (known?.allowed && !known.allowed.includes(value)) throw new CadError('measured.value', `${k} is ${known.allowed.join(' or ')}: the flank forms the coupon prints (got ${value})`);
188
+ const wrong = known?.check?.(value);
189
+ if (wrong) throw new CadError('measured.value', `${k} ${wrong} (got ${value})`);
147
190
  if (!old && !rule && !known) throw new CadError('measured.rule', `${set} has no rule "${key}" (and no check here predicts "${k}"): --rule "what it is" to add it (checks: ${[...new Set(predictions.map((x) => x.code))].join(', ') || 'none'})`);
148
191
  const had = old ?? known, prior = typeof had?.value === 'number' ? had.value : known?.predicted ?? null;
149
192
  if (u && had?.unit && u !== had.unit) throw new CadError('measured.unit', `${k} is in ${had.unit}, and this is in ${u}: give it in ${had.unit}`);
package/lib/pins.mjs ADDED
@@ -0,0 +1,123 @@
1
+ // Pins in an assembly: a fit whose "fastener" names pins, { "pin": "snap pin 4x6", "count": 2, "load": 40 }, is
2
+ // checked as a screwed joint is, from the parts as drawn. The pins' holes are found in part a (round holes about the
3
+ // pin's size whose axis goes on into part b), each followed through a and into b: the hole in each part is held to the
4
+ // one @rulecad/fixings' pinModel draws for the pin and the project's printer (fit.pin), the length the pin has room
5
+ // for to its length (a pin too long for its part is refused by name), and the load the fit gives, shared by its pins,
6
+ // to what each pin and its printed hole carry. The pins go on the shopping list (lib/list.mjs) and the build step
7
+ // (lib/order.mjs) by their names.
8
+ import { jscad } from './design.mjs';
9
+ import { profile, holesIn, fixingsOf, FASTEN } from './fasten.mjs';
10
+ import { magnetOfFit } from './magnets.mjs';
11
+
12
+ export { magnetFit } from './magnets.mjs';
13
+
14
+ const { vec3 } = jscad.maths;
15
+
16
+ const mm = (n) => String(Number(Number(n).toFixed(3))), r3 = (x) => +x.toFixed(3);
17
+ const unit = (v) => { const l = Math.hypot(...v); return v.map((c) => c / l); };
18
+ const top = (n) => String(n).split(/[.@]/)[0];
19
+ /** How far a hole as drawn may be from the pin's hole and still be taken for it (mm across): fasten's own tolerance, at most. */
20
+ const TOL = FASTEN.size.value;
21
+ /**
22
+ * The tolerance for one of a pin's holes: fasten's, or half the least step from that hole to the pin's bare diameter
23
+ * or to another of its holes where that is less, so a hole drawn at the bare diameter (no hole_comp) is never taken
24
+ * for a press hole only x1c.pin_press (0.05 mm) away from it.
25
+ * @param {number} d the hole's diameter @param {number[]} others the pin's bare diameter and its other holes' @returns {number} mm across
26
+ */
27
+ const tolOf = (d, others) => Math.min(TOL, ...others.map((o) => Math.abs(o - d) / 2).filter((g) => g > 1e-9));
28
+ /** How far off the pin's hole a round hole may be and still be looked at as one of its places, mm across. */
29
+ const LOOK = 0.6;
30
+ /** What a fit's pins may say: the assembly schema's $defs.pins. */
31
+ const PIN_KEYS = ['pin', 'count', 'fit', 'load', 'pull'];
32
+
33
+ /**
34
+ * A fit's fastener as the assembly reads it: a name in words ("Two push pins"), kept as it is, or pins by the schema's
35
+ * form ({ pin, count, load, fit }), which become the fit's pin and its fastener's name, or magnets ({ magnet, count,
36
+ * load }: lib/magnets.mjs). Pins fasten the two parts (fastens: true) unless the fit says otherwise.
37
+ * @param {object} x a fit as written @param {string} [project] the project, for its printer (magnets) @returns {object} the fit, with pin and a fastener's name where it names pins
38
+ */
39
+ export function pinOfFit(x, project) {
40
+ if (!x.fastener || typeof x.fastener !== 'object') return x;
41
+ if ('magnet' in x.fastener) return magnetOfFit(x, fixingsOf(project).F); // (magnets: lib/magnets.mjs)
42
+ const p = x.fastener, label = x.note || x.label || `${x.a} / ${x.b}`;
43
+ if (typeof p.pin !== 'string' || !p.pin.trim()) throw new Error(`fit ${label}: fastener as an object names pins: { "pin": "snap pin 4x6", "count": 2 } (got ${JSON.stringify(p)})`);
44
+ const stray = Object.keys(p).filter((k) => !PIN_KEYS.includes(k));
45
+ if (stray.length) throw new Error(`fit ${label}: pins have no "${stray.join('", "')}": a fastener naming pins takes ${PIN_KEYS.join(', ')} (the assembly schema's pins)`);
46
+ if (x.count != null && p.count != null) throw new Error(`fit ${label}: give the pins' count once, in the fastener ({ "pin": ..., "count": 2 })`);
47
+ return { fastens: true, ...x, pin: p, fastener: p.pin.trim(), ...(p.count != null || x.count != null ? { count: p.count ?? x.count } : {}) };
48
+ }
49
+
50
+ /**
51
+ * fit.pin: the pins a fit names, found in the parts as drawn and checked against their models.
52
+ * @param {object} x the fit, with pin (pinOfFit) @param {object} s the built assembly @param {Function} f the findings' sink, as checkAssembly's
53
+ */
54
+ export function pinFit(x, s, f) {
55
+ const label = x.note || x.label || `${x.a} to ${x.b}`, code = 'fit.pin', p = x.pin, refs = { a: x.a, b: x.b, pin: x.fastener };
56
+ const fail = (text, short, more = {}) => f('fail', `${label}: ${text}`, short ?? `${label}: pins`, { code, refs, ...more });
57
+ const { F, material } = fixingsOf(s.project);
58
+ const count = x.count != null ? x.num(x.count) : 1, load = p.load != null ? x.num(p.load) : null;
59
+ if (!(Number.isInteger(count) && count >= 1)) return fail(`count is how many pins, a whole number from 1 (got ${count})`);
60
+ let m0;
61
+ try { m0 = F.pinModel(x.fastener, { material, ...(p.fit ? { fit: p.fit } : {}) }); } catch (e) { return fail(e.message.replace(/^pinModel: /, '')); }
62
+ const named = (q, n) => q.name === n || q.leaf === n || q.item === n || q.name.startsWith(`${n}.`);
63
+ const A = s.parts.filter((q) => !q.hardware && named(q, top(x.a))), B = s.parts.filter((q) => !q.hardware && named(q, top(x.b)));
64
+ if (!A.length || !B.length) return fail(`no part "${A.length ? x.b : x.a}"`, `${label}: no part`);
65
+ const R = m0.diameter + 2, wanted = plainHoles(F, x.fastener, material, m0, p.fit);
66
+ // A part measured along a world axis: where its material and its holes lie along it, and the holes' size
67
+ const run = (parts, O, D) => {
68
+ const segs = parts.flatMap((q) => profile(q.triangles, O, D, R).segs).filter((g) => g.solid || g.hole).sort((a, b) => a.z0 - b.z0);
69
+ if (!segs.length) return null;
70
+ const holes = segs.filter((g) => g.hole), size = (g) => (g.a.loop?.shape === 'round' && g.a.loop.d != null ? Math.min(g.a.loop.d, g.b.loop?.d ?? Infinity) : 2 * Math.min(g.a.free, g.b.free));
71
+ return { lo: segs[0].z0, hi: segs.at(-1).z1, segs, hole: holes.length ? Math.min(...holes.map(size)) : null, solidAt: segs.find((g) => g.solid) ?? null };
72
+ };
73
+ // The pins' places: round holes in a about the pin's hole, standing on an axis that goes on into b
74
+ const axes = [];
75
+ for (const q of A) for (const h of holesIn(q)) {
76
+ if (Math.abs(h.d - m0.hole.diameter) > LOOK && !wanted.some((w) => Math.abs(h.d - w.diameter) <= LOOK)) continue;
77
+ const O = q.m ? vec3.transform([0, 0, 0], h.at, q.m) : h.at, e = q.m ? vec3.transform([0, 0, 0], h.at.map((c, i) => c + h.axis[i]), q.m) : h.at.map((c, i) => c + h.axis[i]), D = unit(e.map((c, i) => c - O[i]));
78
+ const a = run(A, O, D), b = run(B, O, D);
79
+ if (!a || !b) continue;
80
+ const flip = (a.lo + a.hi) / 2 > (b.lo + b.hi) / 2; // (along from a into b)
81
+ const Df = flip ? D.map((c) => -c) : D;
82
+ axes.push({ at: O.map(r3), D: Df, a: flip ? run(A, O, Df) : a, b: flip ? run(B, O, Df) : b });
83
+ }
84
+ if (axes.length < count) return fail(`${count} × ${m0.name} wanted, and ${axes.length ? `only ${axes.length} hole${axes.length > 1 ? 's' : ''} about its ${mm(m0.hole.diameter)} mm hole ${axes.length > 1 ? 'lead' : 'leads'}` : `no hole about its ${mm(m0.hole.diameter)} mm hole leads`} from ${x.a} into ${x.b}: draw the holes with v.fixings.pinHole`, `${label}: holes missing`, { values: { count, found: axes.length } });
85
+ let bad = 0;
86
+ const worst = { margin: Infinity, m: null };
87
+ for (const [i, ax] of axes.entries()) {
88
+ const where = `pin ${i + 1} at ${ax.at.map(mm).join(', ')}`, at = ax.at;
89
+ // the holes: each part's held to the pin's
90
+ for (const [part, r] of [[x.a, ax.a], [x.b, ax.b]]) {
91
+ const d = r.hole;
92
+ if (d == null) { bad++; fail(`${where}: ${part} is solid on the pin's axis: it has no hole there for ${m0.name}`, `${label}: no hole in ${part}`, { at, values: { part } }); continue; }
93
+ const hit = wanted.find((w) => Math.abs(d - w.diameter) <= w.tol);
94
+ if (hit) continue;
95
+ const w = m0.snap ? m0.hole : wanted.find((v) => v.fit === (p.fit ?? 'press')), small = d < Math.min(...(m0.snap ? [m0.hole.diameter] : wanted.map((v) => v.diameter)));
96
+ bad++; fail(`${where}: ${part}'s hole is drawn ${mm(r3(d))} mm, and ${m0.name} wants ${m0.snap ? `${mm(m0.hole.diameter)} mm (${m0.hole.rules.join(' and ')})` : wanted.map((v) => `${mm(v.diameter)} mm for a ${v.fit} fit (${v.rule})`).join(' or ')}: ${small ? 'too small, it will not go in' : 'too big, it will be loose'}`,
97
+ `${label}: hole ${small ? 'small' : 'big'} in ${part}`, { at, values: { part, drawn: r3(d), wanted: w.diameter } });
98
+ }
99
+ // the length: the room from a's outer face to where b closes (a blind hole's floor) or ends
100
+ const end = ax.b.solidAt ? ax.b.solidAt.z0 : ax.b.hi, room = r3(end - ax.a.lo);
101
+ if (m0.snap && ax.b.solidAt) { bad++; fail(`${where}: ${x.b}'s hole is blind ${mm(r3(ax.b.solidAt.z0 - ax.b.lo))} mm deep: a snap pin's barb clicks out past the far face, so its socket goes through`, `${label}: socket blind`, { at }); continue; }
102
+ const grip = r3(Math.max(0.1, Math.min(ax.a.hi - ax.a.lo, end - ax.b.lo)));
103
+ let m;
104
+ try { m = F.pinModel(x.fastener, { material, thickness: room, grip, ...(p.fit ? { fit: p.fit } : {}), ...(load != null ? { load: load / count } : {}), ...(p.pull != null ? { pull: x.num(p.pull) / count } : {}) }); }
105
+ catch (e) { bad++; fail(`${where} in ${x.a} and ${x.b}: ${e.message.replace(/^pinModel: /, '')}`, `${label}: ${/too long/.test(e.message) ? 'pin too long' : /too short/.test(e.message) ? 'pin too short' : 'pin'}`, { at, values: { length: m0.length, room } }); continue; }
106
+ const s1 = m.findings.find((g) => g.code === 'pin.strength');
107
+ if (m.margin != null && m.margin < worst.margin) Object.assign(worst, { margin: m.margin, m, s1, where });
108
+ if (load == null && i === 0) worst.s1 ??= s1;
109
+ }
110
+ if (bad) return;
111
+ const say = m0.snap ? `in sockets drawn ${mm(m0.hole.diameter)} mm (${m0.hole.rules.join(', ')})` : `in holes drawn to ${wanted.map((v) => `${v.fit} ${mm(v.diameter)} mm`).join(' or ')}`;
112
+ f('pass', `${label}: ${count} × ${m0.name} ${say}, each the right length for ${x.a} and ${x.b}`, null, { code, refs, values: { count, hole: m0.hole.diameter, grams: m0.grams } });
113
+ if (worst.m) f(worst.s1.level, `${label}: ${worst.where}: ${worst.s1.text}`, worst.s1.level === 'pass' ? null : `${label}: pins weak`, { code: 'fit.pin.load', refs, values: worst.s1.values });
114
+ else if (worst.s1) f('info', `${label}: ${worst.s1.text}`, null, { code: 'fit.pin.load', refs, values: worst.s1.values });
115
+ }
116
+ // The holes a plain pin may sit in: press and slip, or the one fit asked; a snap pin's is its socket's. Each carries
117
+ // the tolerance it is matched to (tolOf)
118
+ function plainHoles(F, name, material, m0, fit) {
119
+ const all = m0.snap ? [{ fit: 'snap', diameter: m0.hole.diameter, rule: m0.hole.rules.join(', ') }]
120
+ : ['press', 'slip'].map((k) => { const h = F.pinModel(name, { material, fit: k }).hole; return { fit: k, diameter: h.diameter, rule: h.rules.join(', ') }; });
121
+ // each hole's tolerance from its step to the pin's bare diameter and to the other fit's hole, whichever fit is asked
122
+ return all.map((w) => ({ ...w, tol: tolOf(w.diameter, [m0.diameter, ...all.filter((o) => o !== w).map((o) => o.diameter)]) })).filter((w) => !fit || m0.snap || w.fit === fit);
123
+ }
package/lib/preview.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  // preview(parts, { title, meta, out, explode }) -> out: a 1800 × 1200 PNG of six views (front, side, 3/4, top, bottom, 3/4 below),
2
- // parts: [{ name, role, label, item, triangles }]; supports and references are drawn faint (lines only); explode drops
2
+ // parts: [{ name, role, label, item, triangles }]; supports and references are drawn faint (lines only), but references
3
+ // solid with built (an assembly with show: built); explode drops
3
4
  // supports below and, in an assembly, lifts each kind of object above the one before (plate, switches, keycaps); a part
4
5
  // with `lift` (a screw, a nut: lib/fasten.mjs) goes with the part it sits in (`with`) and then out along its own axis.
5
6
  // rendered by headless Chrome from lib/preview/page.html, served on this Mac only for the few seconds it takes.
@@ -19,9 +20,9 @@ const CHROME = process.env.CAD_CHROME || [
19
20
  ].find((f) => fs.existsSync(f));
20
21
  const THREE = path.dirname(createRequire(import.meta.url).resolve('three')); // wherever npm put it
21
22
 
22
- export async function preview(parts, { title = '', meta = '', out, explode = false, marks = null }) {
23
+ export async function preview(parts, { title = '', meta = '', out, explode = false, marks = null, built = false }) {
23
24
  const flat = (tris) => { const positions = []; for (const t of tris) for (let i = 1; i < t.length - 1; i++) positions.push(...t[0], ...t[i], ...t[i + 1]); return positions; };
24
- const data = JSON.stringify({ title, meta, explode, marks, parts: parts.map((p) => ({ name: p.name, role: p.role, label: p.label, item: p.object || p.item, ...(p.lift ? { lift: p.lift, with: p.with } : {}), positions: flat(p.triangles) })) });
25
+ const data = JSON.stringify({ title, meta, explode, marks, parts: parts.map((p) => ({ name: p.name, role: built && p.role === 'reference' ? 'part' : p.role, label: p.label, item: p.object || p.item, ...(p.lift ? { lift: p.lift, with: p.with } : {}), positions: flat(p.triangles) })) });
25
26
  const server = http.createServer((req, res) => {
26
27
  const u = new URL(req.url, 'http://x').pathname;
27
28
  const send = (type, body) => { res.writeHead(200, { 'Content-Type': type }); res.end(body); };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.58",
3
+ "version": "0.7.60",
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": {
@@ -65,17 +65,17 @@
65
65
  "@rulecad/model-link": "^0.3.2",
66
66
  "@rulecad/versions": "^0.1.6",
67
67
  "@rulecad/shapes": "^0.4.5",
68
- "@rulecad/rules": "^0.3.17",
68
+ "@rulecad/rules": "^0.3.19",
69
69
  "@jscad/modeling": "^2.12.0",
70
70
  "three": "^0.186.1",
71
71
  "@rulecad/fea": "^0.2.11",
72
72
  "@rulecad/topopt": "^0.3.0",
73
- "@rulecad/flexures": "^0.5.0",
73
+ "@rulecad/flexures": "^0.5.3",
74
74
  "@rulecad/gears": "^0.3.2",
75
75
  "@rulecad/motors": "^0.1.6",
76
- "@rulecad/fixings": "^0.1.4",
76
+ "@rulecad/fixings": "^0.1.5",
77
77
  "@rulecad/robots": "^0.1.2",
78
- "@rulecad/frames": "^0.1.9"
78
+ "@rulecad/frames": "^0.1.10"
79
79
  },
80
80
  "peerDependencies": {
81
81
  "@rulecad/pcb": "^0.1.0 || ^0.2.0 || ^0.3.0 || ^0.4.0 || ^0.5.0"
@@ -11,6 +11,7 @@
11
11
  "title": { "type": "string" },
12
12
  "description": { "type": "string" },
13
13
  "note": { "type": "string" },
14
+ "show": { "enum": ["built"], "description": "built: the assembly is a picture of the thing built, so its references (bought parts, boards, a module) are drawn solid in previews and on the model page, as its printed parts are; they still aren't printed or downloaded" },
14
15
  "kind": { "enum": ["fit", "plate"] },
15
16
  "packed": { "type": "object", "description": "Written by cad plates: which assembly this plate is for, its filament, its material (each plate is one plastic: the project's, or a printed beam's own) and gap, and each part's build hash, so a changed part re-packs only its plate", "required": ["of", "filament", "gap", "parts"], "additionalProperties": false, "properties": { "of": { "type": "string" }, "filament": { "type": "string" }, "material": { "type": "string" }, "gap": { "type": "number" }, "parts": { "type": "object" } } },
16
17
  "uses": { "type": "array", "items": { "type": "string" } },
@@ -88,7 +89,7 @@
88
89
  "shaft": { "anyOf": [{ "type": "boolean" }, { "enum": ["slide", "press"] }], "description": "a or b is a motor, and the other takes its shaft: reads the bore from the part as drawn" },
89
90
  "seat": { "anyOf": [{ "type": "boolean" }, { "enum": ["press", "slip"] }, { "type": "number" }], "description": "a or b is a bought bearing, and the other its printed seat: reads the pocket as drawn against the bearing's rules and the printer's fit (fit.seat)" },
90
91
  "fastens": { "type": "boolean", "description": "a and b are fastened together (pins, a press, a clip): what holds a part that has no joint. Where screws hold them, use a fasten instead: it knows the screw, checks its holes and lists it" },
91
- "fastener": { "type": "string", "description": "What does the fastening, by hand (two push pins): named on the shopping list and the assembly step. A screw is a fasten's, which chooses its length and counts it" },
92
+ "fastener": { "description": "What does the fastening: in words (two push pins), named on the shopping list and the assembly step as written; or pins, { \"pin\": \"snap pin 4x6\", \"count\": 2 }, found in the parts' holes and checked (fit.pin): each hole against the one @rulecad/fixings draws for the pin and the printer, the pin's length against the parts, and the load; or magnets, { \"magnet\": \"disc magnet 8x3\", \"count\": 2 }, found in the parts' pockets and checked (fit.magnet): each pocket against the one @rulecad/fixings draws for the magnet and the printer, its depth and floor, and their pull against the load. A screw is a fasten's, which chooses its length and counts it", "anyOf": [{ "$ref": "#/$defs/pins" }, { "$ref": "#/$defs/magnets" }, { "type": "string" }] },
92
93
  "count": { "$ref": "#/$defs/expr", "description": "With fastener: how many" },
93
94
  "access": { "type": "string", "description": "<item>.<anchor>: where the screw's tool comes from, its z axis pointing out along the screw. Whatever stands on that line goes on after the screw; if nothing can, assembly.order says so" },
94
95
  "min": { "$ref": "#/$defs/expr" },
@@ -104,6 +105,18 @@
104
105
  "within": { "$ref": "#/$defs/expr", "description": "With an anchor name (item@anchor): only faces this close to it (mm, default 10)" }
105
106
  }
106
107
  },
108
+ "pins": { "type": "object", "required": ["pin"], "additionalProperties": false, "description": "Pins that hold a fit's two parts together: found in round holes of part a that go on into part b", "properties": {
109
+ "pin": { "type": "string", "description": "A pin by name, as @rulecad/fixings reads it: snap pin 4x6 (a printed snap pin, 4 mm peg, 6 mm shaft; barb 0.6 after it for another barb), dowel 3x12 (a steel ISO 8734 dowel; ISO 2338 after it for an unhardened one), filament pin 1.75x12, printed pin 4x10" },
110
+ "count": { "$ref": "#/$defs/expr", "description": "How many (default 1): that many holes must be found" },
111
+ "fit": { "enum": ["press", "slip"], "description": "A plain pin's fit in its holes: press (it grips) or slip (it turns). Left out, each hole may be either" },
112
+ "load": { "$ref": "#/$defs/expr", "description": "N across the joint, shared by the pins: each pin's shear and its hole's bearing are held to it with about twice the margin" },
113
+ "pull": { "$ref": "#/$defs/expr", "description": "N along the pins, shared by them: what snap pins must hold before they let go" } } },
114
+ "magnets": { "type": "object", "required": ["magnet"], "additionalProperties": false, "description": "Magnets that hold a fit's two parts together: found in round pockets of part a or part b", "properties": {
115
+ "magnet": { "type": "string", "description": "A magnet by name, as @rulecad/fixings reads it: disc magnet 8x3 (8 mm across, 3 mm thick, N35 unless a grade follows: disc magnet 8x3 N52), block magnet 10x5x2" },
116
+ "count": { "$ref": "#/$defs/expr", "description": "How many (default 1): that many pockets must be found" },
117
+ "fit": { "enum": ["press", "glue", "ribs"], "description": "How each sits in its pocket: pressed, glued, or held by crush ribs. Left out, each pocket may be any of them" },
118
+ "load": { "$ref": "#/$defs/expr", "description": "N pulling the parts apart, shared by the magnets: their pull is held to it with about twice the margin" },
119
+ "gap": { "$ref": "#/$defs/expr", "description": "mm between each magnet and what it pulls on, when the parts are together (paint, a skin, air): its pull falls across it" } } },
107
120
  "beamAddress": { "type": "string", "pattern": "^([ab](\\.\\d+)?|(top|bottom|front|back)(\\.\\d+)?(@-?\\d+(\\.\\d+)?%?)?)$", "description": "An address on a beam, without its item: an end (a, b), an end's bore (a.1), or a face's place with a distance from end a (top@120), from end b (top@-20) or a share of the length (top@50%), the second place of a face top.2@120" },
108
121
  "beamOp": { "type": "object", "required": ["op", "at"], "additionalProperties": false, "description": "An operation on a beam (@rulecad/frames OPS): each takes only its own keys, and is refused by name otherwise", "properties": {
109
122
  "op": { "enum": ["cut", "mitre", "tap", "access", "drill", "counterbore", "pocket", "notch", "deburr"], "description": "cut: square to length; mitre: an end at an angle about a named face; tap: a thread in an end bore; access: a hole across, in line with a slot, for a key; drill: through one wall or right through, plain or tapped; counterbore: a seat for a head; pocket: milled by outline; notch: a slot's lips cut away; deburr: named so the sheet asks for it" },