dsh-cad-studio 0.8.4 → 0.9.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.
- package/index.js +126 -5
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -184,6 +184,7 @@ function diagnose(bridge, cfg = {}) {
|
|
|
184
184
|
}
|
|
185
185
|
}
|
|
186
186
|
|
|
187
|
+
const defined = (obj) => Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined))
|
|
187
188
|
const renderUndo = (v) => {
|
|
188
189
|
if (!v || v.ok === false) return `✗ ${v?.error ?? '没有可撤销的操作'}`
|
|
189
190
|
if (v.scope === 'assembly') {
|
|
@@ -1201,6 +1202,7 @@ const featuresScript = (ops, exportPath, opts = {}) => `${PRELUDE}
|
|
|
1201
1202
|
import os
|
|
1202
1203
|
_OPS = json.loads(${JSON.stringify(JSON.stringify(Array.isArray(ops) ? ops : []))})
|
|
1203
1204
|
_EXPORT = ${exportPath ? JSON.stringify(exportPath) : 'None'}
|
|
1205
|
+
_SKETCHES = json.loads(${JSON.stringify(JSON.stringify(opts.sketches && typeof opts.sketches === 'object' ? opts.sketches : {}))})
|
|
1204
1206
|
_CACHE = json.loads(${JSON.stringify(JSON.stringify(opts.cache && opts.cache.hashes ? { dir: opts.cache.dir, hashes: opts.cache.hashes } : null))})
|
|
1205
1207
|
_RESUME = json.loads(${JSON.stringify(JSON.stringify(opts.resume && opts.resume.brep ? { index: opts.resume.index, brep: opts.resume.brep } : null))})
|
|
1206
1208
|
|
|
@@ -1230,6 +1232,90 @@ def _anchor(_spec, _cur):
|
|
|
1230
1232
|
_off = _spec.get("offset")
|
|
1231
1233
|
return _center_of(_hits[0]) + (_v3(_off) if _off else Vector(0.0, 0.0, 0.0))
|
|
1232
1234
|
|
|
1235
|
+
|
|
1236
|
+
_SK_CONSTRAINT = {
|
|
1237
|
+
"coincident": ("Coincident", "ab2"), "concentric": ("Coincident", "circles"),
|
|
1238
|
+
"horizontal": ("Horizontal", "one"), "vertical": ("Vertical", "one"),
|
|
1239
|
+
"parallel": ("Parallel", "pair"), "perpendicular": ("Perpendicular", "pair"),
|
|
1240
|
+
"tangent": ("Tangent", "pair"), "distance_x": ("DistanceX", "size"),
|
|
1241
|
+
"distance_y": ("DistanceY", "size"), "radius": ("Radius", "size_one"),
|
|
1242
|
+
"angle": ("Angle", "size_pair"), "distance": ("Distance", "ab2v"),
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
def _sketch(name):
|
|
1246
|
+
import Sketcher
|
|
1247
|
+
spec = _SKETCHES.get(name)
|
|
1248
|
+
if not spec:
|
|
1249
|
+
raise RuntimeError("no such sketch: %s" % name)
|
|
1250
|
+
doc = FreeCAD.newDocument("sk_" + name)
|
|
1251
|
+
sk = doc.addObject("Sketcher::SketchObject", "K")
|
|
1252
|
+
ids = []
|
|
1253
|
+
for g in spec.get("geometry") or []:
|
|
1254
|
+
t = g.get("type")
|
|
1255
|
+
if t == "line":
|
|
1256
|
+
sk.addGeometry(Part.LineSegment(_v3(g["p1"]), _v3(g["p2"])), False)
|
|
1257
|
+
elif t == "circle":
|
|
1258
|
+
sk.addGeometry(Part.Circle(_v3(g["c"]), Vector(0, 0, 1), float(g["r"])), False)
|
|
1259
|
+
else:
|
|
1260
|
+
raise RuntimeError("sketch %s: unknown geometry %s" % (name, t))
|
|
1261
|
+
ids.append(g.get("id"))
|
|
1262
|
+
ix = dict((gid, i) for i, gid in enumerate(ids))
|
|
1263
|
+
def gi(ref):
|
|
1264
|
+
if ref not in ix:
|
|
1265
|
+
raise RuntimeError("sketch %s: constraint refers to missing geometry %s" % (name, ref))
|
|
1266
|
+
return ix[ref]
|
|
1267
|
+
dims = []
|
|
1268
|
+
for c in spec.get("constraints") or []:
|
|
1269
|
+
t = c.get("type")
|
|
1270
|
+
row = _SK_CONSTRAINT.get(t)
|
|
1271
|
+
if not row:
|
|
1272
|
+
raise RuntimeError("sketch %s: unknown constraint %s" % (name, t))
|
|
1273
|
+
fc, form = row
|
|
1274
|
+
v = c.get("value")
|
|
1275
|
+
if form == "one":
|
|
1276
|
+
sk.addConstraint(Sketcher.Constraint(fc, gi(c["a"])))
|
|
1277
|
+
elif form == "ab2":
|
|
1278
|
+
sk.addConstraint(Sketcher.Constraint(fc, gi(c["a"]), int(c.get("pa", 1)), gi(c["b"]), int(c.get("pb", 1))))
|
|
1279
|
+
elif form == "circles":
|
|
1280
|
+
sk.addConstraint(Sketcher.Constraint(fc, gi(c["a"]), 3, gi(c["b"]), 3))
|
|
1281
|
+
elif form == "pair":
|
|
1282
|
+
sk.addConstraint(Sketcher.Constraint(fc, gi(c["a"]), gi(c["b"])))
|
|
1283
|
+
elif form == "size":
|
|
1284
|
+
sk.addConstraint(Sketcher.Constraint(fc, gi(c["a"]), int(c.get("pa", 2)), float(v)))
|
|
1285
|
+
dims.append((c, fc, (gi(c["a"]), int(c.get("pa", 2))), None, float(v)))
|
|
1286
|
+
elif form == "size_one":
|
|
1287
|
+
sk.addConstraint(Sketcher.Constraint(fc, gi(c["a"]), float(v)))
|
|
1288
|
+
dims.append((c, fc, (gi(c["a"]), None), None, float(v)))
|
|
1289
|
+
elif form == "ab2v":
|
|
1290
|
+
sk.addConstraint(Sketcher.Constraint(fc, gi(c["a"]), int(c.get("pa", 1)), gi(c["b"]), int(c.get("pb", 2)), float(v)))
|
|
1291
|
+
dims.append((c, fc, (gi(c["a"]), int(c.get("pa", 1))), (gi(c["b"]), int(c.get("pb", 2))), float(v)))
|
|
1292
|
+
else:
|
|
1293
|
+
sk.addConstraint(Sketcher.Constraint(fc, gi(c["a"]), gi(c["b"]), float(v)))
|
|
1294
|
+
dims.append((c, fc, (gi(c["a"]), None), (gi(c["b"]), None), float(v)))
|
|
1295
|
+
rc = sk.solve()
|
|
1296
|
+
if rc < 0:
|
|
1297
|
+
raise RuntimeError("sketch %s: solver failed (rc=%s), constraints conflict" % (name, rc))
|
|
1298
|
+
doc.recompute()
|
|
1299
|
+
for c, fc, ref1, ref2, want in dims:
|
|
1300
|
+
def _pt(ref):
|
|
1301
|
+
seg = sk.Geometry[ref[0]]
|
|
1302
|
+
return seg.StartPoint if ref[1] == 1 else seg.EndPoint
|
|
1303
|
+
if fc == "Radius":
|
|
1304
|
+
got = sk.Geometry[ref1[0]].Radius
|
|
1305
|
+
elif fc == "Distance":
|
|
1306
|
+
got = (_pt(ref2) - _pt(ref1)).Length
|
|
1307
|
+
elif fc in ("DistanceX", "DistanceY"):
|
|
1308
|
+
p = _pt(ref1)
|
|
1309
|
+
got = p.x if fc == "DistanceX" else p.y
|
|
1310
|
+
else:
|
|
1311
|
+
continue
|
|
1312
|
+
if abs(got - want) > 1e-6:
|
|
1313
|
+
raise RuntimeError("sketch %s: constraint %s not satisfied: want %s got %.4f" % (name, c.get("id"), want, got))
|
|
1314
|
+
wires = sk.Shape.Wires
|
|
1315
|
+
if not wires:
|
|
1316
|
+
raise RuntimeError("sketch %s: not a closed contour (%d curves)" % (name, len(ids)))
|
|
1317
|
+
return wires[0]
|
|
1318
|
+
|
|
1233
1319
|
def _prim(op, _cur=None):
|
|
1234
1320
|
k = op.get("kind")
|
|
1235
1321
|
_at_spec = op.get("at")
|
|
@@ -1247,6 +1333,9 @@ def _prim(op, _cur=None):
|
|
|
1247
1333
|
if k == "torus":
|
|
1248
1334
|
return Part.makeTorus(float(op["r1"]), float(op["r2"]), at, _dir(op.get("axis")))
|
|
1249
1335
|
if k == "extrude":
|
|
1336
|
+
if op.get("sketch"):
|
|
1337
|
+
face = Part.Face(_sketch(str(op["sketch"])))
|
|
1338
|
+
return face.extrude(_dir(op.get("dir"), (0.0, 0.0, float(op.get("h") or 10.0))))
|
|
1250
1339
|
base = float(op.get("base", 0.0))
|
|
1251
1340
|
h = float(op.get("h", 0.0))
|
|
1252
1341
|
# Points may be 2D (z = base) or 3D; dir replaces the +Z extrusion,
|
|
@@ -1764,7 +1853,7 @@ __out = {
|
|
|
1764
1853
|
const scope = typeof args.scope === 'string' ? args.scope : 'auto'
|
|
1765
1854
|
const kind = scope === 'auto' ? undefined : scope
|
|
1766
1855
|
const undone = await bridge.undoSession(kind)
|
|
1767
|
-
if (undone) return { ok: true, scope: undone.kind, undone: undone.label, assembly: undone.assembly, scene: undone.scene, model: undone.model, remaining: bridge.sessionUndo.length, redo: bridge.sessionRedo.length }
|
|
1856
|
+
if (undone) return defined({ ok: true, scope: undone.kind, undone: undone.label, assembly: undone.assembly, scene: undone.scene, model: undone.model, remaining: bridge.sessionUndo.length, redo: bridge.sessionRedo.length })
|
|
1768
1857
|
if (scope !== 'doc') return { ok: false, error: scope === 'assembly' ? '装配层没有可撤销的操作' : scope === 'scene' ? '场景列表没有可撤销的操作' : '没有可撤销的操作' }
|
|
1769
1858
|
const target = typeof args.model === 'string' && args.model ? args.model : ''
|
|
1770
1859
|
if (!target) return { ok: false, error: '文档撤销需要 model 名称(可用 cad_studio_doc list 查看)' }
|
|
@@ -1792,7 +1881,7 @@ __out = {
|
|
|
1792
1881
|
const scope = typeof args.scope === 'string' ? args.scope : 'auto'
|
|
1793
1882
|
const kindR = scope === 'auto' ? undefined : scope
|
|
1794
1883
|
const redone = await bridge.redoSession(kindR)
|
|
1795
|
-
if (redone) return { ok: true, scope: redone.kind, redone: redone.label, assembly: redone.assembly, scene: redone.scene, model: redone.model, remaining: bridge.sessionRedo.length, undo: bridge.sessionUndo.length }
|
|
1884
|
+
if (redone) return defined({ ok: true, scope: redone.kind, redone: redone.label, assembly: redone.assembly, scene: redone.scene, model: redone.model, remaining: bridge.sessionRedo.length, undo: bridge.sessionUndo.length })
|
|
1796
1885
|
if (scope !== 'doc') return { ok: false, error: scope === 'assembly' ? '装配层没有可重做的操作' : '没有可重做的操作' }
|
|
1797
1886
|
const target = typeof args.model === 'string' && args.model ? args.model : ''
|
|
1798
1887
|
if (!target) return { ok: false, error: '文档重做需要 model 名称' }
|
|
@@ -2249,6 +2338,7 @@ ${pair ? ` __out["distance"] = round((FreeCAD.Vector(${JSON.stringify(from)})
|
|
|
2249
2338
|
},
|
|
2250
2339
|
title: { type: 'string', description: 'Panel title for the published scene.' },
|
|
2251
2340
|
export: { type: 'string', description: 'Optional .step/.stp path to also write the result.' },
|
|
2341
|
+
sketches: { type: 'object', description: 'Sketches by name: {S1:{geometry:[{id,type,...}],constraints:[{id,type,...}]}}. A feature extrudes one with {kind:"extrude",sketch:"S1"}.' },
|
|
2252
2342
|
},
|
|
2253
2343
|
required: ['ops'],
|
|
2254
2344
|
additionalProperties: false,
|
|
@@ -2257,11 +2347,11 @@ ${pair ? ` __out["distance"] = round((FreeCAD.Vector(${JSON.stringify(from)})
|
|
|
2257
2347
|
schema: { type: 'object', properties: { ok: { type: 'boolean' }, sceneId: { type: 'string' }, volume: { type: 'number' }, features: { type: 'number' } } },
|
|
2258
2348
|
render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
|
|
2259
2349
|
},
|
|
2260
|
-
execute: async ({ ops, title, export: exportPath }) => {
|
|
2350
|
+
execute: async ({ ops, title, sketches, export: exportPath }) => {
|
|
2261
2351
|
if (!Array.isArray(ops) || !ops.length) return { ok: false, error: 'ops 不能为空:至少给一个图元' }
|
|
2262
2352
|
const unknown = ops.find((op) => !op || !FEATURE_KINDS.includes(op.kind))
|
|
2263
2353
|
if (unknown) return { ok: false, error: `不支持的特征:${unknown?.kind ?? '(空)'}(可用 ${FEATURE_KINDS.join(' / ')})` }
|
|
2264
|
-
const py = featuresScript(ops, exportPath)
|
|
2354
|
+
const py = featuresScript(ops, exportPath, { sketches })
|
|
2265
2355
|
return bridge.run(py, { title: title ?? 'feature' })
|
|
2266
2356
|
},
|
|
2267
2357
|
})
|
|
@@ -2501,9 +2591,11 @@ if _TARGET:
|
|
|
2501
2591
|
}
|
|
2502
2592
|
if (mode === 'remove') {
|
|
2503
2593
|
const before = record.joints.length
|
|
2504
|
-
|
|
2594
|
+
const editRm = bridge.beginAssemblyEdit(record, 'joint remove')
|
|
2595
|
+
record.joints = record.joints.filter((j) => j.id !== joint && j !== joint)
|
|
2505
2596
|
if (record.joints.length === before) return { ok: false, error: `没有这个关节:${joint ?? '(未指定)'}` }
|
|
2506
2597
|
const published = await bridge.republishAssembly(record)
|
|
2598
|
+
bridge.endAssemblyEdit(editRm, record)
|
|
2507
2599
|
return { ok: true, assembly: record.id, removed: joint, sceneId: published.id, joints: record.joints.length }
|
|
2508
2600
|
}
|
|
2509
2601
|
const edit = bridge.beginAssemblyEdit(record, 'joint')
|
|
@@ -2978,6 +3070,33 @@ if _TARGET:
|
|
|
2978
3070
|
* Every mutating action rebuilds the whole list (one FreeCAD run, ~0.2–0.6 s),
|
|
2979
3071
|
* so the model can never be left half-edited — a failed edit is rolled back.
|
|
2980
3072
|
*/
|
|
3073
|
+
/**
|
|
3074
|
+
* Journal a document creation so "undo" removes it again (and the scene row it
|
|
3075
|
+
* published). File bytes are captured after the write, so redo is a plain
|
|
3076
|
+
* restore-and-rebuild — no need to replay the tool arguments.
|
|
3077
|
+
*/
|
|
3078
|
+
const journalDocCreate = async (key, dir, result) => {
|
|
3079
|
+
const file = modelFile(key, dir)
|
|
3080
|
+
let bytes = null
|
|
3081
|
+
try { bytes = await readFile(file) } catch { return }
|
|
3082
|
+
const sceneRow = result?.sceneId ? bridge.history.find((h) => h.id === result.sceneId) : null
|
|
3083
|
+
bridge.journal({
|
|
3084
|
+
kind: 'doc',
|
|
3085
|
+
label: `create ${key}`,
|
|
3086
|
+
undo: async () => {
|
|
3087
|
+
await unlink(file).catch(() => {})
|
|
3088
|
+
if (sceneRow) { try { await bridge.removeScene(sceneRow.id, { journal: false }) } catch {} }
|
|
3089
|
+
return { model: key }
|
|
3090
|
+
},
|
|
3091
|
+
redo: async () => {
|
|
3092
|
+
await writeFile(file, bytes)
|
|
3093
|
+
const doc = await readModel(key, dir)
|
|
3094
|
+
try { await rebuild(doc, dir, { note: 'redo create' }) } catch {}
|
|
3095
|
+
return { model: key }
|
|
3096
|
+
},
|
|
3097
|
+
})
|
|
3098
|
+
}
|
|
3099
|
+
|
|
2981
3100
|
const runFeatureAction = async (args, dir) => {
|
|
2982
3101
|
bridge.noteModelsDir(dir)
|
|
2983
3102
|
const action = String(args.action ?? 'list')
|
|
@@ -3223,6 +3342,7 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
|
|
|
3223
3342
|
if (result.ok === false) return result
|
|
3224
3343
|
doc.history.push({ at: doc.updatedAt, note: args.note ?? 'create', params: JSON.parse(JSON.stringify(doc.params)), features: JSON.parse(JSON.stringify(doc.features)), run: doc.run })
|
|
3225
3344
|
await writeModel(doc, dir)
|
|
3345
|
+
await journalDocCreate(key, dir, result)
|
|
3226
3346
|
return { ...result, kind: 'features', features: publicFeatures(doc) }
|
|
3227
3347
|
}
|
|
3228
3348
|
const doc = {
|
|
@@ -3238,6 +3358,7 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
|
|
|
3238
3358
|
if (result.ok === false) return result
|
|
3239
3359
|
doc.history.push({ at: doc.updatedAt, note: args.note ?? 'create', params: JSON.parse(JSON.stringify(doc.params)), run: doc.run })
|
|
3240
3360
|
await writeModel(doc, dir)
|
|
3361
|
+
await journalDocCreate(key, dir, result)
|
|
3241
3362
|
return result
|
|
3242
3363
|
}
|
|
3243
3364
|
|