dsh-cad-studio 0.20.0 → 0.21.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 (3) hide show
  1. package/README.md +1 -1
  2. package/index.js +297 -0
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -16,7 +16,7 @@ DeepSeek Harness 的 CAD 插件:**把 FreeCAD 桥接成给 AI 用的工具**
16
16
  | 工程文件 | `cad_studio_doc` 存 `script` 或 `features` 两种模型;`cad_studio_features` 改一条特征→整表重算(0.2–0.6 s),失败整表回滚 |
17
17
  | 装配 | `cad_studio_assembly` 读 manifest,`App::Link` 语义的实例位姿;零件是 STEP 文件级引用(改零件重开即跟随);`measure:true` 回每实例体积/包围盒,`interference:true` 回真正重叠的实例对 |
18
18
  | 运动 | `cad_studio_joint`(revolute/linear)+ `cad_studio_drive` + `cad_studio_explode`,面板拖滑杆看运动 |
19
- | 出图 | `cad_studio_drawing` HLR → SVG(主/俯/左/等轴) |
19
+ | 出图 | `cad_studio_drawing` HLR → SVG(主/俯/左/等轴);`cad_studio_sheet` 正式图纸(图框 + 标题栏 + 三视图 + 尺寸,A4/A3/A2,可出 DXF) |
20
20
  | 其它 | `cad_studio_open`(STEP/STL/BREP/IGES 进来看)、`cad_studio_export`、`cad_studio_measure`、`cad_studio_env` |
21
21
  | 模型清单 | `cad_studio_scene`(`action: list / delete / rename`)——面板里那条列表就是它;探查脚本留下的卡片可以直接删 |
22
22
  | 模型改名 / 复制 | `cad_studio_doc {action:"rename", name, to}` 与 `{action:"duplicate", name, to}`:改名会同步列表里的标题与 `docKey`,复制会得到一条独立的新场景(副本不继承运行历史与撤销栈);两者都可 `cad_studio_undo` 回退 |
package/index.js CHANGED
@@ -2414,6 +2414,291 @@ else:
2414
2414
  },
2415
2415
  })
2416
2416
 
