@rulecad/cad 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/AGENTS.md +45 -16
  2. package/CHANGELOG.md +724 -0
  3. package/EXAMPLES.md +61 -54
  4. package/README.md +376 -98
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2664 -541
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1883 -435
  9. package/lib/beams.mjs +256 -52
  10. package/lib/belts.mjs +66 -15
  11. package/lib/board-work.mjs +12 -0
  12. package/lib/bought.mjs +309 -53
  13. package/lib/buildpage.mjs +179 -29
  14. package/lib/cache-file.mjs +105 -0
  15. package/lib/carried.mjs +201 -0
  16. package/lib/clone.mjs +194 -42
  17. package/lib/code-text.mjs +28 -0
  18. package/lib/design-imports.mjs +127 -0
  19. package/lib/design.mjs +871 -147
  20. package/lib/designshapes.mjs +142 -0
  21. package/lib/drive.mjs +187 -63
  22. package/lib/edit.mjs +922 -192
  23. package/lib/errors.mjs +16 -3
  24. package/lib/estimates.mjs +51 -0
  25. package/lib/explain.mjs +62 -13
  26. package/lib/fasten.mjs +2708 -507
  27. package/lib/fe-key.mjs +29 -0
  28. package/lib/fittings.mjs +721 -122
  29. package/lib/fixings.mjs +38 -13
  30. package/lib/framebuild.mjs +790 -175
  31. package/lib/framecheck.mjs +1901 -368
  32. package/lib/framegen.mjs +108 -22
  33. package/lib/frameheat.mjs +225 -42
  34. package/lib/frameprint.mjs +513 -108
  35. package/lib/frames.mjs +86 -18
  36. package/lib/framesize.mjs +719 -120
  37. package/lib/frametip.mjs +235 -0
  38. package/lib/gait.mjs +135 -23
  39. package/lib/grip.mjs +62 -13
  40. package/lib/guides.mjs +1403 -230
  41. package/lib/host.mjs +129 -23
  42. package/lib/inplace.mjs +171 -36
  43. package/lib/jigs.mjs +360 -78
  44. package/lib/joins.mjs +697 -118
  45. package/lib/jsonedit.mjs +88 -26
  46. package/lib/kept.mjs +84 -0
  47. package/lib/kit.mjs +439 -69
  48. package/lib/layout.mjs +2 -1
  49. package/lib/links.mjs +149 -42
  50. package/lib/list.mjs +334 -64
  51. package/lib/live-guard.mjs +68 -0
  52. package/lib/live-shape.mjs +96 -24
  53. package/lib/live.mjs +189 -59
  54. package/lib/loads.mjs +597 -136
  55. package/lib/machine.mjs +372 -74
  56. package/lib/magnets.mjs +162 -44
  57. package/lib/measured.mjs +1080 -117
  58. package/lib/mesh.mjs +526 -119
  59. package/lib/meshcmd.mjs +215 -60
  60. package/lib/motors.mjs +1002 -214
  61. package/lib/motorsvg.mjs +114 -32
  62. package/lib/names.mjs +18 -1
  63. package/lib/optimise.mjs +991 -287
  64. package/lib/order.mjs +515 -114
  65. package/lib/panels.mjs +482 -94
  66. package/lib/parts.mjs +81 -23
  67. package/lib/pins.mjs +163 -44
  68. package/lib/plates.mjs +223 -35
  69. package/lib/player.mjs +37 -9
  70. package/lib/power.mjs +64 -13
  71. package/lib/preview.mjs +83 -16
  72. package/lib/profilemeasure.mjs +572 -129
  73. package/lib/rules.mjs +17 -6
  74. package/lib/sandbox-hooks.mjs +179 -27
  75. package/lib/sandbox-lock.mjs +225 -0
  76. package/lib/sandbox-preload.mjs +2 -2
  77. package/lib/sandbox-run.mjs +122 -25
  78. package/lib/sandbox.mjs +667 -75
  79. package/lib/schema.mjs +42 -11
  80. package/lib/seats.mjs +227 -49
  81. package/lib/services.mjs +261 -52
  82. package/lib/sheet.mjs +963 -179
  83. package/lib/slotnuts.mjs +213 -34
  84. package/lib/targets/gist.mjs +4 -1
  85. package/lib/targets.mjs +22 -4
  86. package/lib/task.mjs +376 -79
  87. package/lib/versions.mjs +285 -39
  88. package/lib/wires.mjs +228 -45
  89. package/lib/workspace.mjs +200 -14
  90. package/package.json +19 -19
  91. package/schemas/assembly.schema.json +2 -2
  92. package/schemas/project.schema.json +6 -0
  93. package/templates/coupons/MEASURE.md +109 -0
  94. package/templates/coupons/assemblies/fixings-test.json +20 -0
  95. package/templates/coupons/assemblies/slot-test.json +11 -0
  96. package/templates/coupons/objects/fixings-coupon.js +88 -0
  97. package/templates/coupons/objects/fixings-coupon.json +26 -0
  98. package/templates/coupons/objects/holds-coupon.js +130 -0
  99. package/templates/coupons/objects/holds-coupon.json +42 -0
  100. package/templates/coupons/objects/slot-coupon.js +89 -0
  101. package/templates/coupons/objects/slot-coupon.json +29 -0
  102. package/templates/coupons/project.json +10 -0
package/lib/sheet.mjs CHANGED
@@ -7,49 +7,208 @@ import path from 'node:path';
7
7
  import zlib from 'node:zlib';
8
8
  import { fileURLToPath } from 'node:url';
9
9
  import { checkRuleSet } from '@rulecad/variables';
10
- import { profileModel, slotModel, slotPath, outline, section, profileFindings, slotNutModel, nutFit } from '@rulecad/frames';
10
+ import {
11
+ profileModel,
12
+ slotModel,
13
+ slotPath,
14
+ outline,
15
+ section,
16
+ profileFindings,
17
+ slotNutModel,
18
+ nutFit,
19
+ } from '@rulecad/frames';
11
20
  import { RULE_DIRS } from './workspace.mjs';
21
+ import { readJson } from './host.mjs';
12
22
  import { schema, validate } from './schema.mjs';
13
23
 
14
24
  const vocabularyFile = fileURLToPath(import.meta.resolve('@rulecad/rules/vocabulary.json'));
15
- const readSet = (f) => JSON.parse(fs.readFileSync(f, 'utf8'));
25
+ const readSet = (f) => readJson(f); // (a set linked in from outside the workspace is refused: host.mjs)
16
26
  export const vocabulary = () => readSet(vocabularyFile);
17
27
 
18
28
  // Every set by name, a workspace's own copy before the published one
19
29
  function allSets() {
20
30
  const found = new Map();
21
- for (const d of RULE_DIRS) if (fs.existsSync(d)) for (const f of fs.readdirSync(d).sort()) if (f.endsWith('.json') && !['package.json', 'vocabulary.json'].includes(f)) { const n = f.slice(0, -5); if (!found.has(n)) found.set(n, path.join(d, f)); }
31
+ for (const d of RULE_DIRS)
32
+ if (fs.existsSync(d))
33
+ for (const f of fs.readdirSync(d).sort())
34
+ if (f.endsWith('.json') && !['package.json', 'vocabulary.json'].includes(f)) {
35
+ const n = f.slice(0, -5);
36
+ if (!found.has(n)) found.set(n, path.join(d, f));
37
+ }
22
38
  return found;
23
39
  }
24
40
  function fileOf(name) {
25
- const all = allSets(), file = all.get(name);
41
+ const all = allSets(),
42
+ file = all.get(name);
26
43
  if (!file) throw new Error(`no rule set "${name}" (there are: ${[...all.keys()].join(', ')})`);
27
44
  return file;
28
45
  }
29
46
 
47
+ // A workspace's copy of a kit set beside the kit's own, rule by rule. cad copies a kit set into rules/ the first time
48
+ // a design uses it and reads only the copy from then on, so a figure the kit corrects later would never reach it. A
49
+ // rule of the copy is the kit's to replace when the copy's is not "measured" (a figure taken from the maker's own part
50
+ // beats any published one) and was checked before the kit's was (a figure checked on the same day or later is the
51
+ // maker's own word, kept). The same figure with only more said of it in the kit's (a range added, say) is the kit's to
52
+ // take too. What the kit has and the copy lacks is new; what the copy has and the kit lacks is its own.
53
+ const day = (r) => {
54
+ const d = String(r?.checked ?? '');
55
+ return /^\d{4}-\d{2}-\d{2}$/.test(d) ? d : '';
56
+ };
57
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
58
+ /**
59
+ * How a copy of a kit rule set stands against the kit's set.
60
+ * @param {{ rules?: Record<string, any> }} copy the workspace's copy
61
+ * @param {{ rules?: Record<string, any> }} kit the kit's set of the same name
62
+ * @returns {{ changed: string[], refreshed: string[], added: string[], measured: string[], newer: string[], own: string[] }}
63
+ * changed: a figure the kit has newer than the copy's (the kit's to take); refreshed: the same figure, its words or
64
+ * date newer in the kit, or more said of it there; added: the kit's rules the copy lacks; measured: the copy's
65
+ * measured figures that differ from the kit's; newer: the copy's figures that differ from the kit's and were checked
66
+ * on or after its date (or where neither says when); own: the copy's rules the kit has none of
67
+ */
68
+ export function kitDifference(copy, kit) {
69
+ const mine = copy?.rules && typeof copy.rules === 'object' ? copy.rules : {},
70
+ theirs = kit?.rules && typeof kit.rules === 'object' ? kit.rules : {},
71
+ out = { changed: [], refreshed: [], added: [], measured: [], newer: [], own: [] };
72
+ for (const [k, r] of Object.entries(theirs)) {
73
+ if (!(k in mine)) {
74
+ out.added.push(k);
75
+ continue;
76
+ }
77
+ const c = mine[k];
78
+ if (same(c, r)) continue;
79
+ const differs = !same(c?.value, r?.value);
80
+ if (c?.kind === 'measured') {
81
+ if (differs) out.measured.push(k);
82
+ } else if (day(r) && day(c) < day(r)) out[differs ? 'changed' : 'refreshed'].push(k);
83
+ else if (differs) out.newer.push(k);
84
+ else if (c && typeof c === 'object' && Object.entries(c).every(([f, x]) => same(x, r?.[f]))) out.refreshed.push(k); // (the kit's adds to the same figure: its range, say)
85
+ }
86
+ for (const k of Object.keys(mine)) if (!(k in theirs)) out.own.push(k);
87
+ return out;
88
+ }
89
+ /**
90
+ * The copy brought up to date with the kit's set: every rule in the kit's order, the kit's where kitDifference says
91
+ * it is the kit's to take (changed, refreshed or added), the copy's otherwise, then the copy's own rules. The set's
92
+ * other fields are the kit's, with any the copy alone has kept, and its "interface" both together.
93
+ * @param {Record<string, any>} copy
94
+ * @param {Record<string, any>} kit
95
+ * @returns {{ set: Record<string, any>, difference: ReturnType<typeof kitDifference> }}
96
+ */
97
+ export function updateFromKit(copy, kit) {
98
+ const difference = kitDifference(copy, kit),
99
+ take = new Set([...difference.changed, ...difference.refreshed, ...difference.added]),
100
+ rules = {};
101
+ for (const [k, r] of Object.entries(kit.rules || {})) rules[k] = take.has(k) ? r : copy.rules[k];
102
+ for (const k of difference.own) rules[k] = copy.rules[k];
103
+ const set = { ...copy, ...kit, rules };
104
+ if (copy.interface || kit.interface) set.interface = { ...copy.interface, ...kit.interface };
105
+ return { set, difference };
106
+ }
107
+ /**
108
+ * cad rules update's reading: the workspace's copy of a kit set and what bringing it up to date would make of it.
109
+ * Writes nothing. A name the kit has no set of is refused (that set is the workspace's alone); a workspace with no copy
110
+ * gets { file, copy: undefined }.
111
+ * @param {string} name a rule set's name, already held to plainName
112
+ * @returns {{ file: string, copy?: Record<string, any>, kit?: Record<string, any>, set?: Record<string, any>, difference?: ReturnType<typeof kitDifference>, fields?: string[] }}
113
+ * fields: the set's own fields (its _doc, its interface) the update changes
114
+ */
115
+ export function updateSet(name) {
116
+ const kitFile = path.join(RULE_DIRS.at(-1), `${name}.json`),
117
+ file = path.join(RULE_DIRS[0], `${name}.json`);
118
+ if (!fs.existsSync(kitFile))
119
+ throw new Error(
120
+ `the kit has no rule set "${name}", so there is nothing to update rules/${name}.json from: it is this workspace's own`,
121
+ );
122
+ if (RULE_DIRS.length < 2 || !fs.existsSync(file)) return { file };
123
+ const copy = readSet(file),
124
+ kit = readSet(kitFile);
125
+ if (!copy?.rules || typeof copy.rules !== 'object')
126
+ throw new Error(`rules/${name}.json has no "rules" to update: cad rules check ${name} says what is wrong with it`);
127
+ const { set, difference } = updateFromKit(copy, kit),
128
+ fields = [...new Set([...Object.keys(copy), ...Object.keys(set)])].filter(
129
+ (k) => k !== 'rules' && !same(copy[k], set[k]),
130
+ );
131
+ return { file, copy, kit, set, difference, fields };
132
+ }
133
+
134
+ // A figure as a note says it: a number or a word as it is, anything else as JSON
135
+ const said = (v) => (typeof v === 'number' || typeof v === 'string' ? String(v) : JSON.stringify(v));
136
+ const listed = (list) =>
137
+ list.length > 8 ? `${list.slice(0, 8).join(', ')} and ${list.length - 8} more (--json lists them)` : list.join(', ');
138
+
30
139
  // What a check notes and never fails on. An alias: a name the vocabulary shares across parts (screw_clearance, which a
31
140
  // motor's mount reads) that a set gives to one of its own rules in "interface". A copy: a workspace's own copy of a
32
141
  // set the kit has (cad copies a set into rules/ the first time a design uses it), which is used as it is, even after
