Skip to content

armgit / SOMA

Public Imported from GitHub
0

Desktop app for designing parametric 3D models in CadQuery together with the coding agent of your choice

soma: CadQuery-Skripte rein und raus (E100, E101)

Kai-Jungsthoefel132b8a02b2c6
diff --git a/python/soma/animrun.py b/python/soma/animrun.py
index 0fa5b07..259a5a0 100644
--- a/python/soma/animrun.py
+++ b/python/soma/animrun.py
@@ -15,7 +15,7 @@ from pathlib import Path
import numpy as np
-from . import anim, build, gltf, registry
+from . import anim, build, cqcompat, gltf, registry
ANIM_DIR = "animations"
OUT_DIR = Path(".soma") / "anim"
@@ -92,7 +92,8 @@ def _run_file(root, path):
mod.__name__, mod.__file__ = mod_name, str(script)
sys.modules[mod_name] = mod
try:
- runpy.run_path(str(path), run_name="__main__")
+ with cqcompat.hooks(): # importiert die Datei ein CadQuery-Skript mit show_object(), bleibt das wirkungslos
+ runpy.run_path(str(path), run_name="__main__")
except SystemExit as e:
if e.code not in (None, 0):
raise build.BuildError(f"{_rel(path, root)} exited with code {e.code}", file=_rel(path, root), kind="SystemExit")
diff --git a/python/soma/build.py b/python/soma/build.py
index 74dc88b..2d311f9 100644
--- a/python/soma/build.py
+++ b/python/soma/build.py
@@ -15,7 +15,7 @@ from pathlib import Path
import cadquery as cq
-from . import measure, mesher, params, registry
+from . import cqcompat, measure, mesher, params, registry
DEFAULT_ENTRY = "model.py"
# Fassung von model.glb, model.map.json und geometry/. Die App zeigt beim Oeffnen den letzten Build ohne neu zu bauen, aber
@@ -169,6 +169,8 @@ def _is_inside(path, root):
# Einstiegspunkt und Namensraum des letzten erfolgreichen run_model(). Animationen importieren daraus (`from model import
# ...`), statt das ganze Modell ein zweites Mal auszufuehren (animrun._run_file).
LAST_RUN = None
+# Hinweis des letzten run_model(), wenn die Teile aus show_object()/result kamen (Kompatibilitaetsmodus, E100), sonst None
+COMPAT_WARNING = None
def run_model(root, entry=None):
@@ -180,15 +182,19 @@ def run_model(root, entry=None):
raise BuildError(
f"Entry point {entry!r} not found. Create {DEFAULT_ENTRY} or set \"entry\" in .soma/project.json.",
kind="EntryMissing")
- global LAST_RUN
+ global LAST_RUN, COMPAT_WARNING
registry.REGISTRY.clear()
+ COMPAT_WARNING = None
params.begin(root) # Werte des Nutzers aus parameters.json (Parameter-Panel)
LAST_RUN = None
old_cwd = os.getcwd()
os.chdir(root)
sys.path.insert(0, str(root))
try:
- LAST_RUN = (script, runpy.run_path(str(script), run_name="__main__"))
+ with cqcompat.hooks():
+ LAST_RUN = (script, runpy.run_path(str(script), init_globals=cqcompat.script_globals(), run_name="__main__"))
+ if not registry.REGISTRY: # ein CadQuery-Skript ohne add_part()
+ COMPAT_WARNING = cqcompat.register_shown(LAST_RUN[1], script)
except BuildError:
raise
except SystemExit as e:
@@ -203,7 +209,8 @@ def run_model(root, entry=None):
if not registry.REGISTRY:
raise BuildError(
"No part registered. Call add_part(name, obj) for every part "
- "(from soma import add_part).", file=entry, kind="NoParts")
+ "(from soma import add_part). Plain CadQuery scripts work too with show_object(obj, name=...) "
+ "or a variable result.", file=entry, kind="NoParts")
return list(registry.REGISTRY)
@@ -310,6 +317,8 @@ def _run_build(root):
timings.update(out["timings"])
result.update(parts=[dict(name=p["name"], role=p["role"], file=p["file"], line=p["line"]) for p in out["map_parts"]],
glb_bytes=out["glb_bytes"], tolerance=out["tolerance"])
+ if COMPAT_WARNING:
+ result["warnings"].append(COMPAT_WARNING)
result["warnings"].extend(params.unused_warnings())
# Zusatzpakete, die das Modell geladen hat, in requirements.txt (E67). Ein Fehler dabei kostet den Build nicht
try:
diff --git a/python/soma/cli.py b/python/soma/cli.py
index 42ab08c..f766827 100644
--- a/python/soma/cli.py
+++ b/python/soma/cli.py
@@ -161,6 +161,35 @@ def cmd_glb(args):
return 0
+def cmd_cadquery(args):
+ """Export als CadQuery-Skript bzw. Import eines CadQuery-Skripts (E100)."""
+ from . import cqexport
+ try:
+ if args.action == "export":
+ if not args.out:
+ print("export needs --out (a .py file, or a folder for models with parts/)", file=sys.stderr)
+ return 2
+ r = cqexport.export(args.project, args.out)
+ else:
+ if not args.script:
+ print("import needs the script, e.g. soma cadquery import box.py --project .", file=sys.stderr)
+ return 2
+ r = cqexport.import_script(args.script, args.project, backup=args.backup)
+ except cqexport.ExportError as e:
+ print(json.dumps(dict(status="error", error=str(e)), ensure_ascii=False) if args.json else str(e),
+ file=sys.stdout if args.json else sys.stderr)
+ return 1
+ if args.json:
+ print(json.dumps(dict(status="ok", **r), ensure_ascii=False))
+ else:
+ verb = "exported" if args.action == "export" else "imported"
+ for f in r["files"]:
+ print(f"{verb}: {f}")
+ for w in r["warnings"]:
+ print(f"Note: {w}")
+ return 0
+
+
def cmd_warm(args):
"""Vorgewaermter Prozess der App: Python und cadquery sind geladen (rund 3 s), bevor es etwas zu tun gibt. Den Auftrag
schickt die App als eine JSON-Zeile, z. B. {"cwd": "<Ordner>", "argv": ["build", "--project", "<Ordner>", "--json"]}.
@@ -423,6 +452,15 @@ def main(argv=None):
e.add_argument("--project", default=".")
e.set_defaults(func=cmd_export)
+ q = sub.add_parser("cadquery", help="export the model as a plain CadQuery script, or import one (round trip)")
+ q.add_argument("action", choices=["export", "import"])
+ q.add_argument("script", nargs="?", help="import: the CadQuery script (.py)")
+ q.add_argument("--out", help="export: target .py file (a folder for models with parts/)")
+ q.add_argument("--backup", help="import: folder for files of the model that the import replaces")
+ q.add_argument("--project", default=".")
+ q.add_argument("--json", action="store_true")
+ q.set_defaults(func=cmd_cadquery)
+
g = sub.add_parser("glb", help="convert a STEP file to GLB for the viewer (basic mode)")
g.add_argument("step", help="STEP file")
g.add_argument("--out", required=True, help="target folder (model.glb and model.map.json)")
diff --git a/python/soma/cqcompat.py b/python/soma/cqcompat.py
new file mode 100644
index 0000000..62403ea
--- /dev/null
+++ b/python/soma/cqcompat.py
@@ -0,0 +1,210 @@
+"""Kompatibilitaetsmodus (E100): CadQuery-Skripte ohne add_part() bauen trotzdem.
+
+Ein Skript aus CQ-editor ruft `show_object(obj, name=..., options={"color": ..., "alpha": ...})`, eines fuer VS Code
+`from ocp_vscode import show` und `show(a, b, names=[...], colors=[...])`, manche legen nur `result` an. Waehrend
+run_model() stehen dafuer Ersatzfunktionen bereit, die die Aufrufe mit Datei und Zeile sammeln. Hat das Skript kein
+add_part() aufgerufen, werden daraus die Bauteile (Klick->Code zeigt auf den Aufruf), der Build meldet das als Warnung.
+Ruft das Skript add_part(), gelten nur diese Teile, show_object() bleibt dann wirkungslos.
+"""
+import builtins
+import contextlib
+import inspect
+import sys
+import types
+
+import cadquery as cq
+
+from . import registry
+
+SHOWN = [] # je Lauf von hooks() geleert: dict(obj, name, color, alpha, file, line, end_line)
+WARNING = ("Compatibility mode: the script calls no add_part(), so its {n} part(s) come from {how}. Names and colors are "
+ "taken from there. To convert it to add_part() and param(), ask the agent (skill \"CadQuery scripts\", .soma/skills/cadquery-scripts.md).")
+
+
+def _where(depth):
+ """Datei und Zeilen des Aufrufs im Skript, `depth` Rahmen ueber dem Aufrufer dieser Funktion."""
+ frame = inspect.currentframe().f_back
+ for _ in range(depth):
+ frame = frame.f_back
+ pos = inspect.getframeinfo(frame, context=0).positions
+ line = pos.lineno if pos and pos.lineno else frame.f_lineno
+ return frame, dict(file=frame.f_code.co_filename, line=line, end_line=(pos.end_lineno if pos and pos.end_lineno else line))
+
+
+def _var_name(frame, obj):
+ """Name der Variablen, die `obj` haelt (wie ocp_vscode ihn zeigt), sonst None."""
+ for ns in (frame.f_locals, frame.f_globals):
+ for k, v in ns.items():
+ if v is obj and not k.startswith("_"):
+ return k
+ return None
+
+
+def _color(c):
+ """Farbe aus CQ-editor/ocp_vscode als ((r, g, b) 0..1, alpha) oder (None, None). Unbekanntes wird ignoriert."""
+ if c is None:
+ return None, None
+ try:
+ if isinstance(c, cq.Color):
+ t = c.toTuple()
+ return tuple(t[:3]), (t[3] if len(t) > 3 else None)
+ if isinstance(c, str):
+ s = c.strip()
+ if s.startswith("#") and len(s) in (7, 9):
+ v = [int(s[i:i + 2], 16) / 255 for i in range(1, len(s), 2)]
+ return tuple(v[:3]), (v[3] if len(v) > 3 else None)
+ t = cq.Color(s).toTuple() # Farbnamen von OCCT, etwa "red", "steelblue"
+ return tuple(t[:3]), None
+ v = [float(x) for x in c]
+ if len(v) in (3, 4):
+ if any(x > 1 for x in v[:3]): # CQ-editor nimmt auch 0..255
+ v[:3] = [x / 255 for x in v[:3]]
+ return tuple(max(0.0, min(1.0, x)) for x in v[:3]), (v[3] if len(v) > 3 else None)
+ except Exception: # noqa: BLE001 (fremde Farbangaben duerfen den Build nicht kosten)
+ pass
+ return None, None
+
+
+def _collect(obj, name, color, alpha, where, frame, how="show_object()"):
+ if registry.IGNORE_ADD: # Animation/Zeichnung importiert das Modell: die Teile sind schon bekannt
+ return
+ if isinstance(obj, (list, tuple)):
+ for o in obj:
+ _collect(o, None, color, alpha, where, frame, how)
+ return
+ rgb, a = _color(color)
+ SHOWN.append(dict(obj=obj, name=name or _var_name(frame, obj), color=rgb,
+ alpha=alpha if alpha is not None else a, how=how, **where))
+
+
+def show_object(obj, name=None, options=None, **_kw):
+ """Ersatz fuer show_object() aus CQ-editor (und cq-cli): merkt sich das Objekt fuer den Build."""
+ frame, where = _where(1)
+ options = options if isinstance(options, dict) else {}
+ alpha = options.get("alpha")
+ _collect(obj, name, options.get("color"), float(alpha) if isinstance(alpha, (int, float)) else None, where, frame)
+
+
+def debug(_obj, *_a, **_kw):
+ """debug() aus CQ-editor zeigt Hilfsgeometrie in Rot. Sie gehoert nicht zum Modell."""
+
+
+def log(*a, **_kw):
+ print(*a, file=sys.stderr)
+
+
+class _Noop:
+ """Fuer alles, was ocp_vscode sonst noch bietet (set_port, Camera.RESET, ...): tut nichts."""
+
+ def __call__(self, *_a, **_kw):
+ return None
+
+ def __getattr__(self, _name):
+ return self
+
+
+def _ocp_show(*objs, names=None, colors=None, alphas=None, **_kw):
+ frame, where = _where(1)
+ for i, o in enumerate(objs):
+ pick = lambda seq: seq[i] if isinstance(seq, (list, tuple)) and i < len(seq) else None # noqa: E731
+ a = pick(alphas)
+ _collect(o, pick(names), pick(colors), float(a) if isinstance(a, (int, float)) else None, where, frame,
+ "show() of ocp_vscode")
+
+
+def _ocp_show_object(obj, name=None, options=None, **kw):
+ frame, where = _where(1)
+ options = options if isinstance(options, dict) else {}
+ alpha = options.get("alpha", kw.get("alpha"))
+ _collect(obj, name, options.get("color", kw.get("color")), float(alpha) if isinstance(alpha, (int, float)) else None, where, frame,
+ "show_object() of ocp_vscode")
+
+
+def _ocp_show_all(*_a, **_kw):
+ """show_all() zeigt alle CadQuery-Objekte im Namensraum des Aufrufers."""
+ frame, where = _where(1)
+ for k, v in list(frame.f_locals.items()):
+ if not k.startswith("_") and isinstance(v, (cq.Workplane, cq.Shape, cq.Assembly)):
+ _collect(v, k, None, None, where, frame, "show_all() of ocp_vscode")
+
+
+def _ocp_module():
+ mod = types.ModuleType("ocp_vscode")
+ mod.__doc__ = "Stand-in of SOMA for ocp_vscode: show() and show_object() hand the objects to soma build."
+ mod.show, mod.show_object, mod.show_all = _ocp_show, _ocp_show_object, _ocp_show_all
+ mod.__all__ = ["show", "show_object", "show_all", "show_clear", "reset_show", "set_port", "set_defaults",
+ "get_defaults", "reset_defaults", "set_viewer_config", "Camera", "Collapse", "Animation", "status"]
+ noop = _Noop()
+
+ def attr(name):
+ if name.startswith("__"): # importlib und pickle fragen nach __path__, __spec__ ...
+ raise AttributeError(name)
+ return noop
+ mod.__getattr__ = attr
+ return mod
+
+
+def script_globals():
+ """Fuer den Namensraum des Einstiegspunkts, wie CQ-editor ihn vorbelegt: Viele Skripte fragen
+ `if "show_object" in globals()` und exportieren sonst selbst eine Datei. Die eingebauten Namen aus hooks() sieht diese
+ Abfrage nicht."""
+ return dict(show_object=show_object, debug=debug, log=log)
+
+
+def hooks():
+ """Ersatzfunktionen fuer die Dauer eines Laufs: show_object/debug/log als eingebaute Namen (wie CQ-editor sie
+ bereitstellt, so finden auch Module in parts/ sie) und ein Ersatzmodul ocp_vscode. Danach alles wie vorher."""
+ SHOWN.clear()
+ missing = object()
+ saved = {k: getattr(builtins, k, missing) for k in ("show_object", "debug", "log")}
+ old_mod = sys.modules.get("ocp_vscode", missing)
+ builtins.show_object, builtins.debug, builtins.log = show_object, debug, log
+ sys.modules["ocp_vscode"] = _ocp_module()
+ try:
+ yield
+ finally:
+ for k, v in saved.items():
+ if v is missing:
+ with contextlib.suppress(AttributeError):
+ delattr(builtins, k)
+ else:
+ setattr(builtins, k, v)
+ if old_mod is missing:
+ sys.modules.pop("ocp_vscode", None)
+ else:
+ sys.modules["ocp_vscode"] = old_mod
+
+
+def _unique(name, taken):
+ base, i = name, 2
+ while name in taken:
+ name, i = f"{base} ({i})", i + 1
+ return name
+
+
+def register_shown(namespace, script):
+ """Nach dem Lauf, wenn kein add_part() kam: gesammelte Objekte als Bauteile eintragen, sonst `result`.
+ Liefert die Warnung fuer build.json oder None, wenn es nichts gab. Fehler einzelner Objekte werden Warnungen."""
+ items = list(SHOWN)
+ if not items:
+ res = namespace.get("result")
+ if isinstance(res, (cq.Workplane, cq.Shape, cq.Assembly)) or hasattr(res, "__soma_shape__"):
+ items = [dict(obj=res, name="result", color=None, alpha=None, how="the variable result",
+ file=str(script), line=None, end_line=None)]
+ if not items:
+ return None
+ taken, skipped = set(), []
+ for i, it in enumerate(items):
+ name = _unique(str(it["name"] or f"Part {i + 1}").strip() or f"Part {i + 1}", taken)
+ try:
+ registry._add(name, it["obj"], None, it["color"], None,
+ dict(file=it["file"], line=it["line"], end_line=it["end_line"]), alpha=it["alpha"])
+ taken.add(name)
+ except (TypeError, ValueError) as e:
+ skipped.append(f"{name}: {e}")
+ hows = sorted({it["how"] for it in items})
+ msg = WARNING.format(n=len(registry.REGISTRY), how=" and ".join(hows))
+ if skipped:
+ msg += " Skipped: " + "; ".join(skipped)
+ return msg
diff --git a/python/soma/cqexport.py b/python/soma/cqexport.py
new file mode 100644
index 0000000..93a058a
--- /dev/null
+++ b/python/soma/cqexport.py
@@ -0,0 +1,411 @@
+"""CadQuery rein und raus (E100): "Export as CadQuery" und "New model from CadQuery script".
+
+Export: Der Modellcode bleibt Zeichen fuer Zeichen gleich. Nur die Zeilen `from soma import ...` und
+`from soma.fasteners import ...` werden ersetzt: Jede Originalzeile bleibt als Kommentar `# soma-import: ...` stehen,
+beim ersten Import folgt ein markierter Block mit add_part(), param(), import_step(), import_assembly() und bei Bedarf
+den Normteilen samt Tabellen (cqruntime.py, Apache 2.0, E101). Am Ende ruft ein Fussblock show_object() (CQ-editor,
+cq-cli) bzw. ocp_vscode auf und legt `result` an. Ein Modell mit eigenen Modulen (parts/) wird ein Ordner mit
+soma_compat.py statt des Blocks.
+
+Import: Die Markierungen werden zurueckgedreht (Block und Fussblock fallen weg, die Originalzeilen kommen zurueck), die
+Werte des Parameter-Panels gehen nach parameters.json. Ein Skript ohne Markierungen bleibt unveraendert, es baut im
+Kompatibilitaetsmodus (cqcompat.py). Wurde der Block veraendert, bleibt er stehen und das wird gemeldet (E28).
+"""
+import ast
+import hashlib
+import json
+import re
+import shutil
+from pathlib import Path
+
+from . import __version__, params
+from .build import DEFAULT_ENTRY, read_project_json
+
+CORE = ("add_part", "param", "import_step", "import_assembly")
+FASTENERS = ("Screw", "Nut", "Washer", "HeatSetInsert", "lengths", "pick_length", "standards") # = fasteners.__all__
+MARK = "# soma-import: "
+BLOCK_START = "# >>> soma-compat"
+BLOCK_END = "# <<< soma-compat"
+FOOTER_START = "# >>> soma-compat footer"
+FOOTER_END = "# <<< soma-compat footer"
+CHECK = "# soma-checksum: "
+TAG = " # soma-compat" # Ende der Importzeile, die im Ordner-Export an die Stelle der soma-Imports tritt
+VALUES = "_SOMA_VALUES = " # die einzige Zeile des Blocks, die der Nutzer aendern darf (nicht in der Pruefsumme)
+COMPAT_MODULE = "soma_compat"
+_HERE = Path(__file__).parent
+
+
+class ExportError(Exception):
+ pass
+
+
+# --- Quelltext untersuchen ---------------------------------------------------------------------------------------------
+
+def _soma_imports(tree, rel):
+ """soma-Imports der Datei als [(Knoten, Modul, [(Name, Alias)])], nach Zeile. Was der Export nicht abbilden kann
+ (import soma, soma.anim, Imports in Funktionen, zwei Anweisungen in einer Zeile), ist ein Fehler mit Zeile."""
+ found = []
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ for a in node.names:
+ if a.name == "soma" or a.name.startswith("soma."):
+ raise ExportError(f"{rel}, line {node.lineno}: `import {a.name}` cannot be exported. "
+ "Write `from soma import add_part, param` (or from soma.fasteners import ...) instead.")
+ elif isinstance(node, ast.ImportFrom) and node.level == 0 and (node.module == "soma" or (node.module or "").startswith("soma.")):
+ allowed = CORE if node.module == "soma" else FASTENERS if node.module == "soma.fasteners" else None
+ if allowed is None:
+ raise ExportError(f"{rel}, line {node.lineno}: {node.module} only works in SOMA and cannot be exported.")
+ if node not in tree.body:
+ raise ExportError(f"{rel}, line {node.lineno}: the import from {node.module} must be at the top level of the file.")
+ names = []
+ for a in node.names:
+ if a.name == "*":
+ names += [(n, n) for n in allowed]
+ elif a.name in allowed:
+ names.append((a.name, a.asname or a.name))
+ else:
+ raise ExportError(f"{rel}, line {node.lineno}: {node.module}.{a.name} cannot be exported "
+ f"(possible: {', '.join(allowed)}).")
+ found.append((node, node.module, names))
+ for node, _, _ in found:
+ for other in tree.body:
+ if other is not node and other.lineno <= node.end_lineno and other.end_lineno >= node.lineno:
+ raise ExportError(f"{rel}, line {node.lineno}: put the import from {node.module} on lines of its own.")
+ return sorted(found, key=lambda f: f[0].lineno)
+
+
+def _module_files(base, rel, tree):
+ """Eigene Module, die die Datei importiert, als Pfade relativ zu `base` (parts/lid.py, parts/__init__.py ...)."""
+ pkg = Path(rel).parent
+ wanted = []
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ wanted += [a.name for a in node.names]
+ elif isinstance(node, ast.ImportFrom):
+ if node.level:
+ up = pkg
+ for _ in range(node.level - 1):
+ up = up.parent
+ mod = ".".join([*up.parts, *(node.module.split(".") if node.module else [])])
+ else:
+ mod = node.module or ""
+ if mod:
+ wanted += [mod] + [f"{mod}.{a.name}" for a in node.names if a.name != "*"]
+ out = []
+ for mod in wanted:
+ parts = mod.split(".")
+ if parts[0] in ("soma", COMPAT_MODULE):
+ continue
+ for i in range(1, len(parts) + 1): # auch die Pakete auf dem Weg (parts/__init__.py)
+ stem = Path(*parts[:i])
+ for cand in (stem.with_suffix(".py"), stem / "__init__.py"):
+ if (base / cand).is_file() and cand.as_posix() not in out:
+ out.append(cand.as_posix())
+ return out
+
+
+def _all_files(base, entry, strict=True):
+ """Einstiegspunkt und alle eigenen Module, die er (auch ueber andere) importiert. `strict=False` (Import): Eine Datei
+ mit Syntaxfehler wird trotzdem uebernommen, nur ihre Imports bleiben unbekannt. Den Fehler meldet dann der Build."""
+ files, todo = [], [entry]
+ while todo:
+ rel = todo.pop(0)
+ if rel in files:
+ continue
+ files.append(rel)
+ try:
+ tree = _parse(base / rel, rel)
+ except ExportError:
+ if strict:
+ raise
+ continue
+ todo += [m for m in _module_files(base, rel, tree) if m not in files]
+ return files
+
+
+def _parse(path, rel):
+ try:
+ return ast.parse(path.read_text(encoding="utf-8-sig"), filename=rel)
+ except SyntaxError as e:
+ raise ExportError(f"{rel}, line {e.lineno}: syntax error, fix it before exporting ({e.msg}).")
+ except OSError as e:
+ raise ExportError(f"{rel} cannot be read: {e}")
+
+
+# --- Block erzeugen ---------------------------------------------------------------------------------------------------
+
+def _literal(text):
+ """Text als Python-Literal, moeglichst lesbar (Rohtext in dreifachen Anfuehrungszeichen)."""
+ if "'''" not in text and not text.endswith("\\"):
+ return "r'''" + text + "'''"
+ return repr(text)
+
+
+def _checksum(lines):
+ body = "\n".join(l for l in lines if not l.startswith(VALUES))
+ return hashlib.sha256(body.encode("utf-8")).hexdigest()[:16]
+
+
+def _runtime_lines(values, fasteners):
+ lines = (_HERE / "cqruntime.py").read_text(encoding="utf-8").splitlines()
+ i = next(k for k, l in enumerate(lines) if l.startswith(VALUES))
+ lines[i] = VALUES + repr(dict(values)) + lines[i][lines[i].index(" #"):]
+ if fasteners:
+ src = (_HERE / "fasteners.py").read_text(encoding="utf-8")
+ tables = {p.name: p.read_text(encoding="utf-8-sig") for p in sorted((_HERE / "data" / "fasteners").glob("*.csv"))}
+ notice = (_HERE / "data" / "fasteners" / "LICENSE-bd_warehouse.txt")
+ lines += [
+ "",
+ "",
+ "# Standard parts of SOMA (soma.fasteners, Apache License 2.0). The dimension tables come from bd_warehouse",
+ "# (https://github.com/gumyr/bd_warehouse, Apache License 2.0" + (", see its LICENSE)." if notice.is_file() else ")."),
+ "_SOMA_FASTENERS_SOURCE = " + _literal(src),
+ "_SOMA_TABLES = {",
+ *[f" {name!r}: {_literal(text)}," for name, text in tables.items()],
+ "}",
+ "",
+ "",
+ "def _soma_fasteners():",
+ " import types",
+ " module = types.ModuleType(\"soma_fasteners\")",
+ " module.__file__ = _soma_os.path.join(_SOMA_DIR, \"soma_fasteners.py\")",
+ " _soma_linecache.cache[\"<soma fasteners>\"] = (len(_SOMA_FASTENERS_SOURCE), None,",
+ " _SOMA_FASTENERS_SOURCE.splitlines(True), \"<soma fasteners>\")",
+ " exec(compile(_SOMA_FASTENERS_SOURCE, \"<soma fasteners>\", \"exec\"), module.__dict__)",
+ " module._EMBEDDED.update(_SOMA_TABLES)",
+ " return module",
+ "",
+ "",
+ "_soma_fasteners_module = _soma_fasteners()",
+ *[f"{n} = _soma_fasteners_module.{n}" for n in FASTENERS],
+ ]
+ return lines
+
+
+def _block(values, fasteners, aliases):
+ body = _runtime_lines(values, fasteners) + [f"{alias} = {name}" for name, alias in aliases]
+ head = [f"{BLOCK_START} {__version__} (generated by SOMA. Keep this block unchanged, then SOMA can import the script "
+ "again. Only the values in _SOMA_VALUES may change.)", CHECK + _checksum(body)]
+ return head + body + [BLOCK_END]
+
+
+def _footer(folder):
+ call = ([f"import {COMPAT_MODULE} as _soma_compat", "_soma_compat._soma_show(globals())"] if folder
+ else ["_soma_show(globals())"])
+ return ["", "", f"{FOOTER_START} (generated by SOMA: shows the parts in CQ-editor or ocp_vscode, `result` is the assembly)",
+ *call, FOOTER_END]
+
+
+def _rewrite(text, imports, mode, block=None, footer=False):
+ """Ersetzt die soma-Imports. mode "single": Block beim ersten Import, "folder": Import aus soma_compat."""
+ lines = text.splitlines()
+ out, i = [], 0
+ for k, (node, _, names) in enumerate(imports):
+ a, b = node.lineno - 1, node.end_lineno
+ out += lines[i:a]
+ out += [MARK + l for l in lines[a:b]]
+ if mode == "single":
+ if k == 0:
+ out += block
+ else:
+ out.append(f"from {COMPAT_MODULE} import " + ", ".join(n if n == al else f"{n} as {al}" for n, al in names) + TAG)
+ i = b
+ out += lines[i:]
+ if footer:
+ while out and not out[-1].strip():
+ out.pop()
+ out += _footer(mode == "folder")
+ return "\n".join(out) + "\n"
+
+
+# --- Export -----------------------------------------------------------------------------------------------------------
+
+def _uses_inputs(texts):
+ return any(re.search(r"""["'](\./)?inputs[/\\]""", t) for t in texts)
+
+
+def _copy_tree(src, dst, warnings, what):
+ """Kopiert Dateien, ohne Vorhandenes zu ueberschreiben (das wird gemeldet)."""
+ copied = []
+ for f in sorted(p for p in src.rglob("*") if p.is_file()):
+ target = dst / f.relative_to(src)
+ if target.exists():
+ warnings.append(f"{what}: {target.name} already exists and was kept.")
+ continue
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(f, target)
+ copied.append(target)
+ return copied
+
+
+def export(project, out):
+ """Schreibt das Modell als CadQuery: `out` ist eine .py-Datei (eine Datei) oder ein Ordner (mit parts/).
+ Liefert dict(mode, files, warnings). Ein Ordner muss leer sein oder fehlen, eine .py-Datei wird ersetzt (der
+ Speicherdialog hat gefragt)."""
+ root = Path(project).resolve()
+ entry = read_project_json(root).get("entry") or DEFAULT_ENTRY
+ if not (root / entry).is_file():
+ raise ExportError(f"Entry point {entry!r} not found.")
+ files = _all_files(root, entry)
+ values, problem = params.read_user_values(root)
+ warnings = [problem] if problem else []
+ texts = {rel: (root / rel).read_text(encoding="utf-8-sig") for rel in files}
+ imports = {rel: _soma_imports(_parse(root / rel, rel), rel) for rel in files}
+ used = {m for rel in files for _, m, _ in imports[rel]}
+ fasteners = "soma.fasteners" in used
+ out = Path(out)
+ written = []
+ if len(files) == 1:
+ mode = "single"
+ if out.suffix.lower() != ".py":
+ out = out.with_suffix(".py")
+ imp = imports[entry]
+ aliases = sorted({(n, al) for _, _, names in imp for n, al in names if n != al})
+ text = _rewrite(texts[entry], imp, "single", _block(values, fasteners, aliases), footer=bool(imp)) if imp else texts[entry]
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_text(text, encoding="utf-8", newline="\n")
+ written.append(out)
+ base = out.parent
+ else:
+ mode = "folder"
+ if out.suffix.lower() == ".py": # die App nennt vorab nur einen Namen: box.py wird der Ordner box
+ out = out.with_suffix("")
+ if out.exists() and (not out.is_dir() or any(out.iterdir())):
+ raise ExportError(f"{out} already exists and is not an empty folder. Choose a new folder for the export.")
+ out.mkdir(parents=True, exist_ok=True)
+ for rel in files:
+ target = out / ("model.py" if rel == entry else rel)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ imp = imports[rel]
+ text = _rewrite(texts[rel], imp, "folder", footer=rel == entry and bool(used)) if imp or rel == entry and used else texts[rel]
+ target.write_text(text, encoding="utf-8", newline="\n")
+ written.append(target)
+ if used:
+ body = _runtime_lines(values, fasteners)
+ head = [f"# {COMPAT_MODULE}.py, generated by SOMA {__version__}: add_part(), param() and the standard parts in plain "
+ "CadQuery. Keep it unchanged, then SOMA can import the model again.", CHECK + _checksum(body)]
+ (out / f"{COMPAT_MODULE}.py").write_text("\n".join(head + body) + "\n", encoding="utf-8", newline="\n")
+ written.append(out / f"{COMPAT_MODULE}.py")
+ base = out
+ if (root / "inputs").is_dir() and _uses_inputs(texts.values()):
+ written += _copy_tree(root / "inputs", base / "inputs", warnings, "inputs")
+ for extra in ("animations", "drawings", "analyses"):
+ if (root / extra).is_dir() and any((root / extra).glob("*.py")):
+ warnings.append(f"{extra}/ only works in SOMA and is not part of the export.")
+ if values:
+ warnings.append(f"The values from the Parameters panel ({', '.join(sorted(values))}) are in _SOMA_VALUES.")
+ return dict(mode=mode, files=[p.as_posix() for p in written], warnings=warnings)
+
+
+# --- Import -----------------------------------------------------------------------------------------------------------
+
+def restore(text):
+ """Dreht den Export zurueck. Liefert (Text, Werte aus _SOMA_VALUES oder None, Warnungen). Ist der Block veraendert
+ oder unvollstaendig, bleibt der Text, wie er ist."""
+ lines = text.splitlines()
+ out, values, found, i = [], None, False, 0
+ while i < len(lines):
+ line = lines[i]
+ if line.startswith(MARK):
+ found = True
+ while i < len(lines) and lines[i].startswith(MARK):
+ out.append(lines[i][len(MARK):])
+ i += 1
+ if i < len(lines) and lines[i].startswith(BLOCK_START) and not lines[i].startswith(FOOTER_START):
+ end = next((k for k in range(i + 1, len(lines)) if lines[k] == BLOCK_END), None)
+ if end is None:
+ return text, None, ["The SOMA compatibility block has no end marker. The script was kept as it is."]
+ body = lines[i + 1:end]
+ if not body or not body[0].startswith(CHECK) or body[0][len(CHECK):].strip() != _checksum(body[1:]):
+ return text, None, ["The SOMA compatibility block was changed. The script was kept as it is, it builds "
+ "with its own copy of add_part() and param()."]
+ values = _values(body)
+ i = end + 1
+ elif i < len(lines) and lines[i].endswith(TAG):
+ i += 1
+ continue
+ if line.startswith(FOOTER_START):
+ end = next((k for k in range(i + 1, len(lines)) if lines[k] == FOOTER_END), None)
+ if end is not None:
+ while out and not out[-1].strip():
+ out.pop()
+ i = end + 1
+ continue
+ out.append(line)
+ i += 1
+ if not found:
+ return text, None, []
+ return "\n".join(out) + "\n", values, []
+
+
+def _values(lines):
+ line = next((l for l in lines if l.startswith(VALUES)), None)
+ if line is None:
+ return None
+ src = line[len(VALUES):].split(" #")[0].strip()
+ try:
+ v = ast.literal_eval(src)
+ except (ValueError, SyntaxError):
+ return None
+ return v if isinstance(v, dict) else None
+
+
+def _free(path):
+ """Freier Dateiname: board.py, board (2).py ..."""
+ i = 2
+ cand = path
+ while cand.exists():
+ cand = path.with_name(f"{path.stem} ({i}){path.suffix}")
+ i += 1
+ return cand
+
+
+def import_script(script, project, backup=None):
+ """Uebernimmt ein CadQuery-Skript (und seine eigenen Module) als Modell des Projekts. Das Original kommt als Sicherung
+ nach inputs/. Vorhandene Dateien werden nur ersetzt, wenn `backup` (Ordner) angegeben ist, dorthin kommen sie vorher.
+ Liefert dict(mode "soma" | "cadquery", files, warnings)."""
+ src, root = Path(script).resolve(), Path(project).resolve()
+ if not src.is_file() or src.suffix.lower() != ".py":
+ raise ExportError(f"{src} is not a Python file.")
+ base = src.parent
+ files = _all_files(base, src.name, strict=False) if base != root else [src.name]
+ warnings, written, all_values, mode = [], [], {}, "cadquery"
+ plan = []
+ for rel in files:
+ text = (base / rel).read_text(encoding="utf-8-sig")
+ new, values, w = restore(text)
+ warnings += [f"{rel}: {m}" for m in w]
+ if new != text:
+ mode = "soma"
+ all_values.update(values or {})
+ plan.append(("model.py" if rel == src.name else rel, new))
+ compat = base / f"{COMPAT_MODULE}.py"
+ if compat.is_file() and mode == "soma": # Ordner-Export: die Werte stehen in soma_compat.py
+ all_values.update(_values(compat.read_text(encoding="utf-8-sig").splitlines()) or {})
+ for rel, text in plan:
+ target = root / rel
+ if target.exists() and target.read_text(encoding="utf-8-sig") != text:
+ if backup is None:
+ raise ExportError(f"{rel} already exists in the model. Import into a new model.")
+ b = Path(backup) / rel
+ b.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(target, b)
+ for rel, text in plan:
+ target = root / rel
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(text, encoding="utf-8", newline="\n")
+ written.append(rel)
+ (root / "inputs").mkdir(exist_ok=True)
+ keep = _free(root / "inputs" / src.name)
+ shutil.copy2(src, keep)
+ written.append(keep.relative_to(root).as_posix())
+ if (base / "inputs").is_dir() and base != root:
+ written += [p.relative_to(root).as_posix() for p in _copy_tree(base / "inputs", root / "inputs", warnings, "inputs")]
+ if all_values:
+ (root / params.USER_FILE).write_text(json.dumps(dict(note=params.FILE_NOTE, values=all_values), indent=2, ensure_ascii=False) + "\n",
+ encoding="utf-8", newline="\n")
+ written.append(params.USER_FILE)
+ if mode == "cadquery":
+ warnings.append("Plain CadQuery script: it builds in compatibility mode (show_object(), ocp_vscode or result). "
+ "To convert it to add_part() and param(), ask the agent.")
+ return dict(mode=mode, files=written, warnings=warnings)
diff --git a/python/soma/cqruntime.py b/python/soma/cqruntime.py
new file mode 100644
index 0000000..6588b3e
--- /dev/null
+++ b/python/soma/cqruntime.py
@@ -0,0 +1,136 @@
+# SPDX-License-Identifier: Apache-2.0
+# SOMA compatibility layer: add_part(), param(), import_step() and import_assembly() in plain CadQuery.
+# Copyright the SOMA contributors. Licensed under the Apache License 2.0, https://www.apache.org/licenses/LICENSE-2.0
+# (E101). "Export as CadQuery" puts this file into exported models (cqexport.py): as a block in a single script, or as
+# soma_compat.py next to it. It must run without soma, with CadQuery only. Everything up to the end marker is copied.
+import builtins as _soma_builtins
+import inspect as _soma_inspect
+import linecache as _soma_linecache
+import os as _soma_os
+import re as _soma_re
+
+import cadquery as _soma_cq
+
+_SOMA_VALUES = {} # values set in the Parameters panel of SOMA, they take the place of the defaults of param()
+_SOMA_PARTS = []
+_SOMA_COLORS = {"part": (0.62, 0.66, 0.72), "reference": (0.1, 0.65, 0.3), "hardware": (0.45, 0.46, 0.49)}
+_SOMA_ASSIGN = _soma_re.compile(r"^\s*([A-Za-z_][A-Za-z0-9_]*)\s*(?::[^=]*)?=\s*param\s*\(")
+try:
+ _SOMA_DIR = _soma_os.path.dirname(_soma_os.path.abspath(__file__))
+except NameError: # some viewers run the code without a file name
+ _SOMA_DIR = _soma_os.getcwd()
+
+
+def param(default, label=None, *, name=None, **_spec):
+ """A value the user can change in SOMA. Here: the value set in SOMA when the model was exported, else the default."""
+ if name is None:
+ frame = _soma_inspect.currentframe().f_back
+ pos = getattr(_soma_inspect.getframeinfo(frame, context=0), "positions", None) # Python 3.11+: start of the call
+ line = _soma_linecache.getline(frame.f_code.co_filename, pos.lineno if pos and pos.lineno else frame.f_lineno)
+ match = _SOMA_ASSIGN.match(line)
+ name = match.group(1) if match else None
+ if name not in _SOMA_VALUES:
+ return default
+ value = _SOMA_VALUES[name]
+ if isinstance(default, bool) or isinstance(value, bool):
+ return value if isinstance(default, bool) and isinstance(value, bool) else default
+ if isinstance(default, (int, float)):
+ if not isinstance(value, (int, float)):
+ return default
+ return int(value) if isinstance(default, int) and float(value).is_integer() else value
+ return value if isinstance(value, type(default)) else default
+
+
+def _soma_path(path):
+ """Paths like "inputs/board.step" relative to the script, if they are not found relative to the working folder."""
+ path = str(path)
+ if _soma_os.path.isabs(path) or _soma_os.path.exists(path):
+ return path
+ return _soma_os.path.join(_SOMA_DIR, path)
+
+
+def import_step(path):
+ """Imports a STEP file as one shape."""
+ return _soma_cq.importers.importStep(_soma_path(path)).val()
+
+
+def import_assembly(path):
+ """Imports a STEP file with its structure as a cq.Assembly."""
+ return _soma_cq.Assembly.importStep(_soma_path(path))
+
+
+def _soma_shape(obj):
+ if hasattr(obj, "__soma_shape__"): # standard parts (Screw, Nut ...)
+ return obj.__soma_shape__()
+ if isinstance(obj, _soma_cq.Workplane):
+ vals = obj.vals()
+ if not vals:
+ raise ValueError("The Workplane is empty (no geometry).")
+ return vals[0] if len(vals) == 1 else _soma_cq.Compound.makeCompound(vals)
+ if isinstance(obj, (_soma_cq.Shape, _soma_cq.Assembly)):
+ return obj
+ raise TypeError(f"add_part expects a cq.Workplane, a cq.Shape, a cq.Assembly or a standard part, not {type(obj).__name__}")
+
+
+def add_part(name, obj, role=None, color=None, group=None):
+ """Registers a part (SOMA). Here: collects it for the assembly `result` and for show_object() of the viewer."""
+ standard = hasattr(obj, "__soma_shape__")
+ role = role or (getattr(obj, "role", "part") if standard else "part")
+ if color is None and standard:
+ color = getattr(obj, "color", None)
+ groups = tuple(s.strip() for s in str(group or "").split("/") if s.strip())
+ if role == "reference":
+ groups = ("Reference",) + groups
+ rgb = tuple(color[:3]) if color else _SOMA_COLORS.get(role, _SOMA_COLORS["part"])
+ _SOMA_PARTS.append(dict(name=str(name), shape=_soma_shape(obj), role=role, groups=groups,
+ color=(*rgb, 0.45 if role == "reference" else 1.0)))
+
+
+def _soma_assembly(name="Model"):
+ """All parts as a cq.Assembly, groups as sub-assemblies. cq.Assembly needs names that differ from the assembly
+ they are added to and from their siblings (SOMA allows a part "X beam" in the group "X beam"): such names get
+ " (2)" in the assembly. show_object() keeps the names from add_part()."""
+ root = _soma_cq.Assembly(name=name)
+ subs, used = {(): root}, {(): {name}}
+
+ def free(parent, wanted):
+ taken, unique, i = used[parent], wanted, 2
+ while unique in taken:
+ unique, i = f"{wanted} ({i})", i + 1
+ taken.add(unique)
+ return unique
+
+ for p in _SOMA_PARTS:
+ for i in range(1, len(p["groups"]) + 1):
+ key = p["groups"][:i]
+ if key not in subs:
+ subs[key] = _soma_cq.Assembly(name=free(key[:-1], key[-1]))
+ used[key] = {subs[key].name}
+ parent = subs[p["groups"]]
+ unique = free(p["groups"], p["name"])
+ if isinstance(p["shape"], _soma_cq.Assembly):
+ parent.add(p["shape"], name=unique)
+ else:
+ parent.add(p["shape"], name=unique, color=_soma_cq.Color(*p["color"]))
+ # Inner groups first: cq.Assembly copies a sub-assembly when it is added
+ for key in sorted((k for k in subs if k), key=len, reverse=True):
+ subs[key[:-1]].add(subs[key], name=subs[key].name)
+ return root
+
+
+def _soma_show(namespace):
+ """End of the script: `result` for cq-cli and others, show_object() in CQ-editor, else ocp_vscode if installed."""
+ assembly = _soma_assembly()
+ namespace.setdefault("result", assembly)
+ show = namespace.get("show_object") or getattr(_soma_builtins, "show_object", None)
+ if show is not None:
+ for p in _SOMA_PARTS:
+ show(p["shape"], name=p["name"], options={"color": tuple(p["color"][:3]), "alpha": p["color"][3]})
+ elif namespace.get("__name__") == "__main__":
+ try:
+ from ocp_vscode import show as ocp_show
+ except ImportError:
+ print(f"{len(_SOMA_PARTS)} part(s) in the assembly `result`. To see them, open the script in CQ-editor "
+ "or install ocp_vscode (VS Code).")
+ else:
+ ocp_show(assembly)
diff --git a/python/soma/drawrun.py b/python/soma/drawrun.py
index d694caa..8321d5e 100644
--- a/python/soma/drawrun.py
+++ b/python/soma/drawrun.py
@@ -17,7 +17,7 @@ from pathlib import Path
import numpy as np
-from . import build, drawing
+from . import build, cqcompat, drawing
DRAW_DIR = "drawings"
OUT_DIR = Path("output") / "drawings"
@@ -70,7 +70,8 @@ def _run_file(root, path):
mod.__name__, mod.__file__ = mod_name, str(script)
sys.modules[mod_name] = mod
try:
- runpy.run_path(str(path), run_name="__main__")
+ with cqcompat.hooks(): # importiert die Datei ein CadQuery-Skript mit show_object(), bleibt das wirkungslos
+ runpy.run_path(str(path), run_name="__main__")
except SystemExit as e:
if e.code not in (None, 0):
raise build.BuildError(f"{_rel(path, root)} exited with code {e.code}", file=_rel(path, root), kind="SystemExit")
diff --git a/python/soma/fasteners.py b/python/soma/fasteners.py
index 2a152b3..2115e73 100644
--- a/python/soma/fasteners.py
+++ b/python/soma/fasteners.py
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0
+# Zusaetzlich Apache 2.0 (E101): "Export as CadQuery" kopiert dieses Modul in das Skript des Nutzers.
"""Standard parts: screws, nuts, washers and heat-set inserts, simplified without threads, with matching holes.
from soma import add_part
@@ -21,6 +23,7 @@ maximum values. Threads are not modelled: the shank and the bore of the nut have
import copy
import csv
import functools
+import io
import math
import numbers
import re
@@ -33,6 +36,9 @@ from OCP.gp import gp_Ax1, gp_Dir, gp_Lin, gp_Pnt, gp_Trsf
__all__ = ["Screw", "Nut", "Washer", "HeatSetInsert", "lengths", "pick_length", "standards"]
_DATA = Path(__file__).parent / "data" / "fasteners"
+# Tabellen als Text (Dateiname -> CSV). Fuellt nur der Block von "Export as CadQuery" (cqexport.py), dann laeuft dieses
+# Modul ohne soma und ohne data/
+_EMBEDDED = {}
INCH = 25.4
# Bohrwerkzeuge ragen so weit ueber die Oberflaeche hinaus: Deckungsgleiche Flaechen machen cut() unzuverlaessig
MARGIN = 1.0
@@ -92,10 +98,17 @@ HINTS = {
# --- Tabellen ----------------------------------------------------------------------------------------------------------
+def _open(name):
+ """Tabelle zum Lesen: eingebettet (Export als CadQuery) oder aus data/fasteners."""
+ if name in _EMBEDDED:
+ return io.StringIO(_EMBEDDED[name].lstrip(""), newline="")
+ return open(_DATA / name, encoding="utf-8-sig", newline="")
+
+
@functools.cache
def _table(name):
"""CSV als Liste von (Schluessel, {Spalte: Wert}). Kopfzeilen haben teils Leerzeichen am Rand, die fallen weg."""
- with open(_DATA / name, encoding="utf-8-sig", newline="") as f:
+ with _open(name) as f:
rows = list(csv.reader(f))
head = [h.strip() for h in rows[0]]
return [(r[0].strip(), {h: v.strip() for h, v in zip(head[1:], r[1:])}) for r in rows[1:] if r and r[0].strip()]
@@ -192,7 +205,7 @@ def _split_designation(standard, size):
@functools.cache
def _nominal_lengths():
out = {}
- with open(_DATA / "nominal_screw_lengths.csv", encoding="utf-8-sig", newline="") as f:
+ with _open("nominal_screw_lengths.csv") as f:
for row in csv.DictReader(f):
if row["Unit"].strip() == "mm":
out[row["Screw_Type"].strip()] = [_num(x) for x in row["Nominal_Sizes"].split(",") if x.strip()]
@@ -252,7 +265,7 @@ def _tap_drill(d):
@functools.cache
def _drills():
- with open(_DATA / "drill_sizes.csv", encoding="utf-8-sig", newline="") as f:
+ with _open("drill_sizes.csv") as f:
return {r[0].strip(): _num(r[1].strip()) * INCH for r in list(csv.reader(f))[1:] if len(r) > 1}
diff --git a/python/soma/registry.py b/python/soma/registry.py
index 0e63c2d..a3bfde4 100644
--- a/python/soma/registry.py
+++ b/python/soma/registry.py
@@ -81,6 +81,14 @@ def add_part(name, obj, role=None, color=None, group=None):
"""
if IGNORE_ADD:
return
+ frame = inspect.currentframe().f_back
+ pos = inspect.getframeinfo(frame, context=0).positions # Startzeile und Endzeile des Aufrufs
+ _add(name, obj, role, color, group, dict(file=frame.f_code.co_filename, line=pos.lineno, end_line=pos.end_lineno))
+
+
+def _add(name, obj, role, color, group, where, alpha=None):
+ """add_part ohne Blick auf den Aufrufer: Der Kompatibilitaetsmodus (cqcompat.py) nennt die Stelle von show_object().
+ `alpha` < 1: halbtransparent wie in CQ-editor (options={"alpha": ...})."""
standard_part = hasattr(obj, "__soma_shape__")
if role is None:
role = getattr(obj, "role", "part") if standard_part else "part"
@@ -91,16 +99,13 @@ def add_part(name, obj, role=None, color=None, group=None):
if not isinstance(name, str) or not name.strip():
raise ValueError("The part name must be a non-empty text")
groups = _group_path(group)
- frame = inspect.currentframe().f_back
- pos = inspect.getframeinfo(frame, context=0).positions # Startzeile und Endzeile des Aufrufs
- where = dict(file=frame.f_code.co_filename, line=pos.lineno, end_line=pos.end_lineno)
if isinstance(obj, cq.Assembly):
leaves = list(_leaves(obj, cq.Location(), (), None))
if not leaves:
raise ValueError(f"The assembly for {name!r} contains no geometry")
if len(leaves) == 1: # nur ein Koerper: ein Bauteil unter dem angegebenen Namen, ohne eigene Gruppe
_, _, o, c, loc = leaves[0]
- _register(name, to_shape(o).moved(loc), role, color or (c.toTuple()[:3] if c else None), groups, where)
+ _register(name, to_shape(o).moved(loc), role, color or (c.toTuple()[:3] if c else None), groups, where, alpha=alpha)
return
taken = {p["name"] for p in REGISTRY}
for sub_groups, leaf_name, o, c, loc in leaves:
@@ -108,11 +113,12 @@ def add_part(name, obj, role=None, color=None, group=None):
path = groups + (name,) + sub_groups[1:]
nm = _unique(leaf_name or "Part", taken)
taken.add(nm)
- _register(nm, to_shape(o).moved(loc), role, color or (c.toTuple()[:3] if c else None), path, where, unique_step=True)
+ _register(nm, to_shape(o).moved(loc), role, color or (c.toTuple()[:3] if c else None), path, where, unique_step=True,
+ alpha=alpha)
return
if any(p["name"] == name for p in REGISTRY):
raise ValueError(f"Part name {name!r} is already taken (names must be unique)")
- _register(name, to_shape(obj), role, color, groups, where, axis=_axis(obj), fastener=obj if standard_part else None)
+ _register(name, to_shape(obj), role, color, groups, where, axis=_axis(obj), fastener=obj if standard_part else None, alpha=alpha)
def _axis(obj):
@@ -130,7 +136,7 @@ def _axis(obj):
return tuple(round(-x / n, 6) + 0.0 for x in d) # + 0.0: kein "-0.0" in den Metadaten
-def _register(name, shape, role, color, groups, where, unique_step=False, axis=None, fastener=None):
+def _register(name, shape, role, color, groups, where, unique_step=False, axis=None, fastener=None, alpha=None):
step_name = ascii_name(name)
if any(p["step_name"] == step_name for p in REGISTRY):
if not unique_step:
@@ -142,7 +148,7 @@ def _register(name, shape, role, color, groups, where, unique_step=False, axis=N
rgb = tuple(color[:3]) if color else DEFAULT_COLORS[role]
REGISTRY.append(dict(
name=name, step_name=step_name, role=role, shape=shape, group=tuple(groups),
- color=(*rgb, REFERENCE_ALPHA if role == "reference" else 1.0), axis=axis, **where,
+ color=(*rgb, REFERENCE_ALPHA if role == "reference" else alpha if alpha is not None and 0 < alpha < 1 else 1.0), axis=axis, **where,
# Das Normteil selbst (Screw, Nut ...), nur im Speicher: soma.fem liest daraus Groesse, Kopf und Lage (bolt())
fastener=fastener,
))