2417
+ tool({
2418
+ name: 'cad_studio_sheet',
2419
+ description: 'Write a drawing sheet you can hand to a shop: sheet frame, title block, arranged HLR views (first- or third-angle), overall dimensions in mm, SVG (and optional DXF). Views are oriented to the usual convention (front = width x height, top = width x depth, right = depth x height) by measuring the projection basis instead of assuming it.',
2420
+ parameters: {
2421
+ type: 'object',
2422
+ properties: {
2423
+ target: { type: 'string', description: 'Absolute .svg output path.' },
2424
+ source: { type: 'string', description: 'Existing BRep model file (STEP/IGES/BREP).' },
2425
+ code: { type: 'string', description: 'FreeCAD Python that binds `scene` or `export_shapes`.' },
2426
+ model: { type: 'string', description: 'Draw a saved model document by name instead of a file or a script.' },
2427
+ size: { type: 'string', description: 'Sheet size: A4, A3 or A2 (landscape). Default A3.' },
2428
+ projection: { type: 'string', description: 'first (GB/ISO, default) or third (ASME).' },
2429
+ views: { type: 'array', items: { type: 'string' }, description: 'Subset of ["front","top","right"]. Default all three.' },
2430
+ scale: { type: 'number', description: 'Drawing scale factor, e.g. 0.5 for 1:2. Omit to fit the sheet.' },
2431
+ title: { type: 'string', description: 'Part name for the title block.' },
2432
+ number: { type: 'string', description: 'Drawing number for the title block.' },
2433
+ material: { type: 'string', description: 'Material text for the title block.' },
2434
+ dims: { type: 'boolean', description: 'Draw overall dimension lines (default true).' },
2435
+ dxf: { type: 'boolean', description: 'Also write a sidecar .dxf next to the SVG.' },
2436
+ },
2437
+ required: ['target'],
2438
+ additionalProperties: false,
2439
+ },
2440
+ output: {
2441
+ schema: { type: 'object', properties: { ok: { type: 'boolean' }, path: { type: 'string' }, scale: { type: 'number' } } },
2442
+ render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
2443
+ },
2444
+ execute: async ({ target, source, code, model, size, projection, views, scale, title, number, material, dims, dxf }) => {
2445
+ if (!target || extOf(target) !== 'svg') return { ok: false, error: 'target must be a .svg path' }
2446
+ let src = ''
2447
+ if (typeof model === 'string' && model) {
2448
+ src = await modelShapes(model)
2449
+ if (!src) return { ok: false, error: `没有这个模型:${model}` }
2450
+ } else {
2451
+ const x = shapesFrom({ source, code })
2452
+ if (!x) return { ok: false, error: 'pass either source (a model file), model (a saved document) or code' }
2453
+ src = x
2454
+ }
2455
+ const wanted = Array.isArray(views) && views.length ? views : ['front', 'top', 'right']
2456
+ const py = `${PRELUDE}
2457
+ ${src}
2458
+ import os, re, TechDraw
2459
+ _SIZES = {"A4": (297.0, 210.0), "A3": (420.0, 297.0), "A2": (594.0, 420.0)}
2460
+ # (view direction, horizontal model axis, vertical model axis) — the pair is what
2461
+ # a reader expects: front shows width x height, top shows width x depth.
2462
+ _WANT = {"front": ("X", "Z"), "top": ("X", "Y"), "right": ("Y", "Z")}
2463
+ _CAND = {"front": ((0, -1, 0), (0, 1, 0)), "top": ((0, 0, 1), (0, 0, -1)), "right": ((1, 0, 0), (-1, 0, 0))}
2464
+ _M = 10.0
2465
+ _TBW, _TBH = 180.0, 40.0
2466
+ _GAP = 26.0
2467
+ _PL = 10.0 # probe segment length (mm)
2468
+
2469
+ def _seg(vec):
2470
+ return Part.makeLine(FreeCAD.Vector(0, 0, 0), FreeCAD.Vector(*vec))
2471
+
2472
+ def _nums(d):
2473
+ return [float(x) for x in re.findall(r'-?[0-9]+(?:[.][0-9]+)?(?:[eE]-?[0-9]+)?', d)]
2474
+
2475
+ def _axis_vectors(dv):
2476
+ """Fragment-space image of each model axis, as a unit vector (+-1, 0).
2477
+
2478
+ One 10 mm edge per axis, projected on its own: an axis pointing along the
2479
+ view direction collapses to nothing, the other two give their direction in
2480
+ the fragment. Probing beats guessing — TechDraw's basis is not the naive
2481
+ "front shows X-Z" one.
2482
+ """
2483
+ out = {}
2484
+ for name, vec in (("X", (_PL, 0, 0)), ("Y", (0, _PL, 0)), ("Z", (0, 0, _PL))):
2485
+ frag = TechDraw.projectToSVG(_seg(vec), FreeCAD.Vector(*dv))
2486
+ ds = re.findall(r'd="([^"]+)"', frag)
2487
+ if not ds:
2488
+ continue
2489
+ ns = _nums(ds[0])
2490
+ if len(ns) < 4:
2491
+ continue
2492
+ dx, dy = ns[-2] - ns[0], ns[-1] - ns[1]
2493
+ ln = math.hypot(dx, dy)
2494
+ if ln < 1e-6:
2495
+ continue # this axis is the view direction
2496
+ out[name] = (round(dx / ln), round(dy / ln))
2497
+ return out
2498
+
2499
+ def _solve(view):
2500
+ """Pick a projection direction whose fragment basis is a rotation.
2501
+
2502
+ F maps read-space (u', v') to fragment-space (u, v): its columns are the
2503
+ fragment images of the two read axes. det(F) < 0 means the drawing would be
2504
+ mirrored (a reader would see the part the wrong way round), so the opposite
2505
+ candidate direction wins instead.
2506
+ """
2507
+ pa, pb = _WANT[view]
2508
+ for dv in _CAND[view]:
2509
+ vec = _axis_vectors(dv)
2510
+ if pa not in vec or pb not in vec:
2511
+ continue
2512
+ fu, fv = vec[pa], vec[pb]
2513
+ det = fu[0] * fv[1] - fu[1] * fv[0]
2514
+ if det <= 0:
2515
+ continue
2516
+ inv = (fv[1] / det, -fv[0] / det, -fu[1] / det, fu[0] / det)
2517
+ return {"dir": dv, "inv": inv}
2518
+ return None
2519
+
2520
+ def _remap(frag, inv):
2521
+ """Rewrite the fragment paths in read-space, y flipped for SVG."""
2522
+ ia, ib, ic, id_ = inv
2523
+ out = []
2524
+ for d in re.findall(r'd="([^"]+)"', frag):
2525
+ ns = _nums(d)
2526
+ pts = [(ns[i], ns[i + 1]) for i in range(0, len(ns) - 1, 2)]
2527
+ if not pts:
2528
+ continue
2529
+ q = [(ia * x + ib * y, -(ic * x + id_ * y)) for x, y in pts]
2530
+ out.append("M " + " L ".join("%r %r" % p for p in q))
2531
+ return out
2532
+
2533
+ if not _shapes:
2534
+ __out = {"ok": False, "error": "nothing to draw: pass a source path, a model, or bind scene / export_shapes"}
2535
+ else:
2536
+ _shape = _shapes[0] if len(_shapes) == 1 else Part.makeCompound(_shapes)
2537
+ _SW, _SH = _SIZES.get(str(${JSON.stringify(String(size || 'A3').toUpperCase())}).upper(), _SIZES["A3"])
2538
+ _wanted = [v for v in ${JSON.stringify(wanted)} if v in _WANT] or ["front", "top", "right"]
2539
+ _views = {}
2540
+ _missing = []
2541
+ for _v in _wanted:
2542
+ _sol = _solve(_v)
2543
+ if not _sol:
2544
+ _missing.append(_v)
2545
+ continue
2546
+ _paths = _remap(TechDraw.projectToSVG(_shape, FreeCAD.Vector(*_sol["dir"])), _sol["inv"])
2547
+ _pts = []
2548
+ for _d in _paths:
2549
+ _ns = _nums(_d)
2550
+ _pts += [(_ns[i], _ns[i + 1]) for i in range(0, len(_ns) - 1, 2)]
2551
+ if not _pts:
2552
+ _missing.append(_v)
2553
+ continue
2554
+ _xs = [p[0] for p in _pts]; _ys = [p[1] for p in _pts]
2555
+ _views[_v] = {"paths": _paths, "dir": _sol["dir"],
2556
+ "box": (min(_xs), min(_ys), max(_xs), max(_ys))}
2557
+ if _missing:
2558
+ __out = {"ok": False, "error": "无法为这些视图找到保持手性的投影方向:" + ", ".join(_missing)}
2559
+ else:
2560
+ _need_w = max(_views[v]["box"][2] - _views[v]["box"][0] for v in _wanted) + _GAP
2561
+ _need_h = max(_views[v]["box"][3] - _views[v]["box"][1] for v in _wanted) + _GAP
2562
+ _avail_w = _SW - 2 * _M
2563
+ _avail_h = _SH - 2 * _M - _TBH - 6.0
2564
+ _fit = min(_avail_w / max(_need_w, 1e-6), _avail_h / max(_need_h, 1e-6))
2565
+ _given = float(${Number.isFinite(scale) && Number(scale) > 0 ? Number(scale) : 0})
2566
+ if _given > 0:
2567
+ _scale = _given
2568
+ else:
2569
+ _scale = 0.0
2570
+ for _cand in (2.0, 1.5, 1.0, 0.5, 0.4, 0.25, 0.2, 0.1, 0.05):
2571
+ if _cand <= _fit:
2572
+ _scale = _cand
2573
+ break
2574
+ if _scale <= 0:
2575
+ _scale = _fit
2576
+
2577
+ def _size(view):
2578
+ _bx = _views[view]["box"]
2579
+ return ((_bx[2] - _bx[0]) * _scale, (_bx[3] - _bx[1]) * _scale)
2580
+
2581
+ _first = str(${JSON.stringify(String(projection || 'first').toLowerCase())}).lower() != "third"
2582
+ _cells = {}
2583
+ _fw, _fh = _size("front") if "front" in _views else (0.0, 0.0)
2584
+ for _v in _wanted:
2585
+ _w, _h = _size(_v)
2586
+ if _v == "front":
2587
+ _cells[_v] = (0.0, 0.0, _w, _h)
2588
+ elif _v == "top":
2589
+ _cells[_v] = (0.0, (_fh + _GAP) if _first else -(_h + _GAP), _w, _h)
2590
+ else:
2591
+ _cells[_v] = ((_fw + _GAP) if not _first else -(_w + _GAP), 0.0, _w, _h)
2592
+ _minx = min(c[0] for c in _cells.values()); _miny = min(c[1] for c in _cells.values())
2593
+ _maxx = max(c[0] + c[2] for c in _cells.values()); _maxy = max(c[1] + c[3] for c in _cells.values())
2594
+ _offx = _M + (_avail_w - (_maxx - _minx)) / 2.0 - _minx
2595
+ _offy = _M + (_avail_h - (_maxy - _miny)) / 2.0 - _miny
2596
+
2597
+ _views_svg = []; _dims_svg = []; _labels = []; _dim_list = []
2598
+ _draw_dims = bool(${dims === false ? 'False' : 'True'})
2599
+ for _v in _wanted:
2600
+ _vv = _views[_v]
2601
+ _n0x, _n0y, _n1x, _n1y = _vv["box"]
2602
+ _bw = _n1x - _n0x; _bh = _n1y - _n0y
2603
+ _cx, _cy, _w, _h = _cells[_v]
2604
+ _px = _cx + _offx; _py = _cy + _offy
2605
+ # The paths are already in read-space (y down); place the bbox corner
2606
+ # at the cell corner and scale.
2607
+ _views_svg.append('<g fill="none" stroke="#111" stroke-width="0.25" stroke-linejoin="round" stroke-linecap="round" '
2608
+ 'transform="translate(%r %r) scale(%r)">%s</g>' % (
2609
+ _px - _n0x * _scale, _py - _n0y * _scale, _scale,
2610
+ "".join('<path d="%s"/>' % _d for _d in _vv["paths"])))
2611
+ _labels.append('<text x="%r" y="%r" font-size="3.0" fill="#555" font-family="sans-serif" text-anchor="middle">%s</text>' % (
2612
+ _px + _w / 2.0, _py - 3.0, {"front": "主视图", "top": "俯视图", "right": "左视图"}.get(_v, _v)))
2613
+ _wm = round(_bw, 2); _hm = round(_bh, 2)
2614
+ _dim_list.append({"view": _v, "width_mm": _wm, "height_mm": _hm})
2615
+ if _draw_dims and _w > 1e-6 and _h > 1e-6:
2616
+ _yd = _py + _h + 9.0
2617
+ _xd = _px + _w + 9.0
2618
+ _dims_svg.append('<g stroke="#111" stroke-width="0.25" fill="none">'
2619
+ '<path d="M %r %r L %r %r" stroke-dasharray="1,1"/>'
2620
+ '<path d="M %r %r L %r %r" stroke-dasharray="1,1"/>'
2621
+ '<path d="M %r %r L %r %r"/>'
2622
+ '<path d="M %r %r L %r %r" stroke-dasharray="1,1"/>'
2623
+ '<path d="M %r %r L %r %r" stroke-dasharray="1,1"/>'
2624
+ '<path d="M %r %r L %r %r"/></g>' % (
2625
+ _px, _py + _h, _px, _yd + 2.0, _px + _w, _py + _h, _px + _w, _yd + 2.0,
2626
+ _px, _yd, _px + _w, _yd,
2627
+ _px + _w, _py, _xd + 2.0, _py, _px + _w, _py + _h, _xd + 2.0, _py + _h,
2628
+ _xd, _py, _xd, _py + _h))
2629
+ _dims_svg.append('<text x="%r" y="%r" font-size="3.2" fill="#111" text-anchor="middle" font-family="sans-serif">%s</text>' % (
2630
+ _px + _w / 2.0, _yd + 4.2, _wm))
2631
+ _dims_svg.append('<text x="%r" y="%r" font-size="3.2" fill="#111" text-anchor="middle" font-family="sans-serif" transform="rotate(90 %r %r)">%s</text>' % (
2632
+ _xd + 7.0, _py + _h / 2.0, _xd + 7.0, _py + _h / 2.0, _hm))
2633
+
2634
+ _frame = ('<g stroke="#111" fill="none" stroke-width="0.5">'
2635
+ '<rect x="%r" y="%r" width="%r" height="%r"/>'
2636
+ '<rect x="%r" y="%r" width="%r" height="%r"/></g>' % (
2637
+ _M, _M, _SW - 2 * _M, _SH - 2 * _M,
2638
+ _M + 2.0, _M + 2.0, _SW - 2 * _M - 4.0, _SH - 2 * _M - 4.0))
2639
+ _tb_x = _SW - _M - _TBW
2640
+ _tb_y = _SH - _M - _TBH
2641
+ _title = str(${JSON.stringify(typeof title === 'string' ? title : '')}) or os.path.splitext(os.path.basename(${JSON.stringify(target)}))[0]
2642
+ _number = str(${JSON.stringify(typeof number === 'string' ? number : '')})
2643
+ _material = str(${JSON.stringify(typeof material === 'string' ? material : '')})
2644
+ _scale_txt = ("1:%g" % round(1.0 / _scale, 4)) if _scale < 1.0 else (("%g:1" % _scale) if _scale > 1.0 else "1:1")
2645
+ _tb = ['<g stroke="#111" fill="none" stroke-width="0.4">'
2646
+ '<rect x="%r" y="%r" width="%r" height="%r"/>'
2647
+ '<path d="M %r %r L %r %r"/><path d="M %r %r L %r %r"/><path d="M %r %r L %r %r"/></g>' % (
2648
+ _tb_x, _tb_y, _TBW, _TBH,
2649
+ _tb_x, _tb_y + 12.0, _tb_x + _TBW, _tb_y + 12.0,
2650
+ _tb_x, _tb_y + 24.0, _tb_x + _TBW, _tb_y + 24.0,
2651
+ _tb_x + 100.0, _tb_y + 12.0, _tb_x + 100.0, _tb_y + _TBH)]
2652
+ _tb.append('<text x="%r" y="%r" font-size="4.4" font-weight="600" fill="#111" font-family="sans-serif">%s</text>' % (
2653
+ _tb_x + 3.0, _tb_y + 8.4, _title.replace("&", "&amp;").replace("<", "&lt;")))
2654
+ _tb.append('<text x="%r" y="%r" font-size="3.2" fill="#333" font-family="sans-serif">图号 %s</text>' % (
2655
+ _tb_x + 3.0, _tb_y + 19.4, (_number or "-")))
2656
+ _tb.append('<text x="%r" y="%r" font-size="3.2" fill="#333" font-family="sans-serif">材料 %s</text>' % (
2657
+ _tb_x + 3.0, _tb_y + 31.4, (_material or "-")))
2658
+ _tb.append('<text x="%r" y="%r" font-size="3.2" fill="#333" font-family="sans-serif">比例 %s</text>' % (
2659
+ _tb_x + 103.0, _tb_y + 19.4, _scale_txt))
2660
+ _tb.append('<text x="%r" y="%r" font-size="3.2" fill="#333" font-family="sans-serif">图幅 %s · 单位 mm</text>' % (
2661
+ _tb_x + 103.0, _tb_y + 31.4, str(${JSON.stringify(String(size || 'A3').toUpperCase())})))
2662
+ _tb.append('<text x="%r" y="%r" font-size="2.8" fill="#666" font-family="sans-serif">%s</text>' % (
2663
+ _tb_x + 103.0, _tb_y + 8.4, __import__("datetime").date.today().isoformat()))
2664
+ _svg = ('<svg xmlns="http://www.w3.org/2000/svg" width="%rmm" height="%rmm" viewBox="0 0 %r %r">'
2665
+ '<rect width="100%%" height="100%%" fill="white"/>%s%s%s%s%s</svg>') % (
2666
+ _SW, _SH, _SW, _SH, _frame, "".join(_views_svg), "".join(_dims_svg), "".join(_labels), "".join(_tb))
2667
+ os.makedirs(os.path.dirname(${JSON.stringify(target)}) or ".", exist_ok=True)
2668
+ open(${JSON.stringify(target)}, "w").write(_svg)
2669
+ __out = {"ok": True, "path": ${JSON.stringify(target)}, "bytes": os.path.getsize(${JSON.stringify(target)}),
2670
+ "sheet_mm": [_SW, _SH], "scale": round(_scale, 4), "views": _wanted,
2671
+ "projection": "first" if _first else "third", "dimensions": _dim_list,
2672
+ "directions": {v: list(_views[v]["dir"]) for v in _wanted}}
2673
+ `
2674
+ const out = await bridge.run(py, { title: `sheet → ${target}`, publishHint: false })
2675
+ if (out && out.ok && dxf) {
2676
+ const side = target.replace(/\.svg$/i, '.dxf')
2677
+ const py2 = `${PRELUDE}
2678
+ ${src}
2679
+ import os, TechDraw
2680
+ _doc = FreeCAD.newDocument("sheet")
2681
+ _obj = _doc.addObject("Part::Feature", "S")
2682
+ _obj.Shape = _shapes[0] if len(_shapes) == 1 else Part.makeCompound(_shapes)
2683
+ _page = _doc.addObject("TechDraw::DrawPage", "Page")
2684
+ for _v, _dir in (("front", (0, -1, 0)), ("top", (0, 0, 1)), ("right", (1, 0, 0))):
2685
+ _view = _doc.addObject("TechDraw::DrawViewPart", "V" + _v)
2686
+ _page.addView(_view)
2687
+ _view.Source = [_obj]
2688
+ _view.Direction = _dir
2689
+ _doc.recompute()
2690
+ _side = ${JSON.stringify(side)}
2691
+ os.makedirs(os.path.dirname(_side) or ".", exist_ok=True)
2692
+ TechDraw.writeDXFPage(_page, _side)
2693
+ __out = {"ok": True, "path": _side, "bytes": os.path.getsize(_side)}
2694
+ `
2695
+ const d = await bridge.run(py2, { title: `sheet dxf → ${side}`, publishHint: false })
2696
+ if (d && d.ok) out.dxf = { path: d.path, bytes: d.bytes }
2697
+ }
2698
+ return out
2699
+ },
2700
+ })
2701
+
2417
2702
  tool({
2418
2703
  name: 'cad_studio_measure',
2419
2704
  description: 'Measure a model: volume, surface area, bounding box, centroid, face/edge counts, and optionally the distance between two points.',
@@ -3821,6 +4106,18 @@ if _TARGET:
3821
4106
  * the emitter. A feature model runs its own `featuresScript` (which already
3822
4107
  * knows how to export); a script model gets three extra lines appended.
3823
4108
  */
4109
+ /** Python source that rebuilds a saved model's shapes into `_shapes`. */
4110
+ async function modelShapes(name) {
4111
+ const dirs = bridge.modelsCandidates()
4112
+ const dir = dirs.find((d) => existsSync(join(d, `${name}.json`))) || dirs[0]
4113
+ if (!existsSync(join(dir, `${name}.json`))) return ''
4114
+ const doc = await readModel(name, dir)
4115
+ bridge.noteModelsDir(dir)
4116
+ return doc.kind === 'features'
4117
+ ? featuresScript(featureOps(doc), '', { sketches: doc.sketches })
4118
+ : `${PRELUDE}\nP = ${JSON.stringify(doc.params ?? {})}\n${doc.script}\n`
4119
+ }
4120
+
3824
4121
  async function exportModelStep(doc, target) {
3825
4122
  if (typeof target !== 'string' || !target) throw new Error('export 需要目标路径,例如 /path/model.step')
3826
4123
  await mkdir(dirname(target), { recursive: true })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cad-studio",
3
- "version": "0.20.0",
3
+ "version": "0.21.0",
4
4
  "type": "module",
5
5
  "description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
6
6
  "exports": {