33
- // the kit's set gains figures: it is told which, so a design that wants one knows where it went.
142
+ // the kit's set gains figures or corrects one: it is told which (rules.new, rules.changed), and cad rules update takes
143
+ // them. A copy that is the kit's set word for word holds nothing of the workspace's own (rules.same).
34
144
  function notesOf(set, file) {
35
- const notes = [], kitDir = RULE_DIRS.at(-1), name = path.basename(file, '.json');
36
- for (const [shared, own] of Object.entries(set.interface || {})) if (set.rules?.[own]) notes.push({ level: 'info', code: 'rules.alias', text: `${own} is also read as ${shared}, the vocabulary's name for it`, rule: own, values: { alias: shared } });
145
+ const notes = [],
146
+ kitDir = RULE_DIRS.at(-1),
147
+ name = path.basename(file, '.json');
148
+ for (const [shared, own] of Object.entries(set.interface || {}))
149
+ if (set.rules?.[own])
150
+ notes.push({
151
+ level: 'info',
152
+ code: 'rules.alias',
153
+ text: `${own} is also read as ${shared}, the vocabulary's name for it`,
154
+ rule: own,
155
+ values: { alias: shared },
156
+ });
37
157
  const kitFile = path.join(kitDir, `${name}.json`);
38
- if (path.dirname(path.resolve(file)) !== path.resolve(kitDir) && fs.existsSync(kitFile) && set.rules && typeof set.rules === 'object') {
39
- const kit = readSet(kitFile), added = Object.keys(kit.rules || {}).filter((k) => !(k in set.rules));
40
- if (added.length) notes.push({ level: 'info', code: 'rules.new', text: `your copy is used as it is; the kit's ${name} now also has ${added.length > 8 ? `${added.slice(0, 8).join(', ')} and ${added.length - 8} more (--json lists them)` : added.join(', ')}: copy any you want into rules/${name}.json, or delete it to read the kit's own`, values: { count: added.length }, refs: { rules: added } });
158
+ if (
159
+ path.dirname(path.resolve(file)) !== path.resolve(kitDir) &&
160
+ fs.existsSync(kitFile) &&
161
+ set.rules &&
162
+ typeof set.rules === 'object'
163
+ ) {
164
+ const kit = readSet(kitFile),
165
+ { added, changed } = kitDifference(set, kit);
166
+ if (same(set, kit))
167
+ notes.push({
168
+ level: 'info',
169
+ code: 'rules.same',
170
+ text: `rules/${name}.json is the kit's ${name} as it is: nothing in it is yours yet. Unless you mean to put your own figures in it, you can delete it: the next design to use ${name} copies in the kit's as it is then`,
171
+ });
172
+ if (changed.length) {
173
+ const one = changed[0],
174
+ c = set.rules[one],
175
+ k = kit.rules[one];
176
+ notes.push({
177
+ level: 'info',
178
+ code: 'rules.changed',
179
+ text: `the kit's ${name} has a newer figure than your copy for ${one} (${said(c?.value)} here, ${said(k?.value)} in the kit's, checked ${k.checked})${changed.length > 1 ? ` and for ${listed(changed.slice(1))}` : ''}: cad rules update ${name} takes the kit's newer figures and keeps your measured ones`,
180
+ values: { count: changed.length },
181
+ refs: { rules: changed },
182
+ });
183
+ }
184
+ if (added.length)
185
+ notes.push({
186
+ level: 'info',
187
+ code: 'rules.new',
188
+ text: `your copy is used as it is; the kit's ${name} now also has ${listed(added)}: copy any you want into rules/${name}.json, or cad rules update ${name} adds them all and keeps what is yours`,
189
+ values: { count: added.length },
190
+ refs: { rules: added },
191
+ });
41
192
  }
42
193
  return notes;
43
194
  }
44
195
 
45
-
46
196
  // What a profile's model reads beside its own set: any other set by name (its slot family, a thread, its material),
47
197
  // the workspace's first, and a measured outline in outlines/<name>.json beside the set, held to its schema
48
198
  function given(name, file, all = allSets()) {
49
- const load = (n) => (all.has(n) ? readSet(all.get(n)) : undefined), at = path.join(path.dirname(file), 'outlines', `${name}.json`), problems = [];
199
+ const load = (n) => (all.has(n) ? readSet(all.get(n)) : undefined),
200
+ at = path.join(path.dirname(file), 'outlines', `${name}.json`),
201
+ problems = [];
50
202
  let measured;
51
203
  if (fs.existsSync(at)) {
52
- try { measured = readSet(at); problems.push(...validate(measured, schema('outline')).map((x) => `outlines/${name}.json: ${x.path}: ${x.message}`)); } catch (e) { problems.push(`outlines/${name}.json isn't JSON: ${e.message}`); }
204
+ try {
205
+ measured = readSet(at);
206
+ problems.push(
207
+ ...validate(measured, schema('outline')).map((x) => `outlines/${name}.json: ${x.path}: ${x.message}`),
208
+ );
209
+ } catch (e) {
210
+ problems.push(`outlines/${name}.json isn't JSON: ${e.message}`);
211
+ }
53
212
  if (problems.length) measured = undefined;
54
213
  }
55
214
  return { load, ...(measured ? { outline: measured } : {}), problems };
@@ -58,18 +217,40 @@ const own = (e) => e.message.replace(/^\w+: /, ''); // a refusal without the fun
58
217
 
59
218
  // A profile, a slot or a slot nut held to sense as well as to the vocabulary: what @rulecad/frames finds in its model
60
219
  function partFindings(set, name, file, all) {
61
- const out = [], say = (level, code, text, extra = {}) => out.push({ level, code, text, ...extra }), g = given(name, file, all);
220
+ const out = [],
221
+ say = (level, code, text, extra = {}) => out.push({ level, code, text, ...extra }),
222
+ g = given(name, file, all);
62
223
  for (const p of g.problems) say('fail', 'outline.schema', p);
63
224
  try {
64
225
  if (set.part === 'profile') out.push(...profileFindings(profileModel(set, {}, g)));
65
226
  if (set.part === 'slot') slotModel(set, {}, g);
66
227
  if (set.part === 'slot_nut') {
67
- const r = (k) => set.rules[k]?.value, slot = g.load(String(r('slot')));
68
- if (slot?.part !== 'slot') say('warn', 'slot_nut.slot', `slot names the slot family it is made for, and there is no slot set "${r('slot')}": its fit is not checked`, { rule: 'slot' });
228
+ const r = (k) => set.rules[k]?.value,
229
+ slot = g.load(String(r('slot')));
230
+ if (slot?.part !== 'slot')
231
+ say(
232
+ 'warn',
233
+ 'slot_nut.slot',
234
+ `slot names the slot family it is made for, and there is no slot set "${r('slot')}": its fit is not checked`,
235
+ { rule: 'slot' },
236
+ );
69
237
  else out.push(...nutFit(slotNutModel(set, {}, g), slotModel(slot, {}, g), g));
70
- if (![...all.values()].some((f) => { const t = readSet(f); return t.part === 'thread' && (t.name === r('thread') || t.rules.thread?.value === r('thread')); })) say('warn', 'slot_nut.thread', `thread ${JSON.stringify(r('thread'))} is no thread set here (M5, or a set's name)`, { rule: 'thread' });
238
+ if (
239
+ ![...all.values()].some((f) => {
240
+ const t = readSet(f);
241
+ return t.part === 'thread' && (t.name === r('thread') || t.rules.thread?.value === r('thread'));
242
+ })
243
+ )
244
+ say(
245
+ 'warn',
246
+ 'slot_nut.thread',
247
+ `thread ${JSON.stringify(r('thread'))} is no thread set here (M5, or a set's name)`,
248
+ { rule: 'thread' },
249
+ );
71
250
  }
72
- } catch (e) { say('fail', `${set.part}.model`, own(e)); }
251
+ } catch (e) {
252
+ say('fail', `${set.part}.model`, own(e));
253
+ }
73
254
  return out;
74
255
  }
75
256
 
@@ -77,21 +258,37 @@ function partFindings(set, name, file, all) {
77
258
  // (its rule is the field's own sentence, which stays), and cad rules draft from a PDF writes each figure's rule
78
259
  // "DRAFT: name and check me" while its kind is estimate. A set that still has one checks and draws as it stands, so it
79
260
  // is said by name until each is filled (a source of its own, or a rule of its own and kind spec) or deleted
80
- const isDraft = (r) => /^DRAFT\b/.test(String(r.source ?? '')) || (/^DRAFT\b/.test(String(r.rule ?? '')) && r.kind === 'estimate');
261
+ const isDraft = (r) =>
262
+ /^DRAFT\b/.test(String(r.source ?? '')) || (/^DRAFT\b/.test(String(r.rule ?? '')) && r.kind === 'estimate');
81
263
  function draftLeft(set) {
82
- const left = Object.entries(set.rules && typeof set.rules === 'object' ? set.rules : {}).filter(([, r]) => r && typeof r === 'object' && isDraft(r)).map(([k]) => k);
264
+ const left = Object.entries(set.rules && typeof set.rules === 'object' ? set.rules : {})
265
+ .filter(([, r]) => r && typeof r === 'object' && isDraft(r))
266
+ .map(([k]) => k);
83
267
  if (!left.length) return [];
84
- const n = Object.keys(set.rules).length, named = left.length > 8 ? `${left.slice(0, 8).join(', ')} and ${left.length - 8} more` : left.join(', ');
85
- return [{ level: 'warn', code: 'rules.draft', text: `${left.length} of its ${n} figures are still the draft's, not read from a sheet: ${named}. Fill each from the maker's sheet (its value, the sheet and page as its source, the date) or delete it`, values: { count: left.length, total: n }, refs: { rules: left } }];
268
+ const n = Object.keys(set.rules).length,
269
+ named = left.length > 8 ? `${left.slice(0, 8).join(', ')} and ${left.length - 8} more` : left.join(', ');
270
+ return [
271
+ {
272
+ level: 'warn',
273
+ code: 'rules.draft',
274
+ text: `${left.length} of its ${n} figures are still the draft's, not read from a sheet: ${named}. Fill each from the maker's sheet (its value, the sheet and page as its source, the date) or delete it`,
275
+ values: { count: left.length, total: n },
276
+ refs: { rules: left },
277
+ },
278
+ ];
86
279
  }
87
280
 
88
281
  /** Every named set checked (or all of them): [{ name, file, findings, notes? }]. A finding's level is fail, warn or info;
89
282
  * notes: what is said and never fails */
90
283
  export function checkSets(names = []) {
91
- const v = vocabulary(), all = allSets();
284
+ const v = vocabulary(),
285
+ all = allSets();
92
286
  return (names.length ? names.map((n) => [n, fileOf(n)]) : [...all]).map(([name, file]) => {
93
- const set = readSet(file), findings = checkRuleSet(set, v), notes = notesOf(set, file);
94
- if (!findings.length && ['profile', 'slot', 'slot_nut'].includes(set.part)) findings.push(...partFindings(set, name, file, all));
287
+ const set = readSet(file),
288
+ findings = checkRuleSet(set, v),
289
+ notes = notesOf(set, file);
290
+ if (!findings.length && ['profile', 'slot', 'slot_nut'].includes(set.part))
291
+ findings.push(...partFindings(set, name, file, all));
95
292
  findings.push(...draftLeft(set));
96
293
  return { name, file, findings, ...(notes.length ? { notes } : {}) };
97
294
  });
@@ -99,23 +296,49 @@ export function checkSets(names = []) {
99
296
 
100
297
  // ---------- a dimension drawing ----------
101
298
  const fig = (x) => String(+Number(x).toFixed(2));
102
- const INK = '#1a1a1a', THIN = '#666', FILL = '#eceae4', METAL = '#c4c8cc';
299
+ const INK = '#1a1a1a',
300
+ THIN = '#666',
301
+ FILL = '#eceae4',
302
+ METAL = '#c4c8cc';
103
303
 
104
304
  /** @param {string} name the rule set's name @returns {string} an SVG drawing of what it says the part mounts by */
105
- export function drawSet(name) { const file = fileOf(name); return drawing(readSet(file), vocabulary(), given(name, file)); }
305
+ export function drawSet(name) {
306
+ const file = fileOf(name);
307
+ return drawing(readSet(file), vocabulary(), given(name, file));
308
+ }
106
309
 
107
310
  // The drawing's marks, in sheet units: each adds to out, and span is a dimension with its extension lines, ticks and figure
108
311
  function pen() {
109
312
  const out = [];
110
- const line = (a, b, c, e, s = INK, sw = 1.2, dash = '') => out.push(`<line x1="${fig(a)}" y1="${fig(b)}" x2="${fig(c)}" y2="${fig(e)}" stroke="${s}" stroke-width="${sw}"${dash ? ` stroke-dasharray="${dash}"` : ''}/>`);
111
- const circle = (x, y, r, fill = 'none', s = INK) => out.push(`<circle cx="${fig(x)}" cy="${fig(y)}" r="${fig(r)}" fill="${fill}" stroke="${s}" stroke-width="1.2"/>`);
112
- const rect = (x, y, a, b, fill = FILL) => out.push(`<rect x="${fig(x)}" y="${fig(y)}" width="${fig(a)}" height="${fig(b)}" fill="${fill}" stroke="${INK}" stroke-width="1.2"/>`);
113
- const text = (x, y, t, a = 'middle', z = 12) => out.push(`<text x="${fig(x)}" y="${fig(y)}" text-anchor="${a}" font-size="${z}" font-family="system-ui, sans-serif" fill="${INK}">${t}</text>`);
114
- const span = (x1, y1, x2, y2, t, across_ = 14) => { // a dimension: extension lines, a line with its ticks, the figure
115
- const horizontal = Math.abs(y2 - y1) < 1e-6, ox = horizontal ? 0 : across_, oy = horizontal ? across_ : 0;
116
- line(x1, y1, x1 + ox, y1 + oy, THIN, 0.6); line(x2, y2, x2 + ox, y2 + oy, THIN, 0.6); line(x1 + ox, y1 + oy, x2 + ox, y2 + oy, THIN, 0.8);
117
- for (const [a, b] of [[x1 + ox, y1 + oy], [x2 + ox, y2 + oy]]) line(a - 3, b + 3, a + 3, b - 3, THIN, 0.8);
118
- if (horizontal) text((x1 + x2) / 2, y1 + oy + (across_ > 0 ? 13 : -4), t); else text(x1 + ox + (across_ > 0 ? 4 : -4), (y1 + y2) / 2 + 4, t, across_ > 0 ? 'start' : 'end');
313
+ const line = (a, b, c, e, s = INK, sw = 1.2, dash = '') =>
314
+ out.push(
315
+ `<line x1="${fig(a)}" y1="${fig(b)}" x2="${fig(c)}" y2="${fig(e)}" stroke="${s}" stroke-width="${sw}"${dash ? ` stroke-dasharray="${dash}"` : ''}/>`,
316
+ );
317
+ const circle = (x, y, r, fill = 'none', s = INK) =>
318
+ out.push(`<circle cx="${fig(x)}" cy="${fig(y)}" r="${fig(r)}" fill="${fill}" stroke="${s}" stroke-width="1.2"/>`);
319
+ const rect = (x, y, a, b, fill = FILL) =>
320
+ out.push(
321
+ `<rect x="${fig(x)}" y="${fig(y)}" width="${fig(a)}" height="${fig(b)}" fill="${fill}" stroke="${INK}" stroke-width="1.2"/>`,
322
+ );
323
+ const text = (x, y, t, a = 'middle', z = 12) =>
324
+ out.push(
325
+ `<text x="${fig(x)}" y="${fig(y)}" text-anchor="${a}" font-size="${z}" font-family="system-ui, sans-serif" fill="${INK}">${t}</text>`,
326
+ );
327
+ const span = (x1, y1, x2, y2, t, across_ = 14) => {
328
+ // a dimension: extension lines, a line with its ticks, the figure
329
+ const horizontal = Math.abs(y2 - y1) < 1e-6,
330
+ ox = horizontal ? 0 : across_,
331
+ oy = horizontal ? across_ : 0;
332
+ line(x1, y1, x1 + ox, y1 + oy, THIN, 0.6);
333
+ line(x2, y2, x2 + ox, y2 + oy, THIN, 0.6);
334
+ line(x1 + ox, y1 + oy, x2 + ox, y2 + oy, THIN, 0.8);
335
+ for (const [a, b] of [
336
+ [x1 + ox, y1 + oy],
337
+ [x2 + ox, y2 + oy],
338
+ ])
339
+ line(a - 3, b + 3, a + 3, b - 3, THIN, 0.8);
340
+ if (horizontal) text((x1 + x2) / 2, y1 + oy + (across_ > 0 ? 13 : -4), t);
341
+ else text(x1 + ox + (across_ > 0 ? 4 : -4), (y1 + y2) / 2 + 4, t, across_ > 0 ? 'start' : 'end');
119
342
  };
120
343
  return { out, line, circle, rect, text, span };
121
344
  }
@@ -124,23 +347,47 @@ function pen() {
124
347
  function sheet(set, { out, text }, W, H) {
125
348
  const kinds = Object.values(set.rules).reduce((m, r) => ({ ...m, [r.kind]: (m[r.kind] || 0) + 1 }), {});
126
349
  text(20, 26, set.name, 'start', 16);
127
- text(20, 44, `all in mm. ${Object.entries(kinds).map(([k, c]) => `${c} ${k}`).join(', ')}: compare it with the datasheet`, 'start', 11);
350
+ text(
351
+ 20,
352
+ 44,
353
+ `all in mm. ${Object.entries(kinds)
354
+ .map(([k, c]) => `${c} ${k}`)
355
+ .join(', ')}: compare it with the datasheet`,
356
+ 'start',
357
+ 11,
358
+ );
128
359
  return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${fig(W)} ${fig(H + 60)}" width="${fig(W)}" height="${fig(H + 60)}"><rect width="100%" height="100%" fill="#fff"/>${out.join('')}</svg>\n`;
129
360
  }
130
361
 
131
362
  // A bearing from its end and in section: bore, outer diameter, width, and the flange or the thrust washers where it has them
132
363
  function bearingDrawing(set) {
133
- const n = (k) => set.rules[k]?.value ?? 0, thrust = set.rules.type?.value === 'thrust';
134
- const d = n('bore'), D = n('outer_diameter'), B = n('width'), F = n('flange_diameter'), Fw = n('flange_width'), d1 = n('shaft_washer_diameter'), D1 = n('housing_washer_bore');
135
- const R = Math.max(D, F) / 2, S = Math.max(4, Math.min(20, 90 / R)), W = 2 * R * S + B * S + 330, H = 2 * R * S + 170;
136
- const cx = R * S + 70, cy = H / 2 + 22, sx = cx + R * S + 120, top = cy - R * S, bottom = cy + R * S;
137
- const pens = pen(), { line, circle, rect, text, span } = pens;
364
+ const n = (k) => set.rules[k]?.value ?? 0,
365
+ thrust = set.rules.type?.value === 'thrust';
366
+ const d = n('bore'),
367
+ D = n('outer_diameter'),
368
+ B = n('width'),
369
+ F = n('flange_diameter'),
370
+ Fw = n('flange_width'),
371
+ d1 = n('shaft_washer_diameter'),
372
+ D1 = n('housing_washer_bore');
373
+ const R = Math.max(D, F) / 2,
374
+ S = Math.max(4, Math.min(20, 90 / R)),
375
+ W = 2 * R * S + B * S + 330,
376
+ H = 2 * R * S + 170;
377
+ const cx = R * S + 70,
378
+ cy = H / 2 + 22,
379
+ sx = cx + R * S + 120,
380
+ top = cy - R * S,
381
+ bottom = cy + R * S;
382
+ const pens = pen(),
383
+ { line, circle, rect, text, span } = pens;
138
384
  // ---- from the end ----
139
385
  if (F) circle(cx, cy, (F / 2) * S, '#f6f4ee');
140
386
  circle(cx, cy, (D / 2) * S, FILL);
141
387
  if (D1) circle(cx, cy, (D1 / 2) * S, 'none', THIN);
142
388
  circle(cx, cy, (d / 2) * S, '#fff');
143
- line(cx - R * S - 8, cy, cx + R * S + 8, cy, THIN, 0.5, '8 3 2 3'); line(cx, cy - R * S - 8, cx, cy + R * S + 8, THIN, 0.5, '8 3 2 3');
389
+ line(cx - R * S - 8, cy, cx + R * S + 8, cy, THIN, 0.5, '8 3 2 3');
390
+ line(cx, cy - R * S - 8, cx, cy + R * S + 8, THIN, 0.5, '8 3 2 3');
144
391
  span(cx - (D / 2) * S, bottom + 6, cx + (D / 2) * S, bottom + 6, `Ø${fig(D)}`, 18);
145
392
  span(cx - (d / 2) * S, top - 6, cx + (d / 2) * S, top - 6, `bore Ø${fig(d)}`, -14);
146
393
  if (F) text(cx, bottom + 66, `flange Ø${fig(F)}, ${fig(Fw)} thick`);
@@ -148,23 +395,45 @@ function bearingDrawing(set) {
148
395
  // ---- the section, axis along the sheet ----
149
396
  for (const side of [-1, 1]) {
150
397
  const y = (a, b) => (side < 0 ? [cy - b * S, (b - a) * S] : [cy + a * S, (b - a) * S]);
151
- const [ry, rh] = y(d / 2, D / 2); rect(sx, ry, B * S, rh);
152
- if (F) { const [fy, fh] = y(D / 2, F / 2); rect(sx, fy, Fw * S, fh, '#ddd9cf'); }
398
+ const [ry, rh] = y(d / 2, D / 2);
399
+ rect(sx, ry, B * S, rh);
400
+ if (F) {
401
+ const [fy, fh] = y(D / 2, F / 2);
402
+ rect(sx, fy, Fw * S, fh, '#ddd9cf');
403
+ }
153
404
  if (thrust) line(sx + (B * S) / 2, ry, sx + (B * S) / 2, ry + rh, THIN, 0.8, '4 3');
154
405
  }
155
406
  line(sx - 12, cy, sx + B * S + 12, cy, THIN, 0.5, '8 3 2 3');
156
407
  span(sx, bottom + 6, sx + B * S, bottom + 6, `${fig(B)}`, 18);
157
408
  span(sx + B * S + 6, cy - (D / 2) * S, sx + B * S + 6, cy + (D / 2) * S, `Ø${fig(D)}`, 30);
158
409
  text(sx + (B * S) / 2, top - 22, `chamfer ${fig(n('chamfer'))}`, 'middle', 11);
159
- text(cx, bottom + 86, `${set.rules.type?.value || 'bearing'}: ${fig(n('dynamic_rating'))} N dynamic, ${fig(n('static_rating'))} N static${set.rules.radial_play ? `, ${set.rules.radial_play.value}` : ''}`, 'middle', 11);
410
+ text(
411
+ cx,
412
+ bottom + 86,
413
+ `${set.rules.type?.value || 'bearing'}: ${fig(n('dynamic_rating'))} N dynamic, ${fig(n('static_rating'))} N static${set.rules.radial_play ? `, ${set.rules.radial_play.value}` : ''}`,
414
+ 'middle',
415
+ 11,
416
+ );
160
417
  return sheet(set, pens, W, H);
161
418
  }
162
419
 
163
420
  // A driver module from above: the board and its two header rows, at their spacing
164
421
  function driverDrawing(set) {
165
- const n = (k) => set.rules[k]?.value ?? 0, w = n('body_width'), d = n('body_depth'), pitch = n('pin_pitch'), row = n('row_spacing'), count = n('pin_count') / 2;
166
- const S = 16, W = w * S + 260, H = d * S + 170, cx = W / 2, cy = H / 2 + 22, X = (x) => cx + x * S, Y = (y) => cy - y * S;
167
- const pens = pen(), { line, circle, rect, text, span } = pens;
422
+ const n = (k) => set.rules[k]?.value ?? 0,
423
+ w = n('body_width'),
424
+ d = n('body_depth'),
425
+ pitch = n('pin_pitch'),
426
+ row = n('row_spacing'),
427
+ count = n('pin_count') / 2;
428
+ const S = 16,
429
+ W = w * S + 260,
430
+ H = d * S + 170,
431
+ cx = W / 2,
432
+ cy = H / 2 + 22,
433
+ X = (x) => cx + x * S,
434
+ Y = (y) => cy - y * S;
435
+ const pens = pen(),
436
+ { line, circle, rect, text, span } = pens;
168
437
  rect(X(-w / 2), Y(d / 2), w * S, d * S);
169
438
  const pins = Array.from({ length: count }, (_, i) => (i - (count - 1) / 2) * pitch);
170
439
  for (const y of [-row / 2, row / 2]) for (const x of pins) circle(X(x), Y(y), (pitch / 3.2) * S, METAL);
@@ -180,22 +449,45 @@ function driverDrawing(set) {
180
449
 
181
450
  // A round part from its end and along its axis: linear bearings, nuts, couplers, pulleys, idlers, rods. Each says what it has: flange, hole circle, a dashed pitch circle, the bores of a coupler
182
451
  function roundDrawing(set, { D, d = 0, L, bores, flange, circle: holeCircle, pitchD, notes = [] }) {
183
- const R = Math.max(D, flange?.D ?? 0) / 2, S = Math.max(3, Math.min(14, 90 / R)), W = 2 * R * S + L * S + 340, H = 2 * R * S + 190;
184
- const cx = R * S + 70, cy = H / 2 + 22, sx = cx + R * S + 120, top = cy - R * S, bottom = cy + R * S;
185
- const pens = pen(), { line, circle, rect, text, span } = pens;
452
+ const R = Math.max(D, flange?.D ?? 0) / 2,
453
+ S = Math.max(3, Math.min(14, 90 / R)),
454
+ W = 2 * R * S + L * S + 340,
455
+ H = 2 * R * S + 190;
456
+ const cx = R * S + 70,
457
+ cy = H / 2 + 22,
458
+ sx = cx + R * S + 120,
459
+ top = cy - R * S,
460
+ bottom = cy + R * S;
461
+ const pens = pen(),
462
+ { line, circle, rect, text, span } = pens;
186
463
  // ---- from the end ----
187
464
  if (flange) circle(cx, cy, (flange.D / 2) * S, '#f6f4ee');
188
465
  circle(cx, cy, (D / 2) * S, FILL);
189
466
  if (pitchD) circle(cx, cy, (pitchD / 2) * S, 'none', THIN);
190
467
  if (d) circle(cx, cy, (d / 2) * S, '#fff');
191
- if (holeCircle) for (let i = 0; i < holeCircle.count; i++) { const a = (2 * Math.PI * i) / holeCircle.count; circle(cx + (holeCircle.D / 2) * Math.cos(a) * S, cy + (holeCircle.D / 2) * Math.sin(a) * S, (holeCircle.hole / 2) * S, '#fff'); }
192
- line(cx - R * S - 8, cy, cx + R * S + 8, cy, THIN, 0.5, '8 3 2 3'); line(cx, cy - R * S - 8, cx, cy + R * S + 8, THIN, 0.5, '8 3 2 3');
468
+ if (holeCircle)
469
+ for (let i = 0; i < holeCircle.count; i++) {
470
+ const a = (2 * Math.PI * i) / holeCircle.count;
471
+ circle(
472
+ cx + (holeCircle.D / 2) * Math.cos(a) * S,
473
+ cy + (holeCircle.D / 2) * Math.sin(a) * S,
474
+ (holeCircle.hole / 2) * S,
475
+ '#fff',
476
+ );
477
+ }
478
+ line(cx - R * S - 8, cy, cx + R * S + 8, cy, THIN, 0.5, '8 3 2 3');
479
+ line(cx, cy - R * S - 8, cx, cy + R * S + 8, THIN, 0.5, '8 3 2 3');
193
480
  span(cx - R * S, bottom + 6, cx + R * S, bottom + 6, `Ø${fig(flange?.D ?? D)}`, 18);
194
481
  if (d) span(cx - (d / 2) * S, top - 6, cx + (d / 2) * S, top - 6, `bore Ø${fig(d)}`, -14);
195
482
  // ---- along the axis ----
196
- const ring = (x, len, a, b, fill = FILL) => { for (const side of [-1, 1]) rect(x, side < 0 ? cy - (b / 2) * S : cy + (a / 2) * S, len * S, ((b - a) / 2) * S, fill); };
197
- if (bores) { ring(sx, L / 2, bores[0], D); ring(sx + (L / 2) * S, L / 2, bores[1], D); }
198
- else if (d) ring(sx, L, d, D);
483
+ const ring = (x, len, a, b, fill = FILL) => {
484
+ for (const side of [-1, 1])
485
+ rect(x, side < 0 ? cy - (b / 2) * S : cy + (a / 2) * S, len * S, ((b - a) / 2) * S, fill);
486
+ };
487
+ if (bores) {
488
+ ring(sx, L / 2, bores[0], D);
489
+ ring(sx + (L / 2) * S, L / 2, bores[1], D);
490
+ } else if (d) ring(sx, L, d, D);
199
491
  else rect(sx, cy - (D / 2) * S, L * S, D * S, METAL);
200
492
  if (flange) ring(sx + flange.at * S, flange.w, d, flange.D, '#ddd9cf');
201
493
  line(sx - 12, cy, sx + L * S + 12, cy, THIN, 0.5, '8 3 2 3');
@@ -207,34 +499,85 @@ function roundDrawing(set, { D, d = 0, L, bores, flange, circle: holeCircle, pit
207
499
 
208
500
  // A lead screw from the side: the crest and root, the starts' flanks, and pitch against lead
209
501
  function leadScrewDrawing(set) {
210
- const n = (k) => set.rules[k]?.value ?? 0, D = n('diameter'), root = n('root_diameter'), P = n('pitch'), lead = n('lead'), starts = n('starts') || 1;
211
- const L = Math.max(3 * lead, 20), S = Math.min(14, 420 / L), W = L * S + 240, H = D * S + 200, x0 = 110, cy = H / 2 + 12;
212
- const pens = pen(), { line, rect, text, span } = pens;
502
+ const n = (k) => set.rules[k]?.value ?? 0,
503
+ D = n('diameter'),
504
+ root = n('root_diameter'),
505
+ P = n('pitch'),
506
+ lead = n('lead'),
507
+ starts = n('starts') || 1;
508
+ const L = Math.max(3 * lead, 20),
509
+ S = Math.min(14, 420 / L),
510
+ W = L * S + 240,
511
+ H = D * S + 200,
512
+ x0 = 110,
513
+ cy = H / 2 + 12;
514
+ const pens = pen(),
515
+ { line, rect, text, span } = pens;
213
516
  rect(x0, cy - (D / 2) * S, L * S, D * S, METAL);
214
- for (const side of [-1, 1]) line(x0, cy + side * (root / 2) * S, x0 + L * S, cy + side * (root / 2) * S, THIN, 0.6, '4 3');
517
+ for (const side of [-1, 1])
518
+ line(x0, cy + side * (root / 2) * S, x0 + L * S, cy + side * (root / 2) * S, THIN, 0.6, '4 3');
215
519
  const lean = (D * S * Math.tan((n('helix_angle') * Math.PI) / 180)) / 2;
216
- for (let i = 0; i * P <= L + 1e-9; i++) { const x = x0 + i * P * S; if (x - lean >= x0 && x + lean <= x0 + L * S) line(x - lean, cy + (D / 2) * S, x + lean, cy - (D / 2) * S, i % starts === 0 ? INK : THIN, i % starts === 0 ? 1.6 : 0.7); }
520
+ for (let i = 0; i * P <= L + 1e-9; i++) {
521
+ const x = x0 + i * P * S;
522
+ if (x - lean >= x0 && x + lean <= x0 + L * S)
523
+ line(
524
+ x - lean,
525
+ cy + (D / 2) * S,
526
+ x + lean,
527
+ cy - (D / 2) * S,
528
+ i % starts === 0 ? INK : THIN,
529
+ i % starts === 0 ? 1.6 : 0.7,
530
+ );
531
+ }
217
532
  line(x0 - 12, cy, x0 + L * S + 12, cy, THIN, 0.5, '8 3 2 3');
218
- const below = cy + (D / 2) * S + 6, above = cy - (D / 2) * S - 6;
533
+ const below = cy + (D / 2) * S + 6,
534
+ above = cy - (D / 2) * S - 6;
219
535
  span(x0, below, x0 + P * S, below, `pitch ${fig(P)}`, 18);
220
536
  span(x0, below, x0 + lead * S, below, `lead ${fig(lead)}`, 44);
221
537
  span(x0 + L * S + 6, cy - (D / 2) * S, x0 + L * S + 6, cy + (D / 2) * S, `Ø${fig(D)}`, 30);
222
538
  span(x0 - 6, cy - (root / 2) * S, x0 - 6, cy + (root / 2) * S, `root Ø${fig(root)}`, -18);
223
- text(x0 + (L * S) / 2, above - 8, `${set.rules.thread?.value ?? ''}, ${fig(starts)} start${starts > 1 ? 's' : ''}, helix ${fig(n('helix_angle'))}°`, 'middle', 12);
539
+ text(
540
+ x0 + (L * S) / 2,
541
+ above - 8,
542
+ `${set.rules.thread?.value ?? ''}, ${fig(starts)} start${starts > 1 ? 's' : ''}, helix ${fig(n('helix_angle'))}°`,
543
+ 'middle',
544
+ 12,
545
+ );
224
546
  text(x0 + (L * S) / 2, below + 72, 'each dark line one start, repeating at the lead', 'middle', 11);
225
547
  return sheet(set, pens, W, H);
226
548
  }
227
549
 
228
550
  // A short length of belt, teeth along it
229
551
  function beltDrawing(set) {
230
- const n = (k) => set.rules[k]?.value ?? 0, P = n('pitch'), w = n('width'), L = P * 8, S = 12, W = L * S + 220, H = w * S + 190, x0 = 90, cy = H / 2 + 10;
231
- const pens = pen(), { line, rect, text, span } = pens;
552
+ const n = (k) => set.rules[k]?.value ?? 0,
553
+ P = n('pitch'),
554
+ w = n('width'),
555
+ L = P * 8,
556
+ S = 12,
557
+ W = L * S + 220,
558
+ H = w * S + 190,
559
+ x0 = 90,
560
+ cy = H / 2 + 10;
561
+ const pens = pen(),
562
+ { line, rect, text, span } = pens;
232
563
  rect(x0, cy - (w / 2) * S, L * S, w * S);
233
564
  for (let i = 0; i <= 8; i++) line(x0 + i * P * S, cy - (w / 2) * S, x0 + i * P * S, cy + (w / 2) * S, THIN, 0.7);
234
565
  span(x0, cy + (w / 2) * S + 6, x0 + P * S, cy + (w / 2) * S + 6, `pitch ${fig(P)}`, 18);
235
566
  span(x0 + L * S + 6, cy - (w / 2) * S, x0 + L * S + 6, cy + (w / 2) * S, `${fig(w)}`, 18);
236
- text(x0 + (L * S) / 2, cy + (w / 2) * S + 66, `${fig(n('stiffness'))} N per unit strain, pitch line ${n('pitch_line_offset')} beyond the teeth`, 'middle', 11);
237
- text(x0 + (L * S) / 2, cy + (w / 2) * S + 84, `rated ${fig(n('rated_tension'))} N, breaks at ${fig(n('breaking_strength'))} N`, 'middle', 11);
567
+ text(
568
+ x0 + (L * S) / 2,
569
+ cy + (w / 2) * S + 66,
570
+ `${fig(n('stiffness'))} N per unit strain, pitch line ${n('pitch_line_offset')} beyond the teeth`,
571
+ 'middle',
572
+ 11,
573
+ );
574
+ text(
575
+ x0 + (L * S) / 2,
576
+ cy + (w / 2) * S + 84,
577
+ `rated ${fig(n('rated_tension'))} N, breaks at ${fig(n('breaking_strength'))} N`,
578
+ 'middle',
579
+ 11,
580
+ );
238
581
  return sheet(set, pens, W, H);
239
582
  }
240
583
 
@@ -242,53 +585,177 @@ function beltDrawing(set) {
242
585
  // every one dimensioned from the set's own figures, to hold against the standard's table. Seats are level across the
243
586
  // row: a head stands above the line, a countersunk head sits under it, and a length runs from that line to the tip.
244
587
  function threadDrawing(set) {
245
- const n = (k) => (typeof set.rules[k]?.value === 'number' ? set.rules[k].value : 0), has = (k) => n(k) > 0, says = (k) => String(set.rules[k]?.value ?? '');
246
- const d = n('major_diameter'), P = n('pitch'), lengths = Array.isArray(set.rules.lengths?.value) ? set.rules.lengths.value : [];
588
+ const n = (k) => (typeof set.rules[k]?.value === 'number' ? set.rules[k].value : 0),
589
+ has = (k) => n(k) > 0,
590
+ says = (k) => String(set.rules[k]?.value ?? '');
591
+ const d = n('major_diameter'),
592
+ P = n('pitch'),
593
+ lengths = Array.isArray(set.rules.lengths?.value) ? set.rules.lengths.value : [];
247
594
  const L = lengths.find((l) => l >= 2.5 * d) ?? lengths.at(-1) ?? 3 * d; // a length it is sold in, near three diameters
248
595
  const heads = [
249
596
  has('head') && { name: 'socket cap', form: 'cap', D: n('head'), k: n('head_height'), key: n('head_key') },
250
- has('button_head') && { name: 'button', form: 'button', D: n('button_head'), k: n('button_head_height'), key: n('button_key') },
251
- has('countersunk_head') && { name: `countersunk ${fig(n('countersunk_angle'))}°`, form: 'countersunk', D: n('countersunk_head'), k: n('countersunk_head_height') || (n('countersunk_head') - d) / 2 / Math.tan((n('countersunk_angle') * Math.PI) / 360), key: n('countersunk_key') },
252
- has('hex_head_flats') && { name: 'hexagon', form: 'hex', D: n('hex_head_flats'), k: n('hex_head_height'), note: 'across flats' },
253
- has('pan_head') && { name: 'pan', form: 'pan', D: n('pan_head'), k: n('pan_head_height'), note: says('pan_head_drive') },
597
+ has('button_head') && {
598
+ name: 'button',
599
+ form: 'button',
600
+ D: n('button_head'),
601
+ k: n('button_head_height'),
602
+ key: n('button_key'),
603
+ },
604
+ has('countersunk_head') && {
605
+ name: `countersunk ${fig(n('countersunk_angle'))}°`,
606
+ form: 'countersunk',
607
+ D: n('countersunk_head'),
608
+ k:
609
+ n('countersunk_head_height') ||
610
+ (n('countersunk_head') - d) / 2 / Math.tan((n('countersunk_angle') * Math.PI) / 360),
611
+ key: n('countersunk_key'),
612
+ },
613
+ has('hex_head_flats') && {
614
+ name: 'hexagon',
615
+ form: 'hex',
616
+ D: n('hex_head_flats'),
617
+ k: n('hex_head_height'),
618
+ note: 'across flats',
619
+ },
620
+ has('pan_head') && {
621
+ name: 'pan',
622
+ form: 'pan',
623
+ D: n('pan_head'),
624
+ k: n('pan_head_height'),
625
+ note: says('pan_head_drive'),
626
+ },
254
627
  ].filter(Boolean);
255
628
  if (!heads.length) heads.push({ name: 'thread', form: 'stud', D: d, k: 0 });
256
629
  const nuts = [
257
630
  has('nut_flats') && { name: 'hexagon nut', s: n('nut_flats'), m: n('nut_height'), sides: 6 },
258
631
  has('square_nut_flats') && { name: 'square nut', s: n('square_nut_flats'), m: n('square_nut_height'), sides: 4 },
259
- has('lock_nut_height') && { name: 'lock nut', s: n('lock_nut_flats') || n('nut_flats'), m: n('lock_nut_height'), sides: 6 },
260
- has('washer_diameter') && { name: 'washer', s: n('washer_diameter'), m: n('washer_thickness'), bore: n('washer_bore') },
632
+ has('lock_nut_height') && {
633
+ name: 'lock nut',
634
+ s: n('lock_nut_flats') || n('nut_flats'),
635
+ m: n('lock_nut_height'),
636
+ sides: 6,
637
+ },
638
+ has('washer_diameter') && {
639
+ name: 'washer',
640
+ s: n('washer_diameter'),
641
+ m: n('washer_thickness'),
642
+ bore: n('washer_bore'),
643
+ },
261
644
  ].filter(Boolean);
262
- const holes = [['tap drill', 'tap_drill'], ['close', 'clearance_close'], ['normal', 'clearance'], ['loose', 'clearance_loose'], ['pilot in plastic', 'pilot'], ['insert hole', 'insert_hole']].filter(([, k]) => has(k)).map(([name, k]) => ({ name, D: n(k), ring: k === 'insert_hole' ? n('insert_diameter') : k === 'pilot' ? n('pilot_boss') : k.startsWith('clearance') ? d : 0 })); // (dashed round a hole: an insert's knurls, a pilot's boss; grey inside one: the thread passing through)
263
- const widest = Math.max(d, ...heads.map((h) => h.D), ...nuts.map((x) => x.s), ...holes.map((h) => Math.max(h.D, h.ring))), S = Math.max(3, Math.min(16, 90 / widest));
264
- const col = widest * S + 84, count = Math.max(heads.length, nuts.length, 3), X = (i) => 60 + col * (i + 0.5);
265
- const big = Math.max(0, ...holes.map((h) => Math.max(h.D, h.ring))) * S, holeCol = Math.max(big + 64, Math.min(col, (count * col) / Math.max(holes.length, 1))), HX = (i) => 60 + holeCol * (i + 0.5); // (holes are small: their row is spaced closer, so six fit under four screws)
645
+ const holes = [
646
+ ['tap drill', 'tap_drill'],
647
+ ['close', 'clearance_close'],
648
+ ['normal', 'clearance'],
649
+ ['loose', 'clearance_loose'],
650
+ ['pilot in plastic', 'pilot'],
651
+ ['insert hole', 'insert_hole'],
652
+ ]
653
+ .filter(([, k]) => has(k))
654
+ .map(([name, k]) => ({
655
+ name,
656
+ D: n(k),
657
+ ring:
658
+ k === 'insert_hole'
659
+ ? n('insert_diameter')
660
+ : k === 'pilot'
661
+ ? n('pilot_boss')
662
+ : k.startsWith('clearance')
663
+ ? d
664
+ : 0,
665
+ })); // (dashed round a hole: an insert's knurls, a pilot's boss; grey inside one: the thread passing through)
666
+ const widest = Math.max(
667
+ d,
668
+ ...heads.map((h) => h.D),
669
+ ...nuts.map((x) => x.s),
670
+ ...holes.map((h) => Math.max(h.D, h.ring)),
671
+ ),
672
+ S = Math.max(3, Math.min(16, 90 / widest));
673
+ const col = widest * S + 84,
674
+ count = Math.max(heads.length, nuts.length, 3),
675
+ X = (i) => 60 + col * (i + 0.5);
676
+ const big = Math.max(0, ...holes.map((h) => Math.max(h.D, h.ring))) * S,
677
+ holeCol = Math.max(big + 64, Math.min(col, (count * col) / Math.max(holes.length, 1))),
678
+ HX = (i) => 60 + holeCol * (i + 0.5); // (holes are small: their row is spaced closer, so six fit under four screws)
266
679
  const W = Math.max(count * col, holes.length * holeCol) + 80;
267
- const pens = pen(), { out, line, circle, rect, text, span } = pens, poly = (pts, fill = FILL) => out.push(`<polygon points="${pts.map(([a, b]) => `${fig(a)},${fig(b)}`).join(' ')}" fill="${fill}" stroke="${INK}" stroke-width="1.2"/>`);
680
+ const pens = pen(),
681
+ { out, line, circle, rect, text, span } = pens,
682
+ poly = (pts, fill = FILL) =>
683
+ out.push(
684
+ `<polygon points="${pts.map(([a, b]) => `${fig(a)},${fig(b)}`).join(' ')}" fill="${fill}" stroke="${INK}" stroke-width="1.2"/>`,
685
+ );
268
686
  // ---- the screws, from the side ----
269
- const maxK = Math.max(...heads.map((h) => (h.form === 'countersunk' ? 0 : h.k))), yFace = 92 + maxK * S, yTip = yFace + L * S, root = (has('root_diameter') ? (d - n('root_diameter')) / 2 : 0.6134 * P) * S; // (its root where the set gives one; else an external thread is 0.6134 of its pitch deep: ISO 68-1)
687
+ const maxK = Math.max(...heads.map((h) => (h.form === 'countersunk' ? 0 : h.k))),
688
+ yFace = 92 + maxK * S,
689
+ yTip = yFace + L * S,
690
+ root = (has('root_diameter') ? (d - n('root_diameter')) / 2 : 0.6134 * P) * S; // (its root where the set gives one; else an external thread is 0.6134 of its pitch deep: ISO 68-1)
270
691
  heads.forEach((h, i) => {
271
- const cx = X(i), r = (h.D / 2) * S, kS = h.k * S, sunk = h.form === 'countersunk', top = sunk ? yFace : yFace - kS, under = sunk ? yFace + kS : yFace;
692
+ const cx = X(i),
693
+ r = (h.D / 2) * S,
694
+ kS = h.k * S,
695
+ sunk = h.form === 'countersunk',
696
+ top = sunk ? yFace : yFace - kS,
697
+ under = sunk ? yFace + kS : yFace;
272
698
  rect(cx - (d / 2) * S, under, d * S, yTip - under, METAL);
273
- for (const side of [-1, 1]) line(cx + side * ((d / 2) * S - root), under + 2, cx + side * ((d / 2) * S - root), yTip, THIN, 0.6, '4 3');
699
+ for (const side of [-1, 1])
700
+ line(cx + side * ((d / 2) * S - root), under + 2, cx + side * ((d / 2) * S - root), yTip, THIN, 0.6, '4 3');
274
701
  if (h.form === 'cap' || h.form === 'hex') rect(cx - r, top, 2 * r, kS, METAL);
275
- if (h.form === 'pan') out.push(`<rect x="${fig(cx - r)}" y="${fig(top)}" width="${fig(2 * r)}" height="${fig(kS)}" rx="${fig(Math.min(kS, r) * 0.45)}" fill="${METAL}" stroke="${INK}" stroke-width="1.2"/>`);
276
- if (h.form === 'button') { const R = (r * r + kS * kS) / (2 * kS); out.push(`<path d="M ${fig(cx - r)} ${fig(yFace)} A ${fig(R)} ${fig(R)} 0 0 1 ${fig(cx + r)} ${fig(yFace)} Z" fill="${METAL}" stroke="${INK}" stroke-width="1.2"/>`); }
277
- if (sunk) poly([[cx - r, top], [cx + r, top], [cx + (d / 2) * S, under], [cx - (d / 2) * S, under]], METAL);
278
- if (h.key) { const kw = (h.key / 2) * S, deep = Math.min(kS * 0.6, h.key * S); for (const side of [-1, 1]) line(cx + side * kw, top, cx + side * kw, top + deep, THIN, 0.7, '3 2'); line(cx - kw, top + deep, cx + kw, top + deep, THIN, 0.7, '3 2'); }
702
+ if (h.form === 'pan')
703
+ out.push(
704
+ `<rect x="${fig(cx - r)}" y="${fig(top)}" width="${fig(2 * r)}" height="${fig(kS)}" rx="${fig(Math.min(kS, r) * 0.45)}" fill="${METAL}" stroke="${INK}" stroke-width="1.2"/>`,
705
+ );
706
+ if (h.form === 'button') {
707
+ const R = (r * r + kS * kS) / (2 * kS);
708
+ out.push(
709
+ `<path d="M ${fig(cx - r)} ${fig(yFace)} A ${fig(R)} ${fig(R)} 0 0 1 ${fig(cx + r)} ${fig(yFace)} Z" fill="${METAL}" stroke="${INK}" stroke-width="1.2"/>`,
710
+ );
711
+ }
712
+ if (sunk)
713
+ poly(
714
+ [
715
+ [cx - r, top],
716
+ [cx + r, top],
717
+ [cx + (d / 2) * S, under],
718
+ [cx - (d / 2) * S, under],
719
+ ],
720
+ METAL,
721
+ );
722
+ if (h.key) {
723
+ const kw = (h.key / 2) * S,
724
+ deep = Math.min(kS * 0.6, h.key * S);
725
+ for (const side of [-1, 1]) line(cx + side * kw, top, cx + side * kw, top + deep, THIN, 0.7, '3 2');
726
+ line(cx - kw, top + deep, cx + kw, top + deep, THIN, 0.7, '3 2');
727
+ }
279
728
  if (h.form !== 'stud') span(cx - r, top - 6, cx + r, top - 6, `${h.form === 'hex' ? '' : 'Ø'}${fig(h.D)}`, -14);
280
729
  if (h.k) span(cx + r + 6, top, cx + r + 6, top + kS, fig(h.k), 12);
281
- if (i === 0) { span(cx - (d / 2) * S, yTip + 6, cx + (d / 2) * S, yTip + 6, `Ø${fig(d)}`, 14); span(cx - Math.max(r, (d / 2) * S) - 6, yFace, cx - Math.max(r, (d / 2) * S) - 6, yTip, fig(L), -14); }
730
+ if (i === 0) {
731
+ span(cx - (d / 2) * S, yTip + 6, cx + (d / 2) * S, yTip + 6, `Ø${fig(d)}`, 14);
732
+ span(cx - Math.max(r, (d / 2) * S) - 6, yFace, cx - Math.max(r, (d / 2) * S) - 6, yTip, fig(L), -14);
733
+ }
282
734
  text(cx, yTip + 58, h.name);
283
735
  const under2 = [h.key ? `key ${fig(h.key)}` : '', h.note || ''].filter(Boolean).join(', ');
284
736
  if (under2) text(cx, yTip + 74, under2, 'middle', 11);
285
737
  });
286
738
  line(40, yFace, W - 40, yFace, THIN, 0.5, '8 3 2 3');
287
739
  // ---- nuts and the washer: from above, then from the side ----
288
- const tall = Math.max(0, ...nuts.map((x) => (x.sides === 6 ? x.s * 2 / Math.sqrt(3) : x.s))) * S, yPlan = yTip + 104 + tall / 2, ySide = yPlan + tall / 2 + 48, maxM = Math.max(0, ...nuts.map((x) => x.m)) * S;
740
+ const tall = Math.max(0, ...nuts.map((x) => (x.sides === 6 ? (x.s * 2) / Math.sqrt(3) : x.s))) * S,
741
+ yPlan = yTip + 104 + tall / 2,
742
+ ySide = yPlan + tall / 2 + 48,
743
+ maxM = Math.max(0, ...nuts.map((x) => x.m)) * S;
289
744
  nuts.forEach((x, i) => {
290
- const cx = X(i), r = (x.s / 2) * S, across = x.sides === 6 ? x.s * S / Math.sqrt(3) : r;
291
- if (x.sides === 6) poly([[r, across / 2], [0, across], [-r, across / 2], [-r, -across / 2], [0, -across], [r, -across / 2]].map(([a, b]) => [cx + a, yPlan + b]));
745
+ const cx = X(i),
746
+ r = (x.s / 2) * S,
747
+ across = x.sides === 6 ? (x.s * S) / Math.sqrt(3) : r;
748
+ if (x.sides === 6)
749
+ poly(
750
+ [
751
+ [r, across / 2],
752
+ [0, across],
753
+ [-r, across / 2],
754
+ [-r, -across / 2],
755
+ [0, -across],
756
+ [r, -across / 2],
757
+ ].map(([a, b]) => [cx + a, yPlan + b]),
758
+ );
292
759
  else if (x.sides === 4) rect(cx - r, yPlan - r, 2 * r, 2 * r);
293
760
  else circle(cx, yPlan, r, FILL);
294
761
  circle(cx, yPlan, ((x.bore || d) / 2) * S, '#fff');
@@ -304,9 +771,15 @@ function threadDrawing(set) {
304
771
  const yHole = (nuts.length ? ySide + maxM + 62 : yTip + 104) + big / 2;
305
772
  holes.forEach((h, i) => {
306
773
  const cx = HX(i);
307
- if (h.ring > h.D) out.push(`<circle cx="${fig(cx)}" cy="${fig(yHole)}" r="${fig((h.ring / 2) * S)}" fill="none" stroke="${THIN}" stroke-width="0.8" stroke-dasharray="4 3"/>`);
774
+ if (h.ring > h.D)
775
+ out.push(
776
+ `<circle cx="${fig(cx)}" cy="${fig(yHole)}" r="${fig((h.ring / 2) * S)}" fill="none" stroke="${THIN}" stroke-width="0.8" stroke-dasharray="4 3"/>`,
777
+ );
308
778
  circle(cx, yHole, (h.D / 2) * S, '#fff');
309
- if (h.ring && h.ring < h.D) out.push(`<circle cx="${fig(cx)}" cy="${fig(yHole)}" r="${fig((h.ring / 2) * S)}" fill="${METAL}" stroke="${THIN}" stroke-width="0.8"/>`);
779
+ if (h.ring && h.ring < h.D)
780
+ out.push(
781
+ `<circle cx="${fig(cx)}" cy="${fig(yHole)}" r="${fig((h.ring / 2) * S)}" fill="${METAL}" stroke="${THIN}" stroke-width="0.8"/>`,
782
+ );
310
783
  span(cx - (h.D / 2) * S, yHole + big / 2 + 4, cx + (h.D / 2) * S, yHole + big / 2 + 4, `Ø${fig(h.D)}`, 14);
311
784
  text(cx, yHole + big / 2 + 50, h.name);
312
785
  });
@@ -314,67 +787,155 @@ function threadDrawing(set) {
314
787
  const notes = [
315
788
  `${says('thread')}, ${says('thread_form')}: pitch ${fig(P)}${has('pitch_fine') ? `, fine ${fig(n('pitch_fine'))}` : ''}${has('set_screw_key') ? `, set screw key ${fig(n('set_screw_key'))}` : ''}${says('thread_form') === 'unified' ? ' (divide by 25.4 for the inch table)' : ''}`,
316
789
  lengths.length ? `socket cap lengths: ${lengths.map(fig).join(', ')}` : '',
317
- has('proof_stress') ? `${has('property_class') ? `class ${fig(n('property_class'))}: ` : ''}proof stress ${fig(n('proof_stress'))} MPa${has('stainless_proof_stress') ? `; ${says('stainless_class')}: ${fig(n('stainless_proof_stress'))} MPa` : ''}` : '',
318
- has('insert_hole') ? `insert${has('insert_diameter') ? ` Ø${fig(n('insert_diameter'))}` : ''}${has('insert_length') ? ` × ${fig(n('insert_length'))} long` : ''} (dashed) in a Ø${fig(n('insert_hole'))} hole${has('insert_taper') ? `, tapered ${fig(n('insert_taper'))}°` : ''}${has('insert_wall') ? `, ${fig(n('insert_wall'))} of wall round it at least` : ''}` : '',
319
- has('pilot') ? `pilot Ø${fig(n('pilot'))}${has('pilot_depth') ? `, ${fig(n('pilot_depth'))} deep at least` : ''}${has('pilot_boss') ? `, in a boss of Ø${fig(n('pilot_boss'))} at least (dashed)` : ''}: a starting figure, your printer's measured one comes first` : '',
790
+ has('proof_stress')
791
+ ? `${has('property_class') ? `class ${fig(n('property_class'))}: ` : ''}proof stress ${fig(n('proof_stress'))} MPa${has('stainless_proof_stress') ? `; ${says('stainless_class')}: ${fig(n('stainless_proof_stress'))} MPa` : ''}`
792
+ : '',
793
+ has('insert_hole')
794
+ ? `insert${has('insert_diameter') ? ` Ø${fig(n('insert_diameter'))}` : ''}${has('insert_length') ? ` × ${fig(n('insert_length'))} long` : ''} (dashed) in a Ø${fig(n('insert_hole'))} hole${has('insert_taper') ? `, tapered ${fig(n('insert_taper'))}°` : ''}${has('insert_wall') ? `, ${fig(n('insert_wall'))} of wall round it at least` : ''}`
795
+ : '',
796
+ has('pilot')
797
+ ? `pilot Ø${fig(n('pilot'))}${has('pilot_depth') ? `, ${fig(n('pilot_depth'))} deep at least` : ''}${has('pilot_boss') ? `, in a boss of Ø${fig(n('pilot_boss'))} at least (dashed)` : ''}: a starting figure, your printer's measured one comes first`
798
+ : '',
320
799
  ].filter(Boolean);
321
- const yNotes = (holes.length ? yHole + big / 2 + 80 : nuts.length ? ySide + maxM + 66 : yTip + 104);
800
+ const yNotes = holes.length ? yHole + big / 2 + 80 : nuts.length ? ySide + maxM + 66 : yTip + 104;
322
801
  notes.forEach((t, i) => text(40, yNotes + i * 17, t, 'start', 11));
323
802
  return sheet(set, pens, Math.max(W, 620), yNotes + notes.length * 17 - 50);
324
803
  }
325
804
 
326
805
  // ---------- profiles, slots and slot nuts ----------
327
- const pathOf = (loops, X, Y) => loops.map((l) => `M ${l.map(([x, y]) => `${fig(X(x))} ${fig(Y(y))}`).join(' L ')} Z`).join(' ');
806
+ const pathOf = (loops, X, Y) =>
807
+ loops.map((l) => `M ${l.map(([x, y]) => `${fig(X(x))} ${fig(Y(y))}`).join(' L ')} Z`).join(' ');
328
808
  const sig = (x, n = 4) => String(+Number(x).toPrecision(n));
329
809
 
330
810
  // A profile's section to scale, with what a sheet's drawing dimensions (size, slot, bore, corner), and under it the
331
811
  // sheet's section figures beside what the drawn outline comes to
332
812
  function profileDrawing(set, g) {
333
- const m = profileModel(set, {}, g), o = outline(m), s = section(m), W = m.width, H = m.height;
334
- const S = Math.min(18, 380 / Math.max(W, H)), sheetW = Math.max(W * S + 330, 640), cx = 130 + (W * S) / 2, cy = 110 + (H * S) / 2, X = (x) => cx + x * S, Y = (y) => cy - y * S;
335
- const pens = pen(), { out, line, text, span } = pens;
336
- out.push(`<path d="${pathOf(o.loops, X, Y)}" fill="${METAL}" fill-rule="evenodd" stroke="${INK}" stroke-width="1.2" stroke-linejoin="round"/>`);
337
- line(X(-W / 2) - 10, Y(0), X(W / 2) + 10, Y(0), THIN, 0.5, '8 3 2 3'); line(X(0), Y(H / 2) - 10, X(0), Y(-H / 2) + 10, THIN, 0.5, '8 3 2 3');
813
+ const m = profileModel(set, {}, g),
814
+ o = outline(m),
815
+ s = section(m),
816
+ W = m.width,
817
+ H = m.height;
818
+ const S = Math.min(18, 380 / Math.max(W, H)),
819
+ sheetW = Math.max(W * S + 330, 640),
820
+ cx = 130 + (W * S) / 2,
821
+ cy = 110 + (H * S) / 2,
822
+ X = (x) => cx + x * S,
823
+ Y = (y) => cy - y * S;
824
+ const pens = pen(),
825
+ { out, line, text, span } = pens;
826
+ out.push(
827
+ `<path d="${pathOf(o.loops, X, Y)}" fill="${METAL}" fill-rule="evenodd" stroke="${INK}" stroke-width="1.2" stroke-linejoin="round"/>`,
828
+ );
829
+ line(X(-W / 2) - 10, Y(0), X(W / 2) + 10, Y(0), THIN, 0.5, '8 3 2 3');
830
+ line(X(0), Y(H / 2) - 10, X(0), Y(-H / 2) + 10, THIN, 0.5, '8 3 2 3');
338
831
  span(X(-W / 2), Y(-H / 2) + 6, X(W / 2), Y(-H / 2) + 6, fig(W), 22);
339
832
  span(X(-W / 2) - 6, Y(H / 2), X(-W / 2) - 6, Y(-H / 2), fig(H), -22);
340
833
  // the slot nearest the top right: its opening and cavity above, its lip and depth at the side
341
- const face = ['top', 'back', 'bottom', 'front'].find((f) => m.faces[f].some((p) => p.slot)), notes = [];
834
+ const face = ['top', 'back', 'bottom', 'front'].find((f) => m.faces[f].some((p) => p.slot)),
835
+ notes = [];
342
836
  if (face && !o.measured) {
343
- const p = m.faces[face].filter((q) => q.slot).at(-1), sl = m.slots[p.slot], top = face === 'top' || face === 'bottom', sign = face === 'top' || face === 'back' ? 1 : -1;
837
+ const p = m.faces[face].filter((q) => q.slot).at(-1),
838
+ sl = m.slots[p.slot],
839
+ top = face === 'top' || face === 'bottom',
840
+ sign = face === 'top' || face === 'back' ? 1 : -1;
344
841
  if (top) {
345
- const y0 = Y(p.at[1]) - sign * 6, d = -sign * 14;
842
+ const y0 = Y(p.at[1]) - sign * 6,
843
+ d = -sign * 14;
346
844
  span(X(p.at[0] - sl.mouth / 2), y0, X(p.at[0] + sl.mouth / 2), y0, fig(sl.mouth), d);
347
- span(X(p.at[0] - sl.cavityWidth / 2), y0 - sign * 24, X(p.at[0] + sl.cavityWidth / 2), y0 - sign * 24, fig(sl.cavityWidth), d);
845
+ span(
846
+ X(p.at[0] - sl.cavityWidth / 2),
847
+ y0 - sign * 24,
848
+ X(p.at[0] + sl.cavityWidth / 2),
849
+ y0 - sign * 24,
850
+ fig(sl.cavityWidth),
851
+ d,
852
+ );
348
853
  const x0 = X(W / 2) + 6;
349
854
  span(x0, Y(p.at[1]), x0, Y(p.at[1] - sign * sl.lip), fig(sl.lip), 16);
350
855
  span(x0 + 44, Y(p.at[1]), x0 + 44, Y(p.at[1] - sign * sl.cavityDepth), fig(sl.cavityDepth), 16);
351
856
  } else {
352
- const x0 = X(p.at[0]) + sign * 6, d = sign * 14;
857
+ const x0 = X(p.at[0]) + sign * 6,
858
+ d = sign * 14;
353
859
  span(x0, Y(p.at[1] + sl.mouth / 2), x0, Y(p.at[1] - sl.mouth / 2), fig(sl.mouth), d);
354
- span(x0 + sign * 30, Y(p.at[1] + sl.cavityWidth / 2), x0 + sign * 30, Y(p.at[1] - sl.cavityWidth / 2), fig(sl.cavityWidth), d);
860
+ span(
861
+ x0 + sign * 30,
862
+ Y(p.at[1] + sl.cavityWidth / 2),
863
+ x0 + sign * 30,
864
+ Y(p.at[1] - sl.cavityWidth / 2),
865
+ fig(sl.cavityWidth),
866
+ d,
867
+ );
355
868
  const y0 = Y(-H / 2) + 6;
356
869
  span(X(p.at[0]), y0 + 40, X(p.at[0] - sign * sl.lip), y0 + 40, fig(sl.lip), 14);
357
870
  span(X(p.at[0]), y0 + 70, X(p.at[0] - sign * sl.cavityDepth), y0 + 70, fig(sl.cavityDepth), 14);
358
871
  }
359
- const families = [...new Set(Object.values(m.faces).flat().map((q) => q.slot ?? 'closed'))];
360
- notes.push(`slot: ${families.join(', ')}${families.length > 1 ? ` (${['top', 'bottom', 'front', 'back'].map((f) => `${f} ${m.faces[f].map((q) => q.slot ?? 'closed').join(' | ')}`).join('; ')})` : ''}: ${fig(sl.mouth)} wide, ${fig(sl.cavityWidth)} under lips ${fig(sl.lip)} thick, ${fig(sl.cavityDepth)} deep, floor ${fig(sl.floorWidth)}`);
872
+ const families = [
873
+ ...new Set(
874
+ Object.values(m.faces)
875
+ .flat()
876
+ .map((q) => q.slot ?? 'closed'),
877
+ ),
878
+ ];
879
+ notes.push(
880
+ `slot: ${families.join(', ')}${families.length > 1 ? ` (${['top', 'bottom', 'front', 'back'].map((f) => `${f} ${m.faces[f].map((q) => q.slot ?? 'closed').join(' | ')}`).join('; ')})` : ''}: ${fig(sl.mouth)} wide, ${fig(sl.cavityWidth)} under lips ${fig(sl.lip)} thick, ${fig(sl.cavityDepth)} deep, floor ${fig(sl.floorWidth)}`,
881
+ );
361
882
  }
362
883
  if (o.measured) notes.push(`drawn from its outline: ${esc(o.source)}`);
363
884
  const kinds = ['cell', 'given', 'corner'].map((w) => m.bores.filter((b) => b.where === w)).filter((l) => l.length);
364
- for (const list of kinds) notes.push(`${list.length} × ${list[0].where === 'corner' ? 'corner hole' : 'bore'} Ø${fig(list[0].diameter)}${list[0].thread ? `, taps ${esc(list[0].thread)}${list[0].tapDrill ? ` (tap drill Ø${fig(list[0].tapDrill)})` : ''}` : ''}`);
365
- if (m.bores.length) { const b = m.bores.find((q) => q.where !== 'corner') ?? m.bores[0], a = X(b.at[0]) + (b.diameter / 2) * S * 0.7, c = Y(b.at[1]) + (b.diameter / 2) * S * 0.7; line(a, c, a + 26, c + 26, THIN, 0.8); text(a + 30, c + 34, `Ø${fig(b.diameter)}`, 'start'); }
885
+ for (const list of kinds)
886
+ notes.push(
887
+ `${list.length} × ${list[0].where === 'corner' ? 'corner hole' : 'bore'} Ø${fig(list[0].diameter)}${list[0].thread ? `, taps ${esc(list[0].thread)}${list[0].tapDrill ? ` (tap drill Ø${fig(list[0].tapDrill)})` : ''}` : ''}`,
888
+ );
889
+ if (m.bores.length) {
890
+ const b = m.bores.find((q) => q.where !== 'corner') ?? m.bores[0],
891
+ a = X(b.at[0]) + (b.diameter / 2) * S * 0.7,
892
+ c = Y(b.at[1]) + (b.diameter / 2) * S * 0.7;
893
+ line(a, c, a + 26, c + 26, THIN, 0.8);
894
+ text(a + 30, c + 34, `Ø${fig(b.diameter)}`, 'start');
895
+ }
366
896
  if (m.cornerRadius) text(X(W / 2) + 8, Y(H / 2) - 8, `R${fig(m.cornerRadius)}`, 'start', 11);
367
897
  if (m.wall) notes.push(`wall ${fig(m.wall)}`);
368
898
  if (m.hollows.length) notes.push(`${m.hollows.length} × corner hollow ${fig(m.hollows[0].width)} square`);
369
899
  if (m.chambers.length) notes.push(`${m.chambers.length} × hollow between cells, ${fig(m.chambers[0].width)} wide`);
370
- notes.push(`${m.family}${m.cells[0] * m.cells[1] > 1 ? `, ${m.cells[0]} × ${m.cells[1]} cells of ${fig(m.pitch[0])}${m.absent?.length ? ` with ${m.absent.length} not there` : ''}` : ''}${m.material ? `, ${m.material.alloy ? `${esc(m.material.alloy)} (${m.material.name})` : m.material.name}` : ''}`);
371
- if (m.supply.lengths.length || m.supply.cutMax) notes.push([m.supply.lengths.length ? `sold as ${m.supply.lengths.map(fig).join(', ')}` : '', m.supply.cutMax ? `cut ${fig(m.supply.cutMin ?? 0)} to ${fig(m.supply.cutMax)}${m.supply.cutTolerance != null ? ` ±${fig(m.supply.cutTolerance)}` : ''}` : '', m.supply.straightness != null ? `straight within ${fig(m.supply.straightness)} mm/m` : '', m.supply.twist != null ? `twist within ${fig(m.supply.twist)}°/m` : ''].filter(Boolean).join('; '));
900
+ notes.push(
901
+ `${m.family}${m.cells[0] * m.cells[1] > 1 ? `, ${m.cells[0]} × ${m.cells[1]} cells of ${fig(m.pitch[0])}${m.absent?.length ? ` with ${m.absent.length} not there` : ''}` : ''}${m.material ? `, ${m.material.alloy ? `${esc(m.material.alloy)} (${m.material.name})` : m.material.name}` : ''}`,
902
+ );
903
+ if (m.supply.lengths.length || m.supply.cutMax)
904
+ notes.push(
905
+ [
906
+ m.supply.lengths.length ? `sold as ${m.supply.lengths.map(fig).join(', ')}` : '',
907
+ m.supply.cutMax
908
+ ? `cut ${fig(m.supply.cutMin ?? 0)} to ${fig(m.supply.cutMax)}${m.supply.cutTolerance != null ? ` ±${fig(m.supply.cutTolerance)}` : ''}`
909
+ : '',
910
+ m.supply.straightness != null ? `straight within ${fig(m.supply.straightness)} mm/m` : '',
911
+ m.supply.twist != null ? `twist within ${fig(m.supply.twist)}°/m` : '',
912
+ ]
913
+ .filter(Boolean)
914
+ .join('; '),
915
+ );
372
916
  // the table: what the sheet says, what the outline comes to
373
- const rows = [['area, mm²', 'area', s.area], ['second moment about x, mm⁴', 'inertiaX', s.inertiaX], ['second moment about y, mm⁴', 'inertiaY', s.inertiaY], ['torsion constant, mm⁴', 'torsion', s.torsion], ['mass, kg/m', 'massPerMetre', s.massPerMetre]];
374
- const ty = Y(-H / 2) + 120, tx = 40, col = [0, 230, 330, 440];
375
- ['', 'sheet', o.measured ? 'measured' : 'drawn', 'difference'].forEach((t, i) => text(tx + col[i], ty, t, i ? 'end' : 'start', 11));
917
+ const rows = [
918
+ ['area, mm²', 'area', s.area],
919
+ ['second moment about x, mm⁴', 'inertiaX', s.inertiaX],
920
+ ['second moment about y, mm⁴', 'inertiaY', s.inertiaY],
921
+ ['torsion constant, mm⁴', 'torsion', s.torsion],
922
+ ['mass, kg/m', 'massPerMetre', s.massPerMetre],
923
+ ];
924
+ const ty = Y(-H / 2) + 120,
925
+ tx = 40,
926
+ col = [0, 230, 330, 440];
927
+ ['', 'sheet', o.measured ? 'measured' : 'drawn', 'difference'].forEach((t, i) =>
928
+ text(tx + col[i], ty, t, i ? 'end' : 'start', 11),
929
+ );
376
930
  line(tx, ty + 6, tx + 450, ty + 6, THIN, 0.6);
377
- rows.forEach(([label, k, got], i) => { const y = ty + 24 + i * 18, c = s.sheet[k]; text(tx, y, label, 'start', 11); text(tx + col[1], y, m.sheet[k] != null ? sig(m.sheet[k]) : 'not given', 'end', 11); text(tx + col[2], y, got != null ? sig(got) : 'no material', 'end', 11); text(tx + col[3], y, c ? `${c.difference >= 0 ? '+' : ''}${(c.difference * 100).toFixed(1)}%` : '', 'end', 11); });
931
+ rows.forEach(([label, k, got], i) => {
932
+ const y = ty + 24 + i * 18,
933
+ c = s.sheet[k];
934
+ text(tx, y, label, 'start', 11);
935
+ text(tx + col[1], y, m.sheet[k] != null ? sig(m.sheet[k]) : 'not given', 'end', 11);
936
+ text(tx + col[2], y, got != null ? sig(got) : 'no material', 'end', 11);
937
+ text(tx + col[3], y, c ? `${c.difference >= 0 ? '+' : ''}${(c.difference * 100).toFixed(1)}%` : '', 'end', 11);
938
+ });
378
939
  const ny = ty + 24 + rows.length * 18 + 14;
379
940
  notes.forEach((t, i) => text(tx, ny + i * 17, t, 'start', 11));
380
941
  return sheet(set, pens, sheetW, ny + notes.length * 17 - 44);
@@ -382,30 +943,69 @@ function profileDrawing(set, g) {
382
943
 
383
944
  // A slot cut into a block of metal, every figure of its family dimensioned
384
945
  function slotDrawing(set, g) {
385
- const sl = slotModel(set, {}, g), block = sl.cavityWidth + 8, deep = sl.cavityDepth + 4, S = Math.min(30, 380 / block), W = block * S + 300, x0 = 110 + (block * S) / 2, y0 = 110, X = (u) => x0 + u * S, Y = (v) => y0 + v * S;
386
- const pens = pen(), { out, line, text, span } = pens, pts = [[-block / 2, 0], ...slotPath(sl), [block / 2, 0], [block / 2, deep], [-block / 2, deep]];
387
- out.push(`<path d="M ${pts.map(([u, v]) => `${fig(X(u))} ${fig(Y(v))}`).join(' L ')} Z" fill="${METAL}" stroke="${INK}" stroke-width="1.2" stroke-linejoin="round"/>`);
946
+ const sl = slotModel(set, {}, g),
947
+ block = sl.cavityWidth + 8,
948
+ deep = sl.cavityDepth + 4,
949
+ S = Math.min(30, 380 / block),
950
+ W = block * S + 300,
951
+ x0 = 110 + (block * S) / 2,
952
+ y0 = 110,
953
+ X = (u) => x0 + u * S,
954
+ Y = (v) => y0 + v * S;
955
+ const pens = pen(),
956
+ { out, line, text, span } = pens,
957
+ pts = [[-block / 2, 0], ...slotPath(sl), [block / 2, 0], [block / 2, deep], [-block / 2, deep]];
958
+ out.push(
959
+ `<path d="M ${pts.map(([u, v]) => `${fig(X(u))} ${fig(Y(v))}`).join(' L ')} Z" fill="${METAL}" stroke="${INK}" stroke-width="1.2" stroke-linejoin="round"/>`,
960
+ );
388
961
  line(X(0), Y(0) - 14, X(0), Y(deep) + 10, THIN, 0.5, '8 3 2 3');
389
962
  span(X(-sl.opening / 2), Y(0) - 6, X(sl.opening / 2), Y(0) - 6, fig(sl.opening), -14);
390
- if (sl.trackWidth) span(X(-sl.trackWidth / 2), Y(0) - 34, X(sl.trackWidth / 2), Y(0) - 34, `track ${fig(sl.trackWidth)}`, -14);
963
+ if (sl.trackWidth)
964
+ span(X(-sl.trackWidth / 2), Y(0) - 34, X(sl.trackWidth / 2), Y(0) - 34, `track ${fig(sl.trackWidth)}`, -14);
391
965
  span(X(-sl.cavityWidth / 2), Y(deep) + 6, X(sl.cavityWidth / 2), Y(deep) + 6, fig(sl.cavityWidth), 16);
392
- if (sl.floorWidth < sl.cavityWidth) span(X(-sl.floorWidth / 2), Y(deep) + 46, X(sl.floorWidth / 2), Y(deep) + 46, `floor ${fig(sl.floorWidth)}`, 16);
966
+ if (sl.floorWidth < sl.cavityWidth)
967
+ span(X(-sl.floorWidth / 2), Y(deep) + 46, X(sl.floorWidth / 2), Y(deep) + 46, `floor ${fig(sl.floorWidth)}`, 16);
393
968
  span(X(block / 2) + 6, Y(0), X(block / 2) + 6, Y(sl.lip), fig(sl.lip), 16);
394
969
  span(X(block / 2) + 56, Y(0), X(block / 2) + 56, Y(sl.cavityDepth), fig(sl.cavityDepth), 16);
395
- const notes = [`opening ${fig(sl.opening)}, lip ${fig(sl.lip)}${sl.lipAngle ? ` sloping ${fig(sl.lipAngle)}°` : ''}, ${fig(sl.cavityWidth)} wide under the lips, ${fig(sl.cavityDepth)} deep`, sl.floorWidth < sl.cavityWidth ? `walls straight to ${fig(sl.straight)} below the face, then flanks at ${fig(sl.flankAngle)}° to a floor of ${fig(sl.floorWidth)}` : 'straight walls', sl.trackWidth ? `V mouth ${fig(sl.trackWidth)} across at ${fig(sl.trackAngle)}°` : '', `takes the nuts of ${esc(sl.nutFamily)}`].filter(Boolean);
396
- const ny = Y(deep) + 110; notes.forEach((t, i) => text(40, ny + i * 17, t, 'start', 11));
970
+ const notes = [
971
+ `opening ${fig(sl.opening)}, lip ${fig(sl.lip)}${sl.lipAngle ? ` sloping ${fig(sl.lipAngle)}°` : ''}, ${fig(sl.cavityWidth)} wide under the lips, ${fig(sl.cavityDepth)} deep`,
972
+ sl.floorWidth < sl.cavityWidth
973
+ ? `walls straight to ${fig(sl.straight)} below the face, then flanks at ${fig(sl.flankAngle)}° to a floor of ${fig(sl.floorWidth)}`
974
+ : 'straight walls',
975
+ sl.trackWidth ? `V mouth ${fig(sl.trackWidth)} across at ${fig(sl.trackAngle)}°` : '',
976
+ `takes the nuts of ${esc(sl.nutFamily)}`,
977
+ ].filter(Boolean);
978
+ const ny = Y(deep) + 110;
979
+ notes.forEach((t, i) => text(40, ny + i * 17, t, 'start', 11));
397
980
  return sheet(set, pens, Math.max(W, 620), ny + notes.length * 17 - 44);
398
981
  }
399
982
 
400
983
  // A slot nut from above and from the side
401
984
  function nutDrawing(set) {
402
- const n = (k) => (typeof set.rules[k]?.value === 'number' ? set.rules[k].value : 0), says = (k) => String(set.rules[k]?.value ?? ''), L = n('length'), w = n('width'), h = n('height'), d = parseFloat(says('thread').replace(/^[^0-9]*/, '')) || 0;
403
- const S = Math.min(24, 260 / Math.max(L, w, 1)), pens = pen(), { line, circle, rect, text, span } = pens, x0 = 90, y0 = 100;
404
- rect(x0, y0, L * S, w * S, METAL); if (d) circle(x0 + (L * S) / 2, y0 + (w * S) / 2, (d / 2) * S, '#fff');
405
- span(x0, y0 + w * S + 6, x0 + L * S, y0 + w * S + 6, fig(L), 16); span(x0 + L * S + 6, y0, x0 + L * S + 6, y0 + w * S, fig(w), 16);
406
- const y1 = y0 + w * S + 80; rect(x0, y1, L * S, h * S, METAL); span(x0 + L * S + 6, y1, x0 + L * S + 6, y1 + h * S, fig(h), 16);
985
+ const n = (k) => (typeof set.rules[k]?.value === 'number' ? set.rules[k].value : 0),
986
+ says = (k) => String(set.rules[k]?.value ?? ''),
987
+ L = n('length'),
988
+ w = n('width'),
989
+ h = n('height'),
990
+ d = parseFloat(says('thread').replace(/^[^0-9]*/, '')) || 0;
991
+ const S = Math.min(24, 260 / Math.max(L, w, 1)),
992
+ pens = pen(),
993
+ { line, circle, rect, text, span } = pens,
994
+ x0 = 90,
995
+ y0 = 100;
996
+ rect(x0, y0, L * S, w * S, METAL);
997
+ if (d) circle(x0 + (L * S) / 2, y0 + (w * S) / 2, (d / 2) * S, '#fff');
998
+ span(x0, y0 + w * S + 6, x0 + L * S, y0 + w * S + 6, fig(L), 16);
999
+ span(x0 + L * S + 6, y0, x0 + L * S + 6, y0 + w * S, fig(w), 16);
1000
+ const y1 = y0 + w * S + 80;
1001
+ rect(x0, y1, L * S, h * S, METAL);
1002
+ span(x0 + L * S + 6, y1, x0 + L * S + 6, y1 + h * S, fig(h), 16);
407
1003
  line(x0 + (L * S) / 2, y0 - 10, x0 + (L * S) / 2, y1 + h * S + 10, THIN, 0.5, '8 3 2 3');
408
- const ny = y1 + h * S + 50; [`${esc(says('nut_kind'))} nut, ${esc(says('thread'))}, for ${esc(says('slot'))}`, says('nut_entry') === 'end' ? 'goes in from an open end of the slot' : 'goes in anywhere along the slot'].forEach((t, i) => text(40, ny + i * 17, t, 'start', 11));
1004
+ const ny = y1 + h * S + 50;
1005
+ [
1006
+ `${esc(says('nut_kind'))} nut, ${esc(says('thread'))}, for ${esc(says('slot'))}`,
1007
+ says('nut_entry') === 'end' ? 'goes in from an open end of the slot' : 'goes in anywhere along the slot',
1008
+ ].forEach((t, i) => text(40, ny + i * 17, t, 'start', 11));
409
1009
  return sheet(set, pens, Math.max(L * S + 260, 520), ny - 10);
410
1010
  }
411
1011
  const esc = (t) => String(t).replace(/&/g, '&amp;').replace(/</g, '&lt;');
@@ -420,75 +1020,223 @@ export function drawing(set, vocab, g = { load: () => undefined, problems: [] })
420
1020
  const v = (k) => set.rules[k]?.value ?? 0;
421
1021
  if (set.part === 'leadscrew') return leadScrewDrawing(set);
422
1022
  if (set.part === 'belt') return beltDrawing(set);
423
- if (set.part === 'linear_bearing') return roundDrawing(set, { D: v('outer_diameter'), d: v('bore'), L: v('length'), notes: [`linear bearing: ${fig(v('dynamic_rating'))} N dynamic, ${fig(v('static_rating'))} N static`] });
424
- if (set.part === 'nut') { return roundDrawing(set, { D: v('body_diameter'), d: v('diameter'), L: v('length'), flange: { D: v('flange_diameter'), w: v('flange_width'), at: v('flange_offset') }, circle: { D: v('hole_circle'), count: v('hole_count'), hole: v('mount_hole_diameter') || 3.5 }, notes: [`${set.rules.thread?.value ?? ''}, ${set.rules.material?.value ?? ''}, lead ${fig(v('lead'))}`, `${fig(v('hole_count'))} × Ø${fig(v('mount_hole_diameter'))} on Ø${fig(v('hole_circle'))}`] }); }
425
- if (set.part === 'coupler') return roundDrawing(set, { D: v('outer_diameter'), L: v('length'), bores: [v('bore_a'), v('bore_b')], d: 0, notes: [`bores Ø${fig(v('bore_a'))} and Ø${fig(v('bore_b'))}`, String(set.rules.style?.value ?? '')] });
426
- if (set.part === 'pulley' || set.part === 'idler') return roundDrawing(set, { D: v('outer_diameter'), d: v('bore'), L: v('body_width'), pitchD: v('pitch_diameter'), notes: [set.part === 'pulley' ? `${fig(v('teeth'))} teeth, pitch circle Ø${fig(v('pitch_diameter'))} (thin), across the teeth Ø${fig(v('tooth_diameter'))}` : `${set.rules.toothed?.value === 'yes' ? `${fig(v('teeth'))} teeth` : 'smooth'}, for ${fig(v('belt_width'))} mm belt`, set.part === 'pulley' ? `for ${fig(v('belt_width'))} mm belt` : ''] });
427
- if (set.part === 'rod') return roundDrawing(set, { D: v('diameter'), L: 40, notes: [`${String(set.rules.tolerance?.value ?? '')}; ${String(set.rules.hardness?.value ?? '')}`] });
428
- const get = (k) => { const r = set.rules[set.interface?.[k] ?? k]; return r?.value; }, n = (k, d = 0) => { const x = get(k); return typeof x === 'number' ? x : d; };
429
- if (!set.part && !Object.keys(set.interface || {}).some((k) => k.startsWith('body_'))) throw new Error(`rule set "${set.name}" doesn't say what shape it is (no body_ names in it, or "part", or "interface"): there's nothing to draw`);
430
- const shape = get('body_shape') ?? 'box', round = shape === 'round', w = round ? n('body_diameter') : n('body_width'), d = round ? w : shape === 'square' ? w : n('body_depth', n('body_width'));
431
- const tabs = n('mount_tab_length'), off = n('boss_offset'), cx = tabs ? -off : 0, cy = tabs ? 0 : -off; // the body's centre, from the shaft
432
- const spacing = n('mount_hole_spacing'), pattern = get('mount_pattern'), hole = n('mount_hole_diameter') || (parseFloat(String(get('mount_hole_thread') ?? '').slice(1)) || 2);
433
- const holes = !spacing ? [] : pattern === 'square' ? [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([a, b]) => [cx + (a * spacing) / 2, cy + (b * spacing) / 2]) : [[cx - spacing / 2, cy], [cx + spacing / 2, cy]];
434
- const earR = n('mount_ear_radius'), reach = Math.max(w / 2, d / 2, spacing / 2 + (earR || hole), tabs / 2) + 2, shaftD = n('shaft_diameter'), bossD = n('boss_diameter');
435
- const L = n('body_length'), top = n('body_top'), bossH = n('boss_height'), shaftL = n('shaft_length'), flat = n('shaft_flat_length'), flats = n('shaft_flats'), across = n('shaft_flat_across');
1023
+ if (set.part === 'linear_bearing')
1024
+ return roundDrawing(set, {
1025
+ D: v('outer_diameter'),
1026
+ d: v('bore'),
1027
+ L: v('length'),
1028
+ notes: [`linear bearing: ${fig(v('dynamic_rating'))} N dynamic, ${fig(v('static_rating'))} N static`],
1029
+ });
1030
+ if (set.part === 'nut') {
1031
+ return roundDrawing(set, {
1032
+ D: v('body_diameter'),
1033
+ d: v('diameter'),
1034
+ L: v('length'),
1035
+ flange: { D: v('flange_diameter'), w: v('flange_width'), at: v('flange_offset') },
1036
+ circle: { D: v('hole_circle'), count: v('hole_count'), hole: v('mount_hole_diameter') || 3.5 },
1037
+ notes: [
1038
+ `${set.rules.thread?.value ?? ''}, ${set.rules.material?.value ?? ''}, lead ${fig(v('lead'))}`,
1039
+ `${fig(v('hole_count'))} × Ø${fig(v('mount_hole_diameter'))} on Ø${fig(v('hole_circle'))}`,
1040
+ ],
1041
+ });
1042
+ }
1043
+ if (set.part === 'coupler')
1044
+ return roundDrawing(set, {
1045
+ D: v('outer_diameter'),
1046
+ L: v('length'),
1047
+ bores: [v('bore_a'), v('bore_b')],
1048
+ d: 0,
1049
+ notes: [`bores Ø${fig(v('bore_a'))} and Ø${fig(v('bore_b'))}`, String(set.rules.style?.value ?? '')],
1050
+ });
1051
+ if (set.part === 'pulley' || set.part === 'idler')
1052
+ return roundDrawing(set, {
1053
+ D: v('outer_diameter'),
1054
+ d: v('bore'),
1055
+ L: v('body_width'),
1056
+ pitchD: v('pitch_diameter'),
1057
+ notes: [
1058
+ set.part === 'pulley'
1059
+ ? `${fig(v('teeth'))} teeth, pitch circle Ø${fig(v('pitch_diameter'))} (thin), across the teeth Ø${fig(v('tooth_diameter'))}`
1060
+ : `${set.rules.toothed?.value === 'yes' ? `${fig(v('teeth'))} teeth` : 'smooth'}, for ${fig(v('belt_width'))} mm belt`,
1061
+ set.part === 'pulley' ? `for ${fig(v('belt_width'))} mm belt` : '',
1062
+ ],
1063
+ });
1064
+ if (set.part === 'rod')
1065
+ return roundDrawing(set, {
1066
+ D: v('diameter'),
1067
+ L: 40,
1068
+ notes: [`${String(set.rules.tolerance?.value ?? '')}; ${String(set.rules.hardness?.value ?? '')}`],
1069
+ });
1070
+ const get = (k) => {
1071
+ const r = set.rules[set.interface?.[k] ?? k];
1072
+ return r?.value;
1073
+ },
1074
+ n = (k, d = 0) => {
1075
+ const x = get(k);
1076
+ return typeof x === 'number' ? x : d;
1077
+ };
1078
+ if (!set.part && !Object.keys(set.interface || {}).some((k) => k.startsWith('body_')))
1079
+ throw new Error(
1080
+ `rule set "${set.name}" doesn't say what shape it is (no body_ names in it, or "part", or "interface"): there's nothing to draw`,
1081
+ );
1082
+ const shape = get('body_shape') ?? 'box',
1083
+ round = shape === 'round',
1084
+ w = round ? n('body_diameter') : n('body_width'),
1085
+ d = round ? w : shape === 'square' ? w : n('body_depth', n('body_width'));
1086
+ const tabs = n('mount_tab_length'),
1087
+ off = n('boss_offset'),
1088
+ cx = tabs ? -off : 0,
1089
+ cy = tabs ? 0 : -off; // the body's centre, from the shaft
1090
+ const spacing = n('mount_hole_spacing'),
1091
+ pattern = get('mount_pattern'),
1092
+ hole = n('mount_hole_diameter') || parseFloat(String(get('mount_hole_thread') ?? '').slice(1)) || 2;
1093
+ const holes = !spacing
1094
+ ? []
1095
+ : pattern === 'square'
1096
+ ? [
1097
+ [-1, -1],
1098
+ [1, -1],
1099
+ [1, 1],
1100
+ [-1, 1],
1101
+ ].map(([a, b]) => [cx + (a * spacing) / 2, cy + (b * spacing) / 2])
1102
+ : [
1103
+ [cx - spacing / 2, cy],
1104
+ [cx + spacing / 2, cy],
1105
+ ];
1106
+ const earR = n('mount_ear_radius'),
1107
+ reach = Math.max(w / 2, d / 2, spacing / 2 + (earR || hole), tabs / 2) + 2,
1108
+ shaftD = n('shaft_diameter'),
1109
+ bossD = n('boss_diameter');
1110
+ const L = n('body_length'),
1111
+ top = n('body_top'),
1112
+ bossH = n('boss_height'),
1113
+ shaftL = n('shaft_length'),
1114
+ flat = n('shaft_flat_length'),
1115
+ flats = n('shaft_flats'),
1116
+ across = n('shaft_flat_across');
436
1117
  // scaled so a small part fills the sheet as a large one does
437
- const scale = 300 / (2 * reach + Math.max(L + top, shaftL + L, 10)) / 1.4, S = Math.max(3, Math.min(12, scale));
438
- const W = 2 * reach * S + (L + Math.max(shaftL, top + bossH) + 8) * S + 200, H = Math.max(2 * reach * S + 150, 280);
439
- const fx = reach * S + 70, fy = H / 2 + 8, X = (x) => fx + x * S, Y = (y) => fy - y * S; // the face view, shaft at the origin
440
- const sx = fx + reach * S + 90 + L * S, SX = (z) => sx + z * S, SY = (y) => fy - y * S; // the side view: z along the sheet, the mounting face at z = 0
441
- const pens = pen(), { out, line, circle, rect, text, span } = pens;
1118
+ const scale = 300 / (2 * reach + Math.max(L + top, shaftL + L, 10)) / 1.4,
1119
+ S = Math.max(3, Math.min(12, scale));
1120
+ const W = 2 * reach * S + (L + Math.max(shaftL, top + bossH) + 8) * S + 200,
1121
+ H = Math.max(2 * reach * S + 150, 280);
1122
+ const fx = reach * S + 70,
1123
+ fy = H / 2 + 8,
1124
+ X = (x) => fx + x * S,
1125
+ Y = (y) => fy - y * S; // the face view, shaft at the origin
1126
+ const sx = fx + reach * S + 90 + L * S,
1127
+ SX = (z) => sx + z * S,
1128
+ SY = (y) => fy - y * S; // the side view: z along the sheet, the mounting face at z = 0
1129
+ const pens = pen(),
1130
+ { out, line, circle, rect, text, span } = pens;
442
1131
  // ---- the face, from the shaft's end ----
443
1132
  if (tabs) rect(X(cx - tabs / 2), Y(cy + d / 2), tabs * S, d * S, '#f6f4ee');
444
1133
  for (const [hx, hy] of earR ? holes : []) circle(X(hx), Y(hy), earR * S, '#f6f4ee');
445
- if (shape === 'square') { const c = n('body_corner'), h = w / 2; const p = [[-h + c, -h], [h - c, -h], [h, -h + c], [h, h - c], [h - c, h], [-h + c, h], [-h, h - c], [-h, -h + c]].map(([a, b]) => `${fig(X(cx + a))},${fig(Y(cy + b))}`).join(' '); out.push(`<polygon points="${p}" fill="${FILL}" stroke="${INK}" stroke-width="1.2"/>`); }
446
- else if (round) circle(X(cx), Y(cy), (w / 2) * S, FILL); else rect(X(cx - w / 2), Y(cy + d / 2), w * S, d * S);
1134
+ if (shape === 'square') {
1135
+ const c = n('body_corner'),
1136
+ h = w / 2;
1137
+ const p = [
1138
+ [-h + c, -h],
1139
+ [h - c, -h],
1140
+ [h, -h + c],
1141
+ [h, h - c],
1142
+ [h - c, h],
1143
+ [-h + c, h],
1144
+ [-h, h - c],
1145
+ [-h, -h + c],
1146
+ ]
1147
+ .map(([a, b]) => `${fig(X(cx + a))},${fig(Y(cy + b))}`)
1148
+ .join(' ');
1149
+ out.push(`<polygon points="${p}" fill="${FILL}" stroke="${INK}" stroke-width="1.2"/>`);
1150
+ } else if (round) circle(X(cx), Y(cy), (w / 2) * S, FILL);
1151
+ else rect(X(cx - w / 2), Y(cy + d / 2), w * S, d * S);
447
1152
  if (bossD) circle(X(0), Y(0), (bossD / 2) * S, '#ddd9cf');
448
1153
  if (shaftD) circle(X(0), Y(0), (shaftD / 2) * S, METAL);
449
- if (flats && across) { const a = flats === 2 ? across / 2 : across - shaftD / 2, c = Math.sqrt(Math.max(0, (shaftD / 2) ** 2 - a ** 2)); line(X(-c), Y(a), X(c), Y(a), INK, 1.4); if (flats === 2) line(X(-c), Y(-a), X(c), Y(-a), INK, 1.4); }
1154
+ if (flats && across) {
1155
+ const a = flats === 2 ? across / 2 : across - shaftD / 2,
1156
+ c = Math.sqrt(Math.max(0, (shaftD / 2) ** 2 - a ** 2));
1157
+ line(X(-c), Y(a), X(c), Y(a), INK, 1.4);
1158
+ if (flats === 2) line(X(-c), Y(-a), X(c), Y(-a), INK, 1.4);
1159
+ }
450
1160
  for (const [hx, hy] of holes) circle(X(hx), Y(hy), (hole / 2) * S, '#fff');
451
- line(X(-reach), Y(0), X(reach), Y(0), THIN, 0.5, '8 3 2 3'); line(X(0), Y(-reach), X(0), Y(reach), THIN, 0.5, '8 3 2 3');
452
- const bottom = Y(Math.min(cy - d / 2, -reach + 2)), topY = Y(Math.max(cy + d / 2, 0));
1161
+ line(X(-reach), Y(0), X(reach), Y(0), THIN, 0.5, '8 3 2 3');
1162
+ line(X(0), Y(-reach), X(0), Y(reach), THIN, 0.5, '8 3 2 3');
1163
+ const bottom = Y(Math.min(cy - d / 2, -reach + 2)),
1164
+ topY = Y(Math.max(cy + d / 2, 0));
453
1165
  if (!round && !tabs) span(X(cx - w / 2), bottom, X(cx + w / 2), bottom, `${fig(w)}`, 18);
454
1166
  if (round) span(X(cx - w / 2), bottom, X(cx + w / 2), bottom, `Ø${fig(w)}`, 18);
455
1167
  if (tabs) span(X(cx - tabs / 2), bottom, X(cx + tabs / 2), bottom, `tabs ${fig(tabs)}`, 18);
456
1168
  if (spacing) span(X(holes[0][0]), bottom, X(holes[1][0]), bottom, `holes ${fig(spacing)}`, 40);
457
1169
  if (bossD) span(X(-bossD / 2), topY, X(bossD / 2), topY, `boss Ø${fig(bossD)}`, -14);
458
- if (off) { text(X(reach), Y(reach) + 2, `shaft ${fig(off)} from centre`, 'end'); }
459
- const thread = get('mount_hole_thread'), holeNote = thread ? `${holes.length} × ${thread}${n('mount_hole_depth') ? `, ${fig(n('mount_hole_depth'))} deep` : ''}` : hole ? `${holes.length} × Ø${fig(hole)}` : '';
1170
+ if (off) {
1171
+ text(X(reach), Y(reach) + 2, `shaft ${fig(off)} from centre`, 'end');
1172
+ }
1173
+ const thread = get('mount_hole_thread'),
1174
+ holeNote = thread
1175
+ ? `${holes.length} × ${thread}${n('mount_hole_depth') ? `, ${fig(n('mount_hole_depth'))} deep` : ''}`
1176
+ : hole
1177
+ ? `${holes.length} × Ø${fig(hole)}`
1178
+ : '';
460
1179
  if (holeNote) text(fx, bottom + 78, holeNote);
461
1180
  // ---- the side, shaft to the right ----
462
1181
  const halfH = (d / 2) * S;
463
1182
  if (L) rect(SX(-L), SY(cy + d / 2), L * S, d * S);
464
1183
  if (top) rect(SX(0), SY(cy + d / 2), top * S, d * S);
465
- const bossAt = top; if (bossH) rect(SX(bossAt), SY(bossD / 2), bossH * S, bossD * S, '#ddd9cf');
1184
+ const bossAt = top;
1185
+ if (bossH) rect(SX(bossAt), SY(bossD / 2), bossH * S, bossD * S, '#ddd9cf');
466
1186
  if (shaftL) rect(SX(bossAt), SY(shaftD / 2), (shaftL + (top ? bossH : 0)) * S, shaftD * S, METAL);
467
- if (flat) { const tip = bossAt + (top ? bossH : 0) + shaftL; const a = flats === 2 ? across / 2 : across - shaftD / 2; line(SX(tip - flat), SY(a), SX(tip), SY(a), INK, 1.2); if (flats === 2) line(SX(tip - flat), SY(-a), SX(tip), SY(-a), INK, 1.2); }
1187
+ if (flat) {
1188
+ const tip = bossAt + (top ? bossH : 0) + shaftL;
1189
+ const a = flats === 2 ? across / 2 : across - shaftD / 2;
1190
+ line(SX(tip - flat), SY(a), SX(tip), SY(a), INK, 1.2);
1191
+ if (flats === 2) line(SX(tip - flat), SY(-a), SX(tip), SY(-a), INK, 1.2);
1192
+ }
468
1193
  line(SX(0), SY(reach), SX(0), SY(-reach), THIN, 0.6, '4 3');
469
1194
  text(SX(0), SY(reach) - 6, 'mounting face', 'middle', 10);
470
1195
  const under = SY(cy - d / 2) + halfH * 0 + 6;
471
1196
  if (L) span(SX(-L), under, SX(0), under, `${fig(L)}`, 14);
472
- if (shaftL) span(SX(top + (top ? bossH : 0)), under, SX(top + (top ? bossH : 0) + shaftL), under, `shaft ${fig(shaftL)}`, 36);
473
- if (flat) span(SX(top + (top ? bossH : 0) + shaftL - flat), SY(shaftD / 2) - 4, SX(top + (top ? bossH : 0) + shaftL), SY(shaftD / 2) - 4, `flat ${fig(flat)}`, -14);
1197
+ if (shaftL)
1198
+ span(SX(top + (top ? bossH : 0)), under, SX(top + (top ? bossH : 0) + shaftL), under, `shaft ${fig(shaftL)}`, 36);
1199
+ if (flat)
1200
+ span(
1201
+ SX(top + (top ? bossH : 0) + shaftL - flat),
1202
+ SY(shaftD / 2) - 4,
1203
+ SX(top + (top ? bossH : 0) + shaftL),
1204
+ SY(shaftD / 2) - 4,
1205
+ `flat ${fig(flat)}`,
1206
+ -14,
1207
+ );
474
1208
  if (bossH) text(SX(bossAt + bossH / 2), under + 74, `boss ${fig(bossH)} high`, 'middle', 11);
475
1209
  return sheet(set, pens, W, H);
476
1210
  }
477
1211
 
478
1212
  // ---------- a draft from a datasheet's text ----------
479
- const UNITS = /(-?\d+(?:\.\d+)?)\s*(mm|N\s?m|N\.m|Ncm|N\.cm|kg\s?cm|kgf?\.?cm|V|A|mH|Ω|ohm|rpm|RPM|Hz|g|kg|°)(?![a-zA-Z])/g;
1213
+ const UNITS =
1214
+ /(-?\d+(?:\.\d+)?)\s*(mm|N\s?m|N\.m|Ncm|N\.cm|kg\s?cm|kgf?\.?cm|V|A|mH|Ω|ohm|rpm|RPM|Hz|g|kg|°)(?![a-zA-Z])/g;
480
1215
  // Text drawn in a PDF: its streams unpacked, then the strings shown with Tj and TJ. A datasheet that is a picture has none.
481
1216
  export function pdfText(file) {
482
- const raw = fs.readFileSync(file), latin = raw.toString('latin1'), lines = [];
1217
+ const raw = fs.readFileSync(file),
1218
+ latin = raw.toString('latin1'),
1219
+ lines = [];
483
1220
  for (const m of latin.matchAll(/stream\r?\n/g)) {
484
- const start = m.index + m[0].length, end = latin.indexOf('endstream', start);
1221
+ const start = m.index + m[0].length,
1222
+ end = latin.indexOf('endstream', start);
485
1223
  if (end < 0) continue;
486
1224
  const body = raw.subarray(start, end);
487
- let s; try { s = zlib.inflateSync(body).toString('latin1'); } catch { s = body.toString('latin1'); }
1225
+ let s;
1226
+ try {
1227
+ s = zlib.inflateSync(body).toString('latin1');
1228
+ } catch {
1229
+ s = body.toString('latin1');
1230
+ }
488
1231
  if (!/\b(Tj|TJ)\b/.test(s)) continue;
489
1232
  for (const block of s.matchAll(/BT([\s\S]*?)ET/g)) {
490
- const words = [...block[1].matchAll(/\[((?:[^\]\\]|\\.)*)\]\s*TJ|\(((?:[^()\\]|\\.)*)\)\s*Tj/g)].map((x) => (x[1] != null ? [...x[1].matchAll(/\(((?:[^()\\]|\\.)*)\)/g)].map((y) => y[1]).join('') : x[2]));
491
- const t = words.join(' ').replace(/\\([()\\])/g, '$1').trim();
1233
+ const words = [...block[1].matchAll(/\[((?:[^\]\\]|\\.)*)\]\s*TJ|\(((?:[^()\\]|\\.)*)\)\s*Tj/g)].map((x) =>
1234
+ x[1] != null ? [...x[1].matchAll(/\(((?:[^()\\]|\\.)*)\)/g)].map((y) => y[1]).join('') : x[2],
1235
+ );
1236
+ const t = words
1237
+ .join(' ')
1238
+ .replace(/\\([()\\])/g, '$1')
1239
+ .trim();
492
1240
  if (t) lines.push(t);
493
1241
  }
494
1242
  }
@@ -500,23 +1248,59 @@ export function pdfText(file) {
500
1248
  * for a person to fill from the maker's sheet. @param {string} part @param {string} name @returns {object | null} null for a part with no draft
501
1249
  */
502
1250
  export function draftPart(part, name) {
503
- const v = vocabulary(), fields = v.drafts?.[part];
1251
+ const v = vocabulary(),
1252
+ fields = v.drafts?.[part];
504
1253
  if (!fields) return null;
505
- const stamp = new Date().toISOString().slice(0, 10), rules = {};
506
- for (const [k, value] of Object.entries(fields)) rules[k] = { value, ...(v.fields[k]?.unit != null ? { unit: v.fields[k].unit } : {}), rule: sentence(v.fields[k]?.says ?? k), kind: 'estimate', source: 'DRAFT, not read from a sheet yet: give the sheet, its page and the date you read it', checked: stamp };
507
- return { _doc: `A draft ${part.replace('_', ' ')}: every field the vocabulary has for one, each with a starting value. Put in the figures from the maker's sheet, with the sheet and its page as the source and today's date, and change each kind to spec as you go. Delete what the sheet has no figure for (cad rules check says which a ${part.replace('_', ' ')} needs). Then cad rules check ${name}, and cad rules draw ${name} to hold against the sheet's drawing.`, name, part, rules };
1254
+ const stamp = new Date().toISOString().slice(0, 10),
1255
+ rules = {};
1256
+ for (const [k, value] of Object.entries(fields))
1257
+ rules[k] = {
1258
+ value,
1259
+ ...(v.fields[k]?.unit != null ? { unit: v.fields[k].unit } : {}),
1260
+ rule: sentence(v.fields[k]?.says ?? k),
1261
+ kind: 'estimate',
1262
+ source: 'DRAFT, not read from a sheet yet: give the sheet, its page and the date you read it',
1263
+ checked: stamp,
1264
+ };
1265
+ return {
1266
+ _doc: `A draft ${part.replace('_', ' ')}: every field the vocabulary has for one, each with a starting value. Put in the figures from the maker's sheet, with the sheet and its page as the source and today's date, and change each kind to spec as you go. Delete what the sheet has no figure for (cad rules check says which a ${part.replace('_', ' ')} needs). Then cad rules check ${name}, and cad rules draw ${name} to hold against the sheet's drawing.`,
1267
+ name,
1268
+ part,
1269
+ rules,
1270
+ };
508
1271
  }
509
- const sentence = (t) => { const x = String(t).trim(); return x ? x[0].toUpperCase() + x.slice(1) : x; };
1272
+ const sentence = (t) => {
1273
+ const x = String(t).trim();
1274
+ return x ? x[0].toUpperCase() + x.slice(1) : x;
1275
+ };
510
1276
  export const draftParts = () => Object.keys(vocabulary().drafts || {});
511
1277
 
512
1278
  /** Every figure a datasheet's text gives, as a rule set of estimates for a person to name and check. @returns {{ set: object, found: number }} */
513
1279
  export function draftSet(name, file) {
514
1280
  if (!fs.existsSync(file)) throw new Error(`no file ${file}`);
515
- const lines = pdfText(file), rules = {}, stamp = new Date().toISOString().slice(0, 10), source = path.basename(file);
1281
+ const lines = pdfText(file),
1282
+ rules = {},
1283
+ stamp = new Date().toISOString().slice(0, 10),
1284
+ source = path.basename(file);
516
1285
  let i = 0;
517
- for (const line of lines) for (const m of line.matchAll(UNITS)) {
518
- i += 1;
519
- rules[`figure_${String(i).padStart(3, '0')}`] = { value: Number(m[1]), unit: m[2], rule: `DRAFT: name and check me. From: "${line.slice(0, 120)}"`, kind: 'estimate', source, checked: stamp };
520
- }
521
- return { set: { _doc: `A draft from ${source}: rename each figure from vocabulary.json, delete the ones you don't want, and only then change its kind to spec.`, name, rules }, found: i };
1286
+ for (const line of lines)
1287
+ for (const m of line.matchAll(UNITS)) {
1288
+ i += 1;
1289
+ rules[`figure_${String(i).padStart(3, '0')}`] = {
1290
+ value: Number(m[1]),
1291
+ unit: m[2],
1292
+ rule: `DRAFT: name and check me. From: "${line.slice(0, 120)}"`,
1293
+ kind: 'estimate',
1294
+ source,
1295
+ checked: stamp,
1296
+ };
1297
+ }
1298
+ return {
1299
+ set: {
1300
+ _doc: `A draft from ${source}: rename each figure from vocabulary.json, delete the ones you don't want, and only then change its kind to spec.`,
1301
+ name,
1302
+ rules,
1303
+ },
1304
+ found: i,
1305
+ };
522
1306
  }