bambu-printer-mcp 1.1.91 → 1.1.92
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONTRIBUTORS.md +2 -0
- package/README.md +5 -3
- package/dist/bambu-native.js +1 -1
- package/dist/cad/contracts.js +16 -7
- package/dist/cad/examples.d.ts +2 -1
- package/dist/cad/examples.js +13 -10
- package/dist/cad/serial.d.ts +1 -1
- package/dist/cad/serial.js +4 -6
- package/dist/cad-engine.js +17 -12
- package/dist/index.js +39 -23
- package/dist/printers/bambu.d.ts +6 -0
- package/dist/printers/bambu.js +32 -6
- package/dist/safety/limits.d.ts +6 -0
- package/dist/safety/limits.js +8 -0
- package/dist/safety/print-file.js +2 -2
- package/dist/safety/printer-state.d.ts +4 -0
- package/dist/safety/printer-state.js +14 -1
- package/dist/studio-print-options.d.ts +9 -0
- package/dist/studio-print-options.js +34 -2
- package/package.json +1 -1
- package/src/bambu-native.ts +1 -1
- package/src/cad/contracts.ts +17 -7
- package/src/cad/examples/bag_clip.py +1 -0
- package/src/cad/examples/bistable_clicker.py +1 -0
- package/src/cad/examples/broom_grip.py +61 -0
- package/src/cad/examples/cable_clip.py +1 -0
- package/src/cad/examples/chainmail.py +1 -0
- package/src/cad/examples/desk_clamp_hook.py +91 -0
- package/src/cad/examples/desk_edge_cable_holder.py +55 -0
- package/src/cad/examples/drawer_divider.py +56 -0
- package/src/cad/examples/hinged_box.py +1 -0
- package/src/cad/examples/knurled_knob.py +1 -0
- package/src/cad/examples/loft_handle.py +1 -0
- package/src/cad/examples/organizer_tray.py +41 -0
- package/src/cad/examples/phone_stand.py +1 -0
- package/src/cad/examples/plant_pot.py +53 -0
- package/src/cad/examples/shelf_bracket.py +53 -0
- package/src/cad/examples/swept_hook.py +1 -0
- package/src/cad/examples/threaded_jar.py +1 -0
- package/src/cad/examples/trigger_capo.py +1 -0
- package/src/cad/examples/wall_hook.py +1 -0
- package/src/cad/examples.ts +13 -10
- package/src/cad/geometry.py +6 -0
- package/src/cad/serial.ts +4 -6
- package/src/cad-engine.ts +9 -3
- package/src/index.ts +36 -19
- package/src/printers/bambu.ts +30 -5
- package/src/safety/limits.ts +8 -0
- package/src/safety/print-file.ts +2 -2
- package/src/safety/printer-state.ts +13 -1
- package/src/studio-print-options.ts +33 -2
package/dist/printers/bambu.js
CHANGED
|
@@ -20,7 +20,7 @@ import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, d
|
|
|
20
20
|
import { describeHmsKey, hiddenHmsKeys, hiddenHmsNotices, reportedHmsKey, unchippedNozzles, validatePrinterState, manualHeatingRequirements } from "../safety/printer-state.js";
|
|
21
21
|
import { withPrinterOperation, withPrintSnapshot, uniquePrintName, normalizedRemotePath, cancelPendingPrinterOperations } from "../safety/artifact.js";
|
|
22
22
|
import { RTSP_CAMERA_MODELS, TCP_CAMERA_MODELS } from "./camera-models.js";
|
|
23
|
-
import { resolveStudioPrintOptions, usedNozzleCount } from "../studio-print-options.js";
|
|
23
|
+
import { directPrintOptionReport, resolveStudioPrintOptions, usedNozzleCount } from "../studio-print-options.js";
|
|
24
24
|
import { Client as FTPClient } from "basic-ftp";
|
|
25
25
|
import { uploadBytes } from "./ftp-upload.js";
|
|
26
26
|
import * as mqtt from "mqtt";
|
|
@@ -143,6 +143,19 @@ const MODEL_ID_TO_NAME = {
|
|
|
143
143
|
C13: "X1E",
|
|
144
144
|
};
|
|
145
145
|
const H2_MODEL_NAMES = new Set(["h2", "h2c", "h2d", "h2dpro", "h2d pro", "h2s", "x2d"]);
|
|
146
|
+
/**
|
|
147
|
+
* X1C firmware 01.12.00.00 was seen refusing every FTPS STOR with
|
|
148
|
+
* "553 Could not create file." (card ready and writable, Developer Mode on)
|
|
149
|
+
* while Bambu Studio's networking plug-in still printed. Name that route.
|
|
150
|
+
*/
|
|
151
|
+
export function ftpsRefusalHint(error, model) {
|
|
152
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
153
|
+
if (normalizeModel(model) !== "x1c" || (error?.code !== 553 && !/^553\b/.test(message)))
|
|
154
|
+
return "";
|
|
155
|
+
return ' X1C firmware 01.12.00.00 has been seen refusing every direct FTPS upload this way. ' +
|
|
156
|
+
'Retry with connection_mode: "bambu_native", which uploads through Bambu Studio\'s networking plug-in ' +
|
|
157
|
+
'(on macOS, first run npm run build:native in the package directory; on Linux, bambu-printer-mcp-native-setup).';
|
|
158
|
+
}
|
|
146
159
|
export function assertDirectPrintSupported(model, serial) {
|
|
147
160
|
if (model?.trim().toLowerCase() === "x2d" || serial?.trim().toUpperCase().startsWith("20P")) {
|
|
148
161
|
throw new Error("X2D direct printing is not supported through legacy MQTT/FTPS. Use the native eMMC route via print_3mf (macOS, or Linux with the native helper installed). " +
|
|
@@ -989,12 +1002,13 @@ export class BambuImplementation {
|
|
|
989
1002
|
});
|
|
990
1003
|
const resumeFile = await checkedFile(inspection, options.filePath);
|
|
991
1004
|
// The options Bambu Studio's Send dialog would send; explicit ones win.
|
|
992
|
-
const
|
|
1005
|
+
const caller = {
|
|
993
1006
|
bedLeveling: options.bedLeveling, flowCalibration: options.flowCalibration,
|
|
994
1007
|
vibrationCalibration: options.vibrationCalibration, layerInspect: options.layerInspect,
|
|
995
1008
|
autoBedLeveling: options.autoBedLeveling, autoFlowCali: options.autoFlowCali,
|
|
996
1009
|
autoOffsetCali: options.autoOffsetCali, extruderCaliManualMode: options.extruderCaliManualMode,
|
|
997
|
-
}
|
|
1010
|
+
};
|
|
1011
|
+
const studio = resolveStudioPrintOptions(model, caller, { usedNozzles: usedNozzleCount(inspection) });
|
|
998
1012
|
const projectMetadata = await this.resolveProjectFileMetadata(options.filePath, options.plateIndex, inspection.plateInternalPath);
|
|
999
1013
|
// Send project_file command via bambu-node MQTT (bypasses bambu-js
|
|
1000
1014
|
// hardcoded use_ams=true and missing ams_mapping support)
|
|
@@ -1115,7 +1129,7 @@ export class BambuImplementation {
|
|
|
1115
1129
|
}
|
|
1116
1130
|
catch (error) {
|
|
1117
1131
|
// Nothing has been sent to the printer but (part of) a file, so the print certainly did not start.
|
|
1118
|
-
throw new PrinterRefusal("printer-upload-failed", `The print file did not reach the printer (${error instanceof Error ? error.message : String(error)}). No print was started
|
|
1132
|
+
throw new PrinterRefusal("printer-upload-failed", `The print file did not reach the printer (${error instanceof Error ? error.message : String(error)}). No print was started.${ftpsRefusalHint(error, model)}`);
|
|
1119
1133
|
}
|
|
1120
1134
|
// Uploads can be long. Recheck current state before the command is dispatched.
|
|
1121
1135
|
const dispatchStatus = await this.getSafetyStatus(host, serial, token);
|
|
@@ -1141,6 +1155,7 @@ export class BambuImplementation {
|
|
|
1141
1155
|
const dispatch = await watcher.settled();
|
|
1142
1156
|
return {
|
|
1143
1157
|
status: "success", dispatch, remoteProjectPath,
|
|
1158
|
+
calibration: directPrintOptionReport(caller, studio, {}),
|
|
1144
1159
|
message: dispatch === "started"
|
|
1145
1160
|
? `The printer accepted and started the checked gcode.3mf print: ${options.projectName}`
|
|
1146
1161
|
: `Uploaded the checked gcode.3mf and sent the print command for ${options.projectName}; the printer has not reported starting yet. ` +
|
|
@@ -1215,6 +1230,7 @@ export class BambuImplementation {
|
|
|
1215
1230
|
},
|
|
1216
1231
|
};
|
|
1217
1232
|
}
|
|
1233
|
+
const calibration = directPrintOptionReport(caller, studio, projectFileCmd.print);
|
|
1218
1234
|
const watcher = this.watchDispatch(printer, host, serial, token, dispatchStatus, assertActive);
|
|
1219
1235
|
this.recordFlightDispatch(host, serial, remoteProjectPath, requirements, resumeFile);
|
|
1220
1236
|
markPrintCommandSent();
|
|
@@ -1230,6 +1246,7 @@ export class BambuImplementation {
|
|
|
1230
1246
|
const dispatch = await watcher.settled();
|
|
1231
1247
|
return {
|
|
1232
1248
|
status: "success",
|
|
1249
|
+
calibration,
|
|
1233
1250
|
dispatch,
|
|
1234
1251
|
message: dispatch === "started"
|
|
1235
1252
|
? `The printer accepted and started the checked 3MF print: ${options.projectName}`
|
|
@@ -1789,8 +1806,17 @@ export class BambuImplementation {
|
|
|
1789
1806
|
const destination = path.posix.join(path.posix.dirname(remotePath), uniquePrintName(remotePath));
|
|
1790
1807
|
if (upload)
|
|
1791
1808
|
await upload(snapshot, destination, assertActive);
|
|
1792
|
-
else
|
|
1793
|
-
|
|
1809
|
+
else {
|
|
1810
|
+
try {
|
|
1811
|
+
await this.ftpUpload(host, token, snapshot, `/${destination}`);
|
|
1812
|
+
}
|
|
1813
|
+
catch (error) {
|
|
1814
|
+
const hint = ftpsRefusalHint(error, model);
|
|
1815
|
+
if (hint && error instanceof Error)
|
|
1816
|
+
error.message += hint;
|
|
1817
|
+
throw error;
|
|
1818
|
+
}
|
|
1819
|
+
}
|
|
1794
1820
|
return { status: "success", uploaded: true, remotePath: destination, printRequested: false, inspected: printable };
|
|
1795
1821
|
}));
|
|
1796
1822
|
}
|
package/dist/safety/limits.d.ts
CHANGED
|
@@ -27,6 +27,12 @@ export declare const MACHINE_LIMITS: Readonly<Record<string, {
|
|
|
27
27
|
* (VIRTUAL_TRAY_DEPUTY_ID). The single-nozzle H2S is deliberately absent. */
|
|
28
28
|
export declare const DUAL_NOZZLE_MODELS: ReadonlySet<string>;
|
|
29
29
|
export declare function isDualNozzleModel(model: unknown): boolean;
|
|
30
|
+
/** File models a printer accepts besides its own, keyed by the printer's observed model.
|
|
31
|
+
* A P1P with the enclosure upgrade kit still reports itself as a P1P, while its jobs are sliced with the P1S
|
|
32
|
+
* preset. Bambu Studio sends those jobs: resources/printers/C11.json (P1P) lists C12 (P1S) in compatible_machine.
|
|
33
|
+
* The two models have identical MACHINE_LIMITS, and the file is still checked against the printer's own limits. */
|
|
34
|
+
export declare const ACCEPTED_FILE_MODELS: Readonly<Record<string, ReadonlySet<string>>>;
|
|
35
|
+
export declare function fileModelFitsPrinter(fileModel: string, printerModel: string): boolean;
|
|
30
36
|
export declare function normalizeModel(value: unknown): string | undefined;
|
|
31
37
|
export declare function normalizeMaterial(value: unknown): string | undefined;
|
|
32
38
|
export declare function validateTemperature(component: 'nozzle' | 'bed' | 'chamber', value: unknown, model: string, materials?: string[]): number;
|
package/dist/safety/limits.js
CHANGED
|
@@ -39,6 +39,14 @@ export function isDualNozzleModel(model) {
|
|
|
39
39
|
const normalized = normalizeModel(model);
|
|
40
40
|
return normalized !== undefined && DUAL_NOZZLE_MODELS.has(normalized);
|
|
41
41
|
}
|
|
42
|
+
/** File models a printer accepts besides its own, keyed by the printer's observed model.
|
|
43
|
+
* A P1P with the enclosure upgrade kit still reports itself as a P1P, while its jobs are sliced with the P1S
|
|
44
|
+
* preset. Bambu Studio sends those jobs: resources/printers/C11.json (P1P) lists C12 (P1S) in compatible_machine.
|
|
45
|
+
* The two models have identical MACHINE_LIMITS, and the file is still checked against the printer's own limits. */
|
|
46
|
+
export const ACCEPTED_FILE_MODELS = { p1p: new Set(['p1s']) };
|
|
47
|
+
export function fileModelFitsPrinter(fileModel, printerModel) {
|
|
48
|
+
return fileModel === printerModel || ACCEPTED_FILE_MODELS[printerModel]?.has(fileModel) === true;
|
|
49
|
+
}
|
|
42
50
|
export function normalizeModel(value) {
|
|
43
51
|
if (typeof value !== 'string')
|
|
44
52
|
return undefined;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { readBoundedPrintFile, loadSafe3mfArchive } from './archive.js';
|
|
3
3
|
import { projectFilaments } from "../ams-mapping.js";
|
|
4
|
-
import { MACHINE_LIMITS, isDualNozzleModel, normalizeMaterial, normalizeModel, validateStartupPurgeTemperature, validateTemperature } from './limits.js';
|
|
4
|
+
import { MACHINE_LIMITS, fileModelFitsPrinter, isDualNozzleModel, normalizeMaterial, normalizeModel, validateStartupPurgeTemperature, validateTemperature } from './limits.js';
|
|
5
5
|
const NUMBER = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/;
|
|
6
6
|
const fail = (message) => { throw new Error(`Print safety: ${message}`); };
|
|
7
7
|
function list(value) {
|
|
@@ -292,7 +292,7 @@ export async function inspectPrintFile(filePath, options) {
|
|
|
292
292
|
const metadata = [project, ...headers];
|
|
293
293
|
validateFffJob([...metadata, plate]);
|
|
294
294
|
const declaredModel = consistent(metadataValues(metadata, ['printer_model']), normalizeModel, 'printer model');
|
|
295
|
-
if (declaredModel
|
|
295
|
+
if (!fileModelFitsPrinter(declaredModel, model))
|
|
296
296
|
return fail(`file model ${declaredModel} contradicts requested model ${model}`);
|
|
297
297
|
const nozzleDiameters = consistent(metadataValues(metadata, ['nozzle_diameter']), value => {
|
|
298
298
|
const values = list(value);
|
|
@@ -105,4 +105,8 @@ export type ExternalStorageState = "none" | "normal" | "abnormal" | "readonly";
|
|
|
105
105
|
* (DevStorage.cpp, DeviceManager.cpp parse_home_flag and parse_new_info).
|
|
106
106
|
*/
|
|
107
107
|
export declare function externalStorageState(raw: unknown): ExternalStorageState;
|
|
108
|
+
/** Studio DeviceManager.cpp at 926a7192574b: fun2 bit 0 advertises eMMC printing.
|
|
109
|
+
* Use only a fresh raw report at the caller. Reject malformed flags rather than
|
|
110
|
+
* stripping arbitrary characters as Studio's general-purpose parser does. */
|
|
111
|
+
export declare function internalPrintingSupported(raw: unknown): boolean;
|
|
108
112
|
export {};
|
|
@@ -364,7 +364,7 @@ function trayRange(value, label) {
|
|
|
364
364
|
/** Dual-nozzle printers report one virtual external slot per nozzle, numbered as Bambu
|
|
365
365
|
* Studio does (VIRTUAL_TRAY_MAIN_ID 255 = right/main nozzle, VIRTUAL_TRAY_DEPUTY_ID 254 =
|
|
366
366
|
* left/deputy nozzle), so the requested tray selects its slot. Single-nozzle printers keep
|
|
367
|
-
* requiring exactly one slot
|
|
367
|
+
* requiring exactly one external slot report, then the legacy vt_tray field. */
|
|
368
368
|
function externalTray(raw, trayIndex, model) {
|
|
369
369
|
const slots = raw.vir_slot;
|
|
370
370
|
const dualNozzle = isDualNozzleModel(model);
|
|
@@ -372,6 +372,10 @@ function externalTray(raw, trayIndex, model) {
|
|
|
372
372
|
const selected = slots.filter((slot) => Number(slot?.id) === trayIndex);
|
|
373
373
|
if (selected.length === 1 && (dualNozzle || slots.length === 1))
|
|
374
374
|
return selected[0];
|
|
375
|
+
// X1C firmware 01.12 reports its single external slot as id 255 (ams_id 255, slot 0) while
|
|
376
|
+
// tray_now is 254. One external slot on a single-nozzle printer is unambiguous.
|
|
377
|
+
if (!dualNozzle && slots.length === 1 && [254, 255].includes(Number(slots[0]?.id)) && [254, 255].includes(trayIndex))
|
|
378
|
+
return slots[0];
|
|
375
379
|
if (dualNozzle && selected.length === 0 && slots.length > 0)
|
|
376
380
|
throw new Error(`External spool ${trayIndex} is not in the fresh per-nozzle report; cannot verify the selected material.`);
|
|
377
381
|
if (slots.length > 0)
|
|
@@ -551,3 +555,12 @@ export function externalStorageState(raw) {
|
|
|
551
555
|
}
|
|
552
556
|
return state;
|
|
553
557
|
}
|
|
558
|
+
/** Studio DeviceManager.cpp at 926a7192574b: fun2 bit 0 advertises eMMC printing.
|
|
559
|
+
* Use only a fresh raw report at the caller. Reject malformed flags rather than
|
|
560
|
+
* stripping arbitrary characters as Studio's general-purpose parser does. */
|
|
561
|
+
export function internalPrintingSupported(raw) {
|
|
562
|
+
if (!object(raw) || typeof raw.fun2 !== "string")
|
|
563
|
+
return false;
|
|
564
|
+
const flags = raw.fun2.trim().replace(/^0x/i, "");
|
|
565
|
+
return /^[0-9a-f]+$/i.test(flags) && (parseInt(flags.slice(-1), 16) & 1) === 1;
|
|
566
|
+
}
|
|
@@ -55,3 +55,12 @@ export declare function usedNozzleCount(inspection: {
|
|
|
55
55
|
usedFilamentPositions: number[];
|
|
56
56
|
filamentNozzleIndices?: Array<number | undefined>;
|
|
57
57
|
}): number | undefined;
|
|
58
|
+
/** Report only verified direct-wire fields. A task boolean is not an SDK mode.
|
|
59
|
+
* null means this route does not transmit that option, not off/auto/unknown hardware state. */
|
|
60
|
+
export declare function directPrintOptionReport(caller: CallerPrintOptions, resolved: StudioPrintOptions, packet: Record<string, unknown>): {
|
|
61
|
+
warning?: string | undefined;
|
|
62
|
+
requested: CallerPrintOptions;
|
|
63
|
+
resolved: StudioPrintOptions;
|
|
64
|
+
transmitted: Record<string, number | boolean | null>;
|
|
65
|
+
unsupported: string[];
|
|
66
|
+
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The print options Bambu Studio's Send dialog sends, resolved the way it
|
|
3
|
-
* resolves them,
|
|
4
|
-
*
|
|
3
|
+
* resolves them, for the vendor SDK. Direct routes report which options their verified
|
|
4
|
+
* wire format can carry; this does not establish SDK packet equivalence. Source: Bambu Studio v02.08.02.61 (commit 926a7192574b), the version
|
|
5
5
|
* the hidden-HMS and stage tables are pinned to:
|
|
6
6
|
*
|
|
7
7
|
* - SelectMachine.cpp:3344-3356 `set_print_config(bed_type,
|
|
@@ -177,3 +177,35 @@ export function usedNozzleCount(inspection) {
|
|
|
177
177
|
const nozzles = inspection.usedFilamentPositions.map(position => inspection.filamentNozzleIndices?.[position]).filter((value) => Number.isInteger(value));
|
|
178
178
|
return nozzles.length === inspection.usedFilamentPositions.length && nozzles.length ? new Set(nozzles).size : undefined;
|
|
179
179
|
}
|
|
180
|
+
/** Report only verified direct-wire fields. A task boolean is not an SDK mode.
|
|
181
|
+
* null means this route does not transmit that option, not off/auto/unknown hardware state. */
|
|
182
|
+
export function directPrintOptionReport(caller, resolved, packet) {
|
|
183
|
+
const fields = {
|
|
184
|
+
bedLeveling: ["task_bed_leveling", "bed_leveling"],
|
|
185
|
+
flowCalibration: ["task_flow_cali", "flow_cali"],
|
|
186
|
+
vibrationCalibration: ["task_vibration_cali", "vibration_cali"],
|
|
187
|
+
layerInspect: ["task_layer_inspect", "layer_inspect"],
|
|
188
|
+
autoBedLeveling: ["auto_bed_leveling", "auto_bed_leveling"],
|
|
189
|
+
autoFlowCali: ["auto_flow_cali", "auto_flow_cali"],
|
|
190
|
+
autoOffsetCali: ["auto_offset_cali", "nozzle_offset_cali"],
|
|
191
|
+
extruderCaliManualMode: ["extruder_cali_manual_mode", "extrude_cali_manual_mode"],
|
|
192
|
+
};
|
|
193
|
+
const requested = {};
|
|
194
|
+
const transmitted = {};
|
|
195
|
+
const unsupported = [];
|
|
196
|
+
for (const key of Object.keys(fields)) {
|
|
197
|
+
const [sdk, wire] = fields[key];
|
|
198
|
+
if (caller[key] !== undefined)
|
|
199
|
+
Object.assign(requested, { [key]: caller[key] });
|
|
200
|
+
const value = packet[wire];
|
|
201
|
+
transmitted[sdk] = typeof value === "boolean" || typeof value === "number" ? value : null;
|
|
202
|
+
if (caller[key] !== undefined && transmitted[sdk] === null)
|
|
203
|
+
unsupported.push(key);
|
|
204
|
+
}
|
|
205
|
+
const omitted = Object.keys(transmitted).filter(key => transmitted[key] === null);
|
|
206
|
+
const warning = omitted.length
|
|
207
|
+
? `Direct print options not transmitted: ${omitted.join(", ")}. Task booleans are not equivalent to Studio integer modes.` +
|
|
208
|
+
(unsupported.length ? ` Requested overrides unsupported by this route: ${unsupported.join(", ")}. Use a vendor bridge/native route that supports these options if required.` : "")
|
|
209
|
+
: undefined;
|
|
210
|
+
return { requested, resolved, transmitted, unsupported, ...(warning ? { warning } : {}) };
|
|
211
|
+
}
|
package/package.json
CHANGED
package/src/bambu-native.ts
CHANGED
|
@@ -221,7 +221,7 @@ function isRegularFile(file: string): boolean {
|
|
|
221
221
|
*/
|
|
222
222
|
function resolveNativeInstall(): NativeInstall {
|
|
223
223
|
if (!isBambuNativePlatform()) {
|
|
224
|
-
throw new Error("Bambu native
|
|
224
|
+
throw new Error("Bambu native transport requires macOS or x86-64 Linux and Bambu's networking plug-in.");
|
|
225
225
|
}
|
|
226
226
|
const helper = resolveNativeHelper();
|
|
227
227
|
if (process.platform !== "linux") return { helper, env: {} };
|
package/src/cad/contracts.ts
CHANGED
|
@@ -113,7 +113,7 @@ export const CAD_TOOLS = [
|
|
|
113
113
|
{
|
|
114
114
|
name: "cad_run",
|
|
115
115
|
description:
|
|
116
|
-
"Build parametric CAD headlessly in OS confinement. Read cad_design first: declare literal P = {...} and build() returning a build123d Shape. Supply script OR script_path; parameters overrides saved named values in one call before derived dimensions. Calls wait for the environment’s exclusive execution slot up to their own deadline and report queue_wait_ms. Each call creates a private immutable subfolder under allowed output_dir, never overwriting previous artifacts. The saved .py and .parameters.json are the recovery checkpoint even after cancellation. Returns independently measured geometry, STL/STEP, six orthographic renders, a perspective view and a contact sheet, the closest approach between every pair of solids (bodies), problems,
|
|
116
|
+
"Build parametric CAD headlessly in OS confinement. Read cad_design first: declare literal P = {...} and build() returning a build123d Shape. Supply script OR script_path; parameters overrides saved named values in one call before derived dimensions. Calls wait for the environment’s exclusive execution slot up to their own deadline and report queue_wait_ms. Each call creates a private immutable subfolder under allowed output_dir, never overwriting previous artifacts. The saved .py and .parameters.json are the recovery checkpoint even after cancellation. Returns independently measured geometry, STL/STEP, six orthographic renders, a perspective view and a contact sheet (with next: read the perspective view before the next change), the closest approach between every pair of solids (bodies), problems, what was checked and not checked, and printed: whatever the script wrote with print(), capped at 4000 characters, so a design can report a number it computed; valid means only that the exported geometry is sound, never that the part fits, holds, moves or prints.",
|
|
117
117
|
inputSchema: {
|
|
118
118
|
type: "object" as const,
|
|
119
119
|
properties: {
|
|
@@ -225,6 +225,12 @@ export const CAD_TOOLS = [
|
|
|
225
225
|
checked: { type: "array", items: { type: "string" } },
|
|
226
226
|
not_checked: { type: "array", items: { type: "string" } },
|
|
227
227
|
renders: { type: "object", additionalProperties: { type: "string" } },
|
|
228
|
+
next: { type: "string", description: "What to do before the next change: look at the perspective render." },
|
|
229
|
+
printed: {
|
|
230
|
+
type: "string",
|
|
231
|
+
description:
|
|
232
|
+
"The script's own print() output from this run, capped at 4000 characters (build.log keeps the rest). The script's words, not a measurement by the engine.",
|
|
233
|
+
},
|
|
228
234
|
seconds: { type: "number" },
|
|
229
235
|
},
|
|
230
236
|
[
|
|
@@ -251,7 +257,7 @@ export const CAD_TOOLS = [
|
|
|
251
257
|
{
|
|
252
258
|
name: "cad_examples",
|
|
253
259
|
description:
|
|
254
|
-
"The code engine's cookbook: worked build123d designs from simple to complex, each modelled on the best bought version of the thing, with its concept, published sizes and script. Without arguments, lists them (name, title, the pattern
|
|
260
|
+
"The code engine's cookbook: worked build123d designs from simple to complex, each modelled on the best bought version of the thing, with its concept, published sizes and script. Without arguments, lists them by purpose (name, title, use_for: the requests it suits, the pattern it shows, the product it is modelled on): choose by use_for before choosing a mechanism. With name, returns that example's record and full script to adapt. Read-only; starts no process.",
|
|
255
261
|
inputSchema: {
|
|
256
262
|
type: "object" as const,
|
|
257
263
|
properties: {
|
|
@@ -271,15 +277,17 @@ export const CAD_TOOLS = [
|
|
|
271
277
|
properties: {
|
|
272
278
|
name: { type: "string" },
|
|
273
279
|
title: { type: "string" },
|
|
280
|
+
use_for: { type: "string" },
|
|
274
281
|
pattern: { type: "string" },
|
|
275
282
|
modelled_on: { type: "string" },
|
|
276
283
|
},
|
|
277
|
-
required: ["name", "title", "pattern"],
|
|
284
|
+
required: ["name", "title", "use_for", "pattern"],
|
|
278
285
|
},
|
|
279
286
|
},
|
|
280
287
|
usage: { type: "string" },
|
|
281
288
|
name: { type: "string" },
|
|
282
289
|
title: { type: "string" },
|
|
290
|
+
use_for: { type: "string" },
|
|
283
291
|
pattern: { type: "string" },
|
|
284
292
|
modelled_on: { type: "string" },
|
|
285
293
|
published_sizes: { type: "string" },
|
|
@@ -293,7 +301,7 @@ export const CAD_TOOLS = [
|
|
|
293
301
|
{
|
|
294
302
|
name: "cad_check_fit",
|
|
295
303
|
description:
|
|
296
|
-
"Check two allowed watertight manifold STL meshes in millimetres. Applies only the explicit rigid transform to reference: XYZ rotation in degrees about the origin, then translation. Never silently scales a scan. Reports Boolean interference volume and minimum surface gap (zero on contact/intersection), plus a clearance verdict; intentional support contact also has zero gap. Fails rather than guessing for open meshes or excessive triangle workload.",
|
|
304
|
+
"Check two allowed watertight manifold STL meshes in millimetres. Applies only the explicit rigid transform to reference: XYZ rotation in degrees about the origin, then translation. Never silently scales a scan. Reports Boolean interference volume and minimum surface gap (zero on contact/intersection), plus a clearance verdict; intentional support contact also has zero gap. Like cad_run, a call waits for the environment's exclusive execution slot up to its timeout_ms and reports queue_wait_ms, so several checks may be sent at once. Fails rather than guessing for open meshes or excessive triangle workload.",
|
|
297
305
|
inputSchema: {
|
|
298
306
|
type: "object" as const,
|
|
299
307
|
properties: {
|
|
@@ -341,6 +349,7 @@ export const CAD_TOOLS = [
|
|
|
341
349
|
outputSchema: output(
|
|
342
350
|
{
|
|
343
351
|
units: { type: "string", const: "mm" },
|
|
352
|
+
queue_wait_ms: { type: "integer" },
|
|
344
353
|
interference_volume_mm3: { type: "number" },
|
|
345
354
|
minimum_gap_mm: { type: "number" },
|
|
346
355
|
clearance_mm: { type: "number" },
|
|
@@ -365,9 +374,10 @@ export const CAD_DESIGN_PROMPT = {
|
|
|
365
374
|
description:
|
|
366
375
|
"MCP-owned rules for headless build123d designs and one-call parameter revisions.",
|
|
367
376
|
text: `Use code-CAD for dimensioned functional designs and parameter edits. Build in millimetres with build123d 0.13.0; the MCP owns the Python environment, execution, export, validation and rendering. Check cad_status and use cad_setup with install: true when needed. No Blender, Fusion, network or printer access is available to your script.
|
|
368
|
-
|
|
369
|
-
|
|
377
|
+
A new design starts from the product, in this order. First, name two or three products a person would buy for this request (search when you are not sure what is sold) and say which one the design follows. Second, choose from the cookbook by purpose: the list below says what each example is for (cad_examples with no name returns it with each one's pattern and product). Read the example whose use is nearest the request, with cad_examples and its name, before deciding anything else, and adapt its form and pattern, never its sizes. Third, and only then, choose the mechanism (a clamp, screw, spring, hinge or snap) and read a second example for it if you need one. A mechanism chosen before the product gives a bracket with the mechanism bolted on.
|
|
378
|
+
The cookbook, by what each example is for:
|
|
370
379
|
${cadExampleLines()}
|
|
380
|
+
Form first: build the product's shape, not a profile pushed up. Before any geometry, write the concept as the script's opening docstring, the way every cookbook example does: what it is, then "Modelled on:" the bought product you named, its mechanism, the load path, the print orientation and why. A script whose header names no product was designed from the mechanism. build123d has loft (through sections of different shape), sweep (a section along a path or a Helix), revolve, fillet, chamfer, offset and shell as well as extrude; use the one the product's surface calls for: lofted where a hand closes round it, revolved where it turns, swept where it runs like a bent rod or a thread, filleted where two surfaces meet under load. Extrude a flat profile only for something that really is a plate or a lever, or for a print-in-place mechanism or spring that must lie in the layers, and say that reason in the result. Choose the print orientation after the form: split a part, turn it or accept a modest support before flattening its design.
|
|
371
381
|
What the cookbook taught about this engine: return several bodies as Compound([a, b]); bodies that touch or overlap come back invalid, so leave a real gap (0.2 mm or more) or union them, and check that solid_count equals the bodies you intend (for a print-in-place mechanism that count is the first evidence nothing fused). fillet() often fails on the edges of an outline unioned from many curves, where chamfer() usually succeeds: fillet or chamfer simple bodies before the booleans that complicate them, and when a chamfer fails too, apply it to the plain body and union the details on afterwards. Do not round a sketch by growing and shrinking it with offset(): the solid looks right and its STEP comes back with no solids (the step_solids check fails). A whole Sphere() exports open at its poles: trim them (Sphere(r) & Box(2 * r, 2 * r, 2 * r - 0.1)). One fillet of the same radius over every edge of a box can export open: fillet in two passes with different radii. A model with moving parts takes a pose parameter: the assembled pose to judge it, the print plate to make it.
|
|
372
382
|
Declare exactly one top-level P = {...} dictionary of JSON-compatible literal named parameters. Put every functional dimension in P; derive geometry from P. Define build() to return a build123d Shape or Compound of disjoint solid parts. When a design has separate bodies (print-in-place parts, a captive wheel, links of a fabric), return Compound(children=[...]) with a label on each body: cad_run then checks that each labelled body is exactly one solid, so a piece cut off one body cannot hide behind two bodies fused into one. Near pairs of solids are screened and, where the screen cannot clear them, measured exactly against P["print_in_place_clearance_mm"] when you declare it, else 0.3 mm. If the bodies are shown assembled rather than printed in place (a shaft in its hole at a fit clearance), set P["print_in_place"] = False: only touching or overlap is then a problem. Export in print orientation with the plate at Z = 0: a solid below it, or above it with nothing under it that reaches it, is a problem. Do not put construction or exports in a __main__ block: cad_run calls build() and exports the result. Imports, functions and derived P entries are fine. Parameters are applied to the literal defaults before derived expressions execute. For solid designs without inputs, the script and parameters file alone reconstruct it. For input-dependent designs, declare inputs as an array of {name, path} files: cad_run snapshots only those allowed files, exposes INPUTS[alias] to your script, and saves an inputs manifest. Retain the snapshots too for recovery; subsequent script_path edits reuse them unless inputs is explicitly supplied. No other personal files are readable. For a mesh-only experiment use mode: "mesh" and return a trimesh.Trimesh from build(); it exports and checks STL plus the same renders, with step: null and an explicit reason. It does not manufacture a fake parametric STEP or promise scan-cleanup capability.
|
|
373
383
|
Call cad_run with script, output_dir and a plain name. It saves <name>.py and <name>.parameters.json before running, then exports <name>.stl and <name>.step in a fresh subfolder. For an edit, one cad_run with script_path pointing to the earlier .py, parameters containing just the changed dimension, output_dir and name regenerates it without resending the script. Existing parameter values are retained; unknown names and type changes are refused. A killed run can be retried from its checkpoint in a new workspace; mutations are never replayed automatically.
|
|
@@ -376,7 +386,7 @@ Fit reference workflow: return load_scan("scan", source_units="m", up_axis="y")
|
|
|
376
386
|
Result selection and edits: set final: true only on the result you select. cad-result.json in each immediate run folder is protected from script writes and retains final, completed_at, lineage_id (source hash), full checks and artifact paths; clients can discover the latest completed final record after restart without rebuilding. Final is a selection marker, not a replacement for valid/checks. Queued calls may expire with cad-queue-timeout before dispatch; do not automatically replay. Unchanged declared files reuse a read-only content-addressed bundle under output_dir/.cad-inputs, preserving filenames and restricting reads to that bundle. Keep this shared cache with the saved runs.
|
|
377
387
|
Mesh cleanup workflow: return a trimesh.Trimesh in mode: "mesh". Load the prepared mesh, fit needed geometry with NumPy/SciPy, rebuild regular sections/features with build123d or manifold3d CrossSection/extrusion/revolve, and combine meshes with manifold3d booleans. scikit-image supplies marching cubes for voxel/SDF work; Shapely supplies planar operations; Pillow supplies image/texture reads. Keep numeric choices in P and regenerate from declared inputs. Validate closure, winding, manifold status, dimensions and all six views using cad_run. What to regularise, infer, preserve or label comes from the caller's cleanup rules, not this engine prompt.
|
|
378
388
|
Captured scan touch-up: t = scan_touchup(load_scan("scan", source_units="m", up_axis="y", ground=False), colour="colour", normal="normal", edge_mm=0.4) takes a textured capture (declare its OBJ, MTL and colour and normal map PNGs as inputs; pass the map aliases). It removes loose pieces and spikes, closes holes and refines to edge_mm without shrinking the body. t.regions() prints the colour regions (id, colour, area, size, flatness; 0 is the body) to build.log and saves regions.png in the run folder: read both, then name regions by id in the same scan and edge_mm. t.flatten(ids, shape="plane" or "curved"), t.bead(id, diameter_mm, proud_mm), t.cord(id, diameter_mm, proud_mm) (a cord follows its region's own curve) and t.seat(height_mm) record steps; return t.mesh(relief_gain=1.0), which adds the normal map's measured relief, applies the steps with manifold3d and prints its changes. Keep relief_gain at 1: a larger gain amplifies the map's noise, not stitches. When the caller's rules call for a textile's relief the scan missed (fabric, knit, crochet the photos show raised), t.texture_relief(height_mm, regions=None) raises its stitch pattern from the colour texture on the textile only (never flattened, beaded or corded regions); about 0.6 to 1.0 mm peak to peak prints visibly. It is off unless called: never for hard objects, printed graphics or labels.
|
|
379
|
-
The result includes paths, millimetre bounds/size, mesh and STEP volumes, solid count, watertight/manifold/winding/STEP checks, bodies (closest approach between solids, contact with the print plate at Z = 0, labelled bodies that are not one solid), problems, checked and not_checked, six orthographic renders (front, back, left, right, top, bottom), a perspective view from the front right and above, and a contact sheet with the perspective view large beside the six. Fix every entry in problems before selecting a result; an empty problems list proves nothing listed in not_checked. Judge the form from the perspective view first: would a person recognise the product and want it? Then inspect all six; revise visible defects. A valid mesh or nominal parameter does not prove the requested dimension: measure the actual exported interfaces. Use cad_check_fit on a model and reference STL with an explicit rigid transform; report raw-scan interference and minimum gap. Calipers are authoritative but disagreement with a scan is unresolved measurement evidence, not permission to silently rescale it. Check assembly/insertion paths and actual articulated poses, not sums of local joint limits or reference points alone. Printing, clearance under load, supports and motion need separate evidence.
|
|
389
|
+
The result includes paths, millimetre bounds/size, mesh and STEP volumes, solid count, watertight/manifold/winding/STEP checks, bodies (closest approach between solids, contact with the print plate at Z = 0, labelled bodies that are not one solid), problems, checked and not_checked, six orthographic renders (front, back, left, right, top, bottom), a perspective view from the front right and above, and a contact sheet with the perspective view large beside the six. Fix every entry in problems before selecting a result; an empty problems list proves nothing listed in not_checked. After every cad_run, Read its perspective view (renders.perspective, as the result's next says) before the next cad_run or any other change: a run you have not looked at tells you nothing about the form. Judge the form from the perspective view first: would a person recognise the product and want it? Then inspect all six; revise visible defects. Before the final run, list what the views show is wrong against the bought product you named (for a scan, the object in its photos), and fix each one or report it. To get a number out of a design (a spring force, a strain, a clearance you derived), print() it in the script: the result returns it as printed, with no need to make a run fail. A valid mesh or nominal parameter does not prove the requested dimension: measure the actual exported interfaces. Use cad_check_fit on a model and reference STL with an explicit rigid transform; report raw-scan interference and minimum gap. Calipers are authoritative but disagreement with a scan is unresolved measurement evidence, not permission to silently rescale it. Check assembly/insertion paths and actual articulated poses, not sums of local joint limits or reference points alone. Printing, clearance under load, supports and motion need separate evidence.
|
|
380
390
|
Fit, flexure and thread parameters: put each interface's nominal size, its source (measured, published, or assumed), the print correction, and the design fit in P as separate named values, so a fit report revises one number without resending the script. Model every dimension you claim: a parameter the geometry never uses (a wallet or case width that no cut or wall reads) is a defect; use it or remove it. Shape flexures so their bending lies in the layer plane of the exported print orientation, with the stroke, preload, and hard-stop gap as P values; build the stopped pose as well as the rest pose when checking. Model printed threads as explicit coarse geometry with the same pitch on both sides and clearance as a radial P offset; never scale a screw to clear its hole.
|
|
381
391
|
Check insertion and articulated poses with cad_check_fit against each object state that matters (the bare product, the product in its case, and the case with its attachment as its own reference envelope), including the widest section on the way in. Report interference and minimum gap per state. In your summary, attach each "fits", "holds", and "prints without supports" claim to the check or slice number that shows it; a valid flag alone shows none of them. Apply fdm_design and fdm_slicing too. When a part meets a real object apply fdm_fit, and when it flexes, grips, snaps or springs apply fdm_flexures: if they were not attached, read them with the design_guidance tool before choosing that fit or spring. Never invoke a printer as part of constructing CAD.`,
|
|
382
392
|
};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
"""Bag-sealing clip: two hinged bars, ridge into groove, snap latch, printed in place
|
|
2
|
+
Use for: closing a bag of food or sealing film; any clip with two hinged bars and a latch
|
|
2
3
|
Pattern: bar cross-section drawn in YZ and extruded along the bar; revolved waisted pin in a C-socket; ridge and its offset as the groove; modelled SHUT, then one bar swung open for printing
|
|
3
4
|
Modelled on: Linden Sweden Twixit! bag clip (https://www.webstaurantstore.com/linden-sweden-411-8-twixit-blue-4-1-4-pastry-bag-clips-pack/534411.8.html); mechanism as in the hinged-bar clip patent US 4656697, Naslund (https://patents.google.com/patent/US4656697)
|
|
4
5
|
Published sizes used: 108 mm (4 1/4 in) = overall length (retailer, https://www.webstaurantstore.com/linden-sweden-411-8-twixit-blue-4-1-4-pastry-bag-clips-pack/534411.8.html); nothing else is published, the other sizes are design choices
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
"""Pocket clicker: a bistable double curved beam in a closed frame
|
|
2
|
+
Use for: a fidget or clicker; any part that must snap between two stable positions
|
|
2
3
|
Pattern: a computed 2D curve (cosine beam from a formula) made into a face, extruded flat with a filleted frame round it
|
|
3
4
|
Modelled on: the double curved-beam bistable mechanism of Qiu, Lang and Slocum, "A curved-beam bistable mechanism", J. Microelectromechanical Systems 13(2), 2004, pp. 137-146 (https://manuscript.isc.ac/Inventory/49/950908.htm)
|
|
4
5
|
Published sizes used: bistability ratio rise / thickness must exceed about 2.31 for a cosine beam clamped at both ends with its twisting mode blocked (Qiu, Lang and Slocum 2004, URL above); here rise / thickness = 3.0. All other sizes are design choices.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Wall-mounted spring grip for a broom or mop handle (one screw, snap-in C with flared lips)
|
|
2
|
+
Use for: storing a broom, mop, rake, torch or any round handle or pipe 19 to 29 mm thick on a wall or inside a cupboard door; any snap-in spring clip that grips a round bar
|
|
3
|
+
Pattern: sweep one rounded section round the handle's axis for the C ring; pad and lip beads as simple bodies chamfered before they are joined; one countersunk screw through the seat, reached through the mouth
|
|
4
|
+
Modelled on: National Hardware spring grip clips for handles (https://www.doitbest.com/product/222143/national-rust-resistant-spring-grip-clip-hook-222143/); screw is SPAX 4.0 mm flat countersunk (https://www.ahlsell.se/en/products/mounting/wood-screw/wood-screw-spax/71333788---traskruv-tft-spax-svart-4.0x25h-200fp-eta-120114)
|
|
5
|
+
Published sizes used: 3/4 to 1 1/8 in (19 to 28.6 mm) = handle diameters the bought steel clip takes (retailer listing, first URL); 4.0 mm = screw thread, 8.0 mm = head diameter, 2.4 mm = head height (SPAX listing, second URL); ring, wall and mouth sizes are design choices
|
|
6
|
+
Concept: A clip on the wall that a broom handle is pushed into and pulled out of with one hand. Frame: the wall is the plane y = 0 and the mouth faces away from it, towards -y (the front view). The handle spreads two arms as it passes the mouth and they close behind it; the ring is made 1 mm smaller than the handle so it keeps squeezing and the broom does not slide down. The bought clip is spring steel; plastic arms must be longer and thicker to do the same job, so the ring wraps 230 degrees and the arms are 4 lines (1.68 mm) thick: opening the 20 mm mouth to a 25 mm handle strains them about 2 percent, and the script prints that figure for whatever sizes it is given. Round beads on the lips guide the handle in and are kind to its paint. The screw sits in the seat, where the handle covers it, and pulls the pad flat to the wall. It is printed with the C outline on the bed, the handle's axis upright, so the arms bend within their layers; printed lying on the pad they would split along a layer the first time. No supports. PETG (PLA arms creep open in a warm cupboard), 4 walls.
|
|
7
|
+
What makes this good: it is sized as a spring, not as a bracket, with the strain worked out in the script, and the one screw is hidden under the handle.
|
|
8
|
+
"""
|
|
9
|
+
from math import acos, asin, degrees, radians
|
|
10
|
+
|
|
11
|
+
from build123d import *
|
|
12
|
+
|
|
13
|
+
P = {
|
|
14
|
+
"handle_d": 25.0, # the handle it grips (inside the published 19 to 28.6 mm range)
|
|
15
|
+
"squeeze": 1.0, # ring is this much smaller than the handle, so it grips
|
|
16
|
+
"mouth": 20.0, # gap between the beads, 80% of the handle
|
|
17
|
+
"arm_t": 1.68, # ring wall: 4 lines of 0.42, thin enough to spring
|
|
18
|
+
"bead_r": 1.6, # round bead on the end of each arm: lead-in outside, retaining bump inside
|
|
19
|
+
"pad_over": 1.0, # the pad stands this far above the seat; lower leaves more arm free to bend
|
|
20
|
+
"height": 22.0, # along the handle = height off the bed as printed
|
|
21
|
+
"pad_w": 34.0, # wall pad width
|
|
22
|
+
"pad_t": 5.0, # wall to the seat; leaves 2.6 mm under the screw head
|
|
23
|
+
"screw_d": 4.0, # screw thread diameter (published)
|
|
24
|
+
"screw_head_d": 8.0, # head diameter (published)
|
|
25
|
+
"screw_head_h": 2.4, # head height (published)
|
|
26
|
+
"screw_clear": 0.5,
|
|
27
|
+
"edge": 0.8, # softening of the ring's, beads' and pad's edges
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def build():
|
|
32
|
+
h, e = P["height"], P["edge"]
|
|
33
|
+
r_in = (P["handle_d"] - P["squeeze"]) / 2
|
|
34
|
+
r_mid = r_in + P["arm_t"] / 2
|
|
35
|
+
yc = P["pad_t"] + r_in # ring centre: the seat is pad_t from the wall
|
|
36
|
+
half = degrees(asin((P["mouth"] / 2 + P["bead_r"]) / r_mid)) # half the mouth angle: the beads end up `mouth` apart
|
|
37
|
+
up = (Align.CENTER, Align.CENTER, Align.MIN)
|
|
38
|
+
|
|
39
|
+
# each piece is a simple body with its own softened edges, then they are joined: an outline chamfered after the
|
|
40
|
+
# union fails here. The ring is one section swept round the handle's axis, open at the mouth.
|
|
41
|
+
arc = Pos(0, yc, h / 2) * CenterArc((0, 0), r_mid, 90 + half, 360 - 2 * half)
|
|
42
|
+
ring = sweep(Plane(arc @ 0, x_dir=(0, 0, 1), z_dir=arc % 0) * RectangleRounded(h, P["arm_t"], e), path=arc)
|
|
43
|
+
bead = Cylinder(P["bead_r"], h, align=up)
|
|
44
|
+
bead = chamfer(bead.edges(), e) # lead-in outside the arm, retaining bump inside it
|
|
45
|
+
pad_y = P["pad_t"] + P["pad_over"]
|
|
46
|
+
pad = Pos(0, pad_y / 2, 0) * Box(P["pad_w"], pad_y, h, align=up)
|
|
47
|
+
pad = fillet(pad.edges().filter_by(Axis.Z).filter_by_position(Axis.Y, 1, 99), 3.0) # round the two front corners in plan
|
|
48
|
+
pad = chamfer(pad.edges().group_by(Axis.Z)[0] + pad.edges().group_by(Axis.Z)[-1], e)
|
|
49
|
+
grip = ring + pad + [Pos(arc @ u) * Pos(0, 0, -h / 2) * bead for u in (0, 1)]
|
|
50
|
+
grip -= Pos(0, yc, 0) * Cylinder(r_in, h, align=up) # the seat, cleared through the pad
|
|
51
|
+
|
|
52
|
+
# the spring, worked out: each arm is a cantilever from where the ring leaves the pad round to its bead,
|
|
53
|
+
# and the handle pushes each bead out by half of (handle - mouth)
|
|
54
|
+
free = radians(180 - half) - acos((r_in - P["pad_over"]) / (r_in + P["arm_t"]))
|
|
55
|
+
strain = 1.5 * P["arm_t"] * (P["handle_d"] - P["mouth"]) / 2 / (r_mid * free) ** 2
|
|
56
|
+
print(f"arm strain while the handle passes the mouth: {100 * strain:.1f} % (keep to about 2 % for PETG)")
|
|
57
|
+
|
|
58
|
+
hole_r, head_r = (P["screw_d"] + P["screw_clear"]) / 2, (P["screw_head_d"] + P["screw_clear"]) / 2
|
|
59
|
+
screw = Cylinder(hole_r, 4 * P["pad_t"]) + Cone(hole_r, head_r, P["screw_head_h"], align=(Align.CENTER, Align.CENTER, Align.MAX)) \
|
|
60
|
+
+ Cylinder(head_r, 6, align=(Align.CENTER, Align.CENTER, Align.MIN)) # head recess clear up into the seat
|
|
61
|
+
return Rot(0, 0, 180) * (grip - Pos(0, P["pad_t"], h / 2) * Rot(-90, 0, 0) * screw) # mouth towards the front view
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
"""Adhesive desk cable clip (single cable, snap-in C channel on a taped pad)
|
|
2
|
+
Use for: holding one cable, cord or charger lead on a desk, wall or bedside; any small stick-on snap-in clip
|
|
2
3
|
Pattern: sweep a rounded (slot) section along an arc for the C ring + loft the pad up into it, fillet the lip tips
|
|
3
4
|
Modelled on: 3M Command Clear Round Cord Clips 17017CLR (https://argo.webstaurantstore.com/3m-command-8482-7100027385-clear-round-cord-clips-pack/39917017CLRES.html)
|
|
4
5
|
Published sizes used: 13/16 in (20.6 mm) = clip width, 1/2 in (12.7 mm) = clip depth (retailer, URL above); cable diameter, mouth and wall are design choices
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
"""Chainmail patch: rigid square links that pass through each other, printed in place
|
|
2
|
+
Use for: flexible printed fabric, a strap or a mat made of linked rigid pieces
|
|
2
3
|
Pattern: one link made from a rounded ring with two box cuts (two bars stay on the bed, two become bridges), then copied on a grid as a Compound of separate solids
|
|
3
4
|
Modelled on: NASA/JPL "space fabric" (https://www.jpl.nasa.gov/news/space-fabric-links-fashion-and-engineering) and Ed Nisley's printable chain mail (https://softsolder.com/2014/12/04/3d-printed-chain-mail-armor-cosplay-edition/)
|
|
4
5
|
Published sizes used: 2.4 mm = bar width, 6 threads of 0.40 mm (maker, https://softsolder.com/2014/12/04/3d-printed-chain-mail-armor-cosplay-edition/); JPL publishes no sizes; the other sizes are design choices
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Clamp-on desk headphone hook (rounded S frame, printed thumbscrew, hook hanging under the desk)
|
|
2
|
+
Use for: hanging headphones, a bag or a cable coil from a desk, shelf or table edge without tape or screws; any clamp that grips a board 18 to 30 mm thick with a printed screw
|
|
3
|
+
Pattern: one rounded section swept along a filleted S path (top jaw, spine, lower jaw, drop, hook, tip); a boss for the nut thread; the screw and nut threads are one section on one helix, the nut's moved out by the fit; "pose" shows it clamped or on the plate
|
|
4
|
+
Modelled on: Brainwavz Hoist headphone hanger with adjustable clamp (https://brainwavzaudio.com/de/products/brainwavz-hoist-headphone-hanger-with-adjustable-clamp)
|
|
5
|
+
Published sizes used: 5 to 40 mm = desk thickness the bought clamp takes, 50 mm = its hanger width (maker's listing, URL above); this printed one is sized for 18 to 30 mm desks and every other size is a design choice
|
|
6
|
+
Concept: Hangs a headset under the desk edge with nothing stuck or screwed to the desk. 2 bodies: the frame and the thumbscrew. Frame as used: the desk edge is at x = 0 and the desk runs towards +x; the top jaw lies on the desk, the spine passes in front of the edge, the lower jaw runs back under the desk and carries the threaded boss, then the frame drops and comes forward again as the hook, with an upturned tip at the front so the headband lifts on and off from where you sit. The screw comes up through the boss and presses the underside of the desk, so one frame takes any desk from 18 to 30 mm; the headphones' weight pulls the frame down onto the top jaw, so the clamp only has to stop it sliding. The knob hangs in the hook's opening, above where the headband rests. The frame is printed on its side so every layer holds the whole S and no bend is a layer joint; its threaded hole then lies level, which a 4 mm pitch, 45 degree thread survives without supports. The screw prints standing on its knob. Stick felt on the top jaw and the screw tip. PETG or PLA, 4 walls.
|
|
7
|
+
What makes this good: the whole frame is a single swept bar with large bends, so it reads as a bent-steel hanger, not a bracket, and the load goes round the bends inside the layers.
|
|
8
|
+
"""
|
|
9
|
+
from build123d import *
|
|
10
|
+
|
|
11
|
+
P = {
|
|
12
|
+
"pose": "plate", # "plate": as printed, frame on its side and screw on its knob; "assembled": clamped on desk_t, standing as used (the screw is then off the plate, which cad_run notes: that pose is for looking, not printing)
|
|
13
|
+
"desk_t": 25.0, # the desk it is shown clamped on (assembled pose only)
|
|
14
|
+
"opening": 32.0, # between the jaws; takes desks up to 30 mm with a felt pad
|
|
15
|
+
"min_desk": 18.0, # thinnest desk the screw still reaches
|
|
16
|
+
"reach": 46.0, # jaws over the desk, from the desk edge
|
|
17
|
+
"bar_t": 10.0, # frame bar thickness, in the bending direction
|
|
18
|
+
"width": 26.0, # frame width = what the headband rests on
|
|
19
|
+
"edge_r": 3.0, # rounding of the bar's four long edges
|
|
20
|
+
"bend_r": 13.0, # centreline radius of every bend
|
|
21
|
+
"drop": 84.0, # lower jaw down to the hook arm (centrelines): knob plus a padded headband
|
|
22
|
+
"hook_len": 60.0, # hook arm, back towards the desk edge
|
|
23
|
+
"tip_h": 24.0, # upturned tip, centreline rise
|
|
24
|
+
"boss_h": 18.0, # threaded length through the lower jaw and its boss (4.5 turns)
|
|
25
|
+
"boss_l": 28.0, # boss length along the jaw
|
|
26
|
+
"thread_d": 14.0, # screw outside diameter
|
|
27
|
+
"pitch": 4.0, # coarse, so it prints lying level in the frame
|
|
28
|
+
"thread_depth": 1.2, # 45 degree flanks
|
|
29
|
+
"crest": 0.8, # flat on the thread crest
|
|
30
|
+
"fit": 0.4, # radial clearance, screw to nut
|
|
31
|
+
"knob_d": 32.0,
|
|
32
|
+
"knob_h": 11.0,
|
|
33
|
+
"flutes": 8,
|
|
34
|
+
"gap_on_plate": 10.0, # frame to screw on the plate
|
|
35
|
+
"print_in_place": False, # two parts assembled by hand: only touching is a problem
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def thread(root_r, crest_r, z0, length):
|
|
40
|
+
"""A 45 degree trapezoid swept along a helix about Z, from z0. root_r > crest_r makes the nut's thread."""
|
|
41
|
+
depth = crest_r - root_r
|
|
42
|
+
half_root = P["crest"] / 2 + abs(depth)
|
|
43
|
+
bury = 0.3 if depth > 0 else -0.3 # the flanks run on into the wall: no section corner lies on the wall's surface
|
|
44
|
+
section = Polygon((root_r - bury, -half_root - 0.3), (crest_r, -P["crest"] / 2),
|
|
45
|
+
(crest_r, P["crest"] / 2), (root_r - bury, half_root + 0.3), align=None)
|
|
46
|
+
return Pos(0, 0, z0) * sweep(Plane.XZ * section, path=Helix(P["pitch"], length, (root_r + crest_r) / 2), is_frenet=True)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def build():
|
|
50
|
+
t, w, r = P["bar_t"], P["width"], P["bend_r"]
|
|
51
|
+
major, root = P["thread_d"] / 2, P["thread_d"] / 2 - P["thread_depth"]
|
|
52
|
+
low = -P["opening"] - t / 2 # lower jaw centreline; the desk top is y = 0
|
|
53
|
+
x_spine = -(r - t / 2) - t / 2 # the inside of the bend ends at the desk edge
|
|
54
|
+
x_screw = P["reach"] - P["boss_l"] / 2
|
|
55
|
+
|
|
56
|
+
# frame, drawn lying on the bed: X into the desk, Y up as used, Z across the width
|
|
57
|
+
path = Polyline((P["reach"], t / 2), (x_spine, t / 2), (x_spine, low), (P["reach"] + r, low),
|
|
58
|
+
(P["reach"] + r, low - P["drop"]), (P["reach"] + r - P["hook_len"], low - P["drop"]),
|
|
59
|
+
(P["reach"] + r - P["hook_len"], low - P["drop"] + P["tip_h"]))
|
|
60
|
+
path = Pos(0, 0, w / 2) * fillet(path.vertices(), r)
|
|
61
|
+
frame = sweep(Plane(path @ 0, x_dir=(0, 0, 1), z_dir=path % 0) * RectangleRounded(w, t, P["edge_r"]), path=path)
|
|
62
|
+
ends = [frame.faces().sort_by_distance(path @ u)[0] for u in (0, 1)]
|
|
63
|
+
frame = fillet(ends[0].edges() + ends[1].edges(), P["edge_r"] - 0.5) # soft jaw end and hook tip; a radius over edge_r exports open
|
|
64
|
+
boss = Pos(x_screw, -P["opening"] - P["boss_h"] / 2) * RectangleRounded(P["boss_l"], P["boss_h"], 5)
|
|
65
|
+
frame += extrude(boss, w)
|
|
66
|
+
|
|
67
|
+
# threads in the screw's own frame: axis Z, origin on the lower jaw's top face. Plain hole first, then the
|
|
68
|
+
# nut's thread added to its wall (a thread subtracted from the cutter does not cut)
|
|
69
|
+
z_nut = -P["boss_h"] + 2.5
|
|
70
|
+
to_frame = Pos(x_screw, -P["opening"], w / 2) * Rot(-90, 0, 0)
|
|
71
|
+
frame -= to_frame * Cylinder(major + P["fit"], 3 * P["boss_h"])
|
|
72
|
+
frame += to_frame * thread(major + P["fit"], root + P["fit"], z_nut, P["boss_h"] - 5)
|
|
73
|
+
|
|
74
|
+
# screw: fluted knob, threaded shank long enough for the thinnest desk, tip and thread ends cut to a chamfer
|
|
75
|
+
shank = P["boss_h"] + P["opening"] - P["min_desk"] + 4
|
|
76
|
+
kh = P["knob_h"]
|
|
77
|
+
knob = fillet(Cylinder(P["knob_d"] / 2, kh, align=(Align.CENTER, Align.CENTER, Align.MIN)).edges(), 2.0)
|
|
78
|
+
flute = Pos(P["knob_d"] / 2 + 1.5, 0, 0) * Cylinder(4.0, kh, align=(Align.CENTER, Align.CENTER, Align.MIN))
|
|
79
|
+
knob -= [Rot(0, 0, i * 360 / P["flutes"]) * flute for i in range(P["flutes"])]
|
|
80
|
+
# the envelope is wider than the thread (a surface shared with the crest breaks the cut) and chamfers the tip
|
|
81
|
+
envelope = chamfer(Cylinder(major + 0.6, shank + 1, align=(Align.CENTER, Align.CENTER, Align.MIN)).edges().group_by(Axis.Z)[-1], P["thread_depth"] + 1.2)
|
|
82
|
+
screw = knob + Pos(0, 0, kh - 1) * ((Cylinder(root, shank + 1, align=(Align.CENTER, Align.CENTER, Align.MIN))
|
|
83
|
+
+ thread(root, major, 2.0, shank - 3)) & envelope)
|
|
84
|
+
|
|
85
|
+
if P["pose"] == "plate":
|
|
86
|
+
return Compound([frame, Pos(P["reach"] + r + P["knob_d"] / 2 + P["gap_on_plate"], 0, 0) * screw])
|
|
87
|
+
# assembled: tip on the underside of the desk; the turn that puts the screw's ridge in the nut's groove
|
|
88
|
+
lift = P["opening"] - P["desk_t"] - (kh + shank)
|
|
89
|
+
turn = 360 * (lift + kh + 1 - z_nut) / P["pitch"] + 180
|
|
90
|
+
used = Rot(90, 0, 0) * Compound([frame, to_frame * Pos(0, 0, lift) * Rot(0, 0, turn) * screw])
|
|
91
|
+
return Pos(0, 0, -used.bounding_box().min.Z) * used
|