diff --git a/README.md b/README.md index 0e276dc0..dd2ef3b9 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,12 @@ incremental assembly solves, and a persistent crash-safe cache for whole parts. See the [full English update notes](docs/updates/2.0.4b3.md) for contracts, cache modes, diagnostics, limitations, and verification coverage. +All formal scripts under `examples/` emit a synchronized `.scadpkg`, AP242 +`.step`, and editable `.FCStd` from the same product package. Run +`uv run python tools/run_examples.py` to rebuild and validate the complete +example export set. The Gmsh example accepts `--skip-mesh` when only the CAD +artifacts are required. + ---
@@ -41,8 +47,8 @@ Current development beta: `simplecadapi==2.0.4b3`. - OCP-native shape types: `Vertex`, `Edge`, `Wire`, `Face`, and `Solid`. - Functional modeling operations for primitives, profiles, extrude, revolve, loft, sweep, booleans, transforms, patterns, fillets, chamfers, and shells. -- Replayable modeling with `@model`, `ModelResult`, `capture_result(...)`, - `import_model_json(...)`, and `replay_model_json(...)`. +- Replayable operation graphs with explicit `GraphSession`, + `export_model_json(...)`, `import_model_json(...)`, and `replay_model_json(...)`. - Expression parameters with `var(...)`, arithmetic expressions, and serialized expression graphs. - Physical units with automatic dimension inference, canonical CAD conversion, @@ -50,7 +56,8 @@ Current development beta: `simplecadapi==2.0.4b3`. - QL selectors for geometry grounding, topology queries, and stable feature selections. - Semantic tags through `apply_tag(shape=..., tag=...)` and `list_tags(shape=...)`. -- STEP/STL export and FreeCAD translation helpers for script or `.FCStd` output. +- STEP/STL export, editable FreeCAD product-package translation, and AP242 + product-structure export with material and named metadata properties. - Agent-oriented STEP/BREP reconstruction with stable entity IDs, focused local diagnostics, highlighted region renders, and measured acceptance gates. - Replayable open and periodic interpolated B-spline Edges/Wires for freeform @@ -84,45 +91,47 @@ from pathlib import Path import simplecadapi as scad out = Path("out") -out.mkdir(exist_ok=True) -base = scad.make_box_rsolid( - width=60.0, height=36.0, depth=8.0, bottom_face_center=(0.0, 0.0, 0.0) -) -hole = scad.make_cylinder_rsolid( - radius=5.0, height=14.0, bottom_face_center=(0.0, 0.0, -3.0) -) -slot = scad.make_box_rsolid( - width=18.0, height=8.0, depth=14.0, bottom_face_center=(14.0, 0.0, -3.0) -) +@scad.part(id="bracket") +def build_bracket() -> scad.Solid: + base = scad.make_box_rsolid( + width=60.0, height=36.0, depth=8.0, bottom_face_center=(0.0, 0.0, 0.0) + ) + hole = scad.make_cylinder_rsolid( + radius=5.0, height=14.0, bottom_face_center=(0.0, 0.0, -3.0) + ) + slot = scad.make_box_rsolid( + width=18.0, height=8.0, depth=14.0, bottom_face_center=(14.0, 0.0, -3.0) + ) + body = scad.cut_rsolid(base, hole, slot) + boss = scad.make_cylinder_rsolid( + radius=8.0, height=7.0, bottom_face_center=(-18.0, 0.0, 8.0) + ) + return scad.apply_tag( + shape=scad.union_rsolid(body, boss), + tag="role.demo.bracket", + ) -part = scad.cut_rsolid(base, hole, slot) -boss = scad.make_cylinder_rsolid( - radius=8.0, height=7.0, bottom_face_center=(-18.0, 0.0, 8.0) -) -part = scad.union_rsolid(part, boss) -part = scad.apply_tag(shape=part, tag="role.demo.bracket") - -print("volume", round(part.get_volume(), 3)) -print("faces", len(part.get_faces())) -print("tags", scad.list_tags(shape=part)) - -scad.export_step(shapes=part, filename=str(out / "bracket.step")) -scad.export_stl(shapes=part, filename=str(out / "bracket.stl")) +result = build_bracket() +package_path = out / "bracket.scadpkg" +scad.capture(result, package_path) +print("volume", round(result.part.body.get_volume(), 3)) +print("tags", scad.list_tags(shape=result.part.body)) +scad.exporter.export_product_package_to_step(package_path, out / "bracket.step") +scad.exporter.export_product_package_to_stl(package_path, out / "bracket.stl") ``` -## Replayable Modeling +## Replayable Operation Graphs -Use one `@scad.model` entry point when a model should be inspectable, -serializable, replayable, or translated into another CAD environment. The -decorated function owns its `GraphSession` and returns a `ModelResult`. +Use an explicit `GraphSession` when a geometry flow should be inspectable, +serializable, replayable, or translated into another CAD environment. ```python import simplecadapi as scad +from simplecadapi import GraphSession, export_model_json, replay_model_json from simplecadapi import ql as Q -@scad.model(graph_id="chamfered_block") -def build_model(): +with GraphSession(graph_id="chamfered_block") as session: body = scad.make_box_rsolid( width=40.0, height=24.0, depth=10.0, bottom_face_center=(0.0, 0.0, 0.0), @@ -140,25 +149,26 @@ def build_model(): .exactly(1) ) final = scad.chamfer_rsolid(solid=drilled, edges=bottom_circle, distance=0.6) - scad.capture_result(value=final) - return final + session.capture_result(value=final) + model_json = export_model_json(session=session) + recorded_nodes = session.graph.node_count -result = build_model() -model_json = result.model_json -rebuilt = result.replay() - -print("recorded_nodes", result.session.graph.node_count) +rebuilt = replay_model_json(json_str=model_json) +print("recorded_nodes", recorded_nodes) print("replayed_outputs", len(rebuilt)) ``` -Pass `export_dir=...` to `@scad.model` when the invocation should also write -one self-contained `.scene.zip`. The package contains `scene.json`, -`model/model.json`, the complete project-relative Python files referenced by -operation source mappings under `sources/`, and the GLB/entity assets required -by the Viewer. Automatic export does not write adjacent model/session JSON, -STEP, STL, or FCStd files; those explicit export APIs remain available. The -package path is `result.artifact_paths["scene"]`. Without `export_dir`, model -execution remains in memory. +An explicit `GraphSession` remains in memory until an export API is called. +For a durable CAD/viewer deliverable, define one physical single-solid part with +`@scad.part` or an assembly with `@scad.assemble`, then capture and write it in one call: + +```python +scad.capture(result, "out/product.scadpkg") +``` + +The package embeds the definition closure, evaluated scene, feature graphs, +source snapshots, topology, and render/selection assets. STEP, STL, FCStd, and +low-level JSON remain explicit exports. ## Persistent Product Builds And Cache @@ -190,6 +200,26 @@ See the [persistent cache and product build workflow](docs/guides/cache-build-wo for cache modes, configuration precedence, PRT reuse, incremental invalidation, corruption repair, and destructive-command confirmation. +```python +scad.capture(warm, "out/mounting_plate.scadpkg") +scad.translator.freecad_translator.translate_product_package_to_fcstd( + "out/mounting_plate.scadpkg", "out/mounting_plate.FCStd" +) +scad.exporter.export_product_package_to_step( + "out/mounting_plate.scadpkg", "out/mounting_plate.step" +) +scad.exporter.export_product_package_to_stl( + "out/mounting_plate.scadpkg", "out/mounting_plate.stl" +) +``` + +AP242 preserves evaluated BREP, shared definitions, hierarchy, occurrence +names/placements, materials, colors, density, and named SimpleCAD JSON +properties. It does not reconstruct canonical feature history as AP242 +features. For the optional `.step -> .msh` volume-mesh workflow, install +`simplecadapi[gmsh]` and run `examples/12_ap242_gmsh_volume_mesh.py`; use +`--skip-mesh` to export only the synchronized CAD artifacts. + ## STEP/BREP Inspection Install the optional rendering dependency when synchronized STEP views, @@ -201,7 +231,7 @@ pip install "simplecadapi[inspect]" Inspection lives under `simplecadapi.inspect.brep`. These APIs are diagnostic tools, not modeling operations: they do not enter the graph and are rejected -inside `GraphSession` and `@model`. Export or obtain the geometry first, then +inside `GraphSession`. Export or obtain the geometry first, then inspect it outside the modeling script. Choose calls from the evidence required by the case instead of following a @@ -281,27 +311,21 @@ expression. child-geometry getter, such as `get_edges(index)`, `get_faces(index)`, `get_wires(index)`, or `get_vertices(index)`, so replayable graph workflows preserve the pick as a geo select node. -- Use model JSON as the interchange boundary for replay, tests, and FreeCAD - translation. - -## FreeCAD Translation - -Recorded model JSON can be translated into a FreeCAD Python script: +Use model JSON only for graph replay and inspection. External CAD translation and +file export consume the validated `.scadpkg` closure: ```python -script = scad.translator.freecad_translator.translate_model_json_to_freecad_script(model_json) -``` - -If FreeCAD or FreeCADCmd is available, the same model JSON can be written as an -`.FCStd` file: - -```python -scad.translator.freecad_translator.translate_model_json_to_fcstd(model_json, "bracket.FCStd") +script = scad.translator.freecad_translator.translate_product_package_to_freecad_script( + package_path +) +scad.translator.freecad_translator.translate_product_package_to_fcstd( + package_path, "bracket.FCStd" +) ``` Part/Assembly models are written as editable FreeCAD assembly structure: parts are `App::Part`, assemblies are `Assembly::AssemblyObject`, and components are links. -Explicit compound projections remain available for geometry-only STEP export. +The exporter namespace owns neutral STEP and STL file output. ## Examples @@ -335,6 +359,7 @@ uv run python examples/20_integrated_bldc_joint_actuator/main.py [`docs/core/physical-units.md`](docs/core/physical-units.md) - Operation graph JSON spec: [`docs/core/operation_graph_json_spec.md`](docs/core/operation_graph_json_spec.md) + `.scadpkg` 产品包规范(中文):[`design-docs/scadpkg-spec.md`](design-docs/scadpkg-spec.md) ## Releasing the Agent Skill diff --git a/README.zh-CN.md b/README.zh-CN.md index 30ae51dc..c5ed2787 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -35,7 +35,7 @@ SimpleCADAPI 是一个基于 OCP 的 Python CAD SDK,提供清晰的函数式 - 基于 OCP 的 `Vertex`、`Edge`、`Wire`、`Face` 和 `Solid` 类型。 - 支持基本体、轮廓、拉伸、旋转、放样、扫掠、布尔运算、变换、阵列、圆角、倒角和抽壳等函数式建模操作。 -- 通过 `@model`、`ModelResult`、`capture_result(...)`、`import_model_json(...)` 和 `replay_model_json(...)` 记录并重放建模过程。 +- 通过显式 `GraphSession`、`export_model_json(...)`、`import_model_json(...)` 和 `replay_model_json(...)` 记录并重放操作图。 - 通过 `var(...)`、算术表达式和可序列化表达式图定义参数。 - 使用 QL 选择器定位几何、查询拓扑并稳定选择特征。 - 通过 `apply_tag(shape=..., tag=...)` 和 `list_tags(shape=...)` 管理语义标签。 @@ -74,34 +74,38 @@ from pathlib import Path import simplecadapi as scad out = Path("out") -out.mkdir(exist_ok=True) -base = scad.make_box_rsolid( - width=60.0, height=36.0, depth=8.0, bottom_face_center=(0.0, 0.0, 0.0) -) -hole = scad.make_cylinder_rsolid( - radius=5.0, height=14.0, bottom_face_center=(0.0, 0.0, -3.0) -) -part = scad.cut_rsolid(base, hole) -part = scad.apply_tag(shape=part, tag="role.demo.bracket") +@scad.part(id="bracket") +def build_bracket() -> scad.Solid: + base = scad.make_box_rsolid( + width=60.0, height=36.0, depth=8.0, bottom_face_center=(0.0, 0.0, 0.0) + ) + hole = scad.make_cylinder_rsolid( + radius=5.0, height=14.0, bottom_face_center=(0.0, 0.0, -3.0) + ) + body = scad.cut_rsolid(base, hole) + return scad.apply_tag(shape=body, tag="role.demo.bracket") -print("volume", round(part.get_volume(), 3)) -print("tags", scad.list_tags(shape=part)) - -scad.export_step(shapes=part, filename=str(out / "bracket.step")) -scad.export_stl(shapes=part, filename=str(out / "bracket.stl")) +result = build_bracket() +package_path = out / "bracket.scadpkg" +scad.capture(result, package_path) +print("volume", round(result.part.body.get_volume(), 3)) +print("tags", scad.list_tags(shape=result.part.body)) +scad.exporter.export_product_package_to_step(package_path, out / "bracket.step") +scad.exporter.export_product_package_to_stl(package_path, out / "bracket.stl") ``` -## 可重放建模 -当模型需要检查、序列化、重放或转换到其他 CAD 环境时,请使用唯一的 -`@scad.model` 顶层入口。该入口拥有自己的 `GraphSession` 并返回 `ModelResult`: +## 可重放操作图 + +几何流程需要检查、序列化、重放或转换到其他 CAD 环境时,请使用显式 +`GraphSession`: ```python import simplecadapi as scad +from simplecadapi import GraphSession, export_model_json, replay_model_json -@scad.model(graph_id="drilled_block") -def build_model(): +with GraphSession(graph_id="drilled_block") as session: body = scad.make_box_rsolid( width=40.0, height=24.0, depth=10.0, bottom_face_center=(0.0, 0.0, 0.0), @@ -110,24 +114,20 @@ def build_model(): radius=4.0, height=16.0, bottom_face_center=(0.0, 0.0, -3.0) ) drilled = scad.cut_rsolid(body, cutter) - scad.capture_result(value=drilled) - return drilled + session.capture_result(value=drilled) + model_json = export_model_json(session=session) + recorded_nodes = session.graph.node_count -result = build_model() -model_json = result.model_json -rebuilt = result.replay() - -print("recorded_nodes", result.session.graph.node_count) +rebuilt = replay_model_json(json_str=model_json) +print("recorded_nodes", recorded_nodes) print("replayed_outputs", len(rebuilt)) ``` -如果模型调用还需要写出最终文件,请向 `@scad.model` 传入 -`export_dir=...`。显式 `capture_result(...)` 的结果会生成一个自包含的 -`.scene.zip`,其中包含 `scene.json`、`model/model.json`、operation -source mapping 引用的完整项目相对 Python 源文件(位于 `sources/`)以及 -Viewer 所需的 GLB/entity 资源。自动导出不会在旁边生成 model/session JSON、 -STEP、STL 或 FCStd;这些格式仍可通过显式导出 API 生成。文件路径为 -`result.artifact_paths["scene"]`。省略 `export_dir` 时不会写文件。 +显式 `GraphSession` 在调用导出 API 前只存在于内存。需要持久 CAD/Viewer +交付物时,一个物理单实体零件使用 `@scad.part`,装配使用 `@scad.assemble`, +直接调用 `scad.capture(result, "out/product.scadpkg")`,一次完成捕获和写盘。 +`.scadpkg` 包含完整定义闭包、求值场景、特征图、源码快照、拓扑以及渲染/选择资源。 +STEP、STL、FCStd 和底层 JSON 仍由显式导出 API 生成。 ## 持久产品构建与缓存 @@ -202,16 +202,18 @@ simplecad-brep tool get_model_summary --arguments-file summary-args.json ## FreeCAD 转换 -可以把记录的模型 JSON 转换为 FreeCAD Python 脚本: +外部 CAD 转换只接受经过验证的 `.scadpkg` 产品包: ```python -script = scad.translator.freecad_translator.translate_model_json_to_freecad_script(model_json) -``` - -如果系统中存在 FreeCAD 或 FreeCADCmd,也可以直接生成 `.FCStd` 文件: - -```python -scad.translator.freecad_translator.translate_model_json_to_fcstd(model_json, "bracket.FCStd") +package_path = artifacts.artifact_paths["product"] +script = scad.translator.freecad_translator.translate_product_package_to_freecad_script( + package_path +) +scad.translator.freecad_translator.translate_product_package_to_fcstd( + package_path, "bracket.FCStd" +) +scad.exporter.export_product_package_to_step(package_path, "bracket.step") +scad.exporter.export_product_package_to_stl(package_path, "bracket.stl") ``` ## 文档 @@ -228,6 +230,7 @@ scad.translator.freecad_translator.translate_model_json_to_fcstd(model_json, "br - 序列化与重放:[`docs/core/serialization/README.md`](docs/core/serialization/README.md) - 操作图 JSON 规范:[`docs/core/operation_graph_json_spec.md`](docs/core/operation_graph_json_spec.md) - 示例索引:[`examples/README.md`](examples/README.md) + `.scadpkg` 产品包规范:[`design-docs/scadpkg-spec.md`](design-docs/scadpkg-spec.md) ## 发布 Agent Skill diff --git a/docs/api/AssemblyBuildResult.md b/docs/api/AssemblyBuildResult.md index db401823..110c784a 100644 --- a/docs/api/AssemblyBuildResult.md +++ b/docs/api/AssemblyBuildResult.md @@ -3,7 +3,7 @@ ## Class Definition ```python -class AssemblyBuildResult(value: Assembly, definition: AssemblyDefinition, model_json: str, solve_report: AssemblySolveReport, artifact_paths: Mapping[str, Path] = field(default_factory=dict)) +class AssemblyBuildResult(value: Assembly, definition: AssemblyDefinition, feature_graph: FeatureGraphArtifact, solve_report: AssemblySolveReport) ``` *Source: build/results.py* @@ -14,4 +14,4 @@ class AssemblyBuildResult(value: Assembly, definition: AssemblyDefinition, model ## Description -Runtime Assembly plus its external-reference durable definition. +Runtime Assembly plus its durable definition, feature DAG, and solve evidence. diff --git a/docs/api/BRepComparison.md b/docs/api/BRepComparison.md index 72179609..df84ff61 100644 --- a/docs/api/BRepComparison.md +++ b/docs/api/BRepComparison.md @@ -10,7 +10,7 @@ class BRepComparison(target: str | None, candidate: str | None, target_minus_can ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.BRepComparison(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.BRepComparison(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/BRepEntityError.md b/docs/api/BRepEntityError.md index 4ea9351f..e3fcb5a5 100644 --- a/docs/api/BRepEntityError.md +++ b/docs/api/BRepEntityError.md @@ -10,7 +10,7 @@ class BRepEntityError ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.BRepEntityError(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.BRepEntityError(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/BRepInspection.md b/docs/api/BRepInspection.md index fea3ee40..4a20c5c6 100644 --- a/docs/api/BRepInspection.md +++ b/docs/api/BRepInspection.md @@ -10,7 +10,7 @@ class BRepInspection(source: str | None, valid: bool, counts: dict[str, int], bo ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.BRepInspection(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.BRepInspection(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/BRepModel.md b/docs/api/BRepModel.md index 3fb7d137..3a82b334 100644 --- a/docs/api/BRepModel.md +++ b/docs/api/BRepModel.md @@ -10,7 +10,7 @@ class BRepModel(root: TopoDS_Shape, source: str | None, bodies: tuple[TopoDS_Sol ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.BRepModel(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.BRepModel(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/CaptureResult.md b/docs/api/CaptureResult.md new file mode 100644 index 00000000..9b2f445c --- /dev/null +++ b/docs/api/CaptureResult.md @@ -0,0 +1,17 @@ +# CaptureResult + +## Class Definition + +```python +class CaptureResult(value: Part | Assembly, definition: PartDefinition | AssemblyDefinition, package: ProductPackage, scene: ProductScenePackage, package_bytes: bytes) +``` + +*Source: capture.py* + +## Import Surface + +- top-level: `from simplecadapi import CaptureResult` + +## Description + +Runtime value plus one complete durable product snapshot. diff --git a/docs/api/EntityInspectionParity.md b/docs/api/EntityInspectionParity.md index 5b9ee7d3..1b89af7a 100644 --- a/docs/api/EntityInspectionParity.md +++ b/docs/api/EntityInspectionParity.md @@ -10,7 +10,7 @@ class EntityInspectionParity(source: str | None, valid: bool, issues: tuple[str, ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.EntityInspectionParity(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.EntityInspectionParity(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/FreeCADScriptTranslator.md b/docs/api/FreeCADScriptTranslator.md deleted file mode 100644 index cbd17f54..00000000 --- a/docs/api/FreeCADScriptTranslator.md +++ /dev/null @@ -1,17 +0,0 @@ -# FreeCADScriptTranslator - -## Class Definition - -```python -class FreeCADScriptTranslator -``` - -*Source: translator/freecad_translator/translator.py* - -## Import Surface - -- translator backend: `from simplecadapi.translator.freecad_translator import FreeCADScriptTranslator` - -## Description - -Backward-compatible class name for the FreeCAD translator. diff --git a/docs/api/FreeCADTranslator.md b/docs/api/FreeCADTranslator.md index 5d26e728..954748b7 100644 --- a/docs/api/FreeCADTranslator.md +++ b/docs/api/FreeCADTranslator.md @@ -3,7 +3,7 @@ ## Class Definition ```python -class FreeCADTranslator(document_name: str = 'SimpleCADModel') +class FreeCADTranslator(document_name: str = 'SimpleCADProduct') ``` *Source: translator/freecad_translator/translator.py* @@ -14,4 +14,4 @@ class FreeCADTranslator(document_name: str = 'SimpleCADModel') ## Description -Public, stateless facade for FreeCAD script translation. +Translate validated `.scadpkg` products into FreeCAD scripts. diff --git a/docs/api/Fusion360Translator.md b/docs/api/Fusion360Translator.md index d5052b82..5c206436 100644 --- a/docs/api/Fusion360Translator.md +++ b/docs/api/Fusion360Translator.md @@ -3,7 +3,7 @@ ## Class Definition ```python -class Fusion360Translator(document_name: str = 'SimpleCADModel', result_node_ids: Optional[Sequence[str]] = None, *, selection_mode: str = 'gsm', source_kernel_fallback: bool = False) +class Fusion360Translator(document_name: str = 'SimpleCADProduct', *, selection_mode: str = 'gsm', source_kernel_fallback: bool = False) ``` *Source: translator/fusion360_translator/translator.py* @@ -14,4 +14,4 @@ class Fusion360Translator(document_name: str = 'SimpleCADModel', result_node_ids ## Description -Translate canonical model JSON into a Fusion 360 Python script. +Translate validated `.scadpkg` products into Fusion 360 scripts. diff --git a/docs/api/GraphSession.md b/docs/api/GraphSession.md index c79981cb..e97d2448 100644 --- a/docs/api/GraphSession.md +++ b/docs/api/GraphSession.md @@ -3,7 +3,7 @@ ## Class Definition ```python -class GraphSession(graph_id: Optional[str] = None) +class GraphSession(graph_id: Optional[str] = None, *, allow_external_definitions: bool = False) ``` *Source: graph.py* diff --git a/docs/api/InspectionSummaryComparison.md b/docs/api/InspectionSummaryComparison.md index 9f2f41b5..6856222d 100644 --- a/docs/api/InspectionSummaryComparison.md +++ b/docs/api/InspectionSummaryComparison.md @@ -10,7 +10,7 @@ class InspectionSummaryComparison(volume_delta: float, surface_area_delta: float ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.InspectionSummaryComparison(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.InspectionSummaryComparison(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/ModelResult.md b/docs/api/ModelResult.md deleted file mode 100644 index fd222ada..00000000 --- a/docs/api/ModelResult.md +++ /dev/null @@ -1,17 +0,0 @@ -# ModelResult - -## Class Definition - -```python -class ModelResult(value: Any, session: GraphSession, result_node_ids: Tuple[str, ...], model_json: str, session_json: str, artifact_paths: Mapping[str, Path] = field(default_factory=dict)) -``` - -*Source: graph.py* - -## Import Surface - -- top-level: `from simplecadapi import ModelResult` - -## Description - -The value and durable graph artifacts produced by ``@model``. diff --git a/docs/api/PartBuildResult.md b/docs/api/PartBuildResult.md index d616c4b0..b81f14ff 100644 --- a/docs/api/PartBuildResult.md +++ b/docs/api/PartBuildResult.md @@ -3,7 +3,7 @@ ## Class Definition ```python -class PartBuildResult(value: Part, definition: PartDefinition, session: GraphSession, result_node_ids: tuple[str, ...], model_json: str, session_json: str, cache_report: CacheReport, interface_diff: PartInterfaceDiff | None = None, artifact_paths: Mapping[str, Path] = field(default_factory=dict)) +class PartBuildResult(value: Part, definition: PartDefinition, feature_graph: FeatureGraphArtifact, cache_report: CacheReport, interface_diff: PartInterfaceDiff | None = None) ``` *Source: build/results.py* @@ -14,4 +14,4 @@ class PartBuildResult(value: Part, definition: PartDefinition, session: GraphSes ## Description -Runtime Part plus its durable definition, graph, and cache evidence. +Runtime Part plus its durable definition, feature DAG, and cache evidence. diff --git a/docs/api/ProductSTEPExportReport.md b/docs/api/ProductSTEPExportReport.md new file mode 100644 index 00000000..4dbea8ce --- /dev/null +++ b/docs/api/ProductSTEPExportReport.md @@ -0,0 +1,17 @@ +# ProductSTEPExportReport + +## Class Definition + +```python +class ProductSTEPExportReport(output_path: Path, schema: str, definition_ids: tuple[str, ...], occurrence_count: int, material_ids: tuple[str, ...], metadata_item_count: int, limitations: tuple[str, ...]) +``` + +*Source: exporter/step.py* + +## Import Surface + +- exporter namespace: `from simplecadapi import exporter` then `exporter.step.ProductSTEPExportReport(...)` + +## Description + +Observed AP242 export facts and explicit semantic limitations. diff --git a/docs/api/ProductSTLExportReport.md b/docs/api/ProductSTLExportReport.md new file mode 100644 index 00000000..66c0e89f --- /dev/null +++ b/docs/api/ProductSTLExportReport.md @@ -0,0 +1,17 @@ +# ProductSTLExportReport + +## Class Definition + +```python +class ProductSTLExportReport(output_path: Path, root_definition_id: str, solid_count: int, definition_count: int, quadrilateral_count: int, residual_triangle_count: int, stl_triangle_count: int, quad_fraction: float, mesh_size: float, remesh_backend: str = 'gmsh-quad-dominant') +``` + +*Source: exporter/stl.py* + +## Import Surface + +- exporter namespace: `from simplecadapi import exporter` then `exporter.stl.ProductSTLExportReport(...)` + +## Description + +Evidence from quad-dominant product-surface remeshing and STL export. diff --git a/docs/api/README.md b/docs/api/README.md index d1235374..05088233 100644 --- a/docs/api/README.md +++ b/docs/api/README.md @@ -6,7 +6,7 @@ This index includes generated docs for the public SimpleCAD API surface, includi - Entries marked `top-level` are exported from `simplecadapi` and can be imported with `from simplecadapi import `. - Entries marked `submodule` are public through the listed submodule, such as `simplecadapi.ql`. -- Entries marked `inspection namespace` are available through `simplecadapi.inspect.brep` and cannot run inside `GraphSession` or `@model`. +- Entries marked `inspection namespace` are available through `simplecadapi.inspect.brep` and cannot run inside `GraphSession`. - Entries marked `translator backend` are public only through `simplecadapi.translator.`. ## Basic Creation @@ -91,22 +91,20 @@ This index includes generated docs for the public SimpleCAD API surface, includi ## Export -- [export_product_package](export_product_package.md) *(from product_packages.py)* `top-level` -- [export_step](export_step.md) *(from operations.py)* `top-level` -- [export_stl](export_stl.md) *(from operations.py)* `top-level` +- [ProductSTEPExportReport](ProductSTEPExportReport.md) *(from exporter/step.py)* `exporter namespace` +- [ProductSTLExportReport](ProductSTLExportReport.md) *(from exporter/stl.py)* `exporter namespace` +- [export_product_package_to_step](export_product_package_to_step.md) *(from exporter/step.py)* `exporter namespace` +- [export_product_package_to_stl](export_product_package_to_stl.md) *(from exporter/stl.py)* `exporter namespace` ## Translator Backends -- [FreeCADScriptTranslator](FreeCADScriptTranslator.md) *(from translator/freecad_translator/translator.py)* `translator backend` - [FreeCADTranslator](FreeCADTranslator.md) *(from translator/freecad_translator/translator.py)* `translator backend` - [Fusion360Translator](Fusion360Translator.md) *(from translator/fusion360_translator/translator.py)* `translator backend` - [SolidWorksTranslator](SolidWorksTranslator.md) *(from translator/solidworks_translator/translator.py)* `translator backend` -- [export_model_json_to_fcstd](export_model_json_to_fcstd.md) *(from translator/freecad_translator/api.py)* `translator backend` -- [export_model_json_to_solidworks_step](export_model_json_to_solidworks_step.md) *(from translator/solidworks_translator/api.py)* `translator backend` -- [translate_model_json_to_fcstd](translate_model_json_to_fcstd.md) *(from translator/freecad_translator/api.py)* `translator backend` -- [translate_model_json_to_freecad_script](translate_model_json_to_freecad_script.md) *(from translator/freecad_translator/api.py)* `translator backend` -- [translate_model_json_to_fusion360_script](translate_model_json_to_fusion360_script.md) *(from translator/fusion360_translator/api.py)* `translator backend` -- [translate_model_json_to_solidworks_script](translate_model_json_to_solidworks_script.md) *(from translator/solidworks_translator/api.py)* `translator backend` +- [translate_product_package_to_fcstd](translate_product_package_to_fcstd.md) *(from translator/freecad_translator/api.py)* `translator backend` +- [translate_product_package_to_freecad_script](translate_product_package_to_freecad_script.md) *(from translator/freecad_translator/api.py)* `translator backend` +- [translate_product_package_to_fusion360_script](translate_product_package_to_fusion360_script.md) *(from translator/fusion360_translator/api.py)* `translator backend` +- [translate_product_package_to_solidworks_script](translate_product_package_to_solidworks_script.md) *(from translator/solidworks_translator/api.py)* `translator backend` ## Math Helpers @@ -116,8 +114,6 @@ This index includes generated docs for the public SimpleCAD API surface, includi ## Modeling Graph and Replay - [GraphSession](GraphSession.md) *(from graph.py)* `top-level` -- [ModelResult](ModelResult.md) *(from graph.py)* `top-level` -- [capture_result](capture_result.md) *(from graph.py)* `top-level` - [export_graph_json](export_graph_json.md) *(from serializer.py)* `top-level` - [export_model_json](export_model_json.md) *(from serializer.py)* `top-level` - [export_session_json](export_session_json.md) *(from serializer.py)* `top-level` @@ -125,10 +121,8 @@ This index includes generated docs for the public SimpleCAD API surface, includi - [import_graph_json](import_graph_json.md) *(from serializer.py)* `top-level` - [import_model_json](import_model_json.md) *(from serializer.py)* `top-level` - [import_session_json](import_session_json.md) *(from serializer.py)* `top-level` -- [model](model.md) *(from graph.py)* `top-level` - [replay_graph](replay_graph.md) *(from serializer.py)* `top-level` - [replay_model_json](replay_model_json.md) *(from serializer.py)* `top-level` -- [requires_session](requires_session.md) *(from graph.py)* `top-level` - [suspend_graph_recording](suspend_graph_recording.md) *(from graph.py)* `top-level` ## Expressions and Parameters @@ -256,6 +250,7 @@ This index includes generated docs for the public SimpleCAD API surface, includi ## Other - [Assembly](Assembly.md) *(from product.py)* `top-level` +- [CaptureResult](CaptureResult.md) *(from capture.py)* `top-level` - [Component](Component.md) *(from product.py)* `top-level` - [Connector](Connector.md) *(from product.py)* `top-level` - [ConnectorAnchor](ConnectorAnchor.md) *(from product.py)* `top-level` @@ -291,6 +286,7 @@ This index includes generated docs for the public SimpleCAD API surface, includi - [and_](and_.md) *(from ql.py)* `submodule:ql` - [assign_material_rpart](assign_material_rpart.md) *(from operations.py)* `top-level` - [build_product_package](build_product_package.md) *(from product_packages.py)* `top-level` +- [capture](capture.md) *(from capture.py)* `top-level` - [constrain_angle_rsketch](constrain_angle_rsketch.md) *(from operations.py)* `top-level` - [constrain_coincident_rsketch](constrain_coincident_rsketch.md) *(from operations.py)* `top-level` - [constrain_collinear_rsketch](constrain_collinear_rsketch.md) *(from operations.py)* `top-level` diff --git a/docs/api/SliceSpec.md b/docs/api/SliceSpec.md index bf3d8e5c..5a0fc0b5 100644 --- a/docs/api/SliceSpec.md +++ b/docs/api/SliceSpec.md @@ -10,7 +10,7 @@ class SliceSpec(plane: SlicePlane, value: float, label: str | None = None) ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.SliceSpec(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.SliceSpec(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/SolidWorksTranslator.md b/docs/api/SolidWorksTranslator.md index 0b3b86ee..09580538 100644 --- a/docs/api/SolidWorksTranslator.md +++ b/docs/api/SolidWorksTranslator.md @@ -3,7 +3,7 @@ ## Class Definition ```python -class SolidWorksTranslator(document_name: str = 'SimpleCADModel', *, output_path: Optional[str] = None, visible: bool = False, source_kernel_fallback: bool = False) +class SolidWorksTranslator(document_name: str = 'SimpleCADProduct', *, output_path: str | None = None, visible: bool = False, source_kernel_fallback: bool = False) ``` *Source: translator/solidworks_translator/translator.py* @@ -14,4 +14,4 @@ class SolidWorksTranslator(document_name: str = 'SimpleCADModel', *, output_path ## Description -Translate canonical model JSON into a SolidWorks COM Python script. +Translate one validated `.scadpkg` closure into SolidWorks automation. diff --git a/docs/api/assemble.md b/docs/api/assemble.md index 36a929fa..af7b3f6a 100644 --- a/docs/api/assemble.md +++ b/docs/api/assemble.md @@ -3,7 +3,7 @@ ## API Definition ```python -def assemble(func: Callable[_P, _R] | None = None, *, id: str | None = None, revision: str = '1.0.0', definitions: Sequence[Any] = (), cache: CachePolicy | Mapping[str, Any] | str | None = None, export_dir: str | Path | None = None, project_root: str | Path | None = None, tolerance_profile: str = 'simplecad-default') -> Callable[[Callable[_P, _R]], Callable[_P, AssemblyBuildResult]] | Callable[_P, AssemblyBuildResult] +def assemble(func: Callable[_P, _R] | None = None, *, id: str | None = None, revision: str = '1.0.0', definitions: Sequence[Any] = (), cache: CachePolicy | Mapping[str, Any] | str | None = None, project_root: str | Path | None = None, tolerance_profile: str = 'simplecad-default') -> Callable[[Callable[_P, _R]], Callable[_P, AssemblyBuildResult]] | Callable[_P, AssemblyBuildResult] ``` *Source: build/assembly_builder.py* diff --git a/docs/api/capture.md b/docs/api/capture.md new file mode 100644 index 00000000..94e50ea8 --- /dev/null +++ b/docs/api/capture.md @@ -0,0 +1,17 @@ +# capture + +## API Definition + +```python +def capture(result: Any, path: str | Path, /) -> CaptureResult +``` + +*Source: capture.py* + +## Import Surface + +- top-level: `from simplecadapi import capture` + +## Description + +Capture a durable product and write its canonical `.scadpkg`. diff --git a/docs/api/capture_result.md b/docs/api/capture_result.md deleted file mode 100644 index 942c6e80..00000000 --- a/docs/api/capture_result.md +++ /dev/null @@ -1,17 +0,0 @@ -# capture_result - -## API Definition - -```python -def capture_result(*, value: Any) -> Any -``` - -*Source: graph.py* - -## Import Surface - -- top-level: `from simplecadapi import capture_result` - -## Description - -Capture *value* as an explicit result in the active model session. diff --git a/docs/api/clear_step_model_cache_rnone.md b/docs/api/clear_step_model_cache_rnone.md index 70c243ba..8ed290cb 100644 --- a/docs/api/clear_step_model_cache_rnone.md +++ b/docs/api/clear_step_model_cache_rnone.md @@ -10,7 +10,7 @@ def clear_step_model_cache_rnone() -> None ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.clear_step_model_cache_rnone(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.clear_step_model_cache_rnone(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/compare_boundary_distance_rdescriptor.md b/docs/api/compare_boundary_distance_rdescriptor.md index 4641a383..19174a8f 100644 --- a/docs/api/compare_boundary_distance_rdescriptor.md +++ b/docs/api/compare_boundary_distance_rdescriptor.md @@ -10,7 +10,7 @@ def compare_boundary_distance_rdescriptor(target: ModelInput, current: ModelInpu ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_boundary_distance_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_boundary_distance_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/compare_entities_rdescriptor.md b/docs/api/compare_entities_rdescriptor.md index f954b08d..a27360af 100644 --- a/docs/api/compare_entities_rdescriptor.md +++ b/docs/api/compare_entities_rdescriptor.md @@ -10,7 +10,7 @@ def compare_entities_rdescriptor(target: ModelInput, target_entity_id: str, curr ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_entities_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_entities_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/compare_global_properties_rdescriptor.md b/docs/api/compare_global_properties_rdescriptor.md index b7b57db6..bfabbbd3 100644 --- a/docs/api/compare_global_properties_rdescriptor.md +++ b/docs/api/compare_global_properties_rdescriptor.md @@ -10,7 +10,7 @@ def compare_global_properties_rdescriptor(target: ModelInput, current: ModelInpu ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_global_properties_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_global_properties_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/compare_inspections_rinspectionsummarycomparison.md b/docs/api/compare_inspections_rinspectionsummarycomparison.md index 29611589..a67187a5 100644 --- a/docs/api/compare_inspections_rinspectionsummarycomparison.md +++ b/docs/api/compare_inspections_rinspectionsummarycomparison.md @@ -10,7 +10,7 @@ def compare_inspections_rinspectionsummarycomparison(target: BRepInspection, can ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_inspections_rinspectionsummarycomparison(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_inspections_rinspectionsummarycomparison(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/compare_material_rdescriptor.md b/docs/api/compare_material_rdescriptor.md index 5121f010..3c0ee100 100644 --- a/docs/api/compare_material_rdescriptor.md +++ b/docs/api/compare_material_rdescriptor.md @@ -10,7 +10,7 @@ def compare_material_rdescriptor(target: ModelInput, current: ModelInput, *, boo ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_material_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_material_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/compare_model_to_inspection_rentityinspectionparity.md b/docs/api/compare_model_to_inspection_rentityinspectionparity.md index ae9beeac..07861031 100644 --- a/docs/api/compare_model_to_inspection_rentityinspectionparity.md +++ b/docs/api/compare_model_to_inspection_rentityinspectionparity.md @@ -10,7 +10,7 @@ def compare_model_to_inspection_rentityinspectionparity(model: BRepModel, report ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_model_to_inspection_rentityinspectionparity(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_model_to_inspection_rentityinspectionparity(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/compare_sections_rdescriptor.md b/docs/api/compare_sections_rdescriptor.md index 0390ead6..e786ee9a 100644 --- a/docs/api/compare_sections_rdescriptor.md +++ b/docs/api/compare_sections_rdescriptor.md @@ -10,7 +10,7 @@ def compare_sections_rdescriptor(target: ModelInput, current: ModelInput, plane_ ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_sections_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_sections_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/compare_shape_slices_rslicecomparison.md b/docs/api/compare_shape_slices_rslicecomparison.md index b85e8e54..53ab45a0 100644 --- a/docs/api/compare_shape_slices_rslicecomparison.md +++ b/docs/api/compare_shape_slices_rslicecomparison.md @@ -10,7 +10,7 @@ def compare_shape_slices_rslicecomparison(target: TopoDS_Shape, candidate: TopoD ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_shape_slices_rslicecomparison(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_shape_slices_rslicecomparison(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/compare_shapes_rbrepcomparison.md b/docs/api/compare_shapes_rbrepcomparison.md index cb33aa7e..2fbbc9bf 100644 --- a/docs/api/compare_shapes_rbrepcomparison.md +++ b/docs/api/compare_shapes_rbrepcomparison.md @@ -10,7 +10,7 @@ def compare_shapes_rbrepcomparison(target: TopoDS_Shape, candidate: TopoDS_Shape ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_shapes_rbrepcomparison(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_shapes_rbrepcomparison(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/compare_step_slices_rslicecomparison.md b/docs/api/compare_step_slices_rslicecomparison.md index e96fccc7..f35b1939 100644 --- a/docs/api/compare_step_slices_rslicecomparison.md +++ b/docs/api/compare_step_slices_rslicecomparison.md @@ -10,7 +10,7 @@ def compare_step_slices_rslicecomparison(target_path: str | Path, candidate_path ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_step_slices_rslicecomparison(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_step_slices_rslicecomparison(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/compare_step_to_inspection_rentityinspectionparity.md b/docs/api/compare_step_to_inspection_rentityinspectionparity.md index d947cb6f..794f212c 100644 --- a/docs/api/compare_step_to_inspection_rentityinspectionparity.md +++ b/docs/api/compare_step_to_inspection_rentityinspectionparity.md @@ -10,7 +10,7 @@ def compare_step_to_inspection_rentityinspectionparity(step_path: str | Path, re ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_step_to_inspection_rentityinspectionparity(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_step_to_inspection_rentityinspectionparity(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/compare_steps_rbrepcomparison.md b/docs/api/compare_steps_rbrepcomparison.md index 9b9f0c69..6fde7668 100644 --- a/docs/api/compare_steps_rbrepcomparison.md +++ b/docs/api/compare_steps_rbrepcomparison.md @@ -10,7 +10,7 @@ def compare_steps_rbrepcomparison(target_path: str | Path, candidate_path: str | ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_steps_rbrepcomparison(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_steps_rbrepcomparison(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/evaluate_reconstruction_rdescriptor.md b/docs/api/evaluate_reconstruction_rdescriptor.md index a674882c..35bc52eb 100644 --- a/docs/api/evaluate_reconstruction_rdescriptor.md +++ b/docs/api/evaluate_reconstruction_rdescriptor.md @@ -10,7 +10,7 @@ def evaluate_reconstruction_rdescriptor(target: ModelInput, current: ModelInput, ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.evaluate_reconstruction_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.evaluate_reconstruction_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/export_model_json_to_fcstd.md b/docs/api/export_model_json_to_fcstd.md deleted file mode 100644 index f2f35fca..00000000 --- a/docs/api/export_model_json_to_fcstd.md +++ /dev/null @@ -1,17 +0,0 @@ -# export_model_json_to_fcstd - -## API Definition - -```python -def export_model_json_to_fcstd(json_str: str, output_path: str, *, document_name: str = 'SimpleCADModel', freecad_cmd: Optional[str] = None) -> str -``` - -*Source: translator/freecad_translator/api.py* - -## Import Surface - -- translator backend: `from simplecadapi.translator.freecad_translator import export_model_json_to_fcstd` - -## Description - -Export canonical model JSON to `.FCStd` via FreeCADCmd/FreeCAD. diff --git a/docs/api/export_model_json_to_solidworks_step.md b/docs/api/export_model_json_to_solidworks_step.md deleted file mode 100644 index c9ee857b..00000000 --- a/docs/api/export_model_json_to_solidworks_step.md +++ /dev/null @@ -1,17 +0,0 @@ -# export_model_json_to_solidworks_step - -## API Definition - -```python -def export_model_json_to_solidworks_step(json_str: str, output_path: str, *, document_name: str = 'SimpleCADModel', visible: bool = False, python_exe: Optional[str] = None, source_kernel_fallback: bool = False) -> str -``` - -*Source: translator/solidworks_translator/api.py* - -## Import Surface - -- translator backend: `from simplecadapi.translator.solidworks_translator import export_model_json_to_solidworks_step` - -## Description - -Execute SolidWorks COM automation and export a STEP file. diff --git a/docs/api/export_product_package.md b/docs/api/export_product_package.md deleted file mode 100644 index 8a903d05..00000000 --- a/docs/api/export_product_package.md +++ /dev/null @@ -1,17 +0,0 @@ -# export_product_package - -## API Definition - -```python -def export_product_package(package: ProductPackage, path: str | Path) -> Path -``` - -*Source: product_packages.py* - -## Import Surface - -- top-level: `from simplecadapi import export_product_package` - -## Description - -Write one canonical self-contained `.scadpkg` archive. diff --git a/docs/api/export_product_package_to_step.md b/docs/api/export_product_package_to_step.md new file mode 100644 index 00000000..6882ff1a --- /dev/null +++ b/docs/api/export_product_package_to_step.md @@ -0,0 +1,17 @@ +# export_product_package_to_step + +## API Definition + +```python +def export_product_package_to_step(data: ProductPackageInput, output_path: str | Path) -> ProductSTEPExportReport +``` + +*Source: exporter/step.py* + +## Import Surface + +- exporter namespace: `from simplecadapi import exporter` then `exporter.step.export_product_package_to_step(...)` + +## Description + +Export a validated `.scadpkg` closure as XCAF-backed AP242 STEP. diff --git a/docs/api/export_product_package_to_stl.md b/docs/api/export_product_package_to_stl.md new file mode 100644 index 00000000..922d7308 --- /dev/null +++ b/docs/api/export_product_package_to_stl.md @@ -0,0 +1,20 @@ +# export_product_package_to_stl + +## API Definition + +```python +def export_product_package_to_stl(data: ProductPackageInput, output_path: str | Path, *, mesh_size: float = 1.0, recombination_angle_degrees: float = 45.0) -> ProductSTLExportReport +``` + +*Source: exporter/stl.py* + +## Import Surface + +- exporter namespace: `from simplecadapi import exporter` then `exporter.stl.export_product_package_to_stl(...)` + +## Description + +Export one validated `.scadpkg` as a quad-dominant remeshed STL. + +Gmsh recombines each CAD surface into quadrilaterals before its STL writer +splits every quad into two triangles, as required by the STL file format. diff --git a/docs/api/export_step.md b/docs/api/export_step.md deleted file mode 100644 index 40ae34f4..00000000 --- a/docs/api/export_step.md +++ /dev/null @@ -1,50 +0,0 @@ -# export_step - -## API Definition - -```python -def export_step(shapes: Union[AnyShape, Sequence[AnyShape]], filename: str) -> None -``` - -*Source: operations.py* - -## Import Surface - -- top-level: `from simplecadapi import export_step` - -## Description - -Export shapes to STEP. - -Use this function when you want to export one shape or many shapes into the -same STEP file. Passing `List[Solid]` is valid for pattern outputs or -explicit shape collections. Boolean operations return a single `Solid`. - -## Parameters - -### shapes - -- **Description**: A single exportable shape or any nested sequence of exportable shapes. Lists of Solid are supported directly, including pattern or explicitly collected multi-shape results. - -### filename - -- **Description**: Output STEP file path. - -## Returns - -None: Writes the provided shapes into one STEP file. - -## Examples - -### Example 1 -```python -main_body = make_box_rsolid(10, 4, 4, bottom_face_center=(0, 0, 0)) -left_cap = make_sphere_rsolid(2.0, center=(-2.0, 2.0, 2.0)) -right_cap = make_sphere_rsolid(2.0, center=(12.0, 2.0, 2.0)) -body = union_rsolid(main_body, [left_cap, right_cap]) -``` - -### Example 2 -```python -export_step(body, "rounded_bar.step") -``` diff --git a/docs/api/export_stl.md b/docs/api/export_stl.md deleted file mode 100644 index fb9f6bca..00000000 --- a/docs/api/export_stl.md +++ /dev/null @@ -1,50 +0,0 @@ -# export_stl - -## API Definition - -```python -def export_stl(shapes: Union[AnyShape, Sequence[AnyShape]], filename: str) -> None -``` - -*Source: operations.py* - -## Import Surface - -- top-level: `from simplecadapi import export_stl` - -## Description - -Export shapes to STL. - -Use this function when you want to export one compound, solid, or face into -the same STL file. Passing `List[Solid]` is valid for pattern outputs or -explicit shape collections. Boolean operations return a single `Solid`. - -## Parameters - -### shapes - -- **Description**: A single Compound, Solid, or Face, or any nested sequence of those. Lists of Solid are supported directly, including pattern or explicitly collected multi-shape results. - -### filename - -- **Description**: Output STL file path. - -## Returns - -None: Writes the provided shapes into one STL file. - -## Examples - -### Example 1 -```python -main_body = make_box_rsolid(10, 4, 4, bottom_face_center=(0, 0, 0)) -left_cap = make_sphere_rsolid(2.0, center=(-2.0, 2.0, 2.0)) -right_cap = make_sphere_rsolid(2.0, center=(12.0, 2.0, 2.0)) -body = union_rsolid(main_body, [left_cap, right_cap]) -``` - -### Example 2 -```python -export_stl(body, "rounded_bar.stl") -``` diff --git a/docs/api/index_shape_rbrepmodel.md b/docs/api/index_shape_rbrepmodel.md index dd615099..42c2e0e9 100644 --- a/docs/api/index_shape_rbrepmodel.md +++ b/docs/api/index_shape_rbrepmodel.md @@ -10,7 +10,7 @@ def index_shape_rbrepmodel(shape: TopoDS_Shape, *, source: str | Path | None = N ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.index_shape_rbrepmodel(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.index_shape_rbrepmodel(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/inspect_difference_regions_rdescriptor.md b/docs/api/inspect_difference_regions_rdescriptor.md index 51f201e8..12dac091 100644 --- a/docs/api/inspect_difference_regions_rdescriptor.md +++ b/docs/api/inspect_difference_regions_rdescriptor.md @@ -10,7 +10,7 @@ def inspect_difference_regions_rdescriptor(target: ModelInput, current: ModelInp ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_difference_regions_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_difference_regions_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/inspect_face_boundaries_rdescriptor.md b/docs/api/inspect_face_boundaries_rdescriptor.md index bb28c35e..e065fb78 100644 --- a/docs/api/inspect_face_boundaries_rdescriptor.md +++ b/docs/api/inspect_face_boundaries_rdescriptor.md @@ -10,7 +10,7 @@ def inspect_face_boundaries_rdescriptor(model_or_path: BRepModel | TopoDS_Shape ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_face_boundaries_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_face_boundaries_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/inspect_nearby_entities_rdescriptor.md b/docs/api/inspect_nearby_entities_rdescriptor.md index 0709fd82..5a60d48a 100644 --- a/docs/api/inspect_nearby_entities_rdescriptor.md +++ b/docs/api/inspect_nearby_entities_rdescriptor.md @@ -10,7 +10,7 @@ def inspect_nearby_entities_rdescriptor(model: ModelInput, *, location: Sequence ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_nearby_entities_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_nearby_entities_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/inspect_point_rdescriptor.md b/docs/api/inspect_point_rdescriptor.md index 11a66545..2612aa82 100644 --- a/docs/api/inspect_point_rdescriptor.md +++ b/docs/api/inspect_point_rdescriptor.md @@ -10,7 +10,7 @@ def inspect_point_rdescriptor(model_or_path: BRepModel | TopoDS_Shape | str | Pa ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_point_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_point_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/inspect_section_rdescriptor.md b/docs/api/inspect_section_rdescriptor.md index c2abcba7..30c0b060 100644 --- a/docs/api/inspect_section_rdescriptor.md +++ b/docs/api/inspect_section_rdescriptor.md @@ -10,7 +10,7 @@ def inspect_section_rdescriptor(model_or_path: BRepModel | TopoDS_Shape | str | ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_section_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_section_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/inspect_shape_rbrepinspection.md b/docs/api/inspect_shape_rbrepinspection.md index e1a77261..c97ffc4d 100644 --- a/docs/api/inspect_shape_rbrepinspection.md +++ b/docs/api/inspect_shape_rbrepinspection.md @@ -10,7 +10,7 @@ def inspect_shape_rbrepinspection(shape: TopoDS_Shape, *, source: str | Path | N ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_shape_rbrepinspection(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_shape_rbrepinspection(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/inspect_step_components_rdescriptorlist.md b/docs/api/inspect_step_components_rdescriptorlist.md index 367b0adc..d107ed3d 100644 --- a/docs/api/inspect_step_components_rdescriptorlist.md +++ b/docs/api/inspect_step_components_rdescriptorlist.md @@ -10,7 +10,7 @@ def inspect_step_components_rdescriptorlist(step_path: str | Path) -> list[dict[ ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_step_components_rdescriptorlist(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_step_components_rdescriptorlist(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/inspect_step_entity_rdescriptor.md b/docs/api/inspect_step_entity_rdescriptor.md index 622794f3..1b4b3a77 100644 --- a/docs/api/inspect_step_entity_rdescriptor.md +++ b/docs/api/inspect_step_entity_rdescriptor.md @@ -10,7 +10,7 @@ def inspect_step_entity_rdescriptor(path: str | Path, entity_id: str, *, include ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_step_entity_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_step_entity_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/inspect_step_rbrepinspection.md b/docs/api/inspect_step_rbrepinspection.md index 39ac34db..cc529692 100644 --- a/docs/api/inspect_step_rbrepinspection.md +++ b/docs/api/inspect_step_rbrepinspection.md @@ -10,7 +10,7 @@ def inspect_step_rbrepinspection(path: str | Path) -> BRepInspection ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_step_rbrepinspection(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_step_rbrepinspection(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/inspect_step_rsummary.md b/docs/api/inspect_step_rsummary.md index 42f569bb..9ff396b2 100644 --- a/docs/api/inspect_step_rsummary.md +++ b/docs/api/inspect_step_rsummary.md @@ -10,7 +10,7 @@ def inspect_step_rsummary(path: str | Path, *, include_parameter_groups: bool = ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_step_rsummary(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_step_rsummary(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/inspect_topology_neighborhood_rdescriptor.md b/docs/api/inspect_topology_neighborhood_rdescriptor.md index b0b5ffb9..f7485d3f 100644 --- a/docs/api/inspect_topology_neighborhood_rdescriptor.md +++ b/docs/api/inspect_topology_neighborhood_rdescriptor.md @@ -10,7 +10,7 @@ def inspect_topology_neighborhood_rdescriptor(model_or_path: BRepModel | TopoDS_ ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_topology_neighborhood_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_topology_neighborhood_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/load_step_rbrepmodel.md b/docs/api/load_step_rbrepmodel.md index 8b0459a6..9eb7cbf0 100644 --- a/docs/api/load_step_rbrepmodel.md +++ b/docs/api/load_step_rbrepmodel.md @@ -10,7 +10,7 @@ def load_step_rbrepmodel(path: str | Path) -> BRepModel ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.load_step_rbrepmodel(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.load_step_rbrepmodel(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/load_step_rshape.md b/docs/api/load_step_rshape.md index 0fc91ecb..6cafd213 100644 --- a/docs/api/load_step_rshape.md +++ b/docs/api/load_step_rshape.md @@ -10,7 +10,7 @@ def load_step_rshape(path: str | Path, *, require_single_root: bool = True, requ ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.load_step_rshape(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.load_step_rshape(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/make_center_slice_specs_rslicespeclist.md b/docs/api/make_center_slice_specs_rslicespeclist.md index 4aa04c0b..87a807ca 100644 --- a/docs/api/make_center_slice_specs_rslicespeclist.md +++ b/docs/api/make_center_slice_specs_rslicespeclist.md @@ -10,7 +10,7 @@ def make_center_slice_specs_rslicespeclist(minimum: np.ndarray, maximum: np.ndar ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.make_center_slice_specs_rslicespeclist(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.make_center_slice_specs_rslicespeclist(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/measure_entity_relation_rdescriptor.md b/docs/api/measure_entity_relation_rdescriptor.md index 6013645c..2f489760 100644 --- a/docs/api/measure_entity_relation_rdescriptor.md +++ b/docs/api/measure_entity_relation_rdescriptor.md @@ -10,7 +10,7 @@ def measure_entity_relation_rdescriptor(model_or_path: BRepModel | TopoDS_Shape ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.measure_entity_relation_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.measure_entity_relation_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/measure_shape_mass_rtuple.md b/docs/api/measure_shape_mass_rtuple.md index 42216d59..ce2f74e4 100644 --- a/docs/api/measure_shape_mass_rtuple.md +++ b/docs/api/measure_shape_mass_rtuple.md @@ -10,7 +10,7 @@ def measure_shape_mass_rtuple(shape: TopoDS_Shape, kind: PropertyKind) -> tuple[ ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.measure_shape_mass_rtuple(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.measure_shape_mass_rtuple(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/model.md b/docs/api/model.md deleted file mode 100644 index 0339b1ab..00000000 --- a/docs/api/model.md +++ /dev/null @@ -1,17 +0,0 @@ -# model - -## API Definition - -```python -def model(func: Optional[Callable[_P, _R]] = None, *, graph_id: Optional[str] = None, export_dir: str | Path | None = None) -> Union[Callable[[Callable[_P, _R]], Callable[_P, ModelResult]], Callable[_P, ModelResult]] -``` - -*Source: graph.py* - -## Import Surface - -- top-level: `from simplecadapi import model` - -## Description - -Decorate a top-level model function with one owned ``GraphSession``. diff --git a/docs/api/part_function.md b/docs/api/part_function.md index 2108b717..82d70405 100644 --- a/docs/api/part_function.md +++ b/docs/api/part_function.md @@ -3,7 +3,7 @@ ## API Definition ```python -def part(func: Callable[_P, _R] | None = None, *, id: str | None = None, revision: str = '1.0.0', inputs: Sequence[FileInput] = (), cache: CachePolicy | Mapping[str, Any] | str | None = None, export_dir: str | Path | None = None, project_root: str | Path | None = None, tolerance_profile: str = 'simplecad-default') -> Callable[[Callable[_P, _R]], Callable[_P, PartBuildResult]] | Callable[_P, PartBuildResult] +def part(func: Callable[_P, _R] | None = None, *, id: str | None = None, revision: str = '1.0.0', inputs: Sequence[FileInput] = (), cache: CachePolicy | Mapping[str, Any] | str | None = None, project_root: str | Path | None = None, tolerance_profile: str = 'simplecad-default') -> Callable[[Callable[_P, _R]], Callable[_P, PartBuildResult]] | Callable[_P, PartBuildResult] ``` *Source: build/part_builder.py* diff --git a/docs/api/render_entity_kind_maps_rpath.md b/docs/api/render_entity_kind_maps_rpath.md index 0d0f831b..9a142601 100644 --- a/docs/api/render_entity_kind_maps_rpath.md +++ b/docs/api/render_entity_kind_maps_rpath.md @@ -10,7 +10,7 @@ def render_entity_kind_maps_rpath(model_or_path: BRepModel | TopoDS_Shape | str ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_entity_kind_maps_rpath(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_entity_kind_maps_rpath(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/render_entity_map_rpath.md b/docs/api/render_entity_map_rpath.md index c11ca2ea..3e27f77c 100644 --- a/docs/api/render_entity_map_rpath.md +++ b/docs/api/render_entity_map_rpath.md @@ -10,7 +10,7 @@ def render_entity_map_rpath(model_or_path: BRepModel | TopoDS_Shape | str | Path ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_entity_map_rpath(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_entity_map_rpath(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/render_region_rpath.md b/docs/api/render_region_rpath.md index bf89ab47..f7d90b54 100644 --- a/docs/api/render_region_rpath.md +++ b/docs/api/render_region_rpath.md @@ -10,7 +10,7 @@ def render_region_rpath(model_or_path: BRepModel | TopoDS_Shape | str | Path, en ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_region_rpath(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_region_rpath(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/render_shape_views_rpath.md b/docs/api/render_shape_views_rpath.md index 044a6dcc..3afb565b 100644 --- a/docs/api/render_shape_views_rpath.md +++ b/docs/api/render_shape_views_rpath.md @@ -10,7 +10,7 @@ def render_shape_views_rpath(shape: TopoDS_Shape, output_path: str | Path, *, ti ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_shape_views_rpath(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_shape_views_rpath(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/render_step_components_colored_rpath.md b/docs/api/render_step_components_colored_rpath.md index 262bd5bb..45c86842 100644 --- a/docs/api/render_step_components_colored_rpath.md +++ b/docs/api/render_step_components_colored_rpath.md @@ -10,7 +10,7 @@ def render_step_components_colored_rpath(step_path: str | Path, component_colors ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_step_components_colored_rpath(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_step_components_colored_rpath(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/render_step_components_rpath.md b/docs/api/render_step_components_rpath.md index 13f76237..534a0368 100644 --- a/docs/api/render_step_components_rpath.md +++ b/docs/api/render_step_components_rpath.md @@ -10,7 +10,7 @@ def render_step_components_rpath(step_path: str | Path, component_names: Sequenc ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_step_components_rpath(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_step_components_rpath(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/render_step_views_rpath.md b/docs/api/render_step_views_rpath.md index de144795..60730573 100644 --- a/docs/api/render_step_views_rpath.md +++ b/docs/api/render_step_views_rpath.md @@ -10,7 +10,7 @@ def render_step_views_rpath(step_path: str | Path, output_path: str | Path, **kw ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_step_views_rpath(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_step_views_rpath(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/requires_session.md b/docs/api/requires_session.md deleted file mode 100644 index ceeaa9ea..00000000 --- a/docs/api/requires_session.md +++ /dev/null @@ -1,17 +0,0 @@ -# requires_session - -## API Definition - -```python -def requires_session(func: Optional[Callable[_P, _R]] = None) -> Union[Callable[[Callable[_P, _R]], Callable[_P, _R]], Callable[_P, _R]] -``` - -*Source: graph.py* - -## Import Surface - -- top-level: `from simplecadapi import requires_session` - -## Description - -Decorate a builder that must reuse the caller's active GraphSession. diff --git a/docs/api/select_region_entities_rdescriptor.md b/docs/api/select_region_entities_rdescriptor.md index cc49d5f0..b9326ce7 100644 --- a/docs/api/select_region_entities_rdescriptor.md +++ b/docs/api/select_region_entities_rdescriptor.md @@ -10,7 +10,7 @@ def select_region_entities_rdescriptor(model_or_path: BRepModel | TopoDS_Shape | ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.select_region_entities_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.select_region_entities_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/docs/api/translate_model_json_to_fcstd.md b/docs/api/translate_model_json_to_fcstd.md deleted file mode 100644 index b4d6627a..00000000 --- a/docs/api/translate_model_json_to_fcstd.md +++ /dev/null @@ -1,40 +0,0 @@ -# translate_model_json_to_fcstd - -## API Definition - -```python -def translate_model_json_to_fcstd(json_str: str, output_path: str, *, document_name: str = 'SimpleCADModel', freecad_cmd: Optional[str] = None) -> str -``` - -*Source: translator/freecad_translator/api.py* - -## Import Surface - -- translator backend: `from simplecadapi.translator.freecad_translator import translate_model_json_to_fcstd` - -## Description - -Translate canonical model JSON to `.FCStd` via FreeCADCmd/FreeCAD. - -Functional sketch promotions are written as visible `Sketcher::SketchObject` -nodes with mapped/skipped constraint evidence. Exact B-spline edges are -exported to FreeCAD using `Part.BSplineCurve().buildFromPolesMultsKnots(...)`. -Safe single-use profile transforms such as section rotate/translate chains are -folded into the section object's placement so downstream `Part::Loft` receives -already-positioned sections instead of placement-bearing `App::Link` proxies. -Geometry results use FreeCAD objects directly: assignment targets name design -objects and shared inputs receive independent occurrences per consumer. Native -features preserve recomputing dependencies, including surface-dependent -Booleans. Their classifications may vary across FreeCAD/OCCT versions. No -presentation proxy, duplicate history tree, or hidden graph-object archive is -created. -`apply_tag_rselection` remains graph metadata rather than a FreeCAD feature; -traceable geometry and visible result objects expose `SimpleCADAppliedTags`, -`SimpleCADTagBindings`, and `SimpleCADTagNodeIds`. -Part/Assembly product nodes are written as editable FreeCAD assembly structure: -parts use `App::Part`, assemblies use native `Assembly::AssemblyObject`, part -components use `App::Link`, and nested assembly components use -`Assembly::AssemblyLink`. Explicit assembly-to-compound projections remain -available for geometry workflows without creating a second user-facing root. -Link source definitions remain in the document for recomputation, but the -Tree View exposes only the resolved product or standalone-geometry roots. diff --git a/docs/api/translate_model_json_to_freecad_script.md b/docs/api/translate_model_json_to_freecad_script.md deleted file mode 100644 index 3ba89b97..00000000 --- a/docs/api/translate_model_json_to_freecad_script.md +++ /dev/null @@ -1,30 +0,0 @@ -# translate_model_json_to_freecad_script - -## API Definition - -```python -def translate_model_json_to_freecad_script(json_str: str, document_name: str = 'SimpleCADModel') -> str -``` - -*Source: translator/freecad_translator/api.py* - -## Import Surface - -- translator backend: `from simplecadapi.translator.freecad_translator import translate_model_json_to_freecad_script` - -## Description - -Translate exported model JSON into a FreeCAD Python script. - -Geometry is emitted as FreeCAD occurrence trees. Serialized source assignment -targets name native design objects, shared DAG inputs are copied per consuming -result, and feature links preserve dependencies. Booleans are emitted as native -recomputable `Part::Cut`, `Part::Fuse`, and `Part::Common` features. Stable node -ids remain available as internal metadata. -`apply_tag_rselection` nodes do not create FreeCAD features. Their canonical -bindings and source node ids are attached to traceable geometry and visible -result objects as `SimpleCADAppliedTags`, `SimpleCADTagBindings`, and -`SimpleCADTagNodeIds`. -The Tree View exposes only resolved product or standalone-geometry roots. -Assembly projection compounds and link source definitions remain available -for recomputation but are hidden from the user-facing document tree. diff --git a/docs/api/translate_model_json_to_fusion360_script.md b/docs/api/translate_model_json_to_fusion360_script.md deleted file mode 100644 index 05156ad7..00000000 --- a/docs/api/translate_model_json_to_fusion360_script.md +++ /dev/null @@ -1,17 +0,0 @@ -# translate_model_json_to_fusion360_script - -## API Definition - -```python -def translate_model_json_to_fusion360_script(json_str: str, document_name: str = 'SimpleCADModel', result_node_ids: Optional[Sequence[str]] = None, *, selection_mode: str = 'gsm', source_kernel_fallback: bool = False) -> str -``` - -*Source: translator/fusion360_translator/api.py* - -## Import Surface - -- translator backend: `from simplecadapi.translator.fusion360_translator import translate_model_json_to_fusion360_script` - -## Description - -Translate canonical model JSON into a Fusion 360 Python script. diff --git a/docs/api/translate_model_json_to_solidworks_script.md b/docs/api/translate_model_json_to_solidworks_script.md deleted file mode 100644 index c1a58832..00000000 --- a/docs/api/translate_model_json_to_solidworks_script.md +++ /dev/null @@ -1,17 +0,0 @@ -# translate_model_json_to_solidworks_script - -## API Definition - -```python -def translate_model_json_to_solidworks_script(json_str: str, document_name: str = 'SimpleCADModel', *, output_path: Optional[str] = None, visible: bool = False, source_kernel_fallback: bool = False) -> str -``` - -*Source: translator/solidworks_translator/api.py* - -## Import Surface - -- translator backend: `from simplecadapi.translator.solidworks_translator import translate_model_json_to_solidworks_script` - -## Description - -Translate canonical model JSON into a SolidWorks automation script. diff --git a/docs/api/translate_product_package_to_fcstd.md b/docs/api/translate_product_package_to_fcstd.md new file mode 100644 index 00000000..7dc48cf1 --- /dev/null +++ b/docs/api/translate_product_package_to_fcstd.md @@ -0,0 +1,17 @@ +# translate_product_package_to_fcstd + +## API Definition + +```python +def translate_product_package_to_fcstd(data: ProductPackageInput, output_path: str, *, document_name: str = 'SimpleCADProduct', freecad_cmd: Optional[str] = None) -> str +``` + +*Source: translator/freecad_translator/api.py* + +## Import Surface + +- translator backend: `from simplecadapi.translator.freecad_translator import translate_product_package_to_fcstd` + +## Description + +Translate one validated `.scadpkg` closure into an editable `.FCStd`. diff --git a/docs/api/translate_product_package_to_freecad_script.md b/docs/api/translate_product_package_to_freecad_script.md new file mode 100644 index 00000000..b4c82c63 --- /dev/null +++ b/docs/api/translate_product_package_to_freecad_script.md @@ -0,0 +1,17 @@ +# translate_product_package_to_freecad_script + +## API Definition + +```python +def translate_product_package_to_freecad_script(data: ProductPackageInput, document_name: str = 'SimpleCADProduct') -> str +``` + +*Source: translator/freecad_translator/api.py* + +## Import Surface + +- translator backend: `from simplecadapi.translator.freecad_translator import translate_product_package_to_freecad_script` + +## Description + +Translate one validated `.scadpkg` closure into a FreeCAD script. diff --git a/docs/api/translate_product_package_to_fusion360_script.md b/docs/api/translate_product_package_to_fusion360_script.md new file mode 100644 index 00000000..5ed70116 --- /dev/null +++ b/docs/api/translate_product_package_to_fusion360_script.md @@ -0,0 +1,17 @@ +# translate_product_package_to_fusion360_script + +## API Definition + +```python +def translate_product_package_to_fusion360_script(data: ProductPackageInput, document_name: str = 'SimpleCADProduct', *, selection_mode: str = 'gsm', source_kernel_fallback: bool = False) -> str +``` + +*Source: translator/fusion360_translator/api.py* + +## Import Surface + +- translator backend: `from simplecadapi.translator.fusion360_translator import translate_product_package_to_fusion360_script` + +## Description + +Translate one validated `.scadpkg` closure into a Fusion 360 script. diff --git a/docs/api/translate_product_package_to_solidworks_script.md b/docs/api/translate_product_package_to_solidworks_script.md new file mode 100644 index 00000000..7d6f3736 --- /dev/null +++ b/docs/api/translate_product_package_to_solidworks_script.md @@ -0,0 +1,17 @@ +# translate_product_package_to_solidworks_script + +## API Definition + +```python +def translate_product_package_to_solidworks_script(data: ProductPackageInput, document_name: str = 'SimpleCADProduct', *, output_path: str | None = None, visible: bool = False, source_kernel_fallback: bool = False) -> str +``` + +*Source: translator/solidworks_translator/api.py* + +## Import Surface + +- translator backend: `from simplecadapi.translator.solidworks_translator import translate_product_package_to_solidworks_script` + +## Description + +Translate one validated `.scadpkg` closure into SolidWorks automation. diff --git a/docs/architecture/sdk-architecture-review.md b/docs/architecture/sdk-architecture-review.md index 01dbc851..c6dbb636 100644 --- a/docs/architecture/sdk-architecture-review.md +++ b/docs/architecture/sdk-architecture-review.md @@ -51,15 +51,15 @@ SimpleCADAPI 的顶层 API 选择是正确的:它没有把用户拖进传统 C - `GraphSession` + `export_model_json` + `replay_model_json` 的主线是对的。它把脚本建模提升为可交换、可 replay 的模型记录。参考:`src/simplecadapi/graph.py:44`、`src/simplecadapi/serializer.py:416`、`src/simplecadapi/serializer.py:732`。 - `ql` 被放到子模块而非全部塞进顶层,是正确的边界意识。参考:`src/simplecadapi/__init__.py`、`docs/api/README.md:5`。 -问题: +当前问题与已完成清理: -- 顶层 API 被 aliases 稀释了。`create_box`、`create_line`、`extrude`、`union`、`to_step` 等别名降低了 canonical API 的唯一性。对用户友好,但对文档、LLM、图记录和长期兼容不友好。参考:`src/simplecadapi/__init__.py:145`、`src/simplecadapi/__init__.py:318`。 -- README 说 API 函数统一用 return type 反映命名,但公开面包含 `translate_shape`、`rotate_shape`、`export_step`、`export_stl` 和大量 aliases。这个声明过强。参考:`README.md:200`、`src/simplecadapi/__init__.py:47`、`src/simplecadapi/__init__.py:187`。 -- `rsolidlist` 命名混杂了“参数类型”和“返回类型”:`cut_rsolid`、`intersect_rsolid` 实际返回 `Solid`,而 `linear_pattern_rsolidlist` 返回 `List[Solid]`。这会伤害 API 语义一致性。参考:`src/simplecadapi/operations.py:2994`、`src/simplecadapi/operations.py:3102`、`src/simplecadapi/operations.py:4121`。 -- public op 名和 graph op 名不完全一致:`translate_shape` 记录为 `make_translate_rshape`,`extrude_rsolid` 记录为 `make_extrude_rsolid`。这种分层可以接受,但必须正式化为“source API”和“canonical IR”的稳定映射表。参考:`src/simplecadapi/operations.py:117`、`src/simplecadapi/serializer.py:116`。 -- 一些非 session 分支仍记录 legacy op 名,如 `make_box`、`make_cylinder`、`make_segment_wire`,和 canonical `make_*_r*` 命名不一致。参考:`src/simplecadapi/operations.py:785`、`src/simplecadapi/operations.py:1534`、`src/simplecadapi/operations.py:1638`。 +- 已完成:顶层 convenience aliases 以及 `export_step`、`export_stl`、`to_step`、`to_stl` 已从公开面移除,不保留兼容转发。 +- 已完成:持久产品只通过 `capture(result, path)` 写出 `.scadpkg`;STEP、STL 和原生 CAD 输出从该产品包显式派生。 +- 仍需关注:`rsolidlist` 命名混杂了“参数类型”和“返回类型”:`cut_rsolid`、`intersect_rsolid` 实际返回 `Solid`,而 `linear_pattern_rsolidlist` 返回 `List[Solid]`。 +- 仍需关注:public op 名和 graph op 名不完全一致,例如 `translate_shape` 记录为 `make_translate_rshape`,`extrude_rsolid` 记录为 `make_extrude_rsolid`;这种分层需要稳定的 source API 到 canonical IR 映射。 +- 仍需关注:部分非 session 分支记录的 graph op 命名与 canonical `make_*_r*` 形式不一致,需要继续收敛。 -建议:保留 `make_*_r*`,但把 aliases 降级为 compatibility surface,不作为文档主路径;把 source API 到 canonical graph op 的映射写成稳定规范;把 `rsolidlist` 这种历史命名列入 3.0 前清理清单。 +后续重点是稳定 source API 到 canonical graph op 的映射,并在下一次不兼容版本中清理剩余历史命名。 ## 函数式架构评价 diff --git a/docs/architecture/translator-backend-contract.md b/docs/architecture/translator-backend-contract.md index f8876797..da75ba3a 100644 --- a/docs/architecture/translator-backend-contract.md +++ b/docs/architecture/translator-backend-contract.md @@ -52,19 +52,21 @@ SimpleCAD package is imported, and must be assembled in one declared order. ## Translation And Export -Translation is an in-memory operation. It consumes canonical model JSON or an -already imported canonical payload and returns a `TranslationArtifact`. +Translation is an in-memory operation over a validated product-package closure. +It consumes `ProductPackageInput` and returns a `TranslationArtifact` containing +the target script or native artifact description. Export is an effectful operation. It may write files, invoke an executable, or -call a remote API. Those effects belong in `exporter.py`, not in the translator -or emitters. +call a remote API. Neutral product file effects belong in `simplecadapi.exporter`; +backend-specific executable effects belong in the backend exporter module. Public naming follows these forms: -- `translate_model_json_to_` for in-memory conversion. -- `export_model_json_to_` for file or external-runtime output. +- `translate_product_package_to_` for in-memory product translation. +- `export_product_package_to_` for neutral product file output. -Existing public names may remain as compatibility aliases. +Standalone model JSON translation and export entrances are removed. Model JSON +remains a graph replay and inspection format, not a downstream CAD contract. ## Dependencies diff --git a/docs/core/README.md b/docs/core/README.md index 90973c49..76383d1a 100644 --- a/docs/core/README.md +++ b/docs/core/README.md @@ -66,7 +66,7 @@ SimpleWorkplane ← local modeling context - **Shape-first API**: users work with `Vertex`, `Edge`, `Wire`, `Face`, `Shell`, and `Solid`, not graph nodes. - **Functional modeling style**: public operations return new geometry values, e.g. `make_box_rsolid(...)`, `cut_rsolid(...)`, `fillet_rsolid(...)`. - **OCP-native runtime**: geometry construction, topology traversal, properties, booleans, transforms, and export use OCP/OpenCascade helpers. -- **Replayable graph workflows**: `@scad.model` owns one `GraphSession` and returns a `ModelResult`; `@scad.requires_session` composes child builders, and `scad.capture_result()` selects canonical output nodes for replay and export. +- **Replayable graph workflows**: an explicit `GraphSession` records operations, `session.capture_result()` selects canonical output nodes, and `export_model_json()` plus `replay_model_json()` provide interchange and replay. - **Tags and metadata**: tags are useful for lightweight semantics; structured numeric facts should be stored in metadata such as `metadata["geo"]`. - **Indexed topology access**: use plural methods such as `get_edges()` and `get_faces()` for enumeration, and pass an index to the same getter, such as `get_edges(index)` or `get_faces(index)`, for intentional indexed picks that should become graph selection nodes. @@ -93,19 +93,18 @@ print(len(top_faces)) ```python import simplecadapi as scad +from simplecadapi import GraphSession, export_model_json, replay_model_json -@scad.model(graph_id="drilled_block") -def build_model(): +with GraphSession(graph_id="drilled_block") as session: body = scad.make_box_rsolid(width=10, height=10, depth=4) hole = scad.make_cylinder_rsolid( radius=1.5, height=8, bottom_face_center=(0, 0, -2) ) part = scad.cut_rsolid(body, hole) - scad.capture_result(value=part) - return part + session.capture_result(value=part) + payload = export_model_json(session=session) -result = build_model() -rebuilt = result.replay() +rebuilt = replay_model_json(json_str=payload) print(len(rebuilt)) ``` diff --git a/docs/core/declarative_constraints.md b/docs/core/declarative_constraints.md index b41dd979..cec8dd52 100644 --- a/docs/core/declarative_constraints.md +++ b/docs/core/declarative_constraints.md @@ -68,10 +68,10 @@ Removed public APIs include: - `stack_rassembly` - `stack` -Current supported workflows should model final parts as ordinary geometry: +Current supported workflows should model durable products through explicit boundaries: -- Use `translate_shape(...)`, `rotate_shape(...)`, and `mirror_shape(...)` for explicit placement. -- Use Python sequences of `Solid` objects plus `export_step([...], path)` / `export_stl(...)` for multi-body exports. +- Use `@scad.part` for one physical solid and `@scad.assemble` for a multi-part product. +- Use `scad.capture(result, path)` as the only public `.scadpkg` write boundary. - Use `union_rsolid(...)`, `cut_rsolid(...)`, and `intersect_rsolid(...)` when a single merged solid is required. `export_model_json(...)` no longer accepts `assembly=...`, and newly exported model JSON does not include `assembly`, `assembly_registry`, or `constraint_registry` fields. diff --git a/docs/core/part_assembly_development_plan.md b/docs/core/part_assembly_development_plan.md index ee2b0c82..57fabbd9 100644 --- a/docs/core/part_assembly_development_plan.md +++ b/docs/core/part_assembly_development_plan.md @@ -371,8 +371,8 @@ projection: - The outer sleeve is one single-body `Part` with a barrel, gland flange, bolt-hole details, rear eye, and pin hole. - The inner piston rod is another single-body `Part` with piston lands, a seal groove, chrome rod, rod-eye neck, and rod-eye pin hole. - The final `Assembly` instantiates both parts with component placement. -- `make_compound_from_assembly_rcompound(...)` produces the flattened preview/STEP projection. -- `translate_model_json_to_fcstd(...)` writes a native FreeCAD Assembly Workbench document where the assembly tree remains visible and editable. +- `make_compound_from_assembly_rcompound(...)` produces the flattened preview projection; `scad.exporter.export_product_package_to_step(...)` writes the package STEP projection. +- `scad.translator.freecad_translator.translate_product_package_to_fcstd(...)` writes a native FreeCAD Assembly Workbench document where the assembly tree remains visible and editable. Run it from the source checkout: diff --git a/docs/core/serialization/README.md b/docs/core/serialization/README.md index a1a5bac6..ce3b5a6e 100644 --- a/docs/core/serialization/README.md +++ b/docs/core/serialization/README.md @@ -9,20 +9,19 @@ The long-form schema reference remains [`../operation_graph_json_spec.md`](../op ```python import json import simplecadapi as scad +from simplecadapi import GraphSession, export_model_json, replay_model_json -@scad.model(graph_id="drilled_block") -def build_model(): +with GraphSession(graph_id="drilled_block") as session: body = scad.make_box_rsolid(width=10, height=6, depth=2) hole = scad.make_cylinder_rsolid( radius=1, height=4, bottom_face_center=(0, 0, -1) ) result = scad.cut_rsolid(body, hole) - scad.capture_result(value=result) - return result + session.capture_result(value=result) + model_json = export_model_json(session=session) -model = build_model() -payload = json.loads(model.model_json) -rebuilt = model.replay() +payload = json.loads(model_json) +rebuilt = replay_model_json(json_str=model_json) ``` Inspect these fields: @@ -36,15 +35,12 @@ Inspect these fields: - `payload["expression_graph"]`: expression DAG used by expression-backed parameters. - `payload["tolerance_graph"]`: dimension-chain requirements and validation evidence. -For new top-level models, `ModelResult.model_json` is the preferred artifact -accessor. Use `@scad.requires_session` for reusable builders and -`scad.capture_result(...)` when the final output should not be inferred from -all graph leaves. If a model invocation also needs durable CAD/viewer files, -pass `export_dir=...` to `@scad.model`; its captured geometry/product values -then produce one self-contained `.scene.zip`. It embeds -`model/model.json`, mapped project-relative Python sources, and the evaluated -render/selection assets. It does not create adjacent model/session JSON, STEP, -STL, or FCStd files. No files are written when `export_dir` is omitted. +Use `session.capture_result(...)` when the final output should not be inferred +from all graph leaves, and treat `export_model_json(session=...)` as the +interchange boundary for direct graph workflows. Durable CAD/viewer products use +`@scad.part` or `@scad.assemble`, then `scad.capture(result, "out/product.scadpkg")` +to build and write one canonical self-contained package. No files are written +unless an export API is called. ## Important rule: source API is not always graph API diff --git a/docs/guides/README.md b/docs/guides/README.md index 4097f20c..f4dcb297 100644 --- a/docs/guides/README.md +++ b/docs/guides/README.md @@ -5,7 +5,8 @@ reusable prompt for controlled, comparable STEP reconstruction trials. - [Persistent Cache and Product Build Workflow](cache-build-workflow.md): durable `@part`/`@assemble` boundaries, PRT reuse, unified cache policy, - incremental invalidation, diagnostics, repair, and maintenance. + diagnostics, `.scadpkg` delivery, FreeCAD/AP242 targets, and optional Gmsh + volume meshing. The corresponding runnable module and examples live in: diff --git a/docs/guides/cache-build-workflow.md b/docs/guides/cache-build-workflow.md index 1a5abb5f..50023c37 100644 --- a/docs/guides/cache-build-workflow.md +++ b/docs/guides/cache-build-workflow.md @@ -61,10 +61,10 @@ fixture = build_fixture() print(fixture.solve_report.component_hits, fixture.solve_report.component_misses) ``` -`@scad.part` and `@scad.assemble` are top-level product boundaries and cannot be -nested inside an active `GraphSession`. Continue to use `@scad.model` plus -`@scad.requires_session` for a replayable geometry flow that is not a durable -part/assembly definition. +`@scad.part` and `@scad.assemble` are top-level product boundaries and each owns +its definition-local `GraphSession`; they cannot be nested inside another active +session. Use an explicit `GraphSession` for lower-level replayable geometry that +is not a durable part or assembly definition. ## Policy @@ -121,23 +121,68 @@ format. ## Product package export -`PartBuildResult` and `AssemblyBuildResult` export one public product format: -the canonical self-contained `.scadpkg` archive. It contains a thin -`package.json` manifest plus the complete content-addressed closure of canonical -`PartDefinition` and `AssemblyDefinition` archives. Repeated definitions are -stored once; assembly instances and relations remain in the ASM definitions. +`PartBuildResult` and `AssemblyBuildResult` are captured and written as one +canonical product package by a single API call: ```python -part_package = warm.export_artifacts(output_dir="out") -assembly_package = fixture.export_artifacts(output_dir="out") +scad.capture(warm, "out/part.scadpkg") +scad.capture(fixture, "out/assembly.scadpkg") -root = scad.load_product_package(assembly_package.artifact_paths["product"]) +root = scad.load_product_package("out/assembly.scadpkg") rebuilt = scad.materialize_definition(root) ``` -Use `build_product_package(...)`, `export_product_package(...)`, -`read_product_package(...)`, and `load_product_package(...)` for explicit -package handling. `validate_product_package(...)` verifies every object hash and -size, the complete recursive definition graph, cycle/depth limits, and rejects -missing or unreferenced objects. Keep `export_definition(...)` only for low-level -definition exchange or inspection; it is not the product delivery format. +Use `build_product_package(...)`, `encode_product_package(...)`, +`read_product_package(...)`, and `load_product_package(...)` only for explicit +in-memory package handling. `validate_product_package(...)` verifies every object +hash and size, the complete recursive definition graph, cycle/depth limits, and +rejects missing or unreferenced objects. Use `export_part_definition(...)` or +`export_assembly_definition(...)` only for low-level definition exchange or +inspection; neither is the product delivery format. + +## Downstream CAD and mesh targets + +Keep `.scadpkg` as the canonical SimpleCAD delivery artifact. Choose a +downstream target from the consumer contract: + +| Target | Use when | Preserved contract | Boundary | +| --- | --- | --- | --- | +| `.scadpkg` | Rebuild, replay, cache, or further SimpleCAD editing is required | Complete durable definition closure, feature graphs, source snapshots, topology, connectors, constraints, and materials | SimpleCAD-specific archive | +| `.FCStd` | A FreeCAD user needs an editable native document | Definition-owned, dependency-first native feature graphs; final body links; repeated instances; nested assemblies; names; solved placements; materials; connectors; constraints; grounding; revision; and content hashes | Requires FreeCADCmd/FreeCAD | +| AP242 `.step` | Neutral CAD exchange or downstream OpenCASCADE tooling is required | Evaluated BREP, product hierarchy, shared definitions, occurrence names/placements, materials, colors, density, and named SimpleCAD property payloads | Canonical feature history is not reconstructed as AP242 features | + +```python +package_path = assembly_package.artifact_paths["product"] + +fcstd_path = scad.translator.freecad_translator.translate_product_package_to_fcstd( + package_path, + "out/product.FCStd", +) +step_report = scad.exporter.export_product_package_to_step( + package_path, + "out/product.step", +) +stl_report = scad.exporter.export_product_package_to_stl( + package_path, + "out/product.stl", +) +print(step_report.definition_ids, step_report.occurrence_count) +print(stl_report.solid_count, stl_report.stl_triangle_count) +``` + +AP242 definition and occurrence metadata is stored in one standard +`PROPERTY_DEFINITION_REPRESENTATION`. Its named +`DESCRIPTIVE_REPRESENTATION_ITEM` records use +`SimpleCAD:definition::` and +`SimpleCAD:occurrence::`. Each description +is canonical sorted JSON containing durable IDs, revision, content hash, +connectors, constraints, grounding, name, and solved placement. +`ProductSTEPExportReport` reports the schema, definition IDs, occurrence +count, material IDs, metadata item count, and explicit limitations. + +For tetrahedral meshing, install `simplecadapi[gmsh]` and run +`examples/12_ap242_gmsh_volume_mesh.py`. The example exports one `.scadpkg`, +converts it to AP242 STEP, imports it with Gmsh's OpenCASCADE kernel, rejects +imports with no 3D volumes, generates a dimension-3 mesh, writes `.msh`, and +always finalizes Gmsh. Gmsh remains optional and is never imported by the core +SDK or the product exporters. diff --git a/docs/guides/reconstruction-agent-test-prompt.md b/docs/guides/reconstruction-agent-test-prompt.md index 205b5c31..8d2ce995 100644 --- a/docs/guides/reconstruction-agent-test-prompt.md +++ b/docs/guides/reconstruction-agent-test-prompt.md @@ -294,7 +294,7 @@ The program must: - run in a fresh process; - export `{CASE_NAME}_rebuilt.step` under `OUTPUT_DIR`; - produce a valid BREP; -- use `@scad.model` and strict replay when supported; +- record supported feature operations in an explicit `GraphSession` and verify strict replay; - clearly label exact transcription, fitting, and approximation. Prefer compact design intent over arbitrary point clouds. Do not describe a diff --git a/docs/guides/step-brep-reverse-engineering.md b/docs/guides/step-brep-reverse-engineering.md index a21c76cf..ca3ccbab 100644 --- a/docs/guides/step-brep-reverse-engineering.md +++ b/docs/guides/step-brep-reverse-engineering.md @@ -10,8 +10,8 @@ src/simplecadapi/inspect/brep/ All of these functions are diagnostic, tool-grade APIs, not modeling operations: they do not record graph nodes and must not run inside a -`GraphSession` or `@model` modeling script. Export or obtain the geometry -under test first, then call them outside the modeling script: +`GraphSession`. Export or obtain the geometry under test first, then call them +outside the modeling script: ```python from simplecadapi.inspect import brep diff --git a/docs/updates/2.0.4b3.md b/docs/updates/2.0.4b3.md index c64931eb..bff8c48e 100644 --- a/docs/updates/2.0.4b3.md +++ b/docs/updates/2.0.4b3.md @@ -67,7 +67,25 @@ Inspection and default prune are read-only. Explicit `--repair`, `--apply`, or object presence, byte length, and SHA-256. Namespace clearing preserves objects still referenced elsewhere. -## 6. Native render crash isolation +## 6. Product-package CAD translation + +Validated `.scadpkg` definition closures now translate to one editable FreeCAD +document or one XCAF-backed AP242 STEP file. FreeCAD output uses a +dependency-first definition registry so repeated parts, nested assemblies, +occurrence names, solved placements, materials, connectors, constraints, +grounding, revision, and content hashes survive in native document structure. + +AP242 output uses `AP242_MANAGED_MODEL_BASED_3D_ENGINEERING`, preserves evaluated +BREP and product occurrences, and writes materials, colors, density, plus named +definition/occurrence properties. The property descriptions contain canonical +sorted JSON for durable IDs and semantics. Feature history is not reconstructed +as AP242 features; `.scadpkg` remains the canonical replayable artifact. + +The optional `gmsh` extra and `examples/12_ap242_gmsh_volume_mesh.py` demonstrate +`.scadpkg -> AP242 STEP -> tetrahedral .msh` without adding Gmsh to the core +runtime dependency set. + +## 7. Native render crash isolation On macOS, VTK 9.5's Cocoa offscreen backend can terminate the interpreter with `SIGSEGV` after repeated or concurrent render-window use. Inspection and SDK @@ -76,7 +94,7 @@ workers guarded by a cross-process lock. Completion markers distinguish a finished image from a partial native crash; incomplete workers retry, while a post-write teardown crash cannot terminate the modeling or test process. -## 7. Verification +## 8. Verification Regression coverage exercises artifact schema closure, deterministic IDs and @@ -84,15 +102,19 @@ hashes, atomic concurrent write deduplication, corruption quarantine, all cache modes, in-process same-key PRT reuse, concurrent PRT build deduplication, cross-wrapper persistent part restore, interface invalidation, assembly definition DAGs, incremental dependency propagation, residual verification, -and nested connector changes. +nested connector changes, translator backend contracts, and generated API docs. -The representative external-reference gear-train smoke builds two cached parts, -solves repeated and nested assembly instances, exports an independent assembly -definition archive, reloads it, materializes it, and verifies nested constraint -residuals. +The nested package smoke writes and reads a native FreeCAD hierarchy with shared +definitions and solved placements. AP242 round-trip checks the managed-model +schema, five-level product explorer records, material and color data, plus seven +named metadata property items for three definitions and four occurrences. The +Gmsh smoke imports AP242 as one 3D volume and generates a non-empty tetrahedral +mesh. ## Related documentation - [Persistent cache and product build workflow](../guides/cache-build-workflow.md) +- [Product package STEP/STL export APIs](../api/export_product_package_to_step.md) +- [Editable FreeCAD product package API](../api/translate_product_package_to_fcstd.md) - [Modeling workflows](../../skills/simplecadapi/references/MODELING_WORKFLOWS.md) - [Previous 2.0.4b2 update notes](2.0.4b2.md) diff --git a/examples/.gitignore b/examples/.gitignore index 903717e1..43faf7b6 100644 --- a/examples/.gitignore +++ b/examples/.gitignore @@ -6,6 +6,6 @@ out/ *.FCBak *.fcstd *.fcbak -*.scene.zip +*.scadpkg *.zip *.log diff --git a/examples/04_dimension_tolerance_chain.py b/examples/04_dimension_tolerance_chain.py index dbb3b0fa..8cf1a48a 100644 --- a/examples/04_dimension_tolerance_chain.py +++ b/examples/04_dimension_tolerance_chain.py @@ -10,11 +10,19 @@ from pathlib import Path import simplecadapi as scad -OUT = Path("examples/out") +OUT = Path(__file__).resolve().parent / "out" / "dimension_tolerance_chain" +PACKAGE_PATH = OUT / "dimension_tolerance_chain.scadpkg" +STEP_PATH = OUT / "dimension_tolerance_chain.step" +FCSTD_PATH = OUT / "dimension_tolerance_chain.FCStd" -@scad.model(graph_id="dimension_tolerance_chain") -def build_model(): +@scad.part( + id="dimension_tolerance_chain", + revision="1.0.0", + cache="off", + project_root=Path(__file__).resolve().parents[1], +) +def build_dimension_tolerance_chain_part() -> scad.Part: housing_span = scad.var( name="housing_span", default=100.0, @@ -38,13 +46,8 @@ def build_model(): comment="Spacer width", ) axial_clearance = housing_span - bearing_width - spacer_width - - worst_case = scad.analyze_tolerance( - value=axial_clearance, - method="worst_case", - ) - rss = scad.analyze_tolerance(value=axial_clearance, method="rss") - + scad.analyze_tolerance(value=axial_clearance, method="worst_case") + scad.analyze_tolerance(value=axial_clearance, method="rss") housing = scad.make_box_rsolid( width=housing_span, height=10.0, @@ -54,7 +57,7 @@ def build_model(): ) session = scad.get_active_session() if session is None: - raise RuntimeError("dimension tolerance model has no active session") + raise RuntimeError("dimension tolerance builder requires an active session") session.require_tolerance( value=axial_clearance, tolerance=(-0.25, 0.24), @@ -62,28 +65,60 @@ def build_model(): method="worst_case", name="axial_clearance", ) - report = session.validate_tolerances(raise_on_failure=True) - scad.capture_result(value=housing) - return { - "housing": housing, + session.validate_tolerances(raise_on_failure=True) + return scad.make_part_rpart( + part_id="dimension_tolerance_chain", + body=housing, + name="Dimension tolerance chain housing", + ) + + +def build_model(): + result = build_dimension_tolerance_chain_part() + session = result.feature_graph.restore_session() + requirement = session.tolerance_graph.requirements[0] + expression = session.expression_graph.get(requirement.target_expr_id) + if expression is None: + raise RuntimeError("tolerance target expression was not restored") + worst_case = scad.analyze_tolerance(value=expression, method="worst_case") + rss = scad.analyze_tolerance(value=expression, method="rss") + data = { + "housing": result.part, "worst_case": worst_case, "rss": rss, - "report": report, + "report": session.validate_tolerances(raise_on_failure=True), } + return ( + data, + scad.export_model_json(session), + scad.export_session_json(session), + result, + ) def main() -> None: OUT.mkdir(parents=True, exist_ok=True) - result = build_model() - report_data = result.value + report_data, model_json, session_json, result = build_model() (OUT / "dimension_tolerance_chain.model.json").write_text( - result.model_json, + model_json, encoding="utf-8", ) + (OUT / "dimension_tolerance_chain.session.json").write_text( + session_json, + encoding="utf-8", + ) + package_path = OUT / "dimension_tolerance_chain.scadpkg" + scad.capture(result, package_path) + step_report = scad.exporter.export_product_package_to_step(package_path, STEP_PATH) + scad.translator.freecad_translator.translate_product_package_to_fcstd( + package_path, + str(FCSTD_PATH), + document_name="DimensionToleranceChain", + ) worst_case = report_data["worst_case"] rss = report_data["rss"] - print("housing_volume", round(report_data["housing"].get_volume(), 3)) + print("housing_volume", round(report_data["housing"].body.get_volume(), 3)) print( "worst_case", round(worst_case.nominal, 3), @@ -98,10 +133,10 @@ def main() -> None: round(rss.upper_bound, 3), ) print("requirements_passed", report_data["report"].passed) - print( - "serialized_tolerance_graph", - "tolerance_graph" in json.loads(result.model_json), - ) + print("serialized_tolerance_graph", "tolerance_graph" in json.loads(model_json)) + print("product_package", package_path) + print("ap242_step", step_report.output_path) + print("fcstd", FCSTD_PATH) if __name__ == "__main__": diff --git a/examples/08_constrained_sketch.py b/examples/08_constrained_sketch.py index 074db04a..d8e1298f 100644 --- a/examples/08_constrained_sketch.py +++ b/examples/08_constrained_sketch.py @@ -6,7 +6,7 @@ Run from the repository root with: Generated files: examples/out/constrained_sketch.model.json examples/out/constrained_sketch.step - examples/out/constrained_sketch.fcstd + examples/out/constrained_sketch.FCStd When the intent is a sketch/profile, use the sketch APIs. Concrete geometry APIs remain for paths, pure geometry, and lowering targets. @@ -20,11 +20,11 @@ from pathlib import Path import simplecadapi as scad -OUT = Path("examples/out") +OUT = Path(__file__).resolve().parent / "out" / "constrained_sketch" MODEL_JSON_PATH = OUT / "constrained_sketch.model.json" +SESSION_JSON_PATH = OUT / "constrained_sketch.session.json" STEP_PATH = OUT / "constrained_sketch.step" -FCSTD_PATH = OUT / "constrained_sketch.fcstd" -FREECAD_CMD = Path("/Applications/FreeCAD.app/Contents/Resources/bin/freecadcmd") +FCSTD_PATH = OUT / "constrained_sketch.FCStd" def _solve_and_report(name: str, sketch: scad.Sketch) -> None: @@ -53,7 +53,6 @@ def _solve_and_report(name: str, sketch: scad.Sketch) -> None: ) -@scad.requires_session def _promote_face(name: str, sketch: scad.Sketch): _solve_and_report(name=name, sketch=sketch) return scad.make_face_from_sketch_rface( @@ -62,7 +61,6 @@ def _promote_face(name: str, sketch: scad.Sketch): ) -@scad.requires_session def make_rect_profile(name, x0, y0, width, height): sketch = scad.make_sketch_rsketch(name=name, plane="XY") @@ -154,7 +152,6 @@ def make_rect_profile(name, x0, y0, width, height): return _promote_face(name=name, sketch=sketch) -@scad.requires_session def make_circle_profile(name, center_x, center_y, radius, circle_id): sketch = scad.make_sketch_rsketch(name=name, plane="XY") sketch = scad.add_point_rsketch( @@ -178,7 +175,6 @@ def make_circle_profile(name, center_x, center_y, radius, circle_id): return _promote_face(name=name, sketch=sketch) -@scad.requires_session def make_guided_diamond_profile(name, center_x, center_y, width, height, guide_gap): half_w = width / 2.0 half_h = height / 2.0 @@ -263,7 +259,6 @@ def make_guided_diamond_profile(name, center_x, center_y, width, height, guide_g return _promote_face(name=name, sketch=sketch) -@scad.requires_session def make_curve_guided_relief_profile(name, center_x, center_y, radius, guide_span): sketch = scad.make_sketch_rsketch(name=name, plane="XY") @@ -374,8 +369,7 @@ def make_curve_guided_relief_profile(name, center_x, center_y, radius, guide_spa return _promote_face(name=name, sketch=sketch) -@scad.model(graph_id="constrained_sketch") -def build_model(): +def _build_model_body(): plate_w = scad.var(name="plate_w", default=96.0, comment="plate width") plate_h = scad.var(name="plate_h", default=54.0, comment="plate height") plate_t = scad.var(name="plate_t", default=6.0, comment="plate thickness") @@ -604,7 +598,6 @@ def build_model(): shape=part, tag="demo.constrained_sketch_bracket", ) - scad.capture_result(value=part) return { "part": part, "plate_profile": plate_profile, @@ -613,73 +606,81 @@ def build_model(): } -def main() -> None: - OUT.mkdir(parents=True, exist_ok=True) - result = build_model() - data = result.value - MODEL_JSON_PATH.write_text(result.model_json, encoding="utf-8") - - rebuilt = result.replay() - scad.export_step(shapes=rebuilt, filename=str(STEP_PATH)) - - freecad_cmd = str(FREECAD_CMD) if FREECAD_CMD.exists() else None - scad.translator.freecad_translator.translate_model_json_to_fcstd( - json_str=result.model_json, - output_path=str(FCSTD_PATH), - document_name="SimpleCADConstrainedSketchDemo", - freecad_cmd=freecad_cmd, +def _profile_entity_tags(profile: scad.Face) -> list[str]: + return sorted( + tag + for edge in scad.ql.select(items=profile.get_edges()) + .where(scad.ql.tag(pattern="sketch_entity.*")) + .all() + for tag in scad.list_tags(shape=edge) + if tag.startswith("sketch_entity.") ) - payload = json.loads(result.model_json) + +@scad.part( + id="constrained_sketch", + revision="1.0.0", + cache="off", + project_root=Path(__file__).resolve().parents[1], +) +def build_constrained_sketch_part() -> scad.Part: + data = _build_model_body() + part = scad.make_part_rpart( + part_id="constrained_sketch", + body=data["part"], + name="Constrained sketch bracket", + ) + part.set_metadata( + "example.profile_entity_tags", + { + "plate": _profile_entity_tags(data["plate_profile"]), + "diamond": _profile_entity_tags(data["diamond_profile"]), + "curve": _profile_entity_tags(data["curve_relief_profile"]), + }, + ) + return part + + +def build_model(): + result = build_constrained_sketch_part() + session = result.feature_graph.restore_session() + return result, scad.export_model_json(session), scad.export_session_json(session) + + +def main() -> None: + OUT.mkdir(parents=True, exist_ok=True) + result, model_json, session_json = build_model() + MODEL_JSON_PATH.write_text(model_json, encoding="utf-8") + SESSION_JSON_PATH.write_text(session_json, encoding="utf-8") + package_path = OUT / "constrained_sketch.scadpkg" + scad.capture(result, package_path) + step_report = scad.exporter.export_product_package_to_step(package_path, STEP_PATH) + scad.translator.freecad_translator.translate_product_package_to_fcstd( + package_path, + str(FCSTD_PATH), + document_name="SimpleCADConstrainedSketchDemo", + ) + + payload = json.loads(model_json) ops = [node["op"] for node in payload["graph"]["nodes"]] promotion_nodes = [ node for node in payload["graph"]["nodes"] - if node["op"] - in {"make_face_from_sketch_rface", "make_wire_from_sketch_rwire"} + if node["op"] in {"make_face_from_sketch_rface", "make_wire_from_sketch_rwire"} ] diamond_promotion = next( node for node in promotion_nodes if node["params"]["sketch"].get("name") == "guided_diamond_pocket" ) - diamond_constraints = diamond_promotion["params"]["sketch"].get( - "constraints", - [], - ) + diamond_constraints = diamond_promotion["params"]["sketch"].get("constraints", []) curve_promotion = next( node for node in promotion_nodes if node["params"]["sketch"].get("name") == "curve_guided_relief" ) - curve_constraints = curve_promotion["params"]["sketch"].get( - "constraints", - [], - ) - sketch_entity_tags = sorted( - tag - for edge in scad.ql.select(items=data["plate_profile"].get_edges()) - .where(scad.ql.tag(pattern="sketch_entity.*")) - .all() - for tag in scad.list_tags(shape=edge) - if tag.startswith("sketch_entity.") - ) - diamond_entity_tags = sorted( - tag - for edge in scad.ql.select(items=data["diamond_profile"].get_edges()) - .where(scad.ql.tag(pattern="sketch_entity.*")) - .all() - for tag in scad.list_tags(shape=edge) - if tag.startswith("sketch_entity.") - ) - curve_entity_tags = sorted( - tag - for edge in scad.ql.select(items=data["curve_relief_profile"].get_edges()) - .where(scad.ql.tag(pattern="sketch_entity.*")) - .all() - for tag in scad.list_tags(shape=edge) - if tag.startswith("sketch_entity.") - ) + curve_constraints = curve_promotion["params"]["sketch"].get("constraints", []) + entity_tags = result.part.get_metadata("example.profile_entity_tags") print("graph_nodes", len(ops)) print("sketch_ops", sum(1 for op in ops if "sketch" in op)) @@ -687,14 +688,12 @@ def main() -> None: print( "promotion_solve_snapshots", sum( - 1 - for node in promotion_nodes - if "solve_snapshot" in node.get("params", {}) + 1 for node in promotion_nodes if "solve_snapshot" in node.get("params", {}) ), ) print("contains_public_solve_node", "make_solve_sketch_rsketchresult" in ops) - print("plate_sketch_entity_tags", sketch_entity_tags) - print("diamond_sketch_entity_tags", diamond_entity_tags) + print("plate_sketch_entity_tags", entity_tags["plate"]) + print("diamond_sketch_entity_tags", entity_tags["diamond"]) print("diamond_constraint_count", len(diamond_constraints)) print( "diamond_parallel_equal_constraints", @@ -704,7 +703,7 @@ def main() -> None: if constraint.get("kind") in {"parallel", "equal_length"} ), ) - print("curve_sketch_entity_tags", curve_entity_tags) + print("curve_sketch_entity_tags", entity_tags["curve"]) print("curve_constraint_count", len(curve_constraints)) print( "curve_tangent_equal_radius_constraints", @@ -715,10 +714,12 @@ def main() -> None: in {"tangent", "equal_radius", "concentric", "point_on"} ), ) - print("volume", round(data["part"].get_volume(), 3)) + print("volume", round(result.part.body.get_volume(), 3)) print("wrote", MODEL_JSON_PATH) - print("wrote", STEP_PATH) + print("wrote", SESSION_JSON_PATH) + print("wrote", step_report.output_path) print("wrote", FCSTD_PATH) + print("product_package", package_path) if __name__ == "__main__": diff --git a/examples/09_naca0016_blade_freecad.py b/examples/09_naca0016_blade_freecad.py index 4336b75a..8dbd0081 100644 --- a/examples/09_naca0016_blade_freecad.py +++ b/examples/09_naca0016_blade_freecad.py @@ -7,7 +7,7 @@ Generated files: examples/out/naca0016_blade/naca0016_blade.model.json examples/out/naca0016_blade/naca0016_blade.session.json examples/out/naca0016_blade/naca0016_blade.step - examples/out/naca0016_blade/naca0016_blade.fcstd + examples/out/naca0016_blade/naca0016_blade.FCStd The NACA section generator starts from sampled airfoil points. The evolve helper fits those samples into exact cubic B-spline control data before calling @@ -25,11 +25,18 @@ import simplecadapi as scad DEFAULT_OUTPUT_DIR = Path("examples/out/naca0016_blade") -DEFAULT_FREECAD_CMD = Path("/Applications/FreeCAD.app/Contents/Resources/bin/freecadcmd") +DEFAULT_FREECAD_CMD = Path( + "/Applications/FreeCAD.app/Contents/Resources/bin/freecadcmd" +) -@scad.model(graph_id="naca0016_blade") -def build_blade() -> scad.ModelResult: +@scad.part( + id="naca0016_blade", + revision="1.0.0", + cache="off", + project_root=Path(__file__).resolve().parents[1], +) +def build_naca0016_blade_part() -> scad.Part: blade = scad.make_naca_propeller_blade_rsolid( blade_length=4.0, root_chord=1.25, @@ -39,8 +46,17 @@ def build_blade() -> scad.ModelResult: ) blade = scad.apply_tag(shape=blade, tag="role.naca0016.blade") blade = scad.apply_tag(shape=blade, tag="part.naca0016.blade") - scad.capture_result(value=blade) - return blade + return scad.make_part_rpart( + part_id="naca0016_blade", + body=blade, + name="NACA 0016 propeller blade", + ) + + +def build_blade() -> tuple[scad.PartBuildResult, str, str]: + result = build_naca0016_blade_part() + session = result.feature_graph.restore_session() + return result, scad.export_model_json(session), scad.export_session_json(session) def write_blade_artifacts( @@ -52,20 +68,26 @@ def write_blade_artifacts( model_json_path = output_dir / "naca0016_blade.model.json" session_json_path = output_dir / "naca0016_blade.session.json" step_path = output_dir / "naca0016_blade.step" - fcstd_path = output_dir / "naca0016_blade.fcstd" + fcstd_path = output_dir / "naca0016_blade.FCStd" - result = build_blade() - blade = result.value - payload = json.loads(result.model_json) - model_json_path.write_text(result.model_json, encoding="utf-8") - session_json_path.write_text(result.session_json, encoding="utf-8") - scad.export_step(shapes=blade, filename=str(step_path)) + result, model_json, session_json = build_blade() + payload = json.loads(model_json) + model_json_path.write_text(model_json, encoding="utf-8") + session_json_path.write_text(session_json, encoding="utf-8") bspline_nodes = [ - node for node in payload["graph"]["nodes"] if node.get("op") == "make_spline_redge" + node + for node in payload["graph"]["nodes"] + if node.get("op") == "make_spline_redge" + ] + loft_nodes = [ + node + for node in payload["graph"]["nodes"] + if node.get("op") == "make_loft_rsolid" + ] + control_counts = [ + len(node["params"].get("control_points", [])) for node in bspline_nodes ] - loft_nodes = [node for node in payload["graph"]["nodes"] if node.get("op") == "make_loft_rsolid"] - control_counts = [len(node["params"].get("control_points", [])) for node in bspline_nodes] knot_counts = [len(node["params"].get("knots", [])) for node in bspline_nodes] print("graph_nodes", len(payload["graph"]["nodes"])) @@ -74,21 +96,24 @@ def write_blade_artifacts( print("loft_nodes", len(loft_nodes)) print("bspline_control_counts", control_counts[:6]) print("bspline_knot_counts", knot_counts[:6]) - print("volume", round(blade.get_volume(), 6)) + package_path = output_dir / "naca0016_blade.scadpkg" + scad.capture(result, package_path) + step_report = scad.exporter.export_product_package_to_step(package_path, step_path) print("wrote", model_json_path) print("wrote", session_json_path) - print("wrote", step_path) - if freecad_cmd is not None and freecad_cmd.exists(): - scad.translator.freecad_translator.translate_model_json_to_fcstd( - json_str=result.model_json, - output_path=str(fcstd_path), - document_name="NACA0016Blade", - freecad_cmd=str(freecad_cmd), - ) - print("wrote", fcstd_path) - else: - print("skipped_fcstd", "FreeCADCmd not found") + resolved_freecad_cmd = ( + str(freecad_cmd) if freecad_cmd is not None and freecad_cmd.exists() else None + ) + scad.translator.freecad_translator.translate_product_package_to_fcstd( + package_path, + str(fcstd_path), + document_name="NACA0016Blade", + freecad_cmd=resolved_freecad_cmd, + ) + print("wrote", step_report.output_path) + print("wrote", fcstd_path) + print("product_package", package_path) return payload @@ -100,7 +125,7 @@ def main() -> None: "--freecad-cmd", type=Path, default=DEFAULT_FREECAD_CMD, - help="FreeCADCmd path used to write .fcstd; skipped if the path does not exist.", + help="Optional FreeCAD executable override; auto-discovered when unavailable.", ) args = parser.parse_args() write_blade_artifacts(args.output_dir, freecad_cmd=args.freecad_cmd) diff --git a/examples/10_part_assembly.py b/examples/10_part_assembly.py index ad3f27d8..cdfb637f 100644 --- a/examples/10_part_assembly.py +++ b/examples/10_part_assembly.py @@ -12,8 +12,7 @@ from simplecadapi import ql OUT_DIR = Path(__file__).resolve().parent / "out" / "hydraulic_rod_assembly" -@scad.model(graph_id="hydraulic_rod_assembly", export_dir=OUT_DIR) -def build_hydraulic_rod_assembly(): +def _build_hydraulic_rod_assembly_body(): flange_holes = [ ("zplus", 0.0, 16.0), ("yplus", 16.0, 0.0), @@ -21,7 +20,6 @@ def build_hydraulic_rod_assembly(): ("yminus", -16.0, 0.0), ] - @scad.requires_session def _build_in_session(): def _named_cylinder( *, @@ -403,73 +401,129 @@ def build_hydraulic_rod_assembly(): part=piston_rod_part, connector=rod_connector ) - hydraulic_assembly = scad.make_assembly_rassembly( - assembly_id="hydraulic_rod_assembly", name="Hydraulic rod assembly" - ) - hydraulic_assembly = scad.add_component_rassembly( - assembly=hydraulic_assembly, - item=sleeve_part, - component_id="outer_sleeve", - placement=scad.identity_placement_rplacement(), - ) - hydraulic_assembly = scad.add_component_rassembly( - assembly=hydraulic_assembly, - item=piston_rod_part, - component_id="inner_piston_rod", - placement=scad.identity_placement_rplacement(), - ) - hydraulic_assembly = scad.ground_component_rassembly( - assembly=hydraulic_assembly, component_id="outer_sleeve" - ) - hydraulic_assembly = scad.add_prismatic_constraint_rassembly( - assembly=hydraulic_assembly, - constraint_id="rod_slide", - connector_a=scad.make_connector_ref_rconnectorref( - component_id="outer_sleeve", connector_id="slide_axis" - ), - connector_b=scad.make_connector_ref_rconnectorref( - component_id="inner_piston_rod", connector_id="slide_axis" - ), - drive_distance=0.0, - distance_limit=scad.make_scalar_limit_rscalarlimit( - lower_value=0.0, upper_value=100.0 - ), - ) - hydraulic_assembly = scad.solve_assembly_constraints_rassembly( - assembly=hydraulic_assembly + return sleeve_part, piston_rod_part + + return _build_in_session() + + +def _assemble_hydraulic_rod(*, sleeve_part: scad.Part, piston_rod_part: scad.Part): + hydraulic_assembly = scad.make_assembly_rassembly( + assembly_id="hydraulic_rod_assembly", name="Hydraulic rod assembly" + ) + identity = scad.identity_placement_rplacement() + hydraulic_assembly = scad.add_component_rassembly( + assembly=hydraulic_assembly, + item=sleeve_part, + component_id="outer_sleeve", + placement=identity, + ) + hydraulic_assembly = scad.add_component_rassembly( + assembly=hydraulic_assembly, + item=piston_rod_part, + component_id="inner_piston_rod", + placement=identity, + ) + hydraulic_assembly = scad.ground_component_rassembly( + assembly=hydraulic_assembly, component_id="outer_sleeve" + ) + hydraulic_assembly = scad.add_prismatic_constraint_rassembly( + assembly=hydraulic_assembly, + constraint_id="rod_slide", + connector_a=scad.make_connector_ref_rconnectorref( + component_id="outer_sleeve", connector_id="slide_axis" + ), + connector_b=scad.make_connector_ref_rconnectorref( + component_id="inner_piston_rod", connector_id="slide_axis" + ), + drive_distance=0.0, + distance_limit=scad.make_scalar_limit_rscalarlimit( + lower_value=0.0, upper_value=100.0 + ), + ) + return scad.solve_assembly_constraints_rassembly(assembly=hydraulic_assembly) + + +@scad.part( + id="outer_sleeve", + revision="1.0.0", + cache="off", + project_root=Path(__file__).resolve().parents[1], +) +def build_outer_sleeve_part() -> scad.Part: + return _build_hydraulic_rod_assembly_body()[0] + + +@scad.part( + id="piston_rod", + revision="1.0.0", + cache="off", + project_root=Path(__file__).resolve().parents[1], +) +def build_piston_rod_part() -> scad.Part: + return _build_hydraulic_rod_assembly_body()[1] + + +def build_hydraulic_product() -> scad.AssemblyBuildResult: + sleeve_result = build_outer_sleeve_part() + rod_result = build_piston_rod_part() + + @scad.assemble( + id="hydraulic_rod_assembly", + revision="1.0.0", + definitions=(sleeve_result, rod_result), + cache="off", + project_root=Path(__file__).resolve().parents[1], + ) + def build_assembly() -> scad.Assembly: + return _assemble_hydraulic_rod( + sleeve_part=sleeve_result.part, + piston_rod_part=rod_result.part, ) - preview = scad.make_compound_from_assembly_rcompound( - assembly=hydraulic_assembly + return build_assembly() + + +def build_hydraulic_rod_assembly(): + session = scad.GraphSession(graph_id="hydraulic_rod_assembly") + with session: + sleeve_part, piston_rod_part = _build_hydraulic_rod_assembly_body() + assembly = _assemble_hydraulic_rod( + sleeve_part=sleeve_part, + piston_rod_part=piston_rod_part, ) + preview = scad.make_compound_from_assembly_rcompound(assembly=assembly) preview = scad.apply_tag( shape=preview, tag="assembly.hydraulic.preview", ) - return hydraulic_assembly, preview - - hydraulic_assembly, preview = _build_in_session() - scad.capture_result(value=(hydraulic_assembly, preview)) - return hydraulic_assembly, preview + session.capture_result(value=(assembly, preview)) + model_json = scad.export_model_json(session) + session_json = scad.export_session_json(session) + return assembly, preview, model_json, session_json def main() -> None: - OUT_DIR.mkdir(parents=True, exist_ok=True) - result = build_hydraulic_rod_assembly() - assembly, preview = result.value + product_result = build_hydraulic_product() + assembly = product_result.assembly + preview = scad.make_compound_from_assembly_rcompound(assembly=assembly) + package_path = OUT_DIR / "hydraulic_rod_assembly.scadpkg" + scad.capture(product_result, package_path) + _, _, model_json, session_json = build_hydraulic_rod_assembly() + model_path = OUT_DIR / "hydraulic_rod_assembly.model.json" + session_path = OUT_DIR / "hydraulic_rod_assembly.session.json" + model_path.write_text(model_json, encoding="utf-8") + session_path.write_text(session_json, encoding="utf-8") + step_path = OUT_DIR / "hydraulic_rod_assembly.step" fcstd_path = OUT_DIR / "hydraulic_rod_assembly.FCStd" - fcstd_status = "skipped" - try: - scad.translator.freecad_translator.translate_model_json_to_fcstd( - json_str=result.model_json, - output_path=str(fcstd_path.resolve()), - ) - fcstd_status = str(fcstd_path) - except Exception as exc: # pragma: no cover - depends on local FreeCAD install - fcstd_status = f"skipped ({exc.__class__.__name__})" + step_report = scad.exporter.export_product_package_to_step(package_path, step_path) + scad.translator.freecad_translator.translate_product_package_to_fcstd( + package_path, + str(fcstd_path.resolve()), + document_name="HydraulicRodAssembly", + ) - payload = json.loads(result.model_json) + payload = json.loads(model_json) face_count = len(ql.faces().resolve(preview)) print("assembly", assembly.assembly_id) print("components", assembly.component_ids()) @@ -477,9 +531,11 @@ def main() -> None: print("preview_faces", face_count) print("preview_volume", round(preview.get_volume(), 3)) print("graph_nodes", len(payload["graph"]["nodes"])) - for path in result.artifact_paths.values(): - print("wrote", path) - print("fcstd", fcstd_status) + print("wrote", model_path) + print("wrote", session_path) + print("step", step_report.output_path) + print("fcstd", fcstd_path) + print("product_package", package_path) if __name__ == "__main__": diff --git a/examples/11_external_reference_gear_train.py b/examples/11_external_reference_gear_train.py index 338643de..687a390a 100644 --- a/examples/11_external_reference_gear_train.py +++ b/examples/11_external_reference_gear_train.py @@ -146,10 +146,21 @@ def build_external_reference_gear_train() -> scad.AssemblyBuildResult: def main() -> None: OUT_DIR.mkdir(parents=True, exist_ok=True) result = build_external_reference_gear_train() - path = result.export_definition( - path=OUT_DIR / "nested_external_reference_gear_trains.assembly-definition.zip" + package_path = OUT_DIR / "nested_external_reference_gear_trains.scadpkg" + scad.capture(result, package_path) + step_path = OUT_DIR / "nested_external_reference_gear_trains.step" + fcstd_path = OUT_DIR / "nested_external_reference_gear_trains.FCStd" + step_report = scad.exporter.export_product_package_to_step(package_path, step_path) + scad.translator.freecad_translator.translate_product_package_to_fcstd( + package_path, + str(fcstd_path), + document_name="NestedExternalReferenceGearTrains", ) - loaded = scad.load_assembly_definition(path) + definition_path = scad.export_assembly_definition( + result.definition, + OUT_DIR / "nested_external_reference_gear_trains.assembly-definition.zip", + ) + loaded = scad.load_product_package(package_path) rebuilt = scad.materialize_definition(loaded) nested = rebuilt.get_component("train_left").item report = scad.inspect_assembly_constraints_rconstraintreport(nested) @@ -162,7 +173,10 @@ def main() -> None: f"definition_refs={len(loaded.definition_refs)} " f"content_hash={loaded.content_hash}" ) - print(f"artifact={path}") + print(f"definition_artifact={definition_path}") + print(f"product_package={package_path}") + print(f"step={step_report.output_path}") + print(f"fcstd={fcstd_path}") if __name__ == "__main__": diff --git a/examples/12_ap242_gmsh_volume_mesh.py b/examples/12_ap242_gmsh_volume_mesh.py new file mode 100644 index 00000000..9c0ed159 --- /dev/null +++ b/examples/12_ap242_gmsh_volume_mesh.py @@ -0,0 +1,169 @@ +"""Export one durable SimpleCAD part as FCStd, AP242 STEP, and Gmsh MSH.""" + +from __future__ import annotations +import argparse + +from dataclasses import dataclass +import importlib +from pathlib import Path +from typing import Any + +import simplecadapi as scad + + +OUT_DIR = Path(__file__).resolve().parent / "out" / "ap242_gmsh_volume_mesh" +CACHE = scad.CachePolicy(root=OUT_DIR / ".cache") + + +@dataclass(frozen=True, slots=True) +class GmshMeshReport: + step_path: Path + mesh_path: Path + volume_count: int + node_count: int + element_count: int + + +@scad.part( + id="ap242_gmsh_bracket", + revision="1.0.0", + inputs=(scad.file_input(path="examples/12_ap242_gmsh_volume_mesh.py"),), + cache=CACHE, +) +def build_bracket() -> scad.Part: + body = scad.make_box_rsolid( + width=40.0, + height=24.0, + depth=8.0, + bottom_face_center=(0.0, 0.0, 0.0), + ) + hole = scad.make_cylinder_rsolid( + radius=4.0, + height=12.0, + bottom_face_center=(-12.0, 0.0, -2.0), + ) + slot = scad.make_box_rsolid( + width=14.0, + height=6.0, + depth=12.0, + bottom_face_center=(10.0, 0.0, -2.0), + ) + body = scad.cut_rsolid(body, hole, slot) + part = scad.make_part_rpart( + part_id="ap242_gmsh_bracket", + body=body, + name="AP242 Gmsh bracket", + ) + material = scad.make_material_rmaterial( + material_id="aluminum_6061_t6", + name="Aluminum 6061-T6", + density=2.70e-6, + density_unit="kg/mm^3", + color=(0.72, 0.74, 0.78), + ) + return scad.assign_material_rpart(part, material) + + +def mesh_step_with_gmsh( + step_path: str | Path, + mesh_path: str | Path, + *, + mesh_size: float = 2.0, + gmsh_module: Any | None = None, +) -> GmshMeshReport: + """Import AP242 STEP with Gmsh's OCC kernel and write a 3D MSH mesh.""" + + if mesh_size <= 0.0: + raise ValueError("mesh_size must be positive") + source = Path(step_path).expanduser().resolve() + destination = Path(mesh_path).expanduser().resolve() + if not source.is_file(): + raise FileNotFoundError(source) + destination.parent.mkdir(parents=True, exist_ok=True) + gmsh = gmsh_module + if gmsh is None: + try: + gmsh = importlib.import_module("gmsh") + except ImportError as exc: + raise RuntimeError( + "Gmsh is optional; install it with `pip install simplecadapi[gmsh]`" + ) from exc + + initialized = False + try: + gmsh.initialize() + initialized = True + gmsh.model.add(source.stem) + gmsh.option.setString("Geometry.OCCTargetUnit", "MM") + imported = gmsh.model.occ.importShapes(str(source)) + gmsh.model.occ.synchronize() + volumes = gmsh.model.getEntities(3) + if not volumes: + raise RuntimeError( + f"Gmsh imported no 3D volumes from {source}; imported entities: {imported}" + ) + physical_group = gmsh.model.addPhysicalGroup( + 3, + [tag for _dimension, tag in volumes], + ) + gmsh.model.setPhysicalName(3, physical_group, source.stem) + gmsh.option.setNumber("Mesh.MeshSizeMin", float(mesh_size)) + gmsh.option.setNumber("Mesh.MeshSizeMax", float(mesh_size)) + gmsh.model.mesh.generate(3) + node_tags, _coordinates, _parameters = gmsh.model.mesh.getNodes() + _types, element_tags, _node_tags = gmsh.model.mesh.getElements(3) + element_count = sum(len(tags) for tags in element_tags) + if not len(node_tags) or not element_count: + raise RuntimeError("Gmsh generated an empty 3D mesh") + gmsh.write(str(destination)) + finally: + if initialized: + gmsh.finalize() + + if not destination.is_file() or destination.stat().st_size <= 0: + raise RuntimeError( + f"Gmsh did not create a non-empty mesh file at {destination}" + ) + return GmshMeshReport( + step_path=source, + mesh_path=destination, + volume_count=len(volumes), + node_count=len(node_tags), + element_count=element_count, + ) + + +def main(*, generate_mesh: bool = True) -> None: + result = build_bracket() + package_path = OUT_DIR / "ap242_gmsh_bracket.scadpkg" + scad.capture(result, package_path) + step_path = OUT_DIR / "ap242_gmsh_bracket.step" + mesh_path = OUT_DIR / "ap242_gmsh_bracket.msh" + fcstd_path = OUT_DIR / "ap242_gmsh_bracket.FCStd" + step_report = scad.exporter.export_product_package_to_step(package_path, step_path) + scad.translator.freecad_translator.translate_product_package_to_fcstd( + package_path, + str(fcstd_path), + document_name="AP242GmshBracket", + ) + mesh = mesh_step_with_gmsh(step_path, mesh_path) if generate_mesh else None + print("product_package", package_path) + print("ap242_step", step_report.output_path) + print("fcstd", fcstd_path) + print("ap242_metadata_items", step_report.metadata_item_count) + if mesh is not None: + print("gmsh_mesh", mesh.mesh_path) + print("gmsh_volumes", mesh.volume_count) + print("gmsh_nodes", mesh.node_count) + print("gmsh_3d_elements", mesh.element_count) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--skip-mesh", + action="store_true", + help="Export .scadpkg, AP242 STEP, and FCStd without optional Gmsh meshing.", + ) + args = parser.parse_args() + main(generate_mesh=not args.skip_mesh) diff --git a/examples/16_compact_two_stage_planetary_reducer/DESIGN.md b/examples/16_compact_two_stage_planetary_reducer/DESIGN.md index fac59c3e..e0cf0a75 100644 --- a/examples/16_compact_two_stage_planetary_reducer/DESIGN.md +++ b/examples/16_compact_two_stage_planetary_reducer/DESIGN.md @@ -38,7 +38,8 @@ - Fix the output flange to the stage 2 carrier/output shaft. - Add external gear constraints from each sun to its planets using `add_gear_constraint_rassembly`. - Add internal ring-to-planet mesh constraints using same-direction `add_belt_constraint_rassembly` with ring and planet pitch radii. -- Use `GraphSession`, `export_session_json`, `export_model_json`, `import_model_json`, and `replay_model_json` in the build script for replayable output. +- Build every physical single-solid component through `@scad.part`, preserve the reusable bearing as a nested `@scad.assemble`, and build the reducer root through `@scad.assemble` with explicit immutable definitions. +- Export `compact_two_stage_planetary_reducer.scadpkg` as the primary product; derive optional model/session JSON and STEP artifacts from the same durable feature DAG and validate strict product replay. - Ground every build step with concise QL-backed prints: part face counts, volumes, tags, bearing component counts, gear radii, constraint residuals, replay counts, and exported file paths. ## Validation Assumptions diff --git a/examples/16_compact_two_stage_planetary_reducer/assembly.py b/examples/16_compact_two_stage_planetary_reducer/assembly.py index 7f052ad7..8c067173 100644 --- a/examples/16_compact_two_stage_planetary_reducer/assembly.py +++ b/examples/16_compact_two_stage_planetary_reducer/assembly.py @@ -1,6 +1,9 @@ """Top-level compact two-stage planetary reducer assembly.""" from __future__ import annotations +import math +from pathlib import Path +from typing import Callable import simplecadapi as scad @@ -32,7 +35,7 @@ if __package__: make_stage_sun_gear_rpart, ) from .housing import make_reducer_housing_rpart - from .materials import make_reducer_materials_rdict + from .materials import make_reducer_material_rmaterial, make_reducer_materials_rdict from .shafts import make_input_shaft_rpart else: from bearings import ( @@ -62,62 +65,14 @@ else: make_stage_sun_gear_rpart, ) from housing import make_reducer_housing_rpart - from materials import make_reducer_materials_rdict + from materials import make_reducer_material_rmaterial, make_reducer_materials_rdict from shafts import make_input_shaft_rpart -@scad.requires_session -def make_two_stage_planetary_reducer_rassembly() -> scad.Assembly: - """Build the full 20:1 compact reducer assembly and solve constraints.""" - - print( - f"ratio_plan: stage1={STAGE_1.fixed_ring_ratio:.1f}:1 " - f"stage2={STAGE_2.fixed_ring_ratio:.1f}:1 total={TOTAL_REDUCTION:.1f}:1" - ) - materials = make_reducer_materials_rdict() - - housing = make_reducer_housing_rpart(material=materials["housing"]) - input_flange = make_input_flange_rpart(material=materials["shaft"]) - output_flange = make_output_flange_rpart(material=materials["shaft"]) - input_shaft = make_input_shaft_rpart(material=materials["shaft"]) - - stage1_ring = make_stage_ring_gear_rpart(stage=STAGE_1, material=materials["gear"]) - stage1_sun = make_stage_sun_gear_rpart( - stage=STAGE_1, - bore_radius=1.56, - material=materials["gear"], - ) - stage1_planet = make_stage_planet_gear_rpart( - stage=STAGE_1, - bearing=STAGE1_PLANET_BEARING, - material=materials["gear"], - ) - stage1_carrier = make_stage_carrier_rpart( - stage=STAGE_1, - material=materials["carrier"], - ) - - stage2_ring = make_stage_ring_gear_rpart(stage=STAGE_2, material=materials["gear"]) - stage2_sun = make_stage_sun_gear_rpart( - stage=STAGE_2, - bore_radius=1.43, - material=materials["gear"], - ) - stage2_planet = make_stage_planet_gear_rpart( - stage=STAGE_2, - bearing=STAGE2_PLANET_BEARING, - material=materials["gear"], - ) - stage2_carrier = make_stage_carrier_rpart( - stage=STAGE_2, - material=materials["carrier"], - ) - - bearing = make_radial_ball_bearing_rassembly( - bearing_id="micro_radial_ball_bearing", - spec=UNIVERSAL_RADIAL_BEARING, - tag_prefix="reducer.bearing.micro.radial", - ) - +def _assemble_two_stage_planetary_reducer( + *, + components: dict[str, scad.Part], + bearing: scad.Assembly, +) -> scad.Assembly: reducer = scad.make_assembly_rassembly( assembly_id="compact_two_stage_planetary_reducer", name="58.8 mm OD 20:1 through-bolted herringbone planetary actuator reducer", @@ -125,39 +80,34 @@ def make_two_stage_planetary_reducer_rassembly() -> scad.Assembly: reducer = _add_fixed_components_rassembly( assembly=reducer, components=( - ("housing", housing, scad.identity_placement_rplacement(), "Fixed outer housing"), - ("input_flange", input_flange, scad.identity_placement_rplacement(), "Rotating input flange"), - ("output_flange", output_flange, scad.identity_placement_rplacement(), "Rotating output flange"), - ("input_shaft", input_shaft, scad.identity_placement_rplacement(), "Input shaft"), - ("stage1_carrier", stage1_carrier, scad.identity_placement_rplacement(), "Stage 1 carrier and stage 2 sun shaft"), - ("stage2_carrier", stage2_carrier, scad.identity_placement_rplacement(), "Stage 2 carrier and output shaft"), - ("stage1_ring", stage1_ring, _gear_stage_rplacement(stage=STAGE_1), "Stage 1 fixed ring"), - ("stage1_sun", stage1_sun, _gear_stage_rplacement(stage=STAGE_1), "Stage 1 sun"), - ("stage2_ring", stage2_ring, _gear_stage_rplacement(stage=STAGE_2), "Stage 2 fixed ring"), - ("stage2_sun", stage2_sun, _gear_stage_rplacement(stage=STAGE_2), "Stage 2 sun"), + ("housing", components["housing"], scad.identity_placement_rplacement(), "Fixed outer housing"), + ("input_flange", components["input_flange"], scad.identity_placement_rplacement(), "Rotating input flange"), + ("output_flange", components["output_flange"], scad.identity_placement_rplacement(), "Rotating output flange"), + ("input_shaft", components["input_shaft"], scad.identity_placement_rplacement(), "Input shaft"), + ("stage1_carrier", components["stage1_carrier"], scad.identity_placement_rplacement(), "Stage 1 carrier and stage 2 sun shaft"), + ("stage2_carrier", components["stage2_carrier"], scad.identity_placement_rplacement(), "Stage 2 carrier and output shaft"), + ("stage1_ring", components["stage1_ring"], _gear_stage_rplacement(stage=STAGE_1), "Stage 1 fixed ring"), + ("stage1_sun", components["stage1_sun"], _gear_stage_rplacement(stage=STAGE_1), "Stage 1 sun"), + ("stage2_ring", components["stage2_ring"], _gear_stage_rplacement(stage=STAGE_2), "Stage 2 fixed ring"), + ("stage2_sun", components["stage2_sun"], _gear_stage_rplacement(stage=STAGE_2), "Stage 2 sun"), ), ) - for index in range(PLANET_COUNT): reducer = scad.add_component_rassembly( assembly=reducer, - item=stage1_planet, + item=components["stage1_planet"], component_id=f"stage1_planet_{index + 1}", placement=make_planet_component_rplacement(stage=STAGE_1, planet_index=index), name=f"Stage 1 planet gear {index + 1}", ) reducer = scad.add_component_rassembly( assembly=reducer, - item=stage2_planet, + item=components["stage2_planet"], component_id=f"stage2_planet_{index + 1}", placement=make_planet_component_rplacement(stage=STAGE_2, planet_index=index), name=f"Stage 2 planet gear {index + 1}", ) - - reducer = _add_bearing_components_rassembly( - assembly=reducer, - bearing=bearing, - ) + reducer = _add_bearing_components_rassembly(assembly=reducer, bearing=bearing) reducer = _add_public_interface_connectors_rassembly(assembly=reducer) reducer = _add_reducer_constraints_rassembly(assembly=reducer) reducer = scad.solve_assembly_constraints_rassembly(assembly=reducer, strict=True) @@ -165,12 +115,208 @@ def make_two_stage_planetary_reducer_rassembly() -> scad.Assembly: return reducer -@scad.requires_session -def _add_fixed_components_rassembly( - *, - assembly: scad.Assembly, - components: tuple[tuple[str, scad.Part, scad.Placement, str], ...], -) -> scad.Assembly: +def _runtime_components() -> dict[str, scad.Part]: + materials = make_reducer_materials_rdict() + return { + "housing": make_reducer_housing_rpart(material=materials["housing"]), + "input_flange": make_input_flange_rpart(material=materials["shaft"]), + "output_flange": make_output_flange_rpart(material=materials["shaft"]), + "input_shaft": make_input_shaft_rpart(material=materials["shaft"]), + "stage1_ring": make_stage_ring_gear_rpart(stage=STAGE_1, material=materials["gear"]), + "stage1_sun": make_stage_sun_gear_rpart(stage=STAGE_1, bore_radius=1.56, material=materials["gear"]), + "stage1_planet": make_stage_planet_gear_rpart(stage=STAGE_1, bearing=STAGE1_PLANET_BEARING, material=materials["gear"]), + "stage1_carrier": make_stage_carrier_rpart(stage=STAGE_1, material=materials["carrier"]), + "stage2_ring": make_stage_ring_gear_rpart(stage=STAGE_2, material=materials["gear"]), + "stage2_sun": make_stage_sun_gear_rpart(stage=STAGE_2, bore_radius=1.43, material=materials["gear"]), + "stage2_planet": make_stage_planet_gear_rpart(stage=STAGE_2, bearing=STAGE2_PLANET_BEARING, material=materials["gear"]), + "stage2_carrier": make_stage_carrier_rpart(stage=STAGE_2, material=materials["carrier"]), + } + + +def make_two_stage_planetary_reducer_rassembly() -> scad.Assembly: + """Build the full 20:1 compact reducer assembly and solve constraints.""" + + print( + f"ratio_plan: stage1={STAGE_1.fixed_ring_ratio:.1f}:1 " + f"stage2={STAGE_2.fixed_ring_ratio:.1f}:1 total={TOTAL_REDUCTION:.1f}:1" + ) + bearing = make_radial_ball_bearing_rassembly( + bearing_id="micro_radial_ball_bearing", + spec=UNIVERSAL_RADIAL_BEARING, + tag_prefix="reducer.bearing.micro.radial", + ) + return _assemble_two_stage_planetary_reducer( + components=_runtime_components(), + bearing=bearing, + ) + + +def _durable_part( + *, definition_id: str, factory: Callable[[], scad.Part] +) -> scad.PartBuildResult: + @scad.part( + id=definition_id, + revision="1.0.0", + cache="off", + project_root=Path(__file__).resolve().parents[2], + ) + def build() -> scad.Part: + return factory() + + return build() + + +def _bearing_component_part(*, role: str) -> scad.Part: + bearing = make_radial_ball_bearing_rassembly( + bearing_id="micro_radial_ball_bearing", + spec=UNIVERSAL_RADIAL_BEARING, + tag_prefix="reducer.bearing.micro.radial", + ) + component_id = "ball_00" if role == "ball" else role + return bearing.get_component(component_id).item + + +def _durable_bearing() -> scad.AssemblyBuildResult: + bearing_id = "micro_radial_ball_bearing" + outer = _durable_part( + definition_id=f"{bearing_id}_outer_ring", + factory=lambda: _bearing_component_part(role="outer_ring"), + ) + inner = _durable_part( + definition_id=f"{bearing_id}_inner_ring", + factory=lambda: _bearing_component_part(role="inner_ring"), + ) + ball = _durable_part( + definition_id=f"{bearing_id}_ball", + factory=lambda: _bearing_component_part(role="ball"), + ) + + @scad.assemble( + id=bearing_id, + revision="1.0.0", + definitions=(outer, inner, ball), + cache="off", + project_root=Path(__file__).resolve().parents[2], + ) + def build() -> scad.Assembly: + spec = UNIVERSAL_RADIAL_BEARING + bearing = scad.make_assembly_rassembly( + assembly_id=bearing_id, + name="Reusable micro radial ball bearing", + ) + identity = scad.identity_placement_rplacement() + bearing = scad.add_component_rassembly( + assembly=bearing, + item=outer.part, + component_id="outer_ring", + placement=identity, + ) + bearing = scad.add_component_rassembly( + assembly=bearing, + item=inner.part, + component_id="inner_ring", + placement=identity, + ) + pitch_radius = (spec.bore_diameter + spec.outer_diameter) / 4.0 + digits = max(2, len(str(spec.ball_count - 1))) + for index in range(spec.ball_count): + angle = 2.0 * math.pi * index / spec.ball_count + cos_a = math.cos(angle) + sin_a = math.sin(angle) + component_id = f"ball_{index:0{digits}d}" + bearing = scad.add_component_rassembly( + assembly=bearing, + item=ball.part, + component_id=component_id, + placement=scad.make_placement_rplacement( + origin=(pitch_radius * cos_a, pitch_radius * sin_a, 0.0), + x_axis=(cos_a, sin_a, 0.0), + y_axis=(-sin_a, cos_a, 0.0), + ), + ) + bearing = scad.ground_component_rassembly( + assembly=bearing, + component_id=component_id, + ) + bearing = scad.ground_component_rassembly( + assembly=bearing, + component_id="outer_ring", + ) + bearing = scad.add_revolute_constraint_rassembly( + assembly=bearing, + constraint_id="inner_outer_revolute", + connector_a=scad.make_connector_ref_rconnectorref( + component_id="outer_ring", connector_id="axis" + ), + connector_b=scad.make_connector_ref_rconnectorref( + component_id="inner_ring", connector_id="axis" + ), + drive_angle_degrees=None, + name="Inner ring spins in outer ring", + ) + offset = scad.make_placement_rplacement( + origin=(0.0, 0.0, -spec.width / 2.0) + ) + bearing = scad.forward_connector_rassembly( + assembly=bearing, + connector_id="outer_axis", + source_component_id="outer_ring", + source_connector_id="axis", + name="Outer ring housing axis", + offset=offset, + ) + return scad.forward_connector_rassembly( + assembly=bearing, + connector_id="inner_axis", + source_component_id="inner_ring", + source_connector_id="axis", + name="Inner ring shaft axis", + offset=offset, + ) + + return build() + + +def build_two_stage_planetary_reducer_product() -> scad.AssemblyBuildResult: + factories: tuple[tuple[str, str, Callable[[], scad.Part]], ...] = ( + ("housing", "reducer_housing", lambda: make_reducer_housing_rpart(material=make_reducer_material_rmaterial(key="housing"))), + ("input_flange", "input_flange", lambda: make_input_flange_rpart(material=make_reducer_material_rmaterial(key="shaft"))), + ("output_flange", "output_flange", lambda: make_output_flange_rpart(material=make_reducer_material_rmaterial(key="shaft"))), + ("input_shaft", "input_shaft", lambda: make_input_shaft_rpart(material=make_reducer_material_rmaterial(key="shaft"))), + ("stage1_ring", "stage1_ring_gear", lambda: make_stage_ring_gear_rpart(stage=STAGE_1, material=make_reducer_material_rmaterial(key="gear"))), + ("stage1_sun", "stage1_sun_gear", lambda: make_stage_sun_gear_rpart(stage=STAGE_1, bore_radius=1.56, material=make_reducer_material_rmaterial(key="gear"))), + ("stage1_planet", "stage1_planet_gear", lambda: make_stage_planet_gear_rpart(stage=STAGE_1, bearing=STAGE1_PLANET_BEARING, material=make_reducer_material_rmaterial(key="gear"))), + ("stage1_carrier", "stage1_carrier", lambda: make_stage_carrier_rpart(stage=STAGE_1, material=make_reducer_material_rmaterial(key="carrier"))), + ("stage2_ring", "stage2_ring_gear", lambda: make_stage_ring_gear_rpart(stage=STAGE_2, material=make_reducer_material_rmaterial(key="gear"))), + ("stage2_sun", "stage2_sun_gear", lambda: make_stage_sun_gear_rpart(stage=STAGE_2, bore_radius=1.43, material=make_reducer_material_rmaterial(key="gear"))), + ("stage2_planet", "stage2_planet_gear", lambda: make_stage_planet_gear_rpart(stage=STAGE_2, bearing=STAGE2_PLANET_BEARING, material=make_reducer_material_rmaterial(key="gear"))), + ("stage2_carrier", "stage2_carrier", lambda: make_stage_carrier_rpart(stage=STAGE_2, material=make_reducer_material_rmaterial(key="carrier"))), + ) + results = { + key: _durable_part(definition_id=definition_id, factory=factory) + for key, definition_id, factory in factories + } + bearing = _durable_bearing() + + @scad.assemble( + id="compact_two_stage_planetary_reducer", + revision="1.0.0", + definitions=(*results.values(), bearing), + cache="off", + project_root=Path(__file__).resolve().parents[2], + ) + def build() -> scad.Assembly: + return _assemble_two_stage_planetary_reducer( + components={key: result.part for key, result in results.items()}, + bearing=bearing.assembly, + ) + + return build() + + +def _add_fixed_components_rassembly(*, +assembly: scad.Assembly, +components: tuple[tuple[str, scad.Part, scad.Placement, str], ...],) -> scad.Assembly: for component_id, item, placement, name in components: assembly = scad.add_component_rassembly( assembly=assembly, @@ -183,12 +329,9 @@ def _add_fixed_components_rassembly( return assembly -@scad.requires_session -def _add_bearing_components_rassembly( - *, - assembly: scad.Assembly, - bearing: scad.Assembly, -) -> scad.Assembly: +def _add_bearing_components_rassembly(*, +assembly: scad.Assembly, +bearing: scad.Assembly,) -> scad.Assembly: bearing_component_count = 0 for component_id, bearing, placement, name in ( ( @@ -245,7 +388,6 @@ def _add_bearing_components_rassembly( return assembly -@scad.requires_session def _add_public_interface_connectors_rassembly(*, assembly: scad.Assembly) -> scad.Assembly: """Expose stable actuator module datums without leaking private component ids.""" @@ -266,7 +408,6 @@ def _add_public_interface_connectors_rassembly(*, assembly: scad.Assembly) -> sc return assembly -@scad.requires_session def _add_reducer_constraints_rassembly(*, assembly: scad.Assembly) -> scad.Assembly: assembly = scad.ground_component_rassembly(assembly=assembly, component_id="housing") assembly = scad.ground_component_rassembly(assembly=assembly, component_id="stage1_ring") @@ -326,7 +467,6 @@ def _add_reducer_constraints_rassembly(*, assembly: scad.Assembly) -> scad.Assem return assembly -@scad.requires_session def _add_bearing_interface_constraints_rassembly(*, assembly: scad.Assembly) -> scad.Assembly: coaxial_interfaces = ( ("input_bearing_outer_to_housing", "housing", "input_bearing_axis", "input_bearing", "outer_axis"), @@ -375,16 +515,13 @@ def _add_bearing_interface_constraints_rassembly(*, assembly: scad.Assembly) -> return assembly -@scad.requires_session -def _add_stage_mesh_constraints_rassembly( - *, - assembly: scad.Assembly, - stage: StageSpec, - driver_component_id: str, - driver_connector_id: str, - ring_component_id: str, - carrier_component_id: str, -) -> scad.Assembly: +def _add_stage_mesh_constraints_rassembly(*, +assembly: scad.Assembly, +stage: StageSpec, +driver_component_id: str, +driver_connector_id: str, +ring_component_id: str, +carrier_component_id: str,) -> scad.Assembly: for index in range(PLANET_COUNT): planet_component_id = f"{stage.stage_id}_planet_{index + 1}" assembly = scad.add_revolute_constraint_rassembly( @@ -426,7 +563,6 @@ def _add_stage_mesh_constraints_rassembly( return assembly -@scad.requires_session def _gear_stage_rplacement(*, stage: StageSpec) -> scad.Placement: return scad.make_placement_rplacement( origin=(0.0, 0.0, stage.bottom_z), @@ -435,7 +571,6 @@ def _gear_stage_rplacement(*, stage: StageSpec) -> scad.Placement: ) -@scad.requires_session def _ref(*, component_id: str, connector_id: str) -> scad.ConnectorRef: return scad.make_connector_ref_rconnectorref( component_id=component_id, diff --git a/examples/16_compact_two_stage_planetary_reducer/bearings.py b/examples/16_compact_two_stage_planetary_reducer/bearings.py index 456fe642..aba33d87 100644 --- a/examples/16_compact_two_stage_planetary_reducer/bearings.py +++ b/examples/16_compact_two_stage_planetary_reducer/bearings.py @@ -10,13 +10,10 @@ from common import make_z_rotation_rplacement from dimensions import BearingSpec, PLANET_COUNT, StageSpec -@scad.requires_session -def make_radial_ball_bearing_rassembly( - *, - bearing_id: str, - spec: BearingSpec, - tag_prefix: str, -) -> scad.Assembly: +def make_radial_ball_bearing_rassembly(*, +bearing_id: str, +spec: BearingSpec, +tag_prefix: str,) -> scad.Assembly: """Create a standard radial ball bearing assembly for reducer placement.""" bearing = scad.std.bearing.make_ball_bearing_rassembly( @@ -48,14 +45,12 @@ def make_radial_ball_bearing_rassembly( return bearing -@scad.requires_session def make_coaxial_bearing_rplacement(*, z: float) -> scad.Placement: """Return a coaxial bearing placement at the requested axial center.""" return make_z_rotation_rplacement(origin=(0.0, 0.0, z), angle_degrees=0.0) -@scad.requires_session def make_planet_bearing_rplacements(*, stage: StageSpec) -> list[scad.Placement]: """Return placed bearing placements centered in all planets of one stage.""" diff --git a/examples/16_compact_two_stage_planetary_reducer/carriers.py b/examples/16_compact_two_stage_planetary_reducer/carriers.py index 856b1eb7..36e0a107 100644 --- a/examples/16_compact_two_stage_planetary_reducer/carriers.py +++ b/examples/16_compact_two_stage_planetary_reducer/carriers.py @@ -35,12 +35,9 @@ from dimensions import ( ) -@scad.requires_session -def make_stage_carrier_rpart( - *, - stage: StageSpec, - material: scad.Material, -) -> scad.Part: +def make_stage_carrier_rpart(*, +stage: StageSpec, +material: scad.Material,) -> scad.Part: """Create one carrier with three planet pins and any coaxial drive shaft.""" if stage.stage_id == "stage1": @@ -145,22 +142,19 @@ def make_stage_carrier_rpart( return part -@scad.requires_session -def _make_carrier_solid_rsolid( - *, - stage: StageSpec, - plate_bottom_z: float, - plate_thickness: float, - pin_bottom_z: float, - pin_radius: float, - pin_land_radius: float, - hub_radius: float, - arm_width: float, - pad_radius: float, - central_shaft_radius: float, - central_shaft_top_z: float, - tag_prefix: str, -) -> scad.Solid: +def _make_carrier_solid_rsolid(*, +stage: StageSpec, +plate_bottom_z: float, +plate_thickness: float, +pin_bottom_z: float, +pin_radius: float, +pin_land_radius: float, +hub_radius: float, +arm_width: float, +pad_radius: float, +central_shaft_radius: float, +central_shaft_top_z: float, +tag_prefix: str,) -> scad.Solid: hub = scad.make_cylinder_rsolid( radius=hub_radius, height=plate_thickness, diff --git a/examples/16_compact_two_stage_planetary_reducer/collision_probe.py b/examples/16_compact_two_stage_planetary_reducer/collision_probe.py index 33cf5667..0bbdb3d2 100644 --- a/examples/16_compact_two_stage_planetary_reducer/collision_probe.py +++ b/examples/16_compact_two_stage_planetary_reducer/collision_probe.py @@ -31,8 +31,7 @@ def _build_reducer_quietly() -> tuple[scad.Assembly, int, float]: log_buffer = io.StringIO() start = time.perf_counter() with contextlib.redirect_stdout(log_buffer): - result = _build_compact_two_stage_planetary_reducer() - assembly, _preview = result.value + assembly, _preview, _model_json, _session_json = _build_compact_two_stage_planetary_reducer() elapsed = time.perf_counter() - start return assembly, len(log_buffer.getvalue().splitlines()), elapsed diff --git a/examples/16_compact_two_stage_planetary_reducer/common.py b/examples/16_compact_two_stage_planetary_reducer/common.py index 3be8a13c..fdbbdd7c 100644 --- a/examples/16_compact_two_stage_planetary_reducer/common.py +++ b/examples/16_compact_two_stage_planetary_reducer/common.py @@ -9,12 +9,9 @@ import simplecadapi as scad from simplecadapi import ql -@scad.requires_session -def make_z_rotation_rplacement( - *, - origin: tuple[float, float, float], - angle_degrees: float, -) -> scad.Placement: +def make_z_rotation_rplacement(*, +origin: tuple[float, float, float], +angle_degrees: float,) -> scad.Placement: """Return a placement rotated about the local Z axis.""" angle_radians = math.radians(angle_degrees) @@ -27,16 +24,13 @@ def make_z_rotation_rplacement( ) -@scad.requires_session -def make_annular_cylinder_rsolid( - *, - outer_radius: float, - inner_radius: float, - height: float, - bottom_z: float, - tag_prefix: str, - tag: str, -) -> scad.Solid: +def make_annular_cylinder_rsolid(*, +outer_radius: float, +inner_radius: float, +height: float, +bottom_z: float, +tag_prefix: str, +tag: str,) -> scad.Solid: """Create a single hollow cylindrical solid with a through bore.""" if inner_radius <= 0.0 or outer_radius <= inner_radius: @@ -63,17 +57,14 @@ def make_annular_cylinder_rsolid( return annular -@scad.requires_session -def make_axis_connector_rconnector( - *, - connector_id: str, - solid: scad.Solid, - center_xy: tuple[float, float], - target_z: float, - normal_z: float, - name: str | None = None, - flip: bool = False, -) -> scad.Connector: +def make_axis_connector_rconnector(*, +connector_id: str, +solid: scad.Solid, +center_xy: tuple[float, float], +target_z: float, +normal_z: float, +name: str | None = None, +flip: bool = False,) -> scad.Connector: """Create a face connector on the axial face nearest the requested center.""" face = _axis_face( @@ -91,15 +82,12 @@ def make_axis_connector_rconnector( ) -@scad.requires_session -def make_axis_part_rpart( - *, - part_id: str, - solid: scad.Solid, - name: str, - connector_specs: Iterable[dict[str, object]], - material: scad.Material | None = None, -) -> scad.Part: +def make_axis_part_rpart(*, +part_id: str, +solid: scad.Solid, +name: str, +connector_specs: Iterable[dict[str, object]], +material: scad.Material | None = None,) -> scad.Part: """Wrap a solid as a Part and attach axial face connectors.""" part = scad.make_part_rpart(part_id=part_id, body=solid, name=name) @@ -122,14 +110,11 @@ def make_axis_part_rpart( return part -@scad.requires_session -def add_placement_axis_connector_rpart( - *, - part: scad.Part, - connector_id: str, - origin: tuple[float, float, float], - name: str | None = None, -) -> scad.Part: +def add_placement_axis_connector_rpart(*, +part: scad.Part, +connector_id: str, +origin: tuple[float, float, float], +name: str | None = None,) -> scad.Part: """Attach a topology-free axis connector at an explicit local placement.""" connector = scad.make_placement_connector_rconnector( @@ -140,7 +125,6 @@ def add_placement_axis_connector_rpart( return scad.add_connector_rpart(part=part, connector=connector) -@scad.requires_session def _apply_tags(shape: scad.Solid, tags: Iterable[str]) -> scad.Solid: """Apply normalized tags through the public SimpleCAD tag API.""" diff --git a/examples/16_compact_two_stage_planetary_reducer/flanges.py b/examples/16_compact_two_stage_planetary_reducer/flanges.py index 5b723d4f..580927e5 100644 --- a/examples/16_compact_two_stage_planetary_reducer/flanges.py +++ b/examples/16_compact_two_stage_planetary_reducer/flanges.py @@ -47,7 +47,6 @@ from dimensions import ( ) -@scad.requires_session def make_input_flange_rpart(*, material: scad.Material) -> scad.Part: """Create the reducer input flange part with six bolt holes.""" @@ -92,7 +91,6 @@ def make_input_flange_rpart(*, material: scad.Material) -> scad.Part: ) -@scad.requires_session def make_output_flange_rpart(*, material: scad.Material) -> scad.Part: """Create the reducer output flange part with realistic mounting detail.""" @@ -126,7 +124,6 @@ def make_output_flange_rpart(*, material: scad.Material) -> scad.Part: ) -@scad.requires_session def _make_output_flange_solid_rsolid(*, tag_prefix: str) -> scad.Solid: """Build the sealed actuator-style output flange. @@ -312,21 +309,18 @@ def _make_output_flange_solid_rsolid(*, tag_prefix: str) -> scad.Solid: return flange -@scad.requires_session -def _make_n_hole_flange_solid_rsolid( - *, - flange_outer_diameter: float, - flange_inner_diameter: float, - flange_thickness: float, - boss_outer_diameter: float, - boss_height: float, - hole_diameter: float, - hole_circle_diameter: float, - hole_count: int, - counterbore_diameter: float | None = None, - counterbore_depth: float = 0.0, - tag_prefix: str, -) -> scad.Solid: +def _make_n_hole_flange_solid_rsolid(*, +flange_outer_diameter: float, +flange_inner_diameter: float, +flange_thickness: float, +boss_outer_diameter: float, +boss_height: float, +hole_diameter: float, +hole_circle_diameter: float, +hole_count: int, +counterbore_diameter: float | None = None, +counterbore_depth: float = 0.0, +tag_prefix: str,) -> scad.Solid: """Build a flange without edge-pick features so FreeCAD export is stable.""" outer = scad.make_cylinder_rsolid( diff --git a/examples/16_compact_two_stage_planetary_reducer/gears.py b/examples/16_compact_two_stage_planetary_reducer/gears.py index a2b52d38..e3187925 100644 --- a/examples/16_compact_two_stage_planetary_reducer/gears.py +++ b/examples/16_compact_two_stage_planetary_reducer/gears.py @@ -28,12 +28,9 @@ from dimensions import ( ) -@scad.requires_session -def make_stage_ring_gear_rpart( - *, - stage: StageSpec, - material: scad.Material, -) -> scad.Part: +def make_stage_ring_gear_rpart(*, +stage: StageSpec, +material: scad.Material,) -> scad.Part: """Create one fixed internal herringbone ring gear part for a stage.""" ring = scad.std.gear.make_herringbone_ring_gear_rsolid( @@ -102,13 +99,10 @@ def make_stage_ring_gear_rpart( ) -@scad.requires_session -def make_stage_sun_gear_rpart( - *, - stage: StageSpec, - bore_radius: float, - material: scad.Material, -) -> scad.Part: +def make_stage_sun_gear_rpart(*, +stage: StageSpec, +bore_radius: float, +material: scad.Material,) -> scad.Part: """Create one bored external herringbone sun gear part for a stage.""" sun = scad.std.gear.make_herringbone_gear_rsolid( @@ -153,13 +147,10 @@ def make_stage_sun_gear_rpart( ) -@scad.requires_session -def make_stage_planet_gear_rpart( - *, - stage: StageSpec, - bearing: BearingSpec, - material: scad.Material, -) -> scad.Part: +def make_stage_planet_gear_rpart(*, +stage: StageSpec, +bearing: BearingSpec, +material: scad.Material,) -> scad.Part: """Create a reusable bored herringbone planet gear part for a stage.""" planet = scad.std.gear.make_herringbone_gear_rsolid( @@ -211,12 +202,9 @@ def make_stage_planet_gear_rpart( ) -@scad.requires_session -def make_planet_component_rplacement( - *, - stage: StageSpec, - planet_index: int, -) -> scad.Placement: +def make_planet_component_rplacement(*, +stage: StageSpec, +planet_index: int,) -> scad.Placement: """Return the placed and phased component placement for one planet gear.""" carrier_angle = 360.0 * planet_index / 3.0 @@ -234,14 +222,11 @@ def make_planet_component_rplacement( return make_z_rotation_rplacement(origin=center, angle_degrees=planet_spin) -@scad.requires_session -def _cut_bore_rsolid( - *, - label: str, - solid: scad.Solid, - bore_radius: float, - tag_prefix: str, -) -> scad.Solid: +def _cut_bore_rsolid(*, +label: str, +solid: scad.Solid, +bore_radius: float, +tag_prefix: str,) -> scad.Solid: cutter = scad.make_cylinder_rsolid( radius=bore_radius, height=GEAR_HEIGHT + 2.0, diff --git a/examples/16_compact_two_stage_planetary_reducer/housing.py b/examples/16_compact_two_stage_planetary_reducer/housing.py index d9932491..21a168cb 100644 --- a/examples/16_compact_two_stage_planetary_reducer/housing.py +++ b/examples/16_compact_two_stage_planetary_reducer/housing.py @@ -48,7 +48,6 @@ from dimensions import ( ) -@scad.requires_session def make_reducer_housing_rpart(*, material: scad.Material) -> scad.Part: """Create the through-bolted housing sleeve with internal datum collars.""" @@ -160,15 +159,12 @@ def make_reducer_housing_rpart(*, material: scad.Material) -> scad.Part: return part -@scad.requires_session -def _make_end_flange_rsolid( - *, - label: str, - inner_radius: float, - thickness: float, - bottom_z: float, - tag_prefix: str, -) -> scad.Solid: +def _make_end_flange_rsolid(*, +label: str, +inner_radius: float, +thickness: float, +bottom_z: float, +tag_prefix: str,) -> scad.Solid: """Build one sealed housing end cap. The end cap is only the annular plate around the rotating input/output @@ -191,7 +187,6 @@ def _make_end_flange_rsolid( return flange -@scad.requires_session def _make_mount_sector_pad_rsolid(*, tag_prefix: str) -> scad.Solid: """Build four graceful full-height sector pads before the global hole cut.""" @@ -224,7 +219,6 @@ def _make_mount_sector_pad_rsolid(*, tag_prefix: str) -> scad.Solid: return pad -@scad.requires_session def _make_mount_gap_cutters_rsolids(*, tag_prefix: str) -> list[scad.Solid]: """Build shallow radial gap cutters that divide the outer band into sectors.""" @@ -261,7 +255,6 @@ def _make_mount_gap_cutters_rsolids(*, tag_prefix: str) -> list[scad.Solid]: return cutters -@scad.requires_session def _make_mount_hole_cutters_rsolids(*, tag_prefix: str) -> list[scad.Solid]: """Build one shared cutter set for the boss and housing body holes.""" @@ -290,12 +283,9 @@ def _make_mount_hole_cutters_rsolids(*, tag_prefix: str) -> list[scad.Solid]: return cutters -@scad.requires_session -def _make_single_mount_hole_cutters_rsolids( - *, - angle: float, - tag_prefix: str, -) -> list[scad.Solid]: +def _make_single_mount_hole_cutters_rsolids(*, +angle: float, +tag_prefix: str,) -> list[scad.Solid]: """Build through and counterbore cutters for one housing screw.""" x = HOUSING_MOUNT_HOLE_CIRCLE_RADIUS * math.cos(angle) diff --git a/examples/16_compact_two_stage_planetary_reducer/main.py b/examples/16_compact_two_stage_planetary_reducer/main.py index 9dea0a34..c3d8b6fe 100644 --- a/examples/16_compact_two_stage_planetary_reducer/main.py +++ b/examples/16_compact_two_stage_planetary_reducer/main.py @@ -29,11 +29,17 @@ if __package__: _module_name, importlib.import_module(f"{__package__}.{_module_name}"), ) - from .assembly import make_two_stage_planetary_reducer_rassembly + from .assembly import ( + build_two_stage_planetary_reducer_product, + make_two_stage_planetary_reducer_rassembly, + ) from .common import _ground_compound from .dimensions import HOUSING_HEIGHT, HOUSING_OUTER_RADIUS, TOTAL_REDUCTION else: - from assembly import make_two_stage_planetary_reducer_rassembly + from assembly import ( + build_two_stage_planetary_reducer_product, + make_two_stage_planetary_reducer_rassembly, + ) from common import _ground_compound from dimensions import HOUSING_HEIGHT, HOUSING_OUTER_RADIUS, TOTAL_REDUCTION @@ -44,50 +50,59 @@ sys.setrecursionlimit(30000) OUT_DIR = Path("examples/out/compact_two_stage_planetary_reducer") -@scad.model(graph_id="compact_two_stage_planetary_reducer") -def _build_compact_two_stage_planetary_reducer(): +def _build_compact_two_stage_planetary_reducer_body(): """Build the reducer and return its assembly and preview compound.""" assembly = make_two_stage_planetary_reducer_rassembly() preview = scad.make_compound_from_assembly_rcompound(assembly=assembly) preview = scad.apply_tag(shape=preview, tag="scene.reducer.preview") _ground_compound(label="reducer_preview", compound=preview) - scad.capture_result(value=(assembly, preview)) return assembly, preview +def _build_compact_two_stage_planetary_reducer(): + session = scad.GraphSession(graph_id="compact_two_stage_planetary_reducer") + with session: + assembly, preview = _build_compact_two_stage_planetary_reducer_body() + session.capture_result(value=(assembly, preview)) + model_json = scad.export_model_json(session) + session_json = scad.export_session_json(session) + return assembly, preview, model_json, session_json + + def main() -> None: - """Generate replayable JSON and STEP output for the reducer example.""" + """Generate synchronized package, AP242 STEP, FCStd, and replay JSON.""" OUT_DIR.mkdir(parents=True, exist_ok=True) model_path = OUT_DIR / "compact_two_stage_planetary_reducer.model.json" session_path = OUT_DIR / "compact_two_stage_planetary_reducer.session.json" step_path = OUT_DIR / "compact_two_stage_planetary_reducer.step" fcstd_path = OUT_DIR / "compact_two_stage_planetary_reducer.FCStd" - if fcstd_path.exists(): - fcstd_path.unlink() - result = _build_compact_two_stage_planetary_reducer() - assembly, preview = result.value - model_path.write_text(result.model_json, encoding="utf-8") - session_path.write_text(result.session_json, encoding="utf-8") - scad.export_step(shapes=preview, filename=str(step_path)) + product_result = build_two_stage_planetary_reducer_product() + assembly = product_result.assembly + preview = scad.make_compound_from_assembly_rcompound(assembly=assembly) + preview = scad.apply_tag(shape=preview, tag="scene.reducer.preview") + _ground_compound(label="reducer_preview", compound=preview) + session = product_result.feature_graph.restore_session() + model_json = scad.export_model_json(session) + session_json = scad.export_session_json(session) + model_path.write_text(model_json, encoding="utf-8") + session_path.write_text(session_json, encoding="utf-8") + package_path = OUT_DIR / "compact_two_stage_planetary_reducer.scadpkg" + scad.capture(product_result, package_path) + step_report = scad.exporter.export_product_package_to_step(package_path, step_path) + scad.translator.freecad_translator.translate_product_package_to_fcstd( + package_path, + str(fcstd_path.resolve()), + document_name="CompactTwoStagePlanetaryReducer", + ) - imported = scad.import_model_json(json_str=result.model_json) - replayed = scad.replay_model_json(json_str=result.model_json) - payload = json.loads(result.model_json) + imported = scad.import_model_json(json_str=model_json) + replayed = [product_result.replay()] + payload = json.loads(model_json) - fcstd_status = "not attempted" - try: - scad.translator.freecad_translator.translate_model_json_to_fcstd( - json_str=result.model_json, - output_path=str(fcstd_path.resolve()), - document_name="CompactTwoStagePlanetaryReducer", - freecad_cmd=None, - ) - fcstd_status = f"{fcstd_path} ({fcstd_path.stat().st_size} bytes)" - except Exception as exc: # pragma: no cover - depends on local FreeCAD install - fcstd_status = f"skipped ({exc.__class__.__name__}: {exc})" + fcstd_status = f"{fcstd_path} ({fcstd_path.stat().st_size} bytes)" solids = preview.get_solids() print(f"envelope_diameter={HOUSING_OUTER_RADIUS * 2.0:.1f}") @@ -104,8 +119,9 @@ def main() -> None: print(f"graph_nodes={len(payload['graph']['nodes'])}") print(f"model={model_path}") print(f"session={session_path}") - print(f"step={step_path}") + print(f"step={step_report.output_path}") print(f"fcstd={fcstd_status}") + print(f"product_package={package_path}") if __name__ == "__main__": diff --git a/examples/16_compact_two_stage_planetary_reducer/materials.py b/examples/16_compact_two_stage_planetary_reducer/materials.py index ed2d984e..c4249ef6 100644 --- a/examples/16_compact_two_stage_planetary_reducer/materials.py +++ b/examples/16_compact_two_stage_planetary_reducer/materials.py @@ -5,39 +5,56 @@ from __future__ import annotations import simplecadapi as scad -@scad.requires_session +_MATERIAL_SPECS = { + "housing": { + "material_id": "hard_anodized_aluminum", + "name": "Hard anodized aluminum", + "density": 2.70e-6, + "color": (0.26, 0.28, 0.30), + }, + "carrier": { + "material_id": "aluminum_7075", + "name": "7075 aluminum carrier", + "density": 2.81e-6, + "color": (0.48, 0.50, 0.52), + }, + "gear": { + "material_id": "case_hardened_steel", + "name": "Case hardened gear steel", + "density": 7.85e-6, + "color": (0.68, 0.70, 0.72), + }, + "shaft": { + "material_id": "tempered_shaft_steel", + "name": "Tempered shaft steel", + "density": 7.85e-6, + "color": (0.55, 0.57, 0.60), + }, +} + + +def make_reducer_material_rmaterial(*, key: str) -> scad.Material: + """Create one reducer material inside the owning feature graph.""" + + try: + spec = _MATERIAL_SPECS[key] + except KeyError as exc: + raise ValueError(f"unknown reducer material key: {key}") from exc + return scad.make_material_rmaterial( + material_id=spec["material_id"], + name=spec["name"], + density=spec["density"], + density_unit="kg/mm^3", + color=spec["color"], + ) + + def make_reducer_materials_rdict() -> dict[str, scad.Material]: """Create the small set of reusable material records for the assembly.""" materials = { - "housing": scad.make_material_rmaterial( - material_id="hard_anodized_aluminum", - name="Hard anodized aluminum", - density=2.70e-6, - density_unit="kg/mm^3", - color=(0.26, 0.28, 0.30), - ), - "carrier": scad.make_material_rmaterial( - material_id="aluminum_7075", - name="7075 aluminum carrier", - density=2.81e-6, - density_unit="kg/mm^3", - color=(0.48, 0.50, 0.52), - ), - "gear": scad.make_material_rmaterial( - material_id="case_hardened_steel", - name="Case hardened gear steel", - density=7.85e-6, - density_unit="kg/mm^3", - color=(0.68, 0.70, 0.72), - ), - "shaft": scad.make_material_rmaterial( - material_id="tempered_shaft_steel", - name="Tempered shaft steel", - density=7.85e-6, - density_unit="kg/mm^3", - color=(0.55, 0.57, 0.60), - ), + key: make_reducer_material_rmaterial(key=key) + for key in _MATERIAL_SPECS } print("materials: " + ",".join(material.material_id for material in materials.values())) return materials diff --git a/examples/16_compact_two_stage_planetary_reducer/shafts.py b/examples/16_compact_two_stage_planetary_reducer/shafts.py index bbc37d31..cd0943e2 100644 --- a/examples/16_compact_two_stage_planetary_reducer/shafts.py +++ b/examples/16_compact_two_stage_planetary_reducer/shafts.py @@ -8,7 +8,6 @@ from common import _apply_tags, add_placement_axis_connector_rpart, make_axis_pa from dimensions import INPUT_BEARING_Z, INPUT_FLANGE_TOP_Z, INPUT_SHAFT_RADIUS, STAGE_1 -@scad.requires_session def make_input_shaft_rpart(*, material: scad.Material) -> scad.Part: """Create the input shaft linking the input flange and stage 1 sun.""" diff --git a/examples/20_integrated_bldc_joint_actuator/assembly.py b/examples/20_integrated_bldc_joint_actuator/assembly.py index de9ef965..bfeb0613 100644 --- a/examples/20_integrated_bldc_joint_actuator/assembly.py +++ b/examples/20_integrated_bldc_joint_actuator/assembly.py @@ -167,10 +167,7 @@ except ImportError: # Support direct execution from this example directory. ) -@scad.requires_session -def make_integrated_bldc_joint_actuator_rassembly( - *, materials: dict[str, scad.Material] -) -> scad.Assembly: +def make_integrated_bldc_joint_actuator_rassembly(*, materials: dict[str, scad.Material]) -> scad.Assembly: """Build and solve the complete compact 50 mm joint actuator.""" component_specs = make_integrated_bldc_joint_actuator_components_rtuple( @@ -196,10 +193,7 @@ def make_integrated_bldc_joint_actuator_rassembly( return actuator -@scad.requires_session -def make_integrated_bldc_joint_actuator_components_rtuple( - *, materials: dict[str, scad.Material] -) -> tuple[tuple[str, scad.Part | scad.Assembly, scad.Placement, str], ...]: +def make_integrated_bldc_joint_actuator_components_rtuple(*, materials: dict[str, scad.Material]) -> tuple[tuple[str, scad.Part | scad.Assembly, scad.Placement, str], ...]: """Build the actuator component inventory without creating a parent assembly.""" print( diff --git a/examples/20_integrated_bldc_joint_actuator/bearings.py b/examples/20_integrated_bldc_joint_actuator/bearings.py index 746600ef..451f70db 100644 --- a/examples/20_integrated_bldc_joint_actuator/bearings.py +++ b/examples/20_integrated_bldc_joint_actuator/bearings.py @@ -16,10 +16,7 @@ except ImportError: # Support direct execution from this example directory. from materials import make_actuator_material_rmaterial -@scad.requires_session -def make_standard_planet_bearing_rassembly( - *, bearing_id: str, spec: BearingSpec, material: scad.Material -) -> scad.Assembly: +def make_standard_planet_bearing_rassembly(*, bearing_id: str, spec: BearingSpec, material: scad.Material) -> scad.Assembly: """Create a fused standard-library planet ball-bearing assembly.""" return make_main_bearing_rassembly( @@ -29,10 +26,7 @@ def make_standard_planet_bearing_rassembly( ) -@scad.requires_session -def make_main_bearing_rassembly( - *, bearing_id: str, spec: BearingSpec, material: scad.Material -) -> scad.Assembly: +def make_main_bearing_rassembly(*, bearing_id: str, spec: BearingSpec, material: scad.Material) -> scad.Assembly: """Create a standard-library bearing with fused rolling elements.""" bearing = scad.std.bearing.make_ball_bearing_rassembly( @@ -61,14 +55,12 @@ def make_main_bearing_rassembly( return bearing -@scad.requires_session def make_coaxial_bearing_rplacement(*, center_z: float) -> scad.Placement: """Place a standard bearing center plane on the actuator Z axis.""" return make_z_rotation_rplacement(origin=(0.0, 0.0, center_z), angle_degrees=0.0) -@scad.requires_session def make_planet_bearing_rplacement(*, stage: StageSpec, index: int) -> scad.Placement: """Place a standard planet bearing at the gear midplane.""" @@ -84,14 +76,11 @@ def make_planet_bearing_rplacement(*, stage: StageSpec, index: int) -> scad.Plac ) -@scad.requires_session -def _make_bearing_ring_part_rpart( - *, - bearing_id: str, - spec: BearingSpec, - role: str, - material: scad.Material, -) -> scad.Part: +def _make_bearing_ring_part_rpart(*, +bearing_id: str, +spec: BearingSpec, +role: str, +material: scad.Material,) -> scad.Part: bearing = make_main_bearing_rassembly( bearing_id=bearing_id, spec=spec, diff --git a/examples/20_integrated_bldc_joint_actuator/common.py b/examples/20_integrated_bldc_joint_actuator/common.py index 14666c37..f54a210c 100644 --- a/examples/20_integrated_bldc_joint_actuator/common.py +++ b/examples/20_integrated_bldc_joint_actuator/common.py @@ -19,7 +19,6 @@ PART_INPUTS = tuple( ) -@scad.requires_session def apply_tags(*, shape: scad.Solid, tags: Iterable[str]) -> scad.Solid: """Apply semantic tags through the public functional API.""" @@ -29,16 +28,13 @@ def apply_tags(*, shape: scad.Solid, tags: Iterable[str]) -> scad.Solid: return tagged -@scad.requires_session -def make_annulus_rsolid( - *, - outer_radius: float, - inner_radius: float, - bottom_z: float, - height: float, - tag_prefix: str, - tags: Iterable[str], -) -> scad.Solid: +def make_annulus_rsolid(*, +outer_radius: float, +inner_radius: float, +bottom_z: float, +height: float, +tag_prefix: str, +tags: Iterable[str],) -> scad.Solid: """Create a strict single-solid annular cylinder.""" outer = scad.make_cylinder_rsolid( @@ -61,15 +57,12 @@ def make_annulus_rsolid( return apply_tags(shape=annulus, tags=tags) -@scad.requires_session -def make_axis_part_rpart( - *, - part_id: str, - body: scad.Solid, - name: str, - material: scad.Material, - connectors: Iterable[tuple[str, tuple[float, float, float], str]], -) -> scad.Part: +def make_axis_part_rpart(*, +part_id: str, +body: scad.Solid, +name: str, +material: scad.Material, +connectors: Iterable[tuple[str, tuple[float, float, float], str]],) -> scad.Part: """Create a single-body part with stable placement-based axis datums.""" part = scad.make_part_rpart(part_id=part_id, body=body, name=name) @@ -105,12 +98,9 @@ def z_rotation_placement( ) -@scad.requires_session -def make_z_rotation_rplacement( - *, - origin: tuple[float, float, float], - angle_degrees: float, -) -> scad.Placement: +def make_z_rotation_rplacement(*, +origin: tuple[float, float, float], +angle_degrees: float,) -> scad.Placement: """Build a replayable Z rotation in the caller's graph session.""" return z_rotation_placement(origin=origin, angle_degrees=angle_degrees) @@ -125,17 +115,14 @@ def radial_centers(*, count: int, radius: float, angle_offset: float = 0.0): yield index, angle_degrees, (radius * math.cos(angle), radius * math.sin(angle)) -@scad.requires_session -def make_axial_hole_cutters_rsolids( - *, - count: int, - pcd: float, - hole_radius: float, - bottom_z: float, - height: float, - tag_prefix: str, - angle_offset: float = 0.0, -) -> list[scad.Solid]: +def make_axial_hole_cutters_rsolids(*, +count: int, +pcd: float, +hole_radius: float, +bottom_z: float, +height: float, +tag_prefix: str, +angle_offset: float = 0.0,) -> list[scad.Solid]: """Create equally spaced axial hole cutters.""" cutters = [] diff --git a/examples/20_integrated_bldc_joint_actuator/electronics.py b/examples/20_integrated_bldc_joint_actuator/electronics.py index a4e005aa..342e9b20 100644 --- a/examples/20_integrated_bldc_joint_actuator/electronics.py +++ b/examples/20_integrated_bldc_joint_actuator/electronics.py @@ -55,12 +55,9 @@ POWER_CAN_TERMINAL_CENTER = (11.0, 0.0) MOSFET_ANGLES = (22.5, 67.5, 112.5, 202.5, 247.5, 292.5) -@scad.requires_session -def make_integrated_controller_rassembly( - *, - pcb_material: scad.Material, - terminal_material: scad.Material, -) -> scad.Assembly: +def make_integrated_controller_rassembly(*, +pcb_material: scad.Material, +terminal_material: scad.Material,) -> scad.Assembly: """Build the circular ESC with six power devices and two service terminals.""" pcb = _make_controller_pcb_rpart(material=pcb_material) @@ -161,7 +158,6 @@ def make_integrated_controller_rassembly( return controller -@scad.requires_session def _make_controller_pcb_rpart(*, material: scad.Material) -> scad.Part: board = scad.make_cylinder_rsolid( radius=PCB_RADIUS, @@ -274,7 +270,6 @@ def _make_controller_pcb_rpart(*, material: scad.Material) -> scad.Part: ) -@scad.requires_session def _make_mosfet_package_rpart(*, material: scad.Material) -> scad.Part: package = scad.make_box_rsolid( width=4.0, @@ -296,15 +291,12 @@ def _make_mosfet_package_rpart(*, material: scad.Material) -> scad.Part: ) -@scad.requires_session -def _make_terminal_block_rpart( - *, - part_id: str, - name: str, - width: float, - pin_count: int, - material: scad.Material, -) -> scad.Part: +def _make_terminal_block_rpart(*, +part_id: str, +name: str, +width: float, +pin_count: int, +material: scad.Material,) -> scad.Part: terminal_tag_prefix = part_id.replace("_", ".") body = scad.make_box_rsolid( width=width, diff --git a/examples/20_integrated_bldc_joint_actuator/gears.py b/examples/20_integrated_bldc_joint_actuator/gears.py index e8d1bc6c..5bad10a4 100644 --- a/examples/20_integrated_bldc_joint_actuator/gears.py +++ b/examples/20_integrated_bldc_joint_actuator/gears.py @@ -116,12 +116,9 @@ except ImportError: # Support direct execution from this example directory. ) -@scad.requires_session -def make_stage_ring_gear_rpart( - *, - stage: StageSpec, - material: scad.Material, -) -> scad.Part: +def make_stage_ring_gear_rpart(*, +stage: StageSpec, +material: scad.Material,) -> scad.Part: """Create one herringbone ring insert with a full housing support rim.""" ring = scad.std.gear.make_herringbone_ring_gear_rsolid( @@ -178,12 +175,9 @@ def make_stage_ring_gear_rpart( ) -@scad.requires_session -def make_stage_planet_gear_rpart( - *, - stage: StageSpec, - material: scad.Material, -) -> scad.Part: +def make_stage_planet_gear_rpart(*, +stage: StageSpec, +material: scad.Material,) -> scad.Part: """Create one reusable herringbone planet with a standard-bearing seat.""" planet = scad.std.gear.make_herringbone_gear_rsolid( @@ -241,7 +235,6 @@ def make_stage_planet_gear_rpart( ) -@scad.requires_session def make_stage1_carrier_sun_rpart(*, material: scad.Material) -> scad.Part: """Create the first carrier and integral second-stage sun/shaft.""" @@ -332,12 +325,9 @@ def make_stage1_carrier_sun_rpart(*, material: scad.Material) -> scad.Part: ) -@scad.requires_session -def make_output_carrier_flange_rpart( - *, - stage: StageSpec, - material: scad.Material, -) -> scad.Part: +def make_output_carrier_flange_rpart(*, +stage: StageSpec, +material: scad.Material,) -> scad.Part: """Create the second carrier, 16 mm bearing land, and output flange.""" carrier = _make_carrier_body_rsolid( @@ -450,7 +440,6 @@ def make_output_carrier_flange_rpart( ) -@scad.requires_session def make_planet_rplacement(*, stage: StageSpec, index: int) -> scad.Placement: """Place and visually phase one planet at its pitch center.""" @@ -477,18 +466,15 @@ def planet_center_xy(*, stage: StageSpec, index: int) -> tuple[float, float]: ) -@scad.requires_session -def _make_carrier_body_rsolid( - *, - stage: StageSpec, - plate_bottom_z: float, - plate_thickness: float, - pin_bottom_z: float, - pin_radius: float, - hub_radius: float, - arm_width: float, - pad_radius: float, -) -> scad.Solid: +def _make_carrier_body_rsolid(*, +stage: StageSpec, +plate_bottom_z: float, +plate_thickness: float, +pin_bottom_z: float, +pin_radius: float, +hub_radius: float, +arm_width: float, +pad_radius: float,) -> scad.Solid: hub = scad.make_cylinder_rsolid( radius=hub_radius, height=plate_thickness, diff --git a/examples/20_integrated_bldc_joint_actuator/housing.py b/examples/20_integrated_bldc_joint_actuator/housing.py index 9e7a4f10..5d9f4fd4 100644 --- a/examples/20_integrated_bldc_joint_actuator/housing.py +++ b/examples/20_integrated_bldc_joint_actuator/housing.py @@ -108,7 +108,6 @@ except ImportError: # Support direct execution from this example directory. ) -@scad.requires_session def make_motor_shell_rpart(*, material: scad.Material) -> scad.Part: """Create the stator sleeve, front attachment land, and rear columns.""" @@ -200,7 +199,6 @@ def make_motor_shell_rpart(*, material: scad.Material) -> scad.Part: ) -@scad.requires_session def make_reducer_housing_rpart(*, material: scad.Material) -> scad.Part: """Create the reducer sleeve and front motor-bearing bulkhead.""" @@ -325,7 +323,6 @@ def make_reducer_housing_rpart(*, material: scad.Material) -> scad.Part: ) -@scad.requires_session def make_rear_bearing_spider_rpart(*, material: scad.Material) -> scad.Part: """Create a four-arm removable rear motor-bearing support.""" @@ -404,7 +401,6 @@ def make_rear_bearing_spider_rpart(*, material: scad.Material) -> scad.Part: ) -@scad.requires_session def make_rear_electronics_cover_rpart(*, material: scad.Material) -> scad.Part: """Create the rear cover with PCB standoffs and terminal apertures.""" @@ -526,7 +522,6 @@ def make_rear_electronics_cover_rpart(*, material: scad.Material) -> scad.Part: ) -@scad.requires_session def make_output_bearing_cap_rpart(*, material: scad.Material) -> scad.Part: """Create the removable paired-bearing cartridge and front cap.""" diff --git a/examples/20_integrated_bldc_joint_actuator/main.py b/examples/20_integrated_bldc_joint_actuator/main.py index 5dc56e05..66cd1664 100644 --- a/examples/20_integrated_bldc_joint_actuator/main.py +++ b/examples/20_integrated_bldc_joint_actuator/main.py @@ -8,10 +8,7 @@ from pathlib import Path import simplecadapi as scad try: - from .assembly import ( - build_integrated_bldc_joint_actuator as build_durable_actuator, - make_integrated_bldc_joint_actuator_rassembly, - ) + from .assembly import build_integrated_bldc_joint_actuator as build_durable_actuator from .common import ground_compound from .dimensions import ( MOTOR_AIR_GAP, @@ -23,12 +20,8 @@ try: TOTAL_REDUCTION, validate_design_dimensions, ) - from .materials import make_actuator_materials_rdict except ImportError: # Support direct execution from this example directory. - from assembly import ( - build_integrated_bldc_joint_actuator as build_durable_actuator, - make_integrated_bldc_joint_actuator_rassembly, - ) + from assembly import build_integrated_bldc_joint_actuator as build_durable_actuator from common import ground_compound from dimensions import ( MOTOR_AIR_GAP, @@ -40,7 +33,6 @@ except ImportError: # Support direct execution from this example directory. TOTAL_REDUCTION, validate_design_dimensions, ) - from materials import make_actuator_materials_rdict sys.setrecursionlimit(30000) @@ -55,54 +47,16 @@ def build_integrated_bldc_joint_actuator() -> scad.AssemblyBuildResult: return build_durable_actuator() -@scad.model(graph_id="integrated_50mm_bldc_joint_actuator") -def _build_integrated_bldc_joint_actuator_model(): - """Build canonical graph JSON for STEP and FreeCAD translator coverage.""" - - validate_design_dimensions() - materials = make_actuator_materials_rdict() - assembly = make_integrated_bldc_joint_actuator_rassembly(materials=materials) - preview = scad.make_compound_from_assembly_rcompound(assembly=assembly) - preview = scad.apply_tag( - shape=preview, - tag="scene.integrated.bldc.joint.actuator.preview", - ) - ground_compound(label="integrated_actuator_preview", compound=preview) - scad.capture_result(value=(assembly, preview)) - return assembly, preview - - -def export_translator_artifacts() -> tuple[Path, Path, Path]: - """Build the separate canonical graph and run the FreeCAD backend.""" - - OUT_DIR.mkdir(parents=True, exist_ok=True) - model_path = OUT_DIR / "integrated_bldc_joint_actuator.model.json" - session_path = OUT_DIR / "integrated_bldc_joint_actuator.session.json" - fcstd_path = OUT_DIR / "integrated_bldc_joint_actuator.FCStd" - model_result = _build_integrated_bldc_joint_actuator_model() - model_path.write_text(model_result.model_json, encoding="utf-8") - session_path.write_text(model_result.session_json, encoding="utf-8") - scad.translator.freecad_translator.translate_model_json_to_fcstd( - json_str=model_result.model_json, - output_path=str(fcstd_path.resolve()), - document_name="Integrated50mmBLDCJointActuator", - freecad_cmd=None, - ) - return model_path, session_path, fcstd_path - - def main() -> None: - """Generate and verify the self-contained product package and STEP output.""" + """Generate and verify synchronized package, AP242 STEP, and FCStd output.""" OUT_DIR.mkdir(parents=True, exist_ok=True) package_path = OUT_DIR / "integrated_bldc_joint_actuator.scadpkg" step_path = OUT_DIR / "integrated_bldc_joint_actuator.step" + fcstd_path = OUT_DIR / "integrated_bldc_joint_actuator.FCStd" product_result = build_integrated_bldc_joint_actuator() assembly = product_result.value - scad.export_product_package( - scad.build_product_package(product_result), - package_path, - ) + scad.capture(product_result, package_path) packaged_definition = scad.load_product_package(package_path) rebuilt = scad.materialize_definition(packaged_definition) if not isinstance(rebuilt, scad.Assembly): @@ -111,7 +65,13 @@ def main() -> None: raise RuntimeError("product package replay changed the assembly identity") preview = scad.make_compound_from_assembly_rcompound(assembly=assembly) ground_compound(label="durable_actuator_preview", compound=preview) - scad.export_step(shapes=preview, filename=str(step_path)) + step_report = scad.exporter.export_product_package_to_step(package_path, + step_path,) + scad.translator.freecad_translator.translate_product_package_to_fcstd( + package_path, + str(fcstd_path), + document_name="IntegratedBLDCJointActuator", + ) print(f"envelope_diameter={PACKAGE_RADIUS * 2.0:.1f}") print(f"structural_length={PACKAGE_TOP_Z - PACKAGE_STRUCTURAL_BOTTOM_Z:.1f}") @@ -124,7 +84,8 @@ def main() -> None: print(f"preview_solids={len(preview.get_solids())}") print(f"preview_volume={preview.get_volume():.3f}") print(f"product_package={package_path}") - print(f"step={step_path}") + print(f"step={step_report.output_path}") + print(f"fcstd={fcstd_path}") if __name__ == "__main__": diff --git a/examples/20_integrated_bldc_joint_actuator/materials.py b/examples/20_integrated_bldc_joint_actuator/materials.py index 5c405a8f..79a4b0a2 100644 --- a/examples/20_integrated_bldc_joint_actuator/materials.py +++ b/examples/20_integrated_bldc_joint_actuator/materials.py @@ -65,7 +65,6 @@ MATERIAL_SPECS = { } -@scad.requires_session def make_actuator_material_rmaterial(*, key: str) -> scad.Material: """Create one material inside the caller's product graph when active.""" @@ -76,7 +75,6 @@ def make_actuator_material_rmaterial(*, key: str) -> scad.Material: return scad.make_material_rmaterial(**spec) -@scad.requires_session def make_actuator_materials_rdict() -> dict[str, scad.Material]: """Create the materials used by Case 20.""" diff --git a/examples/20_integrated_bldc_joint_actuator/motor.py b/examples/20_integrated_bldc_joint_actuator/motor.py index f9bc0c54..0bf42a58 100644 --- a/examples/20_integrated_bldc_joint_actuator/motor.py +++ b/examples/20_integrated_bldc_joint_actuator/motor.py @@ -82,12 +82,9 @@ except ImportError: # Support direct execution from this example directory. ) -@scad.requires_session -def make_bldc_stator_rassembly( - *, - steel_material: scad.Material, - copper_material: scad.Material, -) -> scad.Assembly: +def make_bldc_stator_rassembly(*, +steel_material: scad.Material, +copper_material: scad.Material,) -> scad.Assembly: """Build a laminated 12-slot stator and twelve fixed winding packs.""" core = _make_stator_core_rpart(material=steel_material) @@ -145,12 +142,9 @@ def make_bldc_stator_rassembly( return stator -@scad.requires_session -def make_bldc_rotor_rassembly( - *, - steel_material: scad.Material, - magnet_material: scad.Material, -) -> scad.Assembly: +def make_bldc_rotor_rassembly(*, +steel_material: scad.Material, +magnet_material: scad.Material,) -> scad.Assembly: """Build the rotor, bonded magnets, shaft, and integrated stage-1 sun.""" core = _make_rotor_shaft_sun_rpart(material=steel_material) @@ -214,7 +208,6 @@ def make_bldc_rotor_rassembly( return rotor -@scad.requires_session def _make_stator_core_rpart(*, material: scad.Material) -> scad.Part: yoke = make_annulus_rsolid( outer_radius=MOTOR_STATOR_OUTER_RADIUS, @@ -287,7 +280,6 @@ def _make_stator_core_rpart(*, material: scad.Material) -> scad.Part: return part -@scad.requires_session def _make_winding_pack_rpart(*, material: scad.Material) -> scad.Part: side_depth = MOTOR_STATOR_TOP_Z - MOTOR_STATOR_BOTTOM_Z + 0.4 side_bottom_z = MOTOR_STATOR_BOTTOM_Z - 0.2 @@ -343,7 +335,6 @@ def _make_winding_pack_rpart(*, material: scad.Material) -> scad.Part: ) -@scad.requires_session def _make_rotor_shaft_sun_rpart(*, material: scad.Material) -> scad.Part: shaft_bottom_z = REAR_BEARING_CENTER_Z - 3.0 shaft = scad.make_cylinder_rsolid( @@ -419,7 +410,6 @@ def _make_rotor_shaft_sun_rpart(*, material: scad.Material) -> scad.Part: return part -@scad.requires_session def _make_rotor_magnet_rpart(*, material: scad.Material) -> scad.Part: half_width = MOTOR_MAGNET_TANGENTIAL_WIDTH / 2.0 outer_x = (MOTOR_MAGNET_OUTER_RADIUS**2 - half_width**2) ** 0.5 diff --git a/examples/7ep_caplcd_enclosure.py b/examples/7ep_caplcd_enclosure.py index 7a4e9e6d..ad9294b3 100644 --- a/examples/7ep_caplcd_enclosure.py +++ b/examples/7ep_caplcd_enclosure.py @@ -69,7 +69,8 @@ WINDOW_Y = 80.0 @scad.part( id="caplcd_enclosure_7ep", revision="1.0.0", - export_dir=OUT_DIR, + inputs=(scad.file_input(path="examples/7ep_caplcd_enclosure.py"),), + cache="auto", ) def build_enclosure(): tray = _build_tray() @@ -274,6 +275,16 @@ def _build_tray(): if __name__ == "__main__": result = build_enclosure() + package_path = OUT_DIR / "caplcd_enclosure_7ep.scadpkg" + scad.capture(result, package_path) + step_path = OUT_DIR / "caplcd_enclosure_7ep.step" + fcstd_path = OUT_DIR / "caplcd_enclosure_7ep.FCStd" + step_report = scad.exporter.export_product_package_to_step(package_path, step_path) + scad.translator.freecad_translator.translate_product_package_to_fcstd( + package_path, + str(fcstd_path), + document_name="CaplcdEnclosure7EP", + ) print("replay count", len(result.replay())) print("tray volume", round(result.value.body.get_volume(), 1)) print("geometry interface", result.definition.interface_hashes.geometry) @@ -281,3 +292,6 @@ if __name__ == "__main__": "interface diff", result.interface_diff.to_dict() if result.interface_diff is not None else None, ) + print("product package", package_path) + print("step", step_report.output_path) + print("fcstd", fcstd_path) diff --git a/examples/README.md b/examples/README.md index 66d4116b..7c81218e 100644 --- a/examples/README.md +++ b/examples/README.md @@ -3,25 +3,27 @@ Run examples from the repository root with `uv run python `. Generated artifacts are written to `examples/out/`, which is ignored by git. -Replayable geometry-flow examples use one top-level `@scad.model` entry. That -entry owns the `GraphSession` and returns a `ModelResult`; reusable graph-producing -builders use `@scad.requires_session`. Final outputs are selected with -`scad.capture_result(...)`, and `@scad.model(export_dir=...)` can write a -self-contained Scene ZIP. +Every formal example emits three synchronized artifacts under `examples/out/`: +the canonical self-contained `.scadpkg`, an AP242 `.step`, and an editable +FreeCAD `.FCStd`. Single-solid products use `@scad.part`; assemblies use +`@scad.assemble` with explicit immutable definitions for every physical part or +nested assembly. Both downstream CAD files are translated from the same product +package, so they retain the same definition closure, evaluated geometry, +assembly instances, names, solved placements, materials, and available semantic +metadata. -Durable product examples instead use one `@scad.part` per physical single-solid -part and one `@scad.assemble` entry with explicit immutable definitions. These -return `PartBuildResult`/`AssemblyBuildResult`, use the persistent cache, and -export independent definition artifacts. Explicit export or translator APIs may -also write STEP, JSON, or FreeCAD files. +`tools/run_examples.py` requires every formal example to rewrite and validate +all three artifacts. Model/session JSON and the optional Gmsh `.msh` remain +secondary demonstration outputs. ## Examples -- `04_dimension_tolerance_chain.py` — expression-driven dimension tolerance analysis and validation. -- `08_constrained_sketch.py` — fully constrained sketch profiles, feature promotion, replay, and FreeCAD export. -- `09_naca0016_blade_freecad.py` — NACA 0016 B-spline blade model JSON, STEP, and FreeCAD translation. -- `10_part_assembly.py` — hydraulic rod assembly with sleeve/piston parts, prismatic motion, and automatic self-contained Scene ZIP export. -- `11_external_reference_gear_train.py` — cached single-solid parts, explicit external definitions, repeated/nested assembly instances, incremental constraint solving, and independent definition export. -- `7ep_caplcd_enclosure.py` — cached enclosure part with source-file dependency tracking and durable artifact export. -- `16_compact_two_stage_planetary_reducer/` — modular 58.8 mm diameter, 30 mm tall, 20:1 two-stage herringbone planetary reducer with graph/model JSON replay, STEP export, solved constraints, and a static collision probe. -- `20_integrated_bldc_joint_actuator/` — compact 50 mm OD joint actuator with a 12-slot/14-pole inner-rotor BLDC motor, two-stage planetary reducer, split housing, output bearings, and controller electronics. +- `04_dimension_tolerance_chain.py` — `out/dimension_tolerance_chain/dimension_tolerance_chain.scadpkg` +- `08_constrained_sketch.py` — `out/constrained_sketch/constrained_sketch.scadpkg` +- `09_naca0016_blade_freecad.py` — `out/naca0016_blade/naca0016_blade.scadpkg` +- `10_part_assembly.py` — `out/hydraulic_rod_assembly/hydraulic_rod_assembly.scadpkg` +- `11_external_reference_gear_train.py` — `out/external_reference_gear_train/nested_external_reference_gear_trains.scadpkg` +- `12_ap242_gmsh_volume_mesh.py` — `out/ap242_gmsh_volume_mesh/ap242_gmsh_bracket.scadpkg` +- `7ep_caplcd_enclosure.py` — `out/7ep_caplcd_enclosure/caplcd_enclosure_7ep.scadpkg` +- `16_compact_two_stage_planetary_reducer/` — `out/compact_two_stage_planetary_reducer/compact_two_stage_planetary_reducer.scadpkg` +- `20_integrated_bldc_joint_actuator/` — `out/integrated_bldc_joint_actuator/integrated_bldc_joint_actuator.scadpkg` diff --git a/pyproject.toml b/pyproject.toml index 2a55ca9e..5880c006 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -49,6 +49,9 @@ collision = [ inspect = [ "matplotlib>=3.7.0", ] +gmsh = [ + "gmsh>=4.15,<5", +] [project.urls] Homepage = "https://github.com/NiJingzhe/SimpleCADAPI" @@ -95,6 +98,9 @@ dev = [ "datamodel-code-generator==0.32.0", ] +[tool.pytest.ini_options] +testpaths = ["test", "tests"] + [project.scripts] evolve = "simplecadapi.auto_tools.evolution:main" make-export = "simplecadapi.auto_tools.make_export:main" diff --git a/scene-contract/schemas/scene-2.0.schema.json b/scene-contract/schemas/scene-2.0.schema.json new file mode 100644 index 00000000..2dfab993 --- /dev/null +++ b/scene-contract/schemas/scene-2.0.schema.json @@ -0,0 +1,116 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://simplecad.dev/schemas/scene-2.0.schema.json", + "title": "SimpleCAD Scene 2.0", + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "scene_id", "revision", "units", "roots", "definitions", "geometry_assets", "entity_assets", "product_assets", "feature_graph_assets", "source_assets", "nodes", "connectors", "joints", "feature_index", "source_index", "connector_index", "joint_index", "camera", "extensions"], + "properties": { + "schema_version": {"const": "2.0"}, + "scene_id": {"$ref": "#/$defs/id"}, + "revision": {"$ref": "#/$defs/hash"}, + "units": {"const": "mm"}, + "roots": {"type": "array", "minItems": 1, "maxItems": 25000, "items": {"$ref": "#/$defs/id"}}, + "definitions": {"type": "array", "minItems": 1, "maxItems": 25000, "items": {"$ref": "#/$defs/definition"}}, + "geometry_assets": {"type": "array", "minItems": 1, "maxItems": 25000, "items": {"$ref": "#/$defs/asset"}}, + "entity_assets": {"type": "array", "minItems": 1, "maxItems": 25000, "items": {"$ref": "#/$defs/asset"}}, + "product_assets": {"type": "array", "minItems": 1, "maxItems": 25000, "items": {"$ref": "#/$defs/productAsset"}}, + "feature_graph_assets": {"type": "array", "minItems": 1, "maxItems": 25000, "items": {"$ref": "#/$defs/featureGraphAsset"}}, + "source_assets": {"type": "array", "maxItems": 25000, "items": {"$ref": "#/$defs/sourceAsset"}}, + "nodes": {"type": "array", "minItems": 1, "maxItems": 1000000, "items": {"$ref": "#/$defs/node"}}, + "connectors": {"type": "array", "maxItems": 1000000, "items": {"$ref": "#/$defs/connector"}}, + "joints": {"type": "array", "maxItems": 1000000, "items": {"$ref": "#/$defs/joint"}}, + "feature_index": {"type": "array", "minItems": 1, "maxItems": 1000000, "items": {"$ref": "#/$defs/feature"}}, + "source_index": {"type": "array", "maxItems": 1000000, "items": {"$ref": "#/$defs/sourceIndex"}}, + "connector_index": {"type": "array", "maxItems": 1000000, "items": {"$ref": "#/$defs/connectorIndex"}}, + "joint_index": {"type": "array", "maxItems": 1000000, "items": {"$ref": "#/$defs/jointIndex"}}, + "camera": {"$ref": "#/$defs/camera"}, + "extensions": {"type": "object", "additionalProperties": true} + }, + "$defs": { + "id": {"type": "string", "minLength": 1, "maxLength": 1024, "pattern": "^[A-Za-z][A-Za-z0-9_.:/-]*$"}, + "hash": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"}, + "uri": {"type": "string", "minLength": 1, "maxLength": 4096, "pattern": "^[A-Za-z0-9][A-Za-z0-9._/-]*$"}, + "vec3": {"type": "array", "minItems": 3, "maxItems": 3, "items": {"type": "number"}}, + "transform": { + "type": "object", "additionalProperties": false, + "required": ["origin", "x_axis", "y_axis", "z_axis"], + "properties": {"origin": {"$ref": "#/$defs/vec3"}, "x_axis": {"$ref": "#/$defs/vec3"}, "y_axis": {"$ref": "#/$defs/vec3"}, "z_axis": {"$ref": "#/$defs/vec3"}} + }, + "asset": { + "type": "object", "additionalProperties": false, + "required": ["asset_id", "uri", "media_type", "sha256", "byte_length"], + "properties": {"asset_id": {"$ref": "#/$defs/hash"}, "uri": {"$ref": "#/$defs/uri"}, "media_type": {"type": "string", "minLength": 1}, "sha256": {"$ref": "#/$defs/hash"}, "byte_length": {"type": "integer", "minimum": 0, "maximum": 9007199254740991}} + }, + "definition": { + "type": "object", "additionalProperties": false, + "required": ["definition_id", "definition_kind", "revision", "content_hash", "product_asset_id", "feature_graph_asset_id"], + "properties": {"definition_id": {"$ref": "#/$defs/id"}, "definition_kind": {"enum": ["single_solid", "assembly"]}, "revision": {"type": "string", "minLength": 1}, "content_hash": {"$ref": "#/$defs/hash"}, "product_asset_id": {"$ref": "#/$defs/hash"}, "feature_graph_asset_id": {"$ref": "#/$defs/hash"}} + }, + "productAsset": { + "type": "object", "additionalProperties": false, + "required": ["asset_id", "uri", "media_type", "sha256", "byte_length", "definition_id", "definition_kind", "revision", "content_hash"], + "properties": {"asset_id": {"$ref": "#/$defs/hash"}, "uri": {"$ref": "#/$defs/uri"}, "media_type": {"enum": ["application/vnd.simplecad.part-definition+zip", "application/vnd.simplecad.assembly-definition+zip"]}, "sha256": {"$ref": "#/$defs/hash"}, "byte_length": {"type": "integer", "minimum": 0}, "definition_id": {"$ref": "#/$defs/id"}, "definition_kind": {"enum": ["single_solid", "assembly"]}, "revision": {"type": "string", "minLength": 1}, "content_hash": {"$ref": "#/$defs/hash"}} + }, + "featureGraphAsset": { + "type": "object", "additionalProperties": false, + "required": ["asset_id", "uri", "media_type", "sha256", "byte_length", "definition_id", "graph_id", "graph_revision"], + "properties": {"asset_id": {"$ref": "#/$defs/hash"}, "uri": {"$ref": "#/$defs/uri"}, "media_type": {"const": "application/vnd.simplecad.feature-graph+zip"}, "sha256": {"$ref": "#/$defs/hash"}, "byte_length": {"type": "integer", "minimum": 0}, "definition_id": {"$ref": "#/$defs/id"}, "graph_id": {"$ref": "#/$defs/id"}, "graph_revision": {"$ref": "#/$defs/hash"}} + }, + "sourceAsset": { + "type": "object", "additionalProperties": false, + "required": ["source_asset_id", "uri", "sha256", "byte_length", "media_type", "display_name"], + "properties": {"source_asset_id": {"$ref": "#/$defs/hash"}, "uri": {"$ref": "#/$defs/uri"}, "sha256": {"$ref": "#/$defs/hash"}, "byte_length": {"type": "integer", "minimum": 0}, "media_type": {"type": "string", "minLength": 1}, "display_name": {"type": "string", "minLength": 1, "maxLength": 4096}} + }, + "node": { + "type": "object", "additionalProperties": false, + "required": ["node_id", "parent_node_id", "display_name", "node_kind", "definition_id", "definition_kind", "component_id", "instance_id", "transform", "geometry_asset_id", "entity_asset_id", "material_id", "properties"], + "properties": {"node_id": {"$ref": "#/$defs/id"}, "parent_node_id": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/id"}]}, "display_name": {"type": "string"}, "node_kind": {"enum": ["part", "assembly", "solid"]}, "definition_id": {"$ref": "#/$defs/id"}, "definition_kind": {"enum": ["single_solid", "assembly"]}, "component_id": {"type": ["string", "null"]}, "instance_id": {"type": ["string", "null"]}, "transform": {"$ref": "#/$defs/transform"}, "geometry_asset_id": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/hash"}]}, "entity_asset_id": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/hash"}]}, "material_id": {"type": ["string", "null"]}, "properties": {"type": "object", "additionalProperties": true}} + }, + "connector": { + "type": "object", "additionalProperties": false, + "required": ["connector_snapshot_id", "node_id", "definition_id", "definition_kind", "connector_id", "name", "anchor_kind", "local_frame", "binding", "forwarded_from", "source_feature_id"], + "properties": {"connector_snapshot_id": {"$ref": "#/$defs/id"}, "node_id": {"$ref": "#/$defs/id"}, "definition_id": {"$ref": "#/$defs/id"}, "definition_kind": {"enum": ["single_solid", "assembly"]}, "connector_id": {"$ref": "#/$defs/id"}, "name": {"type": "string"}, "anchor_kind": {"enum": ["explicit", "geometry", "forwarded"]}, "local_frame": {"$ref": "#/$defs/transform"}, "binding": {"type": ["object", "null"]}, "forwarded_from": {"type": ["object", "null"]}, "source_feature_id": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/id"}]}} + }, + "connectorRef": { + "type": "object", "additionalProperties": false, + "required": ["definition_id", "component_id", "instance_id", "connector_id", "connector_snapshot_id"], + "properties": {"definition_id": {"$ref": "#/$defs/id"}, "component_id": {"$ref": "#/$defs/id"}, "instance_id": {"$ref": "#/$defs/id"}, "connector_id": {"$ref": "#/$defs/id"}, "connector_snapshot_id": {"$ref": "#/$defs/id"}} + }, + "joint": { + "type": "object", "additionalProperties": false, + "required": ["joint_id", "assembly_definition_id", "joint_type", "connector_a", "connector_b", "parameters", "limits", "source_feature_id"], + "properties": {"joint_id": {"$ref": "#/$defs/id"}, "assembly_definition_id": {"$ref": "#/$defs/id"}, "joint_type": {"enum": ["fixed", "revolute", "prismatic", "cylindrical", "planar", "ball"]}, "connector_a": {"$ref": "#/$defs/connectorRef"}, "connector_b": {"$ref": "#/$defs/connectorRef"}, "parameters": {"type": "object", "additionalProperties": true}, "limits": {"type": ["object", "null"], "additionalProperties": true}, "source_feature_id": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/id"}]}} + }, + "feature": { + "type": "object", "additionalProperties": false, + "required": ["feature_id", "definition_id", "graph_id", "node_id", "op", "label", "parameters", "input_feature_ids", "output_count", "source_spans"], + "properties": {"feature_id": {"$ref": "#/$defs/id"}, "definition_id": {"$ref": "#/$defs/id"}, "graph_id": {"$ref": "#/$defs/id"}, "node_id": {"$ref": "#/$defs/id"}, "op": {"type": "string", "minLength": 1}, "label": {"type": ["string", "null"]}, "parameters": {"type": "object", "additionalProperties": true}, "input_feature_ids": {"type": "array", "items": {"$ref": "#/$defs/id"}}, "output_count": {"type": "integer", "minimum": 1}, "source_spans": {"type": "array", "items": {"$ref": "#/$defs/sourceSpan"}}} + }, + "sourceSpan": { + "type": "object", "additionalProperties": false, + "required": ["source_asset_id", "uri", "start_line", "end_line", "symbol"], + "properties": {"source_asset_id": {"$ref": "#/$defs/hash"}, "uri": {"$ref": "#/$defs/uri"}, "start_line": {"type": "integer", "minimum": 1}, "end_line": {"type": "integer", "minimum": 1}, "symbol": {"type": ["string", "null"]}} + }, + "sourceIndex": { + "type": "object", "additionalProperties": false, + "required": ["source_index_id", "source_asset_id", "uri", "definition_id", "feature_id", "start_line", "end_line", "symbol"], + "properties": {"source_index_id": {"$ref": "#/$defs/id"}, "source_asset_id": {"$ref": "#/$defs/hash"}, "uri": {"$ref": "#/$defs/uri"}, "definition_id": {"$ref": "#/$defs/id"}, "feature_id": {"$ref": "#/$defs/id"}, "start_line": {"type": "integer", "minimum": 1}, "end_line": {"type": "integer", "minimum": 1}, "symbol": {"type": ["string", "null"]}} + }, + "connectorIndex": { + "type": "object", "additionalProperties": false, + "required": ["connector_index_id", "definition_id", "node_id", "connector_id", "connector_snapshot_id", "source_feature_id"], + "properties": {"connector_index_id": {"$ref": "#/$defs/id"}, "definition_id": {"$ref": "#/$defs/id"}, "node_id": {"$ref": "#/$defs/id"}, "connector_id": {"$ref": "#/$defs/id"}, "connector_snapshot_id": {"$ref": "#/$defs/id"}, "source_feature_id": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/id"}]}} + }, + "jointIndex": { + "type": "object", "additionalProperties": false, + "required": ["joint_index_id", "assembly_definition_id", "joint_id", "source_feature_id"], + "properties": {"joint_index_id": {"$ref": "#/$defs/id"}, "assembly_definition_id": {"$ref": "#/$defs/id"}, "joint_id": {"$ref": "#/$defs/id"}, "source_feature_id": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/id"}]}} + }, + "camera": { + "type": "object", "additionalProperties": false, + "required": ["target", "position", "up", "near", "far", "fit_mode", "margin"], + "properties": {"target": {"$ref": "#/$defs/vec3"}, "position": {"$ref": "#/$defs/vec3"}, "up": {"$ref": "#/$defs/vec3"}, "near": {"type": "number", "exclusiveMinimum": 0}, "far": {"type": "number", "exclusiveMinimum": 0}, "fit_mode": {"enum": ["bounds", "selection"]}, "margin": {"type": "number", "minimum": 0, "maximum": 10}} + } + } +} diff --git a/scene-contract/src/generated/entities.ts b/scene-contract/src/generated/entities.ts index 689c5085..fb5b0ead 100644 --- a/scene-contract/src/generated/entities.ts +++ b/scene-contract/src/generated/entities.ts @@ -24,7 +24,7 @@ export type EntityId = string; * This interface was referenced by `EntityDocument`'s JSON-Schema * via the `definition` "source". */ -export type Source = ModelOutput | ModelTopology | ImportedPrimitive | Unbound; +export type Source = ModelOutput | ModelTopology | PackageGeometry | ImportedPrimitive | Unbound; /** * This interface was referenced by `EntityDocument`'s JSON-Schema * via the `definition` "productId". @@ -143,6 +143,16 @@ export interface ModelTopology { topology_kind: "SOLID" | "FACE" | "EDGE" | "VERTEX"; topo_id: string; } +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "packageGeometry". + */ +export interface PackageGeometry { + kind: "package_geometry"; + package_kind: "part_package" | "assembly_package"; + package_revision: Hash; + definition_id: ProductId; +} /** * This interface was referenced by `EntityDocument`'s JSON-Schema * via the `definition` "importedPrimitive". diff --git a/scene-contract/src/generated/scene.ts b/scene-contract/src/generated/scene.ts index e9f2da2b..f9d85dc3 100644 --- a/scene-contract/src/generated/scene.ts +++ b/scene-contract/src/generated/scene.ts @@ -24,7 +24,7 @@ export type Token = string; * This interface was referenced by `SceneDocument`'s JSON-Schema * via the `definition` "sceneSource". */ -export type SceneSource = ModelSource | ImportedSource | ManualSource; +export type SceneSource = ModelSource | ProductPackageSource | ImportedSource | ManualSource; /** * This interface was referenced by `SceneDocument`'s JSON-Schema * via the `definition` "productId". @@ -69,7 +69,12 @@ export type StructuralId = string; * via the `definition` "definitionSource". */ export type DefinitionSource = - ProductModelSource | ProductManualSource | ModelOutputSource | ImportedDefinitionSource | ManualDefinitionSource; + | ProductModelSource + | ProductManualSource + | ProductPackageDefinitionSource + | ModelOutputSource + | ImportedDefinitionSource + | ManualDefinitionSource; /** * @minItems 3 * @maxItems 3 @@ -111,7 +116,7 @@ export type Connector = { local_transform: Transform; target?: ConnectorTarget; forwarded_from?: ForwardedFrom; - source: null | ModelOperationSource | ManualConnectorSource; + source: null | ModelOperationSource | ManualConnectorSource | ProductPackageConnectorSource; sdk_metadata: { [k: string]: unknown; }; @@ -204,6 +209,16 @@ export interface SourceFile { byte_length: SafeInteger; content_hash: Hash; } +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "productPackageSource". + */ +export interface ProductPackageSource { + kind: "part_package" | "assembly_package"; + definition_id: ProductId; + revision: Hash; + artifact_hash: Hash; +} /** * This interface was referenced by `SceneDocument`'s JSON-Schema * via the `definition` "importedSource". @@ -276,6 +291,18 @@ export interface ProductManualSource { semantic_type: "Part" | "Assembly"; semantic_id: ProductId; } +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "productPackageDefinitionSource". + */ +export interface ProductPackageDefinitionSource { + kind: "product_package"; + root_id: LogicalId; + semantic_type: "Part" | "Assembly"; + semantic_id: ProductId; + package_kind: "part_package" | "assembly_package"; + package_revision: Hash; +} /** * This interface was referenced by `SceneDocument`'s JSON-Schema * via the `definition` "modelOutputSource". @@ -484,6 +511,16 @@ export interface ManualConnectorSource { kind: "manual"; source_id: LogicalId; } +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "productPackageConnectorSource". + */ +export interface ProductPackageConnectorSource { + kind: "product_package"; + package_kind: "part_package" | "assembly_package"; + package_revision: Hash; + definition_id: ProductId; +} /** * This interface was referenced by `SceneDocument`'s JSON-Schema * via the `definition` "perspectiveCamera". diff --git a/scene-contract/src/resources.ts b/scene-contract/src/resources.ts index 27d73fbf..f801cfc7 100644 --- a/scene-contract/src/resources.ts +++ b/scene-contract/src/resources.ts @@ -1,9 +1,9 @@ export const BASE_LIMITS = { zip_members: 50_000, - input_archive_bytes: 256 * 1024 * 1024, - canonical_archive_bytes: 256 * 1024 * 1024, + input_archive_bytes: 512 * 1024 * 1024, + canonical_archive_bytes: 512 * 1024 * 1024, total_uncompressed_bytes: 1024 * 1024 * 1024, - one_member_bytes: 256 * 1024 * 1024, + one_member_bytes: 512 * 1024 * 1024, scene_json_bytes: 32 * 1024 * 1024, entity_json_bytes: 64 * 1024 * 1024, model_json_bytes: 64 * 1024 * 1024, diff --git a/skills/simplecadapi/SKILL.md b/skills/simplecadapi/SKILL.md index ebd87eb5..edc41e7a 100644 --- a/skills/simplecadapi/SKILL.md +++ b/skills/simplecadapi/SKILL.md @@ -38,8 +38,8 @@ metadata: 3. Read the needed `core/` or exact `api/` docs when an API needs `Edge`, `Face`, `Wire`, `Solid`, `GraphSession`, `Sketch`, or expression types. 4. Prefer the standard parts library for standard parts before hand-modeling with core geometry APIs. 5. Follow the documented API signatures exactly. -6. When calling any SimpleCAD public API or standard-library function, use keyword arguments for every documented parameter; do not use positional arguments. -7. Use `@part` for one physical single-solid product, `@assemble` for an assembly with explicit durable definitions, and `@model` only for replayable geometry flows that are not durable product boundaries. Use `@requires_session` for child graph builders and `capture_result(...)` for explicit `@model` outputs. Export `PartBuildResult` and `AssemblyBuildResult` with `export_artifacts(output_dir=...)`; both produce the same canonical self-contained `.scadpkg` product format. +6. For documented SimpleCAD public APIs and standard-library functions, use keyword arguments, except for the canonical durable export call `capture(result, path)`, whose two required arguments are positional. +7. Use `@part` for one physical single-solid product and `@assemble` for an assembly with explicit durable definitions. For replayable geometry, use an explicit `GraphSession`, call `session.capture_result(...)` for canonical outputs, then use `export_model_json(session=...)` and `replay_model_json(json_str=...)`. For durable product delivery, call `capture(result, "out/product.scadpkg")` to build and write the canonical package in one step. 8. Use geometry APIs for integrated parts: profiles, features, booleans, transforms, tagging, QL inspection, serialization, and exports. 9. Use tags consistently through `apply_tag(shape=..., tag=...)` and `list_tags(shape=...)`; do not call shape member tag mutators. 10. Build and validate incrementally. Each step MUST include a small grounding `print`, and grounding MUST use QL where possible. @@ -49,9 +49,9 @@ metadata: 14. For automated example/test harnesses, prefer the repo-local examples in `examples/` and avoid scratch scripts in `sandbox/`. 15. If union cannot produce exactly one merged solid, it fails explicitly; do not silently pick one piece. 16. If a single merged solid is required and union fails, slightly adjust part placement so intended bodies overlap/embed, then recompute. -17. If a task depends on model replay or interchange, prefer `ModelResult.model_json` or `export_model_json()` output over hand-written payloads. +17. If a task depends on model replay or interchange, prefer `export_model_json(session)` output over hand-written payloads. 18. For STEP/BREP inspection or target/candidate comparison, read `references/inspect/brep-reverse-engineering.md` completely. -19. Use `simplecadapi.inspect.brep` only outside `GraphSession` and `@model`; inspection functions are diagnostic tools, not modeling operations. +19. Use `simplecadapi.inspect.brep` only outside `GraphSession`; inspection functions are diagnostic tools, not modeling operations. 20. Reverse engineering is case-by-case: the built-in inspection primitives are tools, not a pipeline — write ad hoc inspection code for the specific model when built-ins do not answer the question. Acceptance hierarchy: BREP topology identity is the best endpoint (complete reverse engineering); identical structure with minor float-level parameter drift from export is acceptable; a visually-close but structurally different result is a valid stop only when no better feature operation order/combination exists or the SDK lacks the required operation type. 21. Before configuring persistent cache, writing a durable product build, or running cache maintenance, read `references/docs/guides/cache-build-workflow.md` completely. Cache mutation requires explicit repair, apply, or clear confirmation. @@ -82,11 +82,11 @@ This file/parameter standard applies to every modeling task. It is mandatory; de - Start with intent: identify the part, its reference axes, critical profiles, and the features that produce the final solid. - Build from lower-dimensional geometry to higher-dimensional geometry: `Vertex` / `Edge` / `Wire` / `Face` profiles first, then `Solid` features such as extrude, revolve, loft, and sweep. - Keep modeling operations functional. Create new values from public functions such as `make_circle_rface(...)`, `extrude_rsolid(...)`, `cut_rsolid(...)`, and `fillet_rsolid(...)`. -- Use keyword arguments for all SimpleCAD function calls, for example `make_box_rsolid(width=10.0, height=20.0, depth=3.0)` instead of positional arguments. -- Use `@model` when a non-product geometry flow should be replayable, inspectable, exported as model JSON, or translated to another CAD system. It owns one `GraphSession`; reusable graph-producing builders use `@requires_session`. -- Use `@part` when the result is one physical single-solid product and needs a durable definition or whole-part cache. Use `@assemble` for explicit part/nested-assembly definitions and incremental constraint solving; do not wrap either product boundary in `@model`. -- Export either build result with `export_artifacts(output_dir=...)`. The only product format is `"product"`, written as a canonical self-contained `.scadpkg` whose content-addressed closure preserves PRT/ASM definitions, instances, relations, stable topology naming, and resolved connector geometry bindings. Use `export_definition(...)` only for low-level definition exchange or inspection. -- Treat model JSON as the interchange boundary for non-product `@model` flows. Prefer `ModelResult.model_json` and `ModelResult.replay()` for top-level models; use `export_model_json(session=...)` for lower-level direct sessions and `replay_model_json(json_str=...)` for standalone payloads. +- Use keyword arguments for SimpleCAD function calls, except the canonical `capture(result, path)` durable export call. For example, use `make_box_rsolid(width=10.0, height=20.0, depth=3.0)` instead of positional primitive arguments. +- Use an explicit `GraphSession` when a non-product geometry flow should be replayable, inspectable, exported as model JSON, or translated to another CAD system. Reusable graph-producing builders accept a session or run inside the caller's session. +- Use `@part` when the result is one physical single-solid product and needs a durable definition or whole-part cache. Use `@assemble` for explicit part/nested-assembly definitions and incremental constraint solving; do not nest either product boundary in a `GraphSession`. +- Use `capture(result, "out/product.scadpkg")` for durable product delivery. It builds and writes the canonical self-contained `.scadpkg`, then returns a `CaptureResult` containing the runtime value, package, scene, and encoded bytes. The public product-package primitives are in-memory construction, encoding, validation, and reading only; use `export_part_definition(...)` or `export_assembly_definition(...)` only for low-level definition exchange or inspection. +- Treat model JSON as the interchange boundary for explicit `GraphSession` flows. Use `session.capture_result(...)`, `export_model_json(session)`, and `replay_model_json(json_str=...)`. - Use QL for precise grounding. Query faces, edges, centers, normals, areas, lengths, curve types, and tags; print only the facts needed to validate the current step. - Use `get_edges(index)`, `get_faces(index)`, `get_wires(index)`, or `get_vertices(index)` when an indexed topology pick is intentional; these picks are preserved as geo select nodes in replayable graph workflows. - Use tags for semantic intent and selection anchors, such as `role.mounting_surface`, `anchor.datum.primary`, `face.top`, or `group.fasteners`. @@ -110,7 +110,7 @@ This file/parameter standard applies to every modeling task. It is mandatory; de - Stdlib docs include an `Import Surface` section that identifies the package-level `simplecadapi.std.gear` module export. - Use `references/SDK_OVERVIEW.md` for the package-level map. - Use `references/SDK_SURFACES.md` for the main public surfaces. -- Use `references/MODELING_WORKFLOWS.md` for graph/model-oriented patterns. +- Use `references/MODELING_WORKFLOWS.md` for explicit graph-session patterns. - Use `references/inspect/brep-reverse-engineering.md` for case-specific STEP/BREP evidence gathering and acceptance. - Use `references/docs/guides/cache-build-workflow.md` for durable product boundaries, cache policy, PRT reuse, incremental invalidation, and maintenance. @@ -118,22 +118,14 @@ This file/parameter standard applies to every modeling task. It is mandatory; de ```python import simplecadapi as scad -from simplecadapi import ModelResult, capture_result, model, requires_session -``` +from simplecadapi import GraphSession, export_model_json, replay_model_json -Typical replayable usage in a Python script: - -```python -import simplecadapi as scad - -@scad.model(graph_id="box") -def build_box(): +with GraphSession(graph_id="box") as session: shape = scad.make_box_rsolid(width=10.0, height=20.0, depth=30.0) - scad.capture_result(value=shape) - return shape + session.capture_result(value=shape) + payload = export_model_json(session=session) -result = build_box() -rebuilt = result.replay() +rebuilt = replay_model_json(json_str=payload) print(len(rebuilt)) ``` diff --git a/skills/simplecadapi/references/MODELING_WORKFLOWS.md b/skills/simplecadapi/references/MODELING_WORKFLOWS.md index 36700d22..bc4a3bb6 100644 --- a/skills/simplecadapi/references/MODELING_WORKFLOWS.md +++ b/skills/simplecadapi/references/MODELING_WORKFLOWS.md @@ -7,11 +7,11 @@ - Use the standard parts library first when a requested standard component is available and does not need complex custom geometry changes. - Start from profiles and reference geometry, then create solids with features such as extrude, revolve, loft, and sweep. - Use booleans and detail features after the base form is clear: cut openings, union intended merged bodies, then apply fillets, chamfers, or shell operations. -- Use `@scad.part` for one physical single-solid product, `@scad.assemble` for explicit durable assembly definitions, and `@scad.model` only for replayable geometry flows that are not product build boundaries. `@scad.model` owns one `GraphSession`; use `@scad.requires_session` for child graph builders. +- Use `@scad.part` for one physical single-solid product and `@scad.assemble` for explicit durable assembly definitions. Use an explicit `GraphSession` for replayable geometry flows. - Use QL for grounding and selection. Query the facts you need, such as face normals, centers, areas, edge lengths, curve types, and tags. - Use indexed child-geometry getters such as `get_edges(index)` and `get_faces(index)` when an indexed topology pick is intentional. - Use semantic tags for design intent and anchors. Keep numeric measurements and geometry facts in metadata or model JSON payloads. -- Treat `ModelResult.model_json` as the interchange boundary for new model entry points. Use `export_model_json(session=...)` for lower-level direct sessions. +- Treat `export_model_json(session=...)` as the interchange boundary for replayable geometry. Capture final outputs with `session.capture_result(...)` and replay with `replay_model_json(json_str=...)`. - Validate incrementally: after each major step, print small QL-derived facts such as selected face count, top face center, edge count, volume, or replay result count. - Read `references/docs/guides/cache-build-workflow.md` before configuring persistent cache or using `@scad.part`/`@scad.assemble`. @@ -19,18 +19,15 @@ ```python import simplecadapi as scad +from simplecadapi import GraphSession, export_model_json, replay_model_json -@scad.model(graph_id="bracket") -def build_bracket(): +with GraphSession(graph_id="bracket") as session: body = scad.make_box_rsolid(width=20.0, height=10.0, depth=3.0) - scad.capture_result(value=body) - return body + session.capture_result(value=body) + payload = export_model_json(session=session) -result = build_bracket() -payload = result.model_json -rebuilt = result.replay() +rebuilt = replay_model_json(json_str=payload) ``` - ## 2) Build a durable cached part ```python @@ -54,10 +51,8 @@ Use `@scad.assemble(definitions=(...))` in the single assembly file. Pass immuta import simplecadapi as scad ``` -## 4) Keep replay payloads as the interchange boundary - -- Prefer `export_model_json()` output instead of hand-written payloads. -- Use `ModelResult.replay()` for a model invocation, or `replay_model_json(json_str=...)` when consuming standalone model JSON. +- Prefer `export_model_json(session=...)` output instead of hand-written payloads. +- Use `session.capture_result(...)` when the final output should not be inferred from all graph leaves, then use `replay_model_json(json_str=...)` when consuming standalone model JSON. - Use `import_model_json()` when consuming previously exported payloads. ## 5) Use standard parts when they fit @@ -87,10 +82,10 @@ bearing = scad.std.bearing.make_ball_bearing_rassembly( ```python import simplecadapi as scad +from simplecadapi import GraphSession, export_model_json, replay_model_json from simplecadapi import ql -@scad.model(graph_id="swept_profile") -def build_model(): +with GraphSession(graph_id="swept_profile") as session: profile = scad.make_circle_rface(center=(0, 0, 0), radius=1.0) body = scad.extrude_rsolid( profile=profile, @@ -108,11 +103,10 @@ def build_model(): print("end face center", end_face.get_center()) path = scad.make_segment_rwire(start=(0, 0, 4), end=(0, 0, 8)) swept = scad.sweep_rsolid(profile=end_face, path=path) - scad.capture_result(value=swept) - return swept + session.capture_result(value=swept) + payload = export_model_json(session=session) -result = build_model() -rebuilt = result.replay() +rebuilt = replay_model_json(json_str=payload) print("rebuilt", len(rebuilt)) ``` diff --git a/skills/simplecadapi/references/SDK_SURFACES.md b/skills/simplecadapi/references/SDK_SURFACES.md index 4c477537..22b18484 100644 --- a/skills/simplecadapi/references/SDK_SURFACES.md +++ b/skills/simplecadapi/references/SDK_SURFACES.md @@ -65,15 +65,13 @@ Use `apply_tag(shape=..., tag=...)` for user-authored semantic tags and `list_ta ```python import simplecadapi as scad +from simplecadapi import GraphSession, export_model_json, replay_model_json -@scad.model(graph_id="demo") -def build_model(): +with GraphSession(graph_id="demo") as session: result = ... - scad.capture_result(value=result) - return result + session.capture_result(value=result) + model_json = export_model_json(session=session) -model = build_model() -model_json = model.model_json -rebuilt = model.replay() +rebuilt = replay_model_json(json_str=model_json) print(len(rebuilt)) ``` diff --git a/skills/simplecadapi/references/docs/api/AssemblyBuildResult.md b/skills/simplecadapi/references/docs/api/AssemblyBuildResult.md index db401823..110c784a 100644 --- a/skills/simplecadapi/references/docs/api/AssemblyBuildResult.md +++ b/skills/simplecadapi/references/docs/api/AssemblyBuildResult.md @@ -3,7 +3,7 @@ ## Class Definition ```python -class AssemblyBuildResult(value: Assembly, definition: AssemblyDefinition, model_json: str, solve_report: AssemblySolveReport, artifact_paths: Mapping[str, Path] = field(default_factory=dict)) +class AssemblyBuildResult(value: Assembly, definition: AssemblyDefinition, feature_graph: FeatureGraphArtifact, solve_report: AssemblySolveReport) ``` *Source: build/results.py* @@ -14,4 +14,4 @@ class AssemblyBuildResult(value: Assembly, definition: AssemblyDefinition, model ## Description -Runtime Assembly plus its external-reference durable definition. +Runtime Assembly plus its durable definition, feature DAG, and solve evidence. diff --git a/skills/simplecadapi/references/docs/api/BRepComparison.md b/skills/simplecadapi/references/docs/api/BRepComparison.md index 72179609..df84ff61 100644 --- a/skills/simplecadapi/references/docs/api/BRepComparison.md +++ b/skills/simplecadapi/references/docs/api/BRepComparison.md @@ -10,7 +10,7 @@ class BRepComparison(target: str | None, candidate: str | None, target_minus_can ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.BRepComparison(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.BRepComparison(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/BRepEntityError.md b/skills/simplecadapi/references/docs/api/BRepEntityError.md index 4ea9351f..e3fcb5a5 100644 --- a/skills/simplecadapi/references/docs/api/BRepEntityError.md +++ b/skills/simplecadapi/references/docs/api/BRepEntityError.md @@ -10,7 +10,7 @@ class BRepEntityError ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.BRepEntityError(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.BRepEntityError(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/BRepInspection.md b/skills/simplecadapi/references/docs/api/BRepInspection.md index fea3ee40..4a20c5c6 100644 --- a/skills/simplecadapi/references/docs/api/BRepInspection.md +++ b/skills/simplecadapi/references/docs/api/BRepInspection.md @@ -10,7 +10,7 @@ class BRepInspection(source: str | None, valid: bool, counts: dict[str, int], bo ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.BRepInspection(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.BRepInspection(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/BRepModel.md b/skills/simplecadapi/references/docs/api/BRepModel.md index 3fb7d137..3a82b334 100644 --- a/skills/simplecadapi/references/docs/api/BRepModel.md +++ b/skills/simplecadapi/references/docs/api/BRepModel.md @@ -10,7 +10,7 @@ class BRepModel(root: TopoDS_Shape, source: str | None, bodies: tuple[TopoDS_Sol ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.BRepModel(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.BRepModel(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/CaptureResult.md b/skills/simplecadapi/references/docs/api/CaptureResult.md new file mode 100644 index 00000000..9b2f445c --- /dev/null +++ b/skills/simplecadapi/references/docs/api/CaptureResult.md @@ -0,0 +1,17 @@ +# CaptureResult + +## Class Definition + +```python +class CaptureResult(value: Part | Assembly, definition: PartDefinition | AssemblyDefinition, package: ProductPackage, scene: ProductScenePackage, package_bytes: bytes) +``` + +*Source: capture.py* + +## Import Surface + +- top-level: `from simplecadapi import CaptureResult` + +## Description + +Runtime value plus one complete durable product snapshot. diff --git a/skills/simplecadapi/references/docs/api/EntityInspectionParity.md b/skills/simplecadapi/references/docs/api/EntityInspectionParity.md index 5b9ee7d3..1b89af7a 100644 --- a/skills/simplecadapi/references/docs/api/EntityInspectionParity.md +++ b/skills/simplecadapi/references/docs/api/EntityInspectionParity.md @@ -10,7 +10,7 @@ class EntityInspectionParity(source: str | None, valid: bool, issues: tuple[str, ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.EntityInspectionParity(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.EntityInspectionParity(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/FreeCADScriptTranslator.md b/skills/simplecadapi/references/docs/api/FreeCADScriptTranslator.md deleted file mode 100644 index cbd17f54..00000000 --- a/skills/simplecadapi/references/docs/api/FreeCADScriptTranslator.md +++ /dev/null @@ -1,17 +0,0 @@ -# FreeCADScriptTranslator - -## Class Definition - -```python -class FreeCADScriptTranslator -``` - -*Source: translator/freecad_translator/translator.py* - -## Import Surface - -- translator backend: `from simplecadapi.translator.freecad_translator import FreeCADScriptTranslator` - -## Description - -Backward-compatible class name for the FreeCAD translator. diff --git a/skills/simplecadapi/references/docs/api/FreeCADTranslator.md b/skills/simplecadapi/references/docs/api/FreeCADTranslator.md index 5d26e728..954748b7 100644 --- a/skills/simplecadapi/references/docs/api/FreeCADTranslator.md +++ b/skills/simplecadapi/references/docs/api/FreeCADTranslator.md @@ -3,7 +3,7 @@ ## Class Definition ```python -class FreeCADTranslator(document_name: str = 'SimpleCADModel') +class FreeCADTranslator(document_name: str = 'SimpleCADProduct') ``` *Source: translator/freecad_translator/translator.py* @@ -14,4 +14,4 @@ class FreeCADTranslator(document_name: str = 'SimpleCADModel') ## Description -Public, stateless facade for FreeCAD script translation. +Translate validated `.scadpkg` products into FreeCAD scripts. diff --git a/skills/simplecadapi/references/docs/api/Fusion360Translator.md b/skills/simplecadapi/references/docs/api/Fusion360Translator.md index d5052b82..5c206436 100644 --- a/skills/simplecadapi/references/docs/api/Fusion360Translator.md +++ b/skills/simplecadapi/references/docs/api/Fusion360Translator.md @@ -3,7 +3,7 @@ ## Class Definition ```python -class Fusion360Translator(document_name: str = 'SimpleCADModel', result_node_ids: Optional[Sequence[str]] = None, *, selection_mode: str = 'gsm', source_kernel_fallback: bool = False) +class Fusion360Translator(document_name: str = 'SimpleCADProduct', *, selection_mode: str = 'gsm', source_kernel_fallback: bool = False) ``` *Source: translator/fusion360_translator/translator.py* @@ -14,4 +14,4 @@ class Fusion360Translator(document_name: str = 'SimpleCADModel', result_node_ids ## Description -Translate canonical model JSON into a Fusion 360 Python script. +Translate validated `.scadpkg` products into Fusion 360 scripts. diff --git a/skills/simplecadapi/references/docs/api/GraphSession.md b/skills/simplecadapi/references/docs/api/GraphSession.md index c79981cb..e97d2448 100644 --- a/skills/simplecadapi/references/docs/api/GraphSession.md +++ b/skills/simplecadapi/references/docs/api/GraphSession.md @@ -3,7 +3,7 @@ ## Class Definition ```python -class GraphSession(graph_id: Optional[str] = None) +class GraphSession(graph_id: Optional[str] = None, *, allow_external_definitions: bool = False) ``` *Source: graph.py* diff --git a/skills/simplecadapi/references/docs/api/InspectionSummaryComparison.md b/skills/simplecadapi/references/docs/api/InspectionSummaryComparison.md index 9f2f41b5..6856222d 100644 --- a/skills/simplecadapi/references/docs/api/InspectionSummaryComparison.md +++ b/skills/simplecadapi/references/docs/api/InspectionSummaryComparison.md @@ -10,7 +10,7 @@ class InspectionSummaryComparison(volume_delta: float, surface_area_delta: float ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.InspectionSummaryComparison(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.InspectionSummaryComparison(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/ModelResult.md b/skills/simplecadapi/references/docs/api/ModelResult.md deleted file mode 100644 index fd222ada..00000000 --- a/skills/simplecadapi/references/docs/api/ModelResult.md +++ /dev/null @@ -1,17 +0,0 @@ -# ModelResult - -## Class Definition - -```python -class ModelResult(value: Any, session: GraphSession, result_node_ids: Tuple[str, ...], model_json: str, session_json: str, artifact_paths: Mapping[str, Path] = field(default_factory=dict)) -``` - -*Source: graph.py* - -## Import Surface - -- top-level: `from simplecadapi import ModelResult` - -## Description - -The value and durable graph artifacts produced by ``@model``. diff --git a/skills/simplecadapi/references/docs/api/PartBuildResult.md b/skills/simplecadapi/references/docs/api/PartBuildResult.md index d616c4b0..b81f14ff 100644 --- a/skills/simplecadapi/references/docs/api/PartBuildResult.md +++ b/skills/simplecadapi/references/docs/api/PartBuildResult.md @@ -3,7 +3,7 @@ ## Class Definition ```python -class PartBuildResult(value: Part, definition: PartDefinition, session: GraphSession, result_node_ids: tuple[str, ...], model_json: str, session_json: str, cache_report: CacheReport, interface_diff: PartInterfaceDiff | None = None, artifact_paths: Mapping[str, Path] = field(default_factory=dict)) +class PartBuildResult(value: Part, definition: PartDefinition, feature_graph: FeatureGraphArtifact, cache_report: CacheReport, interface_diff: PartInterfaceDiff | None = None) ``` *Source: build/results.py* @@ -14,4 +14,4 @@ class PartBuildResult(value: Part, definition: PartDefinition, session: GraphSes ## Description -Runtime Part plus its durable definition, graph, and cache evidence. +Runtime Part plus its durable definition, feature DAG, and cache evidence. diff --git a/skills/simplecadapi/references/docs/api/ProductSTEPExportReport.md b/skills/simplecadapi/references/docs/api/ProductSTEPExportReport.md new file mode 100644 index 00000000..4dbea8ce --- /dev/null +++ b/skills/simplecadapi/references/docs/api/ProductSTEPExportReport.md @@ -0,0 +1,17 @@ +# ProductSTEPExportReport + +## Class Definition + +```python +class ProductSTEPExportReport(output_path: Path, schema: str, definition_ids: tuple[str, ...], occurrence_count: int, material_ids: tuple[str, ...], metadata_item_count: int, limitations: tuple[str, ...]) +``` + +*Source: exporter/step.py* + +## Import Surface + +- exporter namespace: `from simplecadapi import exporter` then `exporter.step.ProductSTEPExportReport(...)` + +## Description + +Observed AP242 export facts and explicit semantic limitations. diff --git a/skills/simplecadapi/references/docs/api/ProductSTLExportReport.md b/skills/simplecadapi/references/docs/api/ProductSTLExportReport.md new file mode 100644 index 00000000..66c0e89f --- /dev/null +++ b/skills/simplecadapi/references/docs/api/ProductSTLExportReport.md @@ -0,0 +1,17 @@ +# ProductSTLExportReport + +## Class Definition + +```python +class ProductSTLExportReport(output_path: Path, root_definition_id: str, solid_count: int, definition_count: int, quadrilateral_count: int, residual_triangle_count: int, stl_triangle_count: int, quad_fraction: float, mesh_size: float, remesh_backend: str = 'gmsh-quad-dominant') +``` + +*Source: exporter/stl.py* + +## Import Surface + +- exporter namespace: `from simplecadapi import exporter` then `exporter.stl.ProductSTLExportReport(...)` + +## Description + +Evidence from quad-dominant product-surface remeshing and STL export. diff --git a/skills/simplecadapi/references/docs/api/README.md b/skills/simplecadapi/references/docs/api/README.md index d1235374..05088233 100644 --- a/skills/simplecadapi/references/docs/api/README.md +++ b/skills/simplecadapi/references/docs/api/README.md @@ -6,7 +6,7 @@ This index includes generated docs for the public SimpleCAD API surface, includi - Entries marked `top-level` are exported from `simplecadapi` and can be imported with `from simplecadapi import `. - Entries marked `submodule` are public through the listed submodule, such as `simplecadapi.ql`. -- Entries marked `inspection namespace` are available through `simplecadapi.inspect.brep` and cannot run inside `GraphSession` or `@model`. +- Entries marked `inspection namespace` are available through `simplecadapi.inspect.brep` and cannot run inside `GraphSession`. - Entries marked `translator backend` are public only through `simplecadapi.translator.`. ## Basic Creation @@ -91,22 +91,20 @@ This index includes generated docs for the public SimpleCAD API surface, includi ## Export -- [export_product_package](export_product_package.md) *(from product_packages.py)* `top-level` -- [export_step](export_step.md) *(from operations.py)* `top-level` -- [export_stl](export_stl.md) *(from operations.py)* `top-level` +- [ProductSTEPExportReport](ProductSTEPExportReport.md) *(from exporter/step.py)* `exporter namespace` +- [ProductSTLExportReport](ProductSTLExportReport.md) *(from exporter/stl.py)* `exporter namespace` +- [export_product_package_to_step](export_product_package_to_step.md) *(from exporter/step.py)* `exporter namespace` +- [export_product_package_to_stl](export_product_package_to_stl.md) *(from exporter/stl.py)* `exporter namespace` ## Translator Backends -- [FreeCADScriptTranslator](FreeCADScriptTranslator.md) *(from translator/freecad_translator/translator.py)* `translator backend` - [FreeCADTranslator](FreeCADTranslator.md) *(from translator/freecad_translator/translator.py)* `translator backend` - [Fusion360Translator](Fusion360Translator.md) *(from translator/fusion360_translator/translator.py)* `translator backend` - [SolidWorksTranslator](SolidWorksTranslator.md) *(from translator/solidworks_translator/translator.py)* `translator backend` -- [export_model_json_to_fcstd](export_model_json_to_fcstd.md) *(from translator/freecad_translator/api.py)* `translator backend` -- [export_model_json_to_solidworks_step](export_model_json_to_solidworks_step.md) *(from translator/solidworks_translator/api.py)* `translator backend` -- [translate_model_json_to_fcstd](translate_model_json_to_fcstd.md) *(from translator/freecad_translator/api.py)* `translator backend` -- [translate_model_json_to_freecad_script](translate_model_json_to_freecad_script.md) *(from translator/freecad_translator/api.py)* `translator backend` -- [translate_model_json_to_fusion360_script](translate_model_json_to_fusion360_script.md) *(from translator/fusion360_translator/api.py)* `translator backend` -- [translate_model_json_to_solidworks_script](translate_model_json_to_solidworks_script.md) *(from translator/solidworks_translator/api.py)* `translator backend` +- [translate_product_package_to_fcstd](translate_product_package_to_fcstd.md) *(from translator/freecad_translator/api.py)* `translator backend` +- [translate_product_package_to_freecad_script](translate_product_package_to_freecad_script.md) *(from translator/freecad_translator/api.py)* `translator backend` +- [translate_product_package_to_fusion360_script](translate_product_package_to_fusion360_script.md) *(from translator/fusion360_translator/api.py)* `translator backend` +- [translate_product_package_to_solidworks_script](translate_product_package_to_solidworks_script.md) *(from translator/solidworks_translator/api.py)* `translator backend` ## Math Helpers @@ -116,8 +114,6 @@ This index includes generated docs for the public SimpleCAD API surface, includi ## Modeling Graph and Replay - [GraphSession](GraphSession.md) *(from graph.py)* `top-level` -- [ModelResult](ModelResult.md) *(from graph.py)* `top-level` -- [capture_result](capture_result.md) *(from graph.py)* `top-level` - [export_graph_json](export_graph_json.md) *(from serializer.py)* `top-level` - [export_model_json](export_model_json.md) *(from serializer.py)* `top-level` - [export_session_json](export_session_json.md) *(from serializer.py)* `top-level` @@ -125,10 +121,8 @@ This index includes generated docs for the public SimpleCAD API surface, includi - [import_graph_json](import_graph_json.md) *(from serializer.py)* `top-level` - [import_model_json](import_model_json.md) *(from serializer.py)* `top-level` - [import_session_json](import_session_json.md) *(from serializer.py)* `top-level` -- [model](model.md) *(from graph.py)* `top-level` - [replay_graph](replay_graph.md) *(from serializer.py)* `top-level` - [replay_model_json](replay_model_json.md) *(from serializer.py)* `top-level` -- [requires_session](requires_session.md) *(from graph.py)* `top-level` - [suspend_graph_recording](suspend_graph_recording.md) *(from graph.py)* `top-level` ## Expressions and Parameters @@ -256,6 +250,7 @@ This index includes generated docs for the public SimpleCAD API surface, includi ## Other - [Assembly](Assembly.md) *(from product.py)* `top-level` +- [CaptureResult](CaptureResult.md) *(from capture.py)* `top-level` - [Component](Component.md) *(from product.py)* `top-level` - [Connector](Connector.md) *(from product.py)* `top-level` - [ConnectorAnchor](ConnectorAnchor.md) *(from product.py)* `top-level` @@ -291,6 +286,7 @@ This index includes generated docs for the public SimpleCAD API surface, includi - [and_](and_.md) *(from ql.py)* `submodule:ql` - [assign_material_rpart](assign_material_rpart.md) *(from operations.py)* `top-level` - [build_product_package](build_product_package.md) *(from product_packages.py)* `top-level` +- [capture](capture.md) *(from capture.py)* `top-level` - [constrain_angle_rsketch](constrain_angle_rsketch.md) *(from operations.py)* `top-level` - [constrain_coincident_rsketch](constrain_coincident_rsketch.md) *(from operations.py)* `top-level` - [constrain_collinear_rsketch](constrain_collinear_rsketch.md) *(from operations.py)* `top-level` diff --git a/skills/simplecadapi/references/docs/api/SliceSpec.md b/skills/simplecadapi/references/docs/api/SliceSpec.md index bf3d8e5c..5a0fc0b5 100644 --- a/skills/simplecadapi/references/docs/api/SliceSpec.md +++ b/skills/simplecadapi/references/docs/api/SliceSpec.md @@ -10,7 +10,7 @@ class SliceSpec(plane: SlicePlane, value: float, label: str | None = None) ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.SliceSpec(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.SliceSpec(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/SolidWorksTranslator.md b/skills/simplecadapi/references/docs/api/SolidWorksTranslator.md index 0b3b86ee..09580538 100644 --- a/skills/simplecadapi/references/docs/api/SolidWorksTranslator.md +++ b/skills/simplecadapi/references/docs/api/SolidWorksTranslator.md @@ -3,7 +3,7 @@ ## Class Definition ```python -class SolidWorksTranslator(document_name: str = 'SimpleCADModel', *, output_path: Optional[str] = None, visible: bool = False, source_kernel_fallback: bool = False) +class SolidWorksTranslator(document_name: str = 'SimpleCADProduct', *, output_path: str | None = None, visible: bool = False, source_kernel_fallback: bool = False) ``` *Source: translator/solidworks_translator/translator.py* @@ -14,4 +14,4 @@ class SolidWorksTranslator(document_name: str = 'SimpleCADModel', *, output_path ## Description -Translate canonical model JSON into a SolidWorks COM Python script. +Translate one validated `.scadpkg` closure into SolidWorks automation. diff --git a/skills/simplecadapi/references/docs/api/assemble.md b/skills/simplecadapi/references/docs/api/assemble.md index 36a929fa..af7b3f6a 100644 --- a/skills/simplecadapi/references/docs/api/assemble.md +++ b/skills/simplecadapi/references/docs/api/assemble.md @@ -3,7 +3,7 @@ ## API Definition ```python -def assemble(func: Callable[_P, _R] | None = None, *, id: str | None = None, revision: str = '1.0.0', definitions: Sequence[Any] = (), cache: CachePolicy | Mapping[str, Any] | str | None = None, export_dir: str | Path | None = None, project_root: str | Path | None = None, tolerance_profile: str = 'simplecad-default') -> Callable[[Callable[_P, _R]], Callable[_P, AssemblyBuildResult]] | Callable[_P, AssemblyBuildResult] +def assemble(func: Callable[_P, _R] | None = None, *, id: str | None = None, revision: str = '1.0.0', definitions: Sequence[Any] = (), cache: CachePolicy | Mapping[str, Any] | str | None = None, project_root: str | Path | None = None, tolerance_profile: str = 'simplecad-default') -> Callable[[Callable[_P, _R]], Callable[_P, AssemblyBuildResult]] | Callable[_P, AssemblyBuildResult] ``` *Source: build/assembly_builder.py* diff --git a/skills/simplecadapi/references/docs/api/capture.md b/skills/simplecadapi/references/docs/api/capture.md new file mode 100644 index 00000000..94e50ea8 --- /dev/null +++ b/skills/simplecadapi/references/docs/api/capture.md @@ -0,0 +1,17 @@ +# capture + +## API Definition + +```python +def capture(result: Any, path: str | Path, /) -> CaptureResult +``` + +*Source: capture.py* + +## Import Surface + +- top-level: `from simplecadapi import capture` + +## Description + +Capture a durable product and write its canonical `.scadpkg`. diff --git a/skills/simplecadapi/references/docs/api/capture_result.md b/skills/simplecadapi/references/docs/api/capture_result.md deleted file mode 100644 index 942c6e80..00000000 --- a/skills/simplecadapi/references/docs/api/capture_result.md +++ /dev/null @@ -1,17 +0,0 @@ -# capture_result - -## API Definition - -```python -def capture_result(*, value: Any) -> Any -``` - -*Source: graph.py* - -## Import Surface - -- top-level: `from simplecadapi import capture_result` - -## Description - -Capture *value* as an explicit result in the active model session. diff --git a/skills/simplecadapi/references/docs/api/clear_step_model_cache_rnone.md b/skills/simplecadapi/references/docs/api/clear_step_model_cache_rnone.md index 70c243ba..8ed290cb 100644 --- a/skills/simplecadapi/references/docs/api/clear_step_model_cache_rnone.md +++ b/skills/simplecadapi/references/docs/api/clear_step_model_cache_rnone.md @@ -10,7 +10,7 @@ def clear_step_model_cache_rnone() -> None ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.clear_step_model_cache_rnone(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.clear_step_model_cache_rnone(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/compare_boundary_distance_rdescriptor.md b/skills/simplecadapi/references/docs/api/compare_boundary_distance_rdescriptor.md index 4641a383..19174a8f 100644 --- a/skills/simplecadapi/references/docs/api/compare_boundary_distance_rdescriptor.md +++ b/skills/simplecadapi/references/docs/api/compare_boundary_distance_rdescriptor.md @@ -10,7 +10,7 @@ def compare_boundary_distance_rdescriptor(target: ModelInput, current: ModelInpu ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_boundary_distance_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_boundary_distance_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/compare_entities_rdescriptor.md b/skills/simplecadapi/references/docs/api/compare_entities_rdescriptor.md index f954b08d..a27360af 100644 --- a/skills/simplecadapi/references/docs/api/compare_entities_rdescriptor.md +++ b/skills/simplecadapi/references/docs/api/compare_entities_rdescriptor.md @@ -10,7 +10,7 @@ def compare_entities_rdescriptor(target: ModelInput, target_entity_id: str, curr ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_entities_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_entities_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/compare_global_properties_rdescriptor.md b/skills/simplecadapi/references/docs/api/compare_global_properties_rdescriptor.md index b7b57db6..bfabbbd3 100644 --- a/skills/simplecadapi/references/docs/api/compare_global_properties_rdescriptor.md +++ b/skills/simplecadapi/references/docs/api/compare_global_properties_rdescriptor.md @@ -10,7 +10,7 @@ def compare_global_properties_rdescriptor(target: ModelInput, current: ModelInpu ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_global_properties_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_global_properties_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/compare_inspections_rinspectionsummarycomparison.md b/skills/simplecadapi/references/docs/api/compare_inspections_rinspectionsummarycomparison.md index 29611589..a67187a5 100644 --- a/skills/simplecadapi/references/docs/api/compare_inspections_rinspectionsummarycomparison.md +++ b/skills/simplecadapi/references/docs/api/compare_inspections_rinspectionsummarycomparison.md @@ -10,7 +10,7 @@ def compare_inspections_rinspectionsummarycomparison(target: BRepInspection, can ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_inspections_rinspectionsummarycomparison(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_inspections_rinspectionsummarycomparison(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/compare_material_rdescriptor.md b/skills/simplecadapi/references/docs/api/compare_material_rdescriptor.md index 5121f010..3c0ee100 100644 --- a/skills/simplecadapi/references/docs/api/compare_material_rdescriptor.md +++ b/skills/simplecadapi/references/docs/api/compare_material_rdescriptor.md @@ -10,7 +10,7 @@ def compare_material_rdescriptor(target: ModelInput, current: ModelInput, *, boo ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_material_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_material_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/compare_model_to_inspection_rentityinspectionparity.md b/skills/simplecadapi/references/docs/api/compare_model_to_inspection_rentityinspectionparity.md index ae9beeac..07861031 100644 --- a/skills/simplecadapi/references/docs/api/compare_model_to_inspection_rentityinspectionparity.md +++ b/skills/simplecadapi/references/docs/api/compare_model_to_inspection_rentityinspectionparity.md @@ -10,7 +10,7 @@ def compare_model_to_inspection_rentityinspectionparity(model: BRepModel, report ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_model_to_inspection_rentityinspectionparity(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_model_to_inspection_rentityinspectionparity(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/compare_sections_rdescriptor.md b/skills/simplecadapi/references/docs/api/compare_sections_rdescriptor.md index 0390ead6..e786ee9a 100644 --- a/skills/simplecadapi/references/docs/api/compare_sections_rdescriptor.md +++ b/skills/simplecadapi/references/docs/api/compare_sections_rdescriptor.md @@ -10,7 +10,7 @@ def compare_sections_rdescriptor(target: ModelInput, current: ModelInput, plane_ ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_sections_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_sections_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/compare_shape_slices_rslicecomparison.md b/skills/simplecadapi/references/docs/api/compare_shape_slices_rslicecomparison.md index b85e8e54..53ab45a0 100644 --- a/skills/simplecadapi/references/docs/api/compare_shape_slices_rslicecomparison.md +++ b/skills/simplecadapi/references/docs/api/compare_shape_slices_rslicecomparison.md @@ -10,7 +10,7 @@ def compare_shape_slices_rslicecomparison(target: TopoDS_Shape, candidate: TopoD ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_shape_slices_rslicecomparison(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_shape_slices_rslicecomparison(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/compare_shapes_rbrepcomparison.md b/skills/simplecadapi/references/docs/api/compare_shapes_rbrepcomparison.md index cb33aa7e..2fbbc9bf 100644 --- a/skills/simplecadapi/references/docs/api/compare_shapes_rbrepcomparison.md +++ b/skills/simplecadapi/references/docs/api/compare_shapes_rbrepcomparison.md @@ -10,7 +10,7 @@ def compare_shapes_rbrepcomparison(target: TopoDS_Shape, candidate: TopoDS_Shape ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_shapes_rbrepcomparison(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_shapes_rbrepcomparison(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/compare_step_slices_rslicecomparison.md b/skills/simplecadapi/references/docs/api/compare_step_slices_rslicecomparison.md index e96fccc7..f35b1939 100644 --- a/skills/simplecadapi/references/docs/api/compare_step_slices_rslicecomparison.md +++ b/skills/simplecadapi/references/docs/api/compare_step_slices_rslicecomparison.md @@ -10,7 +10,7 @@ def compare_step_slices_rslicecomparison(target_path: str | Path, candidate_path ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_step_slices_rslicecomparison(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_step_slices_rslicecomparison(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/compare_step_to_inspection_rentityinspectionparity.md b/skills/simplecadapi/references/docs/api/compare_step_to_inspection_rentityinspectionparity.md index d947cb6f..794f212c 100644 --- a/skills/simplecadapi/references/docs/api/compare_step_to_inspection_rentityinspectionparity.md +++ b/skills/simplecadapi/references/docs/api/compare_step_to_inspection_rentityinspectionparity.md @@ -10,7 +10,7 @@ def compare_step_to_inspection_rentityinspectionparity(step_path: str | Path, re ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_step_to_inspection_rentityinspectionparity(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_step_to_inspection_rentityinspectionparity(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/compare_steps_rbrepcomparison.md b/skills/simplecadapi/references/docs/api/compare_steps_rbrepcomparison.md index 9b9f0c69..6fde7668 100644 --- a/skills/simplecadapi/references/docs/api/compare_steps_rbrepcomparison.md +++ b/skills/simplecadapi/references/docs/api/compare_steps_rbrepcomparison.md @@ -10,7 +10,7 @@ def compare_steps_rbrepcomparison(target_path: str | Path, candidate_path: str | ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_steps_rbrepcomparison(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.compare_steps_rbrepcomparison(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/evaluate_reconstruction_rdescriptor.md b/skills/simplecadapi/references/docs/api/evaluate_reconstruction_rdescriptor.md index a674882c..35bc52eb 100644 --- a/skills/simplecadapi/references/docs/api/evaluate_reconstruction_rdescriptor.md +++ b/skills/simplecadapi/references/docs/api/evaluate_reconstruction_rdescriptor.md @@ -10,7 +10,7 @@ def evaluate_reconstruction_rdescriptor(target: ModelInput, current: ModelInput, ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.evaluate_reconstruction_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.evaluate_reconstruction_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/export_model_json_to_fcstd.md b/skills/simplecadapi/references/docs/api/export_model_json_to_fcstd.md deleted file mode 100644 index f2f35fca..00000000 --- a/skills/simplecadapi/references/docs/api/export_model_json_to_fcstd.md +++ /dev/null @@ -1,17 +0,0 @@ -# export_model_json_to_fcstd - -## API Definition - -```python -def export_model_json_to_fcstd(json_str: str, output_path: str, *, document_name: str = 'SimpleCADModel', freecad_cmd: Optional[str] = None) -> str -``` - -*Source: translator/freecad_translator/api.py* - -## Import Surface - -- translator backend: `from simplecadapi.translator.freecad_translator import export_model_json_to_fcstd` - -## Description - -Export canonical model JSON to `.FCStd` via FreeCADCmd/FreeCAD. diff --git a/skills/simplecadapi/references/docs/api/export_model_json_to_solidworks_step.md b/skills/simplecadapi/references/docs/api/export_model_json_to_solidworks_step.md deleted file mode 100644 index c9ee857b..00000000 --- a/skills/simplecadapi/references/docs/api/export_model_json_to_solidworks_step.md +++ /dev/null @@ -1,17 +0,0 @@ -# export_model_json_to_solidworks_step - -## API Definition - -```python -def export_model_json_to_solidworks_step(json_str: str, output_path: str, *, document_name: str = 'SimpleCADModel', visible: bool = False, python_exe: Optional[str] = None, source_kernel_fallback: bool = False) -> str -``` - -*Source: translator/solidworks_translator/api.py* - -## Import Surface - -- translator backend: `from simplecadapi.translator.solidworks_translator import export_model_json_to_solidworks_step` - -## Description - -Execute SolidWorks COM automation and export a STEP file. diff --git a/skills/simplecadapi/references/docs/api/export_product_package.md b/skills/simplecadapi/references/docs/api/export_product_package.md deleted file mode 100644 index 8a903d05..00000000 --- a/skills/simplecadapi/references/docs/api/export_product_package.md +++ /dev/null @@ -1,17 +0,0 @@ -# export_product_package - -## API Definition - -```python -def export_product_package(package: ProductPackage, path: str | Path) -> Path -``` - -*Source: product_packages.py* - -## Import Surface - -- top-level: `from simplecadapi import export_product_package` - -## Description - -Write one canonical self-contained `.scadpkg` archive. diff --git a/skills/simplecadapi/references/docs/api/export_product_package_to_step.md b/skills/simplecadapi/references/docs/api/export_product_package_to_step.md new file mode 100644 index 00000000..6882ff1a --- /dev/null +++ b/skills/simplecadapi/references/docs/api/export_product_package_to_step.md @@ -0,0 +1,17 @@ +# export_product_package_to_step + +## API Definition + +```python +def export_product_package_to_step(data: ProductPackageInput, output_path: str | Path) -> ProductSTEPExportReport +``` + +*Source: exporter/step.py* + +## Import Surface + +- exporter namespace: `from simplecadapi import exporter` then `exporter.step.export_product_package_to_step(...)` + +## Description + +Export a validated `.scadpkg` closure as XCAF-backed AP242 STEP. diff --git a/skills/simplecadapi/references/docs/api/export_product_package_to_stl.md b/skills/simplecadapi/references/docs/api/export_product_package_to_stl.md new file mode 100644 index 00000000..922d7308 --- /dev/null +++ b/skills/simplecadapi/references/docs/api/export_product_package_to_stl.md @@ -0,0 +1,20 @@ +# export_product_package_to_stl + +## API Definition + +```python +def export_product_package_to_stl(data: ProductPackageInput, output_path: str | Path, *, mesh_size: float = 1.0, recombination_angle_degrees: float = 45.0) -> ProductSTLExportReport +``` + +*Source: exporter/stl.py* + +## Import Surface + +- exporter namespace: `from simplecadapi import exporter` then `exporter.stl.export_product_package_to_stl(...)` + +## Description + +Export one validated `.scadpkg` as a quad-dominant remeshed STL. + +Gmsh recombines each CAD surface into quadrilaterals before its STL writer +splits every quad into two triangles, as required by the STL file format. diff --git a/skills/simplecadapi/references/docs/api/export_step.md b/skills/simplecadapi/references/docs/api/export_step.md deleted file mode 100644 index 40ae34f4..00000000 --- a/skills/simplecadapi/references/docs/api/export_step.md +++ /dev/null @@ -1,50 +0,0 @@ -# export_step - -## API Definition - -```python -def export_step(shapes: Union[AnyShape, Sequence[AnyShape]], filename: str) -> None -``` - -*Source: operations.py* - -## Import Surface - -- top-level: `from simplecadapi import export_step` - -## Description - -Export shapes to STEP. - -Use this function when you want to export one shape or many shapes into the -same STEP file. Passing `List[Solid]` is valid for pattern outputs or -explicit shape collections. Boolean operations return a single `Solid`. - -## Parameters - -### shapes - -- **Description**: A single exportable shape or any nested sequence of exportable shapes. Lists of Solid are supported directly, including pattern or explicitly collected multi-shape results. - -### filename - -- **Description**: Output STEP file path. - -## Returns - -None: Writes the provided shapes into one STEP file. - -## Examples - -### Example 1 -```python -main_body = make_box_rsolid(10, 4, 4, bottom_face_center=(0, 0, 0)) -left_cap = make_sphere_rsolid(2.0, center=(-2.0, 2.0, 2.0)) -right_cap = make_sphere_rsolid(2.0, center=(12.0, 2.0, 2.0)) -body = union_rsolid(main_body, [left_cap, right_cap]) -``` - -### Example 2 -```python -export_step(body, "rounded_bar.step") -``` diff --git a/skills/simplecadapi/references/docs/api/export_stl.md b/skills/simplecadapi/references/docs/api/export_stl.md deleted file mode 100644 index fb9f6bca..00000000 --- a/skills/simplecadapi/references/docs/api/export_stl.md +++ /dev/null @@ -1,50 +0,0 @@ -# export_stl - -## API Definition - -```python -def export_stl(shapes: Union[AnyShape, Sequence[AnyShape]], filename: str) -> None -``` - -*Source: operations.py* - -## Import Surface - -- top-level: `from simplecadapi import export_stl` - -## Description - -Export shapes to STL. - -Use this function when you want to export one compound, solid, or face into -the same STL file. Passing `List[Solid]` is valid for pattern outputs or -explicit shape collections. Boolean operations return a single `Solid`. - -## Parameters - -### shapes - -- **Description**: A single Compound, Solid, or Face, or any nested sequence of those. Lists of Solid are supported directly, including pattern or explicitly collected multi-shape results. - -### filename - -- **Description**: Output STL file path. - -## Returns - -None: Writes the provided shapes into one STL file. - -## Examples - -### Example 1 -```python -main_body = make_box_rsolid(10, 4, 4, bottom_face_center=(0, 0, 0)) -left_cap = make_sphere_rsolid(2.0, center=(-2.0, 2.0, 2.0)) -right_cap = make_sphere_rsolid(2.0, center=(12.0, 2.0, 2.0)) -body = union_rsolid(main_body, [left_cap, right_cap]) -``` - -### Example 2 -```python -export_stl(body, "rounded_bar.stl") -``` diff --git a/skills/simplecadapi/references/docs/api/index_shape_rbrepmodel.md b/skills/simplecadapi/references/docs/api/index_shape_rbrepmodel.md index dd615099..42c2e0e9 100644 --- a/skills/simplecadapi/references/docs/api/index_shape_rbrepmodel.md +++ b/skills/simplecadapi/references/docs/api/index_shape_rbrepmodel.md @@ -10,7 +10,7 @@ def index_shape_rbrepmodel(shape: TopoDS_Shape, *, source: str | Path | None = N ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.index_shape_rbrepmodel(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.index_shape_rbrepmodel(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/inspect_difference_regions_rdescriptor.md b/skills/simplecadapi/references/docs/api/inspect_difference_regions_rdescriptor.md index 51f201e8..12dac091 100644 --- a/skills/simplecadapi/references/docs/api/inspect_difference_regions_rdescriptor.md +++ b/skills/simplecadapi/references/docs/api/inspect_difference_regions_rdescriptor.md @@ -10,7 +10,7 @@ def inspect_difference_regions_rdescriptor(target: ModelInput, current: ModelInp ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_difference_regions_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_difference_regions_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/inspect_face_boundaries_rdescriptor.md b/skills/simplecadapi/references/docs/api/inspect_face_boundaries_rdescriptor.md index bb28c35e..e065fb78 100644 --- a/skills/simplecadapi/references/docs/api/inspect_face_boundaries_rdescriptor.md +++ b/skills/simplecadapi/references/docs/api/inspect_face_boundaries_rdescriptor.md @@ -10,7 +10,7 @@ def inspect_face_boundaries_rdescriptor(model_or_path: BRepModel | TopoDS_Shape ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_face_boundaries_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_face_boundaries_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/inspect_nearby_entities_rdescriptor.md b/skills/simplecadapi/references/docs/api/inspect_nearby_entities_rdescriptor.md index 0709fd82..5a60d48a 100644 --- a/skills/simplecadapi/references/docs/api/inspect_nearby_entities_rdescriptor.md +++ b/skills/simplecadapi/references/docs/api/inspect_nearby_entities_rdescriptor.md @@ -10,7 +10,7 @@ def inspect_nearby_entities_rdescriptor(model: ModelInput, *, location: Sequence ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_nearby_entities_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_nearby_entities_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/inspect_point_rdescriptor.md b/skills/simplecadapi/references/docs/api/inspect_point_rdescriptor.md index 11a66545..2612aa82 100644 --- a/skills/simplecadapi/references/docs/api/inspect_point_rdescriptor.md +++ b/skills/simplecadapi/references/docs/api/inspect_point_rdescriptor.md @@ -10,7 +10,7 @@ def inspect_point_rdescriptor(model_or_path: BRepModel | TopoDS_Shape | str | Pa ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_point_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_point_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/inspect_section_rdescriptor.md b/skills/simplecadapi/references/docs/api/inspect_section_rdescriptor.md index c2abcba7..30c0b060 100644 --- a/skills/simplecadapi/references/docs/api/inspect_section_rdescriptor.md +++ b/skills/simplecadapi/references/docs/api/inspect_section_rdescriptor.md @@ -10,7 +10,7 @@ def inspect_section_rdescriptor(model_or_path: BRepModel | TopoDS_Shape | str | ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_section_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_section_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/inspect_shape_rbrepinspection.md b/skills/simplecadapi/references/docs/api/inspect_shape_rbrepinspection.md index e1a77261..c97ffc4d 100644 --- a/skills/simplecadapi/references/docs/api/inspect_shape_rbrepinspection.md +++ b/skills/simplecadapi/references/docs/api/inspect_shape_rbrepinspection.md @@ -10,7 +10,7 @@ def inspect_shape_rbrepinspection(shape: TopoDS_Shape, *, source: str | Path | N ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_shape_rbrepinspection(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_shape_rbrepinspection(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/inspect_step_components_rdescriptorlist.md b/skills/simplecadapi/references/docs/api/inspect_step_components_rdescriptorlist.md index 367b0adc..d107ed3d 100644 --- a/skills/simplecadapi/references/docs/api/inspect_step_components_rdescriptorlist.md +++ b/skills/simplecadapi/references/docs/api/inspect_step_components_rdescriptorlist.md @@ -10,7 +10,7 @@ def inspect_step_components_rdescriptorlist(step_path: str | Path) -> list[dict[ ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_step_components_rdescriptorlist(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_step_components_rdescriptorlist(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/inspect_step_entity_rdescriptor.md b/skills/simplecadapi/references/docs/api/inspect_step_entity_rdescriptor.md index 622794f3..1b4b3a77 100644 --- a/skills/simplecadapi/references/docs/api/inspect_step_entity_rdescriptor.md +++ b/skills/simplecadapi/references/docs/api/inspect_step_entity_rdescriptor.md @@ -10,7 +10,7 @@ def inspect_step_entity_rdescriptor(path: str | Path, entity_id: str, *, include ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_step_entity_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_step_entity_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/inspect_step_rbrepinspection.md b/skills/simplecadapi/references/docs/api/inspect_step_rbrepinspection.md index 39ac34db..cc529692 100644 --- a/skills/simplecadapi/references/docs/api/inspect_step_rbrepinspection.md +++ b/skills/simplecadapi/references/docs/api/inspect_step_rbrepinspection.md @@ -10,7 +10,7 @@ def inspect_step_rbrepinspection(path: str | Path) -> BRepInspection ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_step_rbrepinspection(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_step_rbrepinspection(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/inspect_step_rsummary.md b/skills/simplecadapi/references/docs/api/inspect_step_rsummary.md index 42f569bb..9ff396b2 100644 --- a/skills/simplecadapi/references/docs/api/inspect_step_rsummary.md +++ b/skills/simplecadapi/references/docs/api/inspect_step_rsummary.md @@ -10,7 +10,7 @@ def inspect_step_rsummary(path: str | Path, *, include_parameter_groups: bool = ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_step_rsummary(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_step_rsummary(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/inspect_topology_neighborhood_rdescriptor.md b/skills/simplecadapi/references/docs/api/inspect_topology_neighborhood_rdescriptor.md index b0b5ffb9..f7485d3f 100644 --- a/skills/simplecadapi/references/docs/api/inspect_topology_neighborhood_rdescriptor.md +++ b/skills/simplecadapi/references/docs/api/inspect_topology_neighborhood_rdescriptor.md @@ -10,7 +10,7 @@ def inspect_topology_neighborhood_rdescriptor(model_or_path: BRepModel | TopoDS_ ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_topology_neighborhood_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.inspect_topology_neighborhood_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/load_step_rbrepmodel.md b/skills/simplecadapi/references/docs/api/load_step_rbrepmodel.md index 8b0459a6..9eb7cbf0 100644 --- a/skills/simplecadapi/references/docs/api/load_step_rbrepmodel.md +++ b/skills/simplecadapi/references/docs/api/load_step_rbrepmodel.md @@ -10,7 +10,7 @@ def load_step_rbrepmodel(path: str | Path) -> BRepModel ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.load_step_rbrepmodel(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.load_step_rbrepmodel(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/load_step_rshape.md b/skills/simplecadapi/references/docs/api/load_step_rshape.md index 0fc91ecb..6cafd213 100644 --- a/skills/simplecadapi/references/docs/api/load_step_rshape.md +++ b/skills/simplecadapi/references/docs/api/load_step_rshape.md @@ -10,7 +10,7 @@ def load_step_rshape(path: str | Path, *, require_single_root: bool = True, requ ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.load_step_rshape(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.load_step_rshape(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/make_center_slice_specs_rslicespeclist.md b/skills/simplecadapi/references/docs/api/make_center_slice_specs_rslicespeclist.md index 4aa04c0b..87a807ca 100644 --- a/skills/simplecadapi/references/docs/api/make_center_slice_specs_rslicespeclist.md +++ b/skills/simplecadapi/references/docs/api/make_center_slice_specs_rslicespeclist.md @@ -10,7 +10,7 @@ def make_center_slice_specs_rslicespeclist(minimum: np.ndarray, maximum: np.ndar ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.make_center_slice_specs_rslicespeclist(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.make_center_slice_specs_rslicespeclist(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/measure_entity_relation_rdescriptor.md b/skills/simplecadapi/references/docs/api/measure_entity_relation_rdescriptor.md index 6013645c..2f489760 100644 --- a/skills/simplecadapi/references/docs/api/measure_entity_relation_rdescriptor.md +++ b/skills/simplecadapi/references/docs/api/measure_entity_relation_rdescriptor.md @@ -10,7 +10,7 @@ def measure_entity_relation_rdescriptor(model_or_path: BRepModel | TopoDS_Shape ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.measure_entity_relation_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.measure_entity_relation_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/measure_shape_mass_rtuple.md b/skills/simplecadapi/references/docs/api/measure_shape_mass_rtuple.md index 42216d59..ce2f74e4 100644 --- a/skills/simplecadapi/references/docs/api/measure_shape_mass_rtuple.md +++ b/skills/simplecadapi/references/docs/api/measure_shape_mass_rtuple.md @@ -10,7 +10,7 @@ def measure_shape_mass_rtuple(shape: TopoDS_Shape, kind: PropertyKind) -> tuple[ ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.measure_shape_mass_rtuple(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.measure_shape_mass_rtuple(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/model.md b/skills/simplecadapi/references/docs/api/model.md deleted file mode 100644 index 0339b1ab..00000000 --- a/skills/simplecadapi/references/docs/api/model.md +++ /dev/null @@ -1,17 +0,0 @@ -# model - -## API Definition - -```python -def model(func: Optional[Callable[_P, _R]] = None, *, graph_id: Optional[str] = None, export_dir: str | Path | None = None) -> Union[Callable[[Callable[_P, _R]], Callable[_P, ModelResult]], Callable[_P, ModelResult]] -``` - -*Source: graph.py* - -## Import Surface - -- top-level: `from simplecadapi import model` - -## Description - -Decorate a top-level model function with one owned ``GraphSession``. diff --git a/skills/simplecadapi/references/docs/api/part_function.md b/skills/simplecadapi/references/docs/api/part_function.md index 2108b717..82d70405 100644 --- a/skills/simplecadapi/references/docs/api/part_function.md +++ b/skills/simplecadapi/references/docs/api/part_function.md @@ -3,7 +3,7 @@ ## API Definition ```python -def part(func: Callable[_P, _R] | None = None, *, id: str | None = None, revision: str = '1.0.0', inputs: Sequence[FileInput] = (), cache: CachePolicy | Mapping[str, Any] | str | None = None, export_dir: str | Path | None = None, project_root: str | Path | None = None, tolerance_profile: str = 'simplecad-default') -> Callable[[Callable[_P, _R]], Callable[_P, PartBuildResult]] | Callable[_P, PartBuildResult] +def part(func: Callable[_P, _R] | None = None, *, id: str | None = None, revision: str = '1.0.0', inputs: Sequence[FileInput] = (), cache: CachePolicy | Mapping[str, Any] | str | None = None, project_root: str | Path | None = None, tolerance_profile: str = 'simplecad-default') -> Callable[[Callable[_P, _R]], Callable[_P, PartBuildResult]] | Callable[_P, PartBuildResult] ``` *Source: build/part_builder.py* diff --git a/skills/simplecadapi/references/docs/api/render_entity_kind_maps_rpath.md b/skills/simplecadapi/references/docs/api/render_entity_kind_maps_rpath.md index 0d0f831b..9a142601 100644 --- a/skills/simplecadapi/references/docs/api/render_entity_kind_maps_rpath.md +++ b/skills/simplecadapi/references/docs/api/render_entity_kind_maps_rpath.md @@ -10,7 +10,7 @@ def render_entity_kind_maps_rpath(model_or_path: BRepModel | TopoDS_Shape | str ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_entity_kind_maps_rpath(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_entity_kind_maps_rpath(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/render_entity_map_rpath.md b/skills/simplecadapi/references/docs/api/render_entity_map_rpath.md index c11ca2ea..3e27f77c 100644 --- a/skills/simplecadapi/references/docs/api/render_entity_map_rpath.md +++ b/skills/simplecadapi/references/docs/api/render_entity_map_rpath.md @@ -10,7 +10,7 @@ def render_entity_map_rpath(model_or_path: BRepModel | TopoDS_Shape | str | Path ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_entity_map_rpath(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_entity_map_rpath(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/render_region_rpath.md b/skills/simplecadapi/references/docs/api/render_region_rpath.md index bf89ab47..f7d90b54 100644 --- a/skills/simplecadapi/references/docs/api/render_region_rpath.md +++ b/skills/simplecadapi/references/docs/api/render_region_rpath.md @@ -10,7 +10,7 @@ def render_region_rpath(model_or_path: BRepModel | TopoDS_Shape | str | Path, en ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_region_rpath(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_region_rpath(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/render_shape_views_rpath.md b/skills/simplecadapi/references/docs/api/render_shape_views_rpath.md index 044a6dcc..3afb565b 100644 --- a/skills/simplecadapi/references/docs/api/render_shape_views_rpath.md +++ b/skills/simplecadapi/references/docs/api/render_shape_views_rpath.md @@ -10,7 +10,7 @@ def render_shape_views_rpath(shape: TopoDS_Shape, output_path: str | Path, *, ti ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_shape_views_rpath(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_shape_views_rpath(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/render_step_components_colored_rpath.md b/skills/simplecadapi/references/docs/api/render_step_components_colored_rpath.md index 262bd5bb..45c86842 100644 --- a/skills/simplecadapi/references/docs/api/render_step_components_colored_rpath.md +++ b/skills/simplecadapi/references/docs/api/render_step_components_colored_rpath.md @@ -10,7 +10,7 @@ def render_step_components_colored_rpath(step_path: str | Path, component_colors ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_step_components_colored_rpath(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_step_components_colored_rpath(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/render_step_components_rpath.md b/skills/simplecadapi/references/docs/api/render_step_components_rpath.md index 13f76237..534a0368 100644 --- a/skills/simplecadapi/references/docs/api/render_step_components_rpath.md +++ b/skills/simplecadapi/references/docs/api/render_step_components_rpath.md @@ -10,7 +10,7 @@ def render_step_components_rpath(step_path: str | Path, component_names: Sequenc ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_step_components_rpath(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_step_components_rpath(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/render_step_views_rpath.md b/skills/simplecadapi/references/docs/api/render_step_views_rpath.md index de144795..60730573 100644 --- a/skills/simplecadapi/references/docs/api/render_step_views_rpath.md +++ b/skills/simplecadapi/references/docs/api/render_step_views_rpath.md @@ -10,7 +10,7 @@ def render_step_views_rpath(step_path: str | Path, output_path: str | Path, **kw ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_step_views_rpath(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.render_step_views_rpath(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/requires_session.md b/skills/simplecadapi/references/docs/api/requires_session.md deleted file mode 100644 index ceeaa9ea..00000000 --- a/skills/simplecadapi/references/docs/api/requires_session.md +++ /dev/null @@ -1,17 +0,0 @@ -# requires_session - -## API Definition - -```python -def requires_session(func: Optional[Callable[_P, _R]] = None) -> Union[Callable[[Callable[_P, _R]], Callable[_P, _R]], Callable[_P, _R]] -``` - -*Source: graph.py* - -## Import Surface - -- top-level: `from simplecadapi import requires_session` - -## Description - -Decorate a builder that must reuse the caller's active GraphSession. diff --git a/skills/simplecadapi/references/docs/api/select_region_entities_rdescriptor.md b/skills/simplecadapi/references/docs/api/select_region_entities_rdescriptor.md index cc49d5f0..b9326ce7 100644 --- a/skills/simplecadapi/references/docs/api/select_region_entities_rdescriptor.md +++ b/skills/simplecadapi/references/docs/api/select_region_entities_rdescriptor.md @@ -10,7 +10,7 @@ def select_region_entities_rdescriptor(model_or_path: BRepModel | TopoDS_Shape | ## Import Surface -- inspection namespace: `from simplecadapi.inspect import brep` then `brep.select_region_entities_rdescriptor(...)`; unavailable inside GraphSession/@model +- inspection namespace: `from simplecadapi.inspect import brep` then `brep.select_region_entities_rdescriptor(...)`; unavailable inside GraphSession ## Description diff --git a/skills/simplecadapi/references/docs/api/translate_model_json_to_fcstd.md b/skills/simplecadapi/references/docs/api/translate_model_json_to_fcstd.md deleted file mode 100644 index b4d6627a..00000000 --- a/skills/simplecadapi/references/docs/api/translate_model_json_to_fcstd.md +++ /dev/null @@ -1,40 +0,0 @@ -# translate_model_json_to_fcstd - -## API Definition - -```python -def translate_model_json_to_fcstd(json_str: str, output_path: str, *, document_name: str = 'SimpleCADModel', freecad_cmd: Optional[str] = None) -> str -``` - -*Source: translator/freecad_translator/api.py* - -## Import Surface - -- translator backend: `from simplecadapi.translator.freecad_translator import translate_model_json_to_fcstd` - -## Description - -Translate canonical model JSON to `.FCStd` via FreeCADCmd/FreeCAD. - -Functional sketch promotions are written as visible `Sketcher::SketchObject` -nodes with mapped/skipped constraint evidence. Exact B-spline edges are -exported to FreeCAD using `Part.BSplineCurve().buildFromPolesMultsKnots(...)`. -Safe single-use profile transforms such as section rotate/translate chains are -folded into the section object's placement so downstream `Part::Loft` receives -already-positioned sections instead of placement-bearing `App::Link` proxies. -Geometry results use FreeCAD objects directly: assignment targets name design -objects and shared inputs receive independent occurrences per consumer. Native -features preserve recomputing dependencies, including surface-dependent -Booleans. Their classifications may vary across FreeCAD/OCCT versions. No -presentation proxy, duplicate history tree, or hidden graph-object archive is -created. -`apply_tag_rselection` remains graph metadata rather than a FreeCAD feature; -traceable geometry and visible result objects expose `SimpleCADAppliedTags`, -`SimpleCADTagBindings`, and `SimpleCADTagNodeIds`. -Part/Assembly product nodes are written as editable FreeCAD assembly structure: -parts use `App::Part`, assemblies use native `Assembly::AssemblyObject`, part -components use `App::Link`, and nested assembly components use -`Assembly::AssemblyLink`. Explicit assembly-to-compound projections remain -available for geometry workflows without creating a second user-facing root. -Link source definitions remain in the document for recomputation, but the -Tree View exposes only the resolved product or standalone-geometry roots. diff --git a/skills/simplecadapi/references/docs/api/translate_model_json_to_freecad_script.md b/skills/simplecadapi/references/docs/api/translate_model_json_to_freecad_script.md deleted file mode 100644 index 3ba89b97..00000000 --- a/skills/simplecadapi/references/docs/api/translate_model_json_to_freecad_script.md +++ /dev/null @@ -1,30 +0,0 @@ -# translate_model_json_to_freecad_script - -## API Definition - -```python -def translate_model_json_to_freecad_script(json_str: str, document_name: str = 'SimpleCADModel') -> str -``` - -*Source: translator/freecad_translator/api.py* - -## Import Surface - -- translator backend: `from simplecadapi.translator.freecad_translator import translate_model_json_to_freecad_script` - -## Description - -Translate exported model JSON into a FreeCAD Python script. - -Geometry is emitted as FreeCAD occurrence trees. Serialized source assignment -targets name native design objects, shared DAG inputs are copied per consuming -result, and feature links preserve dependencies. Booleans are emitted as native -recomputable `Part::Cut`, `Part::Fuse`, and `Part::Common` features. Stable node -ids remain available as internal metadata. -`apply_tag_rselection` nodes do not create FreeCAD features. Their canonical -bindings and source node ids are attached to traceable geometry and visible -result objects as `SimpleCADAppliedTags`, `SimpleCADTagBindings`, and -`SimpleCADTagNodeIds`. -The Tree View exposes only resolved product or standalone-geometry roots. -Assembly projection compounds and link source definitions remain available -for recomputation but are hidden from the user-facing document tree. diff --git a/skills/simplecadapi/references/docs/api/translate_model_json_to_fusion360_script.md b/skills/simplecadapi/references/docs/api/translate_model_json_to_fusion360_script.md deleted file mode 100644 index 05156ad7..00000000 --- a/skills/simplecadapi/references/docs/api/translate_model_json_to_fusion360_script.md +++ /dev/null @@ -1,17 +0,0 @@ -# translate_model_json_to_fusion360_script - -## API Definition - -```python -def translate_model_json_to_fusion360_script(json_str: str, document_name: str = 'SimpleCADModel', result_node_ids: Optional[Sequence[str]] = None, *, selection_mode: str = 'gsm', source_kernel_fallback: bool = False) -> str -``` - -*Source: translator/fusion360_translator/api.py* - -## Import Surface - -- translator backend: `from simplecadapi.translator.fusion360_translator import translate_model_json_to_fusion360_script` - -## Description - -Translate canonical model JSON into a Fusion 360 Python script. diff --git a/skills/simplecadapi/references/docs/api/translate_model_json_to_solidworks_script.md b/skills/simplecadapi/references/docs/api/translate_model_json_to_solidworks_script.md deleted file mode 100644 index c1a58832..00000000 --- a/skills/simplecadapi/references/docs/api/translate_model_json_to_solidworks_script.md +++ /dev/null @@ -1,17 +0,0 @@ -# translate_model_json_to_solidworks_script - -## API Definition - -```python -def translate_model_json_to_solidworks_script(json_str: str, document_name: str = 'SimpleCADModel', *, output_path: Optional[str] = None, visible: bool = False, source_kernel_fallback: bool = False) -> str -``` - -*Source: translator/solidworks_translator/api.py* - -## Import Surface - -- translator backend: `from simplecadapi.translator.solidworks_translator import translate_model_json_to_solidworks_script` - -## Description - -Translate canonical model JSON into a SolidWorks automation script. diff --git a/skills/simplecadapi/references/docs/api/translate_product_package_to_fcstd.md b/skills/simplecadapi/references/docs/api/translate_product_package_to_fcstd.md new file mode 100644 index 00000000..7dc48cf1 --- /dev/null +++ b/skills/simplecadapi/references/docs/api/translate_product_package_to_fcstd.md @@ -0,0 +1,17 @@ +# translate_product_package_to_fcstd + +## API Definition + +```python +def translate_product_package_to_fcstd(data: ProductPackageInput, output_path: str, *, document_name: str = 'SimpleCADProduct', freecad_cmd: Optional[str] = None) -> str +``` + +*Source: translator/freecad_translator/api.py* + +## Import Surface + +- translator backend: `from simplecadapi.translator.freecad_translator import translate_product_package_to_fcstd` + +## Description + +Translate one validated `.scadpkg` closure into an editable `.FCStd`. diff --git a/skills/simplecadapi/references/docs/api/translate_product_package_to_freecad_script.md b/skills/simplecadapi/references/docs/api/translate_product_package_to_freecad_script.md new file mode 100644 index 00000000..b4c82c63 --- /dev/null +++ b/skills/simplecadapi/references/docs/api/translate_product_package_to_freecad_script.md @@ -0,0 +1,17 @@ +# translate_product_package_to_freecad_script + +## API Definition + +```python +def translate_product_package_to_freecad_script(data: ProductPackageInput, document_name: str = 'SimpleCADProduct') -> str +``` + +*Source: translator/freecad_translator/api.py* + +## Import Surface + +- translator backend: `from simplecadapi.translator.freecad_translator import translate_product_package_to_freecad_script` + +## Description + +Translate one validated `.scadpkg` closure into a FreeCAD script. diff --git a/skills/simplecadapi/references/docs/api/translate_product_package_to_fusion360_script.md b/skills/simplecadapi/references/docs/api/translate_product_package_to_fusion360_script.md new file mode 100644 index 00000000..5ed70116 --- /dev/null +++ b/skills/simplecadapi/references/docs/api/translate_product_package_to_fusion360_script.md @@ -0,0 +1,17 @@ +# translate_product_package_to_fusion360_script + +## API Definition + +```python +def translate_product_package_to_fusion360_script(data: ProductPackageInput, document_name: str = 'SimpleCADProduct', *, selection_mode: str = 'gsm', source_kernel_fallback: bool = False) -> str +``` + +*Source: translator/fusion360_translator/api.py* + +## Import Surface + +- translator backend: `from simplecadapi.translator.fusion360_translator import translate_product_package_to_fusion360_script` + +## Description + +Translate one validated `.scadpkg` closure into a Fusion 360 script. diff --git a/skills/simplecadapi/references/docs/api/translate_product_package_to_solidworks_script.md b/skills/simplecadapi/references/docs/api/translate_product_package_to_solidworks_script.md new file mode 100644 index 00000000..7d6f3736 --- /dev/null +++ b/skills/simplecadapi/references/docs/api/translate_product_package_to_solidworks_script.md @@ -0,0 +1,17 @@ +# translate_product_package_to_solidworks_script + +## API Definition + +```python +def translate_product_package_to_solidworks_script(data: ProductPackageInput, document_name: str = 'SimpleCADProduct', *, output_path: str | None = None, visible: bool = False, source_kernel_fallback: bool = False) -> str +``` + +*Source: translator/solidworks_translator/api.py* + +## Import Surface + +- translator backend: `from simplecadapi.translator.solidworks_translator import translate_product_package_to_solidworks_script` + +## Description + +Translate one validated `.scadpkg` closure into SolidWorks automation. diff --git a/skills/simplecadapi/references/docs/core/README.md b/skills/simplecadapi/references/docs/core/README.md index 90973c49..76383d1a 100644 --- a/skills/simplecadapi/references/docs/core/README.md +++ b/skills/simplecadapi/references/docs/core/README.md @@ -66,7 +66,7 @@ SimpleWorkplane ← local modeling context - **Shape-first API**: users work with `Vertex`, `Edge`, `Wire`, `Face`, `Shell`, and `Solid`, not graph nodes. - **Functional modeling style**: public operations return new geometry values, e.g. `make_box_rsolid(...)`, `cut_rsolid(...)`, `fillet_rsolid(...)`. - **OCP-native runtime**: geometry construction, topology traversal, properties, booleans, transforms, and export use OCP/OpenCascade helpers. -- **Replayable graph workflows**: `@scad.model` owns one `GraphSession` and returns a `ModelResult`; `@scad.requires_session` composes child builders, and `scad.capture_result()` selects canonical output nodes for replay and export. +- **Replayable graph workflows**: an explicit `GraphSession` records operations, `session.capture_result()` selects canonical output nodes, and `export_model_json()` plus `replay_model_json()` provide interchange and replay. - **Tags and metadata**: tags are useful for lightweight semantics; structured numeric facts should be stored in metadata such as `metadata["geo"]`. - **Indexed topology access**: use plural methods such as `get_edges()` and `get_faces()` for enumeration, and pass an index to the same getter, such as `get_edges(index)` or `get_faces(index)`, for intentional indexed picks that should become graph selection nodes. @@ -93,19 +93,18 @@ print(len(top_faces)) ```python import simplecadapi as scad +from simplecadapi import GraphSession, export_model_json, replay_model_json -@scad.model(graph_id="drilled_block") -def build_model(): +with GraphSession(graph_id="drilled_block") as session: body = scad.make_box_rsolid(width=10, height=10, depth=4) hole = scad.make_cylinder_rsolid( radius=1.5, height=8, bottom_face_center=(0, 0, -2) ) part = scad.cut_rsolid(body, hole) - scad.capture_result(value=part) - return part + session.capture_result(value=part) + payload = export_model_json(session=session) -result = build_model() -rebuilt = result.replay() +rebuilt = replay_model_json(json_str=payload) print(len(rebuilt)) ``` diff --git a/skills/simplecadapi/references/docs/core/declarative_constraints.md b/skills/simplecadapi/references/docs/core/declarative_constraints.md index b41dd979..cec8dd52 100644 --- a/skills/simplecadapi/references/docs/core/declarative_constraints.md +++ b/skills/simplecadapi/references/docs/core/declarative_constraints.md @@ -68,10 +68,10 @@ Removed public APIs include: - `stack_rassembly` - `stack` -Current supported workflows should model final parts as ordinary geometry: +Current supported workflows should model durable products through explicit boundaries: -- Use `translate_shape(...)`, `rotate_shape(...)`, and `mirror_shape(...)` for explicit placement. -- Use Python sequences of `Solid` objects plus `export_step([...], path)` / `export_stl(...)` for multi-body exports. +- Use `@scad.part` for one physical solid and `@scad.assemble` for a multi-part product. +- Use `scad.capture(result, path)` as the only public `.scadpkg` write boundary. - Use `union_rsolid(...)`, `cut_rsolid(...)`, and `intersect_rsolid(...)` when a single merged solid is required. `export_model_json(...)` no longer accepts `assembly=...`, and newly exported model JSON does not include `assembly`, `assembly_registry`, or `constraint_registry` fields. diff --git a/skills/simplecadapi/references/docs/core/serialization/README.md b/skills/simplecadapi/references/docs/core/serialization/README.md index a1a5bac6..ce3b5a6e 100644 --- a/skills/simplecadapi/references/docs/core/serialization/README.md +++ b/skills/simplecadapi/references/docs/core/serialization/README.md @@ -9,20 +9,19 @@ The long-form schema reference remains [`../operation_graph_json_spec.md`](../op ```python import json import simplecadapi as scad +from simplecadapi import GraphSession, export_model_json, replay_model_json -@scad.model(graph_id="drilled_block") -def build_model(): +with GraphSession(graph_id="drilled_block") as session: body = scad.make_box_rsolid(width=10, height=6, depth=2) hole = scad.make_cylinder_rsolid( radius=1, height=4, bottom_face_center=(0, 0, -1) ) result = scad.cut_rsolid(body, hole) - scad.capture_result(value=result) - return result + session.capture_result(value=result) + model_json = export_model_json(session=session) -model = build_model() -payload = json.loads(model.model_json) -rebuilt = model.replay() +payload = json.loads(model_json) +rebuilt = replay_model_json(json_str=model_json) ``` Inspect these fields: @@ -36,15 +35,12 @@ Inspect these fields: - `payload["expression_graph"]`: expression DAG used by expression-backed parameters. - `payload["tolerance_graph"]`: dimension-chain requirements and validation evidence. -For new top-level models, `ModelResult.model_json` is the preferred artifact -accessor. Use `@scad.requires_session` for reusable builders and -`scad.capture_result(...)` when the final output should not be inferred from -all graph leaves. If a model invocation also needs durable CAD/viewer files, -pass `export_dir=...` to `@scad.model`; its captured geometry/product values -then produce one self-contained `.scene.zip`. It embeds -`model/model.json`, mapped project-relative Python sources, and the evaluated -render/selection assets. It does not create adjacent model/session JSON, STEP, -STL, or FCStd files. No files are written when `export_dir` is omitted. +Use `session.capture_result(...)` when the final output should not be inferred +from all graph leaves, and treat `export_model_json(session=...)` as the +interchange boundary for direct graph workflows. Durable CAD/viewer products use +`@scad.part` or `@scad.assemble`, then `scad.capture(result, "out/product.scadpkg")` +to build and write one canonical self-contained package. No files are written +unless an export API is called. ## Important rule: source API is not always graph API diff --git a/skills/simplecadapi/references/docs/guides/README.md b/skills/simplecadapi/references/docs/guides/README.md index 4097f20c..f4dcb297 100644 --- a/skills/simplecadapi/references/docs/guides/README.md +++ b/skills/simplecadapi/references/docs/guides/README.md @@ -5,7 +5,8 @@ reusable prompt for controlled, comparable STEP reconstruction trials. - [Persistent Cache and Product Build Workflow](cache-build-workflow.md): durable `@part`/`@assemble` boundaries, PRT reuse, unified cache policy, - incremental invalidation, diagnostics, repair, and maintenance. + diagnostics, `.scadpkg` delivery, FreeCAD/AP242 targets, and optional Gmsh + volume meshing. The corresponding runnable module and examples live in: diff --git a/skills/simplecadapi/references/docs/guides/cache-build-workflow.md b/skills/simplecadapi/references/docs/guides/cache-build-workflow.md index 1a5abb5f..50023c37 100644 --- a/skills/simplecadapi/references/docs/guides/cache-build-workflow.md +++ b/skills/simplecadapi/references/docs/guides/cache-build-workflow.md @@ -61,10 +61,10 @@ fixture = build_fixture() print(fixture.solve_report.component_hits, fixture.solve_report.component_misses) ``` -`@scad.part` and `@scad.assemble` are top-level product boundaries and cannot be -nested inside an active `GraphSession`. Continue to use `@scad.model` plus -`@scad.requires_session` for a replayable geometry flow that is not a durable -part/assembly definition. +`@scad.part` and `@scad.assemble` are top-level product boundaries and each owns +its definition-local `GraphSession`; they cannot be nested inside another active +session. Use an explicit `GraphSession` for lower-level replayable geometry that +is not a durable part or assembly definition. ## Policy @@ -121,23 +121,68 @@ format. ## Product package export -`PartBuildResult` and `AssemblyBuildResult` export one public product format: -the canonical self-contained `.scadpkg` archive. It contains a thin -`package.json` manifest plus the complete content-addressed closure of canonical -`PartDefinition` and `AssemblyDefinition` archives. Repeated definitions are -stored once; assembly instances and relations remain in the ASM definitions. +`PartBuildResult` and `AssemblyBuildResult` are captured and written as one +canonical product package by a single API call: ```python -part_package = warm.export_artifacts(output_dir="out") -assembly_package = fixture.export_artifacts(output_dir="out") +scad.capture(warm, "out/part.scadpkg") +scad.capture(fixture, "out/assembly.scadpkg") -root = scad.load_product_package(assembly_package.artifact_paths["product"]) +root = scad.load_product_package("out/assembly.scadpkg") rebuilt = scad.materialize_definition(root) ``` -Use `build_product_package(...)`, `export_product_package(...)`, -`read_product_package(...)`, and `load_product_package(...)` for explicit -package handling. `validate_product_package(...)` verifies every object hash and -size, the complete recursive definition graph, cycle/depth limits, and rejects -missing or unreferenced objects. Keep `export_definition(...)` only for low-level -definition exchange or inspection; it is not the product delivery format. +Use `build_product_package(...)`, `encode_product_package(...)`, +`read_product_package(...)`, and `load_product_package(...)` only for explicit +in-memory package handling. `validate_product_package(...)` verifies every object +hash and size, the complete recursive definition graph, cycle/depth limits, and +rejects missing or unreferenced objects. Use `export_part_definition(...)` or +`export_assembly_definition(...)` only for low-level definition exchange or +inspection; neither is the product delivery format. + +## Downstream CAD and mesh targets + +Keep `.scadpkg` as the canonical SimpleCAD delivery artifact. Choose a +downstream target from the consumer contract: + +| Target | Use when | Preserved contract | Boundary | +| --- | --- | --- | --- | +| `.scadpkg` | Rebuild, replay, cache, or further SimpleCAD editing is required | Complete durable definition closure, feature graphs, source snapshots, topology, connectors, constraints, and materials | SimpleCAD-specific archive | +| `.FCStd` | A FreeCAD user needs an editable native document | Definition-owned, dependency-first native feature graphs; final body links; repeated instances; nested assemblies; names; solved placements; materials; connectors; constraints; grounding; revision; and content hashes | Requires FreeCADCmd/FreeCAD | +| AP242 `.step` | Neutral CAD exchange or downstream OpenCASCADE tooling is required | Evaluated BREP, product hierarchy, shared definitions, occurrence names/placements, materials, colors, density, and named SimpleCAD property payloads | Canonical feature history is not reconstructed as AP242 features | + +```python +package_path = assembly_package.artifact_paths["product"] + +fcstd_path = scad.translator.freecad_translator.translate_product_package_to_fcstd( + package_path, + "out/product.FCStd", +) +step_report = scad.exporter.export_product_package_to_step( + package_path, + "out/product.step", +) +stl_report = scad.exporter.export_product_package_to_stl( + package_path, + "out/product.stl", +) +print(step_report.definition_ids, step_report.occurrence_count) +print(stl_report.solid_count, stl_report.stl_triangle_count) +``` + +AP242 definition and occurrence metadata is stored in one standard +`PROPERTY_DEFINITION_REPRESENTATION`. Its named +`DESCRIPTIVE_REPRESENTATION_ITEM` records use +`SimpleCAD:definition::` and +`SimpleCAD:occurrence::`. Each description +is canonical sorted JSON containing durable IDs, revision, content hash, +connectors, constraints, grounding, name, and solved placement. +`ProductSTEPExportReport` reports the schema, definition IDs, occurrence +count, material IDs, metadata item count, and explicit limitations. + +For tetrahedral meshing, install `simplecadapi[gmsh]` and run +`examples/12_ap242_gmsh_volume_mesh.py`. The example exports one `.scadpkg`, +converts it to AP242 STEP, imports it with Gmsh's OpenCASCADE kernel, rejects +imports with no 3D volumes, generates a dimension-3 mesh, writes `.msh`, and +always finalizes Gmsh. Gmsh remains optional and is never imported by the core +SDK or the product exporters. diff --git a/skills/simplecadapi/references/docs/guides/reconstruction-agent-test-prompt.md b/skills/simplecadapi/references/docs/guides/reconstruction-agent-test-prompt.md index 205b5c31..8d2ce995 100644 --- a/skills/simplecadapi/references/docs/guides/reconstruction-agent-test-prompt.md +++ b/skills/simplecadapi/references/docs/guides/reconstruction-agent-test-prompt.md @@ -294,7 +294,7 @@ The program must: - run in a fresh process; - export `{CASE_NAME}_rebuilt.step` under `OUTPUT_DIR`; - produce a valid BREP; -- use `@scad.model` and strict replay when supported; +- record supported feature operations in an explicit `GraphSession` and verify strict replay; - clearly label exact transcription, fitting, and approximation. Prefer compact design intent over arbitrary point clouds. Do not describe a diff --git a/skills/simplecadapi/references/docs/guides/step-brep-reverse-engineering.md b/skills/simplecadapi/references/docs/guides/step-brep-reverse-engineering.md index a21c76cf..ca3ccbab 100644 --- a/skills/simplecadapi/references/docs/guides/step-brep-reverse-engineering.md +++ b/skills/simplecadapi/references/docs/guides/step-brep-reverse-engineering.md @@ -10,8 +10,8 @@ src/simplecadapi/inspect/brep/ All of these functions are diagnostic, tool-grade APIs, not modeling operations: they do not record graph nodes and must not run inside a -`GraphSession` or `@model` modeling script. Export or obtain the geometry -under test first, then call them outside the modeling script: +`GraphSession`. Export or obtain the geometry under test first, then call them +outside the modeling script: ```python from simplecadapi.inspect import brep diff --git a/skills/simplecadapi/references/docs/updates/2.0.4b3.md b/skills/simplecadapi/references/docs/updates/2.0.4b3.md index c64931eb..bff8c48e 100644 --- a/skills/simplecadapi/references/docs/updates/2.0.4b3.md +++ b/skills/simplecadapi/references/docs/updates/2.0.4b3.md @@ -67,7 +67,25 @@ Inspection and default prune are read-only. Explicit `--repair`, `--apply`, or object presence, byte length, and SHA-256. Namespace clearing preserves objects still referenced elsewhere. -## 6. Native render crash isolation +## 6. Product-package CAD translation + +Validated `.scadpkg` definition closures now translate to one editable FreeCAD +document or one XCAF-backed AP242 STEP file. FreeCAD output uses a +dependency-first definition registry so repeated parts, nested assemblies, +occurrence names, solved placements, materials, connectors, constraints, +grounding, revision, and content hashes survive in native document structure. + +AP242 output uses `AP242_MANAGED_MODEL_BASED_3D_ENGINEERING`, preserves evaluated +BREP and product occurrences, and writes materials, colors, density, plus named +definition/occurrence properties. The property descriptions contain canonical +sorted JSON for durable IDs and semantics. Feature history is not reconstructed +as AP242 features; `.scadpkg` remains the canonical replayable artifact. + +The optional `gmsh` extra and `examples/12_ap242_gmsh_volume_mesh.py` demonstrate +`.scadpkg -> AP242 STEP -> tetrahedral .msh` without adding Gmsh to the core +runtime dependency set. + +## 7. Native render crash isolation On macOS, VTK 9.5's Cocoa offscreen backend can terminate the interpreter with `SIGSEGV` after repeated or concurrent render-window use. Inspection and SDK @@ -76,7 +94,7 @@ workers guarded by a cross-process lock. Completion markers distinguish a finished image from a partial native crash; incomplete workers retry, while a post-write teardown crash cannot terminate the modeling or test process. -## 7. Verification +## 8. Verification Regression coverage exercises artifact schema closure, deterministic IDs and @@ -84,15 +102,19 @@ hashes, atomic concurrent write deduplication, corruption quarantine, all cache modes, in-process same-key PRT reuse, concurrent PRT build deduplication, cross-wrapper persistent part restore, interface invalidation, assembly definition DAGs, incremental dependency propagation, residual verification, -and nested connector changes. +nested connector changes, translator backend contracts, and generated API docs. -The representative external-reference gear-train smoke builds two cached parts, -solves repeated and nested assembly instances, exports an independent assembly -definition archive, reloads it, materializes it, and verifies nested constraint -residuals. +The nested package smoke writes and reads a native FreeCAD hierarchy with shared +definitions and solved placements. AP242 round-trip checks the managed-model +schema, five-level product explorer records, material and color data, plus seven +named metadata property items for three definitions and four occurrences. The +Gmsh smoke imports AP242 as one 3D volume and generates a non-empty tetrahedral +mesh. ## Related documentation - [Persistent cache and product build workflow](../guides/cache-build-workflow.md) +- [Product package STEP/STL export APIs](../api/export_product_package_to_step.md) +- [Editable FreeCAD product package API](../api/translate_product_package_to_fcstd.md) - [Modeling workflows](../../skills/simplecadapi/references/MODELING_WORKFLOWS.md) - [Previous 2.0.4b2 update notes](2.0.4b2.md) diff --git a/skills/simplecadapi/references/inspect/brep-reverse-engineering.md b/skills/simplecadapi/references/inspect/brep-reverse-engineering.md index a21c76cf..ca3ccbab 100644 --- a/skills/simplecadapi/references/inspect/brep-reverse-engineering.md +++ b/skills/simplecadapi/references/inspect/brep-reverse-engineering.md @@ -10,8 +10,8 @@ src/simplecadapi/inspect/brep/ All of these functions are diagnostic, tool-grade APIs, not modeling operations: they do not record graph nodes and must not run inside a -`GraphSession` or `@model` modeling script. Export or obtain the geometry -under test first, then call them outside the modeling script: +`GraphSession`. Export or obtain the geometry under test first, then call them +outside the modeling script: ```python from simplecadapi.inspect import brep diff --git a/src/simplecadapi/__init__.py b/src/simplecadapi/__init__.py index 7d4c8710..2867b0e5 100644 --- a/src/simplecadapi/__init__.py +++ b/src/simplecadapi/__init__.py @@ -1,6 +1,6 @@ """SimpleCAD API: a simplified OCP-native Python CAD modeling API.""" -from . import inspect, math, ql, std, surface, translator, verifier +from . import exporter, inspect, math, ql, std, surface, translator, verifier from .artifacts import ( ArtifactLimits, ArtifactValidationError, @@ -8,23 +8,27 @@ from .artifacts import ( BlobRef, ConnectorInterface, FileInputSnapshot, + FeatureGraphArtifact, InterfaceHashes, MaterialRef, PartDefinition, PartInstance, PartInterfaceDiff, PartInterfaceSnapshot, + SourceFileSnapshot, PartRef, decode_assembly_definition, diff_part_interfaces, encode_assembly_definition, encode_part_definition, + encode_feature_graph_artifact, export_assembly_definition, export_part_definition, geometry_interface_descriptor, geometry_interface_fingerprint, load_assembly_definition, load_latest_part_state, + load_feature_graph_artifact, load_part_definition, materialize_definition, update_latest_part_state, @@ -92,11 +96,7 @@ from .expr import ( ) from .graph import ( GraphSession, - ModelResult, - capture_result, get_active_session, - model, - requires_session, suspend_graph_recording, ) from .math import BSplineFitResult, fit_cubic_bspline_control_points @@ -143,8 +143,6 @@ from .operations import ( # 基础几何创建; 变换操作; 3D操作; 标签 constrain_vertical_rsketch, cut_rsolid, explain_tag, - export_step, - export_stl, extrude_rsolid, fillet_rsolid, forward_connector_rassembly, @@ -236,37 +234,17 @@ from .product import ( Placement, ScalarLimit, ) +from .capture import CaptureResult, capture from .product_packages import ( PRODUCT_PACKAGE_SCHEMA_VERSION, ProductPackage, ProductPackageError, build_product_package, encode_product_package, - export_product_package, load_product_package, read_product_package, validate_product_package, ) -from .scene import ( - CanonicalEdgeBlock, - CanonicalTriangleBlock, - CompiledScenePackage, - RenderEdgeMesh, - RenderGroup, - RenderMesh, - SceneCompileOptions, - SceneRoot, - SceneSource, - build_edge_mesh, - build_render_mesh, - cad_direction_to_gltf, - cad_to_gltf, - compile_scene, - export_scene, - solid_asset_bounds, - write_line_glb, - write_triangle_glb, -) from .serializer import ( export_graph_json, export_model_json, @@ -429,11 +407,9 @@ cut = cut_rsolid intersect = intersect_rsolid union = union_rsolid -# 导出别名 -to_step = export_step -to_stl = export_stl __all__ = [ + "exporter", # 核心类 "CoordinateSystem", "SimpleWorkplane", @@ -580,8 +556,6 @@ __all__ = [ "union_rsolid", "make_2d_union_rface", # 导出 - "export_step", - "export_stl", "replay_model_json", "render_screenshot_rpath", # 高级特征操作 @@ -600,13 +574,8 @@ __all__ = [ "std", "translator", "verifier", - # Graph/session + serialization APIs "GraphSession", - "ModelResult", - "capture_result", "get_active_session", - "model", - "requires_session", "assemble", "AssemblyBuildResult", "AssemblySolveReport", @@ -621,12 +590,13 @@ __all__ = [ "replay_graph", "export_session_json", "import_session_json", + "CaptureResult", + "capture", "PRODUCT_PACKAGE_SCHEMA_VERSION", "ProductPackage", "ProductPackageError", "build_product_package", "encode_product_package", - "export_product_package", "read_product_package", "validate_product_package", "load_product_package", @@ -639,6 +609,10 @@ __all__ = [ "FileInput", "FileInputSnapshot", "InterfaceHashes", + "FeatureGraphArtifact", + "SourceFileSnapshot", + "encode_feature_graph_artifact", + "load_feature_graph_artifact", "MaterialRef", "PartInterfaceDiff", "PartInterfaceSnapshot", @@ -763,24 +737,6 @@ __all__ = [ "SemanticRef", "SemanticDelta", "SimpleCADError", - "CompiledScenePackage", - "CanonicalEdgeBlock", - "CanonicalTriangleBlock", - "RenderEdgeMesh", - "RenderGroup", - "RenderMesh", - "SceneCompileOptions", - "SceneRoot", - "SceneSource", - "compile_scene", - "export_scene", - "build_edge_mesh", - "build_render_mesh", - "cad_direction_to_gltf", - "cad_to_gltf", - "solid_asset_bounds", - "write_line_glb", - "write_triangle_glb", "Assembly", "Component", "Connector", @@ -827,8 +783,6 @@ __all__ = [ "intersect", "revolve", "rotate", - "to_step", - "to_stl", "translate", "union", ] diff --git a/src/simplecadapi/artifacts/__init__.py b/src/simplecadapi/artifacts/__init__.py index 125f36e8..2213eb9d 100644 --- a/src/simplecadapi/artifacts/__init__.py +++ b/src/simplecadapi/artifacts/__init__.py @@ -15,6 +15,12 @@ from .canonical import ( ArtifactLimits, ArtifactValidationError, ) +from .feature_graph import ( + FeatureGraphArtifact, + SourceFileSnapshot, + encode_feature_graph_artifact, + load_feature_graph_artifact, +) from .geometry_interface import ( geometry_interface_descriptor, geometry_interface_fingerprint, @@ -50,6 +56,10 @@ __all__ = [ "AssemblyDefinition", "BlobRef", "PartInterfaceDiff", + "FeatureGraphArtifact", + "SourceFileSnapshot", + "encode_feature_graph_artifact", + "load_feature_graph_artifact", "PartInterfaceSnapshot", "decode_assembly_definition", "encode_assembly_definition", diff --git a/src/simplecadapi/artifacts/assembly_definition.py b/src/simplecadapi/artifacts/assembly_definition.py index 5f8a1dfe..a6e3060c 100644 --- a/src/simplecadapi/artifacts/assembly_definition.py +++ b/src/simplecadapi/artifacts/assembly_definition.py @@ -40,8 +40,8 @@ class AssemblyDefinition: grounded_instance_ids: tuple[str, ...] public_connectors: tuple[ConnectorInterface, ...] interface_hashes: InterfaceHashes + feature_graph_ref: BlobRef solved_snapshot: Mapping[str, Any] | None = None - model_ref: BlobRef | None = None metadata: Mapping[str, Any] = field(default_factory=dict) content_hash: str = "" blobs: Mapping[str, bytes] = field(default_factory=dict, compare=False, repr=False) @@ -60,6 +60,12 @@ class AssemblyDefinition: compare=False, repr=False, ) + _validated_feature_graph: Any = field( + default=None, + init=False, + compare=False, + repr=False, + ) schema_version: str = field(default=ARTIFACT_SCHEMA_VERSION, init=False) artifact_kind: str = field(default="assembly_definition", init=False) @@ -202,9 +208,9 @@ class AssemblyDefinition: ) if self.solved_snapshot is not None: validate_json_value(self.solved_snapshot, "/solved_snapshot") - if self.model_ref is not None and not isinstance(self.model_ref, BlobRef): + if not isinstance(self.feature_graph_ref, BlobRef): raise ArtifactValidationError( - "reference_invalid", "/model_ref", "expected BlobRef or null" + "reference_invalid", "/feature_graph_ref", "expected BlobRef" ) generator = dict(self.generator) expected_generator = { @@ -271,9 +277,7 @@ class AssemblyDefinition: "solved_snapshot": ( dict(solved_snapshot) if solved_snapshot is not None else None ), - "model_ref": ( - self.model_ref.to_dict() if self.model_ref is not None else None - ), + "feature_graph_ref": self.feature_graph_ref.to_dict(), "metadata": dict(self.metadata), } @@ -323,10 +327,8 @@ class AssemblyDefinition: if data["solved_snapshot"] is not None else None ), - model_ref=( - BlobRef.from_dict(data["model_ref"], "/model_ref") - if data["model_ref"] is not None - else None + feature_graph_ref=BlobRef.from_dict( + data["feature_graph_ref"], "/feature_graph_ref" ), metadata=dict(data["metadata"]), content_hash=str(data["content_hash"]), @@ -337,9 +339,12 @@ class AssemblyDefinition: def mark_assembly_definition_validated( definition: AssemblyDefinition, limits: Any, + *, + feature_graph: Any = None, ) -> None: object.__setattr__(definition, "_validated_manifest", definition.canonical_bytes) object.__setattr__(definition, "_validated_limits", limits) + object.__setattr__(definition, "_validated_feature_graph", feature_graph) def assembly_definition_is_validated( @@ -351,5 +356,11 @@ def assembly_definition_is_validated( and definition._validated_manifest == definition.canonical_bytes ) +def validated_assembly_feature_graph(definition: AssemblyDefinition) -> Any: + if definition._validated_manifest != definition.canonical_bytes: + object.__setattr__(definition, "_validated_feature_graph", None) + return None + return definition._validated_feature_graph + __all__ = ["AssemblyDefinition"] diff --git a/src/simplecadapi/artifacts/assembly_io.py b/src/simplecadapi/artifacts/assembly_io.py index 98818072..cee1648d 100644 --- a/src/simplecadapi/artifacts/assembly_io.py +++ b/src/simplecadapi/artifacts/assembly_io.py @@ -28,6 +28,7 @@ from .assembly_definition import ( AssemblyDefinition, assembly_definition_is_validated, mark_assembly_definition_validated, + validated_assembly_feature_graph, ) from .brep import read_brep_solid from .canonical import ( @@ -47,6 +48,7 @@ from .topology_snapshot import ( restore_topology_snapshot, validate_connector_entity_bindings, ) +from .feature_graph import load_feature_graph_artifact from .validation import parse_artifact_json, validate_artifact_blobs _ASSEMBLY_DEFINITION_MANIFEST = "assembly-definition.json" @@ -67,7 +69,7 @@ def definition_archive_name(definition: PartDefinition | AssemblyDefinition) -> def encode_assembly_definition(definition: AssemblyDefinition) -> bytes: - """Encode one assembly manifest and only its own audit blobs.""" + """Encode one assembly manifest and its definition-local graph blob.""" if not isinstance(definition, AssemblyDefinition): raise TypeError("definition must be an AssemblyDefinition") @@ -100,8 +102,8 @@ def decode_assembly_definition( archive.members[_ASSEMBLY_DEFINITION_MANIFEST], kind="assembly_definition", ) - model_ref = manifest["model_ref"] - expected_paths = set() if model_ref is None else {str(model_ref["path"])} + feature_graph_ref = manifest["feature_graph_ref"] + expected_paths = {str(feature_graph_ref["path"])} expected_members = { _ASSEMBLY_DEFINITION_MANIFEST, *(_BLOB_PREFIX + path for path in expected_paths), @@ -199,7 +201,7 @@ def validate_assembly_definition_graph( identities: dict[str, tuple[str, str]] = {} visited: set[tuple[str, str]] = set() active: list[tuple[str, str]] = [] - validated_nodes: list[AssemblyDefinition] = [] + validated_nodes: list[tuple[AssemblyDefinition, Any]] = [] def visit(node: AssemblyDefinition, trace: tuple[str, ...]) -> None: if len(trace) > limits.max_nested_depth: @@ -227,6 +229,19 @@ def validate_assembly_definition_graph( active.append(node_key) try: validate_artifact_blobs(node.to_dict(), node.blobs) + feature_graph = load_feature_graph_artifact( + node.blobs[node.feature_graph_ref.path] + ) + if ( + feature_graph.owner_definition_kind != node.definition_kind + or feature_graph.owner_definition_id != node.definition_id + or feature_graph.owner_revision != node.revision + ): + raise ArtifactValidationError( + "graph_owner_invalid", + "/feature_graph_ref", + "feature graph owner differs from AssemblyDefinition identity", + ) refs = {item.definition_id: item for item in node.definition_refs} resolved = dict(node.resolved_definitions) if set(resolved) != set(refs): @@ -288,6 +303,30 @@ def validate_assembly_definition_graph( ) identities[child.definition_id] = identity connector_sets[child.definition_id] = _connector_ids(child) + graph_refs = tuple( + ( + str(item["definition_kind"]), + str(item["definition_id"]), + str(item["revision"]), + str(item["content_hash"]), + ) + for item in feature_graph.external_definitions + ) + definition_refs = tuple( + ( + item.definition_kind, + item.definition_id, + item.revision, + item.content_hash, + ) + for item in node.definition_refs + ) + if graph_refs != definition_refs: + raise ArtifactValidationError( + "reference_identity_mismatch", + "/feature_graph_ref/external_definitions", + "feature graph external definitions differ from assembly refs", + ) for relation_index, relation in enumerate(node.relations): for side in ("connector_a", "connector_b"): @@ -335,7 +374,7 @@ def validate_assembly_definition_graph( ) visit(child, child_trace) visited.add(node_key) - validated_nodes.append(node) + validated_nodes.append((node, feature_graph)) finally: active.pop() @@ -344,9 +383,13 @@ def validate_assembly_definition_graph( definition.content_hash, ) visit(definition, ()) + for node, feature_graph in validated_nodes: + mark_assembly_definition_validated( + node, + limits, + feature_graph=feature_graph, + ) - for node in validated_nodes: - mark_assembly_definition_validated(node, limits) def assembly_definition_graph_is_validated( @@ -683,6 +726,7 @@ def materialize_definition( ) value._set_runtime("definition.content_hash", node.content_hash) value._set_runtime("definition.kind", node.definition_kind) + value._set_runtime("definition.revision", node.revision) cache[key] = value return value @@ -753,6 +797,7 @@ def materialize_definition( ) restored._set_runtime("definition.content_hash", node.content_hash) restored._set_runtime("definition.kind", node.definition_kind) + restored._set_runtime("definition.revision", node.revision) cache[key] = restored return restored diff --git a/src/simplecadapi/artifacts/canonical.py b/src/simplecadapi/artifacts/canonical.py index a47a9286..575b00e6 100644 --- a/src/simplecadapi/artifacts/canonical.py +++ b/src/simplecadapi/artifacts/canonical.py @@ -11,11 +11,11 @@ from typing import Any, Mapping from ..scene.canonical import canonical_json_bytes, parse_canonical_json, parse_strict_json -ARTIFACT_SCHEMA_VERSION = "1.0" -PART_DEFINITION_PROFILE = "simplecad-part-definition-1" -ASSEMBLY_DEFINITION_PROFILE = "simplecad-assembly-definition-1" +ARTIFACT_SCHEMA_VERSION = "2.0" +PART_DEFINITION_PROFILE = "simplecad-part-definition-2" +ASSEMBLY_DEFINITION_PROFILE = "simplecad-assembly-definition-2" SOLID_EVALUATOR_PROFILE = "ocp-evaluated-solid-1" -TOPOLOGY_SNAPSHOT_PROFILE = "ocp-stable-topology-3" +TOPOLOGY_SNAPSHOT_PROFILE = "ocp-stable-topology-4" _ID_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_.:-]{0,255}$") _HASH_RE = re.compile(r"^sha256:[0-9a-f]{64}$") _REVISION_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$") diff --git a/src/simplecadapi/artifacts/feature_graph.py b/src/simplecadapi/artifacts/feature_graph.py new file mode 100644 index 00000000..fd364666 --- /dev/null +++ b/src/simplecadapi/artifacts/feature_graph.py @@ -0,0 +1,782 @@ +"""Durable definition-owned feature graph artifacts and source snapshots.""" + +from __future__ import annotations + +import json +import os +import stat +from dataclasses import dataclass, field +from functools import lru_cache +from importlib.resources import files +from pathlib import Path +from types import MappingProxyType +from typing import Any, Mapping, Sequence + +from jsonschema import Draft202012Validator + +from ..scene.archive import canonical_zip_bytes, preflight_zip_bytes +from ..source_mapping import canonical_source_payload +from ..topology import OperationGraph, semantic_delta_to_dict, topo_delta_to_dict +from .canonical import ( + DEFAULT_ARTIFACT_LIMITS, + ArtifactLimits, + ArtifactValidationError, + canonical_bytes, + content_hash, + parse_canonical_json, + sha256_bytes, + validate_hash, + validate_json_value, + validate_logical_id, + validate_relative_path, + validate_revision, +) + +FEATURE_GRAPH_SCHEMA_VERSION = "1.0" +FEATURE_GRAPH_PROFILE = "simplecad-feature-graph-1" +FEATURE_GRAPH_MEDIA_TYPE = "application/vnd.simplecad.feature-graph+zip" +_FEATURE_GRAPH_MANIFEST = "feature-graph.json" + + +@lru_cache(maxsize=1) +def _schema() -> Mapping[str, Any]: + resource = files("simplecadapi").joinpath( + "contracts", "feature-graph-1.schema.json" + ) + schema = json.loads(resource.read_text(encoding="utf-8")) + Draft202012Validator.check_schema(schema) + return schema + + +def _pointer(parts: Sequence[Any]) -> str: + encoded = [str(part).replace("~", "~0").replace("/", "~1") for part in parts] + return "/" + "/".join(encoded) if encoded else "/" + + +def _schema_validate(manifest: Mapping[str, Any]) -> None: + errors = sorted( + Draft202012Validator(_schema()).iter_errors(dict(manifest)), + key=lambda item: (list(item.absolute_path), item.message), + ) + if errors: + error = errors[0] + raise ArtifactValidationError( + "schema_invalid", _pointer(list(error.absolute_path)), error.message + ) + + +def _stable_source_bytes(path: Path, *, max_bytes: int, error_path: str) -> bytes: + flags = os.O_RDONLY + if hasattr(os, "O_CLOEXEC"): + flags |= os.O_CLOEXEC + if hasattr(os, "O_NOFOLLOW"): + flags |= os.O_NOFOLLOW + try: + descriptor = os.open(path, flags) + except OSError as exc: + raise ArtifactValidationError( + "source_unavailable", error_path, str(exc) + ) from exc + try: + before = os.fstat(descriptor) + if not stat.S_ISREG(before.st_mode): + raise ArtifactValidationError( + "source_unsafe", error_path, "source must be a regular file" + ) + if before.st_size > max_bytes: + raise ArtifactValidationError( + "resource_limit", error_path, "source exceeds byte limit" + ) + chunks: list[bytes] = [] + remaining = max_bytes + 1 + while remaining > 0: + chunk = os.read(descriptor, min(1024 * 1024, remaining)) + if not chunk: + break + chunks.append(chunk) + remaining -= len(chunk) + payload = b"".join(chunks) + after = os.fstat(descriptor) + if ( + len(payload) > max_bytes + or before.st_dev != after.st_dev + or before.st_ino != after.st_ino + or before.st_size != after.st_size + or before.st_mtime_ns != after.st_mtime_ns + or len(payload) != after.st_size + ): + raise ArtifactValidationError( + "source_changed", error_path, "source changed while being read" + ) + try: + payload.decode("utf-8") + except UnicodeDecodeError as exc: + raise ArtifactValidationError( + "source_invalid", error_path, "Python source must be UTF-8" + ) from exc + return payload + finally: + os.close(descriptor) + + +@dataclass(frozen=True, slots=True) +class SourceFileSnapshot: + """One immutable Python source revision referenced by graph nodes.""" + + source_file_id: str + display_path: str + path_kind: str + content_hash: str + byte_length: int + uri: str + + def __post_init__(self) -> None: + object.__setattr__( + self, + "source_file_id", + validate_hash(self.source_file_id, "/source_file/source_file_id"), + ) + if not isinstance(self.display_path, str) or not self.display_path: + raise ArtifactValidationError( + "path_invalid", "/source_file/display_path", "path must be non-empty" + ) + if self.path_kind not in {"project_relative", "external"}: + raise ArtifactValidationError( + "source_invalid", "/source_file/path_kind", "unsupported path kind" + ) + if self.path_kind == "project_relative": + validate_relative_path(self.display_path, "/source_file/display_path") + object.__setattr__( + self, + "content_hash", + validate_hash(self.content_hash, "/source_file/content_hash"), + ) + if ( + isinstance(self.byte_length, bool) + or not isinstance(self.byte_length, int) + or self.byte_length < 0 + ): + raise ArtifactValidationError( + "size_invalid", "/source_file/byte_length", "must be non-negative" + ) + object.__setattr__( + self, "uri", validate_relative_path(self.uri, "/source_file/uri") + ) + expected_uri = ( + "sources/sha256/" + + self.content_hash.removeprefix("sha256:") + + ".py" + ) + if self.uri != expected_uri: + raise ArtifactValidationError( + "path_invalid", "/source_file/uri", "source URI is not content-addressed" + ) + expected_id = sha256_bytes( + canonical_bytes( + { + "display_path": self.display_path, + "content_hash": self.content_hash, + } + ) + ) + if self.source_file_id != expected_id: + raise ArtifactValidationError( + "hash_invalid", + "/source_file/source_file_id", + "source identity does not match path and content", + ) + + def to_dict(self) -> dict[str, Any]: + return { + "source_file_id": self.source_file_id, + "display_path": self.display_path, + "path_kind": self.path_kind, + "content_hash": self.content_hash, + "byte_length": self.byte_length, + "uri": self.uri, + } + + @classmethod + def from_dict( + cls, data: Mapping[str, Any], path: str = "/source_file" + ) -> "SourceFileSnapshot": + required = { + "source_file_id", + "display_path", + "path_kind", + "content_hash", + "byte_length", + "uri", + } + if not isinstance(data, Mapping) or set(data) != required: + raise ArtifactValidationError( + "fields_invalid", path, "source file fields are not closed" + ) + return cls( + source_file_id=str(data["source_file_id"]), + display_path=str(data["display_path"]), + path_kind=str(data["path_kind"]), + content_hash=str(data["content_hash"]), + byte_length=data["byte_length"], + uri=str(data["uri"]), + ) + + +@dataclass(frozen=True, slots=True) +class FeatureGraphArtifact: + """Closed, replayable feature DAG owned by one durable definition.""" + + owner_definition_kind: str + owner_definition_id: str + owner_revision: str + graph: Mapping[str, Any] + result_node_ids: tuple[str, ...] + external_definitions: tuple[Mapping[str, Any], ...] + expression_graph: Mapping[str, Any] + tolerance_graph: Mapping[str, Any] + frame_graph: Mapping[str, Any] + semantic_index: Mapping[str, Any] + source_files: tuple[SourceFileSnapshot, ...] + content_hash: str = "" + blobs: Mapping[str, bytes] = field(default_factory=dict, compare=False, repr=False) + + schema_version: str = field(default=FEATURE_GRAPH_SCHEMA_VERSION, init=False) + artifact_kind: str = field(default="feature_graph", init=False) + profile: str = field(default=FEATURE_GRAPH_PROFILE, init=False) + + def __post_init__(self) -> None: + if self.owner_definition_kind not in {"single_solid", "assembly"}: + raise ArtifactValidationError( + "definition_kind_invalid", "/owner/definition_kind", "unsupported kind" + ) + object.__setattr__( + self, + "owner_definition_id", + validate_logical_id(self.owner_definition_id, "/owner/definition_id"), + ) + object.__setattr__( + self, + "owner_revision", + validate_revision(self.owner_revision, "/owner/revision"), + ) + graph = json.loads(canonical_bytes(dict(self.graph)).decode("utf-8")) + operation_graph = OperationGraph.from_dict(graph) + if operation_graph.graph_id != self.owner_definition_id: + raise ArtifactValidationError( + "graph_owner_invalid", + "/graph/graph_id", + "graph_id must equal the owning definition_id", + ) + if not operation_graph.is_dag(): + raise ArtifactValidationError( + "graph_invalid", "/graph", "operation graph contains a cycle" + ) + object.__setattr__(self, "graph", MappingProxyType(graph)) + + result_ids = tuple(str(item) for item in self.result_node_ids) + if len(result_ids) != 1 or len(set(result_ids)) != 1: + raise ArtifactValidationError( + "result_invalid", "/result_node_ids", "exactly one result node is required" + ) + if operation_graph.get_node(result_ids[0]) is None: + raise ArtifactValidationError( + "result_invalid", "/result_node_ids/0", "result node does not exist" + ) + object.__setattr__(self, "result_node_ids", result_ids) + + refs = tuple(MappingProxyType(dict(item)) for item in self.external_definitions) + for index, ref in enumerate(refs): + required = { + "definition_kind", + "definition_id", + "revision", + "content_hash", + } + if set(ref) != required: + raise ArtifactValidationError( + "fields_invalid", + f"/external_definitions/{index}", + "external definition fields are not closed", + ) + if ref["definition_kind"] not in {"single_solid", "assembly"}: + raise ArtifactValidationError( + "definition_kind_invalid", + f"/external_definitions/{index}/definition_kind", + "unsupported kind", + ) + validate_logical_id( + ref["definition_id"], + f"/external_definitions/{index}/definition_id", + ) + validate_revision( + ref["revision"], f"/external_definitions/{index}/revision" + ) + validate_hash( + ref["content_hash"], + f"/external_definitions/{index}/content_hash", + ) + ref_ids = [str(item["definition_id"]) for item in refs] + if ref_ids != sorted(ref_ids, key=lambda item: item.encode("utf-8")) or len( + ref_ids + ) != len(set(ref_ids)): + raise ArtifactValidationError( + "array_order_invalid", + "/external_definitions", + "external definitions must be unique and sorted", + ) + if self.owner_definition_kind == "single_solid" and refs: + raise ArtifactValidationError( + "reference_invalid", + "/external_definitions", + "Part feature graphs cannot reference external definitions", + ) + object.__setattr__(self, "external_definitions", refs) + + for name in ( + "expression_graph", + "tolerance_graph", + "frame_graph", + "semantic_index", + ): + value = json.loads(canonical_bytes(dict(getattr(self, name))).decode("utf-8")) + object.__setattr__(self, name, MappingProxyType(value)) + + snapshots = tuple(self.source_files) + if not all(isinstance(item, SourceFileSnapshot) for item in snapshots): + raise ArtifactValidationError( + "source_invalid", "/source_files", "expected SourceFileSnapshot values" + ) + source_ids = [item.source_file_id for item in snapshots] + if source_ids != sorted(source_ids) or len(source_ids) != len(set(source_ids)): + raise ArtifactValidationError( + "array_order_invalid", + "/source_files", + "source files must be unique and sorted by source_file_id", + ) + object.__setattr__(self, "source_files", snapshots) + source_id_set = set(source_ids) + for index, node in enumerate(graph.get("nodes", [])): + source = node.get("source") if isinstance(node, Mapping) else None + if not isinstance(source, Mapping): + continue + if "local_path" in source: + raise ArtifactValidationError( + "source_invalid", + f"/graph/nodes/{index}/source/local_path", + "runtime paths cannot enter a durable graph", + ) + source_file_id = source.get("source_file_id") + if source_file_id is not None and source_file_id not in source_id_set: + raise ArtifactValidationError( + "reference_missing", + f"/graph/nodes/{index}/source/source_file_id", + "source_file_id does not resolve", + ) + + blob_map = {str(path): bytes(payload) for path, payload in self.blobs.items()} + expected_uris = {item.uri for item in snapshots} + if set(blob_map) != expected_uris: + raise ArtifactValidationError( + "blob_unreferenced", + "/blobs", + "source blob set differs from source file records", + ) + total = 0 + for index, snapshot in enumerate(snapshots): + payload = blob_map[snapshot.uri] + total += len(payload) + if total > DEFAULT_ARTIFACT_LIMITS.max_total_file_input_bytes: + raise ArtifactValidationError( + "resource_limit", "/source_files", "source bytes exceed total limit" + ) + if len(payload) != snapshot.byte_length: + raise ArtifactValidationError( + "blob_size_mismatch", + f"/source_files/{index}/byte_length", + "source size differs", + ) + if sha256_bytes(payload) != snapshot.content_hash: + raise ArtifactValidationError( + "blob_hash_mismatch", + f"/source_files/{index}/content_hash", + "source hash differs", + ) + try: + payload.decode("utf-8") + except UnicodeDecodeError as exc: + raise ArtifactValidationError( + "source_invalid", + f"/source_files/{index}", + "Python source must be UTF-8", + ) from exc + object.__setattr__(self, "blobs", MappingProxyType(blob_map)) + + expected_hash = content_hash(self._manifest(content_hash_value="")) + if self.content_hash and validate_hash( + self.content_hash, "/content_hash" + ) != expected_hash: + raise ArtifactValidationError( + "hash_invalid", "/content_hash", "feature graph hash differs" + ) + object.__setattr__(self, "content_hash", expected_hash) + _schema_validate(self.to_dict()) + + def _manifest(self, *, content_hash_value: str) -> dict[str, Any]: + return { + "schema_version": self.schema_version, + "artifact_kind": self.artifact_kind, + "profile": self.profile, + "owner": { + "definition_kind": self.owner_definition_kind, + "definition_id": self.owner_definition_id, + "revision": self.owner_revision, + }, + "graph": dict(self.graph), + "result_node_ids": list(self.result_node_ids), + "external_definitions": [dict(item) for item in self.external_definitions], + "expression_graph": dict(self.expression_graph), + "tolerance_graph": dict(self.tolerance_graph), + "frame_graph": dict(self.frame_graph), + "semantic_index": dict(self.semantic_index), + "source_files": [item.to_dict() for item in self.source_files], + "content_hash": content_hash_value, + } + + def to_dict(self) -> dict[str, Any]: + return self._manifest(content_hash_value=self.content_hash) + + @property + def canonical_bytes(self) -> bytes: + return canonical_bytes(self.to_dict()) + + def restore_session(self): + """Restore a detached GraphSession from the durable payload.""" + + from ..expr import ExpressionGraph + from ..frame import FrameGraph + from ..graph import GraphSession + from ..tolerance import ToleranceGraph + + expression_graph = ExpressionGraph.from_dict(dict(self.expression_graph)) + tolerance_graph = ToleranceGraph.from_dict( + dict(self.tolerance_graph), expression_graph + ) + tolerance_graph.validate(raise_on_failure=True) + session = GraphSession(graph_id=self.owner_definition_id) + session.graph = OperationGraph.from_dict(dict(self.graph)) + session.expression_graph = expression_graph + session.tolerance_graph = tolerance_graph + session.frame_graph = FrameGraph.from_dict(dict(self.frame_graph)) + session._result_node_ids.extend(self.result_node_ids) + session._has_explicit_results = True + return session + + def replay( + self, + *, + strict: bool = True, + external_definitions: Mapping[str, Any] | None = None, + ) -> list[Any]: + from ..serializer import replay_feature_graph + + return replay_feature_graph( + self, + strict=strict, + external_definitions=external_definitions, + ) + + def source_dependencies_match(self, *, project_root: str | Path) -> bool: + """Return whether every project-relative mapped source still has these bytes.""" + + root = Path(project_root).expanduser().resolve() + for index, snapshot in enumerate(self.source_files): + if snapshot.path_kind != "project_relative": + continue + try: + path = (root / snapshot.display_path).resolve(strict=True) + path.relative_to(root) + payload = _stable_source_bytes( + path, + max_bytes=DEFAULT_ARTIFACT_LIMITS.max_file_input_bytes, + error_path=f"/source_files/{index}", + ) + except (ArtifactValidationError, OSError, ValueError): + return False + if sha256_bytes(payload) != snapshot.content_hash: + return False + return True + + @classmethod + def from_dict( + cls, + data: Mapping[str, Any], + *, + blobs: Mapping[str, bytes] | None = None, + ) -> "FeatureGraphArtifact": + _schema_validate(data) + expected_hash = content_hash(data) + if data["content_hash"] != expected_hash: + raise ArtifactValidationError( + "hash_invalid", "/content_hash", "feature graph hash differs" + ) + owner = data["owner"] + return cls( + owner_definition_kind=str(owner["definition_kind"]), + owner_definition_id=str(owner["definition_id"]), + owner_revision=str(owner["revision"]), + graph=dict(data["graph"]), + result_node_ids=tuple(str(item) for item in data["result_node_ids"]), + external_definitions=tuple( + dict(item) for item in data["external_definitions"] + ), + expression_graph=dict(data["expression_graph"]), + tolerance_graph=dict(data["tolerance_graph"]), + frame_graph=dict(data["frame_graph"]), + semantic_index=dict(data["semantic_index"]), + source_files=tuple( + SourceFileSnapshot.from_dict(item, f"/source_files/{index}") + for index, item in enumerate(data["source_files"]) + ), + content_hash=str(data["content_hash"]), + blobs=blobs or {}, + ) + + +def _semantic_index(session: Any) -> dict[str, Any]: + geometry_registry: list[dict[str, Any]] = [] + semantic_entity_registry: list[dict[str, Any]] = [] + sketch_profile_registry: list[dict[str, Any]] = [] + semantic_delta_log: list[dict[str, Any]] = [] + topology_delta_log: list[dict[str, Any]] = [] + semantic_bindings: list[dict[str, Any]] = [] + sketch_ops = { + "make_point_rvertex", + "make_line_redge", + "make_circle_redge", + "make_three_point_arc_redge", + "make_angle_arc_redge", + "make_spline_redge", + "make_interpolated_spline_redge", + "make_helix_redge", + "make_wire_from_edges_rwire", + "make_face_from_wire_rface", + "make_face_from_wires_rface", + "make_wire_from_sketch_rwire", + "make_face_from_sketch_rface", + } + for node in session.graph.topological_order(): + binding = node.params.get("tag_binding") + if node.op == "apply_tag_rselection" and isinstance(binding, Mapping): + semantic_bindings.append(dict(binding)) + if node.semantic_delta is not None: + delta = semantic_delta_to_dict(node.semantic_delta) + semantic_delta_log.append( + {"node_id": node.node_id, "op": node.op, "delta": delta} + ) + for ref in node.semantic_delta.created: + record = { + "graph_id": ref.graph_id, + "node_id": ref.node_id, + "entity_type": ref.entity_type, + "entity_id": ref.entity_id, + "source_op": node.op, + } + geometry_registry.append(record) + semantic_entity_registry.append(dict(record)) + else: + for slot in range(node.output_count): + geometry_registry.append( + { + "graph_id": session.graph.graph_id, + "node_id": node.node_id, + "entity_type": "ShapeOutput", + "entity_id": f"{node.op}:{slot}", + "source_op": node.op, + } + ) + if node.topo_delta is not None: + topology_delta_log.append( + { + "node_id": node.node_id, + "op": node.op, + "delta": topo_delta_to_dict(node.topo_delta), + } + ) + if node.op in sketch_ops: + sketch_profile_registry.append( + { + "graph_id": session.graph.graph_id, + "node_id": node.node_id, + "op": node.op, + "params": dict(node.params), + } + ) + return { + "geometry_registry": geometry_registry, + "semantic_entity_registry": semantic_entity_registry, + "sketch_profile_registry": sketch_profile_registry, + "semantic_delta_log": semantic_delta_log, + "topology_delta_log": topology_delta_log, + "semantic_bindings": semantic_bindings, + } + + +def capture_feature_graph( + *, + session: Any, + owner_definition_kind: str, + owner_definition_id: str, + owner_revision: str, + project_root: str | Path, + external_definitions: Sequence[Mapping[str, Any]] = (), + limits: ArtifactLimits = DEFAULT_ARTIFACT_LIMITS, +) -> FeatureGraphArtifact: + """Freeze one live definition-local session and every resolvable source file.""" + + if session.graph.graph_id != owner_definition_id: + raise ArtifactValidationError( + "graph_owner_invalid", "/graph/graph_id", "session graph owner differs" + ) + root = Path(project_root).expanduser().resolve() + graph_payload = session.graph.to_dict() + payload_nodes = { + str(item["node_id"]): item for item in graph_payload.get("nodes", []) + } + source_records: dict[str, SourceFileSnapshot] = {} + source_blobs: dict[str, bytes] = {} + total = 0 + for node_index, node in enumerate(session.graph.topological_order()): + source = node.source + if not isinstance(source, Mapping): + continue + durable = canonical_source_payload(dict(source)) or {} + local_path = source.get("local_path") + if isinstance(local_path, str) and local_path: + resolved = Path(local_path).expanduser().resolve() + payload = _stable_source_bytes( + resolved, + max_bytes=limits.max_file_input_bytes, + error_path=f"/graph/nodes/{node_index}/source", + ) + total += len(payload) + if total > limits.max_total_file_input_bytes: + raise ArtifactValidationError( + "resource_limit", "/source_files", "source bytes exceed total limit" + ) + try: + display_path = resolved.relative_to(root).as_posix() + path_kind = "project_relative" + except ValueError: + display_path = str(durable.get("path") or resolved.name) + path_kind = "external" + content_digest = sha256_bytes(payload) + source_file_id = sha256_bytes( + canonical_bytes( + { + "display_path": display_path, + "content_hash": content_digest, + } + ) + ) + uri = ( + "sources/sha256/" + + content_digest.removeprefix("sha256:") + + ".py" + ) + snapshot = SourceFileSnapshot( + source_file_id=source_file_id, + display_path=display_path, + path_kind=path_kind, + content_hash=content_digest, + byte_length=len(payload), + uri=uri, + ) + prior = source_records.get(source_file_id) + if prior is not None and prior != snapshot: + raise ArtifactValidationError( + "source_invalid", + f"/graph/nodes/{node_index}/source", + "source identity collision", + ) + source_records[source_file_id] = snapshot + source_blobs[uri] = payload + durable["source_file_id"] = source_file_id + durable["path"] = display_path + durable["path_kind"] = path_kind + payload_nodes[node.node_id]["source"] = durable + + artifact = FeatureGraphArtifact( + owner_definition_kind=owner_definition_kind, + owner_definition_id=owner_definition_id, + owner_revision=owner_revision, + graph=graph_payload, + result_node_ids=tuple(session.result_node_ids), + external_definitions=tuple( + sorted( + (dict(item) for item in external_definitions), + key=lambda item: str(item["definition_id"]).encode("utf-8"), + ) + ), + expression_graph=session.expression_graph.to_dict(), + tolerance_graph=session.tolerance_graph.to_dict(), + frame_graph=session.frame_graph.to_dict(), + semantic_index=_semantic_index(session), + source_files=tuple( + source_records[key] for key in sorted(source_records) + ), + blobs=source_blobs, + ) + return artifact + + +def encode_feature_graph_artifact(artifact: FeatureGraphArtifact) -> bytes: + """Encode one feature graph and its source snapshots canonically.""" + + if not isinstance(artifact, FeatureGraphArtifact): + raise TypeError("artifact must be a FeatureGraphArtifact") + return canonical_zip_bytes( + {_FEATURE_GRAPH_MANIFEST: artifact.canonical_bytes, **artifact.blobs}, + manifest_name=_FEATURE_GRAPH_MANIFEST, + ) + + +def load_feature_graph_artifact( + data: bytes | bytearray | memoryview | str | Path, +) -> FeatureGraphArtifact: + """Read and fully validate one canonical feature graph archive.""" + + raw = Path(data).read_bytes() if isinstance(data, (str, Path)) else bytes(data) + archive = preflight_zip_bytes(raw, manifest_name=_FEATURE_GRAPH_MANIFEST) + manifest = parse_canonical_json(archive.members[_FEATURE_GRAPH_MANIFEST]) + if not isinstance(manifest, Mapping): + raise ArtifactValidationError( + "type_invalid", "/", "feature graph manifest must be an object" + ) + _schema_validate(manifest) + records = manifest["source_files"] + expected = { + _FEATURE_GRAPH_MANIFEST, + *(str(item["uri"]) for item in records), + } + if set(archive.members) != expected: + raise ArtifactValidationError( + "blob_unreferenced", + "/blobs", + "archive member set differs from source file records", + ) + blobs = { + str(item["uri"]): archive.members[str(item["uri"])] for item in records + } + return FeatureGraphArtifact.from_dict(manifest, blobs=blobs) + + +__all__ = [ + "FEATURE_GRAPH_MEDIA_TYPE", + "FEATURE_GRAPH_PROFILE", + "FEATURE_GRAPH_SCHEMA_VERSION", + "FeatureGraphArtifact", + "SourceFileSnapshot", + "capture_feature_graph", + "encode_feature_graph_artifact", + "load_feature_graph_artifact", +] diff --git a/src/simplecadapi/artifacts/part_definition.py b/src/simplecadapi/artifacts/part_definition.py index 3f814f19..9555113f 100644 --- a/src/simplecadapi/artifacts/part_definition.py +++ b/src/simplecadapi/artifacts/part_definition.py @@ -34,7 +34,7 @@ class PartDefinition: revision: str tolerance_profile: str generator: Mapping[str, Any] - model_ref: BlobRef + feature_graph_ref: BlobRef solid_cache_ref: BlobRef topology_snapshot_ref: BlobRef connectors: tuple[ConnectorInterface, ...] @@ -56,6 +56,12 @@ class PartDefinition: compare=False, repr=False, ) + _validated_feature_graph: Any = field( + default=None, + init=False, + compare=False, + repr=False, + ) schema_version: str = field(default=ARTIFACT_SCHEMA_VERSION, init=False) artifact_kind: str = field(default="part_definition", init=False) @@ -78,9 +84,9 @@ class PartDefinition: raise ArtifactValidationError( "profile_invalid", "/tolerance_profile", "invalid tolerance profile" ) - if not isinstance(self.model_ref, BlobRef): + if not isinstance(self.feature_graph_ref, BlobRef): raise ArtifactValidationError( - "reference_invalid", "/model_ref", "expected BlobRef" + "reference_invalid", "/feature_graph_ref", "expected BlobRef" ) if not isinstance(self.solid_cache_ref, BlobRef): raise ArtifactValidationError( @@ -191,8 +197,8 @@ class PartDefinition: "profile": self.profile, "generator": dict(self.generator), "definition": { - "kind": "feature_dag_snapshot", - "model_ref": self.model_ref.to_dict(), + "kind": "feature_graph", + "feature_graph_ref": self.feature_graph_ref.to_dict(), }, "solid_cache": { "evaluator_profile": "ocp-evaluated-solid-1", @@ -232,8 +238,8 @@ class PartDefinition: revision=str(data["revision"]), tolerance_profile=str(data["tolerance_profile"]), generator=dict(data["generator"]), - model_ref=BlobRef.from_dict( - definition["model_ref"], "/definition/model_ref" + feature_graph_ref=BlobRef.from_dict( + definition["feature_graph_ref"], "/definition/feature_graph_ref" ), solid_cache_ref=BlobRef.from_dict( cache["body_ref"], "/solid_cache/body_ref" @@ -265,9 +271,11 @@ def mark_part_definition_validated( definition: PartDefinition, *, body: Any = None, + feature_graph: Any = None, ) -> None: object.__setattr__(definition, "_validated_manifest", definition.canonical_bytes) object.__setattr__(definition, "_validated_body", body) + object.__setattr__(definition, "_validated_feature_graph", feature_graph) def part_definition_is_validated(definition: PartDefinition) -> bool: @@ -277,10 +285,18 @@ def part_definition_is_validated(definition: PartDefinition) -> bool: def take_validated_part_body(definition: PartDefinition) -> Any: if not part_definition_is_validated(definition): object.__setattr__(definition, "_validated_body", None) + object.__setattr__(definition, "_validated_feature_graph", None) return None body = definition._validated_body object.__setattr__(definition, "_validated_body", None) return body +def validated_part_feature_graph(definition: PartDefinition) -> Any: + if not part_definition_is_validated(definition): + object.__setattr__(definition, "_validated_feature_graph", None) + return None + return definition._validated_feature_graph + + __all__ = ["PartDefinition"] diff --git a/src/simplecadapi/artifacts/part_io.py b/src/simplecadapi/artifacts/part_io.py index 8cf86487..ec202e42 100644 --- a/src/simplecadapi/artifacts/part_io.py +++ b/src/simplecadapi/artifacts/part_io.py @@ -17,6 +17,7 @@ from .topology_snapshot import ( validate_connector_entity_bindings, ) from .validation import parse_artifact_json, validate_artifact_blobs +from .feature_graph import load_feature_graph_artifact from ..scene.archive import canonical_zip_bytes, preflight_zip_bytes _PART_DEFINITION_MANIFEST = "part-definition.json" @@ -56,7 +57,7 @@ def load_part_definition( kind="part_definition", ) expected_paths = { - str(manifest["definition"]["model_ref"]["path"]), + str(manifest["definition"]["feature_graph_ref"]["path"]), str(manifest["solid_cache"]["body_ref"]["path"]), str(manifest["topology_snapshot_ref"]["path"]), } @@ -76,13 +77,30 @@ def load_part_definition( blobs = {path: archive.members[_BLOB_PREFIX + path] for path in expected_paths} definition = PartDefinition.from_dict(manifest, blobs=blobs) validate_artifact_blobs(definition.to_dict(), definition.blobs) + feature_graph = load_feature_graph_artifact( + definition.blobs[definition.feature_graph_ref.path] + ) + if ( + feature_graph.owner_definition_kind != definition.definition_kind + or feature_graph.owner_definition_id != definition.definition_id + or feature_graph.owner_revision != definition.revision + ): + raise ArtifactValidationError( + "graph_owner_invalid", + "/definition/feature_graph_ref", + "feature graph owner differs from PartDefinition identity", + ) body = read_brep_solid(definition.blobs[definition.solid_cache_ref.path]) restore_topology_snapshot( body, definition.blobs[definition.topology_snapshot_ref.path], ) validate_connector_entity_bindings(body, definition.connectors) - mark_part_definition_validated(definition, body=body) + mark_part_definition_validated( + definition, + body=body, + feature_graph=feature_graph, + ) return definition diff --git a/src/simplecadapi/artifacts/topology_snapshot.py b/src/simplecadapi/artifacts/topology_snapshot.py index 51e33c02..2867b0f4 100644 --- a/src/simplecadapi/artifacts/topology_snapshot.py +++ b/src/simplecadapi/artifacts/topology_snapshot.py @@ -7,6 +7,7 @@ from typing import Any, Mapping from ..core import Solid from ..tagging import TagBinding, TagLineageWitness, normalize_tag +from ..topology import TopoKind, TopoRef, topo_ref_to_dict from .geometry_interface import ( geometry_interface_fingerprint, stable_topology_entity_hash, @@ -20,7 +21,7 @@ from .canonical import ( validate_json_value, ) -_SNAPSHOT_VERSION = "3.0" +_SNAPSHOT_VERSION = "4.0" _METADATA_EXCLUDED = { "graph", "topo_ref", @@ -103,6 +104,13 @@ def _entity_key(entity: Any) -> tuple[str, str]: def _entity_key_map(entities: list[Any]) -> dict[int, tuple[str, str]]: return {id(entity): _entity_key(entity) for entity in entities} + +def _feature_output(entity: Any) -> dict[str, Any] | None: + ref = entity.runtime.get("topo.ref") + if not isinstance(ref, TopoRef): + return None + return topo_ref_to_dict(ref) + def topology_entity_ref(solid: Solid, topo_id: str) -> dict[str, str]: """Return the immutable package reference for one topology entity.""" @@ -361,6 +369,7 @@ def capture_topology_snapshot(solid: Solid) -> dict[str, Any]: "kind": kind, "topo_id": entity.topo_id, "geometry_hash": entity_geometry_hash, + "feature_output": _feature_output(entity), "tags": sorted(entity.tags, key=lambda item: item.encode("utf-8")), "tag_bindings": _rewrite_binding_identities( [item.to_dict() for item in entity.tag_bindings], binding_identities @@ -431,6 +440,7 @@ def _validate_snapshot(snapshot: Mapping[str, Any]) -> None: "kind", "topo_id", "geometry_hash", + "feature_output", "tags", "tag_bindings", "tag_lineage", @@ -454,6 +464,42 @@ def _validate_snapshot(snapshot: Mapping[str, Any]) -> None: "invalid or duplicate ID", ) seen_ids.add(topo_id) + feature_output = entity["feature_output"] + if feature_output is not None: + if not isinstance(feature_output, Mapping) or set(feature_output) != { + "graph_id", + "node_id", + "output_slot", + "kind", + "topo_id", + }: + raise ArtifactValidationError( + "topology_snapshot_invalid", + f"/entities/{index}/feature_output", + "invalid feature output reference", + ) + if feature_output["kind"] != str(entity["kind"]).upper(): + raise ArtifactValidationError( + "topology_snapshot_invalid", + f"/entities/{index}/feature_output/kind", + "feature output kind differs from topology entity kind", + ) + if ( + not isinstance(feature_output["graph_id"], str) + or not feature_output["graph_id"] + or not isinstance(feature_output["node_id"], str) + or not feature_output["node_id"] + or isinstance(feature_output["output_slot"], bool) + or not isinstance(feature_output["output_slot"], int) + or feature_output["output_slot"] < 0 + or not isinstance(feature_output["topo_id"], str) + or not feature_output["topo_id"] + ): + raise ArtifactValidationError( + "topology_snapshot_invalid", + f"/entities/{index}/feature_output", + "feature output reference values are invalid", + ) validate_json_value(entity["metadata"], f"/entities/{index}/metadata") name_index = snapshot["name_index"] if not isinstance(name_index, Mapping): @@ -631,6 +677,22 @@ def restore_topology_snapshot( entity.tag_lineage[:] = lineage entity.metadata.clear() entity.metadata.update(deepcopy(dict(item["metadata"]))) + feature_output = item["feature_output"] + if feature_output is None: + entity.runtime.pop("topo.ref", None) + entity.runtime.pop("topo.kind", None) + entity.runtime.pop("topo.id", None) + else: + ref = TopoRef( + graph_id=str(feature_output["graph_id"]), + node_id=str(feature_output["node_id"]), + output_slot=int(feature_output["output_slot"]), + kind=TopoKind[str(feature_output["kind"])], + topo_id=str(feature_output["topo_id"]), + ) + entity.runtime["topo.ref"] = ref + entity.runtime["topo.kind"] = ref.kind.name + entity.runtime["topo.id"] = ref.topo_id entity.incident_face_ids.clear() entity.incident_face_ids.update( str(value) for value in item["incident_face_ids"] diff --git a/src/simplecadapi/artifacts/validation.py b/src/simplecadapi/artifacts/validation.py index 88489684..5247cad9 100644 --- a/src/simplecadapi/artifacts/validation.py +++ b/src/simplecadapi/artifacts/validation.py @@ -22,8 +22,8 @@ from .canonical import ( _ARTIFACT_KINDS = {"part_definition", "assembly_definition"} _SCHEMA_FILES = { - "part_definition": "part-definition-1.schema.json", - "assembly_definition": "assembly-definition-1.schema.json", + "part_definition": "part-definition-2.schema.json", + "assembly_definition": "assembly-definition-2.schema.json", } @@ -129,7 +129,7 @@ def parse_artifact_json( def _blob_refs(manifest: Mapping[str, Any]) -> list[tuple[str, Mapping[str, Any]]]: if manifest["artifact_kind"] == "part_definition": refs = [ - ("/definition/model_ref", manifest["definition"]["model_ref"]), + ("/definition/feature_graph_ref", manifest["definition"]["feature_graph_ref"]), ("/solid_cache/body_ref", manifest["solid_cache"]["body_ref"]), ("/topology_snapshot_ref", manifest["topology_snapshot_ref"]), ] @@ -137,8 +137,7 @@ def _blob_refs(manifest: Mapping[str, Any]) -> list[tuple[str, Mapping[str, Any] if material is not None: refs.append(("/material_ref", material)) return refs - model_ref = manifest["model_ref"] - return [] if model_ref is None else [("/model_ref", model_ref)] + return [("/feature_graph_ref", manifest["feature_graph_ref"])] def validate_artifact_blobs( diff --git a/src/simplecadapi/auto_tools/auto_docs_gen.py b/src/simplecadapi/auto_tools/auto_docs_gen.py index 8174b41c..79e3ef3b 100644 --- a/src/simplecadapi/auto_tools/auto_docs_gen.py +++ b/src/simplecadapi/auto_tools/auto_docs_gen.py @@ -27,6 +27,7 @@ DEFAULT_SOURCE_FILENAMES: tuple[str, ...] = ( "graph.py", "sketch.py", "errors.py", + "capture.py", "product_packages.py", "topology.py", "build/assembly_builder.py", @@ -46,6 +47,8 @@ DEFAULT_SOURCE_FILENAMES: tuple[str, ...] = ( "inspect/brep/queries.py", "inspect/brep/render.py", "inspect/brep/slices.py", + "exporter/step.py", + "exporter/stl.py", ) DEFAULT_STDLIB_SOURCE_FILENAMES: tuple[str, ...] = ( @@ -71,6 +74,7 @@ EXPORTED_FUNCTION_MODULES = frozenset( "tolerance.py", "units.py", "errors.py", + "capture.py", "product_packages.py", "build/assembly_builder.py", "build/dependencies.py", @@ -85,6 +89,8 @@ EXPORTED_FUNCTION_MODULES = frozenset( "inspect/brep/queries.py", "inspect/brep/render.py", "inspect/brep/slices.py", + "exporter/step.py", + "exporter/stl.py", } ) @@ -126,6 +132,9 @@ def _default_source_files(package_root: Path) -> List[Path]: translator_root = package_root / "translator" for backend_dir in sorted(translator_root.glob("*_translator")): source_files.extend([backend_dir / "api.py", backend_dir / "translator.py"]) + types_file = backend_dir / "types.py" + if types_file.is_file(): + source_files.append(types_file) return source_files @@ -135,7 +144,7 @@ def _translator_backend_name(module_name: str) -> str | None: len(parts) == 3 and parts[0] == "translator" and parts[1].endswith("_translator") - and parts[2] in {"api.py", "translator.py"} + and parts[2] in {"api.py", "translator.py", "types.py"} ): return parts[1] return None @@ -315,6 +324,8 @@ class APIDocumentGenerator: module_name: str, exported_names: set[str], ) -> bool: + if module_name.startswith("exporter/"): + return True if name.startswith("_"): return False if module_name in FULL_PUBLIC_FUNCTION_MODULES: @@ -354,6 +365,8 @@ class APIDocumentGenerator: ) -> bool: if name.startswith("_"): return False + if module_name.startswith("exporter/"): + return True if _translator_backend_name(module_name) is not None: return True if module_name.startswith("inspect/brep/"): @@ -404,6 +417,13 @@ class APIDocumentGenerator: if name in self.exported_names: return f"top-level: `from simplecadapi import {name}`" + if module_name.startswith("exporter/"): + exporter_module = module_name.removeprefix("exporter/").removesuffix(".py") + return ( + f"exporter namespace: `from simplecadapi import exporter` " + f"then `exporter.{exporter_module}.{name}(...)`" + ) + translator_backend = _translator_backend_name(module_name) if translator_backend is not None: return ( @@ -414,7 +434,7 @@ class APIDocumentGenerator: if module_name.startswith("inspect/brep/"): return ( "inspection namespace: `from simplecadapi.inspect import brep` " - f"then `brep.{name}(...)`; unavailable inside GraphSession/@model" + f"then `brep.{name}(...)`; unavailable inside GraphSession" ) module_stem = module_name.removesuffix(".py") @@ -592,6 +612,9 @@ class APIDocumentGenerator: categories["Modeling Graph and Replay"].append(api) continue + if api.source_file.startswith("exporter/"): + categories["Export"].append(api) + continue if _translator_backend_name(api.source_file) is not None: categories["Translator Backends"].append(api) continue @@ -640,7 +663,7 @@ class APIDocumentGenerator: "", "- Entries marked `top-level` are exported from `simplecadapi` and can be imported with `from simplecadapi import `.", "- Entries marked `submodule` are public through the listed submodule, such as `simplecadapi.ql`.", - "- Entries marked `inspection namespace` are available through `simplecadapi.inspect.brep` and cannot run inside `GraphSession` or `@model`.", + "- Entries marked `inspection namespace` are available through `simplecadapi.inspect.brep` and cannot run inside `GraphSession`.", "- Entries marked `translator backend` are public only through `simplecadapi.translator.`.", "", ] @@ -656,6 +679,8 @@ class APIDocumentGenerator: surface_info = " `top-level`" elif api.source_file.startswith("inspect/brep/"): surface_info = " `inspection namespace`" + elif api.source_file.startswith("exporter/"): + surface_info = " `exporter namespace`" elif api.source_file.startswith("translator/"): surface_info = " `translator backend`" else: diff --git a/src/simplecadapi/auto_tools/make_export.py b/src/simplecadapi/auto_tools/make_export.py index 1c3c5940..da0537a9 100644 --- a/src/simplecadapi/auto_tools/make_export.py +++ b/src/simplecadapi/auto_tools/make_export.py @@ -110,8 +110,6 @@ ALIAS_RULES = { "union_rsolid": "union", "cut_rsolid": "cut", "intersect_rsolid": "intersect", - "export_step": "to_step", - "export_stl": "to_stl", } diff --git a/src/simplecadapi/auto_tools/skill_pack.py b/src/simplecadapi/auto_tools/skill_pack.py index a818ca9c..e2c02724 100644 --- a/src/simplecadapi/auto_tools/skill_pack.py +++ b/src/simplecadapi/auto_tools/skill_pack.py @@ -422,7 +422,7 @@ class SkillPackager: else: destination.write_text( "# STEP/BREP Inspection\n\n" - "Use `simplecadapi.inspect.brep` outside GraphSession/@model. " + "Use `simplecadapi.inspect.brep` outside GraphSession. " "Select inspection primitives according to the case; do not " "apply a fixed reverse-engineering pipeline.\n", encoding="utf-8", @@ -513,8 +513,8 @@ class SkillPackager: 3. Read the needed `core/` or exact `api/` docs when an API needs `Edge`, `Face`, `Wire`, `Solid`, `GraphSession`, `Sketch`, or expression types. 4. Prefer the standard parts library for standard parts before hand-modeling with core geometry APIs. 5. Follow the documented API signatures exactly. - 6. When calling any SimpleCAD public API or standard-library function, use keyword arguments for every documented parameter; do not use positional arguments. - 7. Use `@part` for one physical single-solid product, `@assemble` for an assembly with explicit durable definitions, and `@model` only for replayable geometry flows that are not durable product boundaries. Use `@requires_session` for child graph builders and `capture_result(...)` for explicit `@model` outputs. Export `PartBuildResult` and `AssemblyBuildResult` with `export_artifacts(output_dir=...)`; both produce the same canonical self-contained `.scadpkg` product format. + 6. For documented SimpleCAD public APIs and standard-library functions, use keyword arguments, except for the canonical durable export call `capture(result, path)`, whose two required arguments are positional. + 7. Use `@part` for one physical single-solid product and `@assemble` for an assembly with explicit durable definitions. For replayable geometry, use an explicit `GraphSession`, call `session.capture_result(...)` for canonical outputs, then use `export_model_json(session=...)` and `replay_model_json(json_str=...)`. For durable product delivery, call `capture(result, "out/product.scadpkg")` to build and write the canonical package in one step. 8. Use geometry APIs for integrated parts: profiles, features, booleans, transforms, tagging, QL inspection, serialization, and exports. 9. Use tags consistently through `apply_tag(shape=..., tag=...)` and `list_tags(shape=...)`; do not call shape member tag mutators. 10. Build and validate incrementally. Each step MUST include a small grounding `print`, and grounding MUST use QL where possible. @@ -524,9 +524,9 @@ class SkillPackager: 14. For automated example/test harnesses, prefer the repo-local examples in `examples/` and avoid scratch scripts in `sandbox/`. 15. If union cannot produce exactly one merged solid, it fails explicitly; do not silently pick one piece. 16. If a single merged solid is required and union fails, slightly adjust part placement so intended bodies overlap/embed, then recompute. - 17. If a task depends on model replay or interchange, prefer `ModelResult.model_json` or `export_model_json()` output over hand-written payloads. + 17. If a task depends on model replay or interchange, prefer `export_model_json(session)` output over hand-written payloads. 18. For STEP/BREP inspection or target/candidate comparison, read `references/inspect/brep-reverse-engineering.md` completely. - 19. Use `simplecadapi.inspect.brep` only outside `GraphSession` and `@model`; inspection functions are diagnostic tools, not modeling operations. + 19. Use `simplecadapi.inspect.brep` only outside `GraphSession`; inspection functions are diagnostic tools, not modeling operations. 20. Reverse engineering is case-by-case: the built-in inspection primitives are tools, not a pipeline — write ad hoc inspection code for the specific model when built-ins do not answer the question. Acceptance hierarchy: BREP topology identity is the best endpoint (complete reverse engineering); identical structure with minor float-level parameter drift from export is acceptable; a visually-close but structurally different result is a valid stop only when no better feature operation order/combination exists or the SDK lacks the required operation type. 21. Before configuring persistent cache, writing a durable product build, or running cache maintenance, read `references/docs/guides/cache-build-workflow.md` completely. Cache mutation requires explicit repair, apply, or clear confirmation. @@ -557,11 +557,11 @@ class SkillPackager: - Start with intent: identify the part, its reference axes, critical profiles, and the features that produce the final solid. - Build from lower-dimensional geometry to higher-dimensional geometry: `Vertex` / `Edge` / `Wire` / `Face` profiles first, then `Solid` features such as extrude, revolve, loft, and sweep. - Keep modeling operations functional. Create new values from public functions such as `make_circle_rface(...)`, `extrude_rsolid(...)`, `cut_rsolid(...)`, and `fillet_rsolid(...)`. - - Use keyword arguments for all SimpleCAD function calls, for example `make_box_rsolid(width=10.0, height=20.0, depth=3.0)` instead of positional arguments. - - Use `@model` when a non-product geometry flow should be replayable, inspectable, exported as model JSON, or translated to another CAD system. It owns one `GraphSession`; reusable graph-producing builders use `@requires_session`. - - Use `@part` when the result is one physical single-solid product and needs a durable definition or whole-part cache. Use `@assemble` for explicit part/nested-assembly definitions and incremental constraint solving; do not wrap either product boundary in `@model`. - - Export either build result with `export_artifacts(output_dir=...)`. The only product format is `"product"`, written as a canonical self-contained `.scadpkg` whose content-addressed closure preserves PRT/ASM definitions, instances, relations, stable topology naming, and resolved connector geometry bindings. Use `export_definition(...)` only for low-level definition exchange or inspection. - - Treat model JSON as the interchange boundary for non-product `@model` flows. Prefer `ModelResult.model_json` and `ModelResult.replay()` for top-level models; use `export_model_json(session=...)` for lower-level direct sessions and `replay_model_json(json_str=...)` for standalone payloads. + - Use keyword arguments for SimpleCAD function calls, except the canonical `capture(result, path)` durable export call. For example, use `make_box_rsolid(width=10.0, height=20.0, depth=3.0)` instead of positional primitive arguments. + - Use an explicit `GraphSession` when a non-product geometry flow should be replayable, inspectable, exported as model JSON, or translated to another CAD system. Reusable graph-producing builders accept a session or run inside the caller's session. + - Use `@part` when the result is one physical single-solid product and needs a durable definition or whole-part cache. Use `@assemble` for explicit part/nested-assembly definitions and incremental constraint solving; do not nest either product boundary in a `GraphSession`. + - Use `capture(result, "out/product.scadpkg")` for durable product delivery. It builds and writes the canonical self-contained `.scadpkg`, then returns a `CaptureResult` containing the runtime value, package, scene, and encoded bytes. The public product-package primitives are in-memory construction, encoding, validation, and reading only; use `export_part_definition(...)` or `export_assembly_definition(...)` only for low-level definition exchange or inspection. + - Treat model JSON as the interchange boundary for explicit `GraphSession` flows. Use `session.capture_result(...)`, `export_model_json(session)`, and `replay_model_json(json_str=...)`. - Use QL for precise grounding. Query faces, edges, centers, normals, areas, lengths, curve types, and tags; print only the facts needed to validate the current step. - Use `get_edges(index)`, `get_faces(index)`, `get_wires(index)`, or `get_vertices(index)` when an indexed topology pick is intentional; these picks are preserved as geo select nodes in replayable graph workflows. - Use tags for semantic intent and selection anchors, such as `role.mounting_surface`, `anchor.datum.primary`, `face.top`, or `group.fasteners`. @@ -585,7 +585,7 @@ class SkillPackager: - Stdlib docs include an `Import Surface` section that identifies the package-level `simplecadapi.std.gear` module export. - Use `references/SDK_OVERVIEW.md` for the package-level map. - Use `references/SDK_SURFACES.md` for the main public surfaces. - - Use `references/MODELING_WORKFLOWS.md` for graph/model-oriented patterns. + - Use `references/MODELING_WORKFLOWS.md` for explicit graph-session patterns. - Use `references/inspect/brep-reverse-engineering.md` for case-specific STEP/BREP evidence gathering and acceptance. - Use `references/docs/guides/cache-build-workflow.md` for durable product boundaries, cache policy, PRT reuse, incremental invalidation, and maintenance. @@ -593,22 +593,14 @@ class SkillPackager: ```python import simplecadapi as scad - from simplecadapi import ModelResult, capture_result, model, requires_session - ``` + from simplecadapi import GraphSession, export_model_json, replay_model_json - Typical replayable usage in a Python script: - - ```python - import simplecadapi as scad - - @scad.model(graph_id="box") - def build_box(): + with GraphSession(graph_id="box") as session: shape = scad.make_box_rsolid(width=10.0, height=20.0, depth=30.0) - scad.capture_result(value=shape) - return shape + session.capture_result(value=shape) + payload = export_model_json(session=session) - result = build_box() - rebuilt = result.replay() + rebuilt = replay_model_json(json_str=payload) print(len(rebuilt)) ``` @@ -735,16 +727,14 @@ class SkillPackager: ```python import simplecadapi as scad + from simplecadapi import GraphSession, export_model_json, replay_model_json - @scad.model(graph_id="demo") - def build_model(): + with GraphSession(graph_id="demo") as session: result = ... - scad.capture_result(value=result) - return result + session.capture_result(value=result) + model_json = export_model_json(session=session) - model = build_model() - model_json = model.model_json - rebuilt = model.replay() + rebuilt = replay_model_json(json_str=model_json) print(len(rebuilt)) ``` """) @@ -761,11 +751,11 @@ class SkillPackager: - Use the standard parts library first when a requested standard component is available and does not need complex custom geometry changes. - Start from profiles and reference geometry, then create solids with features such as extrude, revolve, loft, and sweep. - Use booleans and detail features after the base form is clear: cut openings, union intended merged bodies, then apply fillets, chamfers, or shell operations. - - Use `@scad.part` for one physical single-solid product, `@scad.assemble` for explicit durable assembly definitions, and `@scad.model` only for replayable geometry flows that are not product build boundaries. `@scad.model` owns one `GraphSession`; use `@scad.requires_session` for child graph builders. + - Use `@scad.part` for one physical single-solid product and `@scad.assemble` for explicit durable assembly definitions. Use an explicit `GraphSession` for replayable geometry flows. - Use QL for grounding and selection. Query the facts you need, such as face normals, centers, areas, edge lengths, curve types, and tags. - Use indexed child-geometry getters such as `get_edges(index)` and `get_faces(index)` when an indexed topology pick is intentional. - Use semantic tags for design intent and anchors. Keep numeric measurements and geometry facts in metadata or model JSON payloads. - - Treat `ModelResult.model_json` as the interchange boundary for new model entry points. Use `export_model_json(session=...)` for lower-level direct sessions. + - Treat `export_model_json(session=...)` as the interchange boundary for replayable geometry. Capture final outputs with `session.capture_result(...)` and replay with `replay_model_json(json_str=...)`. - Validate incrementally: after each major step, print small QL-derived facts such as selected face count, top face center, edge count, volume, or replay result count. - Read `references/docs/guides/cache-build-workflow.md` before configuring persistent cache or using `@scad.part`/`@scad.assemble`. @@ -773,18 +763,15 @@ class SkillPackager: ```python import simplecadapi as scad + from simplecadapi import GraphSession, export_model_json, replay_model_json - @scad.model(graph_id="bracket") - def build_bracket(): + with GraphSession(graph_id="bracket") as session: body = scad.make_box_rsolid(width=20.0, height=10.0, depth=3.0) - scad.capture_result(value=body) - return body + session.capture_result(value=body) + payload = export_model_json(session=session) - result = build_bracket() - payload = result.model_json - rebuilt = result.replay() + rebuilt = replay_model_json(json_str=payload) ``` - ## 2) Build a durable cached part ```python @@ -808,10 +795,8 @@ class SkillPackager: import simplecadapi as scad ``` - ## 4) Keep replay payloads as the interchange boundary - - - Prefer `export_model_json()` output instead of hand-written payloads. - - Use `ModelResult.replay()` for a model invocation, or `replay_model_json(json_str=...)` when consuming standalone model JSON. + - Prefer `export_model_json(session=...)` output instead of hand-written payloads. + - Use `session.capture_result(...)` when the final output should not be inferred from all graph leaves, then use `replay_model_json(json_str=...)` when consuming standalone model JSON. - Use `import_model_json()` when consuming previously exported payloads. ## 5) Use standard parts when they fit @@ -841,10 +826,10 @@ class SkillPackager: ```python import simplecadapi as scad + from simplecadapi import GraphSession, export_model_json, replay_model_json from simplecadapi import ql - @scad.model(graph_id="swept_profile") - def build_model(): + with GraphSession(graph_id="swept_profile") as session: profile = scad.make_circle_rface(center=(0, 0, 0), radius=1.0) body = scad.extrude_rsolid( profile=profile, @@ -862,11 +847,10 @@ class SkillPackager: print("end face center", end_face.get_center()) path = scad.make_segment_rwire(start=(0, 0, 4), end=(0, 0, 8)) swept = scad.sweep_rsolid(profile=end_face, path=path) - scad.capture_result(value=swept) - return swept + session.capture_result(value=swept) + payload = export_model_json(session=session) - result = build_model() - rebuilt = result.replay() + rebuilt = replay_model_json(json_str=payload) print("rebuilt", len(rebuilt)) ``` diff --git a/src/simplecadapi/capture.py b/src/simplecadapi/capture.py new file mode 100644 index 00000000..0fbf932f --- /dev/null +++ b/src/simplecadapi/capture.py @@ -0,0 +1,65 @@ +"""Unified durable product capture boundary.""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from .artifacts.assembly_definition import AssemblyDefinition +from .artifacts.assembly_io import materialize_definition +from .artifacts.part_definition import PartDefinition +from .product import Assembly, Part +from .product_packages import ( + ProductPackage, + build_product_package, + encode_product_package, +) +from .scene.product_scene import ProductScenePackage, read_scene_package + + +@dataclass(frozen=True, slots=True) +class CaptureResult: + """Runtime value plus one complete durable product snapshot.""" + + value: Part | Assembly + definition: PartDefinition | AssemblyDefinition + package: ProductPackage + scene: ProductScenePackage + package_bytes: bytes + + +def capture(result: Any, path: str | Path, /) -> CaptureResult: + """Capture a durable product and write its canonical `.scadpkg`.""" + + definition = ( + result + if isinstance(result, (PartDefinition, AssemblyDefinition)) + else getattr(result, "definition", None) + ) + if not isinstance(definition, (PartDefinition, AssemblyDefinition)): + raise TypeError( + "result must be a PartDefinition, AssemblyDefinition, PartBuildResult, " + "or AssemblyBuildResult" + ) + runtime = getattr(result, "value", None) + if runtime is None: + runtime = materialize_definition(definition) + if not isinstance(runtime, (Part, Assembly)): + raise TypeError("captured runtime value must be a Part or Assembly") + package = build_product_package(definition) + package_bytes = encode_product_package(package) + destination = Path(path) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(package_bytes) + scene = read_scene_package(package.scene_bytes) + return CaptureResult( + value=runtime, + definition=definition, + package=package, + scene=scene, + package_bytes=package_bytes, + ) + + +__all__ = ["CaptureResult", "capture"] diff --git a/src/simplecadapi/contracts/assembly-definition-1.schema.json b/src/simplecadapi/contracts/assembly-definition-2.schema.json similarity index 88% rename from src/simplecadapi/contracts/assembly-definition-1.schema.json rename to src/simplecadapi/contracts/assembly-definition-2.schema.json index 6ae62254..2fbc0944 100644 --- a/src/simplecadapi/contracts/assembly-definition-1.schema.json +++ b/src/simplecadapi/contracts/assembly-definition-2.schema.json @@ -1,12 +1,12 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://simplecad.dev/schemas/assembly-definition-1.schema.json", - "title": "SimpleCAD AssemblyDefinition 1.0", + "$id": "https://simplecad.dev/schemas/assembly-definition-2.schema.json", + "title": "SimpleCAD AssemblyDefinition 2.0", "type": "object", "additionalProperties": false, - "required": ["schema_version", "artifact_kind", "definition_kind", "definition_id", "revision", "content_hash", "units", "tolerance_profile", "profile", "generator", "definition_refs", "instances", "relations", "grounded_instance_ids", "public_connectors", "interface_hashes", "solved_snapshot", "model_ref", "metadata"], + "required": ["schema_version", "artifact_kind", "definition_kind", "definition_id", "revision", "content_hash", "units", "tolerance_profile", "profile", "generator", "definition_refs", "instances", "relations", "grounded_instance_ids", "public_connectors", "interface_hashes", "solved_snapshot", "feature_graph_ref", "metadata"], "properties": { - "schema_version": {"const": "1.0"}, + "schema_version": {"const": "2.0"}, "artifact_kind": {"const": "assembly_definition"}, "definition_kind": {"const": "assembly"}, "definition_id": {"$ref": "#/$defs/id"}, @@ -14,7 +14,7 @@ "content_hash": {"$ref": "#/$defs/hash"}, "units": {"const": "mm"}, "tolerance_profile": {"type": "string", "minLength": 1, "maxLength": 128}, - "profile": {"const": "simplecad-assembly-definition-1"}, + "profile": {"const": "simplecad-assembly-definition-2"}, "generator": {"$ref": "#/$defs/generator"}, "definition_refs": {"type": "array", "maxItems": 25000, "items": {"$ref": "#/$defs/partRef"}}, "instances": {"type": "array", "maxItems": 100000, "items": {"$ref": "#/$defs/instance"}}, @@ -23,7 +23,7 @@ "public_connectors": {"type": "array", "maxItems": 100000, "items": {"$ref": "#/$defs/connector"}}, "interface_hashes": {"$ref": "#/$defs/interfaceHashes"}, "solved_snapshot": {"type": ["object", "null"]}, - "model_ref": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/blobRef"}]}, + "feature_graph_ref": {"$ref": "#/$defs/blobRef"}, "metadata": {"type": "object"} }, "$defs": { @@ -38,7 +38,7 @@ "partRef": {"type": "object", "additionalProperties": false, "required": ["definition_id", "definition_kind", "path", "revision", "content_hash", "byte_length"], "properties": {"definition_id": {"$ref": "#/$defs/id"}, "definition_kind": {"enum": ["single_solid", "assembly"]}, "path": {"$ref": "#/$defs/path"}, "revision": {"$ref": "#/$defs/revision"}, "content_hash": {"$ref": "#/$defs/hash"}, "byte_length": {"type": "integer", "minimum": 0, "maximum": 9007199254740991}}}, "instance": {"type": "object", "additionalProperties": false, "required": ["instance_id", "definition_id", "name", "placement"], "properties": {"instance_id": {"$ref": "#/$defs/id"}, "definition_id": {"$ref": "#/$defs/id"}, "name": {"type": ["string", "null"], "minLength": 1}, "placement": {"$ref": "#/$defs/frame"}}}, "connectorRef": {"type": "object", "additionalProperties": false, "required": ["component_id", "connector_id"], "properties": {"component_id": {"$ref": "#/$defs/id"}, "connector_id": {"$ref": "#/$defs/id"}}}, - "relation": {"type": "object", "additionalProperties": false, "required": ["constraint_id", "constraint_kind", "connector_a", "connector_b", "drive_distance", "distance_limit", "drive_angle_degrees", "angle_limit", "pitch_radius_a", "pitch_radius_b", "pulley_radius_a", "pulley_radius_b", "pitch_radius", "phase_offset", "name"], "properties": {"constraint_id": {"$ref": "#/$defs/id"}, "constraint_kind": {"enum": ["fixed", "revolute", "prismatic", "gear", "belt", "rack_pinion"]}, "connector_a": {"$ref": "#/$defs/connectorRef"}, "connector_b": {"$ref": "#/$defs/connectorRef"}, "drive_distance": {"type": ["number", "null"]}, "distance_limit": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/scalarLimit"}]}, "drive_angle_degrees": {"type": ["number", "null"]}, "angle_limit": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/scalarLimit"}]}, "pitch_radius_a": {"type": ["number", "null"], "exclusiveMinimum": 0}, "pitch_radius_b": {"type": ["number", "null"], "exclusiveMinimum": 0}, "pulley_radius_a": {"type": ["number", "null"], "exclusiveMinimum": 0}, "pulley_radius_b": {"type": ["number", "null"], "exclusiveMinimum": 0}, "pitch_radius": {"type": ["number", "null"], "exclusiveMinimum": 0}, "phase_offset": {"type": ["number", "null"]}, "name": {"type": ["string", "null"], "minLength": 1}}}, + "relation": {"type": "object", "additionalProperties": false, "required": ["constraint_id", "constraint_kind", "connector_a", "connector_b", "drive_distance", "distance_limit", "drive_angle_degrees", "angle_limit", "pitch_radius_a", "pitch_radius_b", "pulley_radius_a", "pulley_radius_b", "pitch_radius", "phase_offset", "name"], "properties": {"constraint_id": {"$ref": "#/$defs/id"}, "constraint_kind": {"enum": ["fixed", "revolute", "prismatic", "gear", "belt", "rack_pinion"]}, "connector_a": {"$ref": "#/$defs/connectorRef"}, "connector_b": {"$ref": "#/$defs/connectorRef"}, "drive_distance": {"type": ["number", "null"]}, "distance_limit": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/scalarLimit"}]}, "drive_angle_degrees": {"type": ["number", "null"]}, "angle_limit": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/scalarLimit"}]}, "pitch_radius_a": {"type": ["number", "null"]}, "pitch_radius_b": {"type": ["number", "null"]}, "pulley_radius_a": {"type": ["number", "null"]}, "pulley_radius_b": {"type": ["number", "null"]}, "pitch_radius": {"type": ["number", "null"]}, "phase_offset": {"type": ["number", "null"]}, "name": {"type": ["string", "null"], "minLength": 1}}}, "scalarLimit": {"type": "object", "additionalProperties": false, "required": ["lower_value", "upper_value"], "properties": {"lower_value": {"type": "number"}, "upper_value": {"type": "number"}}}, "connector": {"type": "object", "additionalProperties": false, "required": ["connector_id", "name", "anchor_kind", "local_frame", "binding", "forwarded_from", "interface_hash", "binding_hash"], "properties": {"connector_id": {"$ref": "#/$defs/id"}, "name": {"type": ["string", "null"], "minLength": 1}, "anchor_kind": {"const": "forwarded"}, "local_frame": {"$ref": "#/$defs/frame"}, "binding": {"type": "null"}, "forwarded_from": {"type": "object", "additionalProperties": false, "required": ["component_id", "connector_id"], "properties": {"component_id": {"$ref": "#/$defs/id"}, "connector_id": {"$ref": "#/$defs/id"}}}, "interface_hash": {"$ref": "#/$defs/hash"}, "binding_hash": {"$ref": "#/$defs/hash"}}}, "hashMap": {"type": "object", "propertyNames": {"$ref": "#/$defs/id"}, "additionalProperties": {"$ref": "#/$defs/hash"}}, diff --git a/src/simplecadapi/contracts/feature-graph-1.schema.json b/src/simplecadapi/contracts/feature-graph-1.schema.json new file mode 100644 index 00000000..f15d7eee --- /dev/null +++ b/src/simplecadapi/contracts/feature-graph-1.schema.json @@ -0,0 +1,120 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://simplecad.dev/schemas/feature-graph-1.schema.json", + "title": "SimpleCAD FeatureGraphArtifact 1.0", + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "artifact_kind", + "profile", + "owner", + "graph", + "result_node_ids", + "external_definitions", + "expression_graph", + "tolerance_graph", + "frame_graph", + "semantic_index", + "source_files", + "content_hash" + ], + "properties": { + "schema_version": {"const": "1.0"}, + "artifact_kind": {"const": "feature_graph"}, + "profile": {"const": "simplecad-feature-graph-1"}, + "owner": { + "type": "object", + "additionalProperties": false, + "required": ["definition_kind", "definition_id", "revision"], + "properties": { + "definition_kind": {"enum": ["single_solid", "assembly"]}, + "definition_id": {"$ref": "#/$defs/id"}, + "revision": {"$ref": "#/$defs/revision"} + } + }, + "graph": { + "type": "object", + "additionalProperties": true, + "required": ["schema_version", "producer_version", "capabilities", "graph_id", "nodes", "edges"], + "properties": { + "schema_version": {"type": "string", "pattern": "^2\\."}, + "producer_version": {"type": "string", "minLength": 1}, + "capabilities": {"type": "object"}, + "graph_id": {"$ref": "#/$defs/id"}, + "nodes": {"type": "array", "maxItems": 1000000, "items": {"type": "object"}}, + "edges": {"type": "array", "maxItems": 4000000, "items": {"type": "array", "minItems": 2, "maxItems": 2, "items": {"type": "string"}}} + } + }, + "result_node_ids": { + "type": "array", + "minItems": 1, + "maxItems": 1, + "items": {"type": "string", "minLength": 1} + }, + "external_definitions": { + "type": "array", + "maxItems": 25000, + "items": {"$ref": "#/$defs/externalDefinition"} + }, + "expression_graph": {"type": "object"}, + "tolerance_graph": {"type": "object"}, + "frame_graph": {"type": "object"}, + "semantic_index": { + "type": "object", + "additionalProperties": false, + "required": [ + "geometry_registry", + "semantic_entity_registry", + "sketch_profile_registry", + "semantic_delta_log", + "topology_delta_log", + "semantic_bindings" + ], + "properties": { + "geometry_registry": {"type": "array", "items": {"type": "object"}}, + "semantic_entity_registry": {"type": "array", "items": {"type": "object"}}, + "sketch_profile_registry": {"type": "array", "items": {"type": "object"}}, + "semantic_delta_log": {"type": "array", "items": {"type": "object"}}, + "topology_delta_log": {"type": "array", "items": {"type": "object"}}, + "semantic_bindings": {"type": "array", "items": {"type": "object"}} + } + }, + "source_files": { + "type": "array", + "maxItems": 4096, + "items": {"$ref": "#/$defs/sourceFile"} + }, + "content_hash": {"$ref": "#/$defs/hash"} + }, + "$defs": { + "id": {"type": "string", "minLength": 1, "maxLength": 256, "pattern": "^[A-Za-z][A-Za-z0-9_.:-]*$"}, + "revision": {"type": "string", "minLength": 1, "maxLength": 128, "pattern": "^[A-Za-z0-9][A-Za-z0-9._+-]*$"}, + "hash": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"}, + "path": {"type": "string", "minLength": 1, "maxLength": 4096}, + "externalDefinition": { + "type": "object", + "additionalProperties": false, + "required": ["definition_kind", "definition_id", "revision", "content_hash"], + "properties": { + "definition_kind": {"enum": ["single_solid", "assembly"]}, + "definition_id": {"$ref": "#/$defs/id"}, + "revision": {"$ref": "#/$defs/revision"}, + "content_hash": {"$ref": "#/$defs/hash"} + } + }, + "sourceFile": { + "type": "object", + "additionalProperties": false, + "required": ["source_file_id", "display_path", "path_kind", "content_hash", "byte_length", "uri"], + "properties": { + "source_file_id": {"$ref": "#/$defs/hash"}, + "display_path": {"$ref": "#/$defs/path"}, + "path_kind": {"enum": ["project_relative", "external"]}, + "content_hash": {"$ref": "#/$defs/hash"}, + "byte_length": {"type": "integer", "minimum": 0, "maximum": 9007199254740991}, + "uri": {"type": "string", "pattern": "^sources/sha256/[0-9a-f]{64}\\.py$"} + } + } + } +} diff --git a/src/simplecadapi/contracts/part-definition-1.schema.json b/src/simplecadapi/contracts/part-definition-2.schema.json similarity index 93% rename from src/simplecadapi/contracts/part-definition-1.schema.json rename to src/simplecadapi/contracts/part-definition-2.schema.json index c2104a5a..50a0dd19 100644 --- a/src/simplecadapi/contracts/part-definition-1.schema.json +++ b/src/simplecadapi/contracts/part-definition-2.schema.json @@ -1,12 +1,12 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://simplecad.dev/schemas/part-definition-1.schema.json", - "title": "SimpleCAD PartDefinition 1.0", + "$id": "https://simplecad.dev/schemas/part-definition-2.schema.json", + "title": "SimpleCAD PartDefinition 2.0", "type": "object", "additionalProperties": false, "required": ["schema_version", "artifact_kind", "definition_kind", "definition_id", "revision", "content_hash", "units", "tolerance_profile", "profile", "generator", "definition", "solid_cache", "topology_snapshot_ref", "connectors", "material_ref", "file_inputs", "interface_hashes", "metadata"], "properties": { - "schema_version": {"const": "1.0"}, + "schema_version": {"const": "2.0"}, "artifact_kind": {"const": "part_definition"}, "definition_kind": {"const": "single_solid"}, "definition_id": {"$ref": "#/$defs/id"}, @@ -14,15 +14,15 @@ "content_hash": {"$ref": "#/$defs/hash"}, "units": {"const": "mm"}, "tolerance_profile": {"type": "string", "minLength": 1, "maxLength": 128}, - "profile": {"const": "simplecad-part-definition-1"}, + "profile": {"const": "simplecad-part-definition-2"}, "generator": {"$ref": "#/$defs/generator"}, "definition": { "type": "object", "additionalProperties": false, - "required": ["kind", "model_ref"], + "required": ["kind", "feature_graph_ref"], "properties": { - "kind": {"const": "feature_dag_snapshot"}, - "model_ref": {"$ref": "#/$defs/blobRef"} + "kind": {"const": "feature_graph"}, + "feature_graph_ref": {"$ref": "#/$defs/blobRef"} } }, "solid_cache": { diff --git a/src/simplecadapi/contracts/product-package-1.schema.json b/src/simplecadapi/contracts/product-package-1.schema.json deleted file mode 100644 index a95dbfa5..00000000 --- a/src/simplecadapi/contracts/product-package-1.schema.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://simplecad.dev/schemas/product-package-1.schema.json", - "title": "SimpleCAD Product Package 1.0", - "type": "object", - "additionalProperties": false, - "required": ["schema_version", "artifact_kind", "root", "objects", "content_hash"], - "properties": { - "schema_version": {"const": "1.0"}, - "artifact_kind": {"const": "product_package"}, - "root": {"$ref": "#/$defs/path"}, - "objects": { - "type": "array", - "minItems": 1, - "maxItems": 25000, - "items": {"$ref": "#/$defs/object"} - }, - "content_hash": {"$ref": "#/$defs/hash"} - }, - "$defs": { - "id": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "pattern": "^[A-Za-z][A-Za-z0-9_.:-]*$" - }, - "revision": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "pattern": "^[A-Za-z0-9][A-Za-z0-9._+-]*$" - }, - "hash": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"}, - "path": { - "type": "string", - "minLength": 1, - "maxLength": 4096, - "pattern": "^[A-Za-z0-9][A-Za-z0-9._/-]*$" - }, - "object": { - "type": "object", - "additionalProperties": false, - "required": [ - "path", - "definition_kind", - "definition_id", - "revision", - "content_hash", - "sha256", - "byte_length" - ], - "properties": { - "path": {"$ref": "#/$defs/path"}, - "definition_kind": {"enum": ["single_solid", "assembly"]}, - "definition_id": {"$ref": "#/$defs/id"}, - "revision": {"$ref": "#/$defs/revision"}, - "content_hash": {"$ref": "#/$defs/hash"}, - "sha256": {"$ref": "#/$defs/hash"}, - "byte_length": {"type": "integer", "minimum": 0, "maximum": 9007199254740991} - } - } - } -} diff --git a/src/simplecadapi/contracts/product-package-2.schema.json b/src/simplecadapi/contracts/product-package-2.schema.json new file mode 100644 index 00000000..b29bea7e --- /dev/null +++ b/src/simplecadapi/contracts/product-package-2.schema.json @@ -0,0 +1,54 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://simplecad.dev/schemas/product-package-2.schema.json", + "title": "SimpleCAD Product Package 2.0", + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "artifact_kind", "root", "objects", "scene", "content_hash"], + "properties": { + "schema_version": {"const": "2.0"}, + "artifact_kind": {"const": "product_package"}, + "root": {"$ref": "#/$defs/path"}, + "objects": { + "type": "array", + "minItems": 1, + "maxItems": 25000, + "items": {"$ref": "#/$defs/object"} + }, + "scene": {"$ref": "#/$defs/scene"}, + "content_hash": {"$ref": "#/$defs/hash"} + }, + "$defs": { + "id": {"type": "string", "minLength": 1, "maxLength": 256, "pattern": "^[A-Za-z][A-Za-z0-9_.:-]*$"}, + "revision": {"type": "string", "minLength": 1, "maxLength": 128, "pattern": "^[A-Za-z0-9][A-Za-z0-9._+-]*$"}, + "hash": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"}, + "path": {"type": "string", "minLength": 1, "maxLength": 4096, "pattern": "^[A-Za-z0-9][A-Za-z0-9._/-]*$"}, + "object": { + "type": "object", + "additionalProperties": false, + "required": ["path", "definition_kind", "definition_id", "revision", "content_hash", "sha256", "byte_length"], + "properties": { + "path": {"$ref": "#/$defs/path"}, + "definition_kind": {"enum": ["single_solid", "assembly"]}, + "definition_id": {"$ref": "#/$defs/id"}, + "revision": {"$ref": "#/$defs/revision"}, + "content_hash": {"$ref": "#/$defs/hash"}, + "sha256": {"$ref": "#/$defs/hash"}, + "byte_length": {"type": "integer", "minimum": 0, "maximum": 9007199254740991} + } + }, + "scene": { + "type": "object", + "additionalProperties": false, + "required": ["path", "media_type", "scene_id", "revision", "sha256", "byte_length"], + "properties": { + "path": {"const": "scene/scene.zip"}, + "media_type": {"const": "application/vnd.simplecad.scene+zip"}, + "scene_id": {"$ref": "#/$defs/id"}, + "revision": {"$ref": "#/$defs/hash"}, + "sha256": {"$ref": "#/$defs/hash"}, + "byte_length": {"type": "integer", "minimum": 0, "maximum": 9007199254740991} + } + } + } +} diff --git a/src/simplecadapi/exporter/__init__.py b/src/simplecadapi/exporter/__init__.py new file mode 100644 index 00000000..d41319ef --- /dev/null +++ b/src/simplecadapi/exporter/__init__.py @@ -0,0 +1,11 @@ +"""Product-package exporters for neutral CAD and mesh formats.""" + +from .step import ProductSTEPExportReport, export_product_package_to_step +from .stl import ProductSTLExportReport, export_product_package_to_stl + +__all__ = [ + "ProductSTEPExportReport", + "ProductSTLExportReport", + "export_product_package_to_step", + "export_product_package_to_stl", +] diff --git a/src/simplecadapi/exporter/step.py b/src/simplecadapi/exporter/step.py new file mode 100644 index 00000000..09af1b86 --- /dev/null +++ b/src/simplecadapi/exporter/step.py @@ -0,0 +1,346 @@ +"""AP242 STEP export for validated product packages.""" + +from __future__ import annotations + +from dataclasses import dataclass +import json +from pathlib import Path +from typing import Any + +from OCP.BRep import BRep_Builder +from OCP.IFSelect import IFSelect_RetDone +from OCP.Interface import Interface_Static +from OCP.Quantity import Quantity_Color, Quantity_TOC_RGB +from OCP.STEPCAFControl import STEPCAFControl_Writer +from OCP.StepBasic import StepBasic_ProductDefinition +from OCP.StepRepr import ( + StepRepr_CharacterizedDefinition, + StepRepr_DescriptiveRepresentationItem, + StepRepr_HArray1OfRepresentationItem, + StepRepr_ProductDefinitionShape, + StepRepr_PropertyDefinition, + StepRepr_PropertyDefinitionRepresentation, + StepRepr_Representation, + StepRepr_RepresentedDefinition, +) +from OCP.StepShape import StepShape_ShapeDefinitionRepresentation +from OCP.TCollection import TCollection_ExtendedString, TCollection_HAsciiString +from OCP.TDataStd import TDataStd_Comment, TDataStd_Name +from OCP.TDocStd import TDocStd_Document +from OCP.TopLoc import TopLoc_Location +from OCP.TopoDS import TopoDS_Compound +from OCP.XCAFApp import XCAFApp_Application +from OCP.XCAFDoc import XCAFDoc_ColorSurf, XCAFDoc_DocumentTool +from OCP.gp import gp_Trsf + +from ..artifacts import materialize_definition +from ..product import Assembly, Material, Part, Placement +from ..translator.package_units import ( + ProductPackageInput, + read_product_package_translation_units, +) + + +@dataclass(frozen=True, slots=True) +class ProductSTEPExportReport: + """Observed AP242 export facts and explicit semantic limitations.""" + + output_path: Path + schema: str + definition_ids: tuple[str, ...] + occurrence_count: int + material_ids: tuple[str, ...] + metadata_item_count: int + limitations: tuple[str, ...] + + def to_dict(self) -> dict[str, Any]: + return { + "output_path": str(self.output_path), + "schema": self.schema, + "definition_ids": list(self.definition_ids), + "occurrence_count": self.occurrence_count, + "material_ids": list(self.material_ids), + "metadata_item_count": self.metadata_item_count, + "limitations": list(self.limitations), + } + + +def _extended(value: str) -> TCollection_ExtendedString: + return TCollection_ExtendedString(str(value)) + + +def _ascii(value: str) -> TCollection_HAsciiString: + return TCollection_HAsciiString(str(value)) + + +def _set_name(label: Any, value: str) -> None: + TDataStd_Name.Set_s(label, _extended(value)) + + +def _set_comment(label: Any, payload: dict[str, Any]) -> None: + TDataStd_Comment.Set_s( + label, + _extended(json.dumps(payload, ensure_ascii=True, sort_keys=True)), + ) + + +def _placement_location(placement: Placement) -> TopLoc_Location: + transform = gp_Trsf() + transform.SetValues( + placement.x_axis[0], + placement.y_axis[0], + placement.z_axis[0], + placement.origin[0], + placement.x_axis[1], + placement.y_axis[1], + placement.z_axis[1], + placement.origin[1], + placement.x_axis[2], + placement.y_axis[2], + placement.z_axis[2], + placement.origin[2], + ) + return TopLoc_Location(transform) + + +def _empty_compound() -> TopoDS_Compound: + builder = BRep_Builder() + compound = TopoDS_Compound() + builder.MakeCompound(compound) + return compound + + +def _material_density(material: Material) -> tuple[float, str, str]: + if material.density is None: + return 0.0, "", "" + return float(material.density), str(material.density_unit or ""), "mass density" + + +def _inject_metadata_properties( + writer: STEPCAFControl_Writer, + records: list[tuple[str, dict[str, Any]]], +) -> None: + if not records: + return + model = writer.ChangeWriter().WS().Model() + root_definition = None + context = None + for index in range(1, model.NbEntities() + 1): + entity = model.Entity(index) + if not isinstance(entity, StepShape_ShapeDefinitionRepresentation): + continue + represented = entity.Definition().Value() + if not isinstance(represented, StepRepr_ProductDefinitionShape): + continue + characterized = represented.Definition().Value() + if not isinstance(characterized, StepBasic_ProductDefinition): + continue + root_definition = characterized + context = entity.UsedRepresentation().ContextOfItems() + break + if root_definition is None or context is None: + raise RuntimeError("STEPCAF transfer did not create a root product definition") + + items = StepRepr_HArray1OfRepresentationItem(1, len(records)) + for index, (name, payload) in enumerate(records, start=1): + item = StepRepr_DescriptiveRepresentationItem() + item.Init( + _ascii(name), + _ascii(json.dumps(payload, ensure_ascii=True, sort_keys=True)), + ) + items.SetValue(index, item) + representation = StepRepr_Representation() + representation.Init(_ascii("SimpleCAD metadata"), items, context) + characterized_definition = StepRepr_CharacterizedDefinition() + characterized_definition.SetValue(root_definition) + property_definition = StepRepr_PropertyDefinition() + property_definition.Init( + _ascii("SimpleCAD metadata"), + True, + _ascii("Canonical product definition and occurrence metadata"), + characterized_definition, + ) + represented_definition = StepRepr_RepresentedDefinition() + represented_definition.SetValue(property_definition) + property_representation = StepRepr_PropertyDefinitionRepresentation() + property_representation.Init(represented_definition, representation) + model.AddWithRefs(property_representation) + + +def export_product_package_to_step( + data: ProductPackageInput, + output_path: str | Path, +) -> ProductSTEPExportReport: + """Export a validated `.scadpkg` closure as XCAF-backed AP242 STEP.""" + + package, units = read_product_package_translation_units(data) + root_value = materialize_definition(package.root_definition) + destination = Path(output_path).expanduser().resolve() + if destination.suffix.lower() not in {".step", ".stp"}: + raise ValueError("output_path must end in .step or .stp") + destination.parent.mkdir(parents=True, exist_ok=True) + + XCAFApp_Application.GetApplication_s() + document = TDocStd_Document(_extended("BinXCAF")) + shape_tool = XCAFDoc_DocumentTool.ShapeTool_s(document.Main()) + color_tool = XCAFDoc_DocumentTool.ColorTool_s(document.Main()) + material_tool = XCAFDoc_DocumentTool.MaterialTool_s(document.Main()) + labels_by_identity: dict[tuple[str, str], Any] = {} + material_labels: dict[str, Any] = {} + units_by_identity = { + (unit.definition_kind, unit.definition_id): unit for unit in units + } + metadata_records: list[tuple[str, dict[str, Any]]] = [] + occurrence_count = 0 + + def material_label(material: Material) -> Any: + existing = material_labels.get(material.material_id) + if existing is not None: + return existing + density, density_name, density_value_type = _material_density(material) + label = material_tool.AddMaterial( + _ascii(material.name or material.material_id), + _ascii(json.dumps(material.to_dict(), ensure_ascii=True, sort_keys=True)), + density, + _ascii(density_name), + _ascii(density_value_type), + ) + material_labels[material.material_id] = label + return label + + def definition_label(value: Part | Assembly) -> Any: + nonlocal occurrence_count + kind = "assembly" if isinstance(value, Assembly) else "single_solid" + definition_id = ( + value.assembly_id if isinstance(value, Assembly) else value.part_id + ) + identity = (kind, definition_id) + existing = labels_by_identity.get(identity) + unit = units_by_identity.get(identity) + if unit is None: + raise RuntimeError( + f"materialized definition {kind}:{definition_id} is absent from package units" + ) + if existing is not None: + return existing + if isinstance(value, Part): + label = shape_tool.AddShape(value.body.wrapped, False, False) + labels_by_identity[identity] = label + _set_name(label, value.name or value.part_id) + metadata = { + "record_kind": "definition", + "definition_id": value.part_id, + "definition_kind": kind, + "revision": unit.revision, + "content_hash": unit.content_hash, + "connectors": [connector.to_dict() for connector in value.connectors], + } + _set_comment(label, metadata) + metadata_records.append( + (f"SimpleCAD:definition:{kind}:{definition_id}", metadata) + ) + if value.material is not None: + material_tool.SetMaterial(label, material_label(value.material)) + if value.material.color is not None: + color_tool.SetColor( + label, + Quantity_Color(*value.material.color, Quantity_TOC_RGB), + XCAFDoc_ColorSurf, + ) + return label + + label = shape_tool.AddShape(_empty_compound(), False, False) + labels_by_identity[identity] = label + _set_name(label, value.name or value.assembly_id) + metadata = { + "record_kind": "definition", + "definition_id": value.assembly_id, + "definition_kind": kind, + "revision": unit.revision, + "content_hash": unit.content_hash, + "connectors": [connector.to_dict() for connector in value.connectors], + "constraints": [constraint.to_dict() for constraint in value.constraints], + "grounded_component_ids": list(value.grounded_component_ids), + } + _set_comment(label, metadata) + metadata_records.append( + (f"SimpleCAD:definition:{kind}:{definition_id}", metadata) + ) + for component in value.components: + child_label = definition_label(component.item) + component_label = shape_tool.AddComponent( + label, + child_label, + _placement_location(component.placement), + ) + _set_name(component_label, component.name or component.component_id) + child_kind = ( + "assembly" if isinstance(component.item, Assembly) else "single_solid" + ) + child_id = ( + component.item.assembly_id + if isinstance(component.item, Assembly) + else component.item.part_id + ) + occurrence_metadata = { + "record_kind": "occurrence", + "parent_definition_id": definition_id, + "component_id": component.component_id, + "definition_id": child_id, + "definition_kind": child_kind, + "name": component.name, + "placement": component.placement.to_dict(), + } + _set_comment(component_label, occurrence_metadata) + metadata_records.append( + ( + f"SimpleCAD:occurrence:{definition_id}:{component.component_id}", + occurrence_metadata, + ) + ) + occurrence_count += 1 + shape_tool.UpdateAssemblies() + shape_tool.ComputeShapes(label) + return label + + root_label = definition_label(root_value) + shape_tool.UpdateAssemblies() + shape_tool.ComputeShapes(root_label) + + writer = STEPCAFControl_Writer() + writer.SetNameMode(True) + writer.SetColorMode(True) + writer.SetMaterialMode(True) + writer.SetPropsMode(True) + schema_key = "write.step.schema" + prior_schema = Interface_Static.CVal_s(schema_key) + if not Interface_Static.SetCVal_s(schema_key, "AP242DIS"): + raise RuntimeError("OCCT STEP writer does not expose AP242DIS schema selection") + try: + if not writer.Transfer(root_label): + raise RuntimeError("STEPCAF transfer failed") + _inject_metadata_properties(writer, metadata_records) + status = writer.Write(str(destination)) + if status != IFSelect_RetDone and int(status) != int(IFSelect_RetDone): + raise RuntimeError(f"STEPCAF write failed: {status}") + finally: + Interface_Static.SetCVal_s(schema_key, prior_schema) + + if not destination.is_file() or destination.stat().st_size <= 0: + raise RuntimeError("STEPCAF export did not create a non-empty STEP file") + limitations = ( + "Connector, constraint, grounding, revision, content-hash, and placement semantics are encoded as named AP242 descriptive property items containing deterministically sorted JSON.", + "The evaluated BREP and product structure are transferred through STEPCAF; canonical feature history is not reconstructed as AP242 features.", + ) + return ProductSTEPExportReport( + output_path=destination, + schema="AP242DIS", + definition_ids=tuple(unit.definition_id for unit in units), + occurrence_count=occurrence_count, + material_ids=tuple(sorted(material_labels)), + metadata_item_count=len(metadata_records), + limitations=limitations, + ) + + +__all__ = ["ProductSTEPExportReport", "export_product_package_to_step"] diff --git a/src/simplecadapi/exporter/stl.py b/src/simplecadapi/exporter/stl.py new file mode 100644 index 00000000..80ad37a3 --- /dev/null +++ b/src/simplecadapi/exporter/stl.py @@ -0,0 +1,167 @@ +"""Quad-dominant STL export for validated product packages.""" + +from __future__ import annotations + +from dataclasses import dataclass +import importlib +from pathlib import Path +import tempfile +from typing import Any + +from OCP.BRepTools import BRepTools + +from ..artifacts.assembly_io import materialize_definition +from ..operations import make_compound_from_assembly_rcompound +from ..product import Assembly, Part +from ..translator.package_units import ( + ProductPackageInput, + read_product_package_translation_units, +) + + +@dataclass(frozen=True, slots=True) +class ProductSTLExportReport: + """Evidence from quad-dominant product-surface remeshing and STL export.""" + + output_path: Path + root_definition_id: str + solid_count: int + definition_count: int + quadrilateral_count: int + residual_triangle_count: int + stl_triangle_count: int + quad_fraction: float + mesh_size: float + remesh_backend: str = "gmsh-quad-dominant" + + +def _load_gmsh() -> Any: + try: + return importlib.import_module("gmsh") + except ImportError as exc: + raise RuntimeError( + "Product STL export requires the 'gmsh' optional dependency; " + "install simplecadapi[gmsh]" + ) from exc + + +def _product_shape(value: Part | Assembly): + if isinstance(value, Part): + return value.body.wrapped, 1 + projection = make_compound_from_assembly_rcompound(assembly=value) + solid_count = int( + projection.get_metadata("assembly_projection", {}).get("solid_count", 0) + ) + if solid_count <= 0: + raise ValueError("Product assembly produced no solids for STL export") + return projection.wrapped, solid_count + + +def _surface_element_counts(gmsh: Any) -> tuple[int, int, int]: + quadrilaterals = 0 + triangles = 0 + stl_triangles = 0 + element_types, element_tags, _node_tags = gmsh.model.mesh.getElements(2) + for element_type, tags in zip(element_types, element_tags): + name, dimension, _order, node_count, _coords, primary_node_count = ( + gmsh.model.mesh.getElementProperties(element_type) + ) + if int(dimension) != 2: + continue + count = len(tags) + if int(primary_node_count) == 4 and "Quadrilateral" in str(name): + quadrilaterals += count + stl_triangles += 2 * count + elif int(primary_node_count) == 3 and "Triangle" in str(name): + triangles += count + stl_triangles += count + else: + raise RuntimeError( + f"Gmsh produced unsupported STL surface element {name!r} " + f"with {node_count} nodes" + ) + return quadrilaterals, triangles, stl_triangles + + +def export_product_package_to_stl( + data: ProductPackageInput, + output_path: str | Path, + *, + mesh_size: float = 1.0, + recombination_angle_degrees: float = 45.0, +) -> ProductSTLExportReport: + """Export one validated `.scadpkg` as a quad-dominant remeshed STL. + + Gmsh recombines each CAD surface into quadrilaterals before its STL writer + splits every quad into two triangles, as required by the STL file format. + """ + + size = float(mesh_size) + if size <= 0.0: + raise ValueError("mesh_size must be greater than zero") + angle = float(recombination_angle_degrees) + if not 0.0 < angle <= 180.0: + raise ValueError("recombination_angle_degrees must be in (0, 180]") + + package, units = read_product_package_translation_units(data) + root = materialize_definition(package.root_definition) + shape, solid_count = _product_shape(root) + destination = Path(output_path).expanduser().resolve() + if destination.suffix.lower() != ".stl": + raise ValueError("output_path must end in .stl") + destination.parent.mkdir(parents=True, exist_ok=True) + + gmsh = _load_gmsh() + initialized = False + with tempfile.TemporaryDirectory(prefix="simplecad_product_stl_") as temp_dir: + brep_path = Path(temp_dir) / "product.brep" + if not BRepTools.Write_s(shape, str(brep_path)): + raise RuntimeError( + "OpenCASCADE failed to serialize product BREP for remeshing" + ) + try: + gmsh.initialize() + initialized = True + gmsh.option.setNumber("General.Terminal", 0) + gmsh.model.add("SimpleCADProductSTL") + imported = gmsh.model.occ.importShapes( + str(brep_path), highestDimOnly=True, format="brep" + ) + if not imported: + raise RuntimeError("Gmsh imported no product geometry") + gmsh.model.occ.synchronize() + surfaces = gmsh.model.getEntities(2) + if not surfaces: + raise RuntimeError("Gmsh product geometry has no meshable surfaces") + gmsh.option.setNumber("Mesh.Algorithm", 8) + gmsh.option.setNumber("Mesh.RecombinationAlgorithm", 1) + gmsh.option.setNumber("Mesh.MeshSizeMin", size) + gmsh.option.setNumber("Mesh.MeshSizeMax", size) + for _dimension, tag in surfaces: + gmsh.model.mesh.setRecombine(2, tag, angle) + gmsh.model.mesh.generate(2) + quadrilaterals, triangles, stl_triangles = _surface_element_counts(gmsh) + if quadrilaterals + triangles == 0: + raise RuntimeError("Gmsh produced no surface elements") + gmsh.write(str(destination)) + finally: + if initialized: + gmsh.finalize() + + if not destination.is_file() or destination.stat().st_size <= 0: + raise RuntimeError("Gmsh did not create a non-empty STL file") + surface_count = quadrilaterals + triangles + return ProductSTLExportReport( + output_path=destination, + root_definition_id=package.root_definition.definition_id, + solid_count=solid_count, + definition_count=len(units), + quadrilateral_count=quadrilaterals, + residual_triangle_count=triangles, + stl_triangle_count=stl_triangles, + quad_fraction=quadrilaterals / surface_count, + mesh_size=size, + ) + + +__all__ = ["ProductSTLExportReport", "export_product_package_to_stl"] diff --git a/src/simplecadapi/graph.py b/src/simplecadapi/graph.py index 5f74b202..73ea3f8a 100644 --- a/src/simplecadapi/graph.py +++ b/src/simplecadapi/graph.py @@ -61,7 +61,7 @@ from .topology import ( TopoEvent, TopoRoleEntry, ) -from .topology import SemanticDelta +from .topology import SemanticDelta, SemanticRef from .topology import TopoKind, TopoRef, topo_ref_to_dict from .core import Compound, Edge, Face, Shell, Solid, Vertex, Wire, get_current_cs from .product import Assembly, Part @@ -102,7 +102,12 @@ class GraphSession: print(session.graph.topological_order()) """ - def __init__(self, graph_id: Optional[str] = None) -> None: + def __init__( + self, + graph_id: Optional[str] = None, + *, + allow_external_definitions: bool = False, + ) -> None: self.graph = OperationGraph(graph_id=graph_id) self.expression_graph = ExpressionGraph() self.tolerance_graph = ToleranceGraph(self.expression_graph) @@ -113,6 +118,9 @@ class GraphSession: self._captured_values: List[Any] = [] self._object_id_counters: Dict[str, int] = {} + self._external_definition_nodes: Dict[int, OperationNode] = {} + self._external_definition_nodes_by_id: Dict[str, OperationNode] = {} + self._allow_external_definitions = bool(allow_external_definitions) def start(self) -> None: if self._active_session_token is not None: @@ -138,6 +146,64 @@ class GraphSession: self._object_id_counters[prefix] = next_value return f"{prefix}_{next_value:08x}" + def register_external_definition( + self, + *, + value: Part | Assembly, + definition_kind: str, + definition_id: str, + revision: str, + content_hash: str, + ) -> OperationNode: + """Represent one immutable child definition without importing its DAG.""" + + marker = id(value) + existing = self._external_definition_nodes.get(marker) + if existing is not None: + return existing + expected_id = value.part_id if isinstance(value, Part) else value.assembly_id + expected_kind = "single_solid" if isinstance(value, Part) else "assembly" + if expected_id != definition_id or expected_kind != definition_kind: + raise ValueError("external definition runtime identity differs") + node = self.graph.add_node( + op="reference_definition", + params={ + "definition_kind": definition_kind, + "definition_id": definition_id, + "revision": revision, + "content_hash": content_hash, + }, + output_count=1, + semantic_delta=SemanticDelta( + created=( + SemanticRef( + graph_id="pending", + node_id="pending", + entity_type="ExternalDefinition", + entity_id=definition_id, + ), + ), + metadata={ + "definition_kind": definition_kind, + "revision": revision, + "content_hash": content_hash, + }, + ), + ) + self._external_definition_nodes[marker] = node + self._external_definition_nodes_by_id[definition_id] = node + return node + + def external_definition_node(self, value: Any) -> OperationNode | None: + direct = self._external_definition_nodes.get(id(value)) + if direct is not None: + return direct + if isinstance(value, Part): + return self._external_definition_nodes_by_id.get(value.part_id) + if isinstance(value, Assembly): + return self._external_definition_nodes_by_id.get(value.assembly_id) + return None + def require_tolerance( self, value: ScalarLike, @@ -259,38 +325,6 @@ class GraphSession: ) -@dataclass(frozen=True) -class ModelResult: - """The value and durable graph artifacts produced by ``@model``.""" - - value: Any - session: GraphSession - result_node_ids: Tuple[str, ...] - model_json: str - session_json: str - artifact_paths: Mapping[str, Path] = field(default_factory=dict) - - def replay(self, *, strict: bool = True) -> List[Any]: - """Replay the captured canonical model result.""" - - from .serializer import replay_model_json - - return replay_model_json(json_str=self.model_json, strict=strict) - - def export_artifacts( - self, - *, - output_dir: str | Path, - formats: Optional[Sequence[str]] = None, - ) -> "ModelResult": - """Export explicitly selected model, product, and scene artifacts. - - A generic ``@model`` keeps the historical ``scene`` default. Product - packages are opt-in until the dedicated ``@part``/``@assemble`` - decorators land. - """ - - return _export_model_artifacts(self, output_dir=output_dir, formats=formats) def get_active_session() -> Optional[GraphSession]: @@ -371,214 +405,6 @@ def _graph_nodes_in_value(value: Any, *, deep: bool = False) -> Iterable[Operati yield node -def capture_result(*, value: Any) -> Any: - """Capture *value* as an explicit result in the active model session.""" - - session = get_active_session() - if session is None: - raise RuntimeError( - "No active GraphSession. capture_result() must be called inside " - "@model or an active GraphSession." - ) - return session.capture_result(value=value) - - -def model( - func: Optional[Callable[_P, _R]] = None, - *, - graph_id: Optional[str] = None, - export_dir: str | Path | None = None, -) -> Union[ - Callable[[Callable[_P, _R]], Callable[_P, ModelResult]], - Callable[_P, ModelResult], -]: - """Decorate a top-level model function with one owned ``GraphSession``.""" - - def decorate(fn: Callable[_P, _R]) -> Callable[_P, ModelResult]: - if inspect.iscoroutinefunction(fn): - raise TypeError( - "@model does not support async functions; keep CAD model " - "construction synchronous" - ) - - @wraps(fn) - def wrapped(*args: _P.args, **kwargs: _P.kwargs) -> ModelResult: - active = get_active_session() - if active is not None: - raise RuntimeError( - "@model cannot be nested inside an active GraphSession; " - "use @requires_session for child builders." - ) - session = GraphSession(graph_id=graph_id) - with session: - value = fn(*args, **kwargs) - session.validate_graph_ownership(value) - if not session.has_explicit_results: - session.capture_result(value=value) - from .serializer import export_model_json, export_session_json - - result_node_ids = session.result_node_ids - model_json = export_model_json( - session=session, result_node_ids=result_node_ids - ) - session_json = export_session_json(session=session) - result = ModelResult( - value=value, - session=session, - result_node_ids=result_node_ids, - model_json=model_json, - session_json=session_json, - ) - return ( - result.export_artifacts(output_dir=export_dir) - if export_dir is not None - else result - ) - - return wrapped - - if func is None: - return decorate - return decorate(func) - - -def _export_model_artifacts( - result: ModelResult, - *, - output_dir: str | Path, - formats: Optional[Sequence[str]] = None, -) -> ModelResult: - from .scene import ( - SceneCompileOptions, - SceneRoot, - SceneSource, - compile_scene, - export_scene, - ) - - requested = _normalize_export_formats(formats) - destination = Path(output_dir) - destination.mkdir(parents=True, exist_ok=True) - stem = result.session.graph.graph_id - values = _captured_export_values(result.session.captured_values) - products = [value for value in values if isinstance(value, (Part, Assembly))] - shapes = [value for value in values if isinstance(value, (Solid, Compound))] - paths: Dict[str, Path] = {} - if "scene" in requested: - scene_values = products or shapes - if not scene_values: - raise ValueError("scene export requires a captured renderable value") - roots = tuple( - SceneRoot(root_id=f"capture-{index}", value=value) - for index, value in enumerate(scene_values) - ) - scene_source: Any = result - embed_source = True - package = compile_scene( - scene_id=stem, - roots=roots, - source=scene_source, - options=SceneCompileOptions(embed_source=embed_source), - ) - scene_path = destination / f"{stem}.scene.zip" - export_scene(package=package, path=scene_path) - paths["scene"] = scene_path - if "model" in requested: - model_path = destination / f"{stem}.model.json" - model_path.write_text(result.model_json, encoding="utf-8") - paths["model"] = model_path - if "session" in requested: - session_path = destination / f"{stem}.session.json" - session_path.write_text(result.session_json, encoding="utf-8") - paths["session"] = session_path - return ModelResult( - value=result.value, - session=result.session, - result_node_ids=result.result_node_ids, - model_json=result.model_json, - session_json=result.session_json, - artifact_paths=paths, - ) - - -def _normalize_export_formats(formats: Optional[Sequence[str]]) -> Tuple[str, ...]: - requested = ( - ("scene",) if formats is None else tuple(str(item).lower() for item in formats) - ) - allowed = {"scene", "model", "session"} - unknown = sorted(set(requested) - allowed) - if unknown: - raise ValueError( - "unknown @model export format(s): " - + ", ".join(unknown) - + "; durable product packages are exported from @part/@assemble results" - ) - if len(set(requested)) != len(requested): - raise ValueError("export formats must not contain duplicates") - if not requested: - raise ValueError("export formats must not be empty") - return requested - - -def _captured_export_values(values: Iterable[Any]) -> List[Any]: - result: List[Any] = [] - seen: Set[int] = set() - - def visit(value: Any) -> None: - if value is None or id(value) in seen: - return - if isinstance(value, (str, bytes, int, float, bool)): - return - seen.add(id(value)) - if isinstance(value, (Part, Assembly, Solid, Compound)): - result.append(value) - return - if isinstance(value, (list, tuple, set, frozenset)): - for item in value: - visit(item) - return - if is_dataclass(value): - for data_field in fields(value): - if not data_field.name.startswith("_"): - visit(getattr(value, data_field.name)) - - for value in values: - visit(value) - return result - - -def requires_session( - func: Optional[Callable[_P, _R]] = None, -) -> Union[ - Callable[[Callable[_P, _R]], Callable[_P, _R]], - Callable[_P, _R], -]: - """Decorate a builder that must reuse the caller's active GraphSession.""" - - def decorate(fn: Callable[_P, _R]) -> Callable[_P, _R]: - if inspect.iscoroutinefunction(fn): - raise TypeError( - "@requires_session does not support async functions; keep CAD " - "construction synchronous" - ) - - @wraps(fn) - def wrapped(*args: _P.args, **kwargs: _P.kwargs) -> _R: - session = get_active_session() - if session is None: - raise RuntimeError( - f"{fn.__name__} requires an active GraphSession; call it " - "from a @model function or inside `with GraphSession():`." - ) - value = fn(*args, **kwargs) - session.validate_graph_ownership(value) - return value - - return wrapped - - if func is None: - return decorate - return decorate(func) def _normalize_output_shapes(outputs: Any) -> List[Any]: @@ -589,14 +415,18 @@ def _normalize_output_shapes(outputs: Any) -> List[Any]: return [outputs] -def _extract_input_nodes(inputs: Optional[Iterable[Any]]) -> List[OperationNode]: +def _extract_input_nodes( + inputs: Optional[Iterable[Any]], session: GraphSession +) -> List[OperationNode]: if not inputs: return [] nodes: List[OperationNode] = [] seen: Set[str] = set() for obj in inputs: - for node, _graph_id in _graph_nodes_with_ids(obj): + external = session.external_definition_node(obj) + candidates = ((external, session.graph.graph_id),) if external else _graph_nodes_with_ids(obj) + for node, _graph_id in candidates: if node.node_id in seen: continue seen.add(node.node_id) @@ -608,6 +438,22 @@ def _validate_input_graph_ownership( inputs: Optional[Iterable[Any]], session: GraphSession ) -> None: for value in inputs or (): + if session.external_definition_node(value) is not None: + continue + if session._allow_external_definitions and isinstance(value, (Part, Assembly)): + definition_id = value.part_id if isinstance(value, Part) else value.assembly_id + definition_kind = "single_solid" if isinstance(value, Part) else "assembly" + revision = value._get_runtime("definition.revision") + content_hash = value._get_runtime("definition.content_hash") + if isinstance(revision, str) and isinstance(content_hash, str): + session.register_external_definition( + value=value, + definition_kind=definition_kind, + definition_id=definition_id, + revision=revision, + content_hash=content_hash, + ) + continue session.validate_graph_ownership(value) if isinstance(value, (Part, Assembly)) and _graph_node_and_id(value) is None: raise ValueError( @@ -1067,7 +913,7 @@ def record_operation_if_active( output_list = _normalize_output_shapes(outputs) input_list = list(input_shapes or ()) _validate_input_graph_ownership(input_list, session) - input_nodes = _extract_input_nodes(input_list) + input_nodes = _extract_input_nodes(input_list, session) node_id = session.graph.allocate_node_id() canonical_topo_delta = _canonicalize_recorded_topo_delta( topo_delta, diff --git a/src/simplecadapi/inspect/brep/__init__.py b/src/simplecadapi/inspect/brep/__init__.py index 8306fa80..67aa7821 100644 --- a/src/simplecadapi/inspect/brep/__init__.py +++ b/src/simplecadapi/inspect/brep/__init__.py @@ -135,8 +135,7 @@ def _outside_model_graph(function): if _get_active_session() is not None: raise RuntimeError( "simplecadapi.inspect.brep tools cannot run inside an active " - "GraphSession or @model function; inspect exported geometry " - "outside the modeling script" + "GraphSession; inspect exported geometry outside the modeling script" ) return function(*args, **kwargs) diff --git a/src/simplecadapi/operations.py b/src/simplecadapi/operations.py index b637b540..b2199d03 100644 --- a/src/simplecadapi/operations.py +++ b/src/simplecadapi/operations.py @@ -165,12 +165,7 @@ from .kernel.ocp_booleans import ( solids_of, ) from .kernel.ocp_topology import faces_of as faces_of_ocp -from .kernel.ocp_export import ( - export_step_shapes, - export_stl_shape, - make_compound, - make_compound_always, -) +from .kernel.ocp_export import make_compound_always from .kernel.ocp_surfaces import ( fill_shell_holes as fill_shell_holes_ocp, fit_point_grid_surface, @@ -9045,7 +9040,7 @@ _EXPORTABLE_TYPES = (Compound, Solid, Shell, Face, Wire, Edge, Vertex) def _normalize_shape_input( shapes: Union[AnyShape, Sequence[AnyShape]], ) -> List[AnyShape]: - """Normalize export input into a flat list of shapes.""" + """Normalize rendering input into a flat list of shapes.""" if isinstance(shapes, _EXPORTABLE_TYPES): return [shapes] @@ -9057,109 +9052,12 @@ def _normalize_shape_input( return normalized raise ValueError( - "export functions accept Compound, Solid, Shell, Face, Wire, Edge, Vertex, or nested sequences of those types" + "rendering accepts Compound, Solid, Shell, Face, Wire, Edge, Vertex, or nested sequences of those types" ) -def export_step(shapes: Union[AnyShape, Sequence[AnyShape]], filename: str) -> None: - """Export shapes to STEP. - - Args: - shapes: A single exportable shape or any nested sequence of exportable - shapes. Lists of Solid are supported directly, including pattern or - explicitly collected multi-shape results. - filename: Output STEP file path. - - Returns: - None: Writes the provided shapes into one STEP file. - - Usage: - Use this function when you want to export one shape or many shapes into the - same STEP file. Passing `List[Solid]` is valid for pattern outputs or - explicit shape collections. Boolean operations return a single `Solid`. - - Examples: - main_body = make_box_rsolid(10, 4, 4, bottom_face_center=(0, 0, 0)) - left_cap = make_sphere_rsolid(2.0, center=(-2.0, 2.0, 2.0)) - right_cap = make_sphere_rsolid(2.0, center=(12.0, 2.0, 2.0)) - body = union_rsolid(main_body, [left_cap, right_cap]) - - export_step(body, "rounded_bar.step") - """ - try: - shape_list = _normalize_shape_input(shapes) - - export_step_shapes([shape.wrapped for shape in shape_list], filename) - except Exception as e: - _wrap_public_api_error( - operation="export_step", - what_happened="Failed to export the shape set to STEP.", - possible_causes=[ - "One or more inputs are not exportable SimpleCAD shapes.", - "The output path is invalid or not writable.", - "The exporter rejected the provided geometry.", - ], - how_to_fix=[ - "Pass Compound, Solid, Shell, Face, Wire, Edge, Vertex, or sequences of those types.", - "Use a writable file path ending in .step or .stp.", - "If export still fails, inspect each input shape individually.", - ], - error=e, - ) -def export_stl(shapes: Union[AnyShape, Sequence[AnyShape]], filename: str) -> None: - """Export shapes to STL. - - Args: - shapes: A single Compound, Solid, or Face, or any nested sequence of those. - Lists of Solid are supported directly, including pattern or explicitly - collected multi-shape results. - filename: Output STL file path. - - Returns: - None: Writes the provided shapes into one STL file. - - Usage: - Use this function when you want to export one compound, solid, or face into - the same STL file. Passing `List[Solid]` is valid for pattern outputs or - explicit shape collections. Boolean operations return a single `Solid`. - - Examples: - main_body = make_box_rsolid(10, 4, 4, bottom_face_center=(0, 0, 0)) - left_cap = make_sphere_rsolid(2.0, center=(-2.0, 2.0, 2.0)) - right_cap = make_sphere_rsolid(2.0, center=(12.0, 2.0, 2.0)) - body = union_rsolid(main_body, [left_cap, right_cap]) - - export_stl(body, "rounded_bar.stl") - """ - try: - shape_list = _normalize_shape_input(shapes) - - for shape in shape_list: - if not isinstance(shape, (Compound, Solid, Shell, Face)): - raise ValueError( - "export_stl accepts only Compound, Solid, Shell, and Face geometry" - ) - export_stl_shape( - make_compound([shape.wrapped for shape in shape_list]), filename - ) - except Exception as e: - _wrap_public_api_error( - operation="export_stl", - what_happened="Failed to export the shape set to STL.", - possible_causes=[ - "One or more inputs are not Solid or Face objects.", - "The output path is invalid or not writable.", - "The exporter rejected the provided geometry.", - ], - how_to_fix=[ - "Pass Solid or Face objects, or sequences of them.", - "Use a writable file path ending in .stl.", - "If export still fails, isolate which shape triggers the exporter error.", - ], - error=e, - ) def render_screenshot_rpath( diff --git a/src/simplecadapi/product_packages.py b/src/simplecadapi/product_packages.py index 91ba1dc6..50fa54cc 100644 --- a/src/simplecadapi/product_packages.py +++ b/src/simplecadapi/product_packages.py @@ -32,8 +32,14 @@ from .artifacts.canonical import ( from .artifacts.part_definition import PartDefinition from .artifacts.part_io import encode_part_definition, load_part_definition from .scene.archive import canonical_zip_bytes, preflight_zip_bytes +from .scene.product_scene import ( + ProductSceneError, + compile_product_scene, + encode_product_scene, + read_scene_package, +) -PRODUCT_PACKAGE_SCHEMA_VERSION = "1.0" +PRODUCT_PACKAGE_SCHEMA_VERSION = "2.0" _MANIFEST_NAME = "package.json" Definition = PartDefinition | AssemblyDefinition @@ -93,6 +99,14 @@ class ProductPackage: def root_id(self) -> str: return self.root_definition.definition_id + @property + def scene_path(self) -> str: + return str(self.manifest["scene"]["path"]) + + @property + def scene_bytes(self) -> bytes: + return self.objects[self.scene_path] + def _mark_package_validated( package: ProductPackage, @@ -119,7 +133,7 @@ def _package_is_validated( @lru_cache(maxsize=1) def _schema() -> Mapping[str, Any]: resource = files("simplecadapi").joinpath( - "contracts", "product-package-1.schema.json" + "contracts", "product-package-2.schema.json" ) schema = json.loads(resource.read_text(encoding="utf-8")) Draft202012Validator.check_schema(schema) @@ -227,12 +241,26 @@ def _collect_definition_closure( return records, objects -def _manifest(root_path: str, records: list[dict[str, Any]]) -> dict[str, Any]: +def _manifest( + root_path: str, + records: list[dict[str, Any]], + scene_payload: bytes, + scene_id: str, + scene_revision: str, +) -> dict[str, Any]: draft = { "schema_version": PRODUCT_PACKAGE_SCHEMA_VERSION, "artifact_kind": "product_package", "root": root_path, "objects": records, + "scene": { + "path": "scene/scene.zip", + "media_type": "application/vnd.simplecad.scene+zip", + "scene_id": scene_id, + "revision": scene_revision, + "sha256": sha256_bytes(scene_payload), + "byte_length": len(scene_payload), + }, } return {**draft, "content_hash": content_hash(draft, omit=())} @@ -242,7 +270,16 @@ def build_product_package(value: Any) -> ProductPackage: root = _coerce_definition(value) records, objects = _collect_definition_closure(root) - manifest = _manifest(_object_path(root), records) + scene = compile_product_scene(root) + scene_payload = encode_product_scene(scene) + objects["scene/scene.zip"] = scene_payload + manifest = _manifest( + _object_path(root), + records, + scene_payload, + str(scene.manifest["scene_id"]), + str(scene.manifest["revision"]), + ) package = ProductPackage(manifest=manifest, objects=objects, root_definition=root) _mark_package_validated(package, DEFAULT_ARTIFACT_LIMITS) return package @@ -270,6 +307,9 @@ def _validate_manifest(manifest: Mapping[str, Any]) -> None: raise ProductPackageError("product package object identities must be unique") if manifest["root"] not in set(paths): raise ProductPackageError("product package root does not resolve to an object") + scene_path = str(manifest["scene"]["path"]) + if scene_path in set(paths): + raise ProductPackageError("scene path must not collide with a definition object") expected_hash = content_hash( {key: item for key, item in manifest.items() if key != "content_hash"}, omit=(), @@ -289,9 +329,10 @@ def _decode_definition_objects( if len(records) > limits.max_definitions: raise ProductPackageError("product package exceeds the definition limit") expected_paths = {str(item["path"]) for item in records} - if set(objects) != expected_paths: + scene_path = str(manifest["scene"]["path"]) + if set(objects) != expected_paths | {scene_path}: raise ProductPackageError( - "product package member set differs from object records" + "product package member set differs from object and scene records" ) decoded_by_path: dict[str, Definition] = {} @@ -399,6 +440,43 @@ def _decode_definition_objects( validate_assembly_definition_graph(root, limits=limits) except ArtifactValidationError as exc: raise ProductPackageError(f"root assembly graph is invalid: {exc}") from exc + + scene_record = manifest["scene"] + scene_payload = objects[scene_path] + if scene_record["byte_length"] != len(scene_payload): + raise ProductPackageError("embedded scene byte_length differs") + if scene_record["sha256"] != sha256_bytes(scene_payload): + raise ProductPackageError("embedded scene sha256 differs") + try: + scene = read_scene_package(scene_payload) + except (ProductSceneError, ValueError) as exc: + raise ProductPackageError(f"embedded scene is invalid: {exc}") from exc + if ( + scene.manifest["scene_id"] != scene_record["scene_id"] + or scene.manifest["revision"] != scene_record["revision"] + or scene.manifest["scene_id"] != root.definition_id + ): + raise ProductPackageError("embedded scene identity differs") + packaged_identities = { + ( + str(item["definition_kind"]), + str(item["definition_id"]), + str(item["revision"]), + str(item["content_hash"]), + ) + for item in records + } + scene_identities = { + ( + str(item["definition_kind"]), + str(item["definition_id"]), + str(item["revision"]), + str(item["content_hash"]), + ) + for item in scene.manifest["definitions"] + } + if scene_identities != packaged_identities: + raise ProductPackageError("embedded scene definition closure differs") return root @@ -432,12 +510,6 @@ def encode_product_package(package: ProductPackage) -> bytes: ) -def export_product_package(package: ProductPackage, path: str | Path) -> Path: - """Write one canonical self-contained `.scadpkg` archive.""" - destination = Path(path) - destination.parent.mkdir(parents=True, exist_ok=True) - destination.write_bytes(encode_product_package(package)) - return destination def read_product_package( @@ -482,7 +554,6 @@ __all__ = [ "ProductPackageError", "build_product_package", "encode_product_package", - "export_product_package", "load_product_package", "read_product_package", "validate_product_package", diff --git a/src/simplecadapi/scene/__init__.py b/src/simplecadapi/scene/__init__.py index 4898c5fb..6cae844d 100644 --- a/src/simplecadapi/scene/__init__.py +++ b/src/simplecadapi/scene/__init__.py @@ -87,6 +87,21 @@ from .render_mesh import ( solid_asset_bounds, ) + +def __getattr__(name: str): + if name in { + "ProductSceneError", + "ProductScenePackage", + "compile_product_scene", + "encode_product_scene", + "read_scene_package", + "validate_product_scene_package", + }: + from . import product_scene + + return getattr(product_scene, name) + raise AttributeError(name) + __all__ = [ "ArchiveInfo", "BASE_LIMITS", @@ -98,6 +113,8 @@ __all__ = [ "GlbInfo", "NormalizedProductDocument", "PresentationDocument", + "ProductSceneError", + "ProductScenePackage", "SCHEMA_FILES", "SceneContractError", "SceneDocument", @@ -147,6 +164,10 @@ __all__ = [ "build_render_mesh", "cad_direction_to_gltf", "cad_to_gltf", + "compile_product_scene", + "encode_product_scene", + "read_scene_package", + "validate_product_scene_package", "compile_scene", "export_scene", "json_resource_issues", diff --git a/src/simplecadapi/scene/compiler.py b/src/simplecadapi/scene/compiler.py index c8961865..b5334e25 100644 --- a/src/simplecadapi/scene/compiler.py +++ b/src/simplecadapi/scene/compiler.py @@ -36,7 +36,6 @@ from OCP.TopAbs import ( ) from ..core import Compound, Edge, Face, Solid, Vertex -from ..graph import ModelResult from ..kernel.ocp_properties import center_of_mass from ..product import ( Assembly, @@ -166,7 +165,7 @@ def compile_scene( *, scene_id: str, roots: Sequence[SceneRoot], - source: SceneSource | ModelResult | None = None, + source: SceneSource | None = None, presentation: Any = None, options: SceneCompileOptions | None = None, ) -> CompiledScenePackage: @@ -452,7 +451,7 @@ def _binding_status(source: SceneSource, definition_kind: str, frame: Mapping[st def _coerce_source( - source: SceneSource | ModelResult | None, + source: SceneSource | None, roots: Sequence[SceneRoot], *, embed_source: bool, @@ -470,28 +469,6 @@ def _coerce_source( revision=source.revision, _graph=source._graph, ) - if isinstance(source, ModelResult): - try: - model_payload = json.loads(source.model_json) - except (TypeError, ValueError) as exc: - raise ValueError("ModelResult.model_json is not valid JSON") from exc - live_graph_payload = json.loads(json.dumps(source.session.graph.to_dict())) - if model_payload.get("graph") != live_graph_payload: - raise ValueError( - "ModelResult session graph no longer matches its model JSON snapshot" - ) - return SceneSource( - kind="model", - graph_id=source.session.graph.graph_id, - artifact_hash=_model_artifact_hash(source.model_json), - artifact_bytes=( - source.model_json.encode("utf-8") if embed_source else None - ), - _graph=source.session.graph, - _source_files=( - _collect_source_files(source.session.graph) if embed_source else () - ), - ) return SceneSource(kind="manual", source_id=roots[0].root_id) @@ -601,7 +578,7 @@ def _graph_output_ref(value: Any, *, source: SceneSource) -> tuple[str, int]: raise ValueError("model scene root must retain graph node ownership") graph = source._graph if graph is None: - raise ValueError("model scene source requires ModelResult graph evidence") + raise ValueError("model scene source requires GraphSession graph evidence") graph_id = getattr(node, "graph_id", None) or source.graph_id if graph_id != source.graph_id: raise ValueError("model scene root belongs to a different graph") @@ -811,7 +788,7 @@ def _connector_source( } graph = source._graph if graph is None: - raise ValueError("model connector source requires ModelResult graph evidence") + raise ValueError("model connector source requires GraphSession graph evidence") owner_node_id, _output_slot = _graph_output_ref(owner, source=source) producer = _connector_producer( graph=graph, diff --git a/src/simplecadapi/scene/contracts/schemas/scene-2.0.schema.json b/src/simplecadapi/scene/contracts/schemas/scene-2.0.schema.json new file mode 100644 index 00000000..d22e2c91 --- /dev/null +++ b/src/simplecadapi/scene/contracts/schemas/scene-2.0.schema.json @@ -0,0 +1,52 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://simplecad.dev/schemas/scene-2.0.schema.json", + "title": "SimpleCAD Scene 2.0", + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "scene_id", "revision", "units", "roots", "definitions", "geometry_assets", "entity_assets", "product_assets", "feature_graph_assets", "source_assets", "nodes", "connectors", "joints", "feature_index", "source_index", "connector_index", "joint_index", "camera", "extensions"], + "properties": { + "schema_version": {"const": "2.0"}, + "scene_id": {"$ref": "#/$defs/id"}, + "revision": {"$ref": "#/$defs/hash"}, + "units": {"const": "mm"}, + "roots": {"type": "array", "minItems": 1, "maxItems": 25000, "items": {"$ref": "#/$defs/id"}}, + "definitions": {"type": "array", "minItems": 1, "maxItems": 25000, "items": {"$ref": "#/$defs/definition"}}, + "geometry_assets": {"type": "array", "minItems": 1, "maxItems": 25000, "items": {"$ref": "#/$defs/asset"}}, + "entity_assets": {"type": "array", "minItems": 1, "maxItems": 25000, "items": {"$ref": "#/$defs/asset"}}, + "product_assets": {"type": "array", "minItems": 1, "maxItems": 25000, "items": {"$ref": "#/$defs/productAsset"}}, + "feature_graph_assets": {"type": "array", "minItems": 1, "maxItems": 25000, "items": {"$ref": "#/$defs/featureGraphAsset"}}, + "source_assets": {"type": "array", "maxItems": 25000, "items": {"$ref": "#/$defs/sourceAsset"}}, + "nodes": {"type": "array", "minItems": 1, "maxItems": 1000000, "items": {"$ref": "#/$defs/node"}}, + "connectors": {"type": "array", "maxItems": 1000000, "items": {"$ref": "#/$defs/connector"}}, + "joints": {"type": "array", "maxItems": 1000000, "items": {"$ref": "#/$defs/joint"}}, + "feature_index": {"type": "array", "minItems": 1, "maxItems": 1000000, "items": {"$ref": "#/$defs/feature"}}, + "source_index": {"type": "array", "maxItems": 1000000, "items": {"$ref": "#/$defs/sourceIndex"}}, + "connector_index": {"type": "array", "maxItems": 1000000, "items": {"$ref": "#/$defs/connectorIndex"}}, + "joint_index": {"type": "array", "maxItems": 1000000, "items": {"$ref": "#/$defs/jointIndex"}}, + "camera": {"$ref": "#/$defs/camera"}, + "extensions": {"type": "object", "additionalProperties": true} + }, + "$defs": { + "id": {"type": "string", "minLength": 1, "maxLength": 1024, "pattern": "^[A-Za-z][A-Za-z0-9_.:/-]*$"}, + "hash": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"}, + "uri": {"type": "string", "minLength": 1, "maxLength": 4096, "pattern": "^[A-Za-z0-9][A-Za-z0-9._/-]*$"}, + "vec3": {"type": "array", "minItems": 3, "maxItems": 3, "items": {"type": "number"}}, + "transform": {"type": "object", "additionalProperties": false, "required": ["origin", "x_axis", "y_axis", "z_axis"], "properties": {"origin": {"$ref": "#/$defs/vec3"}, "x_axis": {"$ref": "#/$defs/vec3"}, "y_axis": {"$ref": "#/$defs/vec3"}, "z_axis": {"$ref": "#/$defs/vec3"}}}, + "asset": {"type": "object", "additionalProperties": false, "required": ["asset_id", "uri", "media_type", "sha256", "byte_length"], "properties": {"asset_id": {"$ref": "#/$defs/hash"}, "uri": {"$ref": "#/$defs/uri"}, "media_type": {"type": "string", "minLength": 1}, "sha256": {"$ref": "#/$defs/hash"}, "byte_length": {"type": "integer", "minimum": 0, "maximum": 9007199254740991}}}, + "definition": {"type": "object", "additionalProperties": false, "required": ["definition_id", "definition_kind", "revision", "content_hash", "product_asset_id", "feature_graph_asset_id"], "properties": {"definition_id": {"$ref": "#/$defs/id"}, "definition_kind": {"enum": ["single_solid", "assembly"]}, "revision": {"type": "string", "minLength": 1}, "content_hash": {"$ref": "#/$defs/hash"}, "product_asset_id": {"$ref": "#/$defs/hash"}, "feature_graph_asset_id": {"$ref": "#/$defs/hash"}}}, + "productAsset": {"type": "object", "additionalProperties": false, "required": ["asset_id", "uri", "media_type", "sha256", "byte_length", "definition_id", "definition_kind", "revision", "content_hash"], "properties": {"asset_id": {"$ref": "#/$defs/hash"}, "uri": {"$ref": "#/$defs/uri"}, "media_type": {"enum": ["application/vnd.simplecad.part-definition+zip", "application/vnd.simplecad.assembly-definition+zip"]}, "sha256": {"$ref": "#/$defs/hash"}, "byte_length": {"type": "integer", "minimum": 0}, "definition_id": {"$ref": "#/$defs/id"}, "definition_kind": {"enum": ["single_solid", "assembly"]}, "revision": {"type": "string", "minLength": 1}, "content_hash": {"$ref": "#/$defs/hash"}}}, + "featureGraphAsset": {"type": "object", "additionalProperties": false, "required": ["asset_id", "uri", "media_type", "sha256", "byte_length", "definition_id", "graph_id", "graph_revision"], "properties": {"asset_id": {"$ref": "#/$defs/hash"}, "uri": {"$ref": "#/$defs/uri"}, "media_type": {"const": "application/vnd.simplecad.feature-graph+zip"}, "sha256": {"$ref": "#/$defs/hash"}, "byte_length": {"type": "integer", "minimum": 0}, "definition_id": {"$ref": "#/$defs/id"}, "graph_id": {"$ref": "#/$defs/id"}, "graph_revision": {"$ref": "#/$defs/hash"}}}, + "sourceAsset": {"type": "object", "additionalProperties": false, "required": ["source_asset_id", "uri", "sha256", "byte_length", "media_type", "display_name"], "properties": {"source_asset_id": {"$ref": "#/$defs/hash"}, "uri": {"$ref": "#/$defs/uri"}, "sha256": {"$ref": "#/$defs/hash"}, "byte_length": {"type": "integer", "minimum": 0}, "media_type": {"type": "string", "minLength": 1}, "display_name": {"type": "string", "minLength": 1, "maxLength": 4096}}}, + "node": {"type": "object", "additionalProperties": false, "required": ["node_id", "parent_node_id", "display_name", "node_kind", "definition_id", "definition_kind", "component_id", "instance_id", "transform", "geometry_asset_id", "entity_asset_id", "material_id", "properties"], "properties": {"node_id": {"$ref": "#/$defs/id"}, "parent_node_id": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/id"}]}, "display_name": {"type": "string"}, "node_kind": {"enum": ["part", "assembly", "solid"]}, "definition_id": {"$ref": "#/$defs/id"}, "definition_kind": {"enum": ["single_solid", "assembly"]}, "component_id": {"type": ["string", "null"]}, "instance_id": {"type": ["string", "null"]}, "transform": {"$ref": "#/$defs/transform"}, "geometry_asset_id": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/hash"}]}, "entity_asset_id": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/hash"}]}, "material_id": {"type": ["string", "null"]}, "properties": {"type": "object", "additionalProperties": true}}}, + "connector": {"type": "object", "additionalProperties": false, "required": ["connector_snapshot_id", "node_id", "definition_id", "definition_kind", "connector_id", "name", "anchor_kind", "local_frame", "binding", "forwarded_from", "source_feature_id"], "properties": {"connector_snapshot_id": {"$ref": "#/$defs/id"}, "node_id": {"$ref": "#/$defs/id"}, "definition_id": {"$ref": "#/$defs/id"}, "definition_kind": {"enum": ["single_solid", "assembly"]}, "connector_id": {"$ref": "#/$defs/id"}, "name": {"type": "string"}, "anchor_kind": {"enum": ["placement", "geometry", "forwarded"]}, "local_frame": {"$ref": "#/$defs/transform"}, "binding": {"type": ["object", "null"]}, "forwarded_from": {"type": ["object", "null"]}, "source_feature_id": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/id"}]}}}, + "connectorRef": {"type": "object", "additionalProperties": false, "required": ["definition_id", "component_id", "instance_id", "connector_id", "connector_snapshot_id"], "properties": {"definition_id": {"$ref": "#/$defs/id"}, "component_id": {"$ref": "#/$defs/id"}, "instance_id": {"$ref": "#/$defs/id"}, "connector_id": {"$ref": "#/$defs/id"}, "connector_snapshot_id": {"$ref": "#/$defs/id"}}}, + "joint": {"type": "object", "additionalProperties": false, "required": ["joint_id", "assembly_definition_id", "joint_type", "connector_a", "connector_b", "parameters", "limits", "source_feature_id"], "properties": {"joint_id": {"$ref": "#/$defs/id"}, "assembly_definition_id": {"$ref": "#/$defs/id"}, "joint_type": {"enum": ["fixed", "revolute", "prismatic", "cylindrical", "planar", "ball", "gear", "belt", "rack_pinion"]}, "connector_a": {"$ref": "#/$defs/connectorRef"}, "connector_b": {"$ref": "#/$defs/connectorRef"}, "parameters": {"type": "object", "additionalProperties": true}, "limits": {"type": ["object", "null"], "additionalProperties": true}, "source_feature_id": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/id"}]}}}, + "feature": {"type": "object", "additionalProperties": false, "required": ["feature_id", "definition_id", "graph_id", "node_id", "op", "label", "parameters", "input_feature_ids", "output_count", "source_spans"], "properties": {"feature_id": {"$ref": "#/$defs/id"}, "definition_id": {"$ref": "#/$defs/id"}, "graph_id": {"$ref": "#/$defs/id"}, "node_id": {"$ref": "#/$defs/id"}, "op": {"type": "string", "minLength": 1}, "label": {"type": ["string", "null"]}, "parameters": {"type": "object", "additionalProperties": true}, "input_feature_ids": {"type": "array", "items": {"$ref": "#/$defs/id"}}, "output_count": {"type": "integer", "minimum": 1}, "source_spans": {"type": "array", "items": {"$ref": "#/$defs/sourceSpan"}}}}, + "sourceSpan": {"type": "object", "additionalProperties": false, "required": ["source_asset_id", "uri", "start_line", "end_line", "symbol"], "properties": {"source_asset_id": {"$ref": "#/$defs/hash"}, "uri": {"$ref": "#/$defs/uri"}, "start_line": {"type": "integer", "minimum": 1}, "end_line": {"type": "integer", "minimum": 1}, "symbol": {"type": ["string", "null"]}}}, + "sourceIndex": {"type": "object", "additionalProperties": false, "required": ["source_index_id", "source_asset_id", "uri", "definition_id", "feature_id", "start_line", "end_line", "symbol"], "properties": {"source_index_id": {"$ref": "#/$defs/id"}, "source_asset_id": {"$ref": "#/$defs/hash"}, "uri": {"$ref": "#/$defs/uri"}, "definition_id": {"$ref": "#/$defs/id"}, "feature_id": {"$ref": "#/$defs/id"}, "start_line": {"type": "integer", "minimum": 1}, "end_line": {"type": "integer", "minimum": 1}, "symbol": {"type": ["string", "null"]}}}, + "connectorIndex": {"type": "object", "additionalProperties": false, "required": ["connector_index_id", "definition_id", "node_id", "connector_id", "connector_snapshot_id", "source_feature_id"], "properties": {"connector_index_id": {"$ref": "#/$defs/id"}, "definition_id": {"$ref": "#/$defs/id"}, "node_id": {"$ref": "#/$defs/id"}, "connector_id": {"$ref": "#/$defs/id"}, "connector_snapshot_id": {"$ref": "#/$defs/id"}, "source_feature_id": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/id"}]}}}, + "jointIndex": {"type": "object", "additionalProperties": false, "required": ["joint_index_id", "assembly_definition_id", "joint_id", "source_feature_id"], "properties": {"joint_index_id": {"$ref": "#/$defs/id"}, "assembly_definition_id": {"$ref": "#/$defs/id"}, "joint_id": {"$ref": "#/$defs/id"}, "source_feature_id": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/id"}]}}}, + "camera": {"type": "object", "additionalProperties": false, "required": ["target", "position", "up", "near", "far", "fit_mode", "margin"], "properties": {"target": {"$ref": "#/$defs/vec3"}, "position": {"$ref": "#/$defs/vec3"}, "up": {"$ref": "#/$defs/vec3"}, "near": {"type": "number", "exclusiveMinimum": 0}, "far": {"type": "number", "exclusiveMinimum": 0}, "fit_mode": {"enum": ["bounds", "selection"]}, "margin": {"type": "number", "minimum": 0, "maximum": 10}}} + } +} diff --git a/src/simplecadapi/scene/product_scene.py b/src/simplecadapi/scene/product_scene.py new file mode 100644 index 00000000..f99af65f --- /dev/null +++ b/src/simplecadapi/scene/product_scene.py @@ -0,0 +1,1201 @@ +"""Definition-driven, self-contained Scene 2.0 product snapshots.""" + +from __future__ import annotations + +import json +from dataclasses import dataclass, field +from functools import lru_cache +from importlib.resources import files +from pathlib import Path +from types import MappingProxyType +from typing import Any, Mapping + +from jsonschema import Draft202012Validator + +from ..artifacts.assembly_definition import AssemblyDefinition +from ..artifacts.part_definition import PartDefinition, mark_part_definition_validated +from ..artifacts.assembly_io import ( + decode_assembly_definition, + encode_assembly_definition, + materialize_definition, +) +from ..artifacts.canonical import parse_canonical_json as parse_artifact_json +from ..artifacts.canonical import sha256_bytes +from ..artifacts.feature_graph import ( + FeatureGraphArtifact, + load_feature_graph_artifact, +) +from ..artifacts.part_io import encode_part_definition, load_part_definition +from ..core import Edge, Face, Solid, Vertex +from ..kernel.ocp_properties import center_of_mass +from ..product import Placement, identity_placement +from .archive import canonical_zip_bytes, preflight_zip_bytes +from .canonical import ( + canonical_json_bytes, + compute_scene_revision, + parse_canonical_json, + with_scene_revision, +) +from .compiler import ( + DEFAULT_ANGULAR_TOLERANCE, + DEFAULT_LINEAR_TOLERANCE, + _bounds, + _curve_geometry, + _edge_endpoints, + _frame, + _normalize, + _orientation, + _shape_bounds, + _surface_geometry, + _vec, +) +from .glb_writer import write_line_glb, write_triangle_glb +from .render_mesh import build_edge_mesh, build_render_mesh, solid_asset_bounds + +Definition = PartDefinition | AssemblyDefinition +_SCENE_MANIFEST = "scene.json" + + +class ProductSceneError(ValueError): + """Raised when a Scene 2.0 product snapshot is not closed and canonical.""" + + +@dataclass(frozen=True, slots=True) +class ProductScenePackage: + manifest: Mapping[str, Any] + blobs: Mapping[str, bytes] + _validated_manifest: bytes | None = field( + default=None, + init=False, + compare=False, + repr=False, + ) + + def __post_init__(self) -> None: + object.__setattr__(self, "manifest", MappingProxyType(dict(self.manifest))) + object.__setattr__( + self, + "blobs", + MappingProxyType( + {str(path): bytes(payload) for path, payload in self.blobs.items()} + ), + ) + + @property + def scene(self) -> Mapping[str, Any]: + return self.manifest + + +@lru_cache(maxsize=1) +def _schema() -> Mapping[str, Any]: + resource = files("simplecadapi.scene").joinpath( + "contracts", "schemas", "scene-2.0.schema.json" + ) + value = json.loads(resource.read_text(encoding="utf-8")) + Draft202012Validator.check_schema(value) + return value + + +def _schema_validate(manifest: Mapping[str, Any]) -> None: + errors = sorted( + Draft202012Validator(_schema()).iter_errors(dict(manifest)), + key=lambda item: (list(item.absolute_path), item.message), + ) + if errors: + error = errors[0] + pointer = "/" + "/".join(str(item) for item in error.absolute_path) + raise ProductSceneError(f"scene schema invalid at {pointer}: {error.message}") + + +def _definition_bytes(definition: Definition) -> bytes: + if isinstance(definition, PartDefinition): + return encode_part_definition(definition) + return encode_assembly_definition(definition) + + +def _definition_media_type(definition: Definition) -> str: + if isinstance(definition, PartDefinition): + return "application/vnd.simplecad.part-definition+zip" + return "application/vnd.simplecad.assembly-definition+zip" + + +def _definition_closure(root: Definition) -> dict[str, Definition]: + definitions: dict[str, Definition] = {} + active: set[str] = set() + + def visit(definition: Definition) -> None: + existing = definitions.get(definition.definition_id) + if existing is not None: + if ( + existing.definition_kind != definition.definition_kind + or existing.content_hash != definition.content_hash + ): + raise ProductSceneError( + f"definition_id {definition.definition_id!r} has multiple identities" + ) + return + if definition.definition_id in active: + raise ProductSceneError( + f"definition cycle at {definition.definition_id!r}" + ) + active.add(definition.definition_id) + try: + definitions[definition.definition_id] = definition + if isinstance(definition, AssemblyDefinition): + for ref in definition.definition_refs: + child = definition.resolved_definitions.get(ref.definition_id) + if not isinstance(child, (PartDefinition, AssemblyDefinition)): + raise ProductSceneError( + f"assembly {definition.definition_id!r} has unresolved " + f"definition {ref.definition_id!r}" + ) + visit(child) + finally: + active.remove(definition.definition_id) + + visit(root) + return definitions + + +def _feature_graph(definition: Definition) -> FeatureGraphArtifact: + payload = definition.blobs[definition.feature_graph_ref.path] + feature_graph = load_feature_graph_artifact(payload) + if ( + feature_graph.owner_definition_id != definition.definition_id + or feature_graph.owner_definition_kind != definition.definition_kind + or feature_graph.owner_revision != definition.revision + ): + raise ProductSceneError( + f"feature graph owner differs for {definition.definition_id!r}" + ) + return feature_graph + + +def _asset_record(payload: bytes, *, uri: str, media_type: str) -> dict[str, Any]: + digest = sha256_bytes(payload) + return { + "asset_id": digest, + "uri": uri, + "media_type": media_type, + "sha256": digest, + "byte_length": len(payload), + } + + +def _source_feature_id(definition_id: str, node_id: str) -> str: + return f"feature/{definition_id}/{node_id}" + + +def _node_source_spans( + definition_id: str, + node: Mapping[str, Any], + source_ids: Mapping[str, str], + source_uris: Mapping[str, str], +) -> list[dict[str, Any]]: + source = node.get("source") + if not isinstance(source, Mapping): + return [] + source_file_id = source.get("source_file_id") + if not isinstance(source_file_id, str) or source_file_id not in source_ids: + return [] + start_line = source.get("line") + end_line = source.get("end_line", start_line) + if ( + isinstance(start_line, bool) + or not isinstance(start_line, int) + or start_line < 1 + or isinstance(end_line, bool) + or not isinstance(end_line, int) + or end_line < start_line + ): + return [] + targets = source.get("assignment_targets") + symbol = ( + str(targets[0]) + if isinstance(targets, list) and targets and isinstance(targets[0], str) + else None + ) + return [ + { + "source_asset_id": source_ids[source_file_id], + "uri": source_uris[source_file_id], + "start_line": start_line, + "end_line": end_line, + "symbol": symbol, + } + ] + + +def _feature_records( + definition: Definition, + feature_graph: FeatureGraphArtifact, + source_ids: Mapping[str, str], + source_uris: Mapping[str, str], +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + features: list[dict[str, Any]] = [] + source_index: list[dict[str, Any]] = [] + for node in feature_graph.graph.get("nodes", []): + node_id = str(node["node_id"]) + feature_id = _source_feature_id(definition.definition_id, node_id) + spans = _node_source_spans( + definition.definition_id, + node, + source_ids, + source_uris, + ) + display = node.get("display") + label = display.get("label") if isinstance(display, Mapping) else None + features.append( + { + "feature_id": feature_id, + "definition_id": definition.definition_id, + "graph_id": feature_graph.owner_definition_id, + "node_id": node_id, + "op": str(node["op"]), + "label": str(label) if label is not None else None, + "parameters": dict(node.get("params", {})), + "input_feature_ids": [ + _source_feature_id(definition.definition_id, str(input_id)) + for input_id in node.get("inputs", []) + ], + "output_count": int(node["output_count"]), + "source_spans": spans, + } + ) + for span_index, span in enumerate(spans): + source_index.append( + { + "source_index_id": ( + f"source/{definition.definition_id}/{node_id}/{span_index}" + ), + "source_asset_id": span["source_asset_id"], + "uri": span["uri"], + "definition_id": definition.definition_id, + "feature_id": feature_id, + "start_line": span["start_line"], + "end_line": span["end_line"], + "symbol": span["symbol"], + } + ) + return features, source_index + + +def _entity_source( + definition_id: str, + feature_output: Mapping[str, Any] | None, +) -> dict[str, Any]: + if not isinstance(feature_output, Mapping): + raise ProductSceneError( + f"definition {definition_id!r} has topology without feature_output" + ) + return { + "kind": "feature_output", + "definition_id": definition_id, + "graph_id": str(feature_output["graph_id"]), + "node_id": str(feature_output["node_id"]), + "output_slot": int(feature_output["output_slot"]), + "topology_kind": str(feature_output["kind"]), + "topo_id": str(feature_output["topo_id"]), + } + + +def _entity_id(definition_id: str, kind: str, topo_id: str) -> str: + return f"entity/{definition_id}/{kind}/{topo_id}" + + +def _part_geometry( + definition: PartDefinition, + *, + linear_tolerance: float, + angular_tolerance: float, +) -> tuple[ + list[dict[str, Any]], + dict[str, Any], + dict[str, bytes], + str, + str, +]: + runtime = materialize_definition(definition) + body = runtime.body + if not isinstance(body, Solid): + raise ProductSceneError(f"part {definition.definition_id!r} has no solid body") + snapshot = parse_artifact_json( + definition.blobs[definition.topology_snapshot_ref.path] + ) + mark_part_definition_validated( + definition, + body=body, + feature_graph=_feature_graph(definition), + ) + source_by_key = { + (str(item["kind"]), str(item["topo_id"])): _entity_source( + definition.definition_id, item["feature_output"] + ) + for item in snapshot["entities"] + } + + faces = body.get_faces() + edges = body.get_edges() + vertices_by_id: dict[str, Vertex] = {} + for edge in edges: + for vertex in edge.get_vertices(): + vertices_by_id.setdefault(vertex.topo_id, vertex) + vertices = list(vertices_by_id.values()) + face_ids = { + face.topo_id: _entity_id(definition.definition_id, "face", face.topo_id) + for face in faces + } + edge_ids = { + edge.topo_id: _entity_id(definition.definition_id, "edge", edge.topo_id) + for edge in edges + } + vertex_ids = { + vertex.topo_id: _entity_id( + definition.definition_id, "vertex", vertex.topo_id + ) + for vertex in vertices + } + render_mesh = build_render_mesh( + body, + face_entity_ids=[face_ids[item.topo_id] for item in faces], + linear_tolerance=linear_tolerance, + angular_tolerance=angular_tolerance, + ) + edge_mesh = build_edge_mesh( + body, + edge_entity_ids=[edge_ids[item.topo_id] for item in edges], + linear_tolerance=linear_tolerance, + angular_tolerance=angular_tolerance, + ) + triangle_glb = write_triangle_glb(render_mesh) + line_glb = write_line_glb(edge_mesh) + geometry_hash = sha256_bytes(triangle_glb) + edge_hash = sha256_bytes(line_glb) + geometry_uri = f"geometry/sha256-{geometry_hash.removeprefix('sha256:')}.glb" + edge_uri = f"geometry/sha256-{edge_hash.removeprefix('sha256:')}.lines.glb" + geometry_records = [ + _asset_record(triangle_glb, uri=geometry_uri, media_type="model/gltf-binary"), + _asset_record(line_glb, uri=edge_uri, media_type="model/gltf-binary"), + ] + + solid_id = _entity_id(definition.definition_id, "solid", body.topo_id) + entities: list[dict[str, Any]] = [ + { + "entity_id": solid_id, + "kind": "solid", + "topo_id": body.topo_id, + "parent_entity_ids": [], + "child_entity_ids": sorted(face_ids.values()), + "source": source_by_key[("solid", body.topo_id)], + "geometry": {"type": "brep_solid"}, + "properties": { + "bounds": _bounds(solid_asset_bounds(body)), + "volume": body.get_volume(), + "surface_area": sum(face.get_area() for face in faces), + "centroid": list(_vec(center_of_mass(body.wrapped))), + }, + "tags": sorted(body._list_tags()), + } + ] + for face in faces: + center = _vec(face.get_center()) + entities.append( + { + "entity_id": face_ids[face.topo_id], + "kind": "face", + "topo_id": face.topo_id, + "parent_entity_ids": [solid_id], + "child_entity_ids": sorted( + edge_ids[item.topo_id] for item in face.get_edges() + ), + "source": source_by_key[("face", face.topo_id)], + "geometry": _surface_geometry(face), + "properties": { + "bounds": _bounds(_shape_bounds(face)), + "area": face.get_area(), + "centroid": list(center), + "orientation": _orientation(face.wrapped.Orientation()), + "connector_frame": _frame(center, _vec(face.get_normal_at())), + }, + "tags": sorted(face._list_tags()), + } + ) + for edge in edges: + start, end = _edge_endpoints(edge) + frame = None + if start is not None and end is not None and start != end: + direction = _normalize( + tuple(end[index] - start[index] for index in range(3)) + ) + frame = _frame(_vec(edge.get_center()), direction) + entities.append( + { + "entity_id": edge_ids[edge.topo_id], + "kind": "edge", + "topo_id": edge.topo_id, + "parent_entity_ids": sorted( + face_ids[item.topo_id] + for item in edge.get_incident_faces() + if item.topo_id in face_ids + ), + "child_entity_ids": sorted( + vertex_ids[item.topo_id] for item in edge.get_vertices() + ), + "source": source_by_key[("edge", edge.topo_id)], + "geometry": _curve_geometry(edge), + "properties": { + "bounds": _bounds(_shape_bounds(edge)), + "length": edge.get_length(), + "centroid": list(_vec(edge.get_center())), + "connector_frame": frame, + }, + "tags": sorted(edge._list_tags()), + } + ) + for vertex in vertices: + point = list(_vec(vertex.get_coordinates())) + entities.append( + { + "entity_id": vertex_ids[vertex.topo_id], + "kind": "vertex", + "topo_id": vertex.topo_id, + "parent_entity_ids": sorted( + edge_ids[edge.topo_id] + for edge in edges + if any( + child.topo_id == vertex.topo_id + for child in edge.get_vertices() + ) + ), + "child_entity_ids": [], + "source": source_by_key[("vertex", vertex.topo_id)], + "geometry": {"type": "point", "position": point}, + "properties": { + "bounds": {"min": point, "max": point}, + "position": point, + }, + "tags": sorted(vertex._list_tags()), + } + ) + entity_document = { + "schema_version": "2.0", + "definition_id": definition.definition_id, + "geometry_asset_id": geometry_hash, + "edge_asset_id": edge_hash, + "entities": sorted(entities, key=lambda item: item["entity_id"]), + "face_groups": [ + { + "group_id": index, + "entity_id": group.entity_id, + "mesh_index": 0, + "primitive_index": 0, + "first_index": group.first_index, + "index_count": group.index_count, + } + for index, group in enumerate(render_mesh.groups) + ], + "edge_groups": [ + { + "group_id": index, + "entity_id": group.entity_id, + "mesh_index": 0, + "primitive_index": 0, + "first_index": group.first_index, + "index_count": group.index_count, + } + for index, group in enumerate(edge_mesh.groups) + ], + } + entity_bytes = canonical_json_bytes(entity_document) + entity_hash = sha256_bytes(entity_bytes) + entity_uri = f"entities/sha256-{entity_hash.removeprefix('sha256:')}.json" + return ( + geometry_records, + { + **_asset_record( + entity_bytes, + uri=entity_uri, + media_type="application/vnd.simplecad.entities+json", + ) + }, + { + geometry_uri: triangle_glb, + edge_uri: line_glb, + entity_uri: entity_bytes, + }, + geometry_hash, + entity_hash, + ) + + +def _placement(value: Mapping[str, Any]) -> Placement: + return Placement(**dict(value)) + + +def _node_id(path: tuple[str, ...]) -> str: + return "node/" + "/".join(path) + + +def _build_nodes( + root: Definition, + definitions: Mapping[str, Definition], + geometry_ids: Mapping[str, str], + entity_ids: Mapping[str, str], +) -> tuple[ + list[dict[str, Any]], + dict[str, list[str]], + dict[tuple[str, str], str], +]: + nodes: list[dict[str, Any]] = [] + occurrences: dict[str, list[str]] = {} + children: dict[tuple[str, str], str] = {} + + def visit( + definition: Definition, + path: tuple[str, ...], + parent_node_id: str | None, + transform: Placement, + component_id: str | None, + instance_id: str | None, + display_name: str | None, + ) -> str: + node_id = _node_id(path) + occurrences.setdefault(definition.definition_id, []).append(node_id) + is_part = isinstance(definition, PartDefinition) + nodes.append( + { + "node_id": node_id, + "parent_node_id": parent_node_id, + "display_name": display_name or definition.definition_id, + "node_kind": "part" if is_part else "assembly", + "definition_id": definition.definition_id, + "definition_kind": definition.definition_kind, + "component_id": component_id, + "instance_id": instance_id, + "transform": transform.to_dict(), + "geometry_asset_id": geometry_ids.get(definition.definition_id), + "entity_asset_id": entity_ids.get(definition.definition_id), + "material_id": ( + definition.material_ref.material_id + if is_part and definition.material_ref is not None + else None + ), + "properties": { + "content_hash": definition.content_hash, + "revision": definition.revision, + }, + } + ) + if isinstance(definition, AssemblyDefinition): + for instance in definition.instances: + child = definitions[instance.definition_id] + child_path = (*path, instance.instance_id) + child_node = visit( + child, + child_path, + node_id, + _placement(instance.placement), + instance.instance_id, + _node_id(child_path), + instance.name, + ) + children[(node_id, instance.instance_id)] = child_node + return node_id + + root_node = visit( + root, + (root.definition_id,), + None, + identity_placement(), + None, + None, + root.metadata.get("name"), + ) + for values in occurrences.values(): + values.sort() + return sorted(nodes, key=lambda item: item["node_id"]), occurrences, children + + +def _producer_feature( + definition_id: str, + feature_graph: FeatureGraphArtifact, + *, + parameter: str, + value: str, + op_prefix: str, +) -> str | None: + matches = [ + node + for node in feature_graph.graph.get("nodes", []) + if str(node.get("op", "")).startswith(op_prefix) + and node.get("params", {}).get(parameter) == value + ] + if len(matches) != 1: + return None + return _source_feature_id(definition_id, str(matches[0]["node_id"])) + + +def _connector_snapshot_id(node_id: str, connector_id: str) -> str: + return f"connector/{node_id.removeprefix('node/')}/{connector_id}" + + +def _connectors( + definitions: Mapping[str, Definition], + feature_graphs: Mapping[str, FeatureGraphArtifact], + occurrences: Mapping[str, list[str]], +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + connectors: list[dict[str, Any]] = [] + index: list[dict[str, Any]] = [] + for definition_id in sorted(definitions): + definition = definitions[definition_id] + interfaces = ( + definition.connectors + if isinstance(definition, PartDefinition) + else definition.public_connectors + ) + graph = feature_graphs[definition_id] + for node_id in occurrences.get(definition_id, []): + for interface in interfaces: + feature_id = _producer_feature( + definition_id, + graph, + parameter="connector_id", + value=interface.connector_id, + op_prefix=( + "make_add_connector_rpart" + if isinstance(definition, PartDefinition) + else "make_forward_connector_rassembly" + ), + ) + snapshot_id = _connector_snapshot_id( + node_id, interface.connector_id + ) + connectors.append( + { + "connector_snapshot_id": snapshot_id, + "node_id": node_id, + "definition_id": definition_id, + "definition_kind": definition.definition_kind, + "connector_id": interface.connector_id, + "name": interface.name or interface.connector_id, + "anchor_kind": interface.anchor_kind, + "local_frame": dict(interface.local_frame), + "binding": ( + dict(interface.binding) + if interface.binding is not None + else None + ), + "forwarded_from": ( + dict(interface.forwarded_from) + if interface.forwarded_from is not None + else None + ), + "source_feature_id": feature_id, + } + ) + index.append( + { + "connector_index_id": ( + f"connector-index/{node_id.removeprefix('node/')}" + f"/{interface.connector_id}" + ), + "definition_id": definition_id, + "node_id": node_id, + "connector_id": interface.connector_id, + "connector_snapshot_id": snapshot_id, + "source_feature_id": feature_id, + } + ) + return ( + sorted(connectors, key=lambda item: item["connector_snapshot_id"]), + sorted(index, key=lambda item: item["connector_index_id"]), + ) + + +def _joints( + definitions: Mapping[str, Definition], + feature_graphs: Mapping[str, FeatureGraphArtifact], + occurrences: Mapping[str, list[str]], + children: Mapping[tuple[str, str], str], +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + joints: list[dict[str, Any]] = [] + index: list[dict[str, Any]] = [] + for definition_id in sorted(definitions): + definition = definitions[definition_id] + if not isinstance(definition, AssemblyDefinition) or not definition.relations: + continue + instance_by_id = {item.instance_id: item for item in definition.instances} + graph = feature_graphs[definition_id] + for assembly_node in occurrences[definition_id]: + for relation in definition.relations: + constraint_id = str(relation["constraint_id"]) + feature_id = _producer_feature( + definition_id, + graph, + parameter="constraint_id", + value=constraint_id, + op_prefix=( + f"make_{relation['constraint_kind']}_constraint_rassembly" + ), + ) + if feature_id is None: + raise ProductSceneError( + f"joint {definition_id!r}/{constraint_id!r} has no unique producer" + ) + + def endpoint(side: str) -> dict[str, Any]: + ref = relation[side] + component_id = str(ref["component_id"]) + connector_id = str(ref["connector_id"]) + child_node = children[(assembly_node, component_id)] + instance = instance_by_id[component_id] + return { + "definition_id": instance.definition_id, + "component_id": component_id, + "instance_id": child_node, + "connector_id": connector_id, + "connector_snapshot_id": _connector_snapshot_id( + child_node, connector_id + ), + } + + parameters = { + key: relation.get(key) + for key in ( + "drive_distance", + "drive_angle_degrees", + "pitch_radius_a", + "pitch_radius_b", + "pulley_radius_a", + "pulley_radius_b", + "pitch_radius", + "phase_offset", + ) + if relation.get(key) is not None + } + limits = { + key: relation.get(key) + for key in ("distance_limit", "angle_limit") + if relation.get(key) is not None + } + occurrence_path = assembly_node.removeprefix("node/") + joint_id = f"joint/{occurrence_path}/{constraint_id}" + joints.append( + { + "joint_id": joint_id, + "assembly_definition_id": definition_id, + "joint_type": str(relation["constraint_kind"]), + "connector_a": endpoint("connector_a"), + "connector_b": endpoint("connector_b"), + "parameters": parameters, + "limits": limits or None, + "source_feature_id": feature_id, + } + ) + index.append( + { + "joint_index_id": ( + f"joint-index/{occurrence_path}/{constraint_id}" + ), + "assembly_definition_id": definition_id, + "joint_id": joint_id, + "source_feature_id": feature_id, + } + ) + return ( + sorted(joints, key=lambda item: item["joint_id"]), + sorted(index, key=lambda item: item["joint_index_id"]), + ) + + +def _camera(part_definitions: list[PartDefinition]) -> dict[str, Any]: + if not part_definitions: + raise ProductSceneError("product scene has no part geometry") + bounds = [] + for definition in part_definitions: + part = materialize_definition(definition) + bounds.append(solid_asset_bounds(part.body)) + minimum = [min(item[0][axis] for item in bounds) for axis in range(3)] + maximum = [max(item[1][axis] for item in bounds) for axis in range(3)] + target = [(minimum[axis] + maximum[axis]) * 0.5 for axis in range(3)] + span = max(maximum[axis] - minimum[axis] for axis in range(3)) + distance = max(span * 2.5, 10.0) + return { + "target": target, + "position": [target[0] + distance, target[1] - distance, target[2] + distance], + "up": [0.0, 0.0, 1.0], + "near": max(distance / 1000.0, 0.001), + "far": distance * 100.0, + "fit_mode": "bounds", + "margin": 0.08, + } + + +def compile_product_scene( + root: Definition, + *, + linear_tolerance: float = DEFAULT_LINEAR_TOLERANCE, + angular_tolerance: float = DEFAULT_ANGULAR_TOLERANCE, +) -> ProductScenePackage: + """Compile one durable definition closure into a complete Scene 2.0 package.""" + + if not isinstance(root, (PartDefinition, AssemblyDefinition)): + raise TypeError("root must be a PartDefinition or AssemblyDefinition") + definitions = _definition_closure(root) + blobs: dict[str, bytes] = {} + definition_records: list[dict[str, Any]] = [] + product_assets: list[dict[str, Any]] = [] + feature_assets: list[dict[str, Any]] = [] + source_assets_by_uri: dict[str, dict[str, Any]] = {} + source_ids: dict[str, str] = {} + source_uris: dict[str, str] = {} + feature_graphs: dict[str, FeatureGraphArtifact] = {} + feature_index: list[dict[str, Any]] = [] + source_index: list[dict[str, Any]] = [] + + for definition_id in sorted(definitions): + definition = definitions[definition_id] + product_payload = _definition_bytes(definition) + product_hash = sha256_bytes(product_payload) + product_uri = ( + f"products/sha256-{product_hash.removeprefix('sha256:')}" + + (".part.zip" if isinstance(definition, PartDefinition) else ".assembly.zip") + ) + blobs[product_uri] = product_payload + product_assets.append( + { + **_asset_record( + product_payload, + uri=product_uri, + media_type=_definition_media_type(definition), + ), + "definition_id": definition_id, + "definition_kind": definition.definition_kind, + "revision": definition.revision, + "content_hash": definition.content_hash, + } + ) + + graph = _feature_graph(definition) + feature_graphs[definition_id] = graph + feature_payload = definition.blobs[definition.feature_graph_ref.path] + feature_hash = sha256_bytes(feature_payload) + feature_uri = ( + f"features/sha256-{feature_hash.removeprefix('sha256:')}.zip" + ) + blobs[feature_uri] = feature_payload + feature_assets.append( + { + **_asset_record( + feature_payload, + uri=feature_uri, + media_type="application/vnd.simplecad.feature-graph+zip", + ), + "definition_id": definition_id, + "graph_id": graph.owner_definition_id, + "graph_revision": graph.content_hash, + } + ) + definition_records.append( + { + "definition_id": definition_id, + "definition_kind": definition.definition_kind, + "revision": definition.revision, + "content_hash": definition.content_hash, + "product_asset_id": product_hash, + "feature_graph_asset_id": feature_hash, + } + ) + for source_file in graph.source_files: + payload = graph.blobs[source_file.uri] + source_asset_id = source_file.source_file_id + source_ids[source_file.source_file_id] = source_asset_id + source_uris[source_file.source_file_id] = source_file.uri + existing = source_assets_by_uri.get(source_file.uri) + record = { + "source_asset_id": source_asset_id, + "uri": source_file.uri, + "sha256": sha256_bytes(payload), + "byte_length": len(payload), + "media_type": "text/x-python; charset=utf-8", + "display_name": source_file.display_path, + } + if existing is not None and ( + existing["sha256"] != record["sha256"] + or blobs[source_file.uri] != payload + ): + raise ProductSceneError( + f"source URI collision at {source_file.uri!r}" + ) + source_assets_by_uri.setdefault(source_file.uri, record) + blobs[source_file.uri] = payload + + for definition_id in sorted(definitions): + records, sources = _feature_records( + definitions[definition_id], + feature_graphs[definition_id], + source_ids, + source_uris, + ) + feature_index.extend(records) + source_index.extend(sources) + + geometry_assets_by_id: dict[str, dict[str, Any]] = {} + entity_assets: list[dict[str, Any]] = [] + geometry_ids: dict[str, str] = {} + entity_ids: dict[str, str] = {} + part_definitions = [ + definition + for definition in definitions.values() + if isinstance(definition, PartDefinition) + ] + for definition in sorted(part_definitions, key=lambda item: item.definition_id): + geometry_records, entity_record, part_blobs, geometry_id, entity_id = ( + _part_geometry( + definition, + linear_tolerance=linear_tolerance, + angular_tolerance=angular_tolerance, + ) + ) + for record in geometry_records: + geometry_assets_by_id.setdefault(record["asset_id"], record) + entity_assets.append(entity_record) + blobs.update(part_blobs) + geometry_ids[definition.definition_id] = geometry_id + entity_ids[definition.definition_id] = entity_id + + nodes, occurrences, children = _build_nodes( + root, definitions, geometry_ids, entity_ids + ) + connectors, connector_index = _connectors( + definitions, feature_graphs, occurrences + ) + joints, joint_index = _joints( + definitions, feature_graphs, occurrences, children + ) + manifest = with_scene_revision( + { + "schema_version": "2.0", + "scene_id": root.definition_id, + "units": "mm", + "roots": [_node_id((root.definition_id,))], + "definitions": sorted( + definition_records, key=lambda item: item["definition_id"] + ), + "geometry_assets": sorted( + geometry_assets_by_id.values(), key=lambda item: item["asset_id"] + ), + "entity_assets": sorted( + entity_assets, key=lambda item: item["asset_id"] + ), + "product_assets": sorted( + product_assets, key=lambda item: item["definition_id"] + ), + "feature_graph_assets": sorted( + feature_assets, key=lambda item: item["definition_id"] + ), + "source_assets": sorted( + source_assets_by_uri.values(), key=lambda item: item["uri"] + ), + "nodes": nodes, + "connectors": connectors, + "joints": joints, + "feature_index": sorted( + feature_index, key=lambda item: item["feature_id"] + ), + "source_index": sorted( + source_index, key=lambda item: item["source_index_id"] + ), + "connector_index": connector_index, + "joint_index": joint_index, + "camera": _camera(part_definitions), + "extensions": { + "compile_options": { + "linear_tolerance": float(linear_tolerance), + "angular_tolerance": float(angular_tolerance), + } + }, + } + ) + package = ProductScenePackage(manifest=manifest, blobs=blobs) + object.__setattr__(package, "_validated_manifest", canonical_json_bytes(manifest)) + validate_product_scene_package(package) + return package + + +def validate_product_scene_package(package: ProductScenePackage) -> None: + if not isinstance(package, ProductScenePackage): + raise TypeError("package must be a ProductScenePackage") + manifest = package.manifest + _schema_validate(manifest) + if manifest["revision"] != compute_scene_revision(manifest): + raise ProductSceneError("scene revision is invalid") + + asset_records = [ + *manifest["geometry_assets"], + *manifest["entity_assets"], + *manifest["product_assets"], + *manifest["feature_graph_assets"], + ] + source_records = list(manifest["source_assets"]) + expected_uris = {str(item["uri"]) for item in [*asset_records, *source_records]} + if set(package.blobs) != expected_uris: + raise ProductSceneError("scene blob set differs from asset records") + for record in [*asset_records, *source_records]: + uri = str(record["uri"]) + payload = package.blobs[uri] + if record["byte_length"] != len(payload): + raise ProductSceneError(f"scene asset {uri!r} byte_length differs") + digest = sha256_bytes(payload) + if record["sha256"] != digest: + raise ProductSceneError(f"scene asset {uri!r} sha256 differs") + if "asset_id" in record and record["asset_id"] != digest: + raise ProductSceneError(f"scene asset {uri!r} identity differs") + if "source_asset_id" in record and not isinstance( + record["source_asset_id"], str + ): + raise ProductSceneError(f"source asset {uri!r} identity is invalid") + + definitions = {item["definition_id"]: item for item in manifest["definitions"]} + if len(definitions) != len(manifest["definitions"]): + raise ProductSceneError("scene definition IDs must be unique") + feature_ids = {item["feature_id"] for item in manifest["feature_index"]} + if len(feature_ids) != len(manifest["feature_index"]): + raise ProductSceneError("scene feature IDs must be unique") + for feature in manifest["feature_index"]: + if feature["definition_id"] not in definitions: + raise ProductSceneError("feature references an unknown definition") + if not set(feature["input_feature_ids"]).issubset(feature_ids): + raise ProductSceneError("feature input does not resolve") + + source_asset_ids = {item["source_asset_id"] for item in source_records} + for source in manifest["source_index"]: + if ( + source["source_asset_id"] not in source_asset_ids + or source["feature_id"] not in feature_ids + ): + raise ProductSceneError("source index reference does not resolve") + + product_by_id = {item["definition_id"]: item for item in manifest["product_assets"]} + feature_by_id = { + item["definition_id"]: item for item in manifest["feature_graph_assets"] + } + trusted = package._validated_manifest == canonical_json_bytes(dict(manifest)) + for definition_id, record in definitions.items(): + if definition_id not in product_by_id or definition_id not in feature_by_id: + raise ProductSceneError("definition assets do not resolve") + product_record = product_by_id[definition_id] + if not trusted: + payload = package.blobs[product_record["uri"]] + decoded: Definition + if record["definition_kind"] == "single_solid": + decoded = load_part_definition(payload) + else: + decoded = decode_assembly_definition(payload) + if ( + decoded.definition_id != definition_id + or decoded.definition_kind != record["definition_kind"] + or decoded.revision != record["revision"] + or decoded.content_hash != record["content_hash"] + ): + raise ProductSceneError("product asset identity differs") + graph_record = feature_by_id[definition_id] + graph = load_feature_graph_artifact(package.blobs[graph_record["uri"]]) + if ( + graph.owner_definition_id != definition_id + or graph.content_hash != graph_record["graph_revision"] + ): + raise ProductSceneError("feature graph asset identity differs") + + geometry_ids = {item["asset_id"] for item in manifest["geometry_assets"]} + entity_ids = {item["asset_id"] for item in manifest["entity_assets"]} + node_ids = {item["node_id"] for item in manifest["nodes"]} + if len(node_ids) != len(manifest["nodes"]): + raise ProductSceneError("scene node IDs must be unique") + if not set(manifest["roots"]).issubset(node_ids): + raise ProductSceneError("scene root does not resolve") + for node in manifest["nodes"]: + if node["definition_id"] not in definitions: + raise ProductSceneError("node definition does not resolve") + if node["parent_node_id"] is not None and node["parent_node_id"] not in node_ids: + raise ProductSceneError("node parent does not resolve") + if node["geometry_asset_id"] is not None and node["geometry_asset_id"] not in geometry_ids: + raise ProductSceneError("node geometry asset does not resolve") + if node["entity_asset_id"] is not None and node["entity_asset_id"] not in entity_ids: + raise ProductSceneError("node entity asset does not resolve") + + connector_ids = { + item["connector_snapshot_id"] for item in manifest["connectors"] + } + if len(connector_ids) != len(manifest["connectors"]): + raise ProductSceneError("connector snapshot IDs must be unique") + for connector in manifest["connectors"]: + if connector["node_id"] not in node_ids: + raise ProductSceneError("connector node does not resolve") + source_feature = connector["source_feature_id"] + if source_feature is not None and source_feature not in feature_ids: + raise ProductSceneError("connector feature does not resolve") + for joint in manifest["joints"]: + if ( + joint["connector_a"]["connector_snapshot_id"] not in connector_ids + or joint["connector_b"]["connector_snapshot_id"] not in connector_ids + ): + raise ProductSceneError("joint connector does not resolve") + source_feature = joint["source_feature_id"] + if source_feature is not None and source_feature not in feature_ids: + raise ProductSceneError("joint feature does not resolve") + + feature_by_pair = { + (item["graph_id"], item["node_id"]): item["feature_id"] + for item in manifest["feature_index"] + } + for entity_record in manifest["entity_assets"]: + document = parse_canonical_json(package.blobs[entity_record["uri"]]) + if document["definition_id"] not in definitions: + raise ProductSceneError("entity asset definition does not resolve") + for entity in document["entities"]: + source = entity["source"] + if source["kind"] != "feature_output": + raise ProductSceneError("entity source must be a feature_output") + if (source["graph_id"], source["node_id"]) not in feature_by_pair: + raise ProductSceneError("entity feature output does not resolve") + object.__setattr__( + package, + "_validated_manifest", + canonical_json_bytes(dict(package.manifest)), + ) + + +def encode_product_scene(package: ProductScenePackage) -> bytes: + validate_product_scene_package(package) + return canonical_zip_bytes( + {_SCENE_MANIFEST: canonical_json_bytes(dict(package.manifest)), **package.blobs} + ) + + +def read_scene_package(data: bytes | bytearray | memoryview | str | Path) -> ProductScenePackage: + raw = Path(data).read_bytes() if isinstance(data, (str, Path)) else bytes(data) + archive = preflight_zip_bytes(raw) + manifest = parse_canonical_json(archive.members[_SCENE_MANIFEST]) + if not isinstance(manifest, Mapping): + raise ProductSceneError("scene.json must contain an object") + package = ProductScenePackage( + manifest=manifest, + blobs={ + path: payload + for path, payload in archive.members.items() + if path != _SCENE_MANIFEST + }, + ) + validate_product_scene_package(package) + return package + + +__all__ = [ + "ProductSceneError", + "ProductScenePackage", + "compile_product_scene", + "encode_product_scene", + "read_scene_package", + "validate_product_scene_package", +] diff --git a/src/simplecadapi/scene/resources.py b/src/simplecadapi/scene/resources.py index 1d232759..4fc9c0cb 100644 --- a/src/simplecadapi/scene/resources.py +++ b/src/simplecadapi/scene/resources.py @@ -11,10 +11,10 @@ MIB = 1024 * 1024 @dataclass(frozen=True) class SceneResourceLimits: zip_members: int = 50_000 - input_archive_bytes: int = 256 * MIB - canonical_archive_bytes: int = 256 * MIB + input_archive_bytes: int = 512 * MIB + canonical_archive_bytes: int = 512 * MIB total_uncompressed_bytes: int = 1024 * MIB - one_member_bytes: int = 256 * MIB + one_member_bytes: int = 512 * MIB scene_json_bytes: int = 32 * MIB entity_json_bytes: int = 64 * MIB model_json_bytes: int = 64 * MIB diff --git a/src/simplecadapi/serializer.py b/src/simplecadapi/serializer.py index 543adc4e..9410963e 100644 --- a/src/simplecadapi/serializer.py +++ b/src/simplecadapi/serializer.py @@ -23,7 +23,7 @@ from __future__ import annotations import math from contextlib import nullcontext -from typing import Any, Dict, List, Optional, Sequence, Tuple, cast +from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, cast from .errors import raise_harness_error @@ -71,7 +71,8 @@ from .kernel.ocp_properties import bounding_box MODEL_SCHEMA_VERSION = "2.0" CANONICAL_CONTRACT_VERSION = "2.0" - +_ASSEMBLY_TRANSLATION_RESIDUAL_ABS_TOLERANCE = 1.0e-7 +_ASSEMBLY_ANGULAR_RESIDUAL_ABS_TOLERANCE_DEGREES = 1.0e-6 PUBLIC_API_COVERAGE: Dict[str, Dict[str, str]] = { # Core geometry ops that are recorded and replayable @@ -523,6 +524,7 @@ CANONICAL_CORE_OP_SET: Tuple[str, ...] = ( "make_part_rpart", "make_assign_material_rpart", "make_assembly_rassembly", + "reference_definition", "make_add_component_rassembly", "make_place_component_rassembly", "make_compound_from_assembly_rcompound", @@ -544,6 +546,7 @@ CANONICAL_CORE_OP_SET: Tuple[str, ...] = ( "make_belt_constraint_rassembly", "make_rack_pinion_constraint_rassembly", "make_solve_assembly_constraints_rassembly", + "evaluate_assembly_definition", "make_extrude_rsolid", "make_revolve_rsolid", "make_loft_rsolid", @@ -2208,11 +2211,71 @@ def _validate_operation_output_evidence( ) +def _constraint_reports_match( + actual: Mapping[str, Any], + expected: Mapping[str, Any], +) -> bool: + """Compare solved reports without rejecting harmless floating-point drift.""" + + report_fields = { + "solved", + "grounded_component_ids", + "solved_component_ids", + "unsolved_component_ids", + "residuals", + } + residual_fields = { + "constraint_id", + "translation_error", + "angular_error_degrees", + "within_tolerance", + } + if set(actual) != report_fields or set(expected) != report_fields: + return False + scalar_fields = report_fields - {"residuals"} + if any(actual[field] != expected[field] for field in scalar_fields): + return False + actual_residuals = actual["residuals"] + expected_residuals = expected["residuals"] + if not isinstance(actual_residuals, list) or not isinstance(expected_residuals, list): + return False + if len(actual_residuals) != len(expected_residuals): + return False + for actual_item, expected_item in zip(actual_residuals, expected_residuals): + if not isinstance(actual_item, Mapping) or not isinstance(expected_item, Mapping): + return False + if set(actual_item) != residual_fields or set(expected_item) != residual_fields: + return False + if actual_item["constraint_id"] != expected_item["constraint_id"]: + return False + if actual_item["within_tolerance"] != expected_item["within_tolerance"]: + return False + try: + translation_matches = math.isclose( + float(actual_item["translation_error"]), + float(expected_item["translation_error"]), + rel_tol=0.0, + abs_tol=_ASSEMBLY_TRANSLATION_RESIDUAL_ABS_TOLERANCE, + ) + angular_matches = math.isclose( + float(actual_item["angular_error_degrees"]), + float(expected_item["angular_error_degrees"]), + rel_tol=0.0, + abs_tol=_ASSEMBLY_ANGULAR_RESIDUAL_ABS_TOLERANCE_DEGREES, + ) + except (TypeError, ValueError): + return False + if not translation_matches or not angular_matches: + return False + return True + + def _execute_graph( graph: OperationGraph, leaf_node_ids: Optional[Sequence[str]] = None, *, strict: bool = True, + external_definitions: Mapping[str, Part | Assembly] | None = None, ) -> List[Any]: ctx = _ReplayContext(strict=strict) if graph.node_count == 0: @@ -2260,6 +2323,97 @@ def _execute_graph( try: with context_manager: + if op_name == "reference_definition": + ctx.require_params( + node.node_id, + op_name, + params, + ( + "definition_kind", + "definition_id", + "revision", + "content_hash", + ), + ) + definition_id = str(params["definition_id"]) + value = (external_definitions or {}).get(definition_id) + if value is None: + ctx.fail( + f"Graph node '{node.node_id}' ({op_name}) cannot resolve definition {definition_id!r}" + ) + expected_kind = ( + "single_solid" if isinstance(value, Part) else "assembly" + ) + actual_id = ( + value.part_id if isinstance(value, Part) else value.assembly_id + ) + if ( + actual_id != definition_id + or expected_kind != params["definition_kind"] + or value._get_runtime("definition.content_hash") + != params["content_hash"] + ): + ctx.fail( + f"Graph node '{node.node_id}' ({op_name}) resolved definition identity differs" + ) + _store_semantic_outputs(node, value) + continue + + if op_name == "evaluate_assembly_definition": + ctx.require_params( + node.node_id, + op_name, + params, + ( + "solver_profile", + "component_placements", + "constraint_report", + ), + ) + assembly_outputs = _input_outputs(ctx, outputs, node, 0) + if assembly_outputs: + authored = cast(Assembly, assembly_outputs[0]) + result = authored + placements = params["component_placements"] + if not isinstance(placements, list): + ctx.fail( + f"Graph node '{node.node_id}' ({op_name}) component_placements must be an array" + ) + authored_placements = authored._get_runtime( + "assembly.authored_component_placements" + ) + if authored_placements is None: + authored_placements = { + component.component_id: component.placement.to_dict() + for component in authored.components + } + for item in placements: + if not isinstance(item, dict) or set(item) != { + "instance_id", + "placement", + }: + ctx.fail( + f"Graph node '{node.node_id}' ({op_name}) has invalid placement record" + ) + result = result.with_component_placement( + str(item["instance_id"]), + Placement(**dict(item["placement"])), + ) + report = ops.inspect_assembly_constraints_rconstraintreport( + assembly=result + ) + if not _constraint_reports_match( + report.to_dict(), params["constraint_report"] + ): + ctx.fail( + f"Graph node '{node.node_id}' ({op_name}) residual report differs" + ) + result._set_runtime( + "assembly.authored_component_placements", + authored_placements, + ) + _store_semantic_outputs(node, result) + continue if op_name == "apply_tag_rselection": ctx.require_params( node.node_id, op_name, params, ("tag_binding",) @@ -3693,6 +3847,48 @@ def _execute_graph( return leaf_results +def replay_feature_graph( + artifact: Any, + *, + strict: bool = True, + external_definitions: Mapping[str, Any] | None = None, +) -> List[Any]: + """Replay a durable FeatureGraphArtifact with immutable child definitions.""" + + from .artifacts.assembly_definition import AssemblyDefinition + from .artifacts.assembly_io import materialize_definition + from .artifacts.feature_graph import FeatureGraphArtifact + from .artifacts.part_definition import PartDefinition + + if not isinstance(artifact, FeatureGraphArtifact): + raise TypeError("artifact must be a FeatureGraphArtifact") + provided = dict(external_definitions or {}) + expected = {str(item["definition_id"]): item for item in artifact.external_definitions} + if set(provided) != set(expected): + raise ValueError("external definition resolver keys differ from feature graph") + runtime: Dict[str, Part | Assembly] = {} + for definition_id, record in expected.items(): + definition = provided[definition_id] + if not isinstance(definition, (PartDefinition, AssemblyDefinition)): + raise TypeError("external resolver values must be durable definitions") + actual = { + "definition_kind": definition.definition_kind, + "definition_id": definition.definition_id, + "revision": definition.revision, + "content_hash": definition.content_hash, + } + if actual != dict(record): + raise ValueError( + f"external definition {definition_id!r} identity differs from feature graph" + ) + runtime[definition_id] = materialize_definition(definition) + return _execute_graph( + OperationGraph.from_dict(dict(artifact.graph)), + artifact.result_node_ids, + strict=strict, + external_definitions=runtime, + ) + def replay_graph(graph: OperationGraph, *, strict: bool = True) -> List[Any]: """Replay an OperationGraph to rebuild the model. diff --git a/src/simplecadapi/translator/__init__.py b/src/simplecadapi/translator/__init__.py index a4ff08ba..79e41971 100644 --- a/src/simplecadapi/translator/__init__.py +++ b/src/simplecadapi/translator/__init__.py @@ -1,4 +1,4 @@ -"""Translator backends for exporting SimpleCAD model JSON to external CAD systems.""" +"""Translators that rebuild products in external CAD systems.""" from importlib import import_module from importlib.util import find_spec @@ -7,7 +7,6 @@ from . import freecad_translator __all__ = ["freecad_translator"] -# Contributed backends are optional so a FreeCAD-only cherry-pick remains usable. for _backend_name in ("fusion360_translator", "solidworks_translator"): _qualified_name = f"{__name__}.{_backend_name}" if find_spec(_qualified_name) is None: diff --git a/src/simplecadapi/translator/base.py b/src/simplecadapi/translator/base.py index 07f4665a..e30d530b 100644 --- a/src/simplecadapi/translator/base.py +++ b/src/simplecadapi/translator/base.py @@ -1,46 +1,29 @@ -"""Base contract for canonical model translators.""" +"""Base contract for validated product-package translators.""" from __future__ import annotations from abc import ABC, abstractmethod -from typing import Any, Dict, Optional +from typing import Any -from ..serializer import import_model_json -from ..topology import OperationGraph +from .package_units import ProductPackageInput from .types import BackendCapabilities, TranslationArtifact class BaseTranslator(ABC): - """Translate canonical model JSON into an in-memory backend artifact.""" + """Translate one validated `.scadpkg` closure into a backend artifact.""" @property @abstractmethod def capabilities(self) -> BackendCapabilities: """Return the backend's static capability declaration.""" - def translate_model_json(self, json_str: str) -> TranslationArtifact: - """Parse canonical model JSON and translate its payload.""" - - payload = import_model_json(json_str) - graph = payload.get("graph") - if not isinstance(graph, OperationGraph): - raise ValueError( - "Translation requires model JSON with a canonical low-level graph" - ) - if graph.node_count == 0: - raise ValueError( - "Translation requires model JSON with a non-empty canonical low-level graph" - ) - return self.translate_model_payload(payload, graph=graph) - @abstractmethod - def translate_model_payload( + def translate_product_package( self, - payload: Dict[str, Any], - *, - graph: Optional[OperationGraph] = None, + data: ProductPackageInput, + **options: Any, ) -> TranslationArtifact: - """Translate an already-imported canonical model payload.""" + """Translate one complete durable product-definition closure.""" __all__ = ["BaseTranslator"] diff --git a/src/simplecadapi/translator/freecad_translator/__init__.py b/src/simplecadapi/translator/freecad_translator/__init__.py index ec89fa38..3e813f46 100644 --- a/src/simplecadapi/translator/freecad_translator/__init__.py +++ b/src/simplecadapi/translator/freecad_translator/__init__.py @@ -1,18 +1,15 @@ -"""FreeCAD translator backend for SimpleCAD model JSON.""" +"""FreeCAD translator backend for SimpleCAD product packages.""" from .api import ( - export_model_json_to_fcstd, - translate_model_json_to_fcstd, - translate_model_json_to_freecad_script, + translate_product_package_to_fcstd, + translate_product_package_to_freecad_script, ) from .capabilities import CAPABILITIES -from .translator import FreeCADScriptTranslator, FreeCADTranslator +from .translator import FreeCADTranslator __all__ = [ "CAPABILITIES", - "FreeCADScriptTranslator", "FreeCADTranslator", - "export_model_json_to_fcstd", - "translate_model_json_to_fcstd", - "translate_model_json_to_freecad_script", + "translate_product_package_to_fcstd", + "translate_product_package_to_freecad_script", ] diff --git a/src/simplecadapi/translator/freecad_translator/api.py b/src/simplecadapi/translator/freecad_translator/api.py index 519a0201..41725fdf 100644 --- a/src/simplecadapi/translator/freecad_translator/api.py +++ b/src/simplecadapi/translator/freecad_translator/api.py @@ -1,76 +1,41 @@ -"""Public FreeCAD translator entrypoints.""" +"""Public FreeCAD product translator entrypoints.""" from __future__ import annotations from typing import Optional from ...errors import raise_harness_error +from ..package_units import ProductPackageInput from .exporter import discover_freecad_executable, export_freecad_script_to_fcstd from .translator import FreeCADTranslator -def translate_model_json_to_freecad_script( - json_str: str, - document_name: str = "SimpleCADModel", +def translate_product_package_to_freecad_script( + data: ProductPackageInput, + document_name: str = "SimpleCADProduct", ) -> str: - """Translate exported model JSON into a FreeCAD Python script. + """Translate one validated `.scadpkg` closure into a FreeCAD script.""" - Geometry is emitted as FreeCAD occurrence trees. Serialized source assignment - targets name native design objects, shared DAG inputs are copied per consuming - result, and feature links preserve dependencies. Booleans are emitted as native - recomputable `Part::Cut`, `Part::Fuse`, and `Part::Common` features. Stable node - ids remain available as internal metadata. - `apply_tag_rselection` nodes do not create FreeCAD features. Their canonical - bindings and source node ids are attached to traceable geometry and visible - result objects as `SimpleCADAppliedTags`, `SimpleCADTagBindings`, and - `SimpleCADTagNodeIds`. - The Tree View exposes only resolved product or standalone-geometry roots. - Assembly projection compounds and link source definitions remain available - for recomputation but are hidden from the user-facing document tree. - """ - - return FreeCADTranslator( - document_name=document_name - ).translate_model_json_to_script(json_str) + artifact = FreeCADTranslator(document_name=document_name).translate_product_package( + data + ) + assert isinstance(artifact.content, str) + return artifact.content -def translate_model_json_to_fcstd( - json_str: str, +def translate_product_package_to_fcstd( + data: ProductPackageInput, output_path: str, *, - document_name: str = "SimpleCADModel", + document_name: str = "SimpleCADProduct", freecad_cmd: Optional[str] = None, ) -> str: - """Translate canonical model JSON to `.FCStd` via FreeCADCmd/FreeCAD. - - Functional sketch promotions are written as visible `Sketcher::SketchObject` - nodes with mapped/skipped constraint evidence. Exact B-spline edges are - exported to FreeCAD using `Part.BSplineCurve().buildFromPolesMultsKnots(...)`. - Safe single-use profile transforms such as section rotate/translate chains are - folded into the section object's placement so downstream `Part::Loft` receives - already-positioned sections instead of placement-bearing `App::Link` proxies. - Geometry results use FreeCAD objects directly: assignment targets name design - objects and shared inputs receive independent occurrences per consumer. Native - features preserve recomputing dependencies, including surface-dependent - Booleans. Their classifications may vary across FreeCAD/OCCT versions. No - presentation proxy, duplicate history tree, or hidden graph-object archive is - created. - `apply_tag_rselection` remains graph metadata rather than a FreeCAD feature; - traceable geometry and visible result objects expose `SimpleCADAppliedTags`, - `SimpleCADTagBindings`, and `SimpleCADTagNodeIds`. - Part/Assembly product nodes are written as editable FreeCAD assembly structure: - parts use `App::Part`, assemblies use native `Assembly::AssemblyObject`, part - components use `App::Link`, and nested assembly components use - `Assembly::AssemblyLink`. Explicit assembly-to-compound projections remain - available for geometry workflows without creating a second user-facing root. - Link source definitions remain in the document for recomputation, but the - Tree View exposes only the resolved product or standalone-geometry roots. - """ + """Translate one validated `.scadpkg` closure into an editable `.FCStd`.""" freecad_exe = freecad_cmd or discover_freecad_executable() if not freecad_exe: raise_harness_error( - operation="translate_model_json_to_fcstd", + operation="translate_product_package_to_fcstd", what_happened="Could not locate a FreeCAD command-line executable.", possible_causes=[ "FreeCADCmd is not installed or not available on PATH.", @@ -82,9 +47,8 @@ def translate_model_json_to_fcstd( ], error=FileNotFoundError("FreeCADCmd/FreeCAD not found"), ) - - script = translate_model_json_to_freecad_script( - json_str, document_name=document_name + script = translate_product_package_to_freecad_script( + data, document_name=document_name ) try: return export_freecad_script_to_fcstd( @@ -92,36 +56,25 @@ def translate_model_json_to_fcstd( output_path, freecad_executable=freecad_exe, ) - except Exception as e: + except Exception as exc: raise_harness_error( - operation="translate_model_json_to_fcstd", - what_happened="Failed to execute the generated FreeCAD export script.", + operation="translate_product_package_to_fcstd", + what_happened="Failed to execute the generated FreeCAD package script.", possible_causes=[ - "FreeCADCmd started but the generated script hit an unsupported API call.", + "A definition-owned Feature Graph used an unsupported FreeCAD operation.", + "A package reference did not resolve to an earlier definition.", "The output path is invalid or not writable.", - "The installed FreeCAD build lacks Part or Spreadsheet support needed by the translator.", ], how_to_fix=[ - "Inspect the generated script first with translate_model_json_to_freecad_script().", + "Inspect the generated package script.", "Use a writable .FCStd output path.", - "Run the same script manually inside a matching FreeCAD environment to isolate runtime differences.", + "Check the package definition closure and Feature Graph support.", ], - error=e, + error=exc, ) -def export_model_json_to_fcstd( - json_str: str, - output_path: str, - *, - document_name: str = "SimpleCADModel", - freecad_cmd: Optional[str] = None, -) -> str: - """Export canonical model JSON to `.FCStd` via FreeCADCmd/FreeCAD.""" - - return translate_model_json_to_fcstd( - json_str, - output_path, - document_name=document_name, - freecad_cmd=freecad_cmd, - ) +__all__ = [ + "translate_product_package_to_fcstd", + "translate_product_package_to_freecad_script", +] diff --git a/src/simplecadapi/translator/freecad_translator/capabilities.py b/src/simplecadapi/translator/freecad_translator/capabilities.py index 9795093d..1151525e 100644 --- a/src/simplecadapi/translator/freecad_translator/capabilities.py +++ b/src/simplecadapi/translator/freecad_translator/capabilities.py @@ -75,6 +75,8 @@ _CANONICAL_OPS = ( "make_part_rpart", "make_assign_material_rpart", "make_assembly_rassembly", + "reference_definition", + "evaluate_assembly_definition", "make_add_component_rassembly", "make_place_component_rassembly", "make_compound_from_assembly_rcompound", @@ -204,7 +206,7 @@ OP_SUPPORT["apply_tag_rselection"] = OperationCapability( CAPABILITIES = BackendCapabilities( backend_id=BACKEND_NAME, display_name="FreeCAD", - input_schema_versions=("2.0",), + input_schema_versions=("product-package-2.0",), targets=( TranslationTarget( target_id="freecad_script", diff --git a/src/simplecadapi/translator/freecad_translator/codegen.py b/src/simplecadapi/translator/freecad_translator/codegen.py index 3a00e010..df19caf7 100644 --- a/src/simplecadapi/translator/freecad_translator/codegen.py +++ b/src/simplecadapi/translator/freecad_translator/codegen.py @@ -203,9 +203,9 @@ def _sanitize_expr_alias(alias: str, *, prefix: str = "expr") -> str: def _expr_short_suffix(expr_id: str) -> str: raw = str(expr_id).rsplit("_", 1)[-1] - token = "".join( - ch if ch.isascii() and ch.isalnum() else "_" for ch in raw - ).strip("_") + token = "".join(ch if ch.isascii() and ch.isalnum() else "_" for ch in raw).strip( + "_" + ) return token[:8] if token else "id" @@ -215,9 +215,9 @@ def _const_value_alias_token(value: Any) -> str: except Exception: return "value" text = f"{number:.6g}".replace("-", "neg_").replace(".", "_") - token = "".join( - ch if ch.isascii() and ch.isalnum() else "_" for ch in text - ).strip("_") + token = "".join(ch if ch.isascii() and ch.isalnum() else "_" for ch in text).strip( + "_" + ) return token or "value" diff --git a/src/simplecadapi/translator/freecad_translator/context.py b/src/simplecadapi/translator/freecad_translator/context.py index 19ba652a..281fa1a6 100644 --- a/src/simplecadapi/translator/freecad_translator/context.py +++ b/src/simplecadapi/translator/freecad_translator/context.py @@ -13,6 +13,12 @@ class FreeCADCompileContext: """Mutable state owned by one FreeCAD script compilation.""" document_name: str + expression_sheet_name: str = "SimpleCADExpressions" + definition_token: str = "" + definition_id: str = "" + definition_kind: str = "" + definition_revision: str = "" + definition_content_hash: str = "" source_graph: Optional[OperationGraph] = None expression_aliases: Dict[str, str] = field(default_factory=dict) result_node_ids: Set[str] = field(default_factory=set) diff --git a/src/simplecadapi/translator/freecad_translator/emitters/geometry.py b/src/simplecadapi/translator/freecad_translator/emitters/geometry.py index c6292afa..adfc6338 100644 --- a/src/simplecadapi/translator/freecad_translator/emitters/geometry.py +++ b/src/simplecadapi/translator/freecad_translator/emitters/geometry.py @@ -137,16 +137,18 @@ class GeometryEmitterMixin: point_exprs.append(f"_edge_start_point({edge_obj_expr})") point_exprs.append(f"_edge_mid_point({edge_obj_expr})") point_exprs.append(f"_edge_end_point({edge_obj_expr})") - elif input_node.op in {"make_spline_redge", "make_interpolated_spline_redge"}: + elif input_node.op in { + "make_spline_redge", + "make_interpolated_spline_redge", + }: point_exprs.append(f"_edge_start_point({edge_obj_expr})") point_exprs.append(f"_edge_mid_point({edge_obj_expr})") point_exprs.append(f"_edge_end_point({edge_obj_expr})") limitation_payload = _node_expression_limitation(input_node) - if ( - input_node.op - in {"make_circle_redge", "make_angle_arc_redge"} - and _contains_expr_refs(input_node.param_exprs.get("normal")) - ): + if input_node.op in { + "make_circle_redge", + "make_angle_arc_redge", + } and _contains_expr_refs(input_node.param_exprs.get("normal")): limitation_payload = { "op": input_node.op, "reason": _DYNAMIC_CURVE_NORMAL_LIMITATION, @@ -169,8 +171,7 @@ class GeometryEmitterMixin: frame_points = "[" + ", ".join(point_exprs) + "]" preferred_normal_expr = "None" if all( - input_node is not None - and input_node.op == "make_circle_redge" + input_node is not None and input_node.op == "make_circle_redge" for input_node in input_nodes ): circle_var = _safe_name(input_nodes[0].node_id) @@ -308,7 +309,10 @@ class GeometryEmitterMixin: lines.append( f"{var_name}_constraint_bindings.append((f'Constraints[{{{var_name}_angle_constraint_{geom_index}}}]', {_json_ascii(arc_span_formula) if arc_span_formula is not None else 'None'}))" ) - elif input_node.op in {"make_spline_redge", "make_interpolated_spline_redge"}: + elif input_node.op in { + "make_spline_redge", + "make_interpolated_spline_redge", + }: lines.append( f"{var_name}.addGeometry(_bspline_curve_from_params({edge_var}_params, transform_point=lambda point: _local_point_on_frame(point, {var_name}_origin, {var_name}_xaxis, {var_name}_yaxis), context={_py_literal(input_node.context or {})}), False)" ) diff --git a/src/simplecadapi/translator/freecad_translator/emitters/primitives.py b/src/simplecadapi/translator/freecad_translator/emitters/primitives.py index 133240b7..9b8408d8 100644 --- a/src/simplecadapi/translator/freecad_translator/emitters/primitives.py +++ b/src/simplecadapi/translator/freecad_translator/emitters/primitives.py @@ -60,7 +60,9 @@ class PrimitiveEmitterMixin: f"{var_name}.Height = {var_name}_depth", f"{var_name}.Placement = App.Placement({var_name}_corner, App.Rotation())", ] - lines.append(f"_apply_op_expression_bindings({var_name}, {_json_ascii(node.op)}, {re})") + lines.append( + f"_apply_op_expression_bindings({var_name}, {_json_ascii(node.op)}, {re})" + ) lines.extend(finish()) return lines if node.op == "make_cylinder_rsolid": @@ -70,7 +72,9 @@ class PrimitiveEmitterMixin: f"{var_name}.Height = float(_resolve_param_value({rp}, {re}, 'height'))", f"{var_name}.Placement = App.Placement(_vec(_resolve_vec3_param({rp}, {re}, 'bottom_face_center')), App.Rotation(App.Vector(0.0, 0.0, 1.0), _vec(_resolve_vec3_param({rp}, {re}, 'axis'))))", ] - lines.append(f"_apply_op_expression_bindings({var_name}, {_json_ascii(node.op)}, {re})") + lines.append( + f"_apply_op_expression_bindings({var_name}, {_json_ascii(node.op)}, {re})" + ) lines.extend(finish()) return lines if node.op == "make_cone_rsolid": @@ -81,7 +85,9 @@ class PrimitiveEmitterMixin: f"{var_name}.Height = float(_resolve_param_value({rp}, {re}, 'height'))", f"{var_name}.Placement = App.Placement(_vec(_resolve_vec3_param({rp}, {re}, 'bottom_face_center')), App.Rotation(App.Vector(0.0, 0.0, 1.0), _vec(_resolve_vec3_param({rp}, {re}, 'axis'))))", ] - lines.append(f"_apply_op_expression_bindings({var_name}, {_json_ascii(node.op)}, {re})") + lines.append( + f"_apply_op_expression_bindings({var_name}, {_json_ascii(node.op)}, {re})" + ) lines.extend(finish()) return lines if node.op == "make_sphere_rsolid": @@ -90,7 +96,9 @@ class PrimitiveEmitterMixin: f"{var_name}.Radius = float(_resolve_param_value({rp}, {re}, 'radius'))", f"{var_name}.Placement = App.Placement(_vec(_resolve_vec3_param({rp}, {re}, 'center')), App.Rotation())", ] - lines.append(f"_apply_op_expression_bindings({var_name}, {_json_ascii(node.op)}, {re})") + lines.append( + f"_apply_op_expression_bindings({var_name}, {_json_ascii(node.op)}, {re})" + ) lines.extend(finish()) return lines return None diff --git a/src/simplecadapi/translator/freecad_translator/emitters/products.py b/src/simplecadapi/translator/freecad_translator/emitters/products.py index dcdc0113..12bd6d3b 100644 --- a/src/simplecadapi/translator/freecad_translator/emitters/products.py +++ b/src/simplecadapi/translator/freecad_translator/emitters/products.py @@ -47,6 +47,33 @@ class ProductEmitterMixin: f"{var_name} = _register_graph_alias(node_id={_json_ascii(node.node_id)}, source_node_id={_json_ascii(source_node_id)}, op={_json_ascii(node.op)}, params={rp}, inputs={var_name}_inputs, tags={tags_literal}, context={context_literal}, output_count={node.output_count}, param_exprs={param_exprs_literal}, semantic_delta={semantic_delta_literal}, topo_delta={topo_delta_literal})" ] + if node.op == "reference_definition": + return [ + f"{var_name}_definition_id = str({rp}.get('definition_id', ''))", + f"{var_name}_record = DEFINITION_REGISTRY.get({var_name}_definition_id)", + f"if not isinstance({var_name}_record, dict): raise RuntimeError('Missing translated definition ' + repr({var_name}_definition_id))", + f"if str({var_name}_record.get('definition_kind')) != str({rp}.get('definition_kind')) or str({var_name}_record.get('revision')) != str({rp}.get('revision')) or str({var_name}_record.get('content_hash')) != str({rp}.get('content_hash')): raise RuntimeError('Translated definition identity differs for ' + repr({var_name}_definition_id))", + f"{var_name} = {var_name}_record['product']", + f"PRODUCT_VALUES[{_json_ascii(node.node_id)}] = {var_name}", + f"{var_name} = _register_graph_value({var_name}, node_id={_json_ascii(node.node_id)}, op={_json_ascii(node.op)}, params={rp}, inputs={var_name}_inputs, tags={tags_literal}, context={context_literal}, output_count={node.output_count}, param_exprs={param_exprs_literal}, semantic_delta={semantic_delta_literal}, topo_delta={topo_delta_literal})", + ] + if node.op == "evaluate_assembly_definition" and len(inputs) >= 1: + return [ + f"{var_name}_assembly = PRODUCT_VALUES[{_json_ascii(inputs[0])}]", + f"PRODUCT_VALUES[{_json_ascii(node.node_id)}] = dict({var_name}_assembly)", + f"{var_name}_placements = {{str(item.get('instance_id')): item.get('placement') or {{}} for item in list({rp}.get('component_placements') or []) if isinstance(item, dict)}}", + f"{var_name}_components = []", + f"for _component in {var_name}_assembly.get('components', []):", + f" _component = dict(_component)", + f" _component_id = str(_component.get('component_id'))", + f" if _component_id in {var_name}_placements:", + f" _component['placement'] = {var_name}_placements[_component_id]", + f" _set_component_link_placement(_component['link'], _component.get('item') or {{}}, _component['placement'])", + f" {var_name}_components.append(_component)", + f"PRODUCT_VALUES[{_json_ascii(node.node_id)}]['components'] = {var_name}_components", + f"{var_name} = _register_graph_folded_alias(node_id={_json_ascii(node.node_id)}, source_node_id={_json_ascii(inputs[0])}, op={_json_ascii(node.op)}, params={rp}, inputs={var_name}_inputs, tags={tags_literal}, context={context_literal}, output_count={node.output_count}, param_exprs={param_exprs_literal}, semantic_delta={semantic_delta_literal}, topo_delta={topo_delta_literal})", + ] + if node.op == "make_material_rmaterial": return [ f"{var_name} = dict({rp})", @@ -68,8 +95,7 @@ class ProductEmitterMixin: f"{var_name} = doc.addObject('App::Part', {_json_ascii(object_name)})", f"{var_name}.Label = str({rp}.get('name') or {rp}.get('part_id') or {_json_ascii(object_name)})", f"{var_name}_source_body = GRAPH_NODES[{_json_ascii(inputs[0])}]", - f"{var_name}_body = _make_part_body_copy({var_name}, {var_name}_source_body, {_json_ascii(inputs[0])})", - f"{var_name}.addObject({var_name}_body)", + f"{var_name}_body = _adopt_part_feature_history({var_name}, {var_name}_source_body, {_json_ascii(inputs[0])})", f"_ensure_string_property({var_name}, 'SimpleCADPartId')", f"{var_name}.SimpleCADPartId = str({rp}.get('part_id', ''))", f"_hide_origin_tree({var_name})", diff --git a/src/simplecadapi/translator/freecad_translator/emitters/registry.py b/src/simplecadapi/translator/freecad_translator/emitters/registry.py index 8bd6aef5..041ecbac 100644 --- a/src/simplecadapi/translator/freecad_translator/emitters/registry.py +++ b/src/simplecadapi/translator/freecad_translator/emitters/registry.py @@ -11,6 +11,8 @@ EMITTER_METHOD_BY_OP: Dict[str, str] = { "make_cylinder_rsolid": "_emit_primitives", "make_cone_rsolid": "_emit_primitives", "make_sphere_rsolid": "_emit_primitives", + "reference_definition": "_emit_products", + "evaluate_assembly_definition": "_emit_products", "make_material_rmaterial": "_emit_products", "make_placement_rplacement": "_emit_products", "make_identity_placement_rplacement": "_emit_products", diff --git a/src/simplecadapi/translator/freecad_translator/emitters/selections.py b/src/simplecadapi/translator/freecad_translator/emitters/selections.py index f8f7211e..92fddd3e 100644 --- a/src/simplecadapi/translator/freecad_translator/emitters/selections.py +++ b/src/simplecadapi/translator/freecad_translator/emitters/selections.py @@ -57,7 +57,7 @@ class SelectionEmitterMixin: "make_select_rshell", "make_select_rsolid", } - and len(inputs) == 1 + and inputs ): downstream_nodes = [ graph.get_node(node_id) diff --git a/src/simplecadapi/translator/freecad_translator/emitters/transforms.py b/src/simplecadapi/translator/freecad_translator/emitters/transforms.py index 922c903b..0d4861dd 100644 --- a/src/simplecadapi/translator/freecad_translator/emitters/transforms.py +++ b/src/simplecadapi/translator/freecad_translator/emitters/transforms.py @@ -51,7 +51,9 @@ class TransformEmitterMixin: vector = node.params.get("vector") if isinstance(vector, (list, tuple)) and len(vector) == 3: try: - if all(abs(float(v)) <= 1e-12 for v in vector) and not _contains_expr_refs(dict(node.param_exprs)): + if all( + abs(float(v)) <= 1e-12 for v in vector + ) and not _contains_expr_refs(dict(node.param_exprs)): return finish_alias(inputs[0]) except Exception: pass diff --git a/src/simplecadapi/translator/freecad_translator/runtime/__init__.py b/src/simplecadapi/translator/freecad_translator/runtime/__init__.py index 67b0628d..95b97848 100644 --- a/src/simplecadapi/translator/freecad_translator/runtime/__init__.py +++ b/src/simplecadapi/translator/freecad_translator/runtime/__init__.py @@ -22,8 +22,7 @@ _FRAGMENT_NAMES = ( def assemble_runtime_source() -> str: runtime_dir = Path(__file__).resolve().parent return "".join( - (runtime_dir / name).read_text(encoding="utf-8") - for name in _FRAGMENT_NAMES + (runtime_dir / name).read_text(encoding="utf-8") for name in _FRAGMENT_NAMES ) diff --git a/src/simplecadapi/translator/freecad_translator/runtime/assemblies.py b/src/simplecadapi/translator/freecad_translator/runtime/assemblies.py index f11f50cd..4b7f7a19 100644 --- a/src/simplecadapi/translator/freecad_translator/runtime/assemblies.py +++ b/src/simplecadapi/translator/freecad_translator/runtime/assemblies.py @@ -1,10 +1,25 @@ -def _make_native_assembly(name, *, node_id, op, params, inputs, tags, context, output_count, param_exprs=None, semantic_delta=None, topo_delta=None): +def _make_native_assembly( + name, + *, + node_id, + op, + params, + inputs, + tags, + context, + output_count, + param_exprs=None, + semantic_delta=None, + topo_delta=None, +): if Assembly is None: - raise RuntimeError('FreeCAD Assembly workbench module is required for SimpleCAD Assembly translation') - obj = doc.addObject('Assembly::AssemblyObject', name) - obj.Type = 'Assembly' + raise RuntimeError( + "FreeCAD Assembly workbench module is required for SimpleCAD Assembly translation" + ) + obj = doc.addObject("Assembly::AssemblyObject", name) + obj.Type = "Assembly" try: - obj.newObject('Assembly::JointGroup', 'Joints') + obj.newObject("Assembly::JointGroup", "Joints") except Exception: pass return _register_graph_object( @@ -23,192 +38,250 @@ def _make_native_assembly(name, *, node_id, op, params, inputs, tags, context, o def _joint_group_for(assembly_container): - for child in list(getattr(assembly_container, 'OutList', []) or []): - if getattr(child, 'TypeId', '') == 'Assembly::JointGroup': + for child in list(getattr(assembly_container, "OutList", []) or []): + if getattr(child, "TypeId", "") == "Assembly::JointGroup": return child - return assembly_container.newObject('Assembly::JointGroup', 'Joints') + return assembly_container.newObject("Assembly::JointGroup", "Joints") def _find_component_entry(assembly_value, component_id): - for component in list(assembly_value.get('components', []) or []): - if str(component.get('component_id')) == str(component_id): + for component in list(assembly_value.get("components", []) or []): + if str(component.get("component_id")) == str(component_id): return component - raise RuntimeError(f'Missing assembly component {component_id!r}') + raise RuntimeError(f"Missing assembly component {component_id!r}") def _connector_payload_for(component_entry, connector_id): - item = component_entry.get('item') or {} + item = component_entry.get("item") or {} try: return _connector_payload_for_item(item, connector_id) except Exception as exc: - raise RuntimeError(f'Missing connector {connector_id!r} on component {component_entry.get("component_id")!r}') from exc + raise RuntimeError( + f'Missing connector {connector_id!r} on component {component_entry.get("component_id")!r}' + ) from exc def _freecad_subname_for_kind(kind, index): # Convert a 0-based index into a FreeCAD sub-element name string. kind_lower = str(kind).lower() - prefix_map = {'vertex': 'Vertex', 'edge': 'Edge', 'wire': 'Wire', 'face': 'Face', 'solid': 'Solid'} - prefix = prefix_map.get(kind_lower, 'Face') - return f'{prefix}{index + 1}' + prefix_map = { + "vertex": "Vertex", + "edge": "Edge", + "wire": "Wire", + "face": "Face", + "solid": "Solid", + } + prefix = prefix_map.get(kind_lower, "Face") + return f"{prefix}{index + 1}" def _resolve_connector_subname(component_entry, connector_payload): # Resolve the FreeCAD sub-element name (e.g. Face3) for a connector geometry_ref. # Uses the geo_selector to match against the component link shape. # Returns a tuple (subname1, subname2) suitable for FreeCAD Reference1/Reference2. - geometry_ref = connector_payload.get('geometry_ref') or {} - geo_selector = geometry_ref.get('geo_selector') or {} - kind = str(geometry_ref.get('kind') or geo_selector.get('kind') or '').lower() + geometry_ref = connector_payload.get("geometry_ref") or {} + geo_selector = geometry_ref.get("geo_selector") or {} + kind = str(geometry_ref.get("kind") or geo_selector.get("kind") or "").lower() if not kind: - return '', '' - link = component_entry.get('link') + return "", "" + link = component_entry.get("link") if link is None: - return '', '' - linked_obj = getattr(link, 'LinkedObject', None) or link - shape = getattr(linked_obj, 'Shape', None) + return "", "" + linked_obj = getattr(link, "LinkedObject", None) or link + shape = getattr(linked_obj, "Shape", None) if shape is None: - return '', '' + return "", "" try: index = _selection_index_for_selector(shape, geo_selector) subname = _freecad_subname_for_kind(kind, index) return subname, subname except Exception: - return '', '' + return "", "" -def _connector_reference_for_component(assembly_value, component_entry, connector_payload): - link = component_entry.get('link') +def _connector_reference_for_component( + assembly_value, component_entry, connector_payload +): + link = component_entry.get("link") if link is None: - raise RuntimeError(f'Missing component link for component {component_entry.get("component_id")!r}') + raise RuntimeError( + f'Missing component link for component {component_entry.get("component_id")!r}' + ) anchor = _connector_anchor_payload(connector_payload or {}) if ( - getattr(link, 'TypeId', '') == 'Assembly::AssemblyLink' - and not bool(getattr(link, 'Rigid', True)) - and str(anchor.get('anchor_kind') or '').lower() == 'forwarded' + getattr(link, "TypeId", "") == "Assembly::AssemblyLink" + and not bool(getattr(link, "Rigid", True)) + and str(anchor.get("anchor_kind") or "").lower() == "forwarded" ): source_component = _find_component_entry( - component_entry.get('item') or {}, anchor.get('source_component_id') + component_entry.get("item") or {}, anchor.get("source_component_id") ) - source_link = source_component.get('link') + source_link = source_component.get("link") local_link = next( child - for child in list(getattr(link, 'Group', []) or []) - if getattr(child, 'LinkedObject', None) is source_link + for child in list(getattr(link, "Group", []) or []) + if getattr(child, "LinkedObject", None) is source_link ) - source_item = source_component.get('item') or {} + source_item = source_component.get("item") or {} source_connector = _connector_payload_for_item( - source_item, anchor.get('source_connector_id') + source_item, anchor.get("source_connector_id") ) placement = _connector_local_placement(source_item, source_connector) - if isinstance(anchor.get('offset'), dict): - placement = placement.multiply(_placement_from_axes_payload(anchor.get('offset'))) - return local_link, ['', ''], placement, True - datum = (connector_payload or {}).get('datum') - datum_name = str(getattr(datum, 'Name', '') or '') + if isinstance(anchor.get("offset"), dict): + placement = placement.multiply( + _placement_from_axes_payload(anchor.get("offset")) + ) + return local_link, ["", ""], placement, True + datum = (connector_payload or {}).get("datum") + datum_name = str(getattr(datum, "Name", "") or "") if datum_name: - subname = datum_name + '.' + subname = datum_name + "." return link, [subname, subname], App.Placement(), False anchor = _connector_anchor_payload(connector_payload or {}) - if str(anchor.get('anchor_kind') or '').lower() == 'geometry': + if str(anchor.get("anchor_kind") or "").lower() == "geometry": sub_a, sub_b = _resolve_connector_subname(component_entry, connector_payload) if sub_a and sub_b: return link, [sub_a, sub_b], App.Placement(), False - return link, ['', ''], _connector_local_placement(component_entry.get('item') or {}, connector_payload), True + return ( + link, + ["", ""], + _connector_local_placement( + component_entry.get("item") or {}, connector_payload + ), + True, + ) def _make_simplecad_joint(assembly_value, constraint_payload, object_name, label): - assembly_container = assembly_value.get('container') + assembly_container = assembly_value.get("container") if assembly_container is None: - raise RuntimeError('Assembly value has no container for constraint translation') - connector_a = constraint_payload.get('connector_a') or {} - connector_b = constraint_payload.get('connector_b') or {} - component_a = _find_component_entry(assembly_value, connector_a.get('component_id')) - component_b = _find_component_entry(assembly_value, connector_b.get('component_id')) - connector_a_payload = _connector_payload_for(component_a, connector_a.get('connector_id')) - connector_b_payload = _connector_payload_for(component_b, connector_b.get('connector_id')) - joint_type = {'fixed': 'Fixed', 'revolute': 'Revolute', 'prismatic': 'Slider', 'gear': 'Gears', 'belt': 'Belt', 'rack_pinion': 'RackPinion'}.get(str(constraint_payload.get('constraint_kind'))) + raise RuntimeError("Assembly value has no container for constraint translation") + connector_a = constraint_payload.get("connector_a") or {} + connector_b = constraint_payload.get("connector_b") or {} + component_a = _find_component_entry(assembly_value, connector_a.get("component_id")) + component_b = _find_component_entry(assembly_value, connector_b.get("component_id")) + connector_a_payload = _connector_payload_for( + component_a, connector_a.get("connector_id") + ) + connector_b_payload = _connector_payload_for( + component_b, connector_b.get("connector_id") + ) + joint_type = { + "fixed": "Fixed", + "revolute": "Revolute", + "prismatic": "Slider", + "gear": "Gears", + "belt": "Belt", + "rack_pinion": "RackPinion", + }.get(str(constraint_payload.get("constraint_kind"))) if not joint_type: - raise RuntimeError(f"Unsupported SimpleCAD constraint kind {constraint_payload.get('constraint_kind')!r}") + raise RuntimeError( + f"Unsupported SimpleCAD constraint kind {constraint_payload.get('constraint_kind')!r}" + ) joint_group = _joint_group_for(assembly_container) - joint = joint_group.newObject('App::FeaturePython', object_name) - joint.Label = str(label or constraint_payload.get('constraint_id') or object_name) - type_index = {'Fixed': 0, 'Revolute': 1, 'Slider': 3, 'RackPinion': 9, 'Gears': 11, 'Belt': 12}[joint_type] - native_status = 'metadata_only' + joint = joint_group.newObject("App::FeaturePython", object_name) + joint.Label = str(label or constraint_payload.get("constraint_id") or object_name) + type_index = { + "Fixed": 0, + "Revolute": 1, + "Slider": 3, + "RackPinion": 9, + "Gears": 11, + "Belt": 12, + }[joint_type] + native_status = "metadata_only" if JointObject is not None: JointObject.Joint(joint, type_index) - native_status = 'native_equivalent' - if getattr(App, 'GuiUp', False) and hasattr(joint, 'ViewObject') and joint.ViewObject is not None: + native_status = "native_equivalent" + if ( + getattr(App, "GuiUp", False) + and hasattr(joint, "ViewObject") + and joint.ViewObject is not None + ): try: JointObject.ViewProviderJoint(joint.ViewObject) except Exception: pass else: - _ensure_string_property(joint, 'JointType') + _ensure_string_property(joint, "JointType") joint.JointType = joint_type try: - ref_a_obj, ref_a_subs, ref_a_placement, ref_a_detached = _connector_reference_for_component(assembly_value, component_a, connector_a_payload) - ref_b_obj, ref_b_subs, ref_b_placement, ref_b_detached = _connector_reference_for_component(assembly_value, component_b, connector_b_payload) - if hasattr(joint, 'Reference1'): - if hasattr(joint, 'Detach1'): + ref_a_obj, ref_a_subs, ref_a_placement, ref_a_detached = ( + _connector_reference_for_component( + assembly_value, component_a, connector_a_payload + ) + ) + ref_b_obj, ref_b_subs, ref_b_placement, ref_b_detached = ( + _connector_reference_for_component( + assembly_value, component_b, connector_b_payload + ) + ) + if hasattr(joint, "Reference1"): + if hasattr(joint, "Detach1"): joint.Detach1 = bool(ref_a_detached) - if hasattr(joint, 'Detach2'): + if hasattr(joint, "Detach2"): joint.Detach2 = bool(ref_b_detached) joint.Reference1 = [ref_a_obj, list(ref_a_subs)] joint.Reference2 = [ref_b_obj, list(ref_b_subs)] - if hasattr(joint, 'Placement1'): + if hasattr(joint, "Placement1"): joint.Placement1 = ref_a_placement - if hasattr(joint, 'Placement2'): + if hasattr(joint, "Placement2"): joint.Placement2 = ref_b_placement except Exception: - native_status = 'native_partial' - if joint_type == 'Revolute' and constraint_payload.get('drive_angle_degrees') is not None: + native_status = "native_partial" + if ( + joint_type == "Revolute" + and constraint_payload.get("drive_angle_degrees") is not None + ): try: - joint.Angle = float(constraint_payload.get('drive_angle_degrees')) + joint.Angle = float(constraint_payload.get("drive_angle_degrees")) except Exception: - native_status = 'native_partial' - if joint_type == 'Slider' and constraint_payload.get('drive_distance') is not None: + native_status = "native_partial" + if joint_type == "Slider" and constraint_payload.get("drive_distance") is not None: try: - joint.Distance = float(constraint_payload.get('drive_distance')) + joint.Distance = float(constraint_payload.get("drive_distance")) except Exception: - native_status = 'native_partial' - if joint_type == 'Gears': + native_status = "native_partial" + if joint_type == "Gears": try: - joint.Distance = float(constraint_payload.get('pitch_radius_a')) - joint.Distance2 = float(constraint_payload.get('pitch_radius_b')) + joint.Distance = float(constraint_payload.get("pitch_radius_a")) + joint.Distance2 = float(constraint_payload.get("pitch_radius_b")) except Exception: - native_status = 'native_partial' - if joint_type == 'Belt': + native_status = "native_partial" + if joint_type == "Belt": try: - joint.Distance = float(constraint_payload.get('pulley_radius_a')) - joint.Distance2 = float(constraint_payload.get('pulley_radius_b')) + joint.Distance = float(constraint_payload.get("pulley_radius_a")) + joint.Distance2 = float(constraint_payload.get("pulley_radius_b")) except Exception: - native_status = 'native_partial' - if joint_type == 'RackPinion': + native_status = "native_partial" + if joint_type == "RackPinion": try: - joint.Distance = float(constraint_payload.get('pitch_radius')) + joint.Distance = float(constraint_payload.get("pitch_radius")) except Exception: - native_status = 'native_partial' - angle_limit = constraint_payload.get('angle_limit') + native_status = "native_partial" + angle_limit = constraint_payload.get("angle_limit") if angle_limit: try: joint.EnableAngleMin = True joint.EnableAngleMax = True - joint.AngleMin = float(angle_limit.get('lower_value')) - joint.AngleMax = float(angle_limit.get('upper_value')) + joint.AngleMin = float(angle_limit.get("lower_value")) + joint.AngleMax = float(angle_limit.get("upper_value")) except Exception: - native_status = 'native_partial' - distance_limit = constraint_payload.get('distance_limit') + native_status = "native_partial" + distance_limit = constraint_payload.get("distance_limit") if distance_limit: try: joint.EnableLengthMin = True joint.EnableLengthMax = True - joint.LengthMin = float(distance_limit.get('lower_value')) - joint.LengthMax = float(distance_limit.get('upper_value')) + joint.LengthMin = float(distance_limit.get("lower_value")) + joint.LengthMax = float(distance_limit.get("upper_value")) except Exception: - native_status = 'native_partial' - _ensure_string_property(joint, 'SimpleCADConstraint') - _ensure_string_property(joint, 'SimpleCADConstraintTranslationStatus') - joint.SimpleCADConstraint = json.dumps(constraint_payload, ensure_ascii=True, sort_keys=True) + native_status = "native_partial" + _ensure_string_property(joint, "SimpleCADConstraint") + _ensure_string_property(joint, "SimpleCADConstraintTranslationStatus") + joint.SimpleCADConstraint = json.dumps( + constraint_payload, ensure_ascii=True, sort_keys=True + ) joint.SimpleCADConstraintTranslationStatus = native_status _set_visibility(joint, False) try: @@ -219,27 +292,33 @@ def _make_simplecad_joint(assembly_value, constraint_payload, object_name, label def _make_simplecad_grounded_joint(assembly_value, component_id): - assembly_container = assembly_value.get('container') + assembly_container = assembly_value.get("container") if assembly_container is None: - raise RuntimeError('Assembly value has no container for grounded joint translation') + raise RuntimeError( + "Assembly value has no container for grounded joint translation" + ) component_entry = _find_component_entry(assembly_value, component_id) - link = component_entry.get('link') + link = component_entry.get("link") if link is None: - raise RuntimeError(f'Missing component link for grounded component {component_id!r}') + raise RuntimeError( + f"Missing component link for grounded component {component_id!r}" + ) joint_group = _joint_group_for(assembly_container) - ground = joint_group.newObject('App::FeaturePython', 'GroundedJoint_' + str(component_id)) - ground.Label = 'GroundedJoint_' + str(component_id) - native_status = 'metadata_only' + ground = joint_group.newObject( + "App::FeaturePython", "GroundedJoint_" + str(component_id) + ) + ground.Label = "GroundedJoint_" + str(component_id) + native_status = "metadata_only" if JointObject is not None: JointObject.GroundedJoint(ground, link) - native_status = 'native_equivalent' + native_status = "native_equivalent" else: - _ensure_string_property(ground, 'ObjectToGround') - _ensure_string_property(ground, 'SimpleCADGroundedComponent') + _ensure_string_property(ground, "ObjectToGround") + _ensure_string_property(ground, "SimpleCADGroundedComponent") ground.SimpleCADGroundedComponent = str(component_id) _set_visibility(ground, False) try: - SIMPLECAD_JOINT_OBJECTS[str(ground.Name)] = 'Grounded' + SIMPLECAD_JOINT_OBJECTS[str(ground.Name)] = "Grounded" except Exception: pass return ground diff --git a/src/simplecadapi/translator/freecad_translator/runtime/curves.py b/src/simplecadapi/translator/freecad_translator/runtime/curves.py index 48e8447e..ff25c6a1 100644 --- a/src/simplecadapi/translator/freecad_translator/runtime/curves.py +++ b/src/simplecadapi/translator/freecad_translator/runtime/curves.py @@ -6,7 +6,9 @@ def _local_line_from_edge(obj, origin, x_axis, y_axis): projected_len = float((end - start).Length) source_len = float((_vec(end_3d) - _vec(start_3d)).Length) if source_len > 1e-9 and projected_len <= 1e-9: - raise RuntimeError('Projected non-zero edge collapsed to zero length; sketch frame is not coplanar with the source wire') + raise RuntimeError( + "Projected non-zero edge collapsed to zero length; sketch frame is not coplanar with the source wire" + ) return Part.LineSegment( start, end, @@ -43,10 +45,8 @@ def _periodic_axis_x(axis, kernel_x_axis=None, kernel_y_axis=None): Part.Circle(App.Vector(0.0, 0.0, 0.0), z_axis, 1.0).XAxis ) projected = x_axis - z_axis * float(x_axis.dot(z_axis)) - if float(getattr(projected, 'Length', 0.0)) <= 1e-12: - projected = Part.Circle( - App.Vector(0.0, 0.0, 0.0), z_axis, 1.0 - ).XAxis + if float(getattr(projected, "Length", 0.0)) <= 1e-12: + projected = Part.Circle(App.Vector(0.0, 0.0, 0.0), z_axis, 1.0).XAxis return _normalized_vec(projected) @@ -55,27 +55,27 @@ def _periodic_axis_rotation(axis, kernel_x_axis=None, kernel_y_axis=None): x_axis = _periodic_axis_x(z_axis, kernel_x_axis, kernel_y_axis) y_axis = _normalized_vec(z_axis.cross(x_axis)) x_axis = _normalized_vec(y_axis.cross(z_axis)) - return App.Rotation(x_axis, y_axis, z_axis, 'ZXY') + return App.Rotation(x_axis, y_axis, z_axis, "ZXY") def _kernel_circle_from_params(params, param_exprs): normal = ( - _resolve_vec3_param(params, param_exprs, 'normal') - if 'normal' in params + _resolve_vec3_param(params, param_exprs, "normal") + if "normal" in params else (0.0, 0.0, 1.0) ) circle = Part.Circle( - _vec(_resolve_vec3_param(params, param_exprs, 'center')), + _vec(_resolve_vec3_param(params, param_exprs, "center")), _vec(normal), - float(_resolve_param_value(params, param_exprs, 'radius')), + float(_resolve_param_value(params, param_exprs, "radius")), ) dynamic_normal = _contains_expr_refs( - param_exprs.get('normal') if isinstance(param_exprs, dict) else None + param_exprs.get("normal") if isinstance(param_exprs, dict) else None ) circle.XAxis = _periodic_axis_x( normal, - None if dynamic_normal else params.get('_kernel_x_axis'), - None if dynamic_normal else params.get('_kernel_y_axis'), + None if dynamic_normal else params.get("_kernel_x_axis"), + None if dynamic_normal else params.get("_kernel_y_axis"), ) return circle @@ -139,25 +139,31 @@ def _local_angle_arc( ea = float(end_angle) mid_angle = 0.5 * (sa + ea) start_local = _local_point_on_frame( - _vec_tuple(_angle_arc_world_point( - circle_center, radius, sa, normal, kernel_x_axis, kernel_y_axis - )), + _vec_tuple( + _angle_arc_world_point( + circle_center, radius, sa, normal, kernel_x_axis, kernel_y_axis + ) + ), origin, x_axis, y_axis, ) mid_local = _local_point_on_frame( - _vec_tuple(_angle_arc_world_point( - circle_center, radius, mid_angle, normal, kernel_x_axis, kernel_y_axis - )), + _vec_tuple( + _angle_arc_world_point( + circle_center, radius, mid_angle, normal, kernel_x_axis, kernel_y_axis + ) + ), origin, x_axis, y_axis, ) end_local = _local_point_on_frame( - _vec_tuple(_angle_arc_world_point( - circle_center, radius, ea, normal, kernel_x_axis, kernel_y_axis - )), + _vec_tuple( + _angle_arc_world_point( + circle_center, radius, ea, normal, kernel_x_axis, kernel_y_axis + ) + ), origin, x_axis, y_axis, @@ -166,38 +172,49 @@ def _local_angle_arc( def _bspline_curve_from_params(params, transform_point=None, context=None): - exact_params = params.get('_freecad_exact_bspline') + exact_params = params.get("_freecad_exact_bspline") source = exact_params or params def mapped_point(point): point3 = tuple(point) + (0.0,) if len(tuple(point)) == 2 else tuple(point) - world = _vec(point3) if exact_params is not None else _surface_context_point(point3, context) + world = ( + _vec(point3) + if exact_params is not None + else _surface_context_point(point3, context) + ) return transform_point(world) if transform_point is not None else world - poles = [mapped_point(point) for point in source.get('control_points') or []] - if not poles and source.get('points'): - poles = [mapped_point(point) for point in source.get('points') or []] + poles = [mapped_point(point) for point in source.get("control_points") or []] + if not poles and source.get("points"): + poles = [mapped_point(point) for point in source.get("points") or []] if len(poles) < 2: - raise RuntimeError('B-spline has fewer than two points') + raise RuntimeError("B-spline has fewer than two points") curve = Part.BSplineCurve() curve.interpolate( Points=poles, - PeriodicFlag=bool(source.get('periodic', False)), - Tolerance=float(source.get('tolerance', 1.0e-6)), + PeriodicFlag=bool(source.get("periodic", False)), + Tolerance=float(source.get("tolerance", 1.0e-6)), ) return curve if not poles: - raise RuntimeError('B-spline has no control points') - mults = tuple(int(value) for value in (source.get('multiplicities') or [])) - knots = tuple(float(value) for value in (source.get('knots') or [])) - degree = int(source.get('degree', 3)) - periodic = bool(source.get('periodic', False)) - weights = source.get('weights') + raise RuntimeError("B-spline has no control points") + mults = tuple(int(value) for value in (source.get("multiplicities") or [])) + knots = tuple(float(value) for value in (source.get("knots") or [])) + degree = int(source.get("degree", 3)) + periodic = bool(source.get("periodic", False)) + weights = source.get("weights") curve = Part.BSplineCurve() if weights is None: curve.buildFromPolesMultsKnots(poles, mults, knots, periodic, degree) else: - curve.buildFromPolesMultsKnots(poles, mults, knots, periodic, degree, tuple(float(value) for value in weights)) + curve.buildFromPolesMultsKnots( + poles, + mults, + knots, + periodic, + degree, + tuple(float(value) for value in weights), + ) return curve @@ -223,16 +240,16 @@ def _spine_object(node_id): return cached obj = GRAPH_NODES[node_id] try: - shape = getattr(obj, 'Shape', None) + shape = getattr(obj, "Shape", None) except Exception: shape = None if not _shape_is_null(shape): return obj meta = GRAPH_METADATA.get(node_id, {}) - if str(meta.get('op', '')) == 'make_wire_from_edges_rwire': - edge_ids = list(meta.get('inputs') or []) + if str(meta.get("op", "")) == "make_wire_from_edges_rwire": + edge_ids = list(meta.get("inputs") or []) if edge_ids: - fallback = doc.addObject('Part::Feature', f'make_spine_wire_{node_id}') + fallback = doc.addObject("Part::Feature", f"make_spine_wire_{node_id}") fallback.Shape = _wire_shape_from_edge_objects(edge_ids) _set_visibility(fallback, False) GRAPH_SPINE_OBJECTS[node_id] = fallback @@ -241,6 +258,6 @@ def _spine_object(node_id): def _build_face_from_source(source_obj, name): - face_obj = doc.addObject('Part::Face', name) + face_obj = doc.addObject("Part::Face", name) face_obj.Sources = [source_obj] return face_obj diff --git a/src/simplecadapi/translator/freecad_translator/runtime/expressions.py b/src/simplecadapi/translator/freecad_translator/runtime/expressions.py index 3396d9db..3800e4f6 100644 --- a/src/simplecadapi/translator/freecad_translator/runtime/expressions.py +++ b/src/simplecadapi/translator/freecad_translator/runtime/expressions.py @@ -1,9 +1,9 @@ -def _sanitize_expr_alias(expr_id, prefix='expr'): - alias = ''.join(ch if str(ch).isalnum() else '_' for ch in str(expr_id)).strip('_') +def _sanitize_expr_alias(expr_id, prefix="expr"): + alias = "".join(ch if str(ch).isalnum() else "_" for ch in str(expr_id)).strip("_") if not alias: alias = prefix if alias[0].isdigit(): - alias = prefix + '_' + alias + alias = prefix + "_" + alias return alias[:64] @@ -17,8 +17,8 @@ def _expr_alias(expr_id): def _resolve_expr_ref(expr_ref): if not isinstance(expr_ref, dict): return None - expr_id = expr_ref.get('expr_id') - if not expr_id or 'expr_sheet' not in globals() or expr_sheet is None: + expr_id = expr_ref.get("expr_id") + if not expr_id or "expr_sheet" not in globals() or expr_sheet is None: return None alias = _expr_alias(expr_id) try: @@ -36,12 +36,12 @@ def _resolve_expr_ref(expr_ref): def _expr_ref_to_freecad_expr(expr_ref): if not isinstance(expr_ref, dict): return None - expr_id = expr_ref.get('expr_id') - if not expr_id or 'expr_sheet' not in globals() or expr_sheet is None: + expr_id = expr_ref.get("expr_id") + if not expr_id or "expr_sheet" not in globals() or expr_sheet is None: return None if expr_id not in EXPR_CELL_BY_ID: return None - return f"<>.{_expr_alias(expr_id)}" + return f"<<{SIMPLECAD_EXPRESSION_SHEET}>>.{_expr_alias(expr_id)}" def _nested_expr_ref(expr_meta, *path): @@ -61,7 +61,7 @@ def _bind_expression(obj, prop_name, expr_ref): expr = expr_ref else: expr = _expr_ref_to_freecad_expr(expr_ref) - if not expr or not hasattr(obj, 'setExpression'): + if not expr or not hasattr(obj, "setExpression"): return False try: obj.setExpression(prop_name, expr) @@ -109,40 +109,40 @@ def _formula_scale(expr, coeff): if abs(coeff_value - 1.0) <= 1e-12: return expr if abs(coeff_value + 1.0) <= 1e-12: - return f'-({expr})' - return f'({expr}) * ({repr(coeff_value)})' + return f"-({expr})" + return f"({expr}) * ({repr(coeff_value)})" def _formula_mul(left, right): if left is None or right is None: return None - return f'({left}) * ({right})' + return f"({left}) * ({right})" def _formula_join_terms(*terms): filtered = [term for term in terms if term is not None] if not filtered: return None - return ' + '.join(filtered) + return " + ".join(filtered) def _formula_centered(expr, offset): offset_value = float(offset) if abs(offset_value) <= 1e-12: return expr - return f'({expr}) - ({repr(offset_value)})' + return f"({expr}) - ({repr(offset_value)})" def _formula_square(expr): - return f'pow(({expr}); 2)' + return f"pow(({expr}); 2)" def _formula_cos_radians(expr): - return f'cos(({expr}) * 180 / pi)' + return f"cos(({expr}) * 180 / pi)" def _formula_sin_radians(expr): - return f'sin(({expr}) * 180 / pi)' + return f"sin(({expr}) * 180 / pi)" def _local_point_component_formula(params, param_exprs, point_path, origin, axis_vec): @@ -158,8 +158,8 @@ def _local_point_component_formula(params, param_exprs, point_path, origin, axis if term is not None: terms.append(term) if not terms: - return '0.0' - return ' + '.join(terms) + return "0.0" + return " + ".join(terms) def _formula_value(params, param_exprs, key, index): @@ -167,12 +167,12 @@ def _formula_value(params, param_exprs, key, index): def _line_length_formula(params, param_exprs): - sx = _formula_value(params, param_exprs, 'start', 0) - sy = _formula_value(params, param_exprs, 'start', 1) - sz = _formula_value(params, param_exprs, 'start', 2) - ex = _formula_value(params, param_exprs, 'end', 0) - ey = _formula_value(params, param_exprs, 'end', 1) - ez = _formula_value(params, param_exprs, 'end', 2) + sx = _formula_value(params, param_exprs, "start", 0) + sy = _formula_value(params, param_exprs, "start", 1) + sz = _formula_value(params, param_exprs, "start", 2) + ex = _formula_value(params, param_exprs, "end", 0) + ey = _formula_value(params, param_exprs, "end", 1) + ez = _formula_value(params, param_exprs, "end", 2) terms = [] for a, b in ((ex, sx), (ey, sy), (ez, sz)): if a is None or b is None: @@ -192,7 +192,7 @@ def _build_line_sketch_bindings(param_exprs, geom_index=0, use_local_line=False) if axis_expr is None: continue prop = f"Geometry[{int(geom_index)}].{'StartPoint' if point_name == 'start' else 'EndPoint'}.{axis_name}" - if use_local_line and axis_name in {'x', 'y', 'z'}: + if use_local_line and axis_name in {"x", "y", "z"}: continue bindings.append((prop, axis_expr)) return bindings @@ -201,39 +201,54 @@ def _build_line_sketch_bindings(param_exprs, geom_index=0, use_local_line=False) def _build_circle_sketch_bindings(param_exprs, geom_index=0, local=False): bindings = [] for axis_name, axis_index in (("x", 0), ("y", 1), ("z", 2)): - axis_expr = _nested_expr_ref(param_exprs, 'center', axis_index) + axis_expr = _nested_expr_ref(param_exprs, "center", axis_index) if axis_expr is None: continue - if local and axis_name == 'z': + if local and axis_name == "z": continue bindings.append((f"Geometry[{int(geom_index)}].Center.{axis_name}", axis_expr)) - radius_expr = _nested_expr_ref(param_exprs, 'radius') + radius_expr = _nested_expr_ref(param_exprs, "radius") if radius_expr is not None: bindings.append((f"Geometry[{int(geom_index)}].Radius", radius_expr)) return bindings -def _build_local_point_sketch_bindings(params, param_exprs, point_path, prop_prefix, geom_index=0, origin=None, x_axis=None, y_axis=None): +def _build_local_point_sketch_bindings( + params, + param_exprs, + point_path, + prop_prefix, + geom_index=0, + origin=None, + x_axis=None, + y_axis=None, +): bindings = [] if origin is None or x_axis is None or y_axis is None: return bindings - x_expr = _local_point_component_formula(params, param_exprs, point_path, origin, x_axis) + x_expr = _local_point_component_formula( + params, param_exprs, point_path, origin, x_axis + ) if x_expr is not None: bindings.append((f"Geometry[{int(geom_index)}].{prop_prefix}.x", x_expr)) - y_expr = _local_point_component_formula(params, param_exprs, point_path, origin, y_axis) + y_expr = _local_point_component_formula( + params, param_exprs, point_path, origin, y_axis + ) if y_expr is not None: bindings.append((f"Geometry[{int(geom_index)}].{prop_prefix}.y", y_expr)) return bindings -def _build_local_line_sketch_bindings(params, param_exprs, geom_index=0, origin=None, x_axis=None, y_axis=None): +def _build_local_line_sketch_bindings( + params, param_exprs, geom_index=0, origin=None, x_axis=None, y_axis=None +): bindings = [] bindings.extend( _build_local_point_sketch_bindings( params, param_exprs, - 'start', - 'StartPoint', + "start", + "StartPoint", geom_index=geom_index, origin=origin, x_axis=x_axis, @@ -244,8 +259,8 @@ def _build_local_line_sketch_bindings(params, param_exprs, geom_index=0, origin= _build_local_point_sketch_bindings( params, param_exprs, - 'end', - 'EndPoint', + "end", + "EndPoint", geom_index=geom_index, origin=origin, x_axis=x_axis, @@ -255,21 +270,23 @@ def _build_local_line_sketch_bindings(params, param_exprs, geom_index=0, origin= return bindings -def _build_local_circle_sketch_bindings(params, param_exprs, geom_index=0, origin=None, x_axis=None, y_axis=None): +def _build_local_circle_sketch_bindings( + params, param_exprs, geom_index=0, origin=None, x_axis=None, y_axis=None +): bindings = [] bindings.extend( _build_local_point_sketch_bindings( params, param_exprs, - 'center', - 'Center', + "center", + "Center", geom_index=geom_index, origin=origin, x_axis=x_axis, y_axis=y_axis, ) ) - radius_expr = _nested_expr_ref(param_exprs, 'radius') + radius_expr = _nested_expr_ref(param_exprs, "radius") if radius_expr is not None: bindings.append((f"Geometry[{int(geom_index)}].Radius", radius_expr)) return bindings @@ -278,35 +295,43 @@ def _build_local_circle_sketch_bindings(params, param_exprs, geom_index=0, origi def _angle_arc_local_point_formula(params, param_exprs, angle_key, origin, sketch_axis): if origin is None or sketch_axis is None: return None - center_component = _local_point_component_formula(params, param_exprs, 'center', origin, sketch_axis) - radius_expr = _formula_nested_value(params, param_exprs, 'radius') + center_component = _local_point_component_formula( + params, param_exprs, "center", origin, sketch_axis + ) + radius_expr = _formula_nested_value(params, param_exprs, "radius") angle_expr = _formula_nested_value(params, param_exprs, angle_key) if center_component is None or radius_expr is None or angle_expr is None: return None - normal = params.get('normal', (0.0, 0.0, 1.0)) + normal = params.get("normal", (0.0, 0.0, 1.0)) dynamic_normal = _contains_expr_refs( - param_exprs.get('normal') if isinstance(param_exprs, dict) else None + param_exprs.get("normal") if isinstance(param_exprs, dict) else None ) try: arc_x, arc_y = _angle_arc_axes( normal, - None if dynamic_normal else params.get('_kernel_x_axis'), - None if dynamic_normal else params.get('_kernel_y_axis'), + None if dynamic_normal else params.get("_kernel_x_axis"), + None if dynamic_normal else params.get("_kernel_y_axis"), ) except Exception: return None cos_term = _formula_scale( _formula_mul(radius_expr, _formula_cos_radians(angle_expr)), - float(arc_x.x * sketch_axis.x + arc_x.y * sketch_axis.y + arc_x.z * sketch_axis.z), + float( + arc_x.x * sketch_axis.x + arc_x.y * sketch_axis.y + arc_x.z * sketch_axis.z + ), ) sin_term = _formula_scale( _formula_mul(radius_expr, _formula_sin_radians(angle_expr)), - float(arc_y.x * sketch_axis.x + arc_y.y * sketch_axis.y + arc_y.z * sketch_axis.z), + float( + arc_y.x * sketch_axis.x + arc_y.y * sketch_axis.y + arc_y.z * sketch_axis.z + ), ) return _formula_join_terms(center_component, cos_term, sin_term) -def _build_local_angle_arc_sketch_bindings(params, param_exprs, geom_index=0, origin=None, x_axis=None, y_axis=None): +def _build_local_angle_arc_sketch_bindings( + params, param_exprs, geom_index=0, origin=None, x_axis=None, y_axis=None +): bindings = [] bindings.extend( _build_local_circle_sketch_bindings( @@ -318,10 +343,18 @@ def _build_local_angle_arc_sketch_bindings(params, param_exprs, geom_index=0, or y_axis=y_axis, ) ) - start_x = _angle_arc_local_point_formula(params, param_exprs, 'start_angle', origin, x_axis) - start_y = _angle_arc_local_point_formula(params, param_exprs, 'start_angle', origin, y_axis) - end_x = _angle_arc_local_point_formula(params, param_exprs, 'end_angle', origin, x_axis) - end_y = _angle_arc_local_point_formula(params, param_exprs, 'end_angle', origin, y_axis) + start_x = _angle_arc_local_point_formula( + params, param_exprs, "start_angle", origin, x_axis + ) + start_y = _angle_arc_local_point_formula( + params, param_exprs, "start_angle", origin, y_axis + ) + end_x = _angle_arc_local_point_formula( + params, param_exprs, "end_angle", origin, x_axis + ) + end_y = _angle_arc_local_point_formula( + params, param_exprs, "end_angle", origin, y_axis + ) if start_x is not None: bindings.append((f"Geometry[{int(geom_index)}].StartPoint.x", start_x)) if start_y is not None: @@ -333,65 +366,85 @@ def _build_local_angle_arc_sketch_bindings(params, param_exprs, geom_index=0, or return bindings -def _three_point_arc_local_coordinate_formulas(params, param_exprs, origin, x_axis, y_axis): +def _three_point_arc_local_coordinate_formulas( + params, param_exprs, origin, x_axis, y_axis +): return { - 'sx': _local_point_component_formula(params, param_exprs, 'start', origin, x_axis), - 'sy': _local_point_component_formula(params, param_exprs, 'start', origin, y_axis), - 'mx': _local_point_component_formula(params, param_exprs, 'middle', origin, x_axis), - 'my': _local_point_component_formula(params, param_exprs, 'middle', origin, y_axis), - 'ex': _local_point_component_formula(params, param_exprs, 'end', origin, x_axis), - 'ey': _local_point_component_formula(params, param_exprs, 'end', origin, y_axis), + "sx": _local_point_component_formula( + params, param_exprs, "start", origin, x_axis + ), + "sy": _local_point_component_formula( + params, param_exprs, "start", origin, y_axis + ), + "mx": _local_point_component_formula( + params, param_exprs, "middle", origin, x_axis + ), + "my": _local_point_component_formula( + params, param_exprs, "middle", origin, y_axis + ), + "ex": _local_point_component_formula( + params, param_exprs, "end", origin, x_axis + ), + "ey": _local_point_component_formula( + params, param_exprs, "end", origin, y_axis + ), } -def _three_point_arc_center_formula(params, param_exprs, origin, x_axis, y_axis, axis_name): - coords = _three_point_arc_local_coordinate_formulas(params, param_exprs, origin, x_axis, y_axis) +def _three_point_arc_center_formula( + params, param_exprs, origin, x_axis, y_axis, axis_name +): + coords = _three_point_arc_local_coordinate_formulas( + params, param_exprs, origin, x_axis, y_axis + ) if any(value is None for value in coords.values()): return None - sx = coords['sx'] - sy = coords['sy'] - mx = coords['mx'] - my = coords['my'] - ex = coords['ex'] - ey = coords['ey'] - denom = ( - f"2 * ((({sx}) * (({my}) - ({ey}))) + (({mx}) * (({ey}) - ({sy}))) + (({ex}) * (({sy}) - ({my}))))" - ) + sx = coords["sx"] + sy = coords["sy"] + mx = coords["mx"] + my = coords["my"] + ex = coords["ex"] + ey = coords["ey"] + denom = f"2 * ((({sx}) * (({my}) - ({ey}))) + (({mx}) * (({ey}) - ({sy}))) + (({ex}) * (({sy}) - ({my}))))" start_sq = f"({_formula_square(sx)} + {_formula_square(sy)})" mid_sq = f"({_formula_square(mx)} + {_formula_square(my)})" end_sq = f"({_formula_square(ex)} + {_formula_square(ey)})" - if axis_name == 'x': - numer = ( - f"(({start_sq}) * (({my}) - ({ey}))) + (({mid_sq}) * (({ey}) - ({sy}))) + (({end_sq}) * (({sy}) - ({my})))" - ) - elif axis_name == 'y': - numer = ( - f"(({start_sq}) * (({ex}) - ({mx}))) + (({mid_sq}) * (({sx}) - ({ex}))) + (({end_sq}) * (({mx}) - ({sx})))" - ) + if axis_name == "x": + numer = f"(({start_sq}) * (({my}) - ({ey}))) + (({mid_sq}) * (({ey}) - ({sy}))) + (({end_sq}) * (({sy}) - ({my})))" + elif axis_name == "y": + numer = f"(({start_sq}) * (({ex}) - ({mx}))) + (({mid_sq}) * (({sx}) - ({ex}))) + (({end_sq}) * (({mx}) - ({sx})))" else: return None return f"(({numer})) / ({denom})" def _three_point_arc_radius_formula(params, param_exprs, origin, x_axis, y_axis): - coords = _three_point_arc_local_coordinate_formulas(params, param_exprs, origin, x_axis, y_axis) - sx = coords.get('sx') - sy = coords.get('sy') - cx = _three_point_arc_center_formula(params, param_exprs, origin, x_axis, y_axis, 'x') - cy = _three_point_arc_center_formula(params, param_exprs, origin, x_axis, y_axis, 'y') + coords = _three_point_arc_local_coordinate_formulas( + params, param_exprs, origin, x_axis, y_axis + ) + sx = coords.get("sx") + sy = coords.get("sy") + cx = _three_point_arc_center_formula( + params, param_exprs, origin, x_axis, y_axis, "x" + ) + cy = _three_point_arc_center_formula( + params, param_exprs, origin, x_axis, y_axis, "y" + ) if sx is None or sy is None or cx is None or cy is None: return None return f"sqrt({_formula_square(f'({cx}) - ({sx})')} + {_formula_square(f'({cy}) - ({sy})')})" -def _build_local_three_point_arc_sketch_bindings(params, param_exprs, geom_index=0, origin=None, x_axis=None, y_axis=None): +def _build_local_three_point_arc_sketch_bindings( + params, param_exprs, geom_index=0, origin=None, x_axis=None, y_axis=None +): bindings = [] bindings.extend( _build_local_point_sketch_bindings( params, param_exprs, - 'start', - 'StartPoint', + "start", + "StartPoint", geom_index=geom_index, origin=origin, x_axis=x_axis, @@ -402,8 +455,8 @@ def _build_local_three_point_arc_sketch_bindings(params, param_exprs, geom_index _build_local_point_sketch_bindings( params, param_exprs, - 'end', - 'EndPoint', + "end", + "EndPoint", geom_index=geom_index, origin=origin, x_axis=x_axis, @@ -412,9 +465,15 @@ def _build_local_three_point_arc_sketch_bindings(params, param_exprs, geom_index ) if origin is None or x_axis is None or y_axis is None: return bindings - center_x = _three_point_arc_center_formula(params, param_exprs, origin, x_axis, y_axis, 'x') - center_y = _three_point_arc_center_formula(params, param_exprs, origin, x_axis, y_axis, 'y') - radius = _three_point_arc_radius_formula(params, param_exprs, origin, x_axis, y_axis) + center_x = _three_point_arc_center_formula( + params, param_exprs, origin, x_axis, y_axis, "x" + ) + center_y = _three_point_arc_center_formula( + params, param_exprs, origin, x_axis, y_axis, "y" + ) + radius = _three_point_arc_radius_formula( + params, param_exprs, origin, x_axis, y_axis + ) if center_x is not None: bindings.append((f"Geometry[{int(geom_index)}].Center.x", center_x)) if center_y is not None: @@ -428,18 +487,26 @@ def _build_arc_sketch_bindings(param_exprs, geom_index=0, *, prefer_local=False) bindings = [] if prefer_local: for axis_name, axis_index in (("x", 0), ("y", 1)): - start_expr = _nested_expr_ref(param_exprs, 'start', axis_index) + start_expr = _nested_expr_ref(param_exprs, "start", axis_index) if start_expr is not None: - bindings.append((f"Geometry[{int(geom_index)}].StartPoint.{axis_name}", start_expr)) - end_expr = _nested_expr_ref(param_exprs, 'end', axis_index) + bindings.append( + (f"Geometry[{int(geom_index)}].StartPoint.{axis_name}", start_expr) + ) + end_expr = _nested_expr_ref(param_exprs, "end", axis_index) if end_expr is not None: - bindings.append((f"Geometry[{int(geom_index)}].EndPoint.{axis_name}", end_expr)) + bindings.append( + (f"Geometry[{int(geom_index)}].EndPoint.{axis_name}", end_expr) + ) return bindings - bindings.extend(_build_circle_sketch_bindings(param_exprs, geom_index=geom_index, local=False)) - start_angle_expr = _nested_expr_ref(param_exprs, 'start_angle') + bindings.extend( + _build_circle_sketch_bindings(param_exprs, geom_index=geom_index, local=False) + ) + start_angle_expr = _nested_expr_ref(param_exprs, "start_angle") if start_angle_expr is not None: - bindings.append((f"Geometry[{int(geom_index)}].FirstParameter", start_angle_expr)) - end_angle_expr = _nested_expr_ref(param_exprs, 'end_angle') + bindings.append( + (f"Geometry[{int(geom_index)}].FirstParameter", start_angle_expr) + ) + end_angle_expr = _nested_expr_ref(param_exprs, "end_angle") if end_angle_expr is not None: bindings.append((f"Geometry[{int(geom_index)}].LastParameter", end_angle_expr)) return bindings @@ -448,10 +515,10 @@ def _build_arc_sketch_bindings(param_exprs, geom_index=0, *, prefer_local=False) def _detail_edge_binding_expr(param_exprs, key): edge_indices = [] radius_expr = None - if key == 'radius': - radius_expr = _nested_expr_ref(param_exprs, 'radius') - elif key == 'distance': - radius_expr = _nested_expr_ref(param_exprs, 'distance') + if key == "radius": + radius_expr = _nested_expr_ref(param_exprs, "radius") + elif key == "distance": + radius_expr = _nested_expr_ref(param_exprs, "distance") if radius_expr is None: return None return radius_expr @@ -462,13 +529,13 @@ def _apply_detail_feature_bindings(obj, param_exprs, key): if expr_ref is None: return False selected = [] - if key == 'radius': - selected = list(getattr(obj, 'Edges', []) or []) + if key == "radius": + selected = list(getattr(obj, "Edges", []) or []) else: - selected = list(getattr(obj, 'Edges', []) or []) + selected = list(getattr(obj, "Edges", []) or []) applied = False for idx in range(len(selected)): - applied = _bind_expression(obj, f'Edges[{idx}]', expr_ref) or applied + applied = _bind_expression(obj, f"Edges[{idx}]", expr_ref) or applied return applied @@ -487,7 +554,11 @@ def _resolve_nested_param_value(params, param_exprs, *path): value = value[key] if isinstance(expr_meta, dict) and key in expr_meta: expr_meta = expr_meta[key] - elif isinstance(expr_meta, list) and isinstance(key, int) and 0 <= key < len(expr_meta): + elif ( + isinstance(expr_meta, list) + and isinstance(key, int) + and 0 <= key < len(expr_meta) + ): expr_meta = expr_meta[key] else: expr_meta = None diff --git a/src/simplecadapi/translator/freecad_translator/runtime/geometry.py b/src/simplecadapi/translator/freecad_translator/runtime/geometry.py index 72e1511a..3cf7907f 100644 --- a/src/simplecadapi/translator/freecad_translator/runtime/geometry.py +++ b/src/simplecadapi/translator/freecad_translator/runtime/geometry.py @@ -3,22 +3,31 @@ def _vec(v): def _placement_from_axes_payload(payload): - origin = payload.get('origin', (0.0, 0.0, 0.0)) - x_axis = payload.get('x_axis', (1.0, 0.0, 0.0)) - y_axis = payload.get('y_axis', (0.0, 1.0, 0.0)) - z_axis = payload.get('z_axis') + origin = payload.get("origin", (0.0, 0.0, 0.0)) + x_axis = payload.get("x_axis", (1.0, 0.0, 0.0)) + y_axis = payload.get("y_axis", (0.0, 1.0, 0.0)) + z_axis = payload.get("z_axis") if z_axis is None: x = _vec(x_axis) y = _vec(y_axis) z = x.cross(y) - length = float(getattr(z, 'Length', 0.0)) + length = float(getattr(z, "Length", 0.0)) if length == 0.0: - raise RuntimeError('Placement axes do not form a frame') + raise RuntimeError("Placement axes do not form a frame") z_axis = (z.x / length, z.y / length, z.z / length) matrix = App.Matrix() - matrix.A11 = float(x_axis[0]); matrix.A12 = float(y_axis[0]); matrix.A13 = float(z_axis[0]); matrix.A14 = float(origin[0]) - matrix.A21 = float(x_axis[1]); matrix.A22 = float(y_axis[1]); matrix.A23 = float(z_axis[1]); matrix.A24 = float(origin[1]) - matrix.A31 = float(x_axis[2]); matrix.A32 = float(y_axis[2]); matrix.A33 = float(z_axis[2]); matrix.A34 = float(origin[2]) + matrix.A11 = float(x_axis[0]) + matrix.A12 = float(y_axis[0]) + matrix.A13 = float(z_axis[0]) + matrix.A14 = float(origin[0]) + matrix.A21 = float(x_axis[1]) + matrix.A22 = float(y_axis[1]) + matrix.A23 = float(z_axis[1]) + matrix.A24 = float(origin[1]) + matrix.A31 = float(x_axis[2]) + matrix.A32 = float(y_axis[2]) + matrix.A33 = float(z_axis[2]) + matrix.A34 = float(origin[2]) return App.Placement(matrix) @@ -65,21 +74,23 @@ def _orthogonal_axis3(z_axis): def _placement_from_geometry_ref_payload(geometry_ref): geometry_ref = geometry_ref or {} - selector = geometry_ref.get('geo_selector') or {} - kind = str(geometry_ref.get('kind') or selector.get('kind') or '').lower() - flip = bool(geometry_ref.get('flip', False)) - if kind == 'face': - origin = _connector_tuple3(selector.get('center'), (0.0, 0.0, 0.0)) - z_axis = _unit3(selector.get('normal'), (0.0, 0.0, 1.0)) + selector = geometry_ref.get("geo_selector") or {} + kind = str(geometry_ref.get("kind") or selector.get("kind") or "").lower() + flip = bool(geometry_ref.get("flip", False)) + if kind == "face": + origin = _connector_tuple3(selector.get("center"), (0.0, 0.0, 0.0)) + z_axis = _unit3(selector.get("normal"), (0.0, 0.0, 1.0)) if flip: z_axis = (-z_axis[0], -z_axis[1], -z_axis[2]) x_axis = _orthogonal_axis3(z_axis) y_axis = _unit3(_cross3(z_axis, x_axis), (0.0, 1.0, 0.0)) - return _placement_from_axes_payload({'origin': origin, 'x_axis': x_axis, 'y_axis': y_axis}) - if kind == 'edge': - origin = _connector_tuple3(selector.get('center'), (0.0, 0.0, 0.0)) - start = selector.get('start') - end = selector.get('end') + return _placement_from_axes_payload( + {"origin": origin, "x_axis": x_axis, "y_axis": y_axis} + ) + if kind == "edge": + origin = _connector_tuple3(selector.get("center"), (0.0, 0.0, 0.0)) + start = selector.get("start") + end = selector.get("end") if isinstance(start, (list, tuple)) and isinstance(end, (list, tuple)): s = _connector_tuple3(start) e = _connector_tuple3(end) @@ -91,137 +102,175 @@ def _placement_from_geometry_ref_payload(geometry_ref): z_axis = (-z_axis[0], -z_axis[1], -z_axis[2]) x_axis = _orthogonal_axis3(z_axis) y_axis = _unit3(_cross3(z_axis, x_axis), (0.0, 1.0, 0.0)) - return _placement_from_axes_payload({'origin': origin, 'x_axis': x_axis, 'y_axis': y_axis}) - if kind == 'vertex': - return _placement_from_axes_payload({'origin': _connector_tuple3(selector.get('coordinates'), (0.0, 0.0, 0.0))}) - return _placement_from_axes_payload({'origin': _connector_tuple3(selector.get('center'), (0.0, 0.0, 0.0))}) + return _placement_from_axes_payload( + {"origin": origin, "x_axis": x_axis, "y_axis": y_axis} + ) + if kind == "vertex": + return _placement_from_axes_payload( + {"origin": _connector_tuple3(selector.get("coordinates"), (0.0, 0.0, 0.0))} + ) + return _placement_from_axes_payload( + {"origin": _connector_tuple3(selector.get("center"), (0.0, 0.0, 0.0))} + ) def _connector_anchor_payload(connector_payload): - anchor = connector_payload.get('anchor') if isinstance(connector_payload, dict) else None + anchor = ( + connector_payload.get("anchor") if isinstance(connector_payload, dict) else None + ) if isinstance(anchor, dict): return anchor - geometry_ref = connector_payload.get('geometry_ref') if isinstance(connector_payload, dict) else None + geometry_ref = ( + connector_payload.get("geometry_ref") + if isinstance(connector_payload, dict) + else None + ) if isinstance(geometry_ref, dict): - return {'anchor_kind': 'geometry', 'geometry_ref': geometry_ref} - return {'anchor_kind': 'placement', 'placement': {'origin': (0.0, 0.0, 0.0)}} + return {"anchor_kind": "geometry", "geometry_ref": geometry_ref} + return {"anchor_kind": "placement", "placement": {"origin": (0.0, 0.0, 0.0)}} def _connector_payload_for_item(item, connector_id): - for connector in list((item or {}).get('connectors', []) or []): - if str(connector.get('connector_id')) == str(connector_id): + for connector in list((item or {}).get("connectors", []) or []): + if str(connector.get("connector_id")) == str(connector_id): return connector - raise RuntimeError(f'Missing connector {connector_id!r} on product item') + raise RuntimeError(f"Missing connector {connector_id!r} on product item") def _connector_metadata_payload(connector_payload): payload = dict(connector_payload or {}) - payload.pop('datum', None) - payload.pop('placement', None) + payload.pop("datum", None) + payload.pop("placement", None) return payload def _connector_local_placement(item, connector_payload, seen=None): seen = set(seen or set()) - connector_id = str((connector_payload or {}).get('connector_id', '')) + connector_id = str((connector_payload or {}).get("connector_id", "")) key = (id(item), connector_id) if key in seen: - raise RuntimeError(f'forwarded connector cycle detected at {connector_id!r}') + raise RuntimeError(f"forwarded connector cycle detected at {connector_id!r}") seen.add(key) anchor = _connector_anchor_payload(connector_payload or {}) - kind = str(anchor.get('anchor_kind') or '').lower() - if kind == 'geometry': - return _placement_from_geometry_ref_payload(anchor.get('geometry_ref') or (connector_payload or {}).get('geometry_ref')) - if kind == 'placement': - return _placement_from_axes_payload(anchor.get('placement') or {}) - if kind == 'forwarded': - source_component = _find_component_entry(item or {}, anchor.get('source_component_id')) - source_item = source_component.get('item') or {} - source_connector = _connector_payload_for_item(source_item, anchor.get('source_connector_id')) - source_placement = _placement_from_axes_payload(source_component.get('placement') or {}) - result = source_placement.multiply(_connector_local_placement(source_item, source_connector, seen)) - if isinstance(anchor.get('offset'), dict): - result = result.multiply(_placement_from_axes_payload(anchor.get('offset'))) + kind = str(anchor.get("anchor_kind") or "").lower() + if kind == "geometry": + return _placement_from_geometry_ref_payload( + anchor.get("geometry_ref") or (connector_payload or {}).get("geometry_ref") + ) + if kind == "placement": + return _placement_from_axes_payload(anchor.get("placement") or {}) + if kind == "forwarded": + source_component = _find_component_entry( + item or {}, anchor.get("source_component_id") + ) + source_item = source_component.get("item") or {} + source_connector = _connector_payload_for_item( + source_item, anchor.get("source_connector_id") + ) + source_placement = _placement_from_axes_payload( + source_component.get("placement") or {} + ) + result = source_placement.multiply( + _connector_local_placement(source_item, source_connector, seen) + ) + if isinstance(anchor.get("offset"), dict): + result = result.multiply(_placement_from_axes_payload(anchor.get("offset"))) return result return App.Placement() def _make_connector_datum(container, connector_payload, placement): - connector_id = str((connector_payload or {}).get('connector_id') or 'connector') + connector_id = str((connector_payload or {}).get("connector_id") or "connector") metadata_payload = _connector_metadata_payload(connector_payload) - object_name = 'connector_' + _simplecad_slug(connector_id, prefix='connector') + object_name = "connector_" + _simplecad_slug(connector_id, prefix="connector") datum = None try: - datum = container.newObject('PartDesign::CoordinateSystem', object_name) + datum = container.newObject("PartDesign::CoordinateSystem", object_name) except Exception: - datum = container.newObject('App::FeaturePython', object_name) - datum.Label = 'connector.' + connector_id + datum = container.newObject("App::FeaturePython", object_name) + datum.Label = "connector." + connector_id _ensure_placement_property(datum) datum.Placement = placement - _ensure_string_property(datum, 'SimpleCADConnectorId') - _ensure_string_property(datum, 'SimpleCADConnector') + _ensure_string_property(datum, "SimpleCADConnectorId") + _ensure_string_property(datum, "SimpleCADConnector") datum.SimpleCADConnectorId = connector_id - datum.SimpleCADConnector = json.dumps(metadata_payload, ensure_ascii=True, sort_keys=True) + datum.SimpleCADConnector = json.dumps( + metadata_payload, ensure_ascii=True, sort_keys=True + ) _set_visibility(datum, True) return datum def _materialize_product_connector_datums(product_value): - container = (product_value or {}).get('container') + container = (product_value or {}).get("container") if container is None: return product_value resolved = [] - for connector in list((product_value or {}).get('connectors', []) or []): + for connector in list((product_value or {}).get("connectors", []) or []): connector = dict(connector) try: placement = _connector_local_placement(product_value, connector) - connector['datum'] = _make_connector_datum(container, connector, placement) - connector['placement'] = placement + connector["datum"] = _make_connector_datum(container, connector, placement) + connector["placement"] = placement except Exception: pass resolved.append(connector) - product_value['connectors'] = resolved + product_value["connectors"] = resolved return product_value def _component_connector_proxy(assembly_value, component_entry, connector_payload): - assembly_container = assembly_value.get('container') + assembly_container = assembly_value.get("container") if assembly_container is None: - raise RuntimeError('Assembly value has no container for connector proxy') - link = component_entry.get('link') - link_placement = getattr(link, 'Placement', App.Placement()) if link is not None else _placement_from_axes_payload(component_entry.get('placement') or {}) - local_placement = _connector_local_placement(component_entry.get('item') or {}, connector_payload) + raise RuntimeError("Assembly value has no container for connector proxy") + link = component_entry.get("link") + link_placement = ( + getattr(link, "Placement", App.Placement()) + if link is not None + else _placement_from_axes_payload(component_entry.get("placement") or {}) + ) + local_placement = _connector_local_placement( + component_entry.get("item") or {}, connector_payload + ) proxy_payload = dict(connector_payload or {}) - proxy_payload['connector_id'] = str(component_entry.get('component_id')) + '.' + str(proxy_payload.get('connector_id', 'connector')) - return _make_connector_datum(assembly_container, proxy_payload, link_placement.multiply(local_placement)) + proxy_payload["connector_id"] = ( + str(component_entry.get("component_id")) + + "." + + str(proxy_payload.get("connector_id", "connector")) + ) + return _make_connector_datum( + assembly_container, proxy_payload, link_placement.multiply(local_placement) + ) def _shape_from_component_link(link): - source = getattr(link, 'LinkedObject', None) - if source is None or not hasattr(source, 'Shape'): - raise RuntimeError('Component link has no shape-bearing linked object') + source = getattr(link, "LinkedObject", None) + if source is None or not hasattr(source, "Shape"): + raise RuntimeError("Component link has no shape-bearing linked object") shape = source.Shape.copy() try: shape.Placement = link.Placement.multiply(shape.Placement) except Exception: pass return shape + + def _materialize_boolean_operand(obj, name): - if getattr(obj, 'TypeId', '') != 'App::Link': + if getattr(obj, "TypeId", "") != "App::Link": return obj shape = _shape_from_component_link(obj) - wrapper = doc.addObject('Part::Feature', name) + wrapper = doc.addObject("Part::Feature", name) wrapper.Label = str(name) wrapper.Shape = shape - _ensure_string_property(wrapper, 'SimpleCADMaterializedFromLink') - wrapper.SimpleCADMaterializedFromLink = str(getattr(obj, 'Name', '')) + _ensure_string_property(wrapper, "SimpleCADMaterializedFromLink") + wrapper.SimpleCADMaterializedFromLink = str(getattr(obj, "Name", "")) _set_visibility(wrapper, False) return wrapper def _placed_shape_from_body(body, placement): - if body is None or not hasattr(body, 'Shape'): - raise RuntimeError('Part product value has no shape-bearing body') + if body is None or not hasattr(body, "Shape"): + raise RuntimeError("Part product value has no shape-bearing body") shape = body.Shape.copy() try: shape.Placement = placement.multiply(shape.Placement) @@ -232,22 +281,30 @@ def _placed_shape_from_body(body, placement): def _shapes_from_product_value(value, placement=None): placement = placement or App.Placement() - if value.get('kind') == 'part': - return [_placed_shape_from_body(value.get('body'), placement)] - if value.get('kind') == 'assembly': + if value.get("kind") == "part": + return [_placed_shape_from_body(value.get("body"), placement)] + if value.get("kind") == "assembly": shapes = [] - for component in value.get('components', []): - component_placement = component.get('link').Placement if component.get('link') is not None else _placement_from_axes_payload(component.get('placement') or {}) - shapes.extend(_shapes_from_product_value(component.get('item'), placement.multiply(component_placement))) + for component in value.get("components", []): + component_placement = ( + component.get("link").Placement + if component.get("link") is not None + else _placement_from_axes_payload(component.get("placement") or {}) + ) + shapes.extend( + _shapes_from_product_value( + component.get("item"), placement.multiply(component_placement) + ) + ) return shapes - raise RuntimeError('Unsupported product value for shape projection') + raise RuntimeError("Unsupported product value for shape projection") def _normalized_vec(v): vec = _vec(v) - length = float(getattr(vec, 'Length', 0.0)) + length = float(getattr(vec, "Length", 0.0)) if length == 0.0: - raise RuntimeError('Expected a non-zero vector') + raise RuntimeError("Expected a non-zero vector") return App.Vector(vec.x / length, vec.y / length, vec.z / length) @@ -258,20 +315,20 @@ def _scaled_direction(direction, distance): def _twisted_sweep_loft_shape(profile_obj, *, axis, origin, distance, twist_angle): - operation = 'make_twisted_sweep_rsolid' + operation = "make_twisted_sweep_rsolid" face = _face_shape_from_wire_shape(profile_obj, operation) - wires = list(getattr(face, 'Wires', []) or []) + wires = list(getattr(face, "Wires", []) or []) if len(wires) != 1: - raise RuntimeError(f'{operation} emulation requires a face with one outer wire') + raise RuntimeError(f"{operation} emulation requires a face with one outer wire") axis_vec = _normalized_vec(axis) origin_vec = _vec(origin) distance_value = float(distance) twist_value = float(twist_angle) if not math.isfinite(distance_value) or distance_value <= 0.0: - raise RuntimeError(f'{operation} distance must be finite and positive') + raise RuntimeError(f"{operation} distance must be finite and positive") if not math.isfinite(twist_value): - raise RuntimeError(f'{operation} twist angle must be finite') + raise RuntimeError(f"{operation} twist angle must be finite") section_count = max(3, int(math.ceil(abs(twist_value) / 30.0)) + 1) sections = [] @@ -283,19 +340,23 @@ def _twisted_sweep_loft_shape(profile_obj, *, axis, origin, distance, twist_angl section.rotate(origin_vec, axis_vec, angle) offset = distance_value * fraction if abs(offset) > 1.0e-12: - section.translate(App.Vector(axis_vec.x * offset, axis_vec.y * offset, axis_vec.z * offset)) + section.translate( + App.Vector( + axis_vec.x * offset, axis_vec.y * offset, axis_vec.z * offset + ) + ) sections.append(section) result = Part.makeLoft(sections, True, False, False, 5) if result is None or result.isNull() or not result.isValid(): - raise RuntimeError(f'{operation} loft emulation produced an invalid shape') - if len(list(getattr(result, 'Solids', []) or [])) != 1: - raise RuntimeError(f'{operation} loft emulation did not produce one solid') + raise RuntimeError(f"{operation} loft emulation produced an invalid shape") + if len(list(getattr(result, "Solids", []) or [])) != 1: + raise RuntimeError(f"{operation} loft emulation did not produce one solid") return result def _placement_from_context(context): - origin = context.get('origin') if isinstance(context, dict) else None + origin = context.get("origin") if isinstance(context, dict) else None if isinstance(origin, (list, tuple)) and len(origin) == 3: return App.Placement(_vec(origin), App.Rotation()) return App.Placement() @@ -304,13 +365,16 @@ def _placement_from_context(context): def _rotation_from_context_axes(context): if not isinstance(context, dict): return App.Rotation() - x_axis = context.get('x_axis') - y_axis = context.get('y_axis') - z_axis = context.get('z_axis') + x_axis = context.get("x_axis") + y_axis = context.get("y_axis") + z_axis = context.get("z_axis") if not ( - isinstance(x_axis, (list, tuple)) and len(x_axis) == 3 and - isinstance(y_axis, (list, tuple)) and len(y_axis) == 3 and - isinstance(z_axis, (list, tuple)) and len(z_axis) == 3 + isinstance(x_axis, (list, tuple)) + and len(x_axis) == 3 + and isinstance(y_axis, (list, tuple)) + and len(y_axis) == 3 + and isinstance(z_axis, (list, tuple)) + and len(z_axis) == 3 ): return App.Rotation() m = App.Matrix() @@ -321,8 +385,12 @@ def _rotation_from_context_axes(context): def _sketch_placement_from_context(context): - origin = context.get('origin') if isinstance(context, dict) else None - base = _vec(origin) if isinstance(origin, (list, tuple)) and len(origin) == 3 else App.Vector(0.0, 0.0, 0.0) + origin = context.get("origin") if isinstance(context, dict) else None + base = ( + _vec(origin) + if isinstance(origin, (list, tuple)) and len(origin) == 3 + else App.Vector(0.0, 0.0, 0.0) + ) return App.Placement(base, _rotation_from_context_axes(context)) @@ -336,21 +404,21 @@ def _line_sketch_placement(start, end): if dot > 0.95: ref = App.Vector(0.0, 1.0, 0.0) z_axis = x_axis.cross(ref) - z_len = float(getattr(z_axis, 'Length', 0.0)) + z_len = float(getattr(z_axis, "Length", 0.0)) if z_len == 0.0: ref = App.Vector(1.0, 0.0, 0.0) z_axis = x_axis.cross(ref) - z_len = float(getattr(z_axis, 'Length', 0.0)) + z_len = float(getattr(z_axis, "Length", 0.0)) z_axis = App.Vector(z_axis.x / z_len, z_axis.y / z_len, z_axis.z / z_len) y_axis = z_axis.cross(x_axis) - y_len = float(getattr(y_axis, 'Length', 0.0)) + y_len = float(getattr(y_axis, "Length", 0.0)) y_axis = App.Vector(y_axis.x / y_len, y_axis.y / y_len, y_axis.z / y_len) m = App.Matrix() m.A11, m.A21, m.A31 = x_axis.x, x_axis.y, x_axis.z m.A12, m.A22, m.A32 = y_axis.x, y_axis.y, y_axis.z m.A13, m.A23, m.A33 = z_axis.x, z_axis.y, z_axis.z rotation = App.Rotation(m) - return App.Placement(start_v, rotation), float(getattr(delta, 'Length', 0.0)) + return App.Placement(start_v, rotation), float(getattr(delta, "Length", 0.0)) def _pick_perpendicular_axis(vec): @@ -359,25 +427,25 @@ def _pick_perpendicular_axis(vec): if dot > 0.95: ref = App.Vector(0.0, 1.0, 0.0) perp = vec.cross(ref) - length = float(getattr(perp, 'Length', 0.0)) + length = float(getattr(perp, "Length", 0.0)) if length == 0.0: ref = App.Vector(1.0, 0.0, 0.0) perp = vec.cross(ref) - length = float(getattr(perp, 'Length', 0.0)) + length = float(getattr(perp, "Length", 0.0)) return App.Vector(perp.x / length, perp.y / length, perp.z / length) def _frame_from_points(points, fallback_context=None, preferred_normal=None): if not points: - raise RuntimeError('Expected at least one point for sketch frame') + raise RuntimeError("Expected at least one point for sketch frame") origin = _vec(points[0]) fallback_x = None fallback_y = None fallback_z = None if isinstance(fallback_context, dict): - raw_x = fallback_context.get('x_axis') - raw_y = fallback_context.get('y_axis') - raw_z = fallback_context.get('z_axis') + raw_x = fallback_context.get("x_axis") + raw_y = fallback_context.get("y_axis") + raw_z = fallback_context.get("z_axis") if isinstance(raw_x, (list, tuple)) and len(raw_x) == 3: try: fallback_x = _normalized_vec(raw_x) @@ -409,7 +477,7 @@ def _frame_from_points(points, fallback_context=None, preferred_normal=None): float(point[2]) - origin.z, ) offset = abs(float(delta.dot(preferred_z))) - if offset > max(1e-7, float(getattr(delta, 'Length', 0.0)) * 1e-7): + if offset > max(1e-7, float(getattr(delta, "Length", 0.0)) * 1e-7): on_preferred_plane = False break if on_preferred_plane: @@ -418,7 +486,7 @@ def _frame_from_points(points, fallback_context=None, preferred_normal=None): if candidate is None: continue projected = candidate - preferred_z * float(candidate.dot(preferred_z)) - if float(getattr(projected, 'Length', 0.0)) > 1e-12: + if float(getattr(projected, "Length", 0.0)) > 1e-12: preferred_x = _normalized_vec(projected) break if preferred_x is None: @@ -439,9 +507,19 @@ def _frame_from_points(points, fallback_context=None, preferred_normal=None): scale = 1.0 on_fallback_plane = True for point in points[1:]: - delta = App.Vector(float(point[0]) - origin.x, float(point[1]) - origin.y, float(point[2]) - origin.z) - scale = max(scale, float(getattr(delta, 'Length', 0.0))) - offset = abs(float(delta.x * fallback_z.x + delta.y * fallback_z.y + delta.z * fallback_z.z)) + delta = App.Vector( + float(point[0]) - origin.x, + float(point[1]) - origin.y, + float(point[2]) - origin.z, + ) + scale = max(scale, float(getattr(delta, "Length", 0.0))) + offset = abs( + float( + delta.x * fallback_z.x + + delta.y * fallback_z.y + + delta.z * fallback_z.z + ) + ) if offset > max(1e-7, scale * 1e-7): on_fallback_plane = False break @@ -455,8 +533,12 @@ def _frame_from_points(points, fallback_context=None, preferred_normal=None): x_axis = None for point in points[1:]: - delta = App.Vector(float(point[0]) - origin.x, float(point[1]) - origin.y, float(point[2]) - origin.z) - length = float(getattr(delta, 'Length', 0.0)) + delta = App.Vector( + float(point[0]) - origin.x, + float(point[1]) - origin.y, + float(point[2]) - origin.z, + ) + length = float(getattr(delta, "Length", 0.0)) if length > 1e-9: x_axis = App.Vector(delta.x / length, delta.y / length, delta.z / length) break @@ -465,15 +547,27 @@ def _frame_from_points(points, fallback_context=None, preferred_normal=None): z_axis = None for point in points[1:]: - delta = App.Vector(float(point[0]) - origin.x, float(point[1]) - origin.y, float(point[2]) - origin.z) + delta = App.Vector( + float(point[0]) - origin.x, + float(point[1]) - origin.y, + float(point[2]) - origin.z, + ) candidate = x_axis.cross(delta) - length = float(getattr(candidate, 'Length', 0.0)) + length = float(getattr(candidate, "Length", 0.0)) if length > 1e-9: - z_axis = App.Vector(candidate.x / length, candidate.y / length, candidate.z / length) + z_axis = App.Vector( + candidate.x / length, candidate.y / length, candidate.z / length + ) break if z_axis is None and fallback_z is not None: - dot = abs(float(x_axis.x * fallback_z.x + x_axis.y * fallback_z.y + x_axis.z * fallback_z.z)) + dot = abs( + float( + x_axis.x * fallback_z.x + + x_axis.y * fallback_z.y + + x_axis.z * fallback_z.z + ) + ) if dot < 0.95: z_axis = fallback_z @@ -481,10 +575,10 @@ def _frame_from_points(points, fallback_context=None, preferred_normal=None): z_axis = _pick_perpendicular_axis(x_axis) y_axis = z_axis.cross(x_axis) - y_len = float(getattr(y_axis, 'Length', 0.0)) + y_len = float(getattr(y_axis, "Length", 0.0)) if y_len == 0.0: y_axis = _pick_perpendicular_axis(z_axis) - y_len = float(getattr(y_axis, 'Length', 0.0)) + y_len = float(getattr(y_axis, "Length", 0.0)) y_axis = App.Vector(y_axis.x / y_len, y_axis.y / y_len, y_axis.z / y_len) m = App.Matrix() @@ -512,10 +606,12 @@ def _vec_tuple(vec): def _first_edge(obj): - shape = getattr(obj, 'Shape', None) if hasattr(obj, 'Shape') else obj + shape = getattr(obj, "Shape", None) if hasattr(obj, "Shape") else obj if shape is None or shape.isNull(): - raise RuntimeError(f'Object {getattr(obj, "Name", "")} has no valid shape') - edges = list(getattr(shape, 'Edges', [])) + raise RuntimeError( + f'Object {getattr(obj, "Name", "")} has no valid shape' + ) + edges = list(getattr(shape, "Edges", [])) if not edges: raise RuntimeError(f'Object {getattr(obj, "Name", "")} has no edges') return edges[0] @@ -538,7 +634,11 @@ def _edge_mid_point(obj): def _arc_from_edge(obj): - return Part.Arc(_vec(_edge_start_point(obj)), _vec(_edge_mid_point(obj)), _vec(_edge_end_point(obj))) + return Part.Arc( + _vec(_edge_start_point(obj)), + _vec(_edge_mid_point(obj)), + _vec(_edge_end_point(obj)), + ) def _shape_from_object_value(value, seen=None): @@ -547,26 +647,26 @@ def _shape_from_object_value(value, seen=None): seen = set() if seen is None else seen marker = id(value) if marker in seen: - raise RuntimeError('Cyclic FreeCAD link chain while resolving graph shape') + raise RuntimeError("Cyclic FreeCAD link chain while resolving graph shape") seen.add(marker) - linked_object = getattr(value, 'LinkedObject', None) + linked_object = getattr(value, "LinkedObject", None) if linked_object is not None: shape = _shape_from_object_value(linked_object, seen).copy() - placement = getattr(value, 'Placement', None) + placement = getattr(value, "Placement", None) if placement is not None: shape.Placement = placement.multiply(shape.Placement) return shape - if hasattr(value, 'Shape'): - return getattr(value, 'Shape', None) + if hasattr(value, "Shape"): + return getattr(value, "Shape", None) return value def _shape_from_graph_node(node_id): value = GRAPH_NODES.get(node_id) if value is None: - raise RuntimeError(f'Missing graph node {node_id!r}') - if isinstance(value, dict) and 'shape' in value: - return value['shape'] + raise RuntimeError(f"Missing graph node {node_id!r}") + if isinstance(value, dict) and "shape" in value: + return value["shape"] shape = _shape_from_object_value(value) try: shape_invalid = shape is None or shape.isNull() @@ -579,5 +679,5 @@ def _shape_from_graph_node(node_id): pass shape = _shape_from_object_value(value) if shape is None or shape.isNull(): - raise RuntimeError(f'Graph node {node_id!r} has no valid shape') + raise RuntimeError(f"Graph node {node_id!r} has no valid shape") return shape diff --git a/src/simplecadapi/translator/freecad_translator/runtime/metadata.py b/src/simplecadapi/translator/freecad_translator/runtime/metadata.py index 03f1774c..f130580e 100644 --- a/src/simplecadapi/translator/freecad_translator/runtime/metadata.py +++ b/src/simplecadapi/translator/freecad_translator/runtime/metadata.py @@ -216,6 +216,80 @@ def _simplecad_display_name(*, node_id, op, params, tags, semantic_delta): return f"{_op_label_token(op)} {node_id}" +def _assignment_operation_token(op): + token = str(op or "") + if token.startswith("make_"): + token = token[5:] + for suffix in ( + "_rsolid", + "_rface", + "_rwire", + "_redge", + "_rvertex", + "_rshape", + "_rsketch", + "_rassembly", + "_rpart", + "_rcompound", + "_rselection", + ): + if token.endswith(suffix): + token = token[: -len(suffix)] + break + return " ".join(token.replace("_", " ").split()).strip().lower() + + +def _assignment_target_words(target): + return ( + " ".join(str(target or "").replace("_", " ").replace(".", " ").split()) + .strip() + .lower() + ) + + +def _apply_graph_assignment_name(objects, *, node_id, assignment_targets, op): + targets = [ + " ".join(str(value).split()).strip() + for value in list(assignment_targets or []) + if str(value).strip() and str(value).strip() != "_" + ] + if not targets: + return objects + operation = _assignment_operation_token(op) + target = _assignment_target_words(targets[0]) + if not target: + return objects + display_name = target + if operation and not target.endswith(operation): + display_name = f"{target} {operation}" + values = objects if isinstance(objects, (list, tuple)) else [objects] + for obj in values: + if obj is None or not hasattr(obj, "addProperty"): + continue + type_id = str(getattr(obj, "TypeId", "")) + if str(getattr(obj, "SimpleCADNodeId", "")) != str(node_id): + continue + if type_id in { + "App::Part", + "App::Link", + "Assembly::AssemblyObject", + "Assembly::AssemblyLink", + "App::FeaturePython", + }: + continue + _ensure_string_list_property(obj, "SimpleCADAssignmentTargets") + _ensure_string_property(obj, "SimpleCADAssignmentName") + obj.SimpleCADAssignmentTargets = targets + obj.SimpleCADAssignmentName = display_name + _ensure_string_property(obj, "SimpleCADDisplayName") + obj.SimpleCADDisplayName = display_name + try: + obj.Label = display_name + except Exception: + pass + return objects + + def _attach_simplecad_metadata( obj, *, diff --git a/src/simplecadapi/translator/freecad_translator/runtime/occurrences.py b/src/simplecadapi/translator/freecad_translator/runtime/occurrences.py index 10596107..82468d45 100644 --- a/src/simplecadapi/translator/freecad_translator/runtime/occurrences.py +++ b/src/simplecadapi/translator/freecad_translator/runtime/occurrences.py @@ -53,7 +53,8 @@ def _occurrence_slug(value): def _occurrence_label(source, labels): node_id = str(getattr(source, "SimpleCADNodeId", "") or "") base = str( - labels.get(node_id) + getattr(source, "SimpleCADAssignmentName", "") + or labels.get(node_id) or getattr(source, "Label", "") or getattr(source, "SimpleCADOp", "") or "Operation" @@ -193,6 +194,19 @@ def _occurrence_copy_expressions(source, clone): pass +def _prepare_occurrence_definition_label(source): + assignment = str(getattr(source, "SimpleCADAssignmentName", "") or "").strip() + if not assignment: + return source + marker = " [definition]" + if not str(getattr(source, "Label", "")).endswith(marker): + try: + source.Label = assignment + marker + except Exception: + pass + return source + + def _copy_occurrence(source, *, root_token, path, labels): if not _occurrence_is_object(source): return None @@ -201,6 +215,7 @@ def _copy_occurrence(source, *, root_token, path, labels): or str(getattr(source, "TypeId", "")) == "Assembly::AssemblyLink" ) try: + _prepare_occurrence_definition_label(source) clone = doc.copyObject(source, False) except Exception as exc: raise RuntimeError( @@ -252,19 +267,22 @@ def _occurrence_protected_objects(): protected = { id(root) for root in OCCURRENCE_ROOT_OBJECTS.values() if root is not None } + + def protect(obj): + if not _occurrence_is_object(obj) or id(obj) in protected: + return + protected.add(id(obj)) + for child in list(getattr(obj, "Group", []) or []): + protect(child) + for value in list(PRODUCT_VALUES.values()): if not isinstance(value, dict): continue for key in ("container", "body", "material_object"): - obj = value.get(key) - if _occurrence_is_object(obj): - protected.add(id(obj)) + protect(value.get(key)) for component in list(value.get("components", []) or []): - if not isinstance(component, dict): - continue - link = component.get("link") - if _occurrence_is_object(link): - protected.add(id(link)) + if isinstance(component, dict): + protect(component.get("link")) return protected @@ -364,7 +382,10 @@ def _occurrence_make_root(root, source, labels): if clone is None: return None try: - clone.Label = str(root.get("result_label") or _occurrence_label(source, labels)) + if not str(getattr(clone, "SimpleCADAssignmentName", "") or "").strip(): + result_label = root.get("result_label") + if result_label: + clone.Label = str(result_label) except Exception: pass _ensure_string_property(clone, "SimpleCADSemanticRole", "SimpleCAD Semantic") @@ -390,49 +411,24 @@ def _occurrence_make_part_root(root, source, labels): if not isinstance(product, dict): return None container = product.get("container") - if not _occurrence_is_object(container): + body = product.get("body") + if not _occurrence_is_object(container) or not _occurrence_is_object(body): return None container.Label = str(root.get("label") or container.Label) - was_visible = bool(getattr(container, "Visibility", False)) - old_body = product.get("body") - clone = _copy_occurrence( - source, - root_token=_occurrence_slug(root.get("root_id") or "part"), - path=("body",), - labels=labels, - ) - if clone is None: - return None - try: - clone.Label = str(root.get("result_label") or _occurrence_label(source, labels)) - _ensure_string_property(clone, "SimpleCADSourceBodyNodeId") - clone.SimpleCADSourceBodyNodeId = str(root.get("result_node_id") or "") - _attach_tag_metadata_for_node(clone, clone.SimpleCADSourceBodyNodeId) - container.addObject(clone) - except Exception as exc: - raise RuntimeError( - f"FreeCAD could not attach part occurrence {clone.Name!r}" - ) from exc - if old_body is not None and old_body is not clone: - _occurrence_remove_object(old_body) + if not str(getattr(body, "SimpleCADAssignmentName", "") or "").strip(): + body.Label = str(root.get("result_label") or _occurrence_label(body, labels)) + _attach_tag_metadata_for_node(body, str(root.get("result_node_id") or "")) material = product.get("material") - for value in list(PRODUCT_VALUES.values()): - if isinstance(value, dict) and value.get("container") is container: - value["body"] = clone - if value.get("material"): - material = value.get("material") if material: - _apply_material_to_object(clone, material) - _set_visibility(container, was_visible) + _apply_material_to_object(body, material) + _set_visibility(container, True) _set_expanded(container, True) - _occurrence_complete_root( - container, - root, - _occurrence_slug(root.get("root_id") or "part"), - labels, - ) - _set_visibility(clone, was_visible) - _set_expanded(clone, True) + for child in list(getattr(container, "Group", []) or []): + if _is_origin_object(child) or _is_connector_object(child): + _set_visibility(child, False) + else: + _set_visibility(child, child is body) + _set_tree_visibility(child, True) _hide_origin_tree(container) return container diff --git a/src/simplecadapi/translator/freecad_translator/runtime/persistence.py b/src/simplecadapi/translator/freecad_translator/runtime/persistence.py index bc658865..179a2c2c 100644 --- a/src/simplecadapi/translator/freecad_translator/runtime/persistence.py +++ b/src/simplecadapi/translator/freecad_translator/runtime/persistence.py @@ -278,6 +278,7 @@ def _set_part_body_visibility(product_value, visible): if _is_connector_object(child): _set_visibility(child, False) continue + _set_tree_visibility(child, True) _set_visibility(child, bool(visible and child is body)) if body is not None: _set_visibility(body, visible) @@ -387,3 +388,4 @@ def _apply_result_visibility(result_node_ids): _set_visibility(obj, is_visible) _apply_product_result_visibility(display_product_ids) _hide_all_origin_trees() + _hide_all_connector_datums() diff --git a/src/simplecadapi/translator/freecad_translator/runtime/products.py b/src/simplecadapi/translator/freecad_translator/runtime/products.py index 829bb5a1..9c894b30 100644 --- a/src/simplecadapi/translator/freecad_translator/runtime/products.py +++ b/src/simplecadapi/translator/freecad_translator/runtime/products.py @@ -13,15 +13,6 @@ def _named_document_group(name, label): return group -def _construction_group(): - global CONSTRUCTION_GROUP - if CONSTRUCTION_GROUP is None: - CONSTRUCTION_GROUP = _named_document_group( - "SimpleCADConstruction", "SimpleCAD Construction" - ) - return CONSTRUCTION_GROUP - - def _material_library_group(): global MATERIAL_LIBRARY_GROUP if MATERIAL_LIBRARY_GROUP is None: @@ -199,23 +190,10 @@ def _hide_all_origin_trees(): _set_visibility(nested, False) -def _move_to_construction_group(obj): - group = _construction_group() - for candidate in [obj] + list(getattr(obj, "OutListRecursive", []) or []): - if candidate is None: - continue - if getattr(candidate, "TypeId", "") in { - "App::Origin", - "App::Line", - "App::Plane", - "App::Point", - }: - continue - _add_to_group(group, candidate) - _set_visibility(candidate, False) - _set_tree_visibility(candidate, False) - _set_visibility(group, False) - _set_tree_visibility(group, False) +def _hide_all_connector_datums(): + for obj in list(getattr(doc, "Objects", []) or []): + if _is_connector_object(obj): + _set_visibility(obj, False) def _hide_product_source_definition(product_item): @@ -229,19 +207,55 @@ def _hide_product_source_definition(product_item): _hide_origin_tree(container) -def _make_part_body_copy(part_container, source_obj, source_node_id): +def _part_feature_history(source_obj): + ordered = [] + seen = set() + + def visit(obj): + if obj is None or not hasattr(obj, "Name"): + return + marker = id(obj) + if marker in seen: + return + seen.add(marker) + for dependency in list(getattr(obj, "OutList", []) or []): + visit(dependency) + if not hasattr(obj, "Shape"): + return + if getattr(obj, "TypeId", "") in { + "App::Part", + "Assembly::AssemblyObject", + "Assembly::AssemblyLink", + }: + return + ordered.append(obj) + + visit(source_obj) + return ordered + + +def _adopt_part_feature_history(part_container, source_obj, source_node_id): doc.recompute() if source_obj is None or not hasattr(source_obj, "Shape"): - raise RuntimeError("Part body source has no shape") - body = part_container.newObject("Part::Feature", "Body") - body.Label = "Body" - body.Shape = source_obj.Shape.copy() - _ensure_string_property(body, "SimpleCADSourceBodyNodeId") - body.SimpleCADSourceBodyNodeId = str(source_node_id) - _attach_tag_metadata_for_node(body, source_node_id) - _set_visibility(body, True) - _move_to_construction_group(source_obj) - return body + raise RuntimeError("Part body source has no shape-bearing feature") + history = _part_feature_history(source_obj) + if not history or source_obj not in history: + raise RuntimeError("Part body source has no materialized feature history") + for feature in history: + try: + part_container.addObject(feature) + except Exception as exc: + raise RuntimeError( + f"Could not attach FreeCAD feature {feature.Name!r} to part history" + ) from exc + _set_tree_visibility(feature, True) + _set_visibility(feature, feature is source_obj) + _ensure_string_property(part_container, "SimpleCADBodyNodeId") + part_container.SimpleCADBodyNodeId = str(source_node_id) + _ensure_link_property(part_container, "SimpleCADBodyFeature") + part_container.SimpleCADBodyFeature = source_obj + _attach_tag_metadata_for_node(source_obj, source_node_id) + return source_obj def _make_assembly_component_link( diff --git a/src/simplecadapi/translator/freecad_translator/runtime/selections.py b/src/simplecadapi/translator/freecad_translator/runtime/selections.py index 50d6e5c6..ff32dbdb 100644 --- a/src/simplecadapi/translator/freecad_translator/runtime/selections.py +++ b/src/simplecadapi/translator/freecad_translator/runtime/selections.py @@ -5,7 +5,10 @@ def _subshape_candidates_for_kind(shape, kind): if kind == "face": return list(getattr(shape, "Faces", []) or []) if kind == "shell": - return list(getattr(shape, "Shells", []) or ([shape] if getattr(shape, "ShapeType", "") == "Shell" else [])) + return list( + getattr(shape, "Shells", []) + or ([shape] if getattr(shape, "ShapeType", "") == "Shell" else []) + ) if kind == "edge": return list(getattr(shape, "Edges", []) or []) if kind == "wire": diff --git a/src/simplecadapi/translator/freecad_translator/script_translator.py b/src/simplecadapi/translator/freecad_translator/script_translator.py deleted file mode 100644 index a6b56960..00000000 --- a/src/simplecadapi/translator/freecad_translator/script_translator.py +++ /dev/null @@ -1,5 +0,0 @@ -"""Compatibility imports for the historical FreeCAD script translator module.""" - -from .translator import FreeCADScriptTranslator, FreeCADTranslator - -__all__ = ["FreeCADScriptTranslator", "FreeCADTranslator"] diff --git a/src/simplecadapi/translator/freecad_translator/semantic.py b/src/simplecadapi/translator/freecad_translator/semantic.py index d75bdeff..17ad4ab1 100644 --- a/src/simplecadapi/translator/freecad_translator/semantic.py +++ b/src/simplecadapi/translator/freecad_translator/semantic.py @@ -71,6 +71,7 @@ _PRODUCT_OPS = { "make_belt_constraint_rassembly", "make_rack_pinion_constraint_rassembly", "make_solve_assembly_constraints_rassembly", + "evaluate_assembly_definition", } _PRODUCT_VALUE_OPS = _PRODUCT_OPS | { @@ -82,6 +83,7 @@ _PRODUCT_VALUE_OPS = _PRODUCT_OPS | { "make_vertex_connector_rconnector", "make_placement_connector_rconnector", "make_connector_ref_rconnectorref", + "reference_definition", "make_scalar_limit_rscalarlimit", } diff --git a/src/simplecadapi/translator/freecad_translator/translator.py b/src/simplecadapi/translator/freecad_translator/translator.py index 0ccef501..12a66297 100644 --- a/src/simplecadapi/translator/freecad_translator/translator.py +++ b/src/simplecadapi/translator/freecad_translator/translator.py @@ -9,7 +9,6 @@ from __future__ import annotations from typing import Any, Dict, List, Optional, Set -from ...serializer import import_model_json from ...topology import OperationGraph, OperationNode from ..base import BaseTranslator from ..types import BackendCapabilities, TranslationArtifact @@ -155,8 +154,26 @@ class _FreeCADCompiler( geometry translation """ - def __init__(self, document_name: str = "SimpleCADModel") -> None: - self._context = FreeCADCompileContext(document_name=document_name) + def __init__( + self, + document_name: str = "SimpleCADModel", + *, + expression_sheet_name: str = "SimpleCADExpressions", + definition_token: str = "", + definition_id: str = "", + definition_kind: str = "", + definition_revision: str = "", + definition_content_hash: str = "", + ) -> None: + self._context = FreeCADCompileContext( + document_name=document_name, + expression_sheet_name=expression_sheet_name, + definition_token=definition_token, + definition_id=definition_id, + definition_kind=definition_kind, + definition_revision=definition_revision, + definition_content_hash=definition_content_hash, + ) @property def document_name(self) -> str: @@ -203,7 +220,7 @@ class _FreeCADCompiler( alias = self._expr_alias_by_id.get(expr_id) if not alias: alias = _sanitize_expr_alias(expr_id, prefix="expr") - return f"<>.{alias}" + return f"<<{self._context.expression_sheet_name}>>.{alias}" def _angle_arc_span_formula(self, param_exprs: Dict[str, Any]) -> Optional[str]: start_expr = self._compile_time_expr_formula( @@ -237,24 +254,16 @@ class _FreeCADCompiler( return f"0 - ({start_expr})" return f"({end_expr}) - ({start_expr})" - def translate_model_json_to_script(self, json_str: str) -> str: - payload = import_model_json(json_str) - graph = payload.get("graph") - if not isinstance(graph, OperationGraph): - raise ValueError( - "FreeCAD translation requires model JSON with a canonical low-level graph" - ) - if graph.node_count == 0: - raise ValueError( - "FreeCAD translation requires model JSON with a non-empty canonical low-level graph" - ) - return self.translate_model_payload_to_script(payload, graph=graph) def translate_model_payload_to_script( self, payload: Dict[str, Any], *, graph: Optional[OperationGraph] = None, + include_preamble: bool = True, + include_runtime: bool = True, + finalize: bool = True, + register_definition: Optional[Dict[str, str]] = None, ) -> str: source_graph = graph or payload.get("graph") if not isinstance(source_graph, OperationGraph): @@ -268,7 +277,7 @@ class _FreeCADCompiler( self._context.source_graph = source_graph leaf_ids = payload.get("leaf_ids") if isinstance(leaf_ids, list) and leaf_ids: - self._result_node_id_list = [str(v) for v in leaf_ids] + self._result_node_id_list = [str(value) for value in leaf_ids] else: self._result_node_id_list = [ leaf.node_id for leaf in source_graph.leaf_nodes() @@ -284,34 +293,38 @@ class _FreeCADCompiler( ) lines: List[str] = [] emit = lines.append - - emit("import json") - emit("import math") - emit("import FreeCAD as App") - emit("import Part") - emit("try:") - emit(" import Sketcher") - emit("except Exception:") - emit(" Sketcher = None") - emit("try:") - emit(" import Assembly") - emit("except Exception:") - emit(" Assembly = None") - emit("try:") - emit(" import JointObject") - emit("except Exception:") - emit(" JointObject = None") - emit("try:") - emit(" import Spreadsheet") - emit("except Exception:") - emit(" Spreadsheet = None") - emit("import os") - emit("import zipfile") - emit("") - emit(f"DOC_NAME = {_json_ascii(self.document_name)}") - emit( - "doc = App.getDocument(DOC_NAME) if DOC_NAME in App.listDocuments() else App.newDocument(DOC_NAME)" - ) + if include_preamble: + emit("import json") + emit("import math") + emit("import FreeCAD as App") + emit("import Part") + emit("try:") + emit(" import Sketcher") + emit("except Exception:") + emit(" Sketcher = None") + emit("try:") + emit(" import Assembly") + emit("except Exception:") + emit(" Assembly = None") + emit("try:") + emit(" import JointObject") + emit("except Exception:") + emit(" JointObject = None") + emit("try:") + emit(" import Spreadsheet") + emit("except Exception:") + emit(" Spreadsheet = None") + emit("import os") + emit("import zipfile") + emit("") + emit(f"DOC_NAME = {_json_ascii(self.document_name)}") + emit( + "doc = App.getDocument(DOC_NAME) if DOC_NAME in App.listDocuments() else App.newDocument(DOC_NAME)" + ) + emit("DEFINITION_REGISTRY = {}") + if include_runtime: + emit("# FreeCAD runtime") + emit(assemble_runtime_source()) emit("GRAPH_NODES = {}") emit("GRAPH_OUTPUTS = {}") emit("GRAPH_METADATA = {}") @@ -342,6 +355,12 @@ class _FreeCADCompiler( if isinstance(nodes, list): self._expr_alias_by_id = _spreadsheet_expr_aliases(nodes) emit(f"EXPRESSION_GRAPH = {_py_literal(expression_graph_payload)}") + emit( + f"SIMPLECAD_EXPRESSION_SHEET = {_json_ascii(self._context.expression_sheet_name)}" + ) + emit("EXPR_CELL_BY_ID = {}") + emit("EXPR_ALIAS_BY_ID = {}") + emit("expr_sheet = None") tolerance_graph_payload = payload.get("tolerance_graph", {}) if hasattr(tolerance_graph_payload, "to_dict"): tolerance_graph_payload = tolerance_graph_payload.to_dict() @@ -349,13 +368,9 @@ class _FreeCADCompiler( emit(f"OP_EXPRESSION_BINDINGS = {_py_literal(_OP_EXPRESSION_BINDINGS)}") emit(f"OP_EXPRESSION_LIMITATIONS = {_py_literal(_OP_EXPRESSION_LIMITATIONS)}") emit("") - emit(assemble_runtime_source()) - emit("") - for line in self._emit_expression_graph(expression_graph_payload): emit(line) emit("") - emit("EXPRESSION_GRAPH_META = EXPRESSION_GRAPH") emit("TOLERANCE_GRAPH_META = TOLERANCE_GRAPH") emit("if TOLERANCE_GRAPH.get('requirements'):") @@ -363,13 +378,12 @@ class _FreeCADCompiler( " _make_metadata_note('simplecad_tolerance_graph', 'SimpleCAD Tolerance Graph', TOLERANCE_GRAPH)" ) emit("") - for node in source_graph.topological_order(): emit(f"# Step {node.node_id}: {node.op}") - for line in self._emit_node(node): + node_lines = self._emit_node(node) + for line in node_lines: emit(line) emit("") - emit("if GRAPH_LIMITATIONS:") emit( " _make_metadata_note('simplecad_expression_limitations', 'SimpleCAD Expression Limitations', GRAPH_LIMITATIONS)" @@ -378,20 +392,30 @@ class _FreeCADCompiler( emit( " _make_metadata_note('simplecad_translation_limitations', 'SimpleCAD Translation Limitations', GRAPH_TRANSLATION_LIMITATIONS)" ) - emit("") - emit("doc.recompute()") - emit("") - emit("# Leaf/result metadata") - emit(f"RESULT_NODE_IDS = {_py_literal(self._result_node_id_list)}") - emit( - "RESULT_OBJECTS = [obj for node_id in RESULT_NODE_IDS for obj in GRAPH_OUTPUTS.get(node_id, [])]" - ) - emit("_apply_result_visibility(RESULT_NODE_IDS)") - emit("_set_active_result_object(RESULT_NODE_IDS)") - emit("_apply_occurrence_tree(SEMANTIC_PLAN)") - emit("_restore_occurrence_tree_visibility()") - emit("doc.TransientDir = getattr(doc, 'TransientDir', '')") + if register_definition is not None: + required = {"definition_kind", "definition_id", "revision", "content_hash"} + if set(register_definition) != required: + raise ValueError("register_definition identity fields are incomplete") + result_node_id = self._result_node_id_list[-1] + emit( + f"DEFINITION_REGISTRY[{_json_ascii(register_definition['definition_id'])}] = {{" + f"'definition_kind': {_json_ascii(register_definition['definition_kind'])}, " + f"'revision': {_json_ascii(register_definition['revision'])}, " + f"'content_hash': {_json_ascii(register_definition['content_hash'])}, " + f"'product': PRODUCT_VALUES.get({_json_ascii(result_node_id)})}}" + ) + if finalize: + emit("") + emit("RESULT_NODE_IDS = " + _py_literal(self._result_node_id_list)) + emit( + "RESULT_OBJECTS = [obj for node_id in RESULT_NODE_IDS for obj in GRAPH_OUTPUTS.get(node_id, [])]" + ) + emit("_apply_result_visibility(RESULT_NODE_IDS)") + emit("_set_active_result_object(RESULT_NODE_IDS)") + emit("_apply_occurrence_tree(SEMANTIC_PLAN)") + emit("_restore_occurrence_tree_visibility()") + emit("doc.TransientDir = getattr(doc, 'TransientDir', '')") return "\n".join(lines).rstrip() + "\n" def _find_cylinder_profile_nodes(self, graph: OperationGraph) -> Set[str]: @@ -414,7 +438,7 @@ class _FreeCADCompiler( lines.append("EXPR_ALIAS_BY_ID = {}") lines.append("if Spreadsheet is not None:") lines.append( - " expr_sheet = doc.addObject('Spreadsheet::Sheet', 'SimpleCADExpressions')" + f" expr_sheet = doc.addObject('Spreadsheet::Sheet', {_json_ascii(self._context.expression_sheet_name)})" ) alias_by_id = _spreadsheet_expr_aliases(nodes) dimension_by_id, unit_aware_by_id = _expression_physical_metadata(nodes) @@ -509,7 +533,7 @@ class _FreeCADCompiler( alias = alias_by_id.get(str(arg)) if not alias: return None - args.append(f"<>.{alias}") + args.append(f"<<{self._context.expression_sheet_name}>>.{alias}") if op == "add" and len(args) == 2: return f"={args[0]} + {args[1]}" if op == "sub" and len(args) == 2: @@ -581,7 +605,19 @@ class _FreeCADCompiler( ) var_name = _safe_name(node.node_id) - object_name = _safe_name(f"{node.op}_{node.node_id}", prefix="step") + object_token = ( + f"{self._context.definition_token}_" + if self._context.definition_token + else "" + ) + object_name = _safe_name( + f"{object_token}{node.op}_{node.node_id}", prefix="step" + ) + assignment_targets = ( + list(node.source.get("assignment_targets") or []) + if isinstance(node.source, dict) + else [] + ) lines = [ f"{var_name}_params = {params_literal}", f"{var_name}_inputs = {inputs_literal}", @@ -600,6 +636,10 @@ class _FreeCADCompiler( ) if native_lines is not None: lines.extend(native_lines) + if assignment_targets: + lines.append( + f"_apply_graph_assignment_name(GRAPH_OUTPUTS.get({_json_ascii(node.node_id)}, []), node_id={_json_ascii(node.node_id)}, assignment_targets={_py_literal(assignment_targets)}, op={_json_ascii(node.op)})" + ) return lines raise ValueError(f"Unsupported FreeCAD native graph translation op: {node.op}") @@ -695,58 +735,72 @@ class _FreeCADCompiler( class FreeCADTranslator(BaseTranslator): - """Public, stateless facade for FreeCAD script translation.""" + """Translate validated `.scadpkg` products into FreeCAD scripts.""" - def __init__(self, document_name: str = "SimpleCADModel") -> None: - self.document_name = document_name + def __init__(self, document_name: str = "SimpleCADProduct") -> None: + self.document_name = str(document_name) @property def capabilities(self) -> BackendCapabilities: return CAPABILITIES - def translate_model_json_to_script(self, json_str: str) -> str: - return _FreeCADCompiler(self.document_name).translate_model_json_to_script( - json_str - ) + def _translate_product_package_to_script(self, data: Any) -> str: + from ..package_units import read_product_package_translation_units - def translate_model_payload_to_script( + _package, units = read_product_package_translation_units(data) + if not units: + raise ValueError("Product package contains no definition units") + sections: List[str] = [] + for index, unit in enumerate(units): + token = _safe_name(unit.definition_id, prefix="definition") + compiler = _FreeCADCompiler( + self.document_name, + expression_sheet_name=f"SimpleCADExpressions_{token}", + definition_token=token, + definition_id=unit.definition_id, + definition_kind=unit.definition_kind, + definition_revision=unit.revision, + definition_content_hash=unit.content_hash, + ) + sections.append( + compiler.translate_model_payload_to_script( + unit.model_payload(), + graph=unit.graph, + include_preamble=index == 0, + include_runtime=index == 0, + finalize=index == len(units) - 1, + register_definition={ + "definition_kind": unit.definition_kind, + "definition_id": unit.definition_id, + "revision": unit.revision, + "content_hash": unit.content_hash, + }, + ) + ) + return "\n".join(section.rstrip() for section in sections) + "\n" + + def translate_product_package( self, - payload: Dict[str, Any], - *, - graph: Optional[OperationGraph] = None, - ) -> str: - return _FreeCADCompiler(self.document_name).translate_model_payload_to_script( - payload, graph=graph - ) - - def translate_model_json(self, json_str: str) -> TranslationArtifact: - return TranslationArtifact( - backend_id="freecad", - target_id="freecad_script", - media_type="text/x-python", - suggested_suffix=".py", - content=self.translate_model_json_to_script(json_str), - metadata={"document_name": self.document_name}, - ) - - def translate_model_payload( - self, - payload: Dict[str, Any], - *, - graph: Optional[OperationGraph] = None, + data: Any, + **_options: Any, ) -> TranslationArtifact: + from ..package_units import read_product_package_translation_units + + package, units = read_product_package_translation_units(data) return TranslationArtifact( backend_id="freecad", target_id="freecad_script", media_type="text/x-python", suggested_suffix=".py", - content=self.translate_model_payload_to_script(payload, graph=graph), - metadata={"document_name": self.document_name}, + content=self._translate_product_package_to_script(package), + metadata={ + "document_name": self.document_name, + "root_definition_id": package.root_definition.definition_id, + "root_definition_kind": package.root_definition.definition_kind, + "definition_ids": tuple(unit.definition_id for unit in units), + "target_runtime_validated": False, + }, ) -class FreeCADScriptTranslator(FreeCADTranslator): - """Backward-compatible class name for the FreeCAD translator.""" - - -__all__ = ["FreeCADScriptTranslator", "FreeCADTranslator"] +__all__ = ["FreeCADTranslator"] diff --git a/src/simplecadapi/translator/fusion360_translator/__init__.py b/src/simplecadapi/translator/fusion360_translator/__init__.py index e39344ce..a15b2f8f 100644 --- a/src/simplecadapi/translator/fusion360_translator/__init__.py +++ b/src/simplecadapi/translator/fusion360_translator/__init__.py @@ -1,13 +1,11 @@ -"""Fusion 360 translator backend for SimpleCAD model JSON.""" +"""Fusion 360 translator backend for SimpleCAD product packages.""" -from .api import translate_model_json_to_fusion360_script +from .api import translate_product_package_to_fusion360_script from .capabilities import CAPABILITIES -from .compiler import Fusion360ScriptTranslator from .translator import Fusion360Translator __all__ = [ "CAPABILITIES", - "Fusion360ScriptTranslator", "Fusion360Translator", - "translate_model_json_to_fusion360_script", + "translate_product_package_to_fusion360_script", ] diff --git a/src/simplecadapi/translator/fusion360_translator/api.py b/src/simplecadapi/translator/fusion360_translator/api.py index 4bf1f64d..d37e383f 100644 --- a/src/simplecadapi/translator/fusion360_translator/api.py +++ b/src/simplecadapi/translator/fusion360_translator/api.py @@ -1,28 +1,27 @@ -"""Public Fusion 360 translator entrypoints.""" +"""Public Fusion 360 product translator entrypoint.""" from __future__ import annotations -from typing import Optional, Sequence - +from ..package_units import ProductPackageInput from .translator import Fusion360Translator -def translate_model_json_to_fusion360_script( - json_str: str, - document_name: str = "SimpleCADModel", - result_node_ids: Optional[Sequence[str]] = None, +def translate_product_package_to_fusion360_script( + data: ProductPackageInput, + document_name: str = "SimpleCADProduct", *, selection_mode: str = "gsm", source_kernel_fallback: bool = False, ) -> str: - """Translate canonical model JSON into a Fusion 360 Python script.""" + """Translate one validated `.scadpkg` closure into a Fusion 360 script.""" - return Fusion360Translator( + artifact = Fusion360Translator( document_name=document_name, - result_node_ids=result_node_ids, selection_mode=selection_mode, source_kernel_fallback=source_kernel_fallback, - ).translate_model_json_to_script(json_str) + ).translate_product_package(data) + assert isinstance(artifact.content, str) + return artifact.content -__all__ = ["translate_model_json_to_fusion360_script"] +__all__ = ["translate_product_package_to_fusion360_script"] diff --git a/src/simplecadapi/translator/fusion360_translator/capabilities.py b/src/simplecadapi/translator/fusion360_translator/capabilities.py index 14e4245e..9a665d7a 100644 --- a/src/simplecadapi/translator/fusion360_translator/capabilities.py +++ b/src/simplecadapi/translator/fusion360_translator/capabilities.py @@ -16,6 +16,10 @@ from ..types import ( BACKEND_NAME = "fusion360" _GEOMETRY_OPS = { + "make_box_rsolid", + "make_cylinder_rsolid", + "make_cone_rsolid", + "make_sphere_rsolid", "make_line_redge", "make_circle_redge", "make_three_point_arc_redge", @@ -50,6 +54,7 @@ _PRODUCT_OPS = { "make_assign_material_rpart", "make_assembly_rassembly", "make_add_component_rassembly", + "evaluate_assembly_definition", "make_place_component_rassembly", "make_compound_from_assembly_rcompound", "make_face_connector_rconnector", @@ -66,6 +71,7 @@ _PRODUCT_OPS = { "make_revolute_constraint_rassembly", "make_prismatic_constraint_rassembly", "make_solve_assembly_constraints_rassembly", + "apply_tag_rselection", } OP_SUPPORT: Dict[str, OperationCapability] = { @@ -95,7 +101,7 @@ for _op in _PRODUCT_OPS: CAPABILITIES = BackendCapabilities( backend_id=BACKEND_NAME, display_name="Fusion360", - input_schema_versions=("2.0",), + input_schema_versions=("product-package-2.0",), targets=( TranslationTarget( target_id="fusion360_script", @@ -105,7 +111,6 @@ CAPABILITIES = BackendCapabilities( requires_external_runtime=True, option_names=( "document_name", - "result_node_ids", "selection_mode", "source_kernel_fallback", ), diff --git a/src/simplecadapi/translator/fusion360_translator/compiler.py b/src/simplecadapi/translator/fusion360_translator/compiler.py index e12b4bd1..a0b23ef2 100644 --- a/src/simplecadapi/translator/fusion360_translator/compiler.py +++ b/src/simplecadapi/translator/fusion360_translator/compiler.py @@ -1,9 +1,7 @@ -"""Translate SimpleCAD model/graph payloads into Autodesk Fusion 360 scripts. +"""Compile validated product graphs into Autodesk Fusion 360 scripts. -Generated scripts are intended to run inside Fusion 360's Python environment. -They interpret the same canonical low-level graph consumed by -``freecad_translator.py`` and intentionally select detail-feature edges/faces by -geometry signatures instead of topology indices. +Generated scripts run inside Fusion 360's Python environment and select +detail-feature geometry by signatures instead of topology indices. """ from __future__ import annotations @@ -18,7 +16,7 @@ import tempfile import zlib from typing import Any, Dict, List, Optional, Sequence, Set, Tuple -from ...serializer import _execute_graph, import_model_json +from ...serializer import _execute_graph from ...topology import OperationGraph, OperationNode @@ -86,21 +84,17 @@ def _normalized_spline_params(params: Dict[str, Any]) -> Dict[str, Any]: float(curve.Knot(index)) for index in range(1, curve.NbKnots() + 1) ] result["multiplicities"] = [ - int(curve.Multiplicity(index)) - for index in range(1, curve.NbKnots() + 1) + int(curve.Multiplicity(index)) for index in range(1, curve.NbKnots() + 1) ] result["fusion_knots"] = [ knot - for knot, multiplicity in zip( - result["knots"], result["multiplicities"] - ) + for knot, multiplicity in zip(result["knots"], result["multiplicities"]) for _ in range(multiplicity) ] result["periodic"] = bool(curve.IsPeriodic()) if curve.IsRational(): result["weights"] = [ - float(curve.Weight(index)) - for index in range(1, curve.NbPoles() + 1) + float(curve.Weight(index)) for index in range(1, curve.NbPoles() + 1) ] except Exception: return result @@ -158,7 +152,9 @@ def _assembly_state_result_node_ids( ) if len({count for _, _, count in snapshots}) != 1: return {} - common_prefix = os.path.commonprefix([assembly_id for _, assembly_id, _ in snapshots]) + common_prefix = os.path.commonprefix( + [assembly_id for _, assembly_id, _ in snapshots] + ) separator_index = common_prefix.rfind("_") if separator_index <= 0: return {} @@ -237,7 +233,9 @@ def _dominant_result_node_id( return max(0.0, float(props.Mass())) shapes = [getattr(result, "wrapped", None) for result in results] - volumes = [shape_volume(shape) if shape is not None else 0.0 for shape in shapes] + volumes = [ + shape_volume(shape) if shape is not None else 0.0 for shape in shapes + ] except Exception: return None @@ -259,7 +257,10 @@ def _dominant_result_node_id( fused_volume = shape_volume(fused_shape) largest_index = max(range(len(volumes)), key=volumes.__getitem__) tolerance = max(1.0e-12, fused_volume * 1.0e-8) - if fused_volume > 0.0 and abs(volumes[largest_index] - fused_volume) <= tolerance: + if ( + fused_volume > 0.0 + and abs(volumes[largest_index] - fused_volume) <= tolerance + ): return node_ids[largest_index] except Exception: return None @@ -302,8 +303,7 @@ def _dependency_subgraph( omitted_selector_ids = { str(node.node_id) for node in graph.nodes - if node.op in {"make_select_redge", "make_select_rface"} - and not node.inputs + if node.op in {"make_select_redge", "make_select_rface"} and not node.inputs } result = OperationGraph(graph_id=graph.graph_id) for node in graph.topological_order(): @@ -370,7 +370,10 @@ def _seam_split_circle_node_ids(graph: OperationGraph) -> List[str]: if node.op != "make_select_redge": continue selector = node.params.get("geo_selector") - if not isinstance(selector, dict) or str(selector.get("geom_type", "")).upper() != "LINE": + if ( + not isinstance(selector, dict) + or str(selector.get("geom_type", "")).upper() != "LINE" + ): continue source = ( node_by_id.get(str(node.inputs[0].node_id)) @@ -424,11 +427,14 @@ def _seam_split_circle_node_ids(graph: OperationGraph) -> List[str]: normal_v = tuple(value / normal_len for value in normal_v) def radial_distance(point): - delta = tuple(point[index] - center_v[index] for index in range(3)) - axial = sum(delta[index] * normal_v[index] for index in range(3)) + delta = tuple( + point[index] - center_v[index] for index in range(3) + ) + axial = sum( + delta[index] * normal_v[index] for index in range(3) + ) radial = tuple( - delta[index] - axial * normal_v[index] - for index in range(3) + delta[index] - axial * normal_v[index] for index in range(3) ) return abs(axial), sum(value * value for value in radial) ** 0.5 @@ -448,7 +454,9 @@ def _seam_split_circle_node_ids(graph: OperationGraph) -> List[str]: edge_direction[index] * normal_v[index] for index in range(3) ) - ) / edge_length >= 1.0 - 1.0e-6 + ) + / edge_length + >= 1.0 - 1.0e-6 ): result.add(str(node.node_id)) except (TypeError, ValueError): @@ -482,13 +490,13 @@ def _source_kernel_step_payloads( detail_input_ids = [ str(input_ref.node_id) for node in replay_graph.nodes - if node.op in {'make_fillet_rsolid', 'make_chamfer_rsolid'} + if node.op in {"make_fillet_rsolid", "make_chamfer_rsolid"} for input_ref in node.inputs[:1] ] boolean_input_ids = [ str(input_ref.node_id) for node in replay_graph.nodes - if node.op in {'make_cut_rsolid', 'make_union_rsolid', 'make_intersect_rsolid'} + if node.op in {"make_cut_rsolid", "make_union_rsolid", "make_intersect_rsolid"} for input_ref in node.inputs ] node_ids = list( @@ -575,7 +583,9 @@ class Fusion360ScriptTranslator: source_kernel_fallback: bool = False, ) -> None: if selection_mode not in {"gsm", "index", "sample"}: - raise ValueError(f"Unsupported Fusion topology selection mode: {selection_mode}") + raise ValueError( + f"Unsupported Fusion topology selection mode: {selection_mode}" + ) self.document_name = document_name self.selection_mode = selection_mode self.source_kernel_fallback = bool(source_kernel_fallback) @@ -594,19 +604,6 @@ class Fusion360ScriptTranslator: self._source_kernel_signatures: Dict[str, Dict[str, Any]] = {} self._seam_split_circle_node_ids: List[str] = [] - def translate_model_json_to_script(self, json_str: str) -> str: - payload = import_model_json(json_str) - graph = payload.get("graph") - if not isinstance(graph, OperationGraph): - raise ValueError( - "Fusion 360 translation requires model JSON with a canonical low-level graph" - ) - if graph.node_count == 0: - raise ValueError( - "Fusion 360 translation requires model JSON with a non-empty canonical low-level graph" - ) - return self.translate_model_payload_to_script(payload, graph=graph) - def translate_model_payload_to_script( self, payload: Dict[str, Any], @@ -658,9 +655,7 @@ class Fusion360ScriptTranslator: ( self._source_kernel_steps, self._source_kernel_signatures, - ) = _source_kernel_step_payloads( - source_graph, self._result_node_id_list - ) + ) = _source_kernel_step_payloads(source_graph, self._result_node_id_list) else: self._source_kernel_steps = {} self._source_kernel_signatures = {} @@ -681,20 +676,28 @@ class Fusion360ScriptTranslator: emit(f"DOC_NAME = {_json_ascii(self.document_name)}") emit(f"SELECTION_MODE = {_json_ascii(self.selection_mode)}") emit(f"MODEL_PAYLOAD = {_py_literal(payload_dict)}") - emit(f"DECLARED_RESULT_NODE_IDS = {_py_literal(self._declared_result_node_id_list)}") + emit( + f"DECLARED_RESULT_NODE_IDS = {_py_literal(self._declared_result_node_id_list)}" + ) emit(f"RESULT_STATE_NODE_IDS = {_py_literal(self._result_state_node_ids)}") emit(f"ACTIVE_RESULT_STATE = {_py_literal(self._active_result_state)}") emit(f"RESULT_NODE_IDS = {_py_literal(self._result_node_id_list)}") emit(f"SOURCE_KERNEL_STEPS = {_py_literal(self._source_kernel_steps)}") - emit(f"SOURCE_KERNEL_SIGNATURES = {_py_literal(self._source_kernel_signatures)}") - emit(f"SEAM_SPLIT_CIRCLE_NODE_IDS = {_py_literal(self._seam_split_circle_node_ids)}") + emit( + f"SOURCE_KERNEL_SIGNATURES = {_py_literal(self._source_kernel_signatures)}" + ) + emit( + f"SEAM_SPLIT_CIRCLE_NODE_IDS = {_py_literal(self._seam_split_circle_node_ids)}" + ) emit("") emit(self._script_helpers()) emit("") emit("def run(context):") emit(" app = adsk.core.Application.get()") emit(" try:") - emit(" translator = SimpleCADFusionRuntime(MODEL_PAYLOAD, DOC_NAME, RESULT_NODE_IDS, SOURCE_KERNEL_STEPS, SOURCE_KERNEL_SIGNATURES, SEAM_SPLIT_CIRCLE_NODE_IDS)") + emit( + " translator = SimpleCADFusionRuntime(MODEL_PAYLOAD, DOC_NAME, RESULT_NODE_IDS, SOURCE_KERNEL_STEPS, SOURCE_KERNEL_SIGNATURES, SEAM_SPLIT_CIRCLE_NODE_IDS)" + ) emit(" return translator.run()") emit(" except Exception:") emit(" message = traceback.format_exc()") @@ -726,8 +729,7 @@ class Fusion360ScriptTranslator: "op": str(node.op), "params": self._sanitize_payload_for_fusion(params), "inputs": [ - {"node_id": str(input_ref.node_id)} - for input_ref in node.inputs + {"node_id": str(input_ref.node_id)} for input_ref in node.inputs ], } ) @@ -1556,6 +1558,7 @@ class SimpleCADFusionRuntime: self.materialized_native_node_ids = set() self.materialized_component_definitions = {} self.precreated_component_occurrences = {} + self.product_definition_components = {} self.part_body_node_ids = { self._input_ids(node)[0] for node in self.nodes @@ -2623,6 +2626,64 @@ class SimpleCADFusionRuntime: if curve is None: raise RuntimeError('Fusion could not create angle arc geometry') return self._set_output(node, curve) + if op == 'make_box_rsolid': + width = float(params.get('width', 0.0)) * SCALE + height = float(params.get('height', 0.0)) * SCALE + depth = float(params.get('depth', 0.0)) * SCALE + bottom = _v3(params.get('bottom_face_center') or (0.0, 0.0, 0.0)) + center = _pt( + ( + bottom[0], + bottom[1], + bottom[2] + float(params.get('depth', 0.0)) * 0.5, + ) + ) + bounds = adsk.core.OrientedBoundingBox3D.create( + center, + adsk.core.Vector3D.create(1.0, 0.0, 0.0), + adsk.core.Vector3D.create(0.0, 1.0, 0.0), + width, + height, + depth, + ) + body = self.tmp.createBox(bounds) + if body is None: + raise RuntimeError(f'Fusion box creation failed for {node_id}') + return self._set_output(node, body) + if op in {'make_cylinder_rsolid', 'make_cone_rsolid'}: + bottom = _v3(params.get('bottom_face_center') or (0.0, 0.0, 0.0)) + axis = _unit(params.get('axis') or (0.0, 0.0, 1.0)) + height = float(params.get('height', 0.0)) + top = _add(bottom, _scale(axis, height)) + bottom_radius = float( + params.get('bottom_radius', params.get('radius', 0.0)) + ) * SCALE + top_radius = float( + params.get('top_radius', params.get('radius', 0.0)) + ) * SCALE + body = self.tmp.createCylinderOrCone( + _pt(bottom), bottom_radius, _pt(top), top_radius + ) + if body is None: + raise RuntimeError(f'Fusion cylinder/cone creation failed for {node_id}') + return self._set_output(node, body) + if op == 'make_sphere_rsolid': + body = self.tmp.createSphere( + _pt(params.get('center') or (0.0, 0.0, 0.0)), + float(params.get('radius', 0.0)) * SCALE, + ) + if body is None: + raise RuntimeError(f'Fusion sphere creation failed for {node_id}') + return self._set_output(node, body) + if op == 'apply_tag_rselection': + value = self._first_output(inputs[0]) + _set_simplecad_attribute( + value, + 'AppliedTag', + str(params.get('tag') or params.get('normalized_tag') or ''), + ) + return self._set_output(node, value) + if op == 'make_three_point_arc_redge': curve = adsk.core.Arc3D.createByThreePoints(_pt(params.get('start')), _pt(params.get('middle')), _pt(params.get('end'))) return self._set_output(node, curve) @@ -2900,6 +2961,27 @@ class SimpleCADFusionRuntime: assembly['components'] = components self.product_values[node_id] = assembly return self._set_output(node, assembly) + if op == 'evaluate_assembly_definition': + assembly = dict(self._first_output(inputs[0])) + placements = { + str(record.get('instance_id') or ''): { + 'kind': 'placement', + 'params': dict(record.get('placement') or {}), + } + for record in (params.get('component_placements') or []) + if isinstance(record, dict) + } + components = [] + for component in assembly.get('components') or []: + component = dict(component) + component_id = str(component.get('component_id') or '') + if component_id in placements: + component['placement'] = placements[component_id] + components.append(component) + assembly['components'] = components + assembly['evaluation'] = params + self.product_values[node_id] = assembly + return self._set_output(node, assembly) if op == 'make_compound_from_assembly_rcompound': assembly = self._first_output(inputs[0]) if not isinstance(assembly, dict) or not assembly.get('components'): @@ -3755,286 +3837,134 @@ class SimpleCADFusionRuntime: return [body for body in bodies if body is not None] return [] - def _materialize_product_value(self, value, node_id, placements=()): - if not isinstance(value, dict): - return 0 + def _product_definition_key(self, value, node_id): + params = value.get('params') or {} + kind = str(value.get('kind') or '') + if kind == 'part': + definition_id = str(params.get('part_id') or params.get('id') or node_id) + else: + definition_id = str(params.get('assembly_id') or params.get('id') or node_id) + return kind, definition_id + + def _set_occurrence_visibility(self, occurrence, visible): + try: + occurrence.isLightBulbOn = bool(visible) + except Exception: + pass + + def _ensure_product_definition(self, value, result_node_id): + if not isinstance(value, dict) or value.get('kind') not in {'part', 'assembly', 'state'}: + raise RuntimeError('Fusion product definition must be a part or assembly') + key = self._product_definition_key(value, result_node_id) + existing = self.product_definition_components.get(key) + if existing is not None: + return existing + + params = value.get('params') or {} + display_name = str( + params.get('name') + or params.get('part_id') + or params.get('assembly_id') + or key[1] + ) + identity = adsk.core.Matrix3D.create() + if value.get('kind') == 'part': body = value.get('body') if body is None: - return 0 + raise RuntimeError(f'Fusion part definition {key[1]} has no body') body_node = str(value.get('body_node') or '') - native = self.native_bodies.get(body_node) - native_set = self.native_body_sets.get(body_node) or [] - can_use_native_set = ( - bool(native_set) - and all(_placement_is_identity(placement) for placement in placements) - and self._native_body_set_close(native_set, body) - ) - if can_use_native_set: - for index, native_part in enumerate(native_set): - _apply_name(native_part, f'SimpleCAD_{node_id}_{body_node}_{index}') - try: - native_part.isVisible = True - except Exception: - pass - return len(native_set) - can_use_native = ( - native is not None - and body_node not in self.materialized_native_node_ids - and all(_placement_is_identity(placement) for placement in placements) - and self._native_body_close(native, body) - ) - if can_use_native: - self.materialized_native_node_ids.add(body_node) - _apply_name(native, f'SimpleCAD_{node_id}_{body_node}') + seed = self.precreated_component_occurrences.get(body_node) + if seed is not None: + component = seed.component + else: + seed = self.root.occurrences.addNewComponent(identity) + if seed is None: + raise RuntimeError( + f'Fusion could not create part definition {key[1]}' + ) + component = seed.component + base_feature = component.features.baseFeatures.add() + base_feature.startEdit() try: - native.isVisible = True - except Exception: - pass - return 1 - persisted_body = self._body_copy(body) - for placement in reversed(tuple(placements)): - self.tmp.transform(persisted_body, _matrix_from_placement(placement)) - persisted = self._add_base_body(persisted_body) - _apply_name(persisted, f'SimpleCAD_{node_id}_{body_node or "static"}') - try: - persisted.isVisible = True - except Exception: - pass - return 1 - if value.get('kind') in {'assembly', 'state'}: - if not placements: - components = list(value.get('components') or []) - if components and all( - isinstance(component.get('item'), dict) - and component.get('item', {}).get('kind') == 'part' - for component in components - ): - return sum( - self._materialize_component_occurrence(component, node_id) - for component in components - ) - count = 0 - for component in value.get('components') or []: - component_placement = component.get('placement') or {} - count += self._materialize_product_value( - component.get('item'), - node_id, - tuple(placements) + (component_placement,), - ) - return count - return 0 - - def _materialize_component_occurrence(self, component_record, result_node_id): - item = component_record.get('item') or {} - body = item.get('body') - if body is None: - return 0 - component_id = str(component_record.get('component_id') or '') - component_node_id = str(component_record.get('node_id') or '') - body_node = str(item.get('body_node') or '') - params = component_record.get('params') or {} - placement = component_record.get('placement') or {} - placement_matrix = _matrix_from_placement(placement) - precreated_occurrence = self.precreated_component_occurrences.pop( - body_node, None - ) - if precreated_occurrence is not None: - occurrence = precreated_occurrence - child = occurrence.component - result_bodies = list(child.bRepBodies) - if ( - len(result_bodies) != 1 - or not self._native_body_close(result_bodies[0], body) - ): - raise RuntimeError( - f'precreated component geometry mismatch for {component_id}; ' - f'body_count={len(result_bodies)}' - ) - display_name = str(params.get('name') or component_id or component_node_id) - _apply_name(child, display_name) - _apply_name(occurrence, f'SimpleCAD_{component_id or component_node_id}') - _set_simplecad_attribute(occurrence, 'ComponentId', component_id) - _set_simplecad_attribute(occurrence, 'NodeId', component_node_id) - _set_simplecad_attribute(occurrence, 'ResultNodeId', result_node_id) - _set_simplecad_attribute(child, 'BodyNodeId', body_node) - _set_simplecad_attribute(child, 'ResultNodeId', result_node_id) - result_body = result_bodies[0] - _apply_name(result_body, f'SimpleCAD_{component_id}_{body_node}_0') - _set_simplecad_attribute(result_body, 'ComponentId', component_id) - _set_simplecad_attribute(result_body, 'NodeId', body_node) - try: - occurrence.isGroundToParent = False - except Exception: - pass - if not _placement_is_identity(placement): - if bool(getattr(occurrence, 'isValidForEditInitialPosition', False)): - occurrence.initialTransform = placement_matrix - elif not self.root.transformOccurrences( - [occurrence], [placement_matrix], True - ): - raise RuntimeError( - f'Fusion rejected placement for component {component_id}' - ) - if self.design.snapshots.hasPendingSnapshot: - snapshot = self.design.snapshots.add() - if snapshot is None: + added = component.bRepBodies.add(self._body_copy(body), base_feature) + if added is None: raise RuntimeError( - f'Fusion could not capture placement for {component_id}' + f'Fusion could not add body for part definition {key[1]}' ) - try: - result_body.isVisible = True - except Exception: - pass - self.materialized_native_node_ids.add(body_node) - self.materialized_component_definitions[body_node] = child - self.logs.append( - f'adopted precreated live component for {component_id}: ' - f'body_node={body_node}' - ) - return 1 - existing_component = self.materialized_component_definitions.get(body_node) - if existing_component is not None: - try: - occurrence = self.root.occurrences.addExistingComponent( - existing_component, placement_matrix - ) - except Exception: - occurrence = None - if occurrence is None: - raise RuntimeError( - f'Fusion could not reuse component definition for {component_id}' - ) - _apply_name(occurrence, f'SimpleCAD_{component_id or component_node_id}') - _set_simplecad_attribute(occurrence, 'ComponentId', component_id) - _set_simplecad_attribute(occurrence, 'NodeId', component_node_id) - _set_simplecad_attribute(occurrence, 'ResultNodeId', result_node_id) - try: - occurrence.isGroundToParent = False - except Exception: - pass - return max(1, int(existing_component.bRepBodies.count)) + finally: + base_feature.finishEdit() + _apply_name(component, display_name) + _apply_name(seed, f'SimpleCAD_definition_{key[1]}') + _set_simplecad_attribute(component, 'DefinitionKind', 'single_solid') + _set_simplecad_attribute(component, 'DefinitionId', key[1]) + _set_simplecad_attribute(component, 'BodyNodeId', body_node) + self._set_occurrence_visibility(seed, False) + record = {'component': component, 'seed': seed, 'solid_count': 1} + self.product_definition_components[key] = record + return record - native_set = list(self.native_body_sets.get(body_node) or []) - can_use_native_set = ( - bool(native_set) - and body_node not in self.materialized_native_node_ids - and self._native_body_set_close(native_set, body) + seed = self.root.occurrences.addNewComponent(identity) + if seed is None: + raise RuntimeError( + f'Fusion could not create assembly definition {key[1]}' + ) + component = seed.component + _apply_name(component, display_name) + _apply_name(seed, f'SimpleCAD_definition_{key[1]}') + _set_simplecad_attribute(component, 'DefinitionKind', 'assembly') + _set_simplecad_attribute(component, 'DefinitionId', key[1]) + _set_simplecad_chunked_attribute( + component, + 'AssemblyEvaluation', + json.dumps(value.get('evaluation') or {}, sort_keys=True), ) - native = self.native_bodies.get(body_node) - can_use_native = ( - not can_use_native_set - and native is not None - and body_node not in self.materialized_native_node_ids - and self._native_body_close(native, body) - ) - live_bodies = native_set if can_use_native_set else ([native] if can_use_native else []) - created_live_body = None - if len(live_bodies) == 1: - created_live_body = live_bodies[0].createComponent() - if created_live_body is None: - raise RuntimeError( - f'Fusion could not create a live component for {component_id}' - ) - child = created_live_body.parentComponent - occurrences = [ - candidate - for candidate in self.root.occurrences - if candidate.component == child - ] - if len(occurrences) != 1: - raise RuntimeError( - f'Fusion did not expose one occurrence for live component ' - f'{component_id}; found {len(occurrences)}' - ) - occurrence = occurrences[0] - else: - occurrence = self.root.occurrences.addNewComponent( - adsk.core.Matrix3D.create() if live_bodies else placement_matrix + record = {'component': component, 'seed': seed, 'solid_count': 0} + self.product_definition_components[key] = record + solid_count = 0 + for child_record in value.get('components') or []: + item = child_record.get('item') or {} + child_definition = self._ensure_product_definition(item, result_node_id) + placement = child_record.get('placement') or {} + occurrence = component.occurrences.addExistingComponent( + child_definition['component'], _matrix_from_placement(placement) ) if occurrence is None: raise RuntimeError( - f'Fusion could not create occurrence for component {component_id}' + f"Fusion could not instantiate component {child_record.get('component_id')!r} " + f"inside assembly {key[1]!r}" ) - child = occurrence.component - display_name = str(params.get('name') or component_id or component_node_id) - _apply_name(child, display_name) - _apply_name(occurrence, f'SimpleCAD_{component_id or component_node_id}') - _set_simplecad_attribute(occurrence, 'ComponentId', component_id) - _set_simplecad_attribute(occurrence, 'NodeId', component_node_id) - _set_simplecad_attribute(occurrence, 'ResultNodeId', result_node_id) - _set_simplecad_attribute(child, 'BodyNodeId', body_node) - _set_simplecad_attribute(child, 'ResultNodeId', result_node_id) - - if live_bodies: - result_bodies = [] - for index, live_body in enumerate(live_bodies): - moved = ( - created_live_body - if index == 0 and created_live_body is not None - else live_body.moveToComponent(occurrence) - ) - if moved is None: - raise RuntimeError( - f'Fusion could not move live body into component {component_id}' - ) - _apply_name(moved, f'SimpleCAD_{component_id}_{body_node}_{index}') - _set_simplecad_attribute(moved, 'ComponentId', component_id) - _set_simplecad_attribute(moved, 'NodeId', body_node) - result_bodies.append(moved) - self.materialized_native_node_ids.add(body_node) - self.materialized_component_definitions[body_node] = child - try: - occurrence.isGroundToParent = False - except Exception: - pass - if not _placement_is_identity(placement): - if bool(getattr(occurrence, 'isValidForEditInitialPosition', False)): - occurrence.initialTransform = placement_matrix - else: - if not self.root.transformOccurrences( - [occurrence], [placement_matrix], True - ): - raise RuntimeError( - f'Fusion rejected placement for component {component_id}' - ) - if self.design.snapshots.hasPendingSnapshot: - snapshot = self.design.snapshots.add() - if snapshot is None: - raise RuntimeError( - f'Fusion could not capture placement for {component_id}' - ) - self.logs.append( - f'live component body used for {component_id}: ' - f'body_node={body_node}; body_count={len(result_bodies)}' + component_id = str(child_record.get('component_id') or '') + child_params = child_record.get('params') or {} + _apply_name( + occurrence, + str(child_params.get('name') or component_id or child_definition['component'].name), + ) + _set_simplecad_attribute(occurrence, 'ComponentId', component_id) + _set_simplecad_attribute(occurrence, 'ParentDefinitionId', key[1]) + _set_simplecad_attribute( + occurrence, + 'DefinitionId', + self._product_definition_key(item, result_node_id)[1], ) - else: - base_feature = child.features.baseFeatures.add() - base_feature.startEdit() try: - source_body = child.bRepBodies.add(self._body_copy(body), base_feature) - if source_body is None: - raise RuntimeError( - f'Fusion could not add body for component {component_id}' - ) - finally: - base_feature.finishEdit() - result_bodies = list(base_feature.bodies) - if len(result_bodies) != 1: - raise RuntimeError( - f'expected one result body for component {component_id}, ' - f'found {len(result_bodies)}' + occurrence.isGroundToParent = component_id in set( + value.get('grounded_component_ids') or [] ) - _apply_name(result_bodies[0], f'SimpleCAD_{component_id}_{body_node}') - _set_simplecad_attribute(result_bodies[0], 'ComponentId', component_id) - _set_simplecad_attribute(result_bodies[0], 'NodeId', body_node) - - for result_body in result_bodies: - try: - result_body.isVisible = True except Exception: pass - return len(result_bodies) + solid_count += int(child_definition['solid_count']) + record['solid_count'] = solid_count + self._set_occurrence_visibility(seed, False) + return record + + def _materialize_product_value(self, value, node_id, placements=()): + if placements: + raise RuntimeError('Fusion product roots cannot carry external placements') + definition = self._ensure_product_definition(value, node_id) + self._set_occurrence_visibility(definition['seed'], True) + _set_simplecad_attribute(definition['component'], 'RootProduct', 'true') + return int(definition['solid_count']) def _materialize_results(self): if not self.result_node_ids: @@ -4165,21 +4095,3 @@ def _safe_label(op, node_id): token = 'simplecad_' + token return token[:80] ''' - - -def translate_model_json_to_fusion360_script( - json_str: str, - document_name: str = "SimpleCADModel", - result_node_ids: Optional[Sequence[str]] = None, - *, - selection_mode: str = "gsm", - source_kernel_fallback: bool = False, -) -> str: - """Translate exported model JSON into a Fusion 360 Python script.""" - - return Fusion360ScriptTranslator( - document_name=document_name, - result_node_ids=result_node_ids, - selection_mode=selection_mode, - source_kernel_fallback=source_kernel_fallback, - ).translate_model_json_to_script(json_str) diff --git a/src/simplecadapi/translator/fusion360_translator/script_translator.py b/src/simplecadapi/translator/fusion360_translator/script_translator.py deleted file mode 100644 index f0962445..00000000 --- a/src/simplecadapi/translator/fusion360_translator/script_translator.py +++ /dev/null @@ -1,5 +0,0 @@ -"""Compatibility import for the contributed Fusion 360 script compiler.""" - -from .compiler import Fusion360ScriptTranslator - -__all__ = ["Fusion360ScriptTranslator"] diff --git a/src/simplecadapi/translator/fusion360_translator/translator.py b/src/simplecadapi/translator/fusion360_translator/translator.py index 749844a7..6588659b 100644 --- a/src/simplecadapi/translator/fusion360_translator/translator.py +++ b/src/simplecadapi/translator/fusion360_translator/translator.py @@ -1,13 +1,15 @@ -"""Fusion 360 backend facade for canonical model translation.""" +"""Fusion 360 backend facade for product-package translation.""" from __future__ import annotations -from typing import Any, Dict, Optional, Sequence, Set +from typing import Any, Dict, Sequence, Set from ...errors import ErrorGuidance from ...topology import OperationGraph from ..base import BaseTranslator from ..errors import TranslationRequestError +from ..package_units import ProductPackageInput +from ..product_graph import build_product_graph_view from ..types import BackendCapabilities, SupportLevel, TranslationArtifact from .capabilities import CAPABILITIES from .compiler import Fusion360ScriptTranslator @@ -33,22 +35,16 @@ def _dependency_node_ids( class Fusion360Translator(BaseTranslator): - """Translate canonical model JSON into a Fusion 360 Python script.""" + """Translate validated `.scadpkg` products into Fusion 360 scripts.""" def __init__( self, - document_name: str = "SimpleCADModel", - result_node_ids: Optional[Sequence[str]] = None, + document_name: str = "SimpleCADProduct", *, selection_mode: str = "gsm", source_kernel_fallback: bool = False, ) -> None: self.document_name = str(document_name) - self.result_node_ids = ( - tuple(str(node_id) for node_id in result_node_ids) - if result_node_ids is not None - else None - ) self.selection_mode = str(selection_mode) self.source_kernel_fallback = bool(source_kernel_fallback) @@ -56,18 +52,13 @@ class Fusion360Translator(BaseTranslator): def capabilities(self) -> BackendCapabilities: return CAPABILITIES - def _result_ids( - self, payload: Dict[str, Any], graph: OperationGraph - ) -> Sequence[str]: - if self.result_node_ids is not None: - return self.result_node_ids - leaf_ids = payload.get("leaf_ids") - if isinstance(leaf_ids, list) and leaf_ids: - return [str(node_id) for node_id in leaf_ids] - return [node.node_id for node in graph.leaf_nodes()] - - def _preflight(self, payload: Dict[str, Any], graph: OperationGraph) -> None: - needed = _dependency_node_ids(graph, self._result_ids(payload, graph)) + def _preflight( + self, + payload: Dict[str, Any], + graph: OperationGraph, + result_node_id: str, + ) -> None: + needed = _dependency_node_ids(graph, [result_node_id]) unsupported = sorted( { node.op @@ -85,58 +76,48 @@ class Fusion360Translator(BaseTranslator): joined = ", ".join(unsupported) raise TranslationRequestError( "fusion360", - "translate_model_payload", + "translate_product_package", ErrorGuidance( - what_happened=f"The result graph uses unsupported Fusion 360 operations: {joined}.", + what_happened=( + "The product package uses unsupported Fusion 360 " + f"operations: {joined}." + ), possible_causes=( - "The model uses canonical operations not implemented by the contributed runtime.", + "A definition-owned Feature Graph uses operations not " + "implemented by the Fusion 360 runtime.", ), how_to_fix=( - "Lower the model to operations declared by fusion360_translator.CAPABILITIES.", - "Use another translator backend for this model.", + "Use operations declared by fusion360_translator.CAPABILITIES.", + "Use another translator backend for this product.", ), ), ) - def translate_model_payload_to_script( + def translate_product_package( self, - payload: Dict[str, Any], - *, - graph: Optional[OperationGraph] = None, - ) -> str: - source_graph = graph or payload.get("graph") - if not isinstance(source_graph, OperationGraph) or source_graph.node_count == 0: - raise ValueError( - "Fusion 360 translation requires a non-empty canonical graph" - ) - self._preflight(payload, source_graph) - return Fusion360ScriptTranslator( + data: ProductPackageInput, + **_options: Any, + ) -> TranslationArtifact: + view = build_product_graph_view(data) + payload = view.model_payload() + self._preflight(payload, view.graph, view.root_result_node_id) + script = Fusion360ScriptTranslator( document_name=self.document_name, - result_node_ids=self.result_node_ids, + result_node_ids=[view.root_result_node_id], selection_mode=self.selection_mode, source_kernel_fallback=self.source_kernel_fallback, - ).translate_model_payload_to_script(payload, graph=source_graph) - - def translate_model_json_to_script(self, json_str: str) -> str: - artifact = self.translate_model_json(json_str) - assert isinstance(artifact.content, str) - return artifact.content - - def translate_model_payload( - self, - payload: Dict[str, Any], - *, - graph: Optional[OperationGraph] = None, - ) -> TranslationArtifact: + ).translate_model_payload_to_script(payload, graph=view.graph) return TranslationArtifact( backend_id="fusion360", target_id="fusion360_script", media_type="text/x-python", suggested_suffix=".py", - content=self.translate_model_payload_to_script(payload, graph=graph), + content=script, metadata={ "document_name": self.document_name, - "result_node_ids": self.result_node_ids, + "root_definition_id": view.root_definition_id, + "root_definition_kind": view.root_definition_kind, + "definition_ids": view.definition_ids, "selection_mode": self.selection_mode, "source_kernel_fallback": self.source_kernel_fallback, "target_runtime_validated": False, diff --git a/src/simplecadapi/translator/package_units.py b/src/simplecadapi/translator/package_units.py new file mode 100644 index 00000000..11df485b --- /dev/null +++ b/src/simplecadapi/translator/package_units.py @@ -0,0 +1,121 @@ +"""Validated product-package translation units shared by CAD backends.""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from ..artifacts.assembly_definition import AssemblyDefinition +from ..artifacts.feature_graph import FeatureGraphArtifact, load_feature_graph_artifact +from ..artifacts.part_definition import PartDefinition +from ..product_packages import ( + ProductPackage, + read_product_package, + validate_product_package, +) +from ..topology import OperationGraph + +Definition = PartDefinition | AssemblyDefinition +ProductPackageInput = ProductPackage | bytes | bytearray | memoryview | str | Path + + +@dataclass(frozen=True, slots=True) +class ProductPackageTranslationUnit: + """One definition-owned graph in dependency-first translation order.""" + + definition: Definition + feature_graph: FeatureGraphArtifact + graph: OperationGraph + + @property + def definition_kind(self) -> str: + return self.definition.definition_kind + + @property + def definition_id(self) -> str: + return self.definition.definition_id + + @property + def revision(self) -> str: + return self.definition.revision + + @property + def content_hash(self) -> str: + return self.definition.content_hash + + @property + def result_node_id(self) -> str: + return self.feature_graph.result_node_ids[0] + + def model_payload(self) -> dict[str, Any]: + semantic_index = dict(self.feature_graph.semantic_index) + return { + "graph": self.graph, + "leaf_ids": list(self.feature_graph.result_node_ids), + "expression_graph": dict(self.feature_graph.expression_graph), + "tolerance_graph": dict(self.feature_graph.tolerance_graph), + "frame_graph": dict(self.feature_graph.frame_graph), + "geometry_registry": list(semantic_index.get("geometry_registry", [])), + "semantic_entity_registry": list( + semantic_index.get("semantic_entity_registry", []) + ), + "sketch_profile_registry": list( + semantic_index.get("sketch_profile_registry", []) + ), + "semantic_delta_log": list(semantic_index.get("semantic_delta_log", [])), + "topology_delta_log": list(semantic_index.get("topology_delta_log", [])), + "semantic_bindings": list(semantic_index.get("semantic_bindings", [])), + } + + +def read_product_package_translation_units( + data: ProductPackageInput, +) -> tuple[ProductPackage, tuple[ProductPackageTranslationUnit, ...]]: + """Return a validated package and dependency-first definition units.""" + + if isinstance(data, ProductPackage): + validate_product_package(data) + package = data + else: + package = read_product_package(data) + ordered: list[Definition] = [] + visited: set[tuple[str, str]] = set() + + def visit(definition: Definition) -> None: + key = (definition.definition_kind, definition.content_hash) + if key in visited: + return + if isinstance(definition, AssemblyDefinition): + for ref in definition.definition_refs: + child = definition.resolved_definitions.get(ref.definition_id) + if not isinstance(child, (PartDefinition, AssemblyDefinition)): + raise ValueError( + f"assembly {definition.definition_id!r} has unresolved definition " + f"{ref.definition_id!r}" + ) + visit(child) + visited.add(key) + ordered.append(definition) + + visit(package.root_definition) + units: list[ProductPackageTranslationUnit] = [] + for definition in ordered: + feature_graph = load_feature_graph_artifact( + definition.blobs[definition.feature_graph_ref.path] + ) + units.append( + ProductPackageTranslationUnit( + definition=definition, + feature_graph=feature_graph, + graph=OperationGraph.from_dict(dict(feature_graph.graph)), + ) + ) + return package, tuple(units) + + +__all__ = [ + "ProductPackageInput", + "ProductPackageTranslationUnit", + "read_product_package_translation_units", +] diff --git a/src/simplecadapi/translator/product_graph.py b/src/simplecadapi/translator/product_graph.py new file mode 100644 index 00000000..57a5bf8a --- /dev/null +++ b/src/simplecadapi/translator/product_graph.py @@ -0,0 +1,155 @@ +"""Internal dependency-first graph view for product-package translators.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any + +from ..topology import OperationGraph +from .package_units import ProductPackageInput, read_product_package_translation_units + + +_NODE_ID_KEYS = { + "node_id", + "source_node_id", + "target_node_id", + "topology_source_node_id", + "topology_target_node_id", +} +_NODE_IDS_KEYS = { + "node_ids", + "selected_edge_node_ids", + "selected_face_node_ids", + "source_node_ids", + "target_node_ids", +} + + +@dataclass(frozen=True, slots=True) +class ProductGraphView: + """One translator-internal graph spanning a validated package closure.""" + + graph: OperationGraph + root_result_node_id: str + definition_result_node_ids: dict[str, str] + definition_ids: tuple[str, ...] + root_definition_id: str + root_definition_kind: str + + def model_payload(self) -> dict[str, Any]: + return { + "schema_version": "2.0", + "graph": self.graph, + "leaf_ids": [self.root_result_node_id], + } + + +def _safe_token(value: str) -> str: + token = "".join(character if character.isalnum() else "_" for character in value) + return token.strip("_") or "definition" + + +def _remap_node_ids(value: Any, mapping: dict[str, str], key: str | None = None) -> Any: + if isinstance(value, dict): + return { + str(child_key): _remap_node_ids(child, mapping, str(child_key)) + for child_key, child in value.items() + } + if isinstance(value, list): + if key in _NODE_IDS_KEYS: + return [mapping.get(str(child), str(child)) for child in value] + return [_remap_node_ids(child, mapping) for child in value] + if isinstance(value, tuple): + if key in _NODE_IDS_KEYS: + return tuple(mapping.get(str(child), str(child)) for child in value) + return tuple(_remap_node_ids(child, mapping) for child in value) + if key in _NODE_ID_KEYS and value is not None: + return mapping.get(str(value), str(value)) + return value + + +def build_product_graph_view(data: ProductPackageInput) -> ProductGraphView: + """Build a namespaced in-memory graph from one validated `.scadpkg` closure. + + This is a translator implementation detail, not a serialized interchange + format. External-definition reference nodes are resolved to the already + translated dependency result node they name. + """ + + package, units = read_product_package_translation_units(data) + if not units: + raise ValueError("Product package contains no definition units") + + graph = OperationGraph( + graph_id=f"product_{_safe_token(package.root_definition.definition_id)}" + ) + definition_results: dict[str, str] = {} + + for unit_index, unit in enumerate(units): + prefix = f"d{unit_index:04d}_{_safe_token(unit.definition_id)}" + local_mapping: dict[str, str] = {} + for node in unit.graph.topological_order(): + if node.op == "reference_definition": + definition_id = str(node.params.get("definition_id") or "") + result_node_id = definition_results.get(definition_id) + if result_node_id is None: + raise ValueError( + f"Definition {unit.definition_id!r} references unresolved " + f"dependency {definition_id!r}" + ) + local_mapping[node.node_id] = result_node_id + continue + local_mapping[node.node_id] = f"{prefix}_{node.node_id}" + + for node in unit.graph.topological_order(): + if node.op == "reference_definition": + continue + input_nodes = [] + for source in node.inputs: + source_id = local_mapping.get(source.node_id) + if source_id is None: + raise ValueError( + f"Definition {unit.definition_id!r} has unmapped input " + f"{source.node_id!r}" + ) + source_node = graph.get_node(source_id) + if source_node is None: + raise ValueError( + f"Definition {unit.definition_id!r} input {source.node_id!r} " + "was not emitted dependency-first" + ) + input_nodes.append(source_node) + graph.add_node( + op=node.op, + params=_remap_node_ids(node.params, local_mapping), + param_exprs=_remap_node_ids(node.param_exprs, local_mapping), + inputs=input_nodes, + node_id=local_mapping[node.node_id], + output_count=node.output_count, + context=node.context, + tags=set(node.tags), + source=node.source, + ) + + result_node_id = local_mapping.get(unit.result_node_id) + if result_node_id is None or graph.get_node(result_node_id) is None: + raise ValueError( + f"Definition {unit.definition_id!r} result node did not enter product graph" + ) + definition_results[unit.definition_id] = result_node_id + + root = package.root_definition + root_result = definition_results.get(root.definition_id) + if root_result is None: + raise ValueError("Product package root definition has no translated result") + return ProductGraphView( + graph=graph, + root_result_node_id=root_result, + definition_result_node_ids=dict(definition_results), + definition_ids=tuple(unit.definition_id for unit in units), + root_definition_id=root.definition_id, + root_definition_kind=root.definition_kind, + ) + + +__all__ = ["ProductGraphView", "build_product_graph_view"] diff --git a/src/simplecadapi/translator/solidworks_translator/__init__.py b/src/simplecadapi/translator/solidworks_translator/__init__.py index 8bbf3617..b781b5b7 100644 --- a/src/simplecadapi/translator/solidworks_translator/__init__.py +++ b/src/simplecadapi/translator/solidworks_translator/__init__.py @@ -1,19 +1,11 @@ -"""SolidWorks translator backend for SimpleCAD model JSON.""" +"""SolidWorks translator backend for SimpleCAD product packages.""" -from .api import ( - export_model_json_to_solidworks_step, - translate_model_json_to_solidworks_script, - translate_model_json_to_solidworks_step, -) +from .api import translate_product_package_to_solidworks_script from .capabilities import CAPABILITIES -from .compiler import SolidWorksScriptTranslator from .translator import SolidWorksTranslator __all__ = [ "CAPABILITIES", - "SolidWorksScriptTranslator", "SolidWorksTranslator", - "export_model_json_to_solidworks_step", - "translate_model_json_to_solidworks_script", - "translate_model_json_to_solidworks_step", + "translate_product_package_to_solidworks_script", ] diff --git a/src/simplecadapi/translator/solidworks_translator/api.py b/src/simplecadapi/translator/solidworks_translator/api.py index 44d62527..adc0abb1 100644 --- a/src/simplecadapi/translator/solidworks_translator/api.py +++ b/src/simplecadapi/translator/solidworks_translator/api.py @@ -1,56 +1,29 @@ -"""Public SolidWorks translator entrypoints.""" +"""Public SolidWorks product translator entrypoint.""" from __future__ import annotations -from typing import Optional - -from .compiler import translate_model_json_to_solidworks_step as _export_step +from ..package_units import ProductPackageInput from .translator import SolidWorksTranslator -def translate_model_json_to_solidworks_script( - json_str: str, - document_name: str = "SimpleCADModel", +def translate_product_package_to_solidworks_script( + data: ProductPackageInput, + document_name: str = "SimpleCADProduct", *, - output_path: Optional[str] = None, + output_path: str | None = None, visible: bool = False, source_kernel_fallback: bool = False, ) -> str: - """Translate canonical model JSON into a SolidWorks automation script.""" + """Translate one validated `.scadpkg` closure into SolidWorks automation.""" - return SolidWorksTranslator( + artifact = SolidWorksTranslator( document_name=document_name, output_path=output_path, visible=visible, source_kernel_fallback=source_kernel_fallback, - ).translate_model_json_to_script(json_str) + ).translate_product_package(data) + assert isinstance(artifact.content, str) + return artifact.content -def export_model_json_to_solidworks_step( - json_str: str, - output_path: str, - *, - document_name: str = "SimpleCADModel", - visible: bool = False, - python_exe: Optional[str] = None, - source_kernel_fallback: bool = False, -) -> str: - """Execute SolidWorks COM automation and export a STEP file.""" - - return _export_step( - json_str, - output_path, - document_name=document_name, - visible=visible, - python_exe=python_exe, - source_kernel_fallback=source_kernel_fallback, - ) - - -translate_model_json_to_solidworks_step = export_model_json_to_solidworks_step - -__all__ = [ - "export_model_json_to_solidworks_step", - "translate_model_json_to_solidworks_script", - "translate_model_json_to_solidworks_step", -] +__all__ = ["translate_product_package_to_solidworks_script"] diff --git a/src/simplecadapi/translator/solidworks_translator/capabilities.py b/src/simplecadapi/translator/solidworks_translator/capabilities.py index 9becbbc4..58608106 100644 --- a/src/simplecadapi/translator/solidworks_translator/capabilities.py +++ b/src/simplecadapi/translator/solidworks_translator/capabilities.py @@ -16,6 +16,10 @@ from ..types import ( BACKEND_NAME = "solidworks" _GEOMETRY_OPS = { + "make_box_rsolid", + "make_cylinder_rsolid", + "make_cone_rsolid", + "make_sphere_rsolid", "make_line_redge", "make_circle_redge", "make_three_point_arc_redge", @@ -50,6 +54,7 @@ _PRODUCT_OPS = { "make_assign_material_rpart", "make_assembly_rassembly", "make_add_component_rassembly", + "evaluate_assembly_definition", "make_place_component_rassembly", "make_compound_from_assembly_rcompound", "make_face_connector_rconnector", @@ -66,6 +71,7 @@ _PRODUCT_OPS = { "make_revolute_constraint_rassembly", "make_prismatic_constraint_rassembly", "make_solve_assembly_constraints_rassembly", + "apply_tag_rselection", } OP_SUPPORT: Dict[str, OperationCapability] = { @@ -95,7 +101,7 @@ for _op in _PRODUCT_OPS: CAPABILITIES = BackendCapabilities( backend_id=BACKEND_NAME, display_name="SolidWorks", - input_schema_versions=("2.0",), + input_schema_versions=("product-package-2.0",), targets=( TranslationTarget( target_id="solidworks_script", @@ -110,19 +116,6 @@ CAPABILITIES = BackendCapabilities( "source_kernel_fallback", ), ), - TranslationTarget( - target_id="step", - output_kind=TranslationOutputKind.FILE, - media_type="model/step", - extensions=(".step", ".stp"), - requires_external_runtime=True, - option_names=( - "document_name", - "visible", - "python_exe", - "source_kernel_fallback", - ), - ), ), operations=OP_SUPPORT, ) diff --git a/src/simplecadapi/translator/solidworks_translator/compiler.py b/src/simplecadapi/translator/solidworks_translator/compiler.py index 64fe8ad9..8641cffc 100644 --- a/src/simplecadapi/translator/solidworks_translator/compiler.py +++ b/src/simplecadapi/translator/solidworks_translator/compiler.py @@ -15,7 +15,6 @@ import json import os import pprint import re -import sys import tempfile import zlib from typing import Any, Dict, List, Optional, Sequence, Set, Tuple @@ -28,13 +27,8 @@ from OCP.STEPControl import STEPControl_AsIs, STEPControl_Writer from OCP.TopAbs import TopAbs_SOLID from OCP.gp import gp_Ax2, gp_Dir, gp_Pnt -from ...errors import raise_harness_error from ...operations import _make_geo_selector -from ...serializer import ( - _execute_graph, - _resolve_shape_from_geo_selector, - import_model_json, -) +from ...serializer import _execute_graph, _resolve_shape_from_geo_selector from ...topology import OperationGraph @@ -184,9 +178,7 @@ def _dominant_result_node_id( if has_one_detail_result: detail_node_id = next( - node_id - for node_id, op in zip(node_ids, ops) - if op in detail_ops + node_id for node_id, op in zip(node_ids, ops) if op in detail_ops ) volume_by_id = { node_id: volume for node_id, _shape, volume in positive_shapes @@ -260,10 +252,12 @@ def _canonical_union_passthroughs(graph: OperationGraph) -> Dict[str, int]: if output_descriptor is None: continue output_bbox, output_volume = output_descriptor - bbox_size = sum( - (output_bbox[index + 3] - output_bbox[index]) ** 2 - for index in range(3) - ) ** 0.5 + bbox_size = ( + sum( + (output_bbox[index + 3] - output_bbox[index]) ** 2 for index in range(3) + ) + ** 0.5 + ) bbox_tolerance = max(1.0e-7, bbox_size * 1.0e-7) volume_tolerance = max(1.0e-9, abs(output_volume) * 1.0e-8) matches: List[int] = [] @@ -272,10 +266,13 @@ def _canonical_union_passthroughs(graph: OperationGraph) -> Dict[str, int]: if input_descriptor is None: continue input_bbox, input_volume = input_descriptor - bbox_error = sum( - (actual - expected) ** 2 - for actual, expected in zip(input_bbox, output_bbox) - ) ** 0.5 + bbox_error = ( + sum( + (actual - expected) ** 2 + for actual, expected in zip(input_bbox, output_bbox) + ) + ** 0.5 + ) if ( bbox_error <= bbox_tolerance and abs(input_volume - output_volume) <= volume_tolerance @@ -287,10 +284,7 @@ def _canonical_union_passthroughs(graph: OperationGraph) -> Dict[str, int]: def _canonical_cut_descriptors(graph: OperationGraph) -> Dict[str, Dict[str, Any]]: - node_ids = [ - node.node_id for node in graph.nodes - if node.op == "make_cut_rsolid" - ] + node_ids = [node.node_id for node in graph.nodes if node.op == "make_cut_rsolid"] if not node_ids: return {} try: @@ -321,10 +315,7 @@ def _canonical_cut_descriptors(graph: OperationGraph) -> Dict[str, Dict[str, Any def _canonical_union_descriptors(graph: OperationGraph) -> Dict[str, Dict[str, Any]]: - node_ids = [ - node.node_id for node in graph.nodes - if node.op == "make_union_rsolid" - ] + node_ids = [node.node_id for node in graph.nodes if node.op == "make_union_rsolid"] if not node_ids: return {} try: @@ -403,9 +394,7 @@ def _canonical_union_input_indices(graph: OperationGraph) -> Dict[str, List[int] try: common = BRepAlgoAPI_Common(output_shape, input_shape) common.Build() - common_volume = ( - shape_volume(common.Shape()) if common.IsDone() else 0.0 - ) + common_volume = shape_volume(common.Shape()) if common.IsDone() else 0.0 except Exception: common_volume = 0.0 if common_volume > max(1.0e-10, input_volume * 1.0e-8): @@ -416,10 +405,7 @@ def _canonical_union_input_indices(graph: OperationGraph) -> Dict[str, List[int] def _canonical_loft_descriptors(graph: OperationGraph) -> Dict[str, Dict[str, Any]]: - loft_nodes = [ - node for node in graph.nodes - if node.op == "make_loft_rsolid" - ] + loft_nodes = [node for node in graph.nodes if node.op == "make_loft_rsolid"] node_ids = [node.node_id for node in loft_nodes] if not node_ids: return {} @@ -490,9 +476,7 @@ def _canonical_loft_descriptors(graph: OperationGraph) -> Dict[str, Dict[str, An def _canonical_sweep_descriptors(graph: OperationGraph) -> Dict[str, Dict[str, Any]]: sweep_ids = [ - str(node.node_id) - for node in graph.nodes - if node.op == "make_sweep_rsolid" + str(node.node_id) for node in graph.nodes if node.op == "make_sweep_rsolid" ] if not sweep_ids: return {} @@ -590,9 +574,7 @@ def _canonical_detail_edge_catalog( edges = [] for canonical_index, edge in enumerate(source_edges): try: - selector = dict( - _make_geo_selector(edge, source_shape=source_shape) - ) + selector = dict(_make_geo_selector(edge, source_shape=source_shape)) except Exception: continue selector.pop("metadata_geo", None) @@ -625,9 +607,7 @@ def _canonical_detail_edge_catalog( ) if not selector: raise RuntimeError("detail selector has no geometry") - selected_edge = _resolve_shape_from_geo_selector( - source_shape, selector - ) + selected_edge = _resolve_shape_from_geo_selector(source_shape, selector) selected_indices.append( next( index @@ -715,19 +695,13 @@ def _source_kernel_result_step_payload( and BRepCheck_Analyzer(wrapped).IsValid() ) if not source_valid: - if ( - node is None - or node.op != "make_chamfer_rsolid" - or not node.inputs - ): + if node is None or node.op != "make_chamfer_rsolid" or not node.inputs: return None source_id = str(node.inputs[0].node_id) source_result = source_cache.get(source_id) if source_result is None: try: - source_results = _execute_graph( - graph, [source_id], strict=True - ) + source_results = _execute_graph(graph, [source_id], strict=True) except Exception: continue if len(source_results) != 1: @@ -800,26 +774,6 @@ class SolidWorksScriptTranslator: self._result_state_node_ids: Dict[str, List[str]] = {} self._active_result_state: Optional[str] = None - def translate_model_json_to_script( - self, - json_str: str, - *, - output_path: Optional[str] = None, - ) -> str: - payload = import_model_json(json_str) - graph = payload.get("graph") - if not isinstance(graph, OperationGraph): - raise ValueError( - "SolidWorks translation requires model JSON with a canonical low-level graph" - ) - if graph.node_count == 0: - raise ValueError( - "SolidWorks translation requires model JSON with a non-empty canonical low-level graph" - ) - return self.translate_model_payload_to_script( - payload, graph=graph, output_path=output_path - ) - def translate_model_payload_to_script( self, payload: Dict[str, Any], @@ -884,11 +838,9 @@ class SolidWorksScriptTranslator: separators=(",", ":"), sort_keys=True, ).encode("ascii") - payload_dict["solidworks_detail_edge_catalog_z"] = ( - base64.b64encode( - zlib.compress(catalog_json, level=9) - ).decode("ascii") - ) + payload_dict["solidworks_detail_edge_catalog_z"] = base64.b64encode( + zlib.compress(catalog_json, level=9) + ).decode("ascii") return ( "from __future__ import annotations\n" @@ -915,9 +867,7 @@ class SolidWorksScriptTranslator: f"ACTIVE_RESULT_STATE = {_py_literal(self._active_result_state)}\n" f"RESULT_NODE_IDS = {_py_literal(self._result_node_id_list)}\n" f"OUTPUT_PATH = {_json_ascii(os.path.abspath(output_path)) if output_path else 'None'}\n" - "\n" - + self._runtime_helpers() - + "\n" + "\n" + self._runtime_helpers() + "\n" "def main():\n" " pythoncom.CoInitialize()\n" " runtime = None\n" @@ -970,8 +920,7 @@ class SolidWorksScriptTranslator: "op": str(node.op), "params": self._sanitize_payload_for_solidworks(params), "inputs": [ - {"node_id": str(input_ref.node_id)} - for input_ref in node.inputs + {"node_id": str(input_ref.node_id)} for input_ref in node.inputs ], } ) @@ -4424,6 +4373,128 @@ class SimpleCADSolidWorksRuntime: params = node.get('params') or {} node_id = str(node.get('node_id')) inputs = self._input_ids(node) + if op == 'make_box_rsolid': + width = float(params.get('width', 0.0)) + height = float(params.get('height', 0.0)) + depth = float(params.get('depth', 0.0)) + center = _v3(params.get('bottom_face_center') or (0.0, 0.0, 0.0)) + x0, x1 = center[0] - width * 0.5, center[0] + width * 0.5 + y0, y1 = center[1] - height * 0.5, center[1] + height * 0.5 + z = center[2] + points = [(x0, y0, z), (x1, y0, z), (x1, y1, z), (x0, y1, z)] + edges = [ + {'kind': 'edge', 'type': 'line', 'start': points[index], 'end': points[(index + 1) % 4]} + for index in range(4) + ] + profile = { + 'kind': 'face', + 'outer': {'kind': 'wire', 'edges': edges}, + 'inners': [], + 'normal': (0.0, 0.0, 1.0), + } + body = self._extrude_profile( + profile, {'direction': (0.0, 0.0, 1.0), 'distance': depth}, node_id + ) + return self._set_output(node, {'kind': 'body', 'body': body}) + if op == 'make_cylinder_rsolid': + center = _v3(params.get('bottom_face_center') or (0.0, 0.0, 0.0)) + axis = _unit(params.get('axis') or (0.0, 0.0, 1.0)) + radius = float(params.get('radius', 0.0)) + profile = { + 'kind': 'face', + 'outer': { + 'kind': 'wire', + 'edges': [{ + 'kind': 'edge', + 'type': 'circle', + 'center': center, + 'radius': radius, + 'normal': axis, + }], + }, + 'inners': [], + 'normal': axis, + } + body = self._extrude_profile( + profile, + {'direction': axis, 'distance': float(params.get('height', 0.0))}, + node_id, + ) + return self._set_output(node, {'kind': 'body', 'body': body}) + if op == 'make_cone_rsolid': + bottom = _v3(params.get('bottom_face_center') or (0.0, 0.0, 0.0)) + axis = _unit(params.get('axis') or (0.0, 0.0, 1.0)) + top = _add(bottom, _mul(axis, float(params.get('height', 0.0)))) + radial, _unused = _plane_axes(axis) + bottom_outer = _add( + bottom, _mul(radial, float(params.get('bottom_radius', 0.0))) + ) + top_outer = _add( + top, _mul(radial, float(params.get('top_radius', 0.0))) + ) + points = [bottom, bottom_outer, top_outer, top] + compact_points = [] + for point in points: + if not compact_points or _distance(point, compact_points[-1]) > 1.0e-12: + compact_points.append(point) + edges = [ + { + 'kind': 'edge', + 'type': 'line', + 'start': compact_points[index], + 'end': compact_points[(index + 1) % len(compact_points)], + } + for index in range(len(compact_points)) + ] + profile = { + 'kind': 'face', + 'outer': {'kind': 'wire', 'edges': edges}, + 'inners': [], + 'normal': _unit(_cross(axis, radial)), + } + body = self._revolve_profile( + profile, {'origin': bottom, 'axis': axis, 'angle': 360.0}, node_id + ) + return self._set_output(node, {'kind': 'body', 'body': body}) + if op == 'make_sphere_rsolid': + center = _v3(params.get('center') or (0.0, 0.0, 0.0)) + radius = float(params.get('radius', 0.0)) + axis = (0.0, 0.0, 1.0) + radial = (1.0, 0.0, 0.0) + lower = _sub(center, _mul(axis, radius)) + outer = _add(center, _mul(radial, radius)) + upper = _add(center, _mul(axis, radius)) + profile = { + 'kind': 'face', + 'outer': { + 'kind': 'wire', + 'edges': [ + { + 'kind': 'edge', + 'type': 'three_point_arc', + 'start': lower, + 'middle': outer, + 'end': upper, + }, + {'kind': 'edge', 'type': 'line', 'start': upper, 'end': lower}, + ], + }, + 'inners': [], + 'normal': (0.0, 1.0, 0.0), + } + body = self._revolve_profile( + profile, {'origin': center, 'axis': axis, 'angle': 360.0}, node_id + ) + return self._set_output(node, {'kind': 'body', 'body': body}) + if op == 'apply_tag_rselection': + value = self._first_output(inputs[0]) + if isinstance(value, dict): + value = dict(value) + value.setdefault('tag_bindings', []).append( + dict(params.get('tag_binding') or {}) + ) + return self._set_output(node, value) + if op == 'make_line_redge': return self._set_output(node, {'kind': 'edge', 'type': 'line', 'start': _v3(params.get('start')), 'end': _v3(params.get('end'))}) @@ -4949,6 +5020,27 @@ class SimpleCADSolidWorksRuntime: assembly['components'] = components self.product_values[node_id] = assembly return self._set_output(node, assembly) + if op == 'evaluate_assembly_definition': + assembly = dict(self._first_output(inputs[0])) + placements = { + str(record.get('instance_id') or ''): { + 'kind': 'placement', + 'params': dict(record.get('placement') or {}), + } + for record in (params.get('component_placements') or []) + if isinstance(record, dict) + } + components = [] + for component in assembly.get('components') or []: + component = dict(component) + component_id = str(component.get('component_id') or '') + if component_id in placements: + component['placement'] = placements[component_id] + components.append(component) + assembly['components'] = components + assembly['evaluation'] = params + self.product_values[node_id] = assembly + return self._set_output(node, assembly) if op == 'make_compound_from_assembly_rcompound': bodies = self._materialize_product_bodies( self._first_output(inputs[0]), @@ -10762,107 +10854,3 @@ class SimpleCADSolidWorksRuntime: ] return resolved if len(resolved) == len(result_names) else final_bodies ''' - - -def translate_model_json_to_solidworks_script( - json_str: str, - document_name: str = "SimpleCADModel", - *, - output_path: Optional[str] = None, - visible: bool = False, - source_kernel_fallback: bool = False, -) -> str: - """Translate exported model JSON into a SolidWorks Python automation script. - - The generated script traverses the canonical operation graph and maps graph - operations to SolidWorks COM API calls. Detail-feature selections use - geometric signatures rather than stored topology indices. - """ - - return SolidWorksScriptTranslator( - document_name=document_name, - visible=visible, - source_kernel_fallback=source_kernel_fallback, - ).translate_model_json_to_script(json_str, output_path=output_path) - - -def translate_model_json_to_solidworks_step( - json_str: str, - output_path: str, - *, - document_name: str = "SimpleCADModel", - visible: bool = False, - python_exe: Optional[str] = None, - source_kernel_fallback: bool = False, -) -> str: - """Run SolidWorks COM automation and export a STEP file.""" - - import subprocess - - resolved_output_path = os.path.abspath(output_path) - script = translate_model_json_to_solidworks_script( - json_str, - document_name=document_name, - output_path=resolved_output_path, - visible=visible, - source_kernel_fallback=source_kernel_fallback, - ) - - with tempfile.NamedTemporaryFile( - mode="w", suffix="_simplecad_solidworks_export.py", delete=False, encoding="utf-8" - ) as handle: - temp_script_path = handle.name - handle.write(script) - - env = os.environ.copy() - src_root = os.path.abspath( - os.path.join(os.path.dirname(__file__), "..", "..", "..") - ) - env["PYTHONPATH"] = ( - src_root - if not env.get("PYTHONPATH") - else src_root + os.pathsep + env["PYTHONPATH"] - ) - - try: - try: - completed = subprocess.run( - [python_exe or sys.executable, temp_script_path], - check=True, - text=True, - capture_output=True, - env=env, - ) - except subprocess.CalledProcessError as exc: - raise RuntimeError( - "SolidWorks export script failed. " - f"stdout={exc.stdout!r} stderr={exc.stderr!r}" - ) from exc - if not os.path.exists(resolved_output_path) or os.path.getsize(resolved_output_path) <= 0: - raise RuntimeError( - "SolidWorks export completed without creating a non-empty STEP file. " - f"stdout={completed.stdout.strip()!r} stderr={completed.stderr.strip()!r}" - ) - return output_path - except Exception as e: - raise_harness_error( - operation="translate_model_json_to_solidworks_step", - what_happened="Failed to execute the generated SolidWorks export script.", - possible_causes=[ - "SolidWorks is not installed, not licensed, or its COM server is not registered.", - "pywin32 is unavailable in the Python interpreter used for the export.", - "The model JSON contains an operation not yet mapped to a stable SolidWorks COM call.", - "SolidWorks rejected a native feature, geometric selection, body boolean, or STEP SaveAs call.", - ], - how_to_fix=[ - "Open SolidWorks once interactively and confirm it can create and save parts.", - "Inspect the generated script with translate_model_json_to_solidworks_script().", - "Run the same script manually with the same Python interpreter to inspect COM errors.", - ], - error=e, - ) - finally: - try: - os.unlink(temp_script_path) - except OSError: - pass diff --git a/src/simplecadapi/translator/solidworks_translator/script_translator.py b/src/simplecadapi/translator/solidworks_translator/script_translator.py deleted file mode 100644 index 7527f295..00000000 --- a/src/simplecadapi/translator/solidworks_translator/script_translator.py +++ /dev/null @@ -1,5 +0,0 @@ -"""Compatibility import for the contributed SolidWorks script compiler.""" - -from .compiler import SolidWorksScriptTranslator - -__all__ = ["SolidWorksScriptTranslator"] diff --git a/src/simplecadapi/translator/solidworks_translator/translator.py b/src/simplecadapi/translator/solidworks_translator/translator.py index a593886b..808c9df8 100644 --- a/src/simplecadapi/translator/solidworks_translator/translator.py +++ b/src/simplecadapi/translator/solidworks_translator/translator.py @@ -1,13 +1,15 @@ -"""SolidWorks backend facade for canonical model translation.""" +"""SolidWorks backend facade for validated product-package translation.""" from __future__ import annotations -from typing import Any, Dict, Optional, Sequence, Set +from typing import Any, Dict, Sequence, Set from ...errors import ErrorGuidance from ...topology import OperationGraph from ..base import BaseTranslator from ..errors import TranslationRequestError +from ..package_units import ProductPackageInput +from ..product_graph import build_product_graph_view from ..types import BackendCapabilities, SupportLevel, TranslationArtifact from .capabilities import CAPABILITIES from .compiler import SolidWorksScriptTranslator @@ -33,13 +35,13 @@ def _dependency_node_ids( class SolidWorksTranslator(BaseTranslator): - """Translate canonical model JSON into a SolidWorks COM Python script.""" + """Translate one validated `.scadpkg` closure into SolidWorks automation.""" def __init__( self, - document_name: str = "SimpleCADModel", + document_name: str = "SimpleCADProduct", *, - output_path: Optional[str] = None, + output_path: str | None = None, visible: bool = False, source_kernel_fallback: bool = False, ) -> None: @@ -52,16 +54,8 @@ class SolidWorksTranslator(BaseTranslator): def capabilities(self) -> BackendCapabilities: return CAPABILITIES - def _result_ids( - self, payload: Dict[str, Any], graph: OperationGraph - ) -> Sequence[str]: - leaf_ids = payload.get("leaf_ids") - if isinstance(leaf_ids, list) and leaf_ids: - return [str(node_id) for node_id in leaf_ids] - return [node.node_id for node in graph.leaf_nodes()] - - def _preflight(self, payload: Dict[str, Any], graph: OperationGraph) -> None: - needed = _dependency_node_ids(graph, self._result_ids(payload, graph)) + def _preflight(self, graph: OperationGraph, result_node_id: str) -> None: + needed = _dependency_node_ids(graph, [result_node_id]) unsupported = sorted( { node.op @@ -79,62 +73,53 @@ class SolidWorksTranslator(BaseTranslator): joined = ", ".join(unsupported) raise TranslationRequestError( "solidworks", - "translate_model_payload", + "translate_product_package", ErrorGuidance( - what_happened=f"The result graph uses unsupported SolidWorks operations: {joined}.", + what_happened=( + "The product package uses unsupported SolidWorks " + f"operations: {joined}." + ), possible_causes=( - "The model uses canonical operations not implemented by the contributed runtime.", + "A definition-owned Feature Graph uses operations not " + "implemented by the SolidWorks runtime." ), how_to_fix=( - "Lower the model to operations declared by solidworks_translator.CAPABILITIES.", - "Use another translator backend for this model.", + "Use operations declared by solidworks_translator.CAPABILITIES.", + "Use another translator backend for this product.", ), ), ) - def translate_model_payload_to_script( + def translate_product_package( self, - payload: Dict[str, Any], - *, - graph: Optional[OperationGraph] = None, - ) -> str: - source_graph = graph or payload.get("graph") - if not isinstance(source_graph, OperationGraph) or source_graph.node_count == 0: - raise ValueError( - "SolidWorks translation requires a non-empty canonical graph" - ) - self._preflight(payload, source_graph) - return SolidWorksScriptTranslator( + data: ProductPackageInput, + **_options: Any, + ) -> TranslationArtifact: + view = build_product_graph_view(data) + payload = view.model_payload() + self._preflight(view.graph, view.root_result_node_id) + script = SolidWorksScriptTranslator( document_name=self.document_name, visible=self.visible, source_kernel_fallback=self.source_kernel_fallback, ).translate_model_payload_to_script( payload, - graph=source_graph, + graph=view.graph, output_path=self.output_path, ) - - def translate_model_json_to_script(self, json_str: str) -> str: - artifact = self.translate_model_json(json_str) - assert isinstance(artifact.content, str) - return artifact.content - - def translate_model_payload( - self, - payload: Dict[str, Any], - *, - graph: Optional[OperationGraph] = None, - ) -> TranslationArtifact: return TranslationArtifact( backend_id="solidworks", target_id="solidworks_script", media_type="text/x-python", suggested_suffix=".py", - content=self.translate_model_payload_to_script(payload, graph=graph), + content=script, metadata={ "document_name": self.document_name, "output_path": self.output_path, "visible": self.visible, + "root_definition_id": view.root_definition_id, + "root_definition_kind": view.root_definition_kind, + "definition_ids": view.definition_ids, "source_kernel_fallback": self.source_kernel_fallback, "target_runtime_validated": False, }, diff --git a/test/fixtures/scene-contract/corpus.json b/test/fixtures/scene-contract/corpus.json index 8987784f..815a4db6 100644 --- a/test/fixtures/scene-contract/corpus.json +++ b/test/fixtures/scene-contract/corpus.json @@ -3054,7 +3054,7 @@ "appearances": 25000, "assets_per_kind": 25000, "cameras": 1000, - "canonical_archive_bytes": 268435456, + "canonical_archive_bytes": 536870912, "compression_ratio": 100, "connectors": 100000, "definitions": 25000, @@ -3063,7 +3063,7 @@ "entity_json_bytes": 67108864, "forwarded_connector_depth": 64, "hierarchy_depth": 256, - "input_archive_bytes": 268435456, + "input_archive_bytes": 536870912, "json_depth": 64, "json_string_bytes": 1048576, "line_segments_per_asset": 2000000, @@ -3072,7 +3072,7 @@ "line_vertices_total": 10000000, "model_json_bytes": 67108864, "nodes": 100000, - "one_member_bytes": 268435456, + "one_member_bytes": 536870912, "presentation_json_bytes": 8388608, "scene_json_bytes": 33554432, "static_decoded_buffer_bytes": 536870912, diff --git a/test/test_all_features.py b/test/test_all_features.py index dd655c5e..da433a5d 100644 --- a/test/test_all_features.py +++ b/test/test_all_features.py @@ -722,91 +722,6 @@ class TestCoordinateSystem(unittest.TestCase): self.assertTrue(np.allclose(placement.origin, [15.0, 26.0, 26.0], atol=1e-9)) -class TestExport(unittest.TestCase): - """Tests for export functionality.""" - - def setUp(self): - self.temp_dir = tempfile.mkdtemp() - self.box = scad.make_box_rsolid(1.0, 1.0, 1.0) - - def tearDown(self): - shutil.rmtree(self.temp_dir) - - def test_export_stl(self): - """Test export STL.""" - stl_path = os.path.join(self.temp_dir, "test.stl") - try: - scad.export_stl(self.box, stl_path) - # 检查文件是否创建 - self.assertTrue(os.path.exists(stl_path)) - # 检查文件是否有内容 - self.assertGreater(os.path.getsize(stl_path), 0) - except Exception as e: - self.skipTest(f"STL export not fully implemented: {e}") - - def test_export_step(self): - """Test export STEP.""" - step_path = os.path.join(self.temp_dir, "test.step") - try: - scad.export_step(self.box, step_path) - # 检查文件是否创建 - self.assertTrue(os.path.exists(step_path)) - # 检查文件是否有内容 - self.assertGreater(os.path.getsize(step_path), 0) - except Exception as e: - self.skipTest(f"STEP export not fully implemented: {e}") - - def test_export_multiple_shapes(self): - """Test export multiple shapes.""" - box1 = scad.make_box_rsolid(1.0, 1.0, 1.0) - box2 = scad.make_box_rsolid(0.5, 0.5, 0.5, bottom_face_center=(2, 0, 0)) - stl_path = os.path.join(self.temp_dir, "multiple.stl") - - try: - scad.export_stl([box1, box2], stl_path) - # 检查文件是否创建 - self.assertTrue(os.path.exists(stl_path)) - # 检查文件是否有内容 - self.assertGreater(os.path.getsize(stl_path), 0) - except Exception as e: - self.skipTest(f"Multiple shapes export not fully implemented: {e}") - - def test_export_nested_shape_list(self): - """Test export nested shape list.""" - box = scad.make_box_rsolid(0.8, 0.8, 0.8) - cylinder = scad.make_cylinder_rsolid(0.4, 1.0) - sphere = scad.make_sphere_rsolid(0.5) - - nested_shapes = [box, [cylinder, sphere]] - step_path = os.path.join(self.temp_dir, "nested.step") - - try: - scad.export_step(nested_shapes, step_path) - self.assertTrue(os.path.exists(step_path)) - self.assertGreater(os.path.getsize(step_path), 0) - except Exception as e: - self.skipTest(f"Nested shapes export not fully implemented: {e}") - - def test_export_step_multiple_solids_single_file(self): - """Test export STEP multiple solids single file.""" - box1 = scad.make_box_rsolid(1.0, 1.0, 1.0) - box2 = scad.make_box_rsolid(0.7, 0.7, 0.7, bottom_face_center=(2.0, 0, 0)) - step_path = os.path.join(self.temp_dir, "assembly_like.step") - - try: - scad.export_step([box1, box2], step_path) - self.assertTrue(os.path.exists(step_path)) - self.assertGreater(os.path.getsize(step_path), 0) - - with open(step_path, "r", encoding="utf-8", errors="ignore") as f: - step_text = f.read() - - # STEP文本中每个实体通常对应一个MANIFOLD_SOLID_BREP定义 - self.assertGreaterEqual(step_text.count("MANIFOLD_SOLID_BREP"), 2) - except Exception as e: - self.skipTest( - f"Multiple solids in one STEP export not fully implemented: {e}" - ) class TestComplexExamples(unittest.TestCase): diff --git a/test/test_ap242_gmsh_example.py b/test/test_ap242_gmsh_example.py new file mode 100644 index 00000000..35063a40 --- /dev/null +++ b/test/test_ap242_gmsh_example.py @@ -0,0 +1,165 @@ +"""Contract tests for the optional AP242-to-Gmsh volume mesh example.""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +EXAMPLE = ROOT / "examples" / "12_ap242_gmsh_volume_mesh.py" + + +def _load_example(): + spec = importlib.util.spec_from_file_location("ap242_gmsh_example", EXAMPLE) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + import sys + + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +class _Option: + def __init__(self): + self.strings = [] + self.numbers = [] + + def setString(self, name, value): + self.strings.append((name, value)) + + def setNumber(self, name, value): + self.numbers.append((name, value)) + + +class _Occ: + def __init__(self): + self.imported = [] + self.synchronized = False + + def importShapes(self, path): + self.imported.append(path) + return [(3, 9)] + + def synchronize(self): + self.synchronized = True + + +class _Mesh: + def __init__(self, *, fail=False): + self.generated = [] + self.fail = fail + + def generate(self, dimension): + self.generated.append(dimension) + if self.fail: + raise RuntimeError("mesh failure") + + def getNodes(self): + return [1, 2, 3, 4], [0.0] * 12, [] + + def getElements(self, dimension): + return [4], [[20, 21]], [[1, 2, 3, 4, 1, 2, 3, 4]] + + +class _Model: + def __init__(self, *, fail=False): + self.occ = _Occ() + self.mesh = _Mesh(fail=fail) + self.models = [] + self.physical_groups = [] + self.physical_names = [] + + def add(self, name): + self.models.append(name) + + def getEntities(self, dimension): + return [(3, 9)] if dimension == 3 else [] + + def addPhysicalGroup(self, dimension, tags): + self.physical_groups.append((dimension, tags)) + return 7 + + def setPhysicalName(self, dimension, tag, name): + self.physical_names.append((dimension, tag, name)) + + +class _Gmsh: + def __init__(self, *, fail=False): + self.option = _Option() + self.model = _Model(fail=fail) + self.initialized = 0 + self.finalized = 0 + self.written = [] + + def initialize(self): + self.initialized += 1 + + def finalize(self): + self.finalized += 1 + + def write(self, path): + self.written.append(path) + Path(path).write_text( + "$MeshFormat\n4.1 0 8\n$EndMeshFormat\n", encoding="ascii" + ) + + +class TestAP242GmshExample(unittest.TestCase): + def test_example_import_does_not_require_gmsh(self): + module = _load_example() + + self.assertTrue(callable(module.build_bracket)) + self.assertTrue(callable(module.mesh_step_with_gmsh)) + self.assertEqual(module.OUT_DIR.name, "ap242_gmsh_volume_mesh") + + def test_mesh_step_uses_occ_volume_mesh_and_reports_counts(self): + module = _load_example() + gmsh = _Gmsh() + with tempfile.TemporaryDirectory() as tmp_dir: + root = Path(tmp_dir) + step = root / "part.step" + step.write_text("STEP", encoding="ascii") + mesh = root / "part.msh" + report = module.mesh_step_with_gmsh( + step, + mesh, + mesh_size=1.25, + gmsh_module=gmsh, + ) + + self.assertEqual(gmsh.initialized, 1) + self.assertEqual(gmsh.finalized, 1) + self.assertEqual(gmsh.option.strings, [("Geometry.OCCTargetUnit", "MM")]) + self.assertEqual( + gmsh.option.numbers, + [("Mesh.MeshSizeMin", 1.25), ("Mesh.MeshSizeMax", 1.25)], + ) + self.assertEqual(gmsh.model.mesh.generated, [3]) + self.assertEqual(gmsh.model.physical_groups, [(3, [9])]) + self.assertEqual(report.volume_count, 1) + self.assertEqual(report.node_count, 4) + self.assertEqual(report.element_count, 2) + + def test_gmsh_is_finalized_when_meshing_fails(self): + module = _load_example() + gmsh = _Gmsh(fail=True) + with tempfile.TemporaryDirectory() as tmp_dir: + step = Path(tmp_dir) / "part.step" + step.write_text("STEP", encoding="ascii") + with self.assertRaisesRegex(RuntimeError, "mesh failure"): + module.mesh_step_with_gmsh( + step, + Path(tmp_dir) / "part.msh", + gmsh_module=gmsh, + ) + + self.assertEqual(gmsh.initialized, 1) + self.assertEqual(gmsh.finalized, 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/test_artifact_contract.py b/test/test_artifact_contract.py index 5c1eecd0..383aec3a 100644 --- a/test/test_artifact_contract.py +++ b/test/test_artifact_contract.py @@ -1,8 +1,10 @@ import json from copy import deepcopy +from pathlib import Path import pytest +import simplecadapi as scad from simplecadapi.artifacts.assembly_definition import AssemblyDefinition from simplecadapi.artifacts.canonical import ( ArtifactValidationError, @@ -11,6 +13,10 @@ from simplecadapi.artifacts.canonical import ( sha256_bytes, validate_relative_path, ) +from simplecadapi.artifacts.feature_graph import ( + capture_feature_graph, + encode_feature_graph_artifact, +) from simplecadapi.artifacts.part_definition import PartDefinition from simplecadapi.artifacts.references import BlobRef, InterfaceHashes from simplecadapi.artifacts.validation import ( @@ -33,12 +39,36 @@ EMPTY_HASH = content_hash({}, omit=()) def _blob(path, payload, media_type): return BlobRef(path, sha256_bytes(payload), len(payload), media_type) +def _feature_graph_blob(definition_id: str, definition_kind: str): + with scad.GraphSession(graph_id=definition_id) as session: + body = scad.make_box_rsolid(width=1.0, height=1.0, depth=1.0) + session.capture_result(value=body) + artifact = capture_feature_graph( + session=session, + owner_definition_kind=definition_kind, + owner_definition_id=definition_id, + owner_revision="r1", + project_root=Path(__file__).resolve().parents[1], + ) + payload = encode_feature_graph_artifact(artifact) + path = ( + "features/" + + artifact.content_hash.removeprefix("sha256:") + + ".feature-graph.zip" + ) + return _blob( + path, + payload, + "application/vnd.simplecad.feature-graph+zip", + ), payload + def _part_definition(): - model = canonical_bytes({"model": "fixture"}) + feature_ref, feature_payload = _feature_graph_blob( + "fixture_part", "single_solid" + ) body = b"fixture-brep" topology = canonical_bytes({"topology": "fixture"}) - model_ref = _blob("model/model.json", model, "application/json") body_ref = _blob("body/body.brep", body, "application/vnd.opencascade.brep") topology_ref = _blob("topology/snapshot.json", topology, "application/json") return PartDefinition( @@ -46,7 +76,7 @@ def _part_definition(): revision="r1", tolerance_profile="simplecad-default", generator=GENERATOR, - model_ref=model_ref, + feature_graph_ref=feature_ref, solid_cache_ref=body_ref, topology_snapshot_ref=topology_ref, connectors=(), @@ -58,11 +88,18 @@ def _part_definition(): bindings={}, material=None, ), - blobs={model_ref.path: model, body_ref.path: body, topology_ref.path: topology}, + blobs={ + feature_ref.path: feature_payload, + body_ref.path: body, + topology_ref.path: topology, + }, ) def _assembly_definition(): + feature_ref, feature_payload = _feature_graph_blob( + "fixture_assembly", "assembly" + ) return AssemblyDefinition( definition_id="fixture_assembly", revision="r1", @@ -79,7 +116,9 @@ def _assembly_definition(): bindings={}, material=None, ), + feature_graph_ref=feature_ref, solved_snapshot={"component_placements": []}, + blobs={feature_ref.path: feature_payload}, ) diff --git a/test/test_artifact_topology_snapshot.py b/test/test_artifact_topology_snapshot.py index fea62a61..d1281a7c 100644 --- a/test/test_artifact_topology_snapshot.py +++ b/test/test_artifact_topology_snapshot.py @@ -31,6 +31,23 @@ def test_topology_snapshot_restores_exact_semantic_state_after_brep_roundtrip(): assert scad.list_tags(restored) == scad.list_tags(source) +def test_topology_snapshot_restores_feature_output_lineage(): + with scad.GraphSession(graph_id="lineage_probe") as session: + source = scad.make_box_rsolid(2.0, 3.0, 4.0) + session.capture_result(value=source) + snapshot = capture_topology_snapshot(source) + restored = read_brep_solid(write_brep_bytes(source)) + + restore_topology_snapshot(restored, snapshot) + + assert {item["feature_output"]["node_id"] for item in snapshot["entities"]} == { + session.result_node_ids[0] + } + assert { + child._get_runtime("topo.ref").node_id for child in restored.get_children() + } == {session.result_node_ids[0]} + + def test_topology_snapshot_restores_fused_bearing_with_symmetric_wires(): bearing = scad.std.bearing.make_ball_bearing_rassembly( bore_diameter=16.0, diff --git a/test/test_assembly_builder.py b/test/test_assembly_builder.py index cb7fbf22..145e56eb 100644 --- a/test/test_assembly_builder.py +++ b/test/test_assembly_builder.py @@ -1,4 +1,5 @@ from __future__ import annotations +from copy import deepcopy from dataclasses import replace from pathlib import Path @@ -6,7 +7,15 @@ from pathlib import Path import pytest import simplecadapi as scad -from simplecadapi.artifacts.canonical import ArtifactValidationError, content_hash +from simplecadapi.artifacts.canonical import ( + ArtifactValidationError, + content_hash, + sha256_bytes, +) +from simplecadapi.artifacts.feature_graph import ( + FEATURE_GRAPH_MEDIA_TYPE, + capture_feature_graph, +) GENERATOR = { @@ -157,7 +166,10 @@ def test_assemble_external_reference_round_trip_preserves_hierarchy_and_coupling ] assert scad.inspect_assembly_constraints_rconstraintreport(train.value).solved - output = pair.export_definition(path=tmp_path / "pair.assembly-definition.zip") + output = scad.export_assembly_definition( + pair.definition, + tmp_path / "pair.assembly-definition.zip", + ) loaded = scad.load_assembly_definition(output) rebuilt = scad.materialize_definition(loaded) @@ -308,6 +320,30 @@ def test_assembly_loader_reports_cycle_with_instance_path(tmp_path: Path) -> Non content_hash="sha256:" + "1" * 64, byte_length=0, ) + with scad.GraphSession(graph_id="cycle_root") as session: + root = scad.make_assembly_rassembly(assembly_id="cycle_root") + session.capture_result(value=root) + feature_graph = capture_feature_graph( + session=session, + owner_definition_kind="assembly", + owner_definition_id="cycle_root", + owner_revision="r1", + project_root=Path(__file__).resolve().parents[1], + external_definitions=( + { + "definition_kind": cycle_ref.definition_kind, + "definition_id": cycle_ref.definition_id, + "revision": cycle_ref.revision, + "content_hash": cycle_ref.content_hash, + }, + ), + ) + feature_payload = scad.encode_feature_graph_artifact(feature_graph) + feature_path = ( + "features/" + + feature_graph.content_hash.removeprefix("sha256:") + + ".feature-graph.zip" + ) definition = scad.AssemblyDefinition( definition_id="cycle_root", revision="r1", @@ -331,6 +367,13 @@ def test_assembly_loader_reports_cycle_with_instance_path(tmp_path: Path) -> Non bindings={}, material=None, ), + feature_graph_ref=scad.BlobRef( + path=feature_path, + sha256=sha256_bytes(feature_payload), + byte_length=len(feature_payload), + media_type=FEATURE_GRAPH_MEDIA_TYPE, + ), + blobs={feature_path: feature_payload}, ) path = tmp_path / "cycle.assembly-definition.zip" path.write_bytes(scad.encode_assembly_definition(definition)) @@ -566,3 +609,87 @@ def test_nested_forwarded_connector_change_invalidates_parent_component( ) assert changed.solve_report.dirty_relations == ("nested_fixed",) assert scad.inspect_assembly_constraints_rconstraintreport(changed.value).solved + + +def test_assemble_owns_replayable_deterministic_feature_graph(tmp_path: Path) -> None: + policy = _policy(tmp_path / "cache") + + @scad.part(id="graph_child", cache=policy) + def build_child() -> scad.Part: + return scad.make_part_rpart( + part_id="graph_child", + body=scad.make_box_rsolid(width=2.0, height=3.0, depth=4.0), + ) + + child = build_child() + + @scad.assemble(id="graph_parent", definitions=(child,), cache=policy) + def build_parent() -> scad.Assembly: + assembly = scad.make_assembly_rassembly(assembly_id="graph_parent") + return scad.add_component_rassembly( + assembly=assembly, + item=child.value, + component_id="child", + placement=scad.identity_placement_rplacement(), + ) + + cold = build_parent() + warm = build_parent() + nodes = list(cold.feature_graph.graph["nodes"]) + reference_nodes = [item for item in nodes if item["op"] == "reference_definition"] + terminal_nodes = [ + item for item in nodes if item["op"] == "evaluate_assembly_definition" + ] + + assert cold.feature_graph.owner_definition_kind == "assembly" + assert cold.feature_graph.owner_definition_id == "graph_parent" + assert cold.feature_graph.external_definitions == ( + { + "definition_kind": child.definition.definition_kind, + "definition_id": child.definition.definition_id, + "revision": child.definition.revision, + "content_hash": child.definition.content_hash, + }, + ) + assert len(reference_nodes) == 1 + assert reference_nodes[0]["params"]["definition_id"] == "graph_child" + assert len(terminal_nodes) == 1 + assert cold.feature_graph.result_node_ids == (terminal_nodes[0]["node_id"],) + assert cold.feature_graph.canonical_bytes == warm.feature_graph.canonical_bytes + + archived = scad.load_feature_graph_artifact( + cold.definition.blobs[cold.definition.feature_graph_ref.path] + ) + assert archived.canonical_bytes == cold.feature_graph.canonical_bytes + replayed = cold.replay() + assert replayed.component_ids() == ("child",) + assert replayed.get_component("child").item.part_id == "graph_child" + + +def test_assembly_feature_replay_tolerates_only_solver_scale_residual_drift( + tmp_path: Path, +) -> None: + _base, _gear, train, _pair = _build_nested_gear_train(tmp_path) + external_definitions = train.definition.resolved_definitions + + def with_translation_drift(drift: float): + graph = deepcopy(dict(train.feature_graph.graph)) + terminal = next( + node + for node in graph["nodes"] + if node["op"] == "evaluate_assembly_definition" + ) + terminal["params"]["constraint_report"]["residuals"][0][ + "translation_error" + ] += drift + return replace(train.feature_graph, graph=graph, content_hash="") + + replayed = with_translation_drift(5.0e-8).replay( + external_definitions=external_definitions + ) + assert replayed[0].assembly_id == "gear_train" + + with pytest.raises(ValueError, match="residual report differs"): + with_translation_drift(2.0e-7).replay( + external_definitions=external_definitions + ) diff --git a/test/test_auto_docs_gen.py b/test/test_auto_docs_gen.py index c42c8bc4..abbe3703 100644 --- a/test/test_auto_docs_gen.py +++ b/test/test_auto_docs_gen.py @@ -105,6 +105,7 @@ class TestAutoDocsGenPathResolution(unittest.TestCase): backend_root.mkdir(parents=True) (backend_root / "api.py").write_text("", encoding="utf-8") (backend_root / "translator.py").write_text("", encoding="utf-8") + (backend_root / "types.py").write_text("", encoding="utf-8") resolved = auto_docs_gen._default_source_files(package_root) @@ -122,6 +123,10 @@ class TestAutoDocsGenPathResolution(unittest.TestCase): "translator/freecad_translator/translator.py", resolved_names, ) + self.assertIn( + "translator/freecad_translator/types.py", + resolved_names, + ) self.assertIn("inspect/brep/inspect.py", resolved_names) self.assertIn("inspect/brep/queries.py", resolved_names) @@ -138,6 +143,7 @@ class TestAutoDocsGenPathResolution(unittest.TestCase): self.assertIn("build/assembly_builder.py", resolved_names) self.assertIn("build/dependencies.py", resolved_names) self.assertIn("build/results.py", resolved_names) + self.assertIn("capture.py", resolved_names) self.assertIn("cache/policy.py", resolved_names) self.assertIn("cache/store.py", resolved_names) @@ -152,6 +158,8 @@ class TestAutoDocsGenPathResolution(unittest.TestCase): ) names = {api.name for api in generator.extract_apis()} for name in ( + "capture", + "CaptureResult", "assemble", "file_input", "part", @@ -201,7 +209,7 @@ class TestAutoDocsGenPathResolution(unittest.TestCase): self.assertIn("## STEP/BREP Inspection", readme) self.assertIn("`inspection namespace`", readme) self.assertIn("from simplecadapi.inspect import brep", page) - self.assertIn("unavailable inside GraphSession/@model", page) + self.assertIn("unavailable inside GraphSession", page) def test_default_stdlib_source_files_include_standard_modules(self): with tempfile.TemporaryDirectory() as tmp_dir: diff --git a/test/test_example_model_contract.py b/test/test_example_model_contract.py index df1aecd2..977b0fb6 100644 --- a/test/test_example_model_contract.py +++ b/test/test_example_model_contract.py @@ -1,8 +1,7 @@ """Structural checks for the example model/session contract.""" -import ast +import runpy import importlib.util -import math import sys from pathlib import Path import unittest @@ -14,17 +13,6 @@ ROOT = Path(__file__).resolve().parents[1] EXAMPLES = ROOT / "examples" -def _model_files() -> tuple[Path, ...]: - return ( - EXAMPLES / "04_dimension_tolerance_chain.py", - EXAMPLES / "08_constrained_sketch.py", - EXAMPLES / "09_naca0016_blade_freecad.py", - EXAMPLES / "10_part_assembly.py", - EXAMPLES / "16_compact_two_stage_planetary_reducer" / "main.py", - EXAMPLES / "20_integrated_bldc_joint_actuator" / "main.py", - ) - - def _source_files() -> tuple[Path, ...]: return tuple( path @@ -33,15 +21,38 @@ def _source_files() -> tuple[Path, ...]: ) -def _is_decorator(node: ast.expr, name: str) -> bool: - if isinstance(node, ast.Call): - node = node.func - return ( - isinstance(node, ast.Attribute) - and isinstance(node.value, ast.Name) - and node.value.id == "scad" - and node.attr == name - ) or (isinstance(node, ast.Name) and node.id == name) +FORMAL_EXAMPLE_PACKAGES = { + "examples/04_dimension_tolerance_chain.py": ( + "examples/out/dimension_tolerance_chain/dimension_tolerance_chain.scadpkg" + ), + "examples/08_constrained_sketch.py": ( + "examples/out/constrained_sketch/constrained_sketch.scadpkg" + ), + "examples/09_naca0016_blade_freecad.py": ( + "examples/out/naca0016_blade/naca0016_blade.scadpkg" + ), + "examples/10_part_assembly.py": ( + "examples/out/hydraulic_rod_assembly/hydraulic_rod_assembly.scadpkg" + ), + "examples/11_external_reference_gear_train.py": ( + "examples/out/external_reference_gear_train/" + "nested_external_reference_gear_trains.scadpkg" + ), + "examples/12_ap242_gmsh_volume_mesh.py": ( + "examples/out/ap242_gmsh_volume_mesh/ap242_gmsh_bracket.scadpkg" + ), + "examples/7ep_caplcd_enclosure.py": ( + "examples/out/7ep_caplcd_enclosure/caplcd_enclosure_7ep.scadpkg" + ), + "examples/16_compact_two_stage_planetary_reducer/main.py": ( + "examples/out/compact_two_stage_planetary_reducer/" + "compact_two_stage_planetary_reducer.scadpkg" + ), + "examples/20_integrated_bldc_joint_actuator/main.py": ( + "examples/out/integrated_bldc_joint_actuator/" + "integrated_bldc_joint_actuator.scadpkg" + ), +} class TestExampleModelContract(unittest.TestCase): @@ -59,60 +70,30 @@ class TestExampleModelContract(unittest.TestCase): EXAMPLES / "out" / "hydraulic_rod_assembly", ) - def test_each_current_model_entry_has_one_explicit_result(self): - for path in _model_files(): - tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) - model_functions = [ - node - for node in tree.body - if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) - and any( - _is_decorator(decorator, "model") - for decorator in node.decorator_list - ) - ] - self.assertEqual(len(model_functions), 1, path) - self.assertFalse( - isinstance(model_functions[0], ast.AsyncFunctionDef), - f"async model entry is unsupported: {path}", - ) - capture_calls = [ - node - for node in ast.walk(tree) - if isinstance(node, ast.Call) - and isinstance(node.func, ast.Attribute) - and isinstance(node.func.value, ast.Name) - and node.func.value.id == "scad" - and node.func.attr == "capture_result" - ] - self.assertEqual(len(capture_calls), 1, path) + def test_every_formal_example_has_one_scadpkg_contract(self): + runner = runpy.run_path(str(ROOT / "tools" / "run_examples.py")) + cases = runner["CASES"] + actual = {case.path: case.package_path for case in cases} - def test_examples_do_not_own_manual_sessions_or_serialization(self): + self.assertEqual(actual, FORMAL_EXAMPLE_PACKAGES) + self.assertEqual(len(set(actual.values())), len(actual)) + self.assertTrue(all(path.endswith(".scadpkg") for path in actual.values())) + self.assertTrue(all(case.step_path.endswith(".step") for case in cases)) + self.assertTrue(all(case.fcstd_path.endswith(".FCStd") for case in cases)) + self.assertTrue( + all( + Path(case.step_path).stem == Path(case.package_path).stem + and Path(case.fcstd_path).stem == Path(case.package_path).stem + for case in cases + ) + ) + + def test_examples_do_not_use_removed_decorator_api(self): for path in _source_files(): source = path.read_text(encoding="utf-8") - self.assertNotIn("GraphSession(", source, path) - self.assertNotIn("export_model_json(", source, path) - self.assertNotIn("export_session_json(", source, path) - - def test_make_builders_require_the_active_session(self): - for path in _source_files(): - tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) - for node in ast.walk(tree): - if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): - continue - if not ( - node.name.startswith("make_") or node.name.startswith("_make_") - ): - continue - decorators = node.decorator_list - has_session_contract = any( - _is_decorator(decorator, "requires_session") - or _is_decorator(decorator, "model") - for decorator in decorators - ) - self.assertTrue( - has_session_contract, f"{path}:{node.lineno}:{node.name}" - ) + self.assertNotIn("@scad.model", source, path) + self.assertNotIn("scad.requires_session", source, path) + self.assertNotIn("scad.capture_result", source, path) def test_bldc_bearing_decorative_balls_are_part_of_outer_ring(self): example_dir = EXAMPLES / "20_integrated_bldc_joint_actuator" @@ -155,7 +136,9 @@ class TestExampleModelContract(unittest.TestCase): self.assertTrue(outer_meta["rolling_elements_fused"]) self.assertEqual(outer_meta["rolling_element_fuse_mode"], "outer_ring_union") self.assertGreater(outer.get_volume(), 0.0) - self.assertIn("role.rolling_elements_fused_into_outer_ring", scad.list_tags(outer)) + self.assertIn( + "role.rolling_elements_fused_into_outer_ring", scad.list_tags(outer) + ) if __name__ == "__main__": diff --git a/test/test_freecad_translator.py b/test/test_freecad_translator.py index 501312a4..c49a601b 100644 --- a/test/test_freecad_translator.py +++ b/test/test_freecad_translator.py @@ -18,24 +18,201 @@ import xml.etree.ElementTree as ET import simplecadapi as scad from simplecadapi import ql +from simplecadapi.errors import raise_harness_error from simplecadapi.graph import GraphSession from simplecadapi.kernel.ocp_properties import bounding_box from simplecadapi.topology import OperationGraph from simplecadapi.translator import freecad_translator +from simplecadapi.serializer import import_model_json +from simplecadapi.translator.freecad_translator.exporter import ( + discover_freecad_executable, + export_freecad_script_to_fcstd, +) +from simplecadapi.translator.freecad_translator.translator import _FreeCADCompiler from simplecadapi.translator.freecad_translator.semantic import ( build_freecad_semantic_plan, ) +def _build_freecad_nested_package(tmp_path: Path): + cache = scad.CachePolicy(root=tmp_path / "cache") + + @scad.part(id="linked", cache=cache) + def build_part() -> scad.Part: + body = scad.make_box_rsolid(width=1.0, height=2.0, depth=3.0) + named_face = scad.apply_tag(body.get_faces()[0], "interface.mount_face") + part = scad.make_part_rpart("linked", body, name="Part linked") + connector = scad.make_face_connector_rconnector("mount", named_face) + return scad.add_connector_rpart(part, connector) + + part = build_part() + + @scad.assemble(id="child", definitions=(part,), cache=cache) + def build_child() -> scad.Assembly: + assembly = scad.make_assembly_rassembly("child", name="Child assembly") + for component_id in ("inner_a", "inner_b"): + assembly = scad.add_component_rassembly( + assembly, + part.value, + component_id=component_id, + placement=scad.identity_placement_rplacement(), + name=f"Inner linked part {component_id[-1].upper()}", + ) + assembly = scad.ground_component_rassembly(assembly, "inner_a") + assembly = scad.add_revolute_constraint_rassembly( + assembly, + "joint", + scad.make_connector_ref_rconnectorref("inner_a", "mount"), + scad.make_connector_ref_rconnectorref("inner_b", "mount"), + drive_angle_degrees=15.0, + ) + assembly = scad.solve_assembly_constraints_rassembly(assembly) + return scad.forward_connector_rassembly( + assembly, + connector_id="public_mount", + source_component_id="inner_b", + source_connector_id="mount", + ) + + child = build_child() + + @scad.assemble(id="root", definitions=(child, part), cache=cache) + def build_root() -> scad.Assembly: + assembly = scad.make_assembly_rassembly("root", name="Root assembly") + assembly = scad.add_component_rassembly( + assembly, + child.value, + component_id="nested", + placement=scad.make_placement_rplacement(origin=(10.0, 0.0, 0.0)), + name="Nested child assembly", + ) + return scad.add_component_rassembly( + assembly, + part.value, + component_id="direct", + placement=scad.make_placement_rplacement(origin=(0.0, 5.0, 0.0)), + name="Direct linked part", + ) + + return scad.build_product_package(build_root()) + + +def _build_freecad_feature_history_package(tmp_path: Path): + cache = scad.CachePolicy(root=tmp_path / "cache") + + @scad.part(id="feature_history", cache=cache) + def build_part() -> scad.Part: + base = scad.make_box_rsolid(width=10.0, height=8.0, depth=4.0) + tool = scad.make_cylinder_rsolid( + radius=1.0, + height=6.0, + bottom_face_center=(0.0, 0.0, -1.0), + ) + body = scad.cut_rsolid(base, tool) + return scad.make_part_rpart("feature_history", body, name="Feature history") + return scad.build_product_package(build_part()) + + +def _build_freecad_material_package(tmp_path: Path): + cache = scad.CachePolicy(root=tmp_path / "cache") + blue = scad.make_material_rmaterial( + "blue_aluminum", + name="Blue aluminum", + density=2.7e-6, + density_unit="kg/mm^3", + color=(0.2, 0.4, 0.6), + ) + uncolored = scad.make_material_rmaterial( + "uncolored_steel", + name="Uncolored steel", + ) + + def build_part_result(part_id: str, x: float, material: scad.Material): + @scad.part(id=part_id, cache=cache, project_root=Path(__file__).parent) + def build_part() -> scad.Part: + body = scad.make_box_rsolid( + 1.0, + 1.0, + 1.0, + bottom_face_center=(x, 0.0, 0.0), + ) + return scad.assign_material_rpart( + scad.make_part_rpart(part_id, body), + material, + ) + + return build_part() + + parts = ( + build_part_result("blue_a", 0.0, blue), + build_part_result("blue_b", 2.0, blue), + build_part_result("plain", 4.0, uncolored), + ) + + @scad.assemble( + id="material_fixture", + definitions=parts, + cache=cache, + project_root=Path(__file__).parent, + ) + def build_assembly() -> scad.Assembly: + assembly = scad.make_assembly_rassembly("material_fixture") + for part in parts: + assembly = scad.add_component_rassembly( + assembly, + part.value, + component_id=f"{part.value.part_id}_1", + placement=scad.identity_placement_rplacement(), + ) + return assembly + + return scad.build_product_package(build_assembly()) + +def _compile_model_json(payload: str) -> str: + return _FreeCADCompiler().translate_model_payload_to_script( + import_model_json(payload) + ) + + +def _compile_model_json_to_fcstd( + payload: str, + output_path: str, + *, + freecad_cmd: str | None = None, +) -> str: + executable = freecad_cmd or discover_freecad_executable() + if not executable: + raise_harness_error( + operation="_compile_model_json_to_fcstd", + what_happened="FreeCAD executable not found.", + possible_causes=["FreeCAD is not installed or is not discoverable."], + how_to_fix=["Install FreeCAD or pass freecad_cmd."], + ) + return export_freecad_script_to_fcstd( + _compile_model_json(payload), + output_path, + freecad_executable=executable, + ) + + class TestFreeCADTranslator(unittest.TestCase): def test_freecad_translator_is_only_exported_from_translator_namespace(self): self.assertTrue(hasattr(scad, "translator")) - self.assertIs( - scad.translator.freecad_translator.translate_model_json_to_fcstd, - freecad_translator.translate_model_json_to_fcstd, + self.assertEqual( + freecad_translator.__all__, + [ + "CAPABILITIES", + "FreeCADTranslator", + "translate_product_package_to_fcstd", + "translate_product_package_to_freecad_script", + ], ) self.assertFalse(hasattr(scad, "translate_model_json_to_fcstd")) self.assertFalse(hasattr(scad, "translate_model_json_to_freecad_script")) + self.assertFalse(hasattr(freecad_translator, "translate_model_json_to_fcstd")) + self.assertFalse( + hasattr(freecad_translator, "translate_model_json_to_freecad_script") + ) with self.assertRaises(ModuleNotFoundError): importlib.import_module("simplecadapi.freecad_translator") @@ -112,19 +289,58 @@ class TestFreeCADTranslator(unittest.TestCase): fcstd_path = os.path.join(tmp_dir, "model.FCStd") probe_path = os.path.join(tmp_dir, "probe.py") out_path = os.path.join(tmp_dir, "probe.json") - freecad_translator.translate_model_json_to_fcstd( - payload, fcstd_path, freecad_cmd=freecad_cmd - ) + _compile_model_json_to_fcstd(payload, fcstd_path, freecad_cmd=freecad_cmd) with open(probe_path, "w", encoding="utf-8") as fh: fh.write(f"FCSTD_PATH = {json.dumps(fcstd_path)}\n") fh.write(f"OUT_PATH = {json.dumps(out_path)}\n") fh.write(probe_source) - subprocess.run( + completed = subprocess.run( [freecad_cmd, probe_path], check=True, text=True, capture_output=True, ) + if not os.path.isfile(out_path) or os.path.getsize(out_path) <= 0: + self.fail( + "FreeCAD probe did not write JSON. " + f"stdout={completed.stdout!r} stderr={completed.stderr!r}" + ) + with open(out_path, "r", encoding="utf-8") as fh: + return json.load(fh) + + def _inspect_product_package_fcstd_json( + self, + package: object, + probe_source: str, + ) -> dict: + freecad_cmd = self._discover_freecadcmd() + if not freecad_cmd: + self.skipTest("freecadcmd not available") + + with tempfile.TemporaryDirectory() as tmp_dir: + fcstd_path = os.path.join(tmp_dir, "product.FCStd") + probe_path = os.path.join(tmp_dir, "probe.py") + out_path = os.path.join(tmp_dir, "probe.json") + freecad_translator.translate_product_package_to_fcstd( + package, + fcstd_path, + freecad_cmd=freecad_cmd, + ) + with open(probe_path, "w", encoding="utf-8") as fh: + fh.write(f"FCSTD_PATH = {json.dumps(fcstd_path)}\n") + fh.write(f"OUT_PATH = {json.dumps(out_path)}\n") + fh.write(probe_source) + completed = subprocess.run( + [freecad_cmd, probe_path], + check=True, + text=True, + capture_output=True, + ) + if not os.path.isfile(out_path) or os.path.getsize(out_path) <= 0: + self.fail( + "FreeCAD product probe did not write JSON. " + f"stdout={completed.stdout!r} stderr={completed.stderr!r}" + ) with open(out_path, "r", encoding="utf-8") as fh: return json.load(fh) @@ -135,9 +351,7 @@ class TestFreeCADTranslator(unittest.TestCase): with tempfile.TemporaryDirectory() as tmp_dir: fcstd_path = os.path.join(tmp_dir, "model.FCStd") - freecad_translator.translate_model_json_to_fcstd( - payload, fcstd_path, freecad_cmd=freecad_cmd - ) + _compile_model_json_to_fcstd(payload, fcstd_path, freecad_cmd=freecad_cmd) with zipfile.ZipFile(fcstd_path, "r") as archive: names = set(archive.namelist()) gui_xml = archive.read("GuiDocument.xml") @@ -222,9 +436,7 @@ class TestFreeCADTranslator(unittest.TestCase): box = scad.make_box_rsolid(2.0, 3.0, 4.0) scad.translate_shape(box, (1.0, 2.0, 3.0)) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) self.assertIn("import FreeCAD as App", script) self.assertIn("Part::Box", script) @@ -243,9 +455,7 @@ class TestFreeCADTranslator(unittest.TestCase): tag="role.semantic_view", ) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) self.assertIn("# Step", script) self.assertIn("apply_tag_rselection", script) @@ -261,9 +471,7 @@ class TestFreeCADTranslator(unittest.TestCase): tag_prefix="shaft", ) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) self.assertIn("Part::Cylinder", script) self.assertIn("_register_tag_metadata_node", script) @@ -280,9 +488,7 @@ class TestFreeCADTranslator(unittest.TestCase): top_face_tag="role.lid_mount", ) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) self.assertIn("Part::Box", script) self.assertIn("_register_tag_metadata_node", script) @@ -301,9 +507,7 @@ class TestFreeCADTranslator(unittest.TestCase): end_face_tag="role.outlet", ) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) self.assertIn("Part::Cone", script) self.assertIn("_register_tag_metadata_node", script) @@ -333,7 +537,7 @@ class TestFreeCADTranslator(unittest.TestCase): scad.make_face_from_sketch_rface(sketch) model_json = scad.export_model_json(session) - script = freecad_translator.translate_model_json_to_freecad_script(model_json) + script = _compile_model_json(model_json) self.assertIn("SimpleCADSketchPromotion", script) self.assertIn("sketch_entity.bottom", script) @@ -355,7 +559,7 @@ class TestFreeCADTranslator(unittest.TestCase): targets=[box], tag="role.right_branch", ) - scad.capture_result(value=(left, right)) + session.capture_result(value=(left, right)) model_json = scad.export_model_json(session) payload = json.loads(model_json) @@ -399,104 +603,80 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: self.assertEqual(record["node_ids"], [expected_node_ids[tag]]) self.assertEqual(record["volume"], 24.0) - def test_translate_model_json_tagged_parts_preserve_nested_placements(self): - with GraphSession() as session: - lower_body = scad.make_box_rsolid( - width=2.0, - height=4.0, - depth=1.0, - bottom_face_center=(0.0, 0.0, 0.0), - ) - upper_body = scad.make_box_rsolid( - width=2.0, - height=4.0, - depth=1.0, - bottom_face_center=(0.0, 0.0, 10.0), - ) - lower_body = scad.apply_tag(shape=lower_body, tag="role.structure") - upper_body = scad.apply_tag(shape=upper_body, tag="role.structure") - upper_body = scad.apply_tag(shape=upper_body, tag="role.upper") - lower = scad.make_part_rpart(part_id="lower", body=lower_body) - upper = scad.make_part_rpart(part_id="upper", body=upper_body) - child = scad.make_assembly_rassembly(assembly_id="child") - child = scad.add_component_rassembly( - assembly=child, - item=lower, - component_id="lower", - placement=scad.identity_placement_rplacement(), - ) - child = scad.add_component_rassembly( - assembly=child, - item=upper, - component_id="upper", - placement=scad.identity_placement_rplacement(), - ) - root = scad.make_assembly_rassembly(assembly_id="root") - root = scad.add_component_rassembly( - assembly=root, - item=child, - component_id="child", - placement=scad.make_placement_rplacement( - origin=(20.0, 30.0, 5.0), - x_axis=(0.0, 1.0, 0.0), - y_axis=(-1.0, 0.0, 0.0), - ), - ) - scad.make_compound_from_assembly_rcompound(assembly=root) + def test_translate_product_package_emits_dependency_first_definition_registry(self): + with tempfile.TemporaryDirectory() as tmp_dir: + package = _build_freecad_nested_package(Path(tmp_dir)) - probe = """ + script = freecad_translator.translate_product_package_to_freecad_script( + package + ) + + compile(script, "simplecad_product_package.py", "exec") + linked_index = script.index('DEFINITION_REGISTRY["linked"]') + child_index = script.index('DEFINITION_REGISTRY["child"]') + root_index = script.index('DEFINITION_REGISTRY["root"]') + self.assertLess(linked_index, child_index) + self.assertLess(child_index, root_index) + self.assertEqual(script.count('DEFINITION_REGISTRY["linked"]'), 1) + self.assertEqual(script.count('DEFINITION_REGISTRY["child"]'), 1) + self.assertEqual(script.count('DEFINITION_REGISTRY["root"]'), 1) + self.assertEqual(script.count("Translated definition identity differs"), 3) + + def test_translate_product_package_fcstd_preserves_nested_occurrences(self): + with tempfile.TemporaryDirectory() as tmp_dir: + package = _build_freecad_nested_package(Path(tmp_dir)) + probe = """ import json import FreeCAD as App doc = App.openDocument(FCSTD_PATH) -tag_objects = [obj for obj in doc.Objects if getattr(obj, 'SimpleCADOp', '') == 'apply_tag_rselection'] -upper_part = next(obj for obj in doc.Objects if getattr(obj, 'SimpleCADPartId', '') == 'upper') -upper_body = next(obj for obj in upper_part.Group if hasattr(obj, 'SimpleCADSourceBodyNodeId')) -child_link = next(obj for obj in doc.Objects if getattr(obj, 'SimpleCADComponentId', '') == 'child') -compound = next(obj for obj in doc.Objects if getattr(obj, 'SimpleCADOp', '') == 'make_compound_from_assembly_rcompound') +objects = list(doc.Objects) -def bbox(shape): - bounds = shape.BoundBox - return [ - round(float(value), 3) - for value in ( - bounds.XMin, - bounds.YMin, - bounds.ZMin, - bounds.XMax, - bounds.YMax, - bounds.ZMax, - ) - ] +def xyz(obj): + base = obj.Placement.Base + return [round(float(base.x), 3), round(float(base.y), 3), round(float(base.z), 3)] with open(OUT_PATH, 'w', encoding='utf-8') as fh: json.dump({ - 'tag_object_count': len(tag_objects), - 'upper_body_tags': list(upper_body.SimpleCADAppliedTags), - 'upper_body_tag_node_ids': list(upper_body.SimpleCADTagNodeIds), - 'upper_body_bbox': bbox(upper_body.Shape), - 'child_bbox': bbox(child_link.Shape), - 'child_solids': len(child_link.Shape.Solids), - 'child_volume': round(float(child_link.Shape.Volume), 3), - 'compound_bbox': bbox(compound.Shape), - 'compound_solids': len(compound.Shape.Solids), - 'compound_volume': round(float(compound.Shape.Volume), 3), + 'assemblies': sorted( + [obj.SimpleCADAssemblyId, obj.TypeId] + for obj in objects + if getattr(obj, 'SimpleCADAssemblyId', '') + ), + 'components': { + obj.SimpleCADComponentId: {'type': obj.TypeId, 'xyz': xyz(obj)} + for obj in objects + if getattr(obj, 'SimpleCADComponentId', '') + }, + 'part_definition_count': sum( + 1 for obj in objects + if obj.TypeId == 'App::Part' + and getattr(obj, 'SimpleCADPartId', '') == 'linked' + ), + 'connector_ids': sorted( + obj.SimpleCADConnectorId + for obj in objects + if getattr(obj, 'SimpleCADConnectorId', '') + ), }, fh) """ - result = self._inspect_fcstd_json( - scad.export_model_json(session=session), probe - ) + result = self._inspect_product_package_fcstd_json(package, probe) - self.assertEqual(result["tag_object_count"], 0) - self.assertEqual(result["upper_body_tags"], ["role.structure", "role.upper"]) - self.assertEqual(len(result["upper_body_tag_node_ids"]), 2) - self.assertEqual(result["upper_body_bbox"], [-1.0, -2.0, 10.0, 1.0, 2.0, 11.0]) - self.assertEqual(result["child_bbox"], [18.0, 29.0, 5.0, 22.0, 31.0, 16.0]) - self.assertEqual(result["child_solids"], 2) - self.assertEqual(result["child_volume"], 16.0) - self.assertEqual(result["compound_bbox"], result["child_bbox"]) - self.assertEqual(result["compound_solids"], 2) - self.assertEqual(result["compound_volume"], 16.0) + self.assertEqual( + result["assemblies"], + [["child", "Assembly::AssemblyObject"], ["root", "Assembly::AssemblyObject"]], + ) + self.assertEqual(result["part_definition_count"], 1) + self.assertEqual(result["components"]["inner_a"]["type"], "App::Link") + self.assertEqual(result["components"]["inner_a"]["xyz"], [0.0, 0.0, 0.0]) + self.assertEqual(result["components"]["inner_b"]["type"], "App::Link") + self.assertEqual(result["components"]["inner_b"]["xyz"], [0.0, -0.388, 0.051]) + self.assertEqual(result["components"]["nested"]["type"], "Assembly::AssemblyLink") + self.assertEqual(result["components"]["direct"]["type"], "App::Link") + self.assertEqual(result["components"]["direct"]["xyz"], [0.0, 5.0, 0.0]) + self.assertEqual( + result["connector_ids"], ["mount", "public_mount", "public_mount"] + ) def test_translate_model_json_preserves_part_assembly_semantics_in_script(self): with GraphSession() as session: @@ -516,9 +696,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: ) scad.make_compound_from_assembly_rcompound(assembly) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) self.assertIn("PRODUCT_VALUES = {}", script) self.assertIn("import Assembly", script) @@ -568,9 +746,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: all(part.material.to_dict() == material.to_dict() for part in replayed) ) - script = freecad_translator.translate_model_json_to_freecad_script( - json.dumps(payload) - ) + script = _compile_model_json(json.dumps(payload)) self.assertIn("SimpleCADMaterial", script) self.assertIn("_material = _material_from_assignment_params(", script) @@ -601,9 +777,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: source_connector_id="axis", ) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) self.assertIn("make_placement_connector_rconnector", script) self.assertIn("make_forward_connector_rassembly", script) @@ -642,15 +816,13 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: ) scad.solve_assembly_constraints_rassembly(assembly) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) self.assertIn("import JointObject", script) self.assertIn("JointObject.Joint", script) self.assertIn("SimpleCADConstraint", script) self.assertIn("SimpleCADConstraintTranslationStatus", script) - self.assertIn("'Slider'", script) + self.assertIn('"prismatic": "Slider"', script) def test_translate_model_json_emits_native_coupling_joints_in_script(self): with GraphSession() as session: @@ -776,24 +948,21 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: ) scad.make_compound_from_assembly_rcompound(assembly) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) - self.assertIn("'Gears'", script) - self.assertIn("'Belt'", script) - self.assertIn("'RackPinion'", script) + self.assertIn('"gear": "Gears"', script) + self.assertIn('"belt": "Belt"', script) + self.assertIn('"rack_pinion": "RackPinion"', script) self.assertIn("'constraint_kind': 'gear'", script) self.assertIn("'constraint_kind': 'belt'", script) - self.assertIn("'constraint_kind': 'rack_pinion'", script) self.assertIn( - "joint.Distance2 = float(constraint_payload.get('pitch_radius_b'))", script + 'joint.Distance2 = float(constraint_payload.get("pitch_radius_b"))', script ) self.assertIn( - "joint.Distance2 = float(constraint_payload.get('pulley_radius_b'))", script + 'joint.Distance2 = float(constraint_payload.get("pulley_radius_b"))', script ) self.assertIn( - "joint.Distance = float(constraint_payload.get('pitch_radius'))", script + 'joint.Distance = float(constraint_payload.get("pitch_radius"))', script ) def test_translate_model_json_coupling_fcstd_contains_native_joint_properties(self): @@ -1235,44 +1404,10 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: self.assertEqual(result["compound_count"], 1) self.assertGreater(result["compound_volume"], 0.0) - def test_translate_model_json_fcstd_preserves_editable_materials_and_colors(self): - blue = scad.make_material_rmaterial( - "blue_aluminum", - name="Blue aluminum", - density=2.7e-6, - density_unit="kg/mm^3", - color=(0.2, 0.4, 0.6), - ) - uncolored = scad.make_material_rmaterial( - "uncolored_steel", - name="Uncolored steel", - ) - with GraphSession() as session: - parts = [] - for part_id, x, material in ( - ("blue_a", 0.0, blue), - ("blue_b", 2.0, blue), - ("plain", 4.0, uncolored), - ): - body = scad.make_box_rsolid( - 1.0, 1.0, 1.0, bottom_face_center=(x, 0.0, 0.0) - ) - parts.append( - scad.assign_material_rpart( - scad.make_part_rpart(part_id, body), material - ) - ) - assembly = scad.make_assembly_rassembly("material_fixture") - for part in parts: - assembly = scad.add_component_rassembly( - assembly, - part, - component_id=f"{part.part_id}_1", - placement=scad.identity_placement_rplacement(), - ) - scad.make_compound_from_assembly_rcompound(assembly) - - probe = """ + def test_translate_product_package_fcstd_preserves_editable_materials(self): + with tempfile.TemporaryDirectory() as tmp_dir: + package = _build_freecad_material_package(Path(tmp_dir)) + probe = """ import json import FreeCAD as App @@ -1295,28 +1430,18 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: }, 'part_materials': {obj.SimpleCADPartId: obj.SimpleCADMaterialObject.SimpleCADMaterialId for obj in parts}, 'body_materials': {obj.Name: obj.SimpleCADMaterialObject.SimpleCADMaterialId for obj in bodies}, - 'body_labels': sorted(str(obj.Label) for obj in bodies), 'component_materials': {obj.SimpleCADComponentId: obj.SimpleCADMaterialObject.SimpleCADMaterialId for obj in components}, - 'body_names': {obj.SimpleCADMaterialId: sorted(candidate.Name for candidate in bodies if candidate.SimpleCADMaterialObject == obj) for obj in materials}, - 'component_names': {obj.SimpleCADMaterialId: sorted(candidate.Name for candidate in components if candidate.SimpleCADMaterialObject == obj) for obj in materials}, }, fh) """ - payload = scad.export_model_json(session) - result = self._inspect_fcstd_json(payload, probe) + result = self._inspect_product_package_fcstd_json(package, probe) self.assertEqual(set(result["materials"]), {"blue_aluminum", "uncolored_steel"}) self.assertEqual(result["materials"]["blue_aluminum"]["name"], "Blue aluminum") self.assertAlmostEqual(result["materials"]["blue_aluminum"]["density"], 2.7e-6) - self.assertEqual( - result["materials"]["blue_aluminum"]["density_unit"], "kg/mm^3" - ) + self.assertEqual(result["materials"]["blue_aluminum"]["density_unit"], "kg/mm^3") self.assertIsNone(result["materials"]["uncolored_steel"]["density"]) - self.assertIsNone(result["materials"]["uncolored_steel"]["density_unit"]) self.assertEqual( - [ - round(value, 3) - for value in result["materials"]["blue_aluminum"]["color"] - ], + [round(value, 3) for value in result["materials"]["blue_aluminum"]["color"]], [0.2, 0.4, 0.6], ) self.assertEqual( @@ -1325,46 +1450,14 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: ) self.assertEqual( result["part_materials"], - { - "blue_a": "blue_aluminum", - "blue_b": "blue_aluminum", - "plain": "uncolored_steel", - }, + {"blue_a": "blue_aluminum", "blue_b": "blue_aluminum", "plain": "uncolored_steel"}, ) - self.assertEqual( - set(result["body_materials"].values()), {"blue_aluminum", "uncolored_steel"} - ) - self.assertEqual(result["body_labels"], ["body", "body (2)", "body (3)"]) + self.assertEqual(result["body_materials"], {}) self.assertEqual( result["component_materials"], - { - "blue_a_1": "blue_aluminum", - "blue_b_1": "blue_aluminum", - "plain_1": "uncolored_steel", - }, + {"blue_a_1": "blue_aluminum", "blue_b_1": "blue_aluminum", "plain_1": "uncolored_steel"}, ) - gui = self._inspect_fcstd_gui_visibility(payload) - expected_blue = int("336699ff", 16) - blue_names = ( - result["body_names"]["blue_aluminum"] - + result["component_names"]["blue_aluminum"] - ) - plain_names = ( - result["body_names"]["uncolored_steel"] - + result["component_names"]["uncolored_steel"] - ) - self.assertEqual( - {name: gui["shape_colors"][name] for name in blue_names}, - {name: expected_blue for name in blue_names}, - ) - self.assertTrue( - all( - gui["override_material"][name] is True - for name in result["component_names"]["blue_aluminum"] - ) - ) - self.assertTrue(all(name not in gui["shape_colors"] for name in plain_names)) def test_translate_model_json_nested_assembly_uses_native_assembly_link(self): with GraphSession() as session: @@ -1668,111 +1761,6 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: self.assertEqual(result["valid"], [True]) self.assertGreater(result["volumes"][0], 0.0) - def test_translate_model_json_assembly_fcstd_keeps_clean_product_tree(self): - with GraphSession() as session: - body = scad.make_cylinder_rsolid( - radius=2.0, - height=10.0, - bottom_face_center=(0.0, 0.0, 0.0), - axis=(1.0, 0.0, 0.0), - ) - part = scad.make_part_rpart("rod", body, name="Rod") - assembly = scad.make_assembly_rassembly("rod_assembly", name="Rod assembly") - assembly = scad.add_component_rassembly( - assembly, - part, - component_id="rod_1", - placement=scad.identity_placement_rplacement(), - ) - scad.make_compound_from_assembly_rcompound(assembly) - - probe = """ -import json -import FreeCAD as App - -doc = App.openDocument(FCSTD_PATH) -loose_sketches = [obj for obj in doc.Objects if obj.TypeId == 'Sketcher::SketchObject' and not getattr(obj, 'InList', [])] -assemblies = [obj for obj in doc.Objects if obj.TypeId == 'Assembly::AssemblyObject' and hasattr(obj, 'SimpleCADAssemblyId')] -links = [obj for obj in doc.Objects if obj.TypeId == 'App::Link' and hasattr(obj, 'SimpleCADComponentId')] -parts = [obj for obj in doc.Objects if obj.TypeId == 'App::Part' and hasattr(obj, 'SimpleCADPartId')] -construction = [obj for obj in doc.Objects if obj.Name == 'SimpleCADConstruction'] -compound_objs = [obj for obj in doc.Objects if getattr(obj, 'SimpleCADOp', '') == 'make_compound_from_assembly_rcompound'] -origins = [obj for obj in doc.Objects if obj.TypeId == 'App::Origin' or obj.Name.startswith('Origin')] -origin_children = [child for origin in origins for child in list(getattr(origin, 'OutListRecursive', []) or [])] -top_level_names = [obj.Name for obj in doc.Objects if not list(getattr(obj, 'InList', []) or [])] -with open(OUT_PATH, 'w', encoding='utf-8') as fh: - json.dump({ - 'loose_sketch_count': len(loose_sketches), - 'assembly_visible': [bool(obj.Visibility) for obj in assemblies], - 'compound_visible': [bool(obj.Visibility) for obj in compound_objs], - 'link_visible': [bool(obj.Visibility) for obj in links], - 'link_group_sizes': [len(getattr(obj, 'Group', []) or []) for obj in links], - 'part_group_types': [[child.TypeId for child in getattr(obj, 'Group', []) if child.TypeId != 'App::Origin'] for obj in parts], - 'part_group_labels': [[str(child.Label) for child in getattr(obj, 'Group', []) if child.TypeId != 'App::Origin'] for obj in parts], - 'part_group_roles': [[str(getattr(child, 'SimpleCADSemanticRole', '')) for child in getattr(obj, 'Group', []) if child.TypeId != 'App::Origin'] for obj in parts], - 'link_shape_solids': [len(obj.Shape.Solids) for obj in links], - 'part_group_visible': [[bool(child.Visibility) for child in getattr(obj, 'Group', []) if child.TypeId != 'App::Origin'] for obj in parts], - 'construction_visible': [bool(obj.Visibility) for obj in construction], - 'origin_count': len(origins), - 'origin_visible': [bool(obj.Visibility) for obj in origins], - 'origin_child_visible': [bool(obj.Visibility) for obj in origin_children], - 'top_level_names': top_level_names, - 'product_library_present': doc.getObject('SimpleCADProductLibrary') is not None, - }, fh) -""" - payload = scad.export_model_json(session) - result = self._inspect_fcstd_json(payload, probe) - - self.assertEqual(result["loose_sketch_count"], 0) - self.assertEqual(result["assembly_visible"], [True]) - self.assertEqual(result["compound_visible"], [False]) - self.assertEqual(result["link_visible"], [True]) - self.assertEqual(result["link_group_sizes"], [1]) - self.assertEqual(result["part_group_types"], [["Part::Cylinder"]]) - self.assertEqual(result["part_group_labels"], [["body"]]) - self.assertEqual(result["part_group_roles"], [[""]]) - self.assertEqual(result["part_group_visible"], [[True]]) - self.assertEqual(result["link_shape_solids"], [1]) - self.assertEqual(result["construction_visible"], []) - self.assertFalse(result["product_library_present"]) - self.assertGreater(result["origin_count"], 0) - self.assertTrue(all(visible is False for visible in result["origin_visible"])) - self.assertTrue( - all(visible is False for visible in result["origin_child_visible"]) - ) - - gui = self._inspect_fcstd_gui_visibility(payload) - gui_visibility = gui["visibility"] - gui_tree = gui["show_in_tree"] - assembly_names = [ - name - for name in gui_visibility - if name.startswith("make_assembly_rassembly_") - ] - component_names = [ - name - for name in gui_visibility - if name.startswith("make_add_component_rassembly_") - and name.endswith("_component") - ] - compound_names = [ - name - for name in gui_visibility - if name.startswith("make_compound_from_assembly_rcompound_") - ] - self.assertIn("GuiDocument.xml", gui["entries"]) - self.assertEqual([gui_visibility[name] for name in assembly_names], [True]) - self.assertEqual([gui_visibility[name] for name in component_names], [True]) - self.assertEqual([gui_tree[name] for name in assembly_names], [True]) - self.assertEqual([gui_tree[name] for name in component_names], [True]) - self.assertEqual([gui_tree[name] for name in compound_names], [False]) - self.assertNotIn("SimpleCADConstruction", gui_visibility) - self.assertEqual([gui_visibility[name] for name in compound_names], [False]) - self.assertEqual([gui["expanded"][name] for name in assembly_names], [True]) - shown_top_level = [ - name for name in result["top_level_names"] if gui_tree.get(name, True) - ] - self.assertEqual(shown_top_level, assembly_names) def test_translate_model_json_fcstd_multifuse_bridged_union_and_hides_connectors( self, @@ -1820,9 +1808,8 @@ doc = App.openDocument(FCSTD_PATH) parts = [obj for obj in doc.Objects if obj.TypeId == 'App::Part' and getattr(obj, 'SimpleCADPartId', '') == 'bridged_part'] part = parts[0] children = [child for child in getattr(part, 'Group', []) if child.TypeId != 'App::Origin'] -body_children = [child for child in children if hasattr(child, 'SimpleCADSourceBodyNodeId')] +body = next(child for child in children if getattr(child, 'SimpleCADOp', '') == 'make_union_rsolid') connector_children = [child for child in children if hasattr(child, 'SimpleCADConnectorId')] -body = body_children[0] with open(OUT_PATH, 'w', encoding='utf-8') as fh: json.dump({ 'child_labels': [str(child.Label) for child in children], @@ -1834,11 +1821,11 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: """ result = self._inspect_fcstd_json(scad.export_model_json(session), probe) - self.assertIn("body", result["child_labels"]) + self.assertIn("body union", result["child_labels"]) self.assertEqual(result["body_solids"], 1) self.assertGreater(result["body_volume"], 0.0) visible_by_label = dict(zip(result["child_labels"], result["child_visible"])) - self.assertTrue(visible_by_label["body"]) + self.assertTrue(visible_by_label["body union"]) self.assertEqual(result["connector_visible"], [False]) def test_translate_model_json_folds_single_use_translate_into_extrusion_fcstd(self): @@ -1850,7 +1837,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: solid = scad.extrude_rsolid(profile, (0.0, 0.0, 1.0), 2.0) scad.translate_shape(solid, (tx, ty, tz)) payload = scad.export_model_json(session) - script = freecad_translator.translate_model_json_to_freecad_script(payload) + script = _compile_model_json(payload) self.assertIn("_register_graph_folded_alias", script) self.assertNotIn("doc.addObject('App::Link'", script) probe = """ @@ -1902,7 +1889,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: body = scad.extrude_rsolid(profile, (0.0, 0.0, 1.0), 2.0) payload = scad.export_model_json(session) - script = freecad_translator.translate_model_json_to_freecad_script(payload) + script = _compile_model_json(payload) self.assertIn("Part::Extrusion", script) probe = """ @@ -1988,7 +1975,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: ) scad.extrude_rsolid(profile, (0.0, 1.0, 0.0), 2.0) payload = scad.export_model_json(session) - script = freecad_translator.translate_model_json_to_freecad_script(payload) + script = _compile_model_json(payload) self.assertNotIn("doc.addObject('Part::Cylinder'", script) self.assertIn("doc.addObject('Sketcher::SketchObject'", script) @@ -2030,7 +2017,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: profile = scad.make_circle_rface((0.0, 0.0, 0.0), 1.0) source = scad.extrude_rsolid(profile, (1.0, 0.0, 1.0), 2.0) payload = scad.export_model_json(session) - script = freecad_translator.translate_model_json_to_freecad_script(payload) + script = _compile_model_json(payload) self.assertNotIn("doc.addObject('Part::Cylinder'", script) self.assertIn("doc.addObject('Part::Extrusion'", script) @@ -2118,7 +2105,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: scad.translate_shape(solid, (1.0, 0.0, 0.0)) scad.translate_shape(solid, (0.0, 1.0, 0.0)) payload = scad.export_model_json(session) - script = freecad_translator.translate_model_json_to_freecad_script(payload) + script = _compile_model_json(payload) self.assertIn("doc.addObject('App::Link'", script) probe = """ import json @@ -2151,9 +2138,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: with GraphSession() as session: scad.make_box_rsolid(2.0, 3.0, 4.0) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) self.assertIn("Part::Box", script) self.assertIn("RESULT_NODE_IDS", script) @@ -2310,7 +2295,13 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: ) self.assertCountEqual( result["root_group_labels"], - ["base_profile", "Profile", "base", "hole", "finished"], + [ + "base profile wire from edges", + "base profile face from wire", + "base extrude", + "hole cylinder", + "finished cut", + ], ) self.assertEqual(result["cut_base_type"], "Part::Extrusion") self.assertEqual(result["cut_tool_type"], "Part::Cylinder") @@ -2333,7 +2324,7 @@ import FreeCAD as App doc = App.openDocument(FCSTD_PATH) root = next(obj for obj in doc.Objects if obj.TypeId == 'App::Part') cut = next(obj for obj in doc.Objects if obj.TypeId == 'Part::Cut') -profiles = [obj for obj in doc.Objects if obj.TypeId == 'Part::Feature' and obj.Label.startswith('Profile')] +profiles = [obj for obj in doc.Objects if hasattr(obj, 'Shape') and obj.Shape.ShapeType == 'Wire'] with open(OUT_PATH, 'w', encoding='utf-8') as fh: json.dump({ 'base_profile': cut.Base.Base.Name, @@ -2347,8 +2338,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: self.assertNotEqual(result["base_profile"], result["tool_profile"]) self.assertEqual(result["profile_count"], 2) - self.assertEqual(result["profile_labels"], ["Profile", "Profile (2)"]) - self.assertEqual(result["root_children"].count("finished"), 1) + self.assertEqual(result["root_children"].count("finished cut"), 1) def test_semantic_plan_skips_product_state_result_but_keeps_part_root(self): with GraphSession(graph_id="semantic_part_result") as session: @@ -2412,9 +2402,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: } with self.assertRaises(ValueError): - freecad_translator.translate_model_json_to_freecad_script( - json.dumps(payload) - ) + _compile_model_json(json.dumps(payload)) def test_translate_model_json_emits_expression_formulas_for_ir(self): r = scad.var("r", 5.0) @@ -2422,9 +2410,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: face = scad.make_circle_rface((0.0, 0.0, 0.0), r) scad.extrude_rsolid(face, (0.0, 0.0, 1.0), r * 2) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) self.assertIn("SimpleCADExpressions", script) self.assertIn("setAlias", script) @@ -2444,9 +2430,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: scad.make_box_rsolid(width, 2.0, 1.0) session.require_tolerance(width * 2.0, (-0.2, 0.4), name="overall") - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) self.assertIn("TOLERANCE_GRAPH =", script) self.assertIn("simplecad_tolerance_graph", script) @@ -2467,9 +2451,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: ) session.require_tolerance(width, 0.004, tolerance_unit="in") - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) self.assertIn('expr_sheet.set("B1", "25.4")', script) self.assertIn("expr_sheet.set('G1', \"in\")", script) @@ -2488,9 +2470,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: with GraphSession() as session: scad.make_box_rsolid(expression, 2.0, 1.0) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) suffix = hashlib.sha256(second.expr_id.encode("utf-8")).hexdigest()[:8] second_alias = f"var_width_{suffix}" @@ -2505,9 +2485,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: with GraphSession() as session: scad.make_box_rsolid(variables[0] + variables[1] + variables[2], 2.0, 1.0) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) aliases = [] for line in script.splitlines(): marker = "expr_sheet.setAlias(" @@ -2564,9 +2542,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: box = scad.make_box_rsolid(4.0, 4.0, 4.0) scad.fillet_rsolid(box, [box.get_edges(i) for i in range(2)], radius) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) self.assertIn("Part::Fillet", script) self.assertIn("_resolve_param_value", script) @@ -2608,9 +2584,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: "topology_delta_log": [], } - script = freecad_translator.translate_model_json_to_freecad_script( - json.dumps(payload) - ) + script = _compile_model_json(json.dumps(payload)) self.assertIn("_resolve_nested_param_value", script) self.assertIn("_resolve_param_value", script) @@ -2623,9 +2597,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: scad.make_helix_rwire(pitch, 3.0, radius) scad.make_angle_arc_rwire((0.0, 0.0, 0.0), radius, 0.0, angle) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) self.assertIn("Part::Helix", script) self.assertIn("make_angle_arc_redge", script) @@ -2640,9 +2612,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: face = scad.make_circle_rface((0.0, 0.0, 0.0), 1.0) scad.extrude_rsolid(face, (0.0, 0.0, 1.0), expr) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) self.assertIn("sin((<>.", script) self.assertIn("* 180 / pi)", script) @@ -2659,9 +2629,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: dir=(0.0, 1.0, 0.0), ) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) self.assertIn("Part::Helix", script) self.assertIn("Placement = App.Placement", script) @@ -2676,9 +2644,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: origin=(1.0, 0.0, 0.0), ) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) self.assertIn("Part::Revolution", script) self.assertIn(".Axis = _vec(", script) @@ -2695,7 +2661,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: ) scad.revolve_rsolid(profile) payload = scad.export_model_json(session) - script = freecad_translator.translate_model_json_to_freecad_script(payload) + script = _compile_model_json(payload) self.assertNotIn("make_revolve_rsolid_profile", script) probe = """ @@ -2730,9 +2696,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: for node in payload_obj["graph"]["nodes"]: if node["op"] == "make_sweep_rsolid": node["param_exprs"] = {"is_frenet": {"expr_id": "var_frenet"}} - script = freecad_translator.translate_model_json_to_freecad_script( - json.dumps(payload_obj) - ) + script = _compile_model_json(json.dumps(payload_obj)) self.assertIn("Part::Sweep", script) self.assertIn(".Spine = _spine_object", script) @@ -2752,9 +2716,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: twist_angle=45.0, ) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) self.assertIn("_twisted_sweep_loft_shape", script) self.assertIn("Part.makeLoft(sections, True, False, False, 5)", script) @@ -2830,7 +2792,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: for node in payload_obj["graph"]["nodes"] if node["op"] == "make_sweep_rsolid" ) - script = freecad_translator.translate_model_json_to_freecad_script(payload) + script = _compile_model_json(payload) self.assertEqual(sweep_node["inputs"][0], select_node["node_id"]) self.assertIn("GRAPH_SELECTIONS = {}", script) @@ -2910,7 +2872,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: scad.extrude_rsolid(profile, (0.0, 0.0, 1.0), 2.0) payload = scad.export_model_json(session) - script = freecad_translator.translate_model_json_to_freecad_script(payload) + script = _compile_model_json(payload) self.assertIn("Part::Extrusion", script) self.assertNotIn("Unsupported graph operation: make_extrude_rsolid", script) @@ -2978,9 +2940,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: "topology_delta_log": [], } - script = freecad_translator.translate_model_json_to_freecad_script( - json.dumps(payload) - ) + script = _compile_model_json(json.dumps(payload)) self.assertIn("Part::Fuse", script) @@ -3026,9 +2986,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: "topology_delta_log": [], } - script = freecad_translator.translate_model_json_to_freecad_script( - json.dumps(payload) - ) + script = _compile_model_json(json.dumps(payload)) self.assertNotIn("Part::MultiFuse", script) self.assertIn("cut_out_step_1 = doc.addObject('Part::Cut'", script) @@ -3202,7 +3160,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: payload = scad.export_model_json(session) result_node_id = result_solid.get_metadata("graph")["node_id"] - script = freecad_translator.translate_model_json_to_freecad_script(payload) + script = _compile_model_json(payload) self.assertIn(" = doc.addObject('Part::Cut'", script) self.assertNotIn(" = _make_baked_exact_boolean(", script) @@ -3270,7 +3228,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: payload = scad.export_model_json(session) result_node_id = result_solid.get_metadata("graph")["node_id"] - script = freecad_translator.translate_model_json_to_freecad_script(payload) + script = _compile_model_json(payload) self.assertIn(" = doc.addObject('Part::Cut'", script) self.assertNotIn("_make_baked_exact_boolean", script) @@ -3340,7 +3298,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: patch = scad.make_surface_patch_rface( [scad.SurfaceBoundary(edge) for edge in patch_edges] ) - scad.capture_result(value=[bezier, fitted, ruled, gordon, patch]) + session.capture_result(value=[bezier, fitted, ruled, gordon, patch]) probe = """ import json @@ -3402,7 +3360,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: upper = scad.make_circle_rwire(center=(0, 0, 3), radius=1.0) shell = scad.loft_rshell([lower, upper]) boundaries = scad.free_boundaries_rwirelist(shell) - scad.capture_result(value=[shell, *boundaries]) + session.capture_result(value=[shell, *boundaries]) boundary_node_id = next( node.node_id @@ -3451,7 +3409,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: open_shell = scad.loft_rshell([lower, upper]) filled = scad.fill_holes_rshell(open_shell) boundaries = scad.free_boundaries_rwirelist(filled) - scad.capture_result(value=[filled, *boundaries]) + session.capture_result(value=[filled, *boundaries]) boundary_node_id = next( node.node_id @@ -3613,9 +3571,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: for node in payload_obj["graph"]["nodes"]: if node["op"] == "make_loft_rsolid": node["param_exprs"] = {"ruled": {"expr_id": "var_ruled"}} - script = freecad_translator.translate_model_json_to_freecad_script( - json.dumps(payload_obj) - ) + script = _compile_model_json(json.dumps(payload_obj)) self.assertIn("Part::Loft", script) self.assertIn(".Sections = [GRAPH_NODES", script) @@ -4552,7 +4508,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: def test_translate_model_json_supports_functional_sketch_promotion_script(self): payload = self._functional_rectangle_sketch_model_json() - script = freecad_translator.translate_model_json_to_freecad_script(payload) + script = _compile_model_json(payload) self.assertIn("_make_sketch_promotion_object", script) self.assertIn("make_face_from_sketch_rface", script) @@ -4657,7 +4613,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: scad.extrude_rsolid(face, (0.0, 0.0, 1.0), 0.5) payload = scad.export_model_json(session) - script = freecad_translator.translate_model_json_to_freecad_script(payload) + script = _compile_model_json(payload) self.assertNotIn("Large sketch (>50 entities)", script) self.assertNotIn("materialised as Part::Feature for performance", script) @@ -5332,9 +5288,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: scad.chamfer_rsolid(box, [box.get_edges(0)], 0.2) scad.shell_rsolid(box, [box.get_faces(0)], 0.1) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) self.assertIn("Part::Chamfer", script) self.assertIn("Part::Thickness", script) @@ -5347,9 +5301,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: with GraphSession() as session: scad.make_box_rsolid(1.0, 1.0, 1.0) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) self.assertNotIn("= _make_native_assembly(", script) self.assertNotIn("PART_REGISTRY", script) @@ -5361,9 +5313,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: box = scad.make_box_rsolid(1.0, 1.0, 1.0) scad.linear_pattern_rsolidlist(box, (1.0, 0.0, 0.0), 3, 2.0) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) self.assertIn("GRAPH_OUTPUTS", script) self.assertIn("App::Link", script) @@ -5375,9 +5325,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: box = scad.make_box_rsolid(2.0, 3.0, 4.0) scad.translate_shape(box, (1.0, 2.0, 3.0)) - script = freecad_translator.translate_model_json_to_freecad_script( - scad.export_model_json(session) - ) + script = _compile_model_json(scad.export_model_json(session)) self.assertIn("_apply_result_visibility(RESULT_NODE_IDS)", script) self.assertIn("_set_active_result_object(RESULT_NODE_IDS)", script) @@ -5417,9 +5365,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: } with self.assertRaises(ValueError): - freecad_translator.translate_model_json_to_freecad_script( - json.dumps(payload) - ) + _compile_model_json(json.dumps(payload)) def test_translate_model_json_to_fcstd_invokes_freecadcmd(self): with GraphSession() as session: @@ -5441,9 +5387,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: run_mock.return_value = mock.Mock( returncode=0, stdout="/tmp/out.FCStd\n", stderr="" ) - out = freecad_translator.translate_model_json_to_fcstd( - payload, "/tmp/out.FCStd" - ) + out = _compile_model_json_to_fcstd(payload, "/tmp/out.FCStd") self.assertEqual(out, "/tmp/out.FCStd") run_mock.assert_called_once() @@ -5459,9 +5403,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: mock.patch("os.path.exists", return_value=False), ): with self.assertRaises(scad.SimpleCADError): - freecad_translator.translate_model_json_to_fcstd( - payload, "/tmp/out.FCStd" - ) + _compile_model_json_to_fcstd(payload, "/tmp/out.FCStd") def test_translate_model_json_to_fcstd_discovers_macos_bundle_freecadcmd(self): with GraphSession() as session: @@ -5484,9 +5426,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh: run_mock.return_value = mock.Mock( returncode=0, stdout="/tmp/out.FCStd\n", stderr="" ) - out = freecad_translator.translate_model_json_to_fcstd( - payload, "/tmp/out.FCStd" - ) + out = _compile_model_json_to_fcstd(payload, "/tmp/out.FCStd") self.assertEqual(out, "/tmp/out.FCStd") args, _kwargs = run_mock.call_args diff --git a/test/test_fusion360_translator.py b/test/test_fusion360_translator.py index 02eae0ec..753bfbe1 100644 --- a/test/test_fusion360_translator.py +++ b/test/test_fusion360_translator.py @@ -1,264 +1,107 @@ -"""Host-independent tests for the Fusion 360 translator backend.""" +"""Host-independent tests for the Fusion 360 product translator.""" from __future__ import annotations import ast -import copy import importlib -import math +from pathlib import Path import sys -import unittest -import simplecadapi as scad -from simplecadapi import GraphSession -from simplecadapi.translator.errors import TranslationRequestError +from test_product_exporter import _build_nested_package -def _rectangle_extrusion_model() -> str: - with GraphSession() as session: - profile = scad.make_rectangle_rface(width=2.0, height=1.0) - scad.extrude_rsolid( - profile=profile, - direction=(0.0, 0.0, 1.0), - distance=3.0, +def _model_payload(script: str) -> dict: + module = ast.parse(script) + return next( + ast.literal_eval(node.value) + for node in module.body + if isinstance(node, ast.Assign) + and any( + isinstance(target, ast.Name) and target.id == "MODEL_PAYLOAD" + for target in node.targets ) - return scad.export_model_json(session=session) + ) -class TestFusion360Translator(unittest.TestCase): - def test_backend_imports_without_target_runtime_modules(self): - before = set(sys.modules) +def test_backend_imports_without_target_runtime_modules() -> None: + before = set(sys.modules) - fusion = importlib.import_module("simplecadapi.translator.fusion360_translator") + fusion = importlib.import_module("simplecadapi.translator.fusion360_translator") - self.assertNotIn("adsk.core", set(sys.modules) - before) - self.assertNotIn("adsk.fusion", set(sys.modules) - before) - self.assertEqual(fusion.CAPABILITIES.backend_id, "fusion360") - - def test_supported_graph_emits_deterministic_compilable_script(self): - model_json = _rectangle_extrusion_model() - from simplecadapi.translator.fusion360_translator import Fusion360Translator - - translator = Fusion360Translator(document_name="ContractFusion") - first = translator.translate_model_json(model_json) - second = translator.translate_model_json(model_json) - - self.assertEqual(first.content, second.content) - compile(first.content, "", "exec") - self.assertFalse(first.metadata["target_runtime_validated"]) - self.assertTrue(translator.capabilities.targets[0].requires_external_runtime) - - def test_payload_uses_canonical_periodic_curve_frames(self): - with GraphSession() as session: - scad.make_angle_arc_rwire( - (0.0, 0.0, 0.0), - 2.0, - 0.0, - math.pi / 2.0, - normal=(1.0, 0.0, 0.0), - ) - scad.make_helix_rwire( - 1.0, - 3.0, - 2.0, - dir=(1.0, 0.0, 0.0), - ) - - from simplecadapi.translator.fusion360_translator import Fusion360Translator - - script = ( - Fusion360Translator() - .translate_model_json(scad.export_model_json(session)) - .content - ) - module = ast.parse(script) - model_payload = next( - ast.literal_eval(node.value) - for node in module.body - if isinstance(node, ast.Assign) - and any( - isinstance(target, ast.Name) and target.id == "MODEL_PAYLOAD" - for target in node.targets - ) - ) - curve_nodes = { - node["op"]: node - for node in model_payload["graph"]["nodes"] - if node["op"] in {"make_angle_arc_redge", "make_helix_redge"} - } - - for node in curve_nodes.values(): - self.assertEqual(node["params"]["_kernel_x_axis"], [-0.0, 0.0, 1.0]) - self.assertEqual(node["params"]["_kernel_y_axis"], [0.0, -1.0, 0.0]) - self.assertIn("Circle3D.createByCenter", script) - self.assertIn("SweepOrientationTypes.ParallelOrientationType", script) - - def test_fallback_scripts_are_deterministic_and_result_scoped(self): - with GraphSession() as session: - profile = scad.make_rectangle_rface( - 1.0, - 2.0, - center=(2.0, 0.0, 0.0), - normal=(0.0, 1.0, 0.0), - ) - scad.revolve_rsolid(profile, axis=(0.0, 1.0, 0.0)) - scad.make_box_rsolid(width=4.0, height=5.0, depth=6.0) - model_json = scad.export_model_json(session) - payload = scad.import_model_json(model_json) - graph = payload["graph"] - result_id = next( - node.node_id - for node in graph.topological_order() - if node.op == "make_revolve_rsolid" - ) - box_id = next( - node.node_id - for node in graph.topological_order() - if node.op == "make_box_rsolid" - ) - - from simplecadapi.translator.fusion360_translator import Fusion360Translator - - translator = Fusion360Translator( - result_node_ids=[result_id], source_kernel_fallback=True - ) - first = translator.translate_model_json(model_json).content - second = translator.translate_model_json(model_json).content - - self.assertEqual(first, second) - module = ast.parse(first) - fallback_steps = next( - ast.literal_eval(node.value) - for node in module.body - if isinstance(node, ast.Assign) - and any( - isinstance(target, ast.Name) and target.id == "SOURCE_KERNEL_STEPS" - for target in node.targets - ) - ) - self.assertIn(result_id, fallback_steps) - self.assertNotIn(box_id, fallback_steps) - - def test_implicit_results_prefer_active_assembly_state(self): - from simplecadapi.topology import OperationGraph - from simplecadapi.translator.fusion360_translator import Fusion360Translator - - graph = OperationGraph("assembly_states") - locked = graph.add_node( - "make_compound_from_assembly_rcompound", - {"assembly_id": "fixture_locked", "component_count": 1}, - node_id="locked_result", - ) - operating = graph.add_node( - "make_compound_from_assembly_rcompound", - {"assembly_id": "fixture_operating", "component_count": 1}, - node_id="operating_result", - ) - payload = { - "schema_version": "2.0", - "graph": graph, - "leaf_ids": [locked.node_id, operating.node_id], - } - - script = Fusion360Translator().translate_model_payload_to_script( - payload, graph=graph - ) - - self.assertIn("ACTIVE_RESULT_STATE = 'operating'", script) - self.assertIn("RESULT_NODE_IDS = ['operating_result']", script) - - def test_fallback_accepts_legacy_metadata_only_selector_nodes(self): - with GraphSession() as session: - profile = scad.make_rectangle_rface(3.0, 3.0) - solid = scad.extrude_rsolid(profile, (0.0, 0.0, 1.0), 3.0) - scad.fillet_rsolid(solid, [solid.get_edges(0)], 0.2) - payload = scad.import_model_json(scad.export_model_json(session)) - graph_data = copy.deepcopy(payload["graph"].to_dict()) - selector_ids = { - node["node_id"] - for node in graph_data["nodes"] - if node["op"] == "make_select_redge" - } - for node in graph_data["nodes"]: - if node["node_id"] in selector_ids: - node["inputs"] = [] - else: - node["inputs"] = [ - input_ref - for input_ref in node.get("inputs", []) - if input_ref not in selector_ids - ] - graph_data["edges"] = [ - edge - for edge in graph_data.get("edges", []) - if edge[0] not in selector_ids and edge[1] not in selector_ids - ] - - from simplecadapi.topology import OperationGraph - from simplecadapi.translator.fusion360_translator import Fusion360Translator - - legacy_graph = OperationGraph.from_dict(graph_data) - result_id = next( - node.node_id - for node in legacy_graph.nodes - if node.op == "make_fillet_rsolid" - ) - legacy_payload = { - "schema_version": "2.0", - "graph": legacy_graph, - "leaf_ids": [result_id], - } - script = Fusion360Translator( - source_kernel_fallback=True - ).translate_model_payload_to_script(legacy_payload, graph=legacy_graph) - module = ast.parse(script) - fallback_steps = next( - ast.literal_eval(node.value) - for node in module.body - if isinstance(node, ast.Assign) - and any( - isinstance(target, ast.Name) and target.id == "SOURCE_KERNEL_STEPS" - for target in node.targets - ) - ) - - self.assertIn(result_id, fallback_steps) - - def test_explicit_result_only_executes_its_dependency_closure(self): - with GraphSession() as session: - profile = scad.make_rectangle_rface(width=2.0, height=1.0) - scad.extrude_rsolid(profile, (0.0, 0.0, 1.0), 3.0) - scad.make_box_rsolid(width=1.0, height=2.0, depth=3.0) - model_json = scad.export_model_json(session=session) - payload = scad.import_model_json(model_json) - graph = payload["graph"] - extrusion_id = next( - node.node_id - for node in graph.topological_order() - if node.op == "make_extrude_rsolid" - ) - - from simplecadapi.translator.fusion360_translator import Fusion360Translator - - script = ( - Fusion360Translator(result_node_ids=[extrusion_id]) - .translate_model_json(model_json) - .content - ) - - self.assertIn(f"RESULT_NODE_IDS = ['{extrusion_id}']", script) - self.assertIn("active_node_ids = self._result_dependency_ids", script) - self.assertIn("not in active_node_ids", script) - - def test_unsupported_result_operation_is_rejected_before_host_execution(self): - with GraphSession() as session: - scad.make_box_rsolid(width=1.0, height=2.0, depth=3.0) - - from simplecadapi.translator.fusion360_translator import Fusion360Translator - - with self.assertRaises(TranslationRequestError): - Fusion360Translator().translate_model_json(scad.export_model_json(session)) + assert "adsk.core" not in set(sys.modules) - before + assert "adsk.fusion" not in set(sys.modules) - before + assert fusion.CAPABILITIES.backend_id == "fusion360" + assert fusion.CAPABILITIES.input_schema_versions == ("product-package-2.0",) -if __name__ == "__main__": - unittest.main() +def test_nested_package_emits_deterministic_compilable_script(tmp_path: Path) -> None: + from simplecadapi.translator.fusion360_translator import Fusion360Translator + + package = _build_nested_package(tmp_path) + translator = Fusion360Translator(document_name="ContractFusion") + first = translator.translate_product_package(package) + second = translator.translate_product_package(package) + + assert first.content == second.content + compile(first.content, "", "exec") + assert first.metadata["root_definition_id"] == "root" + assert first.metadata["root_definition_kind"] == "assembly" + assert first.metadata["definition_ids"] == ("linked", "child", "root") + assert first.metadata["target_runtime_validated"] is False + assert translator.capabilities.targets[0].requires_external_runtime + + +def test_product_payload_resolves_references_and_keeps_solved_placements( + tmp_path: Path, +) -> None: + from simplecadapi.translator.fusion360_translator import Fusion360Translator + + script = Fusion360Translator().translate_product_package( + _build_nested_package(tmp_path) + ).content + payload = _model_payload(script) + operations = [node["op"] for node in payload["graph"]["nodes"]] + evaluations = [ + node["params"] + for node in payload["graph"]["nodes"] + if node["op"] == "evaluate_assembly_definition" + ] + + assert "reference_definition" not in operations + assert operations.count("make_box_rsolid") == 1 + assert operations.count("evaluate_assembly_definition") == 2 + assert evaluations[0]["constraint_report"]["solved"] is True + inner_b = next( + record + for record in evaluations[0]["component_placements"] + if record["instance_id"] == "inner_b" + ) + assert inner_b["placement"]["origin"] == [ + 0, + -0.3882285676537811, + 0.051111260566397476, + ] + + +def test_runtime_uses_shared_nested_product_definitions(tmp_path: Path) -> None: + from simplecadapi.translator.fusion360_translator import Fusion360Translator + + script = Fusion360Translator().translate_product_package( + _build_nested_package(tmp_path) + ).content + + assert "self.product_definition_components = {}" in script + assert "component.occurrences.addExistingComponent" in script + assert "self.root.occurrences.addExistingComponent" not in script + assert "DefinitionKind" in script + assert "AssemblyEvaluation" in script + assert "if op == 'make_box_rsolid':" in script + assert "if op == 'apply_tag_rselection':" in script + + +def test_public_surface_has_no_model_json_or_compiler_entrypoints() -> None: + from simplecadapi.translator import fusion360_translator as fusion + + assert "translate_product_package_to_fusion360_script" in fusion.__all__ + assert all("model_json" not in name for name in fusion.__all__) + assert all("ScriptTranslator" not in name for name in fusion.__all__) diff --git a/test/test_graph_model_api.py b/test/test_graph_model_api.py index 16696f8a..7d4a1799 100644 --- a/test/test_graph_model_api.py +++ b/test/test_graph_model_api.py @@ -1,226 +1,74 @@ import json from dataclasses import dataclass -from pathlib import Path -from tempfile import TemporaryDirectory import unittest import simplecadapi as scad -from simplecadapi.scene import ( - parse_canonical_json, - preflight_zip_bytes, - validate_scene_package, -) from simplecadapi.topology import TopoKind, TopoRef -class TestGraphModelApi(unittest.TestCase): - def test_model_export_dir_writes_one_self_contained_scene_package(self): - with TemporaryDirectory() as directory: - - @scad.model(graph_id="auto_export", export_dir=directory) - def build_model(): - body = scad.make_box_rsolid(width=1.0, height=2.0, depth=3.0) - scad.capture_result(value=body) - return body - - result = build_model() - self.assertEqual(set(result.artifact_paths), {"scene"}) - self.assertTrue( - all(Path(path).is_file() for path in result.artifact_paths.values()) - ) - self.assertEqual( - sorted(Path(directory).iterdir()), - [result.artifact_paths["scene"]], - ) - - def test_model_export_dir_writes_assembly_artifacts_with_model_provenance(self): - with TemporaryDirectory() as directory: - - @scad.model(graph_id="assembly_export", export_dir=directory) - def build_model(): - body = scad.make_box_rsolid(width=1.0, height=2.0, depth=3.0) - part = scad.make_part_rpart(part_id="body", body=body) - assembly = scad.make_assembly_rassembly(assembly_id="root") - assembly = scad.add_component_rassembly( - assembly=assembly, - item=part, - component_id="body", - placement=scad.identity_placement_rplacement(), - ) - scad.capture_result(value=assembly) - return assembly - - result = build_model() - self.assertEqual(set(result.artifact_paths), {"scene"}) - self.assertTrue( - all(Path(path).is_file() for path in result.artifact_paths.values()) - ) - - archive = preflight_zip_bytes(result.artifact_paths["scene"].read_bytes()) - manifest = parse_canonical_json(archive.members["scene.json"]) - blobs = { - name: payload - for name, payload in archive.members.items() - if name != "scene.json" - } - report = validate_scene_package(manifest, blobs) - self.assertTrue(report.valid, report.issues) - self.assertEqual(manifest["source"]["kind"], "model") - self.assertIn("model/model.json", archive.members) - self.assertTrue(manifest["compile_options"]["embed_source"]) - self.assertEqual( - manifest["source"]["embedded_artifact_uri"], - "model/model.json", - ) - source_files = manifest["source"]["source_files"] - self.assertEqual( - [record["path"] for record in source_files], - ["test/test_graph_model_api.py"], - ) - self.assertEqual( - archive.members[source_files[0]["uri"]], - Path(__file__).read_bytes(), - ) - self.assertFalse( - any( - name.lower().endswith((".step", ".stl", ".fcstd")) - for name in archive.members - ) - ) - self.assertTrue( - manifest["definitions"] - and all( - item["source"]["kind"] == "product_model" - for item in manifest["definitions"] - ) - ) - - def test_model_source_embedding_is_explicit(self): - @scad.model(graph_id="embedded_source") - def build_model(): - body = scad.make_box_rsolid(width=1.0, height=2.0, depth=3.0) - scad.capture_result(value=body) - return body - - result = build_model() - package = scad.compile_scene( - scene_id="embedded_source", - roots=(scad.SceneRoot(root_id="main", value=result.value),), - source=result, - options=scad.SceneCompileOptions(embed_source=True), - ) - - self.assertEqual( - package.blobs["model/model.json"], - result.model_json.encode("utf-8"), - ) - self.assertTrue(package.manifest["compile_options"]["embed_source"]) - self.assertEqual( - package.manifest["source"]["embedded_artifact_uri"], - "model/model.json", - ) - source_files = package.manifest["source"]["source_files"] - self.assertEqual( - [record["path"] for record in source_files], - ["test/test_graph_model_api.py"], - ) - self.assertEqual( - package.blobs[source_files[0]["uri"]], - Path(__file__).read_bytes(), - ) - - def test_model_owns_one_session_and_replays_explicit_result(self): - @scad.model(graph_id="decorator_model") - def build_model(): +class TestGraphSessionApi(unittest.TestCase): + def test_explicit_session_exports_and_replays_selected_result(self): + with scad.GraphSession(graph_id="explicit_session") as session: scad.make_box_rsolid(width=0.5, height=0.5, depth=0.5) - return scad.make_box_rsolid(width=1.0, height=2.0, depth=3.0) + result = scad.make_box_rsolid(width=1.0, height=2.0, depth=3.0) + session.capture_result(value=result) - result = build_model() + model_json = scad.export_model_json(session) + payload = json.loads(model_json) - self.assertIsInstance(result, scad.ModelResult) - self.assertEqual(result.session.graph.graph_id, "decorator_model") - self.assertEqual(len(result.result_node_ids), 1) - self.assertEqual(result.session.graph.node_count, 2) - self.assertEqual(len(result.replay()), 1) - payload = json.loads(result.model_json) - self.assertEqual(payload["leaf_ids"], list(result.result_node_ids)) + self.assertEqual(session.graph.graph_id, "explicit_session") + self.assertEqual(session.graph.node_count, 2) + self.assertEqual(payload["leaf_ids"], list(session.result_node_ids)) + self.assertEqual(len(scad.replay_model_json(model_json)), 1) - def test_same_model_invocation_has_deterministic_graph_ids(self): - @scad.model(graph_id="deterministic_model") - def build_model(): - body = scad.make_box_rsolid(width=1.0, height=2.0, depth=3.0) - return scad.apply_tag(shape=body, tag="role.body") - - first = build_model() - second = build_model() - - self.assertEqual(first.model_json, second.model_json) - self.assertEqual(first.session_json, second.session_json) - self.assertEqual(first.result_node_ids, second.result_node_ids) - - def test_same_model_invocation_has_deterministic_auto_sketch_id(self): - @scad.model(graph_id="deterministic_sketch_model") - def build_model(): - sketch = scad.make_sketch_rsketch(name="profile") - sketch = scad.add_point_rsketch( - sketch=sketch, - point_id="center", - x=0.0, - y=0.0, + def test_repeated_sessions_have_deterministic_graph_payloads(self): + def build() -> tuple[str, str, tuple[str, ...]]: + with scad.GraphSession(graph_id="deterministic_session") as session: + body = scad.make_box_rsolid(width=1.0, height=2.0, depth=3.0) + result = scad.apply_tag(shape=body, tag="role.body") + session.capture_result(value=result) + return ( + scad.export_model_json(session), + scad.export_session_json(session), + session.result_node_ids, ) - sketch = scad.add_circle_rsketch( - sketch=sketch, - entity_id="circle", - center="center", - radius=1.0, - ) - return scad.make_face_from_sketch_rface(sketch=sketch) - first = build_model() - second = build_model() + self.assertEqual(build(), build()) - self.assertEqual(first.model_json, second.model_json) - self.assertEqual(first.session_json, second.session_json) + def test_repeated_sessions_have_deterministic_auto_sketch_ids(self): + def build() -> tuple[str, str]: + with scad.GraphSession( + graph_id="deterministic_sketch_session" + ) as session: + sketch = scad.make_sketch_rsketch(name="profile") + sketch = scad.add_point_rsketch( + sketch=sketch, + point_id="center", + x=0.0, + y=0.0, + ) + sketch = scad.add_circle_rsketch( + sketch=sketch, + entity_id="circle", + center="center", + radius=1.0, + ) + result = scad.make_face_from_sketch_rface(sketch=sketch) + session.capture_result(value=result) + return scad.export_model_json(session), scad.export_session_json(session) - def test_requires_session_reuses_active_session(self): - @scad.requires_session - def build_box(): - return scad.make_box_rsolid(width=1.0, height=1.0, depth=1.0) + self.assertEqual(build(), build()) - with self.assertRaisesRegex(RuntimeError, "requires an active GraphSession"): - build_box() - - with scad.GraphSession(graph_id="shared") as session: - box = build_box() - - self.assertEqual(box.get_metadata("graph")["graph_id"], "shared") - self.assertEqual(session.graph.node_count, 1) - - def test_model_rejects_nested_model_sessions(self): - @scad.model - def child_model(): - return scad.make_box_rsolid(width=1.0, height=1.0, depth=1.0) - - @scad.model - def parent_model(): - return child_model() - - with self.assertRaisesRegex(RuntimeError, "cannot be nested"): - parent_model() - - def test_capture_result_can_exclude_unrelated_leaf(self): - @scad.model - def build_model(): - debug = scad.make_box_rsolid(width=0.25, height=0.25, depth=0.25) + def test_result_selection_excludes_unrelated_leaf(self): + with scad.GraphSession(graph_id="selected_result") as session: + scad.make_box_rsolid(width=0.25, height=0.25, depth=0.25) final = scad.make_box_rsolid(width=2.0, height=2.0, depth=2.0) - scad.capture_result(value=final) - return debug, final + session.capture_result(value=final) - result = build_model() - payload = json.loads(result.model_json) + payload = json.loads(scad.export_model_json(session)) nodes = {node["node_id"]: node for node in payload["graph"]["nodes"]} - self.assertEqual(payload["leaf_ids"], list(result.result_node_ids)) + self.assertEqual(payload["leaf_ids"], list(session.result_node_ids)) self.assertEqual(len(payload["leaf_ids"]), 1) self.assertEqual(nodes[payload["leaf_ids"][0]]["params"]["width"], 2.0) @@ -261,20 +109,17 @@ class TestGraphModelApi(unittest.TestCase): placement=placement, ) - def test_capture_result_walks_dataclass_values_and_is_atomic_on_failure(self): + def test_capture_result_walks_dataclasses_and_is_atomic_on_failure(self): @dataclass class ResultValue: body: scad.Solid - @scad.model(graph_id="dataclass_result") - def build_model(): + with scad.GraphSession(graph_id="dataclass_result") as session: body = scad.make_box_rsolid(width=1.0, height=2.0, depth=3.0) - scad.capture_result(value=ResultValue(body=body)) - return ResultValue(body=body) + session.capture_result(value=ResultValue(body=body)) - result = build_model() - self.assertEqual(len(result.result_node_ids), 1) - self.assertEqual(len(result.replay()), 1) + self.assertEqual(len(session.result_node_ids), 1) + self.assertEqual(len(scad.replay_model_json(scad.export_model_json(session))), 1) with scad.GraphSession(graph_id="atomic_capture") as session: body = scad.make_box_rsolid(width=1.0, height=1.0, depth=1.0) @@ -305,19 +150,9 @@ class TestGraphModelApi(unittest.TestCase): self.assertFalse(session.has_explicit_results) self.assertEqual(session.result_node_ids, ()) - def test_model_and_requires_session_reject_async_functions(self): - async def async_model(): - return scad.make_box_rsolid(width=1.0, height=1.0, depth=1.0) - - async def async_builder(): - return scad.make_box_rsolid(width=1.0, height=1.0, depth=1.0) - - with self.assertRaisesRegex(TypeError, "@model does not support async"): - scad.model(async_model) - with self.assertRaisesRegex( - TypeError, "@requires_session does not support async" - ): - scad.requires_session(async_builder) + def test_removed_decorator_api_is_not_public(self): + for name in ("ModelResult", "model", "requires_session", "capture_result"): + self.assertFalse(hasattr(scad, name), name) if __name__ == "__main__": diff --git a/test/test_inspect_brep.py b/test/test_inspect_brep.py index 7475dcdd..dec75a01 100644 --- a/test/test_inspect_brep.py +++ b/test/test_inspect_brep.py @@ -20,6 +20,7 @@ from OCP.TColStd import TColStd_Array2OfReal from OCP.TColgp import TColgp_Array2OfPnt from OCP.TopoDS import TopoDS_Compound from OCP.gp import gp_Ax2, gp_Dir, gp_Elips, gp_Pnt, gp_Trsf, gp_Vec +from simplecadapi.kernel.ocp_export import export_step_shapes from simplecadapi.inspect import brep import simplecadapi.inspect.brep.compare as compare_module @@ -601,7 +602,7 @@ def test_compare_shape_slices_has_zero_xor_for_same_shape(): def test_step_round_trip_uses_public_inspection_namespace(tmp_path: Path): step = tmp_path / "box.step" - scad.export_step(shapes=_box(), filename=str(step)) + export_step_shapes([_box().wrapped], str(step)) report = brep.inspect_step_rbrepinspection(path=step) comparison = brep.compare_steps_rbrepcomparison( @@ -617,7 +618,7 @@ def test_step_round_trip_uses_public_inspection_namespace(tmp_path: Path): def test_step_model_helpers_cache_and_return_stable_ids(tmp_path: Path): step = tmp_path / "box.step" - scad.export_step(shapes=_box(), filename=str(step)) + export_step_shapes([_box().wrapped], str(step)) brep.clear_step_model_cache_rnone() first = brep.load_step_rbrepmodel(step) diff --git a/test/test_model_json.py b/test/test_model_json.py index cbd783c7..3c4b5947 100644 --- a/test/test_model_json.py +++ b/test/test_model_json.py @@ -518,7 +518,7 @@ class TestModelJson(unittest.TestCase): ): box = scad.make_box_rsolid(2.0, 4.0, 6.0) original = scad.translate_shape(box, (0.0, 0.0, 2.0)) - scad.capture_result(value=original) + session.capture_result(value=original) box_node = next( node @@ -558,7 +558,7 @@ class TestModelJson(unittest.TestCase): sketch = scad.add_circle_rsketch(sketch, "circle", "center", 1.0) original = scad.make_face_from_sketch_rface(sketch, profile="circle") - scad.capture_result(value=original) + session.capture_result(value=original) self.assertEqual(sketch.plane["origin"], (12.0, 24.0, 27.0)) self.assertEqual(sketch.plane["x_axis"], (0.0, 0.0, -1.0)) @@ -648,24 +648,26 @@ class TestOperationGraphDeltaSerialization(unittest.TestCase): ) def test_multi_tool_cut_model_json_is_deterministic(self): - @scad.model(graph_id="deterministic_multi_cut") - def build_model(): - body = scad.make_box_rsolid(4.0, 4.0, 4.0) - tool_a = scad.make_box_rsolid( - 1.0, - 1.0, - 5.0, - bottom_face_center=(1.0, 1.0, -0.5), - ) - tool_b = scad.make_box_rsolid( - 1.0, - 1.0, - 5.0, - bottom_face_center=(2.0, 2.0, -0.5), - ) - return scad.cut_rsolid(body, tool_a, tool_b) + def build_model_json(): + with GraphSession(graph_id="deterministic_multi_cut") as session: + body = scad.make_box_rsolid(4.0, 4.0, 4.0) + tool_a = scad.make_box_rsolid( + 1.0, + 1.0, + 5.0, + bottom_face_center=(1.0, 1.0, -0.5), + ) + tool_b = scad.make_box_rsolid( + 1.0, + 1.0, + 5.0, + bottom_face_center=(2.0, 2.0, -0.5), + ) + result = scad.cut_rsolid(body, tool_a, tool_b) + session.capture_result(value=result) + return scad.export_model_json(session) - self.assertEqual(build_model().model_json, build_model().model_json) + self.assertEqual(build_model_json(), build_model_json()) def test_multi_tool_intersect_topology_delta_keeps_step_chain(self): with GraphSession() as session: diff --git a/test/test_part_builder.py b/test/test_part_builder.py index ad05c477..c214995a 100644 --- a/test/test_part_builder.py +++ b/test/test_part_builder.py @@ -5,6 +5,7 @@ import importlib.util import threading import time from pathlib import Path +import sys import pytest import simplecadapi as scad @@ -53,18 +54,20 @@ def test_part_reuses_runtime_in_process_and_restores_across_wrappers( assert memory_warm.cache_report.hit assert memory_warm.cache_report.part_lookups == 0 assert memory_warm.cache_report.bytes_read == 0 - assert memory_warm.session is cold.session + assert memory_warm.feature_graph is cold.feature_graph assert memory_warm.value is cold.value assert disk_warm.cache_report.hit assert disk_warm.cache_report.part_lookups == 1 assert disk_warm.cache_report.bytes_read > 0 - assert disk_warm.session is not cold.session + assert disk_warm.feature_graph is not cold.feature_graph assert disk_warm.value is not cold.value assert disk_warm.value.body is not cold.value.body assert disk_warm.value.body.get_volume() == pytest.approx(24.0) assert disk_warm.definition.canonical_bytes == cold.definition.canonical_bytes - assert disk_warm.model_json == cold.model_json - assert disk_warm.session.graph.to_dict() == cold.session.graph.to_dict() + assert disk_warm.feature_graph.canonical_bytes == cold.feature_graph.canonical_bytes + assert disk_warm.feature_graph.restore_session().graph.to_dict() == ( + cold.feature_graph.restore_session().graph.to_dict() + ) assert disk_warm.value.connector_ids() == ("mount",) assert disk_warm.definition.interface_hashes == cold.definition.interface_hashes assert scad.list_tags(shape=disk_warm.value.body) == scad.list_tags( @@ -104,7 +107,9 @@ def test_part_accepts_solid_and_wraps_definition_id(tmp_path: Path) -> None: assert result.value.part_id == "solid_result" assert result.value.body.get_volume() == pytest.approx(6.0) - assert result.result_node_ids == result.session.result_node_ids + assert result.feature_graph.result_node_ids == ( + result.feature_graph.restore_session().result_node_ids + ) def test_part_deduplicates_concurrent_same_parameter_calls(tmp_path: Path) -> None: @@ -152,7 +157,9 @@ def test_part_rejects_multiple_explicit_results(tmp_path: Path) -> None: def build(): first = scad.make_box_rsolid(width=1.0, height=1.0, depth=1.0) second = scad.make_box_rsolid(width=2.0, height=2.0, depth=2.0) - scad.capture_result(value=(first, second)) + session = scad.get_active_session() + assert session is not None + session.capture_result(value=(first, second)) return second with pytest.raises(ArtifactValidationError, match="exactly one result node"): @@ -222,6 +229,73 @@ def test_part_key_changes_with_arguments_and_file_bytes_not_mtime( == 3 ) +def test_part_helper_source_change_rebuilds_same_key_without_quarantine( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + (tmp_path / "pyproject.toml").write_text( + "[project]\nname='source-fixture'\nversion='1.0.0'\n", + encoding="utf-8", + ) + helper_path = tmp_path / "cache_helper.py" + builder_path = tmp_path / "builder.py" + helper_path.write_text( + "import simplecadapi as scad\n" + "def make_body():\n" + " return scad.make_box_rsolid(width=1.0, height=2.0, depth=3.0)\n", + encoding="utf-8", + ) + builder_source = ( + "import cache_helper\n" + "def build():\n" + " return cache_helper.make_body()\n" + ) + monkeypatch.syspath_prepend(str(tmp_path)) + _module, function = _load_function(builder_path, builder_source, "build") + policy = _policy(tmp_path / "cache") + first = scad.part( + id="helper_dependent", + cache=policy, + project_root=tmp_path, + )(function)() + first_key = first.cache_report.build_key + first_quarantine = scad.ContentAddressedStore(policy).stats().quarantined + + encoded = scad.encode_part_definition(first.definition) + from simplecadapi.scene.archive import preflight_zip_bytes + + archive = preflight_zip_bytes(encoded, manifest_name="part-definition.json") + feature_payload = archive.members[ + "blobs/" + first.definition.feature_graph_ref.path + ] + archived_graph = scad.load_feature_graph_artifact(feature_payload) + helper_snapshot = next( + item for item in archived_graph.source_files if item.display_path == "cache_helper.py" + ) + assert archived_graph.blobs[helper_snapshot.uri] == helper_path.read_bytes() + + helper_path.write_text( + "import simplecadapi as scad\n" + "def make_body():\n" + " # Deliberately changes helper bytes without changing builder bytes.\n" + " return scad.make_box_rsolid(width=1.0, height=5.0, depth=3.0)\n", + encoding="utf-8", + ) + importlib.invalidate_caches() + sys.modules.pop("cache_helper", None) + _module, changed_function = _load_function(builder_path, builder_source, "build") + changed = scad.part( + id="helper_dependent", + cache=policy, + project_root=tmp_path, + )(changed_function)() + + assert changed.cache_report.build_key == first_key + assert not changed.cache_report.hit + assert changed.cache_report.miss_reason == "source_changed" + assert changed.value.body.get_volume() == pytest.approx(15.0) + assert scad.ContentAddressedStore(policy).stats().quarantined == first_quarantine + def test_part_argument_normalizer_rejects_unknown_cycles_and_nonfinite( tmp_path: Path, @@ -299,25 +373,13 @@ def test_part_corrupt_payload_rebuilds_and_quarantines(tmp_path: Path) -> None: assert store.stats().quarantined >= 1 -def test_part_default_export_is_product_package(tmp_path: Path) -> None: - output = tmp_path / "out" - - @scad.part( - id="exported", - cache=_policy(tmp_path / "cache"), - export_dir=output, - ) - def build() -> scad.Solid: - return scad.make_box_rsolid(width=1.0, height=2.0, depth=3.0) - - result = build() - - assert set(result.artifact_paths) == {"product"} - assert result.artifact_paths["product"].name == "exported.scadpkg" - assert ( - scad.load_product_package(result.artifact_paths["product"]).definition_id - == "exported" - ) +def test_part_rejects_legacy_export_dir(tmp_path: Path) -> None: + with pytest.raises(TypeError, match="export_dir"): + scad.part( + id="exported", + cache=_policy(tmp_path / "cache"), + export_dir=tmp_path / "out", + ) def test_part_definition_archive_round_trip_and_reexport(tmp_path: Path) -> None: @@ -326,7 +388,10 @@ def test_part_definition_archive_round_trip_and_reexport(tmp_path: Path) -> None return scad.make_box_rsolid(width=2.0, height=3.0, depth=4.0) result = build() - first = result.export_definition(path=tmp_path / "first.part-definition.zip") + first = scad.export_part_definition( + result.definition, + tmp_path / "first.part-definition.zip", + ) loaded = scad.load_part_definition(first) second = scad.export_part_definition( loaded, diff --git a/test/test_product_assembly.py b/test/test_product_assembly.py index 29397c22..78e59354 100644 --- a/test/test_product_assembly.py +++ b/test/test_product_assembly.py @@ -6,6 +6,7 @@ import pytest import simplecadapi as scad from simplecadapi import ql +from simplecadapi import scene def test_material_validation_and_assignment_are_separate_from_part_creation(): @@ -573,9 +574,9 @@ def test_boolean_named_face_connector_resolves_after_replay(): tuple(replayed_face.get_center()) ) - package = scad.compile_scene( + package = scene.compile_scene( scene_id="boolean-named-connector", - roots=(scad.SceneRoot(root_id="main", value=replayed),), + roots=(scene.SceneRoot(root_id="main", value=replayed),), ) snapshot = package.manifest["connectors"][0] asset = next( diff --git a/test/test_product_capture.py b/test/test_product_capture.py new file mode 100644 index 00000000..2dd52913 --- /dev/null +++ b/test/test_product_capture.py @@ -0,0 +1,291 @@ +from __future__ import annotations + +from dataclasses import replace +from pathlib import Path + +import pytest + +import simplecadapi as scad +from simplecadapi.artifacts.canonical import canonical_bytes, content_hash, sha256_bytes +from simplecadapi.product_packages import ProductPackage, ProductPackageError +from simplecadapi.scene import ( + ProductScenePackage, + canonical_json_bytes, + canonical_zip_bytes, + compute_scene_revision, + parse_canonical_json, + preflight_zip_bytes, + read_scene_package, +) +from test_product_packages import _build_named_part, _build_nested_assembly + + +def _entity_documents(scene: ProductScenePackage) -> list[dict]: + return [ + parse_canonical_json(scene.blobs[record["uri"]]) + for record in scene.manifest["entity_assets"] + ] + + +def test_capture_part_embeds_one_complete_independent_scene(tmp_path: Path) -> None: + result = _build_named_part(tmp_path, "captured_part") + path = tmp_path / "out" / "captured_part.scadpkg" + + captured = scad.capture(result, path) + payload = path.read_bytes() + loaded = scad.read_product_package(payload) + scene = read_scene_package(loaded.scene_bytes) + + assert captured.value is result.value + assert captured.package.manifest["schema_version"] == "2.0" + assert captured.scene.manifest["schema_version"] == "2.0" + assert loaded.scene_path == "scene/scene.zip" + assert scene.manifest == captured.scene.manifest + assert dict(scene.blobs) == dict(captured.scene.blobs) + assert [item["definition_id"] for item in scene.manifest["definitions"]] == [ + "captured_part" + ] + assert len(scene.manifest["product_assets"]) == 1 + assert len(scene.manifest["feature_graph_assets"]) == 1 + assert scene.manifest["feature_index"] + assert scene.manifest["source_index"] + + +def test_capture_federates_definition_graphs_sources_connectors_and_joints( + tmp_path: Path, +) -> None: + _part, _child, root = _build_nested_assembly(tmp_path) + path = tmp_path / "out" / "root.scadpkg" + + scene = scad.capture(root, path).scene + manifest = scene.manifest + + assert {item["definition_id"] for item in manifest["definitions"]} == { + "linked", + "child", + "root", + } + assert {item["definition_id"] for item in manifest["feature_graph_assets"]} == { + "linked", + "child", + "root", + } + assert {item["definition_id"] for item in manifest["feature_index"]} == { + "linked", + "child", + "root", + } + assert len({item["uri"] for item in manifest["source_index"]}) <= len( + manifest["source_index"] + ) + assert {item["connector_id"] for item in manifest["connectors"]} == { + "mount", + "public_mount", + } + assert len(manifest["joints"]) == 1 + joint = manifest["joints"][0] + assert joint["joint_id"] == "joint/root/nested/joint" + assert joint["connector_a"]["definition_id"] == "linked" + assert joint["connector_b"]["definition_id"] == "linked" + assert joint["source_feature_id"] is not None + feature = next( + item + for item in manifest["feature_index"] + if item["feature_id"] == joint["source_feature_id"] + ) + assert feature["op"] == "make_revolute_constraint_rassembly" + + +def test_capture_preserves_gear_coupling_joint(tmp_path: Path) -> None: + policy = scad.CachePolicy(root=tmp_path / "cache") + + @scad.part(id="coupling_base", cache=policy) + def build_base() -> scad.Part: + part = scad.make_part_rpart( + part_id="coupling_base", + body=scad.make_box_rsolid(width=12.0, height=4.0, depth=2.0), + ) + for connector_id, origin in ( + ("left_axis", (3.0, 2.0, 2.0)), + ("right_axis", (9.0, 2.0, 2.0)), + ): + part = scad.add_connector_rpart( + part=part, + connector=scad.make_placement_connector_rconnector( + connector_id=connector_id, + placement=scad.make_placement_rplacement(origin=origin), + ), + ) + return part + + @scad.part(id="coupling_wheel", cache=policy) + def build_wheel() -> scad.Part: + part = scad.make_part_rpart( + part_id="coupling_wheel", + body=scad.make_cylinder_rsolid(radius=2.0, height=1.0), + ) + return scad.add_connector_rpart( + part=part, + connector=scad.make_placement_connector_rconnector( + connector_id="axis", + placement=scad.identity_placement_rplacement(), + ), + ) + + base = build_base() + wheel = build_wheel() + + @scad.assemble( + id="gear_coupling", + definitions=(base, wheel), + cache=policy, + ) + def build_assembly() -> scad.Assembly: + assembly = scad.make_assembly_rassembly(assembly_id="gear_coupling") + for component_id, item in ( + ("base", base.value), + ("wheel_a", wheel.value), + ("wheel_b", wheel.value), + ): + assembly = scad.add_component_rassembly( + assembly=assembly, + item=item, + component_id=component_id, + placement=scad.identity_placement_rplacement(), + ) + assembly = scad.ground_component_rassembly( + assembly=assembly, + component_id="base", + ) + base_left = scad.make_connector_ref_rconnectorref( + component_id="base", + connector_id="left_axis", + ) + base_right = scad.make_connector_ref_rconnectorref( + component_id="base", + connector_id="right_axis", + ) + wheel_a = scad.make_connector_ref_rconnectorref( + component_id="wheel_a", + connector_id="axis", + ) + wheel_b = scad.make_connector_ref_rconnectorref( + component_id="wheel_b", + connector_id="axis", + ) + assembly = scad.add_revolute_constraint_rassembly( + assembly=assembly, + constraint_id="support_a", + connector_a=base_left, + connector_b=wheel_a, + drive_angle_degrees=30.0, + ) + assembly = scad.add_revolute_constraint_rassembly( + assembly=assembly, + constraint_id="support_b", + connector_a=base_right, + connector_b=wheel_b, + ) + assembly = scad.add_gear_constraint_rassembly( + assembly=assembly, + constraint_id="mesh", + connector_a=wheel_a, + connector_b=wheel_b, + pitch_radius_a=2.0, + pitch_radius_b=4.0, + ) + return scad.solve_assembly_constraints_rassembly(assembly=assembly) + + path = tmp_path / "out" / "gear_coupling.scadpkg" + manifest = scad.capture(build_assembly(), path).scene.manifest + joints = {joint["joint_type"]: joint for joint in manifest["joints"]} + + assert set(joints) == {"revolute", "gear"} + assert joints["gear"]["parameters"] == { + "phase_offset": 0.0, + "pitch_radius_a": 2.0, + "pitch_radius_b": 4.0, + } + feature = next( + item + for item in manifest["feature_index"] + if item["feature_id"] == joints["gear"]["source_feature_id"] + ) + assert feature["op"] == "make_gear_constraint_rassembly" + + +def test_entity_feature_output_matches_durable_topology_snapshot(tmp_path: Path) -> None: + result = _build_named_part(tmp_path, "lineage_part") + path = tmp_path / "out" / "lineage_part.scadpkg" + scene = scad.capture(result, path).scene + definition = result.definition + snapshot = parse_canonical_json( + definition.blobs[definition.topology_snapshot_ref.path] + ) + expected = { + (item["kind"], item["topo_id"]): item["feature_output"] + for item in snapshot["entities"] + } + entity_document = _entity_documents(scene)[0] + + for entity in entity_document["entities"]: + source = entity["source"] + feature_output = expected[(entity["kind"], entity["topo_id"])] + assert source["kind"] == "feature_output" + assert source["graph_id"] == feature_output["graph_id"] + assert source["node_id"] == feature_output["node_id"] + assert source["output_slot"] == feature_output["output_slot"] + assert source["topology_kind"] == feature_output["kind"] + assert source["topo_id"] == feature_output["topo_id"] + + +def test_cold_and_warm_capture_are_byte_identical(tmp_path: Path) -> None: + cold = _build_named_part(tmp_path, "deterministic_capture") + warm = _build_named_part(tmp_path, "deterministic_capture") + cold_path = tmp_path / "out" / "cold.scadpkg" + warm_path = tmp_path / "out" / "warm.scadpkg" + + assert warm.cache_report.hit + cold_capture = scad.capture(cold, cold_path) + warm_capture = scad.capture(warm, warm_path) + assert cold_capture.package_bytes == warm_capture.package_bytes + assert cold_path.read_bytes() == warm_path.read_bytes() + + +def test_product_package_rejects_mutated_embedded_scene(tmp_path: Path) -> None: + package_path = tmp_path / "out" / "mutated_scene.scadpkg" + captured = scad.capture( + _build_named_part(tmp_path, "mutated_scene"), + package_path, + ) + scene_archive = preflight_zip_bytes(captured.package.scene_bytes) + scene_manifest = parse_canonical_json(scene_archive.members["scene.json"]) + scene_manifest["scene_id"] = "changed" + scene_manifest = { + **scene_manifest, + "revision": compute_scene_revision(scene_manifest), + } + changed_scene = canonical_zip_bytes( + {**scene_archive.members, "scene.json": canonical_json_bytes(scene_manifest)} + ) + members = dict(captured.package.objects) + members[captured.package.scene_path] = changed_scene + scene_record = { + **captured.package.manifest["scene"], + "sha256": sha256_bytes(changed_scene), + } + draft = { + key: value + for key, value in captured.package.manifest.items() + if key != "content_hash" + } + draft["scene"] = scene_record + manifest = {**draft, "content_hash": content_hash(draft, omit=())} + mutated = ProductPackage( + manifest=manifest, + objects=members, + root_definition=captured.package.root_definition, + ) + + with pytest.raises(ProductPackageError, match="scene"): + scad.encode_product_package(mutated) diff --git a/test/test_product_exporter.py b/test/test_product_exporter.py new file mode 100644 index 00000000..fbcde60b --- /dev/null +++ b/test/test_product_exporter.py @@ -0,0 +1,319 @@ +"""End-to-end tests for product-package STEP and STL exporters.""" + +from __future__ import annotations + +import json +from pathlib import Path +import tempfile +import unittest + +import numpy as np +import trimesh +from OCP.IFSelect import IFSelect_RetDone +from OCP.STEPCAFControl import STEPCAFControl_Reader +from OCP.StepRepr import StepRepr_DescriptiveRepresentationItem +from OCP.TCollection import TCollection_ExtendedString +from OCP.TDataStd import TDataStd_Name +from OCP.TDocStd import TDocStd_Document +from OCP.XCAFApp import XCAFApp_Application +from OCP.XCAFPrs import XCAFPrs_DocumentExplorer + +import simplecadapi as scad +from simplecadapi.inspect.brep.render import _load_step_xcaf + + +def _label_name(label) -> str: + attribute = TDataStd_Name() + if label.FindAttribute(TDataStd_Name.GetID_s(), attribute): + return attribute.Get().ToExtString() + return "" + + +def _read_occurrences(path: Path) -> list[dict[str, object]]: + XCAFApp_Application.GetApplication_s() + document = TDocStd_Document(TCollection_ExtendedString("BinXCAF")) + reader = STEPCAFControl_Reader() + reader.SetNameMode(True) + reader.SetColorMode(True) + reader.SetPropsMode(True) + if reader.ReadFile(str(path)) != IFSelect_RetDone or not reader.Transfer(document): + raise AssertionError(f"could not read exported STEP file {path}") + explorer = XCAFPrs_DocumentExplorer(document, 0) + records: list[dict[str, object]] = [] + while explorer.More(): + node = explorer.Current() + translation = node.Location.Transformation().TranslationPart() + records.append( + { + "depth": int(explorer.CurrentDepth()), + "name": _label_name(node.Label) or _label_name(node.RefLabel), + "ref_name": _label_name(node.RefLabel), + "assembly": bool(node.IsAssembly), + "xyz": [ + round(float(translation.X()), 3), + round(float(translation.Y()), 3), + round(float(translation.Z()), 3), + ], + } + ) + explorer.Next() + return records + + +def _read_simplecad_metadata(path: Path) -> dict[str, dict[str, object]]: + reader = STEPCAFControl_Reader() + if reader.ReadFile(str(path)) != IFSelect_RetDone: + raise AssertionError(f"could not read exported STEP file {path}") + model = reader.ChangeReader().WS().Model() + records: dict[str, dict[str, object]] = {} + for index in range(1, model.NbEntities() + 1): + entity = model.Entity(index) + if not isinstance(entity, StepRepr_DescriptiveRepresentationItem): + continue + name = entity.Name().ToCString() + if not name.startswith("SimpleCAD:"): + continue + records[name] = json.loads(entity.Description().ToCString()) + return records + + +def _build_nested_package(root: Path): + cache = scad.CachePolicy(root=root / "cache") + + @scad.part(id="linked", cache=cache, project_root=Path(__file__).parent) + def build_part() -> scad.Part: + body = scad.make_box_rsolid(1.0, 2.0, 3.0) + face = scad.apply_tag(body.get_faces()[0], "interface.mount_face") + part = scad.make_part_rpart("linked", body, name="Part linked") + return scad.add_connector_rpart( + part, + scad.make_face_connector_rconnector("mount", face), + ) + + part = build_part() + + @scad.assemble( + id="child", + definitions=(part,), + cache=cache, + project_root=Path(__file__).parent, + ) + def build_child() -> scad.Assembly: + assembly = scad.make_assembly_rassembly("child", name="Child assembly") + for component_id, name in ( + ("inner_a", "Inner linked part A"), + ("inner_b", "Inner linked part B"), + ): + assembly = scad.add_component_rassembly( + assembly, + part.value, + component_id=component_id, + placement=scad.identity_placement_rplacement(), + name=name, + ) + assembly = scad.ground_component_rassembly(assembly, "inner_a") + assembly = scad.add_revolute_constraint_rassembly( + assembly, + "joint", + scad.make_connector_ref_rconnectorref("inner_a", "mount"), + scad.make_connector_ref_rconnectorref("inner_b", "mount"), + drive_angle_degrees=15.0, + ) + return scad.solve_assembly_constraints_rassembly(assembly) + + child = build_child() + + @scad.assemble( + id="root", + definitions=(child, part), + cache=cache, + project_root=Path(__file__).parent, + ) + def build_root() -> scad.Assembly: + assembly = scad.make_assembly_rassembly("root", name="Root assembly") + assembly = scad.add_component_rassembly( + assembly, + child.value, + component_id="nested", + placement=scad.make_placement_rplacement(origin=(10.0, 0.0, 0.0)), + name="Nested child assembly", + ) + return scad.add_component_rassembly( + assembly, + part.value, + component_id="direct", + placement=scad.make_placement_rplacement(origin=(0.0, 5.0, 0.0)), + name="Direct linked part", + ) + + return scad.build_product_package(build_root()) + + +class TestProductExporter(unittest.TestCase): + def test_exporters_are_available_only_from_exporter_namespace(self): + self.assertIs( + scad.exporter.export_product_package_to_step, + scad.exporter.step.export_product_package_to_step, + ) + self.assertIs( + scad.exporter.export_product_package_to_stl, + scad.exporter.stl.export_product_package_to_stl, + ) + self.assertFalse(hasattr(scad, "export_step")) + self.assertFalse(hasattr(scad, "export_stl")) + self.assertFalse(hasattr(scad.translator, "ap242_translator")) + + def test_nested_package_preserves_ap242_product_structure_and_placements(self): + + with tempfile.TemporaryDirectory() as tmp_dir: + root = Path(tmp_dir) + package = _build_nested_package(root) + step_path = root / "nested.step" + report = scad.exporter.export_product_package_to_step(package, step_path) + records = _read_occurrences(step_path) + content = step_path.read_text(encoding="utf-8") + metadata = _read_simplecad_metadata(step_path) + + self.assertIn("AP242_MANAGED_MODEL_BASED_3D_ENGINEERING", content) + self.assertEqual(report.schema, "AP242DIS") + self.assertEqual(report.definition_ids, ("linked", "child", "root")) + self.assertEqual(report.occurrence_count, 4) + self.assertEqual(report.metadata_item_count, 7) + self.assertEqual( + set(metadata), + { + "SimpleCAD:definition:single_solid:linked", + "SimpleCAD:definition:assembly:child", + "SimpleCAD:definition:assembly:root", + "SimpleCAD:occurrence:child:inner_a", + "SimpleCAD:occurrence:child:inner_b", + "SimpleCAD:occurrence:root:nested", + "SimpleCAD:occurrence:root:direct", + }, + ) + linked = metadata["SimpleCAD:definition:single_solid:linked"] + self.assertEqual(linked["revision"], "1.0.0") + self.assertRegex(str(linked["content_hash"]), r"^sha256:[0-9a-f]{64}$") + self.assertEqual(linked["connectors"][0]["connector_id"], "mount") + child = metadata["SimpleCAD:definition:assembly:child"] + self.assertEqual(child["grounded_component_ids"], ["inner_a"]) + self.assertEqual(child["constraints"][0]["constraint_id"], "joint") + self.assertEqual(child["constraints"][0]["drive_angle_degrees"], 15.0) + nested = metadata["SimpleCAD:occurrence:root:nested"] + self.assertEqual(nested["definition_id"], "child") + self.assertEqual(nested["placement"]["origin"], [10.0, 0.0, 0.0]) + self.assertEqual( + records, + [ + { + "depth": 0, + "name": "Root assembly", + "ref_name": "Root assembly", + "assembly": True, + "xyz": [0.0, 0.0, 0.0], + }, + { + "depth": 1, + "name": "Direct linked part", + "ref_name": "Part linked", + "assembly": False, + "xyz": [0.0, 5.0, 0.0], + }, + { + "depth": 1, + "name": "Nested child assembly", + "ref_name": "Child assembly", + "assembly": True, + "xyz": [10.0, 0.0, 0.0], + }, + { + "depth": 2, + "name": "Inner linked part A", + "ref_name": "Part linked", + "assembly": False, + "xyz": [10.0, 0.0, 0.0], + }, + { + "depth": 2, + "name": "Inner linked part B", + "ref_name": "Part linked", + "assembly": False, + "xyz": [10.0, -0.388, 0.051], + }, + ], + ) + self.assertTrue(any("feature history" in item for item in report.limitations)) + self.assertFalse(any("OCAF comments" in item for item in report.limitations)) + + def test_part_material_and_color_enter_stepcaf_payload(self): + + with tempfile.TemporaryDirectory() as tmp_dir: + root = Path(tmp_dir) + cache = scad.CachePolicy(root=root / "cache") + + @scad.part( + id="colored", + cache=cache, + project_root=Path(__file__).parent, + ) + def build_colored() -> scad.Part: + body = scad.make_box_rsolid(1.0, 2.0, 3.0) + part = scad.make_part_rpart("colored", body, name="Colored part") + material = scad.make_material_rmaterial( + "blue_aluminum", + name="Blue aluminum", + density=2.7e-6, + density_unit="kg/mm^3", + color=(0.2, 0.4, 0.6), + ) + return scad.assign_material_rpart(part, material) + + package = scad.build_product_package(build_colored()) + step_path = root / "colored.step" + report = scad.exporter.export_product_package_to_step(package, step_path) + content = step_path.read_text(encoding="utf-8") + _shape, face_colors = _load_step_xcaf(step_path) + + self.assertEqual(report.material_ids, ("blue_aluminum",)) + self.assertIn( + "PROPERTY_DEFINITION('material property','material name'", content + ) + self.assertIn("MEASURE_REPRESENTATION_ITEM('kg/mm^3',2.7E-06", content) + self.assertIn('"material_id": "blue_aluminum"', content) + self.assertTrue(face_colors) + self.assertEqual( + { + tuple(round(value, 3) for value in color[:3]) + for color in face_colors.values() + }, + {(0.2, 0.4, 0.6)}, + ) + + def test_nested_package_exports_quad_dominant_stl(self): + with tempfile.TemporaryDirectory() as tmp_dir: + root = Path(tmp_dir) + package = _build_nested_package(root) + stl_path = root / "nested.stl" + report = scad.exporter.export_product_package_to_stl( + package, + stl_path, + mesh_size=0.75, + ) + mesh = trimesh.load_mesh(stl_path, force="mesh", process=False) + + self.assertEqual(report.root_definition_id, "root") + self.assertEqual(report.definition_count, 3) + self.assertEqual(report.solid_count, 3) + self.assertGreater(report.quadrilateral_count, 0) + self.assertGreater(report.quad_fraction, 0.5) + self.assertEqual(len(mesh.faces), report.stl_triangle_count) + self.assertTrue( + np.allclose( + mesh.bounds, + [[-0.5, -1.35415439394285, -0.2077077845361233], [10.5, 6.0, 3.207707784536123]], + ) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/test_product_packages.py b/test/test_product_packages.py index b3bca0fe..c7cbe5f4 100644 --- a/test/test_product_packages.py +++ b/test/test_product_packages.py @@ -113,18 +113,23 @@ def test_part_package_wraps_canonical_prt_and_preserves_naming_binding( ) -> None: part = _build_named_part(tmp_path) package = scad.build_product_package(part) - path = scad.export_product_package(package, tmp_path / "box.scadpkg") + payload = scad.encode_product_package(package) - loaded_package = scad.read_product_package(path) - loaded_definition = scad.load_product_package(path) + loaded_package = scad.read_product_package(payload) + loaded_definition = scad.load_product_package(payload) rebuilt = scad.materialize_definition(loaded_definition) assert loaded_package.root_kind == "single_solid" assert loaded_package.root_id == "box" assert isinstance(loaded_definition, scad.PartDefinition) assert rebuilt.part_id == "box" - assert len(loaded_package.objects) == 1 - assert next(iter(loaded_package.objects)).endswith(".part-definition.zip") + definition_paths = [ + path for path in loaded_package.objects if path.startswith("objects/") + ] + assert len(definition_paths) == 1 + assert definition_paths[0].endswith(".part-definition.zip") + assert loaded_package.scene_path == "scene/scene.zip" + assert loaded_package.scene_path in loaded_package.objects topology = parse_canonical_json( loaded_definition.blobs[loaded_definition.topology_snapshot_ref.path] @@ -169,8 +174,8 @@ def test_nested_assembly_package_preserves_hierarchy_relations_and_dedup( ) -> None: part, child, root = _build_nested_assembly(tmp_path) package = scad.build_product_package(root) - path = scad.export_product_package(package, tmp_path / "root.scadpkg") - loaded = scad.load_product_package(path) + payload = scad.encode_product_package(package) + loaded = scad.load_product_package(payload) rebuilt = scad.materialize_definition(loaded) assert isinstance(loaded, scad.AssemblyDefinition) @@ -237,8 +242,11 @@ def test_product_package_rejects_mutation_missing_and_unreachable_objects( ) extra_part = _build_named_part(tmp_path, "unused") - extra_path = next(iter(scad.build_product_package(extra_part).objects)) - extra_payload = scad.build_product_package(extra_part).objects[extra_path] + extra_package = scad.build_product_package(extra_part) + extra_path = next( + path for path in extra_package.objects if path.endswith(".part-definition.zip") + ) + extra_payload = extra_package.objects[extra_path] objects = {**package.objects, extra_path: extra_payload} records = [ *package.manifest["objects"], @@ -254,10 +262,11 @@ def test_product_package_rejects_mutation_missing_and_unreachable_objects( ] records.sort(key=lambda item: item["path"]) draft = { - "schema_version": "1.0", + "schema_version": "2.0", "artifact_kind": "product_package", "root": package.root_path, "objects": records, + "scene": dict(package.manifest["scene"]), } manifest = { **draft, @@ -275,13 +284,13 @@ def test_product_package_rejects_mutation_missing_and_unreachable_objects( ) -def test_product_package_reexport_is_byte_identical(tmp_path: Path) -> None: +def test_product_package_encode_round_trip_is_byte_identical(tmp_path: Path) -> None: package = scad.build_product_package(_build_named_part(tmp_path)) - first = scad.export_product_package(package, tmp_path / "first.scadpkg") + first = scad.encode_product_package(package) loaded = scad.read_product_package(first) - second = scad.export_product_package(loaded, tmp_path / "second.scadpkg") + second = scad.encode_product_package(loaded) - assert first.read_bytes() == second.read_bytes() + assert first == second def test_validated_package_skips_repeated_decode_validation( @@ -427,46 +436,33 @@ def test_replaced_part_definition_does_not_inherit_validation( scad.encode_part_definition(mutated) -def test_build_result_default_exports_unified_product_package(tmp_path: Path) -> None: +def test_capture_function_exports_unified_product_package(tmp_path: Path) -> None: part = _build_named_part(tmp_path, "exported") - exported = part.export_artifacts(output_dir=tmp_path / "out") + path = tmp_path / "out" / "exported.scadpkg" + captured = scad.capture(part, path) - assert set(exported.artifact_paths) == {"product"} - assert exported.artifact_paths["product"].name == "exported.scadpkg" - loaded = scad.load_product_package(exported.artifact_paths["product"]) + assert path.is_file() + assert path.read_bytes() == captured.package_bytes + loaded = scad.load_product_package(path) assert isinstance(loaded, scad.PartDefinition) assert loaded.definition_id == "exported" -def test_assembly_build_result_exports_unified_product_package(tmp_path: Path) -> None: +def test_capture_assembly_exports_unified_product_package(tmp_path: Path) -> None: _part, _child, root = _build_nested_assembly(tmp_path) - exported = root.export_artifacts(output_dir=tmp_path / "out") + path = tmp_path / "out" / "root.scadpkg" + captured = scad.capture(root, path) - assert set(exported.artifact_paths) == {"product"} - assert exported.artifact_paths["product"].name == "root.scadpkg" - loaded = scad.load_product_package(exported.artifact_paths["product"]) + assert path.is_file() + assert path.read_bytes() == captured.package_bytes + loaded = scad.load_product_package(path) assert isinstance(loaded, scad.AssemblyDefinition) assert loaded.definition_id == "root" -@pytest.mark.parametrize("format_name", ["part", "prt", "assembly", "asm"]) -def test_build_results_reject_legacy_product_formats( - tmp_path: Path, - format_name: str, -) -> None: - part, _child, root = _build_nested_assembly(tmp_path) +def test_capture_rejects_legacy_keyword_signature(tmp_path: Path) -> None: + part = _build_named_part(tmp_path, "no_keyword_compatibility") + path = tmp_path / "out" / "no_keyword_compatibility.scadpkg" - with pytest.raises(ValueError, match="only the 'product' format"): - part.export_artifacts(output_dir=tmp_path, formats=(format_name,)) - with pytest.raises(ValueError, match="only the 'product' format"): - root.export_artifacts(output_dir=tmp_path, formats=(format_name,)) - - -def test_model_result_does_not_export_runtime_product_packages(tmp_path: Path) -> None: - @scad.model(graph_id="runtime_model") - def build_model() -> scad.Part: - body = scad.make_box_rsolid(width=1.0, height=2.0, depth=3.0) - return scad.make_part_rpart("runtime_part", body) - - with pytest.raises(ValueError, match="@part/@assemble"): - build_model().export_artifacts(output_dir=tmp_path, formats=("prt",)) + with pytest.raises(TypeError, match="positional-only"): + scad.capture(value=part, path=path) diff --git a/test/test_public_api_surface.py b/test/test_public_api_surface.py index 174c09e4..8946c42a 100644 --- a/test/test_public_api_surface.py +++ b/test/test_public_api_surface.py @@ -114,7 +114,6 @@ print(json.dumps({ "ProductPackageError": product_packages.ProductPackageError, "build_product_package": product_packages.build_product_package, "encode_product_package": product_packages.encode_product_package, - "export_product_package": product_packages.export_product_package, "load_product_package": product_packages.load_product_package, "read_product_package": product_packages.read_product_package, "validate_product_package": product_packages.validate_product_package, @@ -129,7 +128,46 @@ print(json.dumps({ "build_assembly_package", "load_part_package", "load_assembly_package", + "export_product_package", ): with self.subTest(legacy_name=legacy_name): self.assertNotIn(legacy_name, scad.__all__) self.assertFalse(hasattr(scad, legacy_name)) + + self.assertFalse(hasattr(product_packages, "export_product_package")) + + def test_scene_implementation_is_not_top_level_product_api(self): + import simplecadapi as scad + from simplecadapi import scene + + internal_scene_names = ( + "CanonicalEdgeBlock", + "CanonicalTriangleBlock", + "CompiledScenePackage", + "ProductSceneError", + "ProductScenePackage", + "RenderEdgeMesh", + "RenderGroup", + "RenderMesh", + "SceneCompileOptions", + "SceneRoot", + "SceneSource", + "build_edge_mesh", + "build_render_mesh", + "cad_direction_to_gltf", + "cad_to_gltf", + "compile_product_scene", + "compile_scene", + "encode_product_scene", + "export_scene", + "read_scene_package", + "solid_asset_bounds", + "validate_product_scene_package", + "write_line_glb", + "write_triangle_glb", + ) + for name in internal_scene_names: + with self.subTest(name=name): + self.assertNotIn(name, scad.__all__) + self.assertFalse(hasattr(scad, name)) + self.assertTrue(hasattr(scene, name)) diff --git a/test/test_rearchitecture_2_0_contract.py b/test/test_rearchitecture_2_0_contract.py index 7ae55c6b..dae59155 100644 --- a/test/test_rearchitecture_2_0_contract.py +++ b/test/test_rearchitecture_2_0_contract.py @@ -260,9 +260,11 @@ class TestRearchitecture20IoContracts(unittest.TestCase): self.assertGreaterEqual(payload["graph"].node_count, 1) self.assertGreaterEqual(payload["expression_graph"].node_count, 1) - def test_step_export_still_exists_as_final_geometry_export(self): - self.assertTrue(hasattr(scad, "export_step")) - self.assertTrue(hasattr(scad, "export_stl")) + def test_step_and_stl_exports_require_product_package_boundary(self): + self.assertFalse(hasattr(scad, "export_step")) + self.assertFalse(hasattr(scad, "export_stl")) + self.assertTrue(hasattr(scad.exporter, "export_product_package_to_step")) + self.assertTrue(hasattr(scad.exporter, "export_product_package_to_stl")) def test_model_json_export_exists_as_canonical_seed(self): r = scad.var("r", 2.0) diff --git a/test/test_scene_compiler.py b/test/test_scene_compiler.py index 4641fa4e..517dbda2 100644 --- a/test/test_scene_compiler.py +++ b/test/test_scene_compiler.py @@ -1,13 +1,11 @@ from __future__ import annotations -import hashlib -import json -from pathlib import Path import pytest import simplecadapi as scad from simplecadapi import _mesh +from simplecadapi import scene from simplecadapi.scene import ( export_scene, parse_canonical_json, @@ -18,56 +16,17 @@ from simplecadapi.scene import ( ) -def _manual_source() -> scad.SceneSource: - return scad.SceneSource(kind="manual", source_id="main") +def _manual_source() -> scene.SceneSource: + return scene.SceneSource(kind="manual", source_id="main") -def _mutable_package(package, tmp_path, name): - archive_path = tmp_path / f"{name}.scene.zip" - export_scene(package=package, path=archive_path) - archive = preflight_zip_bytes(archive_path.read_bytes()) - manifest = parse_canonical_json(archive.members["scene.json"]) - blobs = { - uri: payload - for uri, payload in archive.members.items() - if uri != "scene.json" - } - return manifest, blobs - - -def _replace_embedded_model(manifest, blobs, model): - payload = json.dumps(model, sort_keys=True, separators=(",", ":")).encode( - "utf-8" - ) - blobs["model/model.json"] = payload - manifest["source"]["artifact_hash"] = ( - "sha256:" + hashlib.sha256(payload).hexdigest() - ) - manifest["source"]["embedded_artifact_byte_length"] = len(payload) - return with_scene_revision(manifest) - - -@pytest.fixture -def embedded_source_package(): - @scad.model(graph_id="source-boundaries") - def build_model(): - return scad.make_box_rsolid(width=2.0, height=3.0, depth=4.0) - - result = build_model() - return scad.compile_scene( - scene_id="source-boundaries", - roots=(scad.SceneRoot(root_id="main", value=result.value),), - source=result, - options=scad.SceneCompileOptions(embed_source=True), - ) - def test_compile_scene_is_deterministic_and_self_validating(): solid = scad.make_box_rsolid(width=10.0, height=20.0, depth=30.0) - roots = (scad.SceneRoot(root_id="main", value=solid),) + roots = (scene.SceneRoot(root_id="main", value=solid),) - first = scad.compile_scene(scene_id="box", roots=roots, source=_manual_source()) - second = scad.compile_scene(scene_id="box", roots=roots, source=_manual_source()) + first = scene.compile_scene(scene_id="box", roots=roots, source=_manual_source()) + second = scene.compile_scene(scene_id="box", roots=roots, source=_manual_source()) assert first.manifest == second.manifest assert dict(first.blobs) == dict(second.blobs) @@ -75,141 +34,13 @@ def test_compile_scene_is_deterministic_and_self_validating(): assert first.manifest["revision"].startswith("sha256:") -def test_embedded_python_source_is_integrity_checked(tmp_path): - @scad.model(graph_id="source-integrity") - def build_model(): - return scad.make_box_rsolid(width=2.0, height=3.0, depth=4.0) - - result = build_model() - package = scad.compile_scene( - scene_id="source-integrity", - roots=(scad.SceneRoot(root_id="main", value=result.value),), - source=result, - options=scad.SceneCompileOptions(embed_source=True), - ) - source_record = package.manifest["source"]["source_files"][0] - - assert source_record["path"] == "test/test_scene_compiler.py" - assert package.blobs[source_record["uri"]] == Path(__file__).read_bytes() - assert validate_scene_package(package.manifest, package.blobs).valid - - tampered = dict(package.blobs) - tampered[source_record["uri"]] += b"\n# tampered\n" - report = validate_scene_package(package.manifest, tampered) - assert not report.valid - assert {issue.code for issue in report.issues} >= { - "blob_hash_mismatch", - "blob_length_mismatch", - } - - archive_path = tmp_path / "source-integrity.scene.zip" - export_scene(package=package, path=archive_path) - archive = preflight_zip_bytes(archive_path.read_bytes()) - malformed_manifest = parse_canonical_json(archive.members["scene.json"]) - malformed_manifest["source"]["source_files"][0]["uri"] = "sources/wrong.py" - malformed_manifest = with_scene_revision(malformed_manifest) - report = validate_scene_package(malformed_manifest, package.blobs) - assert not report.valid - assert "source_matrix_invalid" in {issue.code for issue in report.issues} - - -def test_model_scene_rejects_root_from_different_graph_with_same_graph_id(): - @scad.model(graph_id="shared-provenance-id") - def first_model(): - return scad.make_box_rsolid(width=1.0, height=2.0, depth=3.0) - - @scad.model(graph_id="shared-provenance-id") - def second_model(): - return scad.make_box_rsolid(width=4.0, height=5.0, depth=6.0) - - first = first_model() - second = second_model() - - with pytest.raises(ValueError, match="not owned by the source model graph"): - scad.compile_scene( - scene_id="cross-graph-root", - roots=(scad.SceneRoot(root_id="main", value=first.value),), - source=second, - ) - - -def test_model_scene_rejects_stale_model_result_snapshot(): - @scad.model(graph_id="stale-model-snapshot") - def build_model(): - return scad.make_box_rsolid(width=1.0, height=2.0, depth=3.0) - - result = build_model() - result.session.graph.add_node("late_mutation", node_id="late_mutation") - - with pytest.raises(ValueError, match="no longer matches its model JSON snapshot"): - scad.compile_scene( - scene_id="stale-model-snapshot", - roots=(scad.SceneRoot(root_id="main", value=result.value),), - source=result, - ) - - -def test_manifest_rejects_unsafe_embedded_python_path( - embedded_source_package, tmp_path -): - manifest, _blobs = _mutable_package( - embedded_source_package, tmp_path, "unsafe-source-path" - ) - source_file = manifest["source"]["source_files"][0] - source_file["path"] = "test/../test_scene_compiler.py" - source_file["uri"] = "sources/test/../test_scene_compiler.py" - report = validate_scene_manifest(with_scene_revision(manifest)) - - assert any( - issue.code == "source_matrix_invalid" - and issue.path == "/source/source_files/0/path" - for issue in report.issues - ) - - -def test_package_rejects_malformed_operation_source_mapping( - embedded_source_package, tmp_path -): - manifest, blobs = _mutable_package( - embedded_source_package, tmp_path, "malformed-operation-source" - ) - model = json.loads(blobs["model/model.json"]) - node = next(node for node in model["graph"]["nodes"] if "source" in node) - node["source"].pop("callsite_id") - manifest = _replace_embedded_model(manifest, blobs, model) - report = validate_scene_package(manifest, blobs) - - assert any( - issue.code == "source_matrix_invalid" - and issue.path.endswith("/graph/nodes/0/source") - for issue in report.issues - ) - - -def test_package_rejects_invalid_utf8_python_source( - embedded_source_package, tmp_path -): - manifest, blobs = _mutable_package( - embedded_source_package, tmp_path, "invalid-source-utf8" - ) - source_file = manifest["source"]["source_files"][0] - payload = b"\xff" - blobs[source_file["uri"]] = payload - source_file["byte_length"] = len(payload) - source_file["content_hash"] = "sha256:" + hashlib.sha256(payload).hexdigest() - report = validate_scene_package(with_scene_revision(manifest), blobs) - - assert any( - issue.code == "invalid_utf8" and issue.path == f"/{source_file['uri']}" - for issue in report.issues - ) def test_sphere_entity_uses_kernel_axis_directions(): solid = scad.make_sphere_rsolid(radius=2.5, center=(1.0, 2.0, 3.0)) - package = scad.compile_scene( + package = scene.compile_scene( scene_id="sphere", - roots=(scad.SceneRoot(root_id="main", value=solid),), + roots=(scene.SceneRoot(root_id="main", value=solid),), source=_manual_source(), ) entity_uri = package.manifest["entity_assets"][0]["uri"] @@ -248,9 +79,9 @@ def test_repeated_part_occurrences_reuse_definition_and_assets(): placement=scad.make_placement_rplacement(origin=(10.0, 0.0, 0.0)), ) - package = scad.compile_scene( + package = scene.compile_scene( scene_id="repeated", - roots=(scad.SceneRoot(root_id="main", value=assembly),), + roots=(scene.SceneRoot(root_id="main", value=assembly),), source=_manual_source(), ) definitions = package.manifest["definitions"] @@ -292,9 +123,9 @@ def test_same_part_id_with_different_body_geometry_is_rejected(): ) with pytest.raises(ValueError, match="conflicting Part body geometry"): - scad.compile_scene( + scene.compile_scene( scene_id="conflict", - roots=(scad.SceneRoot(root_id="main", value=assembly),), + roots=(scene.SceneRoot(root_id="main", value=assembly),), source=_manual_source(), ) @@ -308,9 +139,9 @@ def test_manual_face_connector_is_exported_with_entity_target(): part = scad.make_part_rpart(part_id="block", body=solid) part = scad.add_connector_rpart(part=part, connector=connector) - package = scad.compile_scene( + package = scene.compile_scene( scene_id="connector", - roots=(scad.SceneRoot(root_id="main", value=part),), + roots=(scene.SceneRoot(root_id="main", value=part),), source=_manual_source(), ) snapshot = package.manifest["connectors"][0] @@ -326,7 +157,7 @@ def test_render_and_collision_use_the_same_default_mesh_object(): cached = _mesh.cached_mesh(solid) assert cached is not None - render = scad.build_render_mesh( + render = scene.build_render_mesh( solid, face_entity_ids=[f"entity/face/{index}" for index in range(len(solid.get_faces()))], linear_tolerance=0.35, @@ -341,13 +172,13 @@ def test_edge_mesh_uses_angular_tolerance_for_curved_edges(): solid = scad.make_cylinder_rsolid(radius=2.0, height=5.0) edge_ids = [f"edge-{index}" for index, _edge in enumerate(solid.get_edges())] - default = scad.build_edge_mesh( + default = scene.build_edge_mesh( solid, edge_entity_ids=edge_ids, linear_tolerance=0.35, angular_tolerance=0.22, ) - finer = scad.build_edge_mesh( + finer = scene.build_edge_mesh( solid, edge_entity_ids=edge_ids, linear_tolerance=0.35, @@ -364,7 +195,7 @@ def test_edge_mesh_default_angular_tolerance_preserves_public_call_shape(): solid = scad.make_cylinder_rsolid(radius=2.0, height=5.0) edge_ids = [f"edge-{index}" for index, _edge in enumerate(solid.get_edges())] - mesh = scad.build_edge_mesh( + mesh = scene.build_edge_mesh( solid, edge_entity_ids=edge_ids, linear_tolerance=0.35, @@ -374,10 +205,10 @@ def test_edge_mesh_default_angular_tolerance_preserves_public_call_shape(): def test_compiler_declares_angular_edge_render_profile(): - package = scad.compile_scene( + package = scene.compile_scene( scene_id="edge-profile", roots=( - scad.SceneRoot( + scene.SceneRoot( root_id="main", value=scad.make_cylinder_rsolid(radius=2.0, height=5.0), ), @@ -397,10 +228,10 @@ def test_compiler_declares_angular_edge_render_profile(): def test_validator_keeps_profile_1_scene_packages_readable(tmp_path): - package = scad.compile_scene( + package = scene.compile_scene( scene_id="legacy-profile", roots=( - scad.SceneRoot( + scene.SceneRoot( root_id="main", value=scad.make_box_rsolid(width=2.0, height=3.0, depth=4.0), ), @@ -418,9 +249,9 @@ def test_validator_keeps_profile_1_scene_packages_readable(tmp_path): def test_export_scene_is_canonical_and_round_trips_through_archive_preflight(tmp_path): - package = scad.compile_scene( + package = scene.compile_scene( scene_id="archive", - roots=(scad.SceneRoot(root_id="main", value=scad.make_box_rsolid(width=2.0, height=3.0, depth=4.0)),), + roots=(scene.SceneRoot(root_id="main", value=scad.make_box_rsolid(width=2.0, height=3.0, depth=4.0)),), source=_manual_source(), ) first_path = tmp_path / "first.scene.zip" @@ -470,9 +301,9 @@ def test_forwarded_connector_is_finalized_after_its_source_connector(): placement=scad.identity_placement_rplacement(), ) - package = scad.compile_scene( + package = scene.compile_scene( scene_id="forwarded", - roots=(scad.SceneRoot(root_id="main", value=root),), + roots=(scene.SceneRoot(root_id="main", value=root),), source=_manual_source(), ) @@ -480,59 +311,3 @@ def test_forwarded_connector_is_finalized_after_its_source_connector(): source = next(item for item in package.manifest["connectors"] if item["connector_id"] == "axis") assert forwarded["forwarded_from"]["source_connector_snapshot_id"] == source["connector_snapshot_id"] assert validate_scene_package(package.manifest, package.blobs).valid - - -def test_model_connector_sources_use_product_attachment_operations(): - @scad.model(graph_id="connector_provenance") - def build_model(): - body = scad.make_box_rsolid(width=2.0, height=2.0, depth=2.0) - part = scad.make_part_rpart(part_id="block", body=body) - part = scad.add_connector_rpart( - part=part, - connector=scad.make_placement_connector_rconnector( - connector_id="axis", - placement=scad.identity_placement_rplacement(), - ), - ) - assembly = scad.make_assembly_rassembly(assembly_id="root") - assembly = scad.add_component_rassembly( - assembly=assembly, - item=part, - component_id="block", - placement=scad.identity_placement_rplacement(), - ) - assembly = scad.forward_connector_rassembly( - assembly=assembly, - connector_id="public_axis", - source_component_id="block", - source_connector_id="axis", - ) - assembly = scad.place_component_rassembly( - assembly=assembly, - component_id="block", - placement=scad.make_placement_rplacement(origin=(1.0, 0.0, 0.0)), - ) - scad.capture_result(value=assembly) - return assembly - - result = build_model() - package = scad.compile_scene( - scene_id="connector-provenance", - roots=(scad.SceneRoot(root_id="main", value=result.value),), - source=result, - ) - graph_nodes = { - node.node_id: node for node in result.session.graph.nodes - } - sources = { - connector["connector_id"]: connector["source"] - for connector in package.manifest["connectors"] - } - - assert graph_nodes[sources["axis"]["node_id"]].op == "make_add_connector_rpart" - assert ( - graph_nodes[sources["public_axis"]["node_id"]].op - == "make_forward_connector_rassembly" - ) - assert sources["axis"]["node_id"] != sources["public_axis"]["node_id"] - assert validate_scene_package(package.manifest, package.blobs).valid diff --git a/test/test_serialization.py b/test/test_serialization.py index 57acb37a..5b437659 100644 --- a/test/test_serialization.py +++ b/test/test_serialization.py @@ -281,6 +281,7 @@ class TestCoverageMatrix(unittest.TestCase): "make_assign_material_rpart", "make_assembly_rassembly", "make_add_component_rassembly", + "reference_definition", "make_place_component_rassembly", "make_compound_from_assembly_rcompound", "make_face_connector_rconnector", @@ -301,6 +302,7 @@ class TestCoverageMatrix(unittest.TestCase): "make_belt_constraint_rassembly", "make_rack_pinion_constraint_rassembly", "make_solve_assembly_constraints_rassembly", + "evaluate_assembly_definition", "make_extrude_rsolid", "make_revolve_rsolid", "make_loft_rsolid", diff --git a/test/test_skill_pack.py b/test/test_skill_pack.py index 2e9e1019..da27c77b 100644 --- a/test/test_skill_pack.py +++ b/test/test_skill_pack.py @@ -184,14 +184,15 @@ class TestSkillPackPathResolution(unittest.TestCase): content = packager._build_skill_markdown() self.assertIn("GraphSession", content) - self.assertIn("ModelResult", content) - self.assertIn("@model", content) - self.assertIn("capture_result", content) + self.assertNotIn("ModelResult", content) + self.assertNotIn("@model", content) + self.assertIn("session.capture_result", content) self.assertIn("export_model_json", content) self.assertIn("replay_model_json", content) self.assertIn("Use the graph/model JSON workflow", content) self.assertIn("use keyword arguments", content) - self.assertIn("do not use positional arguments", content) + self.assertIn("capture(result, path)", content) + self.assertIn("two required arguments are positional", content) self.assertIn("Standard Parts Library", content) self.assertIn("references/docs/stdlib/README.md", content) self.assertIn("scad.std.gear", content) @@ -203,7 +204,7 @@ class TestSkillPackPathResolution(unittest.TestCase): self.assertIn("MODELING_WORKFLOWS.md", content) self.assertIn("references/inspect/brep-reverse-engineering.md", content) self.assertIn("simplecadapi.inspect.brep", content) - self.assertIn("outside `GraphSession` and `@model`", content) + self.assertIn("outside `GraphSession`", content) self.assertIn("Acceptance hierarchy", content) self.assertIn("ad hoc inspection code", content) self.assertIn("SDK_PACKAGE_SUMMARY.md", content) diff --git a/test/test_solidworks_translator.py b/test/test_solidworks_translator.py index 60447427..6ed79313 100644 --- a/test/test_solidworks_translator.py +++ b/test/test_solidworks_translator.py @@ -1,97 +1,107 @@ -"""Host-independent tests for the SolidWorks translator backend.""" +"""Host-independent tests for the SolidWorks product translator.""" from __future__ import annotations +import ast import importlib +from pathlib import Path import sys -import unittest -import simplecadapi as scad -from simplecadapi import GraphSession -from simplecadapi.translator.errors import TranslationRequestError +from test_product_exporter import _build_nested_package -def _rectangle_extrusion_model() -> str: - with GraphSession() as session: - profile = scad.make_rectangle_rface(width=2.0, height=1.0) - scad.extrude_rsolid( - profile=profile, - direction=(0.0, 0.0, 1.0), - distance=3.0, +def _model_payload(script: str) -> dict: + module = ast.parse(script) + return next( + ast.literal_eval(node.value) + for node in module.body + if isinstance(node, ast.Assign) + and any( + isinstance(target, ast.Name) and target.id == "MODEL_PAYLOAD" + for target in node.targets ) - return scad.export_model_json(session=session) + ) -class TestSolidWorksTranslator(unittest.TestCase): - def test_backend_imports_without_target_runtime_modules(self): - before = set(sys.modules) +def test_backend_imports_without_target_runtime_modules() -> None: + before = set(sys.modules) - solidworks = importlib.import_module( - "simplecadapi.translator.solidworks_translator" - ) + solidworks = importlib.import_module( + "simplecadapi.translator.solidworks_translator" + ) - self.assertNotIn("pythoncom", set(sys.modules) - before) - self.assertNotIn("win32com.client", set(sys.modules) - before) - self.assertEqual(solidworks.CAPABILITIES.backend_id, "solidworks") - - def test_supported_graph_emits_deterministic_compilable_script(self): - model_json = _rectangle_extrusion_model() - from simplecadapi.translator.solidworks_translator import SolidWorksTranslator - - translator = SolidWorksTranslator(document_name="ContractSolidWorks") - first = translator.translate_model_json(model_json) - second = translator.translate_model_json(model_json) - - self.assertEqual(first.content, second.content) - compile(first.content, "", "exec") - self.assertFalse(first.metadata["target_runtime_validated"]) - self.assertTrue(translator.capabilities.targets[0].requires_external_runtime) - - def test_fallback_scripts_are_deterministic(self): - with GraphSession() as session: - profile = scad.make_rectangle_rface(3.0, 3.0) - solid = scad.extrude_rsolid(profile, (0.0, 0.0, 1.0), 3.0) - scad.fillet_rsolid(solid, [solid.get_edges(0)], 0.2) - model_json = scad.export_model_json(session) - - from simplecadapi.translator.solidworks_translator import SolidWorksTranslator - - translator = SolidWorksTranslator(source_kernel_fallback=True) - first = translator.translate_model_json(model_json).content - second = translator.translate_model_json(model_json).content - - self.assertEqual(first, second) - compile(first, "", "exec") - - def test_script_owns_com_and_only_its_created_document(self): - from simplecadapi.translator.solidworks_translator import SolidWorksTranslator - - script = ( - SolidWorksTranslator(visible=True) - .translate_model_json(_rectangle_extrusion_model()) - .content - ) - - main_offset = script.index("def main():") - coinit_offset = script.index("pythoncom.CoInitialize()", main_offset) - runtime_offset = script.index( - "runtime = SimpleCADSolidWorksRuntime", main_offset - ) - self.assertLess(coinit_offset, runtime_offset) - self.assertEqual(script.count("pythoncom.CoInitialize()"), 1) - self.assertIn("self.sw.CloseDoc(str(_maybe_call(self.model.GetTitle)))", script) - self.assertIn("if not self.visible:", script) - self.assertIn("self.sw.ExitApp()", script) - - def test_unsupported_result_operation_is_rejected_before_host_execution(self): - with GraphSession() as session: - scad.make_box_rsolid(width=1.0, height=2.0, depth=3.0) - - from simplecadapi.translator.solidworks_translator import SolidWorksTranslator - - with self.assertRaises(TranslationRequestError): - SolidWorksTranslator().translate_model_json(scad.export_model_json(session)) + assert "pythoncom" not in set(sys.modules) - before + assert "win32com.client" not in set(sys.modules) - before + assert solidworks.CAPABILITIES.backend_id == "solidworks" + assert solidworks.CAPABILITIES.input_schema_versions == ("product-package-2.0",) -if __name__ == "__main__": - unittest.main() +def test_nested_package_emits_deterministic_compilable_script(tmp_path: Path) -> None: + from simplecadapi.translator.solidworks_translator import SolidWorksTranslator + + package = _build_nested_package(tmp_path) + translator = SolidWorksTranslator(document_name="ContractSolidWorks") + first = translator.translate_product_package(package) + second = translator.translate_product_package(package) + + assert first.content == second.content + compile(first.content, "", "exec") + assert first.metadata["root_definition_id"] == "root" + assert first.metadata["root_definition_kind"] == "assembly" + assert first.metadata["definition_ids"] == ("linked", "child", "root") + assert first.metadata["target_runtime_validated"] is False + assert translator.capabilities.targets[0].requires_external_runtime + + +def test_product_payload_resolves_references_and_keeps_solved_placements( + tmp_path: Path, +) -> None: + from simplecadapi.translator.solidworks_translator import SolidWorksTranslator + + script = SolidWorksTranslator().translate_product_package( + _build_nested_package(tmp_path) + ).content + payload = _model_payload(script) + operations = [node["op"] for node in payload["graph"]["nodes"]] + evaluations = [ + node["params"] + for node in payload["graph"]["nodes"] + if node["op"] == "evaluate_assembly_definition" + ] + + assert "reference_definition" not in operations + assert operations.count("make_box_rsolid") == 1 + assert operations.count("evaluate_assembly_definition") == 2 + assert evaluations[0]["constraint_report"]["solved"] is True + + +def test_script_owns_com_and_contains_native_product_paths(tmp_path: Path) -> None: + from simplecadapi.translator.solidworks_translator import SolidWorksTranslator + + script = SolidWorksTranslator(visible=True).translate_product_package( + _build_nested_package(tmp_path) + ).content + + main_offset = script.index("def main():") + coinit_offset = script.index("pythoncom.CoInitialize()", main_offset) + runtime_offset = script.index( + "runtime = SimpleCADSolidWorksRuntime", main_offset + ) + assert coinit_offset < runtime_offset + assert script.count("pythoncom.CoInitialize()") == 1 + assert "self.sw.CloseDoc(str(_maybe_call(self.model.GetTitle)))" in script + assert "if not self.visible:" in script + assert "self.sw.ExitApp()" in script + assert "if op == 'make_box_rsolid':" in script + assert "self._extrude_profile(" in script + assert "if op == 'evaluate_assembly_definition':" in script + assert "_save_native_assembly" in script + assert "SimpleCADComponentMap" in script + + +def test_public_surface_has_no_model_json_or_compiler_entrypoints() -> None: + from simplecadapi.translator import solidworks_translator as solidworks + + assert "translate_product_package_to_solidworks_script" in solidworks.__all__ + assert all("model_json" not in name for name in solidworks.__all__) + assert all("ScriptTranslator" not in name for name in solidworks.__all__) diff --git a/test/test_source_mapping.py b/test/test_source_mapping.py index 1af5dd2e..be22a28a 100644 --- a/test/test_source_mapping.py +++ b/test/test_source_mapping.py @@ -78,8 +78,7 @@ def test_source_mapping_records_complex_targets_and_return(): assert second.source["assignment_targets"] == ["items[index]"] -def test_source_mapping_records_return_and_requires_session_builder(): - @scad.requires_session +def test_source_mapping_records_return_from_plain_builder(): def build_box(): return scad.make_box_rsolid(1.0, 1.0, 1.0) diff --git a/test/test_surface_api.py b/test/test_surface_api.py index 243114d6..8b5b01a3 100644 --- a/test/test_surface_api.py +++ b/test/test_surface_api.py @@ -74,7 +74,7 @@ class TestSurfaceApi(unittest.TestCase): [scad.SurfaceBoundary(edge) for edge in edges], tag_prefix="patch", ) - scad.capture_result(value=[gordon, patch]) + session.capture_result(value=[gordon, patch]) replayed = scad.replay_model_json(scad.export_model_json(session)) self.assertEqual(len(replayed), 2) @@ -95,7 +95,7 @@ class TestSurfaceApi(unittest.TestCase): end_wire_tag="anchor.outlet", side_faces_tag="group.side", ) - scad.capture_result(value=open_shell) + session.capture_result(value=open_shell) replayed = scad.replay_model_json(scad.export_model_json(session), strict=True)[0] self.assertIsInstance(replayed, scad.Shell) @@ -131,7 +131,7 @@ class TestSurfaceApi(unittest.TestCase): ) shell = scad.sew_faces_rshell([face]) boundaries = scad.free_boundaries_rwirelist(shell) - scad.capture_result(value=boundaries) + session.capture_result(value=boundaries) replayed = scad.replay_model_json(scad.export_model_json(session)) self.assertEqual(len(boundaries), 1) diff --git a/test/test_translator_backend_contract.py b/test/test_translator_backend_contract.py index 97b3aef9..e2b8b986 100644 --- a/test/test_translator_backend_contract.py +++ b/test/test_translator_backend_contract.py @@ -1,4 +1,4 @@ -"""Contract tests shared by translator backends.""" +"""Contract tests shared by product-package translator backends.""" from __future__ import annotations @@ -7,7 +7,6 @@ from pathlib import Path import unittest import simplecadapi as scad -from simplecadapi.graph import GraphSession from simplecadapi.serializer import CANONICAL_OP_SET from simplecadapi.translator.base import BaseTranslator from simplecadapi.translator.freecad_translator import FreeCADTranslator @@ -28,8 +27,11 @@ class TestTranslatorBackendContract(unittest.TestCase): / "simplecadapi" / "translator" ) - backend_dirs = sorted(translator_root.glob("*_translator")) - self.assertTrue(backend_dirs) + backend_dirs = sorted( + path + for path in translator_root.glob("*_translator") + if (path / "__init__.py").is_file() + ) for backend_dir in backend_dirs: for filename in ( @@ -92,18 +94,49 @@ class TestTranslatorBackendContract(unittest.TestCase): self.assertTrue(runtime_source) compile(runtime_source, "", "exec") - def test_freecad_translator_is_reusable_and_emits_valid_python(self): - with GraphSession() as session: - scad.make_box_rsolid(1.0, 2.0, 3.0) + def test_all_translators_are_reusable_for_product_packages(self): + cache = scad.CachePolicy(mode="off") - model_json = scad.export_model_json(session) - translator = FreeCADTranslator(document_name="ContractTest") - first = translator.translate_model_json_to_script(model_json) - second = translator.translate_model_json_to_script(model_json) + @scad.part(id="contract_part", cache=cache) + def build_part() -> scad.Part: + body = scad.make_box_rsolid(1.0, 2.0, 3.0) + return scad.make_part_rpart("contract_part", body) + + package = scad.build_product_package(build_part()) + + from simplecadapi import translator + + for backend_name in translator.__all__: + backend = getattr(translator, backend_name) + translator_class = getattr( + backend, f"{backend.CAPABILITIES.display_name}Translator" + ) + instance = translator_class(document_name="ContractTest") + first = instance.translate_product_package(package) + second = instance.translate_product_package(package) + + self.assertEqual(first.content, second.content, backend_name) + self.assertEqual(first.metadata["root_definition_id"], "contract_part") + self.assertEqual( + backend.CAPABILITIES.input_schema_versions, + ("product-package-2.0",), + ) + compile(first.content, f"<{backend_name}-script>", "exec") + + def test_translator_public_surfaces_do_not_expose_model_json(self): + from simplecadapi import translator + + for backend_name in translator.__all__: + backend = getattr(translator, backend_name) + self.assertFalse( + any("model_json" in name for name in backend.__all__), + backend_name, + ) + self.assertFalse( + any("ScriptTranslator" in name for name in backend.__all__), + backend_name, + ) - self.assertEqual(first, second) - self.assertIn('DOC_NAME = "ContractTest"', first) - compile(first, "", "exec") if __name__ == "__main__": diff --git a/tools/run_example_scene_exports.py b/tools/run_example_scene_exports.py deleted file mode 100644 index c0761a0f..00000000 --- a/tools/run_example_scene_exports.py +++ /dev/null @@ -1,383 +0,0 @@ -"""Run every current example model in an isolated process and export scenes. - -This is intentionally a disposable harness for the example tagging migration. -It uses the model list from ``test_example_model_contract`` so the execution -set stays aligned with the repository's structural contract. -""" - -from __future__ import annotations - -import argparse -import ast -from concurrent.futures import ThreadPoolExecutor, as_completed -from datetime import datetime, timezone -import importlib.util -import json -import os -from pathlib import Path -import shutil -import signal -import subprocess -import sys -import time -from typing import Any - - -ROOT = Path(__file__).resolve().parents[1] -EXAMPLES = ROOT / "examples" -DEFAULT_TIMEOUT_SECONDS = 900 -DEFAULT_HEAVY_TIMEOUT_SECONDS = 1800 -HEAVY_CASES = { - "examples/16_compact_two_stage_planetary_reducer/main.py", - "examples/20_integrated_bldc_joint_actuator/main.py", -} - - -def _is_model_decorator(node: ast.expr) -> bool: - if isinstance(node, ast.Call): - node = node.func - return ( - isinstance(node, ast.Attribute) - and isinstance(node.value, ast.Name) - and node.value.id == "scad" - and node.attr == "model" - ) or (isinstance(node, ast.Name) and node.id == "model") - - -def _builder_name(path: Path) -> str: - tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) - model_functions = [ - node.name - for node in tree.body - if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) - and any(_is_model_decorator(decorator) for decorator in node.decorator_list) - ] - if len(model_functions) != 1: - raise RuntimeError(f"expected one @model entry in {path}, got {model_functions}") - return model_functions[0] - - -def _model_cases() -> list[tuple[str, str]]: - contract_path = ROOT / "test" / "test_example_model_contract.py" - spec = importlib.util.spec_from_file_location( - "simplecadapi_example_model_contract", contract_path - ) - if spec is None or spec.loader is None: - raise RuntimeError(f"could not load model contract: {contract_path}") - contract = importlib.util.module_from_spec(spec) - spec.loader.exec_module(contract) - - cases = [] - for path in contract._model_files(): - relative_path = path.resolve().relative_to(ROOT).as_posix() - cases.append((relative_path, _builder_name(path))) - return cases - - -def _child_main(relative_path: str, builder_name: str, output_dir: Path) -> None: - path = (ROOT / relative_path).resolve() - sys.path.insert(0, str(path.parent)) - spec = importlib.util.spec_from_file_location( - f"simplecadapi_scene_case_{os.getpid()}", path - ) - if spec is None or spec.loader is None: - raise RuntimeError(f"could not load example module: {path}") - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - builder = getattr(module, builder_name) - result = builder() - exported = result.export_artifacts(output_dir=output_dir) - print( - "SCENE_RUN_RESULT=" - + json.dumps( - { - "graph_id": exported.session.graph.graph_id, - "artifact_paths": { - key: str(value) for key, value in exported.artifact_paths.items() - }, - "result_node_count": len(exported.result_node_ids), - }, - sort_keys=True, - ), - flush=True, - ) - - -def _kill_process_group(process: subprocess.Popen[str]) -> None: - try: - os.killpg(process.pid, signal.SIGKILL) - except ProcessLookupError: - pass - - -def _run_case( - *, - relative_path: str, - builder_name: str, - run_dir: Path, - timeout_seconds: int, - heavy_timeout_seconds: int, -) -> dict[str, Any]: - case_name = relative_path.removesuffix(".py").replace("/", "__") - case_dir = run_dir / case_name - case_dir.mkdir(parents=True, exist_ok=True) - attempt = 1 - while (case_dir / f"stdout.attempt-{attempt}.log").exists(): - attempt += 1 - for log_name in ("stdout.log", "stderr.log"): - log_path = case_dir / log_name - if log_path.exists(): - log_path.replace( - case_dir / f"{log_path.stem}.attempt-{attempt}{log_path.suffix}" - ) - timeout = ( - heavy_timeout_seconds - if relative_path in HEAVY_CASES - else timeout_seconds - ) - command = [ - sys.executable, - str(Path(__file__).resolve()), - "--child", - relative_path, - builder_name, - str(case_dir), - ] - environment = dict(os.environ) - environment["PYTHONHASHSEED"] = "0" - started_at = datetime.now(timezone.utc) - started = time.monotonic() - print( - f"[scene-export] starting {relative_path}::{builder_name} " - f"timeout={timeout}s", - flush=True, - ) - stdout = "" - stderr = "" - returncode: int | None = None - timed_out = False - error: str | None = None - try: - process = subprocess.Popen( - command, - cwd=ROOT, - env=environment, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - text=True, - errors="replace", - start_new_session=True, - ) - try: - stdout, stderr = process.communicate(timeout=timeout) - returncode = process.returncode - except subprocess.TimeoutExpired as exc: - timed_out = True - _kill_process_group(process) - stdout, stderr = process.communicate() - if exc.stdout: - stdout = str(exc.stdout) - if exc.stderr: - stderr = str(exc.stderr) - except Exception as exc: # pragma: no cover - harness failure path - error = f"{exc.__class__.__name__}: {exc}" - - elapsed = time.monotonic() - started - (case_dir / "stdout.log").write_text(stdout, encoding="utf-8") - (case_dir / "stderr.log").write_text(stderr, encoding="utf-8") - scene_paths = sorted(case_dir.glob("*.scene.zip")) - child_result: dict[str, Any] | None = None - for line in stdout.splitlines(): - if line.startswith("SCENE_RUN_RESULT="): - try: - child_result = json.loads(line.removeprefix("SCENE_RUN_RESULT=")) - except json.JSONDecodeError: - error = "invalid SCENE_RUN_RESULT payload" - - status = "passed" - if timed_out: - status = "timeout" - elif error is not None or returncode != 0: - status = "failed" - elif len(scene_paths) != 1: - status = "failed" - error = f"expected one scene zip, found {len(scene_paths)}" - - record = { - "case": relative_path, - "builder": builder_name, - "case_dir": str(case_dir.relative_to(ROOT)), - "status": status, - "returncode": returncode, - "timed_out": timed_out, - "timeout_seconds": timeout, - "elapsed_seconds": round(elapsed, 3), - "started_at": started_at.isoformat(), - "stdout_log": str((case_dir / "stdout.log").relative_to(ROOT)), - "stderr_log": str((case_dir / "stderr.log").relative_to(ROOT)), - "scene_paths": [str(path.relative_to(ROOT)) for path in scene_paths], - "child_result": child_result, - "error": error, - "attempt": attempt, - } - print( - f"[scene-export] {status} {relative_path} elapsed={elapsed:.1f}s", - flush=True, - ) - return record - - -def _publish_scenes( - run_dir: Path, - records: list[dict[str, Any]], -) -> list[dict[str, Any]]: - scene_dir = run_dir / "scenes" - scene_dir.mkdir(parents=True, exist_ok=True) - for existing in scene_dir.glob("*.scene.zip"): - existing.unlink() - published: list[dict[str, Any]] = [] - for record in records: - scene_paths = record.get("scene_paths", []) - if record.get("status") != "passed" or len(scene_paths) != 1: - continue - case_path = Path(record["case"]) - case_name = ( - case_path.parent.name if case_path.name == "main.py" else case_path.stem - ) - source_path = ROOT / scene_paths[0] - destination = scene_dir / f"{case_name}.scene.zip" - shutil.copy2(source_path, destination) - published.append( - { - "case": record["case"], - "path": str(destination.relative_to(ROOT)), - } - ) - return published - - -def _parent_main(args: argparse.Namespace) -> int: - all_cases = _model_cases() - previous_records: dict[str, dict[str, Any]] = {} - if args.resume is not None: - run_dir = args.resume.resolve() - report_path = run_dir / "execution_report.json" - previous_report = json.loads(report_path.read_text(encoding="utf-8")) - run_id = str(previous_report["run_id"]) - started_at = datetime.fromisoformat(previous_report["started_at"]) - previous_records = { - record["case"]: record for record in previous_report["cases"] - } - cases = [ - case - for case in all_cases - if previous_records.get(case[0], {}).get("status") != "passed" - ] - print( - f"[scene-export] resuming {run_id}; retrying {len(cases)} cases", - flush=True, - ) - else: - cases = all_cases - run_id = datetime.now(timezone.utc).strftime("scene_export_%Y%m%dT%H%M%SZ") - run_dir = EXAMPLES / "out" / run_id - run_dir.mkdir(parents=True, exist_ok=False) - started_at = datetime.now(timezone.utc) - if args.case: - requested = set(args.case) - cases = [case for case in cases if case[0] in requested] - unknown = requested - {case[0] for case in all_cases} - if unknown: - raise ValueError(f"unknown example cases: {sorted(unknown)}") - if args.publish_only: - cases = [] - records: list[dict[str, Any]] = [] - with ThreadPoolExecutor(max_workers=args.workers) as executor: - futures = { - executor.submit( - _run_case, - relative_path=relative_path, - builder_name=builder_name, - run_dir=run_dir, - timeout_seconds=args.timeout, - heavy_timeout_seconds=args.heavy_timeout, - ): (relative_path, builder_name) - for relative_path, builder_name in cases - } - for future in as_completed(futures): - relative_path, builder_name = futures[future] - try: - records.append(future.result()) - except Exception as exc: # pragma: no cover - harness failure path - records.append( - { - "case": relative_path, - "builder": builder_name, - "status": "failed", - "error": f"runner worker {exc.__class__.__name__}: {exc}", - } - ) - - records_by_case = dict(previous_records) - records_by_case.update({record["case"]: record for record in records}) - records = sorted(records_by_case.values(), key=lambda record: record["case"]) - report = { - "run_id": run_id, - "started_at": started_at.isoformat(), - "finished_at": datetime.now(timezone.utc).isoformat(), - "root": str(ROOT), - "workers": args.workers, - "timeout_seconds": args.timeout, - "heavy_timeout_seconds": args.heavy_timeout, - "case_count": len(all_cases), - "passed": sum(record.get("status") == "passed" for record in records), - "failed": sum(record.get("status") == "failed" for record in records), - "timed_out": sum(record.get("status") == "timeout" for record in records), - "cases": records, - } - report_path = run_dir / "execution_report.json" - manifest_path = run_dir / "manifest.json" - report_path.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n") - published_scenes = _publish_scenes(run_dir, records) - manifest = { - "run_id": run_id, - "case_count": len(all_cases), - "successful_scene_count": len(published_scenes), - "standalone_scene_packages": published_scenes, - } - manifest_path.write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n") - print(f"[scene-export] report={report_path}", flush=True) - print(f"[scene-export] scenes={run_dir / 'scenes'}", flush=True) - print( - f"[scene-export] passed={report['passed']} failed={report['failed']} " - f"timed_out={report['timed_out']}", - flush=True, - ) - return 0 if report["failed"] == 0 and report["timed_out"] == 0 else 1 - - -def main() -> int: - parser = argparse.ArgumentParser() - parser.add_argument("--child", nargs=3, metavar=("PATH", "BUILDER", "OUTPUT")) - parser.add_argument("--workers", type=int, default=3) - parser.add_argument("--timeout", type=int, default=DEFAULT_TIMEOUT_SECONDS) - parser.add_argument("--resume", type=Path) - parser.add_argument("--case", action="append") - parser.add_argument("--publish-only", action="store_true") - parser.add_argument( - "--heavy-timeout", type=int, default=DEFAULT_HEAVY_TIMEOUT_SECONDS - ) - args = parser.parse_args() - if args.child: - relative_path, builder_name, output = args.child - _child_main(relative_path, builder_name, Path(output).resolve()) - return 0 - if args.workers < 1: - parser.error("--workers must be at least 1") - if args.publish_only and args.resume is None: - parser.error("--publish-only requires --resume") - return _parent_main(args) - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/run_examples.py b/tools/run_examples.py new file mode 100644 index 00000000..87f956cc --- /dev/null +++ b/tools/run_examples.py @@ -0,0 +1,313 @@ +"""Run every documented example and validate each emitted product package.""" + +from __future__ import annotations + +import argparse +from concurrent.futures import ThreadPoolExecutor, as_completed +from dataclasses import dataclass +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import time +from typing import Any + +import simplecadapi as scad +from simplecadapi.scene import read_scene_package + + +ROOT = Path(__file__).resolve().parents[1] +EXAMPLES = ROOT / "examples" +DEFAULT_TIMEOUT_SECONDS = 900 +DEFAULT_HEAVY_TIMEOUT_SECONDS = 1800 + + +@dataclass(frozen=True, slots=True) +class ExampleCase: + path: str + package_path: str + args: tuple[str, ...] = () + heavy: bool = False + + @property + def step_path(self) -> str: + return str(Path(self.package_path).with_suffix(".step")) + + @property + def fcstd_path(self) -> str: + return str(Path(self.package_path).with_suffix(".FCStd")) + + @property + def output_paths(self) -> tuple[str, str, str]: + return (self.package_path, self.step_path, self.fcstd_path) + + +CASES = ( + ExampleCase( + "examples/04_dimension_tolerance_chain.py", + "examples/out/dimension_tolerance_chain/dimension_tolerance_chain.scadpkg", + ), + ExampleCase( + "examples/08_constrained_sketch.py", + "examples/out/constrained_sketch/constrained_sketch.scadpkg", + heavy=True, + ), + ExampleCase( + "examples/09_naca0016_blade_freecad.py", + "examples/out/naca0016_blade/naca0016_blade.scadpkg", + heavy=True, + ), + ExampleCase( + "examples/10_part_assembly.py", + "examples/out/hydraulic_rod_assembly/hydraulic_rod_assembly.scadpkg", + heavy=True, + ), + ExampleCase( + "examples/11_external_reference_gear_train.py", + "examples/out/external_reference_gear_train/" + "nested_external_reference_gear_trains.scadpkg", + ), + ExampleCase( + "examples/12_ap242_gmsh_volume_mesh.py", + "examples/out/ap242_gmsh_volume_mesh/ap242_gmsh_bracket.scadpkg", + args=("--skip-mesh",), + ), + ExampleCase( + "examples/7ep_caplcd_enclosure.py", + "examples/out/7ep_caplcd_enclosure/caplcd_enclosure_7ep.scadpkg", + ), + ExampleCase( + "examples/16_compact_two_stage_planetary_reducer/main.py", + "examples/out/compact_two_stage_planetary_reducer/" + "compact_two_stage_planetary_reducer.scadpkg", + heavy=True, + ), + ExampleCase( + "examples/20_integrated_bldc_joint_actuator/main.py", + "examples/out/integrated_bldc_joint_actuator/" + "integrated_bldc_joint_actuator.scadpkg", + heavy=True, + ), +) + + +def _kill_process_group(process: subprocess.Popen[str]) -> None: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + + +def _inspect_product_package(path: Path) -> dict[str, Any]: + package = scad.read_product_package(path) + scene = read_scene_package(package.scene_bytes) + manifest = package.manifest + scene_manifest = scene.manifest + if manifest["schema_version"] != "2.0": + raise ValueError("product package is not schema 2.0") + if scene_manifest["schema_version"] != "2.0": + raise ValueError("embedded scene is not schema 2.0") + if len(scene_manifest["product_assets"]) != len(manifest["objects"]): + raise ValueError("embedded scene definition closure is incomplete") + if not scene_manifest["feature_graph_assets"]: + raise ValueError("embedded scene has no feature graph assets") + if not scene_manifest["source_assets"]: + raise ValueError("embedded scene has no source assets") + return { + "path": str(path.relative_to(ROOT)), + "byte_length": path.stat().st_size, + "content_hash": manifest["content_hash"], + "root_definition_id": package.root_definition.definition_id, + "root_definition_kind": package.root_definition.definition_kind, + "definition_count": len(manifest["objects"]), + "feature_graph_asset_count": len(scene_manifest["feature_graph_assets"]), + "feature_count": len(scene_manifest["feature_index"]), + "source_asset_count": len(scene_manifest["source_assets"]), + "source_index_count": len(scene_manifest["source_index"]), + } + + +def _case_directory(run_dir: Path, case: ExampleCase) -> Path: + return run_dir / case.path.removesuffix(".py").replace("/", "__") + + +def _run_case( + case: ExampleCase, + *, + run_dir: Path, + timeout_seconds: int, + heavy_timeout_seconds: int, +) -> dict[str, Any]: + case_dir = _case_directory(run_dir, case) + case_dir.mkdir(parents=True, exist_ok=True) + timeout = heavy_timeout_seconds if case.heavy else timeout_seconds + command = [sys.executable, case.path, *case.args] + environment = dict(os.environ) + environment["PYTHONHASHSEED"] = "0" + output_paths = tuple(ROOT / path for path in case.output_paths) + previous_output_mtimes = { + path: path.stat().st_mtime_ns if path.exists() else None + for path in output_paths + } + started_at = datetime.now(timezone.utc) + started = time.monotonic() + print(f"[examples] starting {case.path} timeout={timeout}s", flush=True) + stdout = "" + stderr = "" + returncode: int | None = None + timed_out = False + error: str | None = None + package_inspection: dict[str, Any] | None = None + export_inspection: dict[str, dict[str, Any]] | None = None + try: + process = subprocess.Popen( + command, + cwd=ROOT, + env=environment, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + errors="replace", + start_new_session=True, + ) + try: + stdout, stderr = process.communicate(timeout=timeout) + returncode = process.returncode + except subprocess.TimeoutExpired: + timed_out = True + _kill_process_group(process) + stdout, stderr = process.communicate() + except Exception as exc: # pragma: no cover - runner failure path + error = f"{exc.__class__.__name__}: {exc}" + + if returncode == 0 and not timed_out and error is None: + try: + for output_path in output_paths: + if not output_path.is_file(): + raise FileNotFoundError(f"expected example artifact: {output_path}") + if output_path.stat().st_size <= 0: + raise RuntimeError(f"example artifact is empty: {output_path}") + previous_mtime = previous_output_mtimes[output_path] + if ( + previous_mtime is not None + and output_path.stat().st_mtime_ns <= previous_mtime + ): + raise RuntimeError( + f"example artifact was not rewritten by this run: {output_path}" + ) + package_path = output_paths[0] + export_inspection = { + output_path.suffix: { + "path": str(output_path.relative_to(ROOT)), + "byte_length": output_path.stat().st_size, + } + for output_path in output_paths[1:] + } + package_inspection = _inspect_product_package(package_path) + except Exception as exc: + error = f"{exc.__class__.__name__}: {exc}" + + elapsed = time.monotonic() - started + (case_dir / "stdout.log").write_text(stdout, encoding="utf-8") + (case_dir / "stderr.log").write_text(stderr, encoding="utf-8") + status = "passed" + if timed_out: + status = "timeout" + elif error is not None or returncode != 0: + status = "failed" + record = { + "case": case.path, + "status": status, + "returncode": returncode, + "timed_out": timed_out, + "timeout_seconds": timeout, + "elapsed_seconds": round(elapsed, 3), + "started_at": started_at.isoformat(), + "stdout_log": str((case_dir / "stdout.log").relative_to(ROOT)), + "stderr_log": str((case_dir / "stderr.log").relative_to(ROOT)), + "package": package_inspection, + "exports": export_inspection, + "error": error, + } + print(f"[examples] {status} {case.path} elapsed={elapsed:.1f}s", flush=True) + return record + + +def _run_all(args: argparse.Namespace) -> int: + all_cases = {case.path: case for case in CASES} + selected = list(CASES) + if args.case: + unknown = set(args.case) - set(all_cases) + if unknown: + raise ValueError(f"unknown example cases: {sorted(unknown)}") + selected = [all_cases[path] for path in args.case] + run_id = datetime.now(timezone.utc).strftime("examples_%Y%m%dT%H%M%SZ") + run_dir = EXAMPLES / "out" / run_id + run_dir.mkdir(parents=True, exist_ok=False) + started_at = datetime.now(timezone.utc) + records: list[dict[str, Any]] = [] + with ThreadPoolExecutor(max_workers=args.workers) as executor: + futures = { + executor.submit( + _run_case, + case, + run_dir=run_dir, + timeout_seconds=args.timeout, + heavy_timeout_seconds=args.heavy_timeout, + ): case + for case in selected + } + for future in as_completed(futures): + case = futures[future] + try: + records.append(future.result()) + except Exception as exc: # pragma: no cover - runner failure path + records.append( + { + "case": case.path, + "status": "failed", + "error": f"runner worker {exc.__class__.__name__}: {exc}", + } + ) + records.sort(key=lambda record: record["case"]) + report = { + "run_id": run_id, + "started_at": started_at.isoformat(), + "finished_at": datetime.now(timezone.utc).isoformat(), + "root": str(ROOT), + "case_count": len(selected), + "passed": sum(record["status"] == "passed" for record in records), + "failed": sum(record["status"] == "failed" for record in records), + "timed_out": sum(record["status"] == "timeout" for record in records), + "cases": records, + } + report_path = run_dir / "execution_report.json" + report_path.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n") + print(f"[examples] report={report_path}", flush=True) + print( + f"[examples] passed={report['passed']} failed={report['failed']} " + f"timed_out={report['timed_out']}", + flush=True, + ) + return 0 if report["failed"] == 0 and report["timed_out"] == 0 else 1 + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--workers", type=int, default=1) + parser.add_argument("--timeout", type=int, default=DEFAULT_TIMEOUT_SECONDS) + parser.add_argument( + "--heavy-timeout", type=int, default=DEFAULT_HEAVY_TIMEOUT_SECONDS + ) + parser.add_argument("--case", action="append") + args = parser.parse_args() + if args.workers < 1: + parser.error("--workers must be at least 1") + return _run_all(args) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/uv.lock b/uv.lock index 320fb1b5..f364e95a 100644 --- a/uv.lock +++ b/uv.lock @@ -855,6 +855,17 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/16/02/767f744ab6d4cb7761e5008acc3d534b7a0481af62563d52e391fbcb2140/genson-1.4.0-py3-none-any.whl", hash = "sha256:03bc71bbe52defde70660cc4dcd1ea1097997da5a1cbb90a9dbd3acc7c9e1b65", size = 24484, upload-time = "2026-07-06T08:21:49.046Z" }, ] +[[package]] +name = "gmsh" +version = "4.15.2" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/19/a6/f3f74f53234c812ffa0191ce2aceb0811ea82bdf12867a73bebb03f28f7a/gmsh-4.15.2-py2.py3-none-macosx_10_15_x86_64.whl", hash = "sha256:9f5a97b6633e40be331cb777ab571cef96e6ff5979bb7b20aad2438724ca417b", size = 40171095, upload-time = "2026-03-24T19:33:46.37Z" }, + { url = "https://files.pythonhosted.org/packages/3d/b4/0d25938ad62ea4db6bcbdecbc77c72d05d8a6a679abe4addcd86167ffd77/gmsh-4.15.2-py2.py3-none-macosx_12_0_arm64.whl", hash = "sha256:f6649b3e59f49272e7ee8ab282ecb4d1a6e0d627e86cf3e3b1a83fd07417e4f8", size = 36427761, upload-time = "2026-03-24T19:33:51.161Z" }, + { url = "https://files.pythonhosted.org/packages/ab/d4/336becb1488ac4fbab205043987128839c8c62d54e2036b7e887bd009040/gmsh-4.15.2-py2.py3-none-manylinux_2_24_x86_64.whl", hash = "sha256:4076a948ce22625330d1413d4982e22b5c69fc2f0f7951f5df64c778cf54108c", size = 40006930, upload-time = "2026-03-24T19:33:55.549Z" }, + { url = "https://files.pythonhosted.org/packages/78/e9/63c763c0d75544680800651d5ea8c7c3203ae4b5e054706f19a54021a7fb/gmsh-4.15.2-py2.py3-none-win_amd64.whl", hash = "sha256:7b36083bb410fa27c5d0e052929d1a9844a5b09169d66017b72b41aabd49d711", size = 42235999, upload-time = "2026-03-24T19:34:00.529Z" }, +] + [[package]] name = "h11" version = "0.16.0" @@ -2952,6 +2963,9 @@ dev = [ { name = "pytest" }, { name = "pytest-cov" }, ] +gmsh = [ + { name = "gmsh" }, +] inspect = [ { name = "matplotlib" }, ] @@ -2972,6 +2986,7 @@ dev = [ requires-dist = [ { name = "black", marker = "extra == 'dev'", specifier = ">=23.0" }, { name = "cadquery-ocp", specifier = ">=7.9.3.1" }, + { name = "gmsh", marker = "extra == 'gmsh'", specifier = ">=4.15,<5" }, { name = "isort", marker = "extra == 'dev'", specifier = ">=5.0" }, { name = "jsonschema", specifier = ">=4.25.1,<5.0.0" }, { name = "matplotlib", marker = "extra == 'inspect'", specifier = ">=3.7.0" }, @@ -2987,7 +3002,7 @@ requires-dist = [ { name = "tomli", marker = "python_full_version < '3.11'", specifier = ">=2.0,<3" }, { name = "typing-extensions", specifier = ">=4.12,<5" }, ] -provides-extras = ["dev", "editor", "collision", "inspect"] +provides-extras = ["dev", "editor", "collision", "inspect", "gmsh"] [package.metadata.requires-dev] dev = [ diff --git a/viewer/README.md b/viewer/README.md index edb9124d..34728900 100644 --- a/viewer/README.md +++ b/viewer/README.md @@ -1,42 +1,47 @@ -# SimpleCAD Scene Viewer +# SimpleCAD Product Viewer -This is a browser-only viewer for exported `Scene Schema 1.0` packages. It -does not import SimpleCAD, Python, or OpenCascade. The loader reads the -canonical `.scene.zip`, parses `scene.json`, and loads the referenced GLB and -entity sidecar assets. When present, it also loads `model/model.json` and the -manifest-declared Python files under `sources/`. ZIP resource limits and every -referenced member's exact byte length and SHA-256 are checked before scene -assets are parsed. +This browser-only viewer opens canonical `.scadpkg` product packages without +importing SimpleCAD, Python, or OpenCascade. The loader validates `package.json`, +the complete content-addressed definition closure, and the embedded evaluated +scene before parsing GLB or entity assets. It rejects standalone Scene ZIPs and +any package with missing, extra, length-mismatched, or hash-mismatched members. ## Run ```bash npm install -npm run prepare:example npm run dev ``` -Open `http://localhost:5173/`, click **Open .scene.zip**, and select the package -generated at `examples/out/hydraulic_rod_assembly/hydraulic_rod_assembly.scene.zip`. +Open `http://localhost:5173/`, click **Open .scadpkg**, and select a package +written directly by the functional capture API: + +```python +scad.capture(result, "out/product.scadpkg") +``` + The same file can be dropped directly into the viewport. -The file picker accepts any local `.scene.zip` package. The viewer does not -load scenes from URL query parameters or require a built-in case registry. +The file picker accepts local `.scadpkg` product packages only. The viewer does +not load packages from URL query parameters or require a built-in case registry. -## Inspecting A Model +## Inspecting A Product -The left **ASSEMBLY** tab shows the evaluated occurrence hierarchy. Click an -occurrence to inspect its definition, visibility, and evaluated body data. Use -the visibility control on a row to hide or show that occurrence. +The **Components** tab shows the evaluated occurrence hierarchy. Select an +occurrence to inspect its definition, visibility, and evaluated body data. The +visibility control on each row hides or shows that occurrence. -The **FEATURES** tab shows the embedded replayable operation tree from -`model/model.json`. Select an operation to inspect its canonical operation name, -category, inputs, output count, parameters, and summary. For mapped operations, -the inspector shows assignment targets and the complete embedded Python file, -scrolls to the originating call, and highlights its source line range. +The **Features** tab federates the immutable feature DAGs embedded by every part +and nested assembly definition. Selecting a feature shows its operation, +definition-local identity, inputs, outputs, parameters, source spans, and linked +geometry. Connector and joint selections resolve through the package indexes to +the exact producing feature when that evidence exists. -Click a rendered face or CAD edge in the viewport to select the corresponding -evaluated entity. The selected face or edge is highlighted and its measured -properties are shown in the inspector. The scene package must contain the -embedded model artifact for the Features tab; older scene packages still retain -assembly-tree and geometry selection support. +The source panel lists the content-addressed source snapshots embedded by the +definition closure. Selecting a mapped feature opens the exact source asset, +scrolls to its recorded line range, and highlights that range without reading +files from the local machine. + +Select components, solids, faces, edges, or vertices in the viewport to inspect +evaluated geometry and measurements. Geometry selections link back to the +feature DAG through stable definition, node, output-slot, and topology evidence. diff --git a/viewer/src/main.ts b/viewer/src/main.ts index ab7f9792..da23bf07 100644 --- a/viewer/src/main.ts +++ b/viewer/src/main.ts @@ -1,6 +1,6 @@ import './style.css'; -import { unzipSync, strFromU8 } from 'fflate'; +import { strFromU8 } from 'fflate'; import { Box, Boxes, @@ -35,35 +35,29 @@ import { LineMaterial } from 'three/addons/lines/LineMaterial.js'; import { bindClickSelection } from './components/click-selection'; import { bindResizablePanels } from './components/panel-resizer'; import { SourceDock } from './components/source-dock'; +import { openCadPackage, type PackageFiles } from './product-package'; +import { + buildFederatedFeatureModel, + type Asset, + type ConnectorSnapshot, + type Definition, + type Entity, + type EntitySidecar, + type FaceGroup, + type Joint, + type ModelDocument, + type ModelNode, + type OperationSource, + type SceneManifest, + type SceneNode, + type SourceRecord, + type Transform, + type Vec3, +} from './scene2'; -type Vec3 = [number, number, number]; -type Bounds = { min: Vec3; max: Vec3 }; -type Transform = { origin: Vec3; x_axis: Vec3; y_axis: Vec3; z_axis: Vec3 }; -type Appearance = { appearance_id: string; name: string | null; base_color: [number, number, number, 1]; metallic: number; roughness: number; alpha_mode: 'opaque' | 'mask' | 'blend'; double_sided: boolean; edge_color: [number, number, number, 1] }; -type SourceRecord = Record & { kind: string; root_id?: string; graph_id?: string; node_id?: string; output_slot?: number; component_path?: string[] }; -type Definition = { definition_id: string; kind: string; name: string | null; source: SourceRecord; sdk_metadata: Record; geometry_asset_id?: string; edge_asset_id?: string; entity_asset_id?: string; appearance_id?: string }; -type SceneNode = { node_id: string; parent_node_id: string | null; order: number; definition_id: string; name: string | null; transform: Transform; visible: boolean; selectable: boolean; source: SourceRecord; sdk_metadata: Record }; -type Asset = { asset_id: string; uri: string; byte_length: number; content_hash: string; scene_local_bounds: Bounds; asset_to_scene: number[] }; -type Entity = { entity_id: string; kind: 'solid' | 'face' | 'edge' | 'vertex'; parent_entity_ids: string[]; child_entity_ids: string[]; source: SourceRecord; properties: Record; geometry: Record; sdk_connector_frame: Transform | null; render_status: string; connector_binding_status: string; semantic_binding_ids: string[]; evaluated_tags: string[]; sdk_metadata: Record }; -type EntityAsset = { entity_asset_id: string; uri: string; byte_length: number; content_hash: string }; -type FaceGroup = { entity_id: string; first_index: number; index_count: number }; -type SourceFile = { path: string; uri: string; media_type: string; byte_length: number; content_hash: string }; -type EmbeddedSource = { artifact_hash?: string; embedded_artifact_uri?: string; embedded_artifact_byte_length?: number; source_files?: SourceFile[] }; -type SceneManifest = { schema_version: string; scene_id: string; revision: string; generator: { profile: string; simplecadapi_version: string; ocp_version: string }; source: EmbeddedSource; presentation_source?: EmbeddedSource; coordinate_system: { length_unit: string; up_axis: string }; definitions: Definition[]; nodes: SceneNode[]; geometry_assets: Asset[]; edge_assets: Asset[]; appearances: Appearance[]; entity_assets: EntityAsset[]; connectors: Array<{ connector_snapshot_id: string; owner_definition_id: string; name: string | null; anchor_kind: string; target?: { entity_asset_id: string; entity_id: string } }> }; -type PackageFiles = Record; -type EntitySidecar = { entities: Entity[]; face_groups: FaceGroup[]; edge_groups?: FaceGroup[] }; -type PackageRecord = { uri: string; byte_length: number; content_hash: string }; -type OperationSource = { path?: string | null; line: number; column: number; end_line: number; end_column: number; call_text: string; callsite_id: string; assignment_targets: string[] }; -type ModelNode = { node_id: string; op: string; params: Record; inputs: string[]; output_count?: number; tags?: string[]; display?: { label?: string; category?: string; summary?: string }; source?: OperationSource }; -type ModelDocument = { graph: { graph_id: string; nodes: ModelNode[] }; leaf_ids?: string[] }; type SelectionMode = 'component' | 'solid' | 'face' | 'edge' | 'vertex'; const MAX_PACKAGE_BYTES = 256 * 1024 * 1024; -const MAX_PACKAGE_MEMBERS = 10_000; -const MAX_UNPACKED_BYTES = 512 * 1024 * 1024; -const MAX_MEMBER_BYTES = 256 * 1024 * 1024; -const MAX_SCENE_JSON_BYTES = 8 * 1024 * 1024; -const MAX_COMPRESSION_RATIO = 100; const app = document.querySelector('#app'); if (!app) throw new Error('viewer root is missing'); @@ -110,13 +104,13 @@ app.innerHTML = `
SC
SimpleCADevaluated scene viewer
-
+
-
Loading evaluated package
Waiting for package
SELECT
+
Loading evaluated package
Waiting for package
SELECT
@@ -146,6 +140,7 @@ const tree = document.querySelector('#tree')!; const details = document.querySelector('#details')!; const selectionKind = document.querySelector('#selection-kind')!; const nodeCount = document.querySelector('#node-count')!; +const interfacesButton = document.querySelector('#interfaces-button')!; const status = document.querySelector('#status')!; const statusDot = document.querySelector('#status-dot')!; const packageMeta = document.querySelector('#package-meta')!; @@ -213,8 +208,8 @@ const edgeCache = new Map(); const entityCache = new Map(); const nodeObjects = new Map(); const nodeRows = new Map(); +const nodeVisibility = new Map(); const manifestByDefinition = new Map(); -const appearanceById = new Map(); let currentManifest: SceneManifest | null = null; let currentFiles: PackageFiles | null = null; let currentModel: ModelDocument | null = null; @@ -222,6 +217,8 @@ const sourceFiles = new Map(); let selectedNodeId: string | null = null; let selectedFeatureId: string | null = null; let selectedOverlays: THREE.Object3D[] = []; +let interfaceRoot: THREE.Group | null = null; +let interfacesVisible = true; const featureRows = new Map(); let focusFeatureInTree: ((featureId: string) => void) | null = null; let selectionMode: SelectionMode = 'component'; @@ -237,94 +234,33 @@ function bytesFor(files: PackageFiles, uri: string): Uint8Array { return value; } -function validateMemberName(name: string): void { - if (!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,1023}$/.test(name) || name.split('/').some((segment) => !segment || segment === '.' || segment === '..')) { - throw new Error(`invalid scene package member: ${name}`); - } -} - -function packageRecords(manifest: SceneManifest): PackageRecord[] { - const records: PackageRecord[] = []; - const addAsset = (asset: Asset, kind: 'geometry' | 'edges'): void => { - if (asset.asset_id !== asset.content_hash) throw new Error(`${kind} asset ID differs from its content hash`); - const digest = /^sha256:([0-9a-f]{64})$/.exec(asset.content_hash)?.[1]; - if (!digest || asset.uri !== `${kind}/sha256-${digest}.glb`) throw new Error(`invalid content-addressed ${kind} asset URI`); - records.push(asset); - }; - for (const asset of manifest.geometry_assets) addAsset(asset, 'geometry'); - for (const asset of manifest.edge_assets) addAsset(asset, 'edges'); - for (const asset of manifest.entity_assets) { - if (asset.entity_asset_id !== asset.content_hash) throw new Error('entity asset ID differs from its content hash'); - const digest = /^sha256:([0-9a-f]{64})$/.exec(asset.content_hash)?.[1]; - if (!digest || asset.uri !== `entities/sha256-${digest}.json`) throw new Error('invalid content-addressed entity asset URI'); - records.push(asset); - } - for (const source of [manifest.source, manifest.presentation_source]) { - if (!source?.embedded_artifact_uri) continue; - if (typeof source.embedded_artifact_byte_length !== 'number' || typeof source.artifact_hash !== 'string') throw new Error('embedded artifact integrity metadata is missing'); - records.push({ uri: source.embedded_artifact_uri, byte_length: source.embedded_artifact_byte_length, content_hash: source.artifact_hash }); - for (const sourceFile of source.source_files ?? []) records.push(sourceFile); - } - return records; -} - -async function validatePackageMembers(files: PackageFiles, manifest: SceneManifest): Promise { - const records = packageRecords(manifest); - const referenced = new Set(['scene.json']); - for (const record of records) { - validateMemberName(record.uri); - if (referenced.has(record.uri)) throw new Error(`duplicate scene package reference: ${record.uri}`); - referenced.add(record.uri); - } - const names = Object.keys(files); - for (const name of names) { - validateMemberName(name); - } - if (names.length !== referenced.size || names.some((name) => !referenced.has(name))) { - throw new Error('scene package members do not match scene.json references'); - } - for (const record of records) { - const payload = bytesFor(files, record.uri); - if (!Number.isSafeInteger(record.byte_length) || record.byte_length < 0 || payload.byteLength !== record.byte_length) { - throw new Error(`package member length differs from scene.json: ${record.uri}`); - } - const expected = /^sha256:([0-9a-f]{64})$/.exec(record.content_hash)?.[1]; - if (!expected) throw new Error(`invalid package member hash: ${record.uri}`); - const digest = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', payload)), (byte) => byte.toString(16).padStart(2, '0')).join(''); - if (digest !== expected) throw new Error(`package member hash differs from scene.json: ${record.uri}`); - } -} - async function loadGlb(files: PackageFiles, uri: string): Promise { const bytes = bytesFor(files, uri); const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength); const gltf = await loader.parseAsync(buffer, ''); return gltf.scene; } - -function applyAssetTransform(object: THREE.Object3D, matrix: number[]): void { - if (matrix.length !== 16) throw new Error('asset_to_scene must contain 16 values'); - // The contract stores row-major CAD-to-scene values. Three.js uses metres. - object.applyMatrix4(new THREE.Matrix4().set( - matrix[0] / 1000, matrix[1] / 1000, matrix[2] / 1000, matrix[3] / 1000, - matrix[4] / 1000, matrix[5] / 1000, matrix[6] / 1000, matrix[7] / 1000, - matrix[8] / 1000, matrix[9] / 1000, matrix[10] / 1000, matrix[11] / 1000, - matrix[12], matrix[13], matrix[14], matrix[15], - )); -} +const CAD_TO_GLTF = new THREE.Matrix4().set(0.001, 0, 0, 0, 0, 0, 0.001, 0, 0, -0.001, 0, 0, 0, 0, 0, 1); +const GLTF_TO_CAD = new THREE.Matrix4().set(1000, 0, 0, 0, 0, 0, -1000, 0, 0, 1000, 0, 0, 0, 0, 0, 1); function placementMatrix(transform: Transform): THREE.Matrix4 { const { origin, x_axis, y_axis, z_axis } = transform; - return new THREE.Matrix4().set( - x_axis[0], y_axis[0], z_axis[0], origin[0] / 1000, - x_axis[1], y_axis[1], z_axis[1], origin[1] / 1000, - x_axis[2], y_axis[2], z_axis[2], origin[2] / 1000, + const cad = new THREE.Matrix4().set( + x_axis[0], y_axis[0], z_axis[0], origin[0], + x_axis[1], y_axis[1], z_axis[1], origin[1], + x_axis[2], y_axis[2], z_axis[2], origin[2], 0, 0, 0, 1, ); + return CAD_TO_GLTF.clone().multiply(cad).multiply(GLTF_TO_CAD); +} + +function cadPointToGltf(point: Vec3): THREE.Vector3 { + return new THREE.Vector3(point[0] / 1000, point[2] / 1000, -point[1] / 1000); } const CAD_EDGE_LIGHTNESS_OFFSET = 0.5; const CAD_EDGE_LINE_WIDTH = 1.6; +const DEFAULT_BASE_COLOR: [number, number, number, 1] = [0.72, 0.75, 0.78, 1]; function cadEdgeColor(baseColor: [number, number, number, 1]): THREE.Color { const hsl = { h: 0, s: 0, l: 0 }; @@ -332,28 +268,18 @@ function cadEdgeColor(baseColor: [number, number, number, 1]): THREE.Color { return new THREE.Color().setHSL(hsl.h, hsl.s, (hsl.l + CAD_EDGE_LIGHTNESS_OFFSET) % 1); } -function materialFor(definition: Definition): THREE.MeshStandardMaterial { - const appearance = definition.appearance_id ? appearanceById.get(definition.appearance_id) : undefined; - const color = appearance?.base_color ?? [0.72, 0.75, 0.78, 1]; - return new THREE.MeshStandardMaterial({ color: new THREE.Color(color[0], color[1], color[2]), metalness: appearance?.metallic ?? 0, roughness: appearance?.roughness ?? 0.55, side: appearance?.double_sided ? THREE.DoubleSide : THREE.FrontSide, transparent: appearance?.alpha_mode === 'blend', opacity: color[3] }); +function materialFor(node: SceneNode): THREE.MeshStandardMaterial { + const color = node.material_id ? [0.68, 0.78, 0.88, 1] as const : DEFAULT_BASE_COLOR; + return new THREE.MeshStandardMaterial({ color: new THREE.Color(color[0], color[1], color[2]), metalness: 0.08, roughness: 0.52, side: THREE.FrontSide, transparent: color[3] < 1, opacity: color[3] }); } -function edgeMaterialFor(definition: Definition): LineMaterial { - const appearance = definition.appearance_id ? appearanceById.get(definition.appearance_id) : undefined; - const baseColor = appearance?.base_color ?? [0.72, 0.75, 0.78, 1]; - const material = new LineMaterial({ - color: cadEdgeColor(baseColor), - linewidth: CAD_EDGE_LINE_WIDTH, - worldUnits: false, - transparent: baseColor[3] < 1, - opacity: baseColor[3], - depthTest: true, - depthWrite: false, - }); +function edgeMaterial(): LineMaterial { + const material = new LineMaterial({ color: cadEdgeColor(DEFAULT_BASE_COLOR), linewidth: CAD_EDGE_LINE_WIDTH, worldUnits: false, depthTest: true, depthWrite: false }); material.resolution.set(renderer.domElement.clientWidth, renderer.domElement.clientHeight); return material; } -function addWideEdgeVisual(source: THREE.LineSegments, definition: Definition): void { + +function addWideEdgeVisual(source: THREE.LineSegments): void { const position = source.geometry.getAttribute('position'); const index = source.geometry.index; const indexCount = index?.count ?? position.count; @@ -365,7 +291,7 @@ function addWideEdgeVisual(source: THREE.LineSegments, definition: Definition): } const geometry = new LineSegmentsGeometry(); geometry.setPositions(positions); - const visual = new LineSegments2(geometry, edgeMaterialFor(definition)); + const visual = new LineSegments2(geometry, edgeMaterial()); visual.name = 'cad-edge-visual'; visual.userData.pickable = false; source.add(visual); @@ -374,52 +300,58 @@ function addWideEdgeVisual(source: THREE.LineSegments, definition: Definition): source.material = pickingMaterial; } -async function instantiateDefinition(definition: Definition): Promise { +function sidecarForNode(node: SceneNode | undefined): EntitySidecar | null { + if (!currentManifest || !currentFiles || !node?.entity_asset_id) return null; + const asset = currentManifest.entity_assets.find((item) => item.asset_id === node.entity_asset_id); + if (!asset) return null; + const cached = entityCache.get(asset.asset_id); + if (cached) return cached; + const parsed = JSON.parse(strFromU8(bytesFor(currentFiles, asset.uri))) as EntitySidecar; + if (parsed.schema_version !== '2.0' || parsed.definition_id !== node.definition_id) throw new Error(`entity sidecar identity differs: ${asset.uri}`); + entityCache.set(asset.asset_id, parsed); + return parsed; +} + +async function instantiateNode(node: SceneNode): Promise { if (!currentManifest || !currentFiles) throw new Error('scene package is not loaded'); const group = new THREE.Group(); - group.name = definition.name || definition.definition_id; - const geometryAsset = currentManifest.geometry_assets.find((asset) => asset.asset_id === definition.geometry_asset_id); + group.name = node.display_name || node.node_id; + const geometryAsset = node.geometry_asset_id ? currentManifest.geometry_assets.find((asset) => asset.asset_id === node.geometry_asset_id) : undefined; if (geometryAsset) { let geometry = geometryCache.get(geometryAsset.asset_id); if (!geometry) { geometry = await loadGlb(currentFiles, geometryAsset.uri); - applyAssetTransform(geometry, geometryAsset.asset_to_scene); geometryCache.set(geometryAsset.asset_id, geometry); } const renderGeometry = geometry.clone(true); renderGeometry.traverse((child) => { - if (child instanceof THREE.Mesh) child.material = materialFor(definition); + if (child instanceof THREE.Mesh) child.material = materialFor(node); }); group.add(renderGeometry); } - const edgeAsset = currentManifest.edge_assets.find((asset) => asset.asset_id === definition.edge_asset_id); + const sidecar = sidecarForNode(node); + const edgeAsset = sidecar ? currentManifest.geometry_assets.find((asset) => asset.asset_id === sidecar.edge_asset_id) : undefined; if (edgeAsset) { let edge = edgeCache.get(edgeAsset.asset_id); if (!edge) { edge = await loadGlb(currentFiles, edgeAsset.uri); - applyAssetTransform(edge, edgeAsset.asset_to_scene); edgeCache.set(edgeAsset.asset_id, edge); } const edgeInstance = edge.clone(true); - edgeInstance.traverse((child) => { if (child instanceof THREE.LineSegments) addWideEdgeVisual(child, definition); }); - edgeInstance.visible = true; + edgeInstance.traverse((child) => { if (child instanceof THREE.LineSegments) addWideEdgeVisual(child); }); group.add(edgeInstance); } - const sidecar = sidecarForDefinition(definition); if (sidecar) { const vertices = sidecar.entities.filter((entity) => entity.kind === 'vertex'); if (vertices.length) { const positions = new Float32Array(vertices.length * 3); vertices.forEach((entity, index) => { - const position = entity.geometry.position as Vec3; - positions.set([position[0] / 1000, position[1] / 1000, position[2] / 1000], index * 3); + const position = entity.properties.position; + if (Array.isArray(position) && position.length === 3 && position.every((item) => typeof item === 'number')) cadPointToGltf(position as Vec3).toArray(positions, index * 3); }); const vertexGeometry = new THREE.BufferGeometry(); vertexGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3)); - const vertexPoints = new THREE.Points( - vertexGeometry, - new THREE.PointsMaterial({ color: '#d8ff83', size: 7, sizeAttenuation: false, depthWrite: false, transparent: true, opacity: 0.48 }), - ); + const vertexPoints = new THREE.Points(vertexGeometry, new THREE.PointsMaterial({ color: '#d8ff83', size: 7, sizeAttenuation: false, depthWrite: false, transparent: true, opacity: 0.48 })); vertexPoints.visible = selectionMode === 'vertex'; vertexPoints.userData.pickRole = 'vertex'; vertexPoints.userData.vertexEntityIds = vertices.map((entity) => entity.entity_id); @@ -467,9 +399,11 @@ function clearModel(): void { } nodeObjects.clear(); nodeRows.clear(); - geometryCache.clear(); edgeCache.clear(); entityCache.clear(); + interfaceRoot = null; + entityCache.clear(); + nodeVisibility.clear(); currentModel = null; sourceFiles.clear(); sourceDock.clear(); @@ -480,27 +414,115 @@ function clearModel(): void { selectedFeatureId = null; focusFeatureInTree = null; } +function interfaceFrameMatrix(transform: Transform): THREE.Matrix4 { + return placementMatrix(transform); +} + +function addInterfaceAxis(parent: THREE.Object3D, direction: Vec3, color: number, interfaceId: string, nodeId: string): void { + const geometry = new THREE.BufferGeometry(); + const length = 0.012; + geometry.setAttribute('position', new THREE.Float32BufferAttribute([0, 0, 0, direction[0] * length, direction[1] * length, direction[2] * length], 3)); + const line = new THREE.LineSegments(geometry, new THREE.LineBasicMaterial({ color, depthTest: false, transparent: true, opacity: 0.9 })); + line.userData.interfaceId = interfaceId; + line.userData.nodeId = nodeId; + line.userData.interfaceKind = 'connector'; + line.renderOrder = 20; + parent.add(line); +} + +function renderInterfaces(manifest: SceneManifest): void { + interfaceRoot?.removeFromParent(); + interfaceRoot = new THREE.Group(); + interfaceRoot.name = 'interfaces'; + interfaceRoot.visible = interfacesVisible; + interfaceRoot.userData.pickable = true; + modelRoot.add(interfaceRoot); + const connectorGroups = new Map(); + for (const connector of manifest.connectors) { + const nodeObject = nodeObjects.get(connector.node_id); + if (!nodeObject) continue; + const frame = new THREE.Group(); + frame.name = connector.connector_snapshot_id; + frame.matrixAutoUpdate = false; + frame.matrix.copy(interfaceFrameMatrix(connector.local_frame)); + frame.userData.interfaceId = connector.connector_snapshot_id; + frame.userData.interfaceKind = 'connector'; + frame.userData.nodeId = connector.node_id; + frame.visible = interfacesVisible; + addInterfaceAxis(frame, [1, 0, 0], 0xe56b6f, connector.connector_snapshot_id, connector.node_id); + addInterfaceAxis(frame, [0, 0, -1], 0x80c783, connector.connector_snapshot_id, connector.node_id); + addInterfaceAxis(frame, [0, 1, 0], 0x78a9e6, connector.connector_snapshot_id, connector.node_id); + nodeObject.add(frame); + connectorGroups.set(connector.connector_snapshot_id, frame); + } + modelRoot.updateMatrixWorld(true); + for (const joint of manifest.joints) { + const first = connectorGroups.get(joint.connector_a.connector_snapshot_id); + const second = connectorGroups.get(joint.connector_b.connector_snapshot_id); + if (!first || !second) continue; + const start = new THREE.Vector3().setFromMatrixPosition(first.matrixWorld); + const end = new THREE.Vector3().setFromMatrixPosition(second.matrixWorld); + const geometry = new THREE.BufferGeometry().setFromPoints([start, end]); + const line = new THREE.LineSegments(geometry, new THREE.LineBasicMaterial({ color: 0xf2c14e, depthTest: false, transparent: true, opacity: 0.95 })); + line.name = joint.joint_id; + line.userData.interfaceId = joint.joint_id; + line.userData.interfaceKind = 'joint'; + line.userData.pickable = true; + line.renderOrder = 21; + interfaceRoot.add(line); + } +} + +function linkInterfaceFeature(featureId: string | null): void { + if (!featureId || !currentModel) return; + selectedFeatureId = featureId; + for (const [id, rows] of featureRows) rows.forEach((row) => row.classList.toggle('selected', id === featureId)); + setNavigatorTab('features'); + focusFeatureInTree?.(featureId); + const feature = currentModel.graph.nodes.find((item) => item.node_id === featureId); + if (feature?.source) sourceDock.reveal(feature.source); +} + +function selectInterface(interfaceId: string): void { + if (!currentManifest) return; + clearSelectionOverlay(); + selectedNodeId = null; + const connector = currentManifest.connectors.find((item) => item.connector_snapshot_id === interfaceId); + const joint = currentManifest.joints.find((item) => item.joint_id === interfaceId); + const sourceFeatureId = connector?.source_feature_id ?? joint?.source_feature_id ?? null; + selectionKind.textContent = connector ? 'CONNECTOR' : 'JOINT'; + if (connector) { + const node = currentManifest.nodes.find((item) => item.node_id === connector.node_id); + details.innerHTML = `
${iconMarkup('GitBranch', 'detail-icon-svg')}
${escapeHtml(connector.name)}${escapeHtml(connector.connector_snapshot_id)}
CONNECTOR
Node
${escapeHtml(connector.node_id)}
Definition
${escapeHtml(connector.definition_id)}
Anchor
${escapeHtml(connector.anchor_kind)}
Connector
${escapeHtml(connector.connector_id)}
LOCAL FRAME
${escapeHtml(jsonText(connector.local_frame))}
${connector.binding ? metadataSection('BINDING', connector.binding) : ''}${connector.forwarded_from ? metadataSection('FORWARDED FROM', connector.forwarded_from) : ''}${sourceFeatureId ? `
SOURCE FEATURE
` : ''}`; + if (node) nodeRows.get(node.node_id)?.classList.add('selected'); + } else if (joint) { + details.innerHTML = `
${iconMarkup('GitBranch', 'detail-icon-svg')}
${escapeHtml(joint.joint_type)}${escapeHtml(joint.joint_id)}
JOINT
Assembly
${escapeHtml(joint.assembly_definition_id)}
Connector A
${escapeHtml(joint.connector_a.connector_snapshot_id)}
Connector B
${escapeHtml(joint.connector_b.connector_snapshot_id)}
PARAMETERS
${escapeHtml(jsonText(joint.parameters))}
${joint.limits ? metadataSection('LIMITS', joint.limits) : ''}${sourceFeatureId ? `
SOURCE FEATURE
` : ''}`; + } else return; + renderIcons(details); + details.querySelector('#interface-source')?.addEventListener('click', () => linkInterfaceFeature(sourceFeatureId)); + linkInterfaceFeature(sourceFeatureId); +} function renderTree(manifest: SceneManifest): void { tree.replaceChildren(); nodeRows.clear(); const byParent = new Map(); for (const node of manifest.nodes) byParent.set(node.parent_node_id, [...(byParent.get(node.parent_node_id) ?? []), node]); - for (const nodes of byParent.values()) nodes.sort((a, b) => a.order - b.order); const append = (parent: HTMLElement, parentId: string | null, depth: number): void => { for (const node of byParent.get(parentId) ?? []) { const row = document.createElement('button'); row.className = 'tree-row'; row.style.setProperty('--depth', String(depth)); row.dataset.nodeId = node.node_id; - row.classList.toggle('hidden-node', !node.visible); - const hasChildren = (byParent.get(node.node_id)?.length ?? 0) > 0; - const isAssembly = node.definition_id.includes('/assembly/'); - row.innerHTML = `${iconMarkup(hasChildren ? 'ChevronDown' : 'CircleDot', 'tree-chevron-icon')}${iconMarkup(isAssembly ? 'Boxes' : 'Box', 'tree-type-icon')}${escapeHtml(node.name || node.node_id.split('/').pop() || node.node_id)}${iconMarkup(node.visible ? 'Eye' : 'EyeOff', 'tree-visibility-icon')}`; - renderIcons(row); + const visible = nodeVisibility.get(node.node_id) ?? true; + row.classList.toggle('hidden-node', !visible); + const hasChildren = (byParent.get(node.node_id)?.length ?? 0) > 0; + const isAssembly = node.definition_kind === 'assembly'; + row.innerHTML = `${iconMarkup(hasChildren ? 'ChevronDown' : 'CircleDot', 'tree-chevron-icon')}${iconMarkup(isAssembly ? 'Boxes' : 'Box', 'tree-type-icon')}${escapeHtml(node.display_name || node.node_id)}${iconMarkup(visible ? 'Eye' : 'EyeOff', 'tree-visibility-icon')}`; + renderIcons(row); row.addEventListener('click', () => { if (!canSelectNode(node.node_id)) { - setStatus('Occurrence is hidden or not selectable', true); + setStatus('Occurrence is hidden', true); return; } selectNode(node.node_id); @@ -616,7 +638,7 @@ function renderFeatureTree(): void { const prefixIcon = reference ? 'Link' : inputs.length ? (expanded ? 'ChevronDown' : 'ChevronRight') : 'CircleDot'; row.setAttribute('aria-expanded', inputs.length && !reference ? String(expanded) : 'false'); row.setAttribute('aria-label', reference ? `Reference to ${featureTreeLabel(feature)}` : featureTreeLabel(feature)); - row.innerHTML = `${iconMarkup(prefixIcon, 'tree-chevron-icon')}${iconMarkup(featureIconName(feature.op), 'tree-type-icon')}${escapeHtml(featureTreeLabel(feature))}${reference ? 'REF' : ''}${shared && !reference ? `USED ${consumerCount.get(featureId)}` : ''}${inputs.length && !reference ? `${inputs.length} IN` : ''}${feature.tags?.length ? 'TAG' : ''}`; + row.innerHTML = `${iconMarkup(prefixIcon, 'tree-chevron-icon')}${iconMarkup(featureIconName(feature.op), 'tree-type-icon')}${escapeHtml(featureTreeLabel(feature))}${reference ? 'REF' : ''}${shared && !reference ? `USED ${consumerCount.get(featureId)}` : ''}${inputs.length && !reference ? `${inputs.length} IN` : ''}`; renderIcons(row); row.addEventListener('click', () => { selectFeature(featureId); @@ -672,7 +694,12 @@ function sourceLocationMarkup(source: OperationSource): string { const start = Math.max(1, source.line); const end = Math.max(start, source.end_line); const location = source.path ? `${source.path}:${start}${end !== start ? `-${end}` : ''}` : 'Source path is unavailable'; - return `
${escapeHtml(location)}
${source.path && sourceFiles.has(source.path) ? '

The embedded file is open in the Source dock.

' : `
${escapeHtml(source.call_text)}
`}`; + return `
${escapeHtml(location)}
${source.path && sourceFiles.has(source.path) ? '

The embedded file is open in the Source dock.

' : `
${escapeHtml(source.call_text ?? '')}
`}`; +} + +function sourceLocationsMarkup(sources: OperationSource[]): string { + if (sources.length <= 1) return sources[0] ? sourceLocationMarkup(sources[0]) : '

Source mapping unavailable.

'; + return sources.map((source, index) => ``).join(''); } function pythonLiteral(value: unknown): string { @@ -699,51 +726,25 @@ function entityMeasure(entity: Entity): [string, number] | null { return path && typeof value === 'number' ? [path, value] : null; } -function selectionSourceForEntity(entity: Entity): SourceRecord { +function featureIdForGeometry(entity: Entity | undefined): string | null { + if (!currentModel || !entity) return null; const source = entity.source; - if (!currentModel || typeof source.node_id !== 'string') return source; - const byId = new Map(currentModel.graph.nodes.map((node) => [node.node_id, node])); - const visited = new Set(); - const findSolidProducer = (nodeId: string): ModelNode | null => { - if (visited.has(nodeId)) return null; - visited.add(nodeId); - const node = byId.get(nodeId); - if (!node) return null; - if (/(?:_rsolid|_rshape|_rcompound)$/.test(node.op)) return node; - for (const input of node.inputs) { - const producer = findSolidProducer(input); - if (producer) return producer; - } - return null; - }; - const producer = findSolidProducer(source.node_id); - return producer ? { ...source, node_id: producer.node_id, output_slot: 0 } : source; -} - -function featureIdForGeometry(definition: Definition | undefined, entity: Entity | undefined): string | null { - if (!currentModel) return null; - const source = entity ? selectionSourceForEntity(entity) : definition?.source; - if (!source || typeof source.node_id !== 'string') return null; - if (typeof source.graph_id === 'string' && source.graph_id !== currentModel.graph.graph_id) return null; - return currentModel.graph.nodes.some((feature) => feature.node_id === source.node_id) ? source.node_id : null; + if (source.kind !== 'feature_output' || typeof source.definition_id !== 'string' || typeof source.graph_id !== 'string' || typeof source.node_id !== 'string') return null; + return currentModel.graph.nodes.find((feature) => feature.definition_id === source.definition_id && feature.graph_id === source.graph_id && feature.local_node_id === source.node_id)?.node_id ?? null; } function qlSelectorForEntity(entity: Entity, sidecar: EntitySidecar): { expression: string; unique: boolean } { type Fact = { expression: string; matches: (candidate: Entity) => boolean }; const candidates = sidecar.entities.filter((candidate) => candidate.kind === entity.kind); const facts: Fact[] = []; - for (const tag of entity.evaluated_tags) { - facts.push({ expression: `Q.tag(${pythonLiteral(tag)})`, matches: (candidate) => candidate.evaluated_tags.includes(tag) }); - } + for (const tag of entity.tags) facts.push({ expression: `Q.tag(${pythonLiteral(tag)})`, matches: (candidate) => candidate.tags.includes(tag) }); const geometryType = entity.geometry.type; if (typeof geometryType === 'string' && !geometryType.startsWith('other_') && geometryType !== 'brep_solid' && geometryType !== 'point') { const expected = geometryType.toUpperCase().replace(/^BSPLINE_(CURVE|SURFACE)$/, 'BSPLINE'); facts.push({ expression: `Q.prop("geom.type", "==", ${pythonLiteral(expected)})`, matches: (candidate) => candidate.geometry.type === geometryType }); } const measure = entityMeasure(entity); - if (measure) { - facts.push({ expression: `Q.prop(${pythonLiteral(measure[0])}, "==", ${pythonLiteral(measure[1])})`, matches: (candidate) => entityMeasure(candidate)?.[1] === measure[1] }); - } + if (measure) facts.push({ expression: `Q.prop(${pythonLiteral(measure[0])}, "==", ${pythonLiteral(measure[1])})`, matches: (candidate) => entityMeasure(candidate)?.[1] === measure[1] }); const center = entityCenter(entity); if (center) { (['x', 'y', 'z'] as const).forEach((axis, index) => facts.push({ @@ -763,9 +764,8 @@ function qlSelectorForEntity(entity: Entity, sidecar: EntitySidecar): { expressi } const unique = matches.length === 1 && matches[0].entity_id === entity.entity_id; const factory = entity.kind === 'solid' ? 'Q.ShapeSelector(target_kind="solid")' : `Q.${entity.kind}s()`; - const source = selectionSourceForEntity(entity); const lines = [factory]; - if (typeof source.node_id === 'string') lines.push(`.from_source(${pythonLiteral(source.node_id)}, ${typeof source.output_slot === 'number' ? source.output_slot : 0})`); + if (typeof entity.source.node_id === 'string') lines.push(`.from_source(${pythonLiteral(entity.source.node_id)}, ${typeof entity.source.output_slot === 'number' ? entity.source.output_slot : 0})`); if (selectedFacts.length === 1) lines.push(`.where(${selectedFacts[0].expression})`); if (selectedFacts.length > 1) lines.push(`.where(Q.and_(\n ${selectedFacts.map((fact) => fact.expression).join(',\n ')}\n))`); lines.push('.exactly(1)'); @@ -791,21 +791,11 @@ function sourceIdentityRows(source: SourceRecord | undefined): string { return rows.map(([label, value]) => `
${escapeHtml(label)}
${escapeHtml(String(value))}
`).join(''); } -function sidecarForDefinition(definition: Definition | undefined): EntitySidecar | null { - if (!currentManifest || !currentFiles || !definition?.entity_asset_id) return null; - const asset = currentManifest.entity_assets.find((item) => item.entity_asset_id === definition.entity_asset_id); - if (!asset) return null; - const cached = entityCache.get(asset.entity_asset_id); - if (cached) return cached; - const parsed = JSON.parse(strFromU8(bytesFor(currentFiles, asset.uri))) as EntitySidecar; - entityCache.set(asset.entity_asset_id, parsed); - return parsed; -} function selectNode(nodeId: string, entityId?: string): void { if (!currentManifest) return; if (!canSelectNode(nodeId)) { - setStatus('Occurrence is hidden or not selectable', true); + setStatus('Occurrence is hidden', true); return; } clearSelectionOverlay(); @@ -815,14 +805,12 @@ function selectNode(nodeId: string, entityId?: string): void { for (const rows of featureRows.values()) rows.forEach((row) => row.classList.remove('selected')); const node = currentManifest.nodes.find((item) => item.node_id === nodeId); if (!node) return; - const definition = manifestByDefinition.get(node.definition_id); - selectionKind.textContent = definition?.kind.toUpperCase() ?? 'NODE'; - const sidecar = sidecarForDefinition(definition); + const sidecar = sidecarForNode(node); const entity = sidecar?.entities.find((item) => item.entity_id === entityId); const solid = sidecar?.entities.find((item) => item.kind === 'solid'); - selectionKind.textContent = entity?.kind.toUpperCase() ?? definition?.kind.toUpperCase() ?? 'NODE'; - const evaluated = entity ?? solid; - const linkedFeatureId = featureIdForGeometry(definition, evaluated); + const inspected = entity ?? solid; + selectionKind.textContent = inspected?.kind.toUpperCase() ?? node.definition_kind.toUpperCase(); + const linkedFeatureId = featureIdForGeometry(inspected); selectedFeatureId = linkedFeatureId; for (const [id, rows] of featureRows) rows.forEach((row) => row.classList.toggle('selected', id === linkedFeatureId)); if (linkedFeatureId) { @@ -831,48 +819,35 @@ function selectNode(nodeId: string, entityId?: string): void { const feature = currentModel?.graph.nodes.find((item) => item.node_id === linkedFeatureId); if (feature?.source) sourceDock.reveal(feature.source); } - const inspected = evaluated; const measure = inspected ? entityMeasure(inspected) : null; const measureLabel = inspected?.kind === 'face' ? 'Area' : inspected?.kind === 'edge' ? 'Length' : inspected?.kind === 'vertex' ? 'Position' : 'Volume'; const measureUnit = inspected?.kind === 'face' ? 'mm²' : inspected?.kind === 'edge' ? 'mm' : inspected?.kind === 'vertex' ? 'mm' : 'mm³'; - const measureValue = inspected?.kind === 'vertex' ? (inspected.properties.position as Vec3 | undefined)?.map(formatNumber).join(', ') : formatNumber(measure?.[1]); - const componentPath = Array.isArray(node.source.component_path) && node.source.component_path.length ? node.source.component_path.join(' / ') : 'root'; - const tags = inspected?.evaluated_tags ?? []; + const position = inspected?.kind === 'vertex' && Array.isArray(inspected.properties.position) ? inspected.properties.position as Vec3 : undefined; + const measureValue = position ? position.map(formatNumber).join(', ') : formatNumber(measure?.[1]); + const componentPath = node.parent_node_id ? node.node_id.replace(/^node\//, '').replace(/\/[^/]+$/, '') : 'root'; const selector = inspected && sidecar ? qlSelectorForEntity(inspected, sidecar) : null; - const iconName: keyof typeof lucideIcons = inspected?.kind === 'face' - ? 'ScanFace' - : inspected?.kind === 'edge' - ? 'Spline' - : inspected?.kind === 'vertex' - ? 'CircleDot' - : definition?.kind === 'assembly' - ? 'Boxes' - : 'Box'; + const iconName: keyof typeof lucideIcons = inspected?.kind === 'face' ? 'ScanFace' : inspected?.kind === 'edge' ? 'Spline' : inspected?.kind === 'vertex' ? 'CircleDot' : node.definition_kind === 'assembly' ? 'Boxes' : 'Box'; const occurrenceObject = nodeObjects.get(nodeId); - const effectiveVisible = occurrenceObject ? isEffectivelyVisible(occurrenceObject) : node.visible; - details.innerHTML = ` -
${iconMarkup(iconName, 'detail-icon-svg')}
${escapeHtml(entity ? `${node.name || node.node_id} / ${entity.entity_id}` : node.name || node.node_id)}${escapeHtml(node.definition_id)}
-
OCCURRENCE
Node
${escapeHtml(node.node_id)}
Component path
${escapeHtml(componentPath)}
Visibility
${effectiveVisible ? 'Visible' : 'Hidden'}
Selectable
${canSelectNode(nodeId) ? 'Yes' : 'No'}
Order
${node.order}
- ${evaluated ? `
${entity ? 'EVALUATED ENTITY' : 'EVALUATED BODY'}
Entity
${escapeHtml(evaluated.entity_id)}
Topology
${escapeHtml(evaluated.kind)}
Geometry
${escapeHtml(String(evaluated.geometry.type ?? 'unknown'))}
${measureLabel}
${escapeHtml(measureValue || 'n/a')} ${measureUnit}
Quality
${escapeHtml(String(evaluated.properties.quality ?? 'evaluated'))}
Render
${escapeHtml(evaluated.render_status)}
Parents
${evaluated.parent_entity_ids.length}
Children
${evaluated.child_entity_ids.length}
` : ''} -
NAMING & SOURCE
Definition
${escapeHtml(node.definition_id)}
${sourceIdentityRows(definition?.source)}${inspected ? sourceIdentityRows(inspected.source) : ''}
- ${inspected ? `
TAGS${tags.length ? `
${tags.map((tag) => `${escapeHtml(tag)}`).join('')}
` : '

No evaluated tags.

'}
` : ''} - ${selector ? `
UNIQUE QL SELECTOR${selector.unique ? `` : ''}
${selector.unique ? `
${escapeHtml(selector.expression)}
` : '

The exported tags and geometric facts do not uniquely identify this entity. No selector was fabricated.

'}
` : ''} - ${inspected ? metadataSection('ENTITY METADATA', inspected.sdk_metadata) : ''} - ${metadataSection('DEFINITION METADATA', definition?.sdk_metadata)} - ${metadataSection('OCCURRENCE METADATA', node.sdk_metadata)} -
DEFINITION
Type
${escapeHtml(definition?.kind ?? 'unknown')}
Geometry
${definition?.geometry_asset_id ? 'GLB / cached' : 'none'}
Entity sidecar
${definition?.entity_asset_id ? 'available' : 'none'}
`; - renderIcons(details); + const effectiveVisible = occurrenceObject ? isEffectivelyVisible(occurrenceObject) : (nodeVisibility.get(nodeId) ?? true); + const tags = inspected?.tags ?? []; + details.innerHTML = ` +
${iconMarkup(iconName, 'detail-icon-svg')}
${escapeHtml(entity ? `${node.display_name} / ${entity.entity_id}` : node.display_name)}${escapeHtml(node.definition_id)}
+
OCCURRENCE
Node
${escapeHtml(node.node_id)}
Component path
${escapeHtml(componentPath)}
Visibility
${effectiveVisible ? 'Visible' : 'Hidden'}
Definition kind
${escapeHtml(node.definition_kind)}
+ ${inspected ? `
EVALUATED ENTITY
Entity
${escapeHtml(inspected.entity_id)}
Topology
${escapeHtml(inspected.kind)}
Geometry
${escapeHtml(String(inspected.geometry.type ?? 'unknown'))}
${measureLabel}
${escapeHtml(measureValue || 'n/a')} ${measureUnit}
Parents
${inspected.parent_entity_ids.length}
Children
${inspected.child_entity_ids.length}
` : ''} +
NAMING & SOURCE
Definition
${escapeHtml(node.definition_id)}
${inspected ? sourceIdentityRows(inspected.source) : '
Source
unavailable
'}
+ ${inspected ? `
TAGS${tags.length ? `
${tags.map((tag: string) => `${escapeHtml(tag)}`).join('')}
` : '

No evaluated tags.

'}
` : ''} + ${selector ? `
UNIQUE QL SELECTOR${selector.unique ? `` : ''}
${selector.unique ? `
${escapeHtml(selector.expression)}
` : '

The exported tags and geometric facts do not uniquely identify this entity. No selector was fabricated.

'}
` : ''} + ${inspected ? metadataSection('ENTITY METADATA', inspected.properties) : ''} + ${metadataSection('OCCURRENCE METADATA', node.properties)} +
DEFINITION
Type
${escapeHtml(node.definition_kind)}
Geometry
${node.geometry_asset_id ? 'GLB / cached' : 'none'}
Entity sidecar
${node.entity_asset_id ? 'available' : 'none'}
`; + renderIcons(details); const copyButton = details.querySelector('#copy-ql'); copyButton?.addEventListener('click', async () => { if (!selector?.unique) return; try { await navigator.clipboard.writeText(selector.expression); - copyButton.innerHTML = `${iconMarkup('CopyCheck', 'button-icon')}COPIED`; - renderIcons(copyButton); - window.setTimeout(() => { - copyButton.innerHTML = `${iconMarkup('Copy', 'button-icon')}COPY`; - renderIcons(copyButton); - }, 1200); + copyButton.innerHTML = `${iconMarkup('CopyCheck', 'button-icon')}COPIED`; + renderIcons(copyButton); } catch { setStatus('Clipboard access was denied', currentManifest !== null); } @@ -886,15 +861,20 @@ function selectFeature(featureId: string): void { selectedFeatureId = featureId; selectedNodeId = null; for (const row of nodeRows.values()) row.classList.remove('selected'); - for (const [id, rows] of featureRows) rows.forEach((row) => row.classList.toggle('selected', id === featureId)); + for (const [id, rows] of featureRows) rows.forEach((row) => row.classList.toggle('selected', id === featureId)); const feature = currentModel.graph.nodes.find((item) => item.node_id === featureId); if (!feature) return; selectionKind.textContent = 'FEATURE'; const inputs = feature.inputs.length ? feature.inputs.join(', ') : 'none'; - const assignment = feature.source?.assignment_targets.length ? feature.source.assignment_targets.join(', ') : 'unassigned'; - details.innerHTML = `
${iconMarkup(featureIconName(feature.op), 'detail-icon-svg')}
${escapeHtml(featureLabel(feature))}${escapeHtml(feature.node_id)}
OPERATION
Function
${escapeHtml(feature.op)}
Category
${escapeHtml(feature.display?.category || 'operation')}
Assigned to
${escapeHtml(assignment)}
Inputs
${escapeHtml(inputs)}
Output count
${feature.output_count ?? 1}
${feature.source ? `
SOURCE${sourceLocationMarkup(feature.source)}
` : ''}
PARAMETERS
${escapeHtml(jsonText(feature.params))}
${feature.display?.summary ? `
SUMMARY

${escapeHtml(feature.display.summary)}

` : ''}${feature.tags?.length ? `
TAGS
${feature.tags.map((tag) => `${escapeHtml(tag)}`).join('')}
` : ''}`; - renderIcons(details); - if (feature.source) sourceDock.reveal(feature.source); + const assignment = feature.source?.assignment_targets.length ? feature.source.assignment_targets.join(', ') : 'unassigned'; + details.innerHTML = `
${iconMarkup(featureIconName(feature.op), 'detail-icon-svg')}
${escapeHtml(featureLabel(feature))}${escapeHtml(feature.node_id)}
OPERATION
Function
${escapeHtml(feature.op)}
Category
${escapeHtml(feature.display?.category || 'operation')}
Assigned to
${escapeHtml(assignment)}
Inputs
${escapeHtml(inputs)}
Output count
${feature.output_count ?? 1}
${feature.sources.length ? `
SOURCE (${feature.sources.length})
${sourceLocationsMarkup(feature.sources)}
` : ''}
PARAMETERS
${escapeHtml(jsonText(feature.params))}
`; + renderIcons(details); + const sourceButtons = [...details.querySelectorAll('[data-source-index]')]; + sourceButtons.forEach((button) => button.addEventListener('click', () => { + const source = feature.sources[Number(button.dataset.sourceIndex)]; + if (source) sourceDock.reveal(source); + })); + if (feature.source) sourceDock.reveal(feature.source); } function clearFeatureSelection(): void { @@ -928,23 +908,9 @@ function isEffectivelyVisible(object: THREE.Object3D): boolean { } function canSelectNode(nodeId: string): boolean { - if (!currentManifest) return false; - const byId = new Map(currentManifest.nodes.map((node) => [node.node_id, node])); - for (let currentId: string | null = nodeId; currentId; ) { - const manifestNode = byId.get(currentId); - if (!manifestNode || !manifestNode.visible || !manifestNode.selectable) return false; - currentId = manifestNode.parent_node_id; - } + if (!currentManifest?.nodes.some((node) => node.node_id === nodeId)) return false; const object = nodeObjects.get(nodeId); - if (object && !isEffectivelyVisible(object)) return false; - if (object) { - for (let current: THREE.Object3D | null = object; current; current = current.parent) { - const ancestorNodeId = current.userData.nodeId; - if (typeof ancestorNodeId === 'string' && currentManifest.nodes.find((item) => item.node_id === ancestorNodeId)?.selectable === false) return false; - if (current === modelRoot) break; - } - } - return true; + return !!object && isEffectivelyVisible(object) && (nodeVisibility.get(nodeId) ?? true); } function attachSelectionOverlay(source: THREE.Object3D, overlay: THREE.Object3D): void { @@ -960,13 +926,13 @@ function attachSelectionOverlay(source: THREE.Object3D, overlay: THREE.Object3D) function highlightEntity(nodeId: string, entityId?: string): void { clearSelectionOverlay(); - const node = nodeObjects.get(nodeId); - if (!node) return; - const definition = manifestByDefinition.get(String(node.userData.definitionId)); - const sidecar = sidecarForDefinition(definition); - const entityGroup = entityId ? sidecar?.face_groups.find((group) => group.entity_id === entityId) : undefined; - const edgeGroup = entityId ? sidecar?.edge_groups?.find((group) => group.entity_id === entityId) : undefined; - node.traverse((child) => { + const node = currentManifest?.nodes.find((item) => item.node_id === nodeId); + const object = nodeObjects.get(nodeId); + const sidecar = sidecarForNode(node); + if (!object || !sidecar) return; + const entityGroup = entityId ? sidecar.face_groups.find((group: FaceGroup) => group.entity_id === entityId) : undefined; + const edgeGroup = entityId ? sidecar.edge_groups.find((group: FaceGroup) => group.entity_id === entityId) : undefined; + object.traverse((child: THREE.Object3D) => { if (selectedOverlays.length || !isEffectivelyVisible(child) || !(child instanceof THREE.Mesh || child instanceof THREE.LineSegments || child instanceof THREE.Points)) return; const source = child as THREE.Mesh | THREE.LineSegments | THREE.Points; const range = entityGroup || edgeGroup; @@ -1014,14 +980,13 @@ function highlightComponent(nodeId: string): void { const node = nodeObjects.get(nodeId); if (!node) return; const meshes: THREE.Mesh[] = []; - node.traverse((child) => { + node.traverse((child: THREE.Object3D) => { if (child instanceof THREE.Mesh && !(child instanceof LineSegments2) && child.userData.pickable !== false && isEffectivelyVisible(child)) meshes.push(child); }); for (const child of meshes) { const geometry = child.geometry.clone(); const material = new THREE.MeshBasicMaterial({ color: '#fff04d', transparent: true, opacity: 0.44, depthTest: false, side: THREE.DoubleSide, polygonOffset: true, polygonOffsetFactor: -4, polygonOffsetUnits: -4 }); - const overlay = new THREE.Mesh(geometry, material); - attachSelectionOverlay(child, overlay); + attachSelectionOverlay(child, new THREE.Mesh(geometry, material)); } } @@ -1030,28 +995,25 @@ function toggleNodeVisibility(nodeId: string): void { const row = nodeRows.get(nodeId); if (!object || !row) return; object.visible = !object.visible; - const manifestNode = currentManifest?.nodes.find((node) => node.node_id === nodeId); - if (manifestNode) manifestNode.visible = object.visible; - row.classList.toggle('hidden-node', !object.visible); - const visibility = row.querySelector('.tree-visibility'); - if (visibility) { - visibility.innerHTML = iconMarkup(object.visible ? 'Eye' : 'EyeOff', 'tree-visibility-icon'); - visibility.setAttribute('aria-label', object.visible ? 'Hide occurrence' : 'Show occurrence'); - visibility.setAttribute('title', object.visible ? 'Hide occurrence' : 'Show occurrence'); - renderIcons(visibility); - } + nodeVisibility.set(nodeId, object.visible); + row.classList.toggle('hidden-node', !object.visible); + const visibility = row.querySelector('.tree-visibility'); + if (visibility) { + visibility.innerHTML = iconMarkup(object.visible ? 'Eye' : 'EyeOff', 'tree-visibility-icon'); + visibility.setAttribute('aria-label', object.visible ? 'Hide occurrence' : 'Show occurrence'); + visibility.setAttribute('title', object.visible ? 'Hide occurrence' : 'Show occurrence'); + renderIcons(visibility); + } if (selectedNodeId && !canSelectNode(selectedNodeId)) { clearSelectionOverlay(); selectedNodeId = null; selectedFeatureId = null; for (const selectedRow of nodeRows.values()) selectedRow.classList.remove('selected'); - for (const rows of featureRows.values()) rows.forEach((row) => row.classList.remove('selected')); + for (const rows of featureRows.values()) rows.forEach((selectedRow) => selectedRow.classList.remove('selected')); selectionKind.textContent = 'SCENE'; - details.innerHTML = `
${iconMarkup('EyeOff', 'empty-state-icon')}Selection hiddenThe selected occurrence is hidden or no longer selectable.
`; - renderIcons(details); - } else if (!isEffectivelyVisible(object)) { - clearSelectionOverlay(); - } + details.innerHTML = `
${iconMarkup('EyeOff', 'empty-state-icon')}Selection hiddenThe selected occurrence is hidden.
`; + renderIcons(details); + } else if (!isEffectivelyVisible(object)) clearSelectionOverlay(); } function formatNumber(value: unknown): string { return typeof value === 'number' ? new Intl.NumberFormat('en-US', { maximumFractionDigits: 2 }).format(value) : 'n/a'; } @@ -1062,8 +1024,7 @@ function frameModel(): void { const center = box.getCenter(new THREE.Vector3()); const size = box.getSize(new THREE.Vector3()); const radius = Math.max(size.length() * 0.5, 0.01); - const direction = new THREE.Vector3(1, 0.78, 1).normalize(); - camera.position.copy(center).add(direction.multiplyScalar(radius * 2.4)); + camera.position.copy(center).add(new THREE.Vector3(1, 0.78, 1).normalize().multiplyScalar(radius * 2.4)); camera.near = Math.max(radius / 100, 0.001); camera.far = Math.max(radius * 100, 10); camera.updateProjectionMatrix(); @@ -1074,89 +1035,57 @@ function frameModel(): void { async function loadPackage(files: PackageFiles): Promise { const manifest = JSON.parse(strFromU8(bytesFor(files, 'scene.json'))) as SceneManifest; - if (manifest.schema_version !== '1.0') throw new Error(`unsupported scene schema: ${manifest.schema_version}`); - await validatePackageMembers(files, manifest); + if (manifest.schema_version !== '2.0') throw new Error(`unsupported scene schema: ${manifest.schema_version}`); + clearModel(); currentManifest = manifest; currentFiles = files; manifestByDefinition.clear(); - appearanceById.clear(); for (const definition of manifest.definitions) manifestByDefinition.set(definition.definition_id, definition); - for (const appearance of manifest.appearances) appearanceById.set(appearance.appearance_id, appearance); - clearModel(); - if (manifest.source.embedded_artifact_uri === 'model/model.json') { - currentModel = JSON.parse(strFromU8(bytesFor(files, 'model/model.json'))) as ModelDocument; - for (const sourceFile of manifest.source.source_files ?? []) { - sourceFiles.set(sourceFile.path, strFromU8(bytesFor(files, sourceFile.uri))); - } - sourceDock.setFiles(sourceFiles); - } + const federated = buildFederatedFeatureModel(manifest, files); + currentModel = federated.model; + for (const [path, content] of federated.sources) sourceFiles.set(path, content); + sourceDock.setFiles(sourceFiles); renderTree(manifest); renderFeatureTree(); sceneTitle.textContent = manifest.scene_id.replaceAll('-', ' '); nodeCount.textContent = String(manifest.nodes.length); - packageMeta.textContent = `${manifest.generator.profile} · ${manifest.generator.simplecadapi_version} · ${manifest.coordinate_system.length_unit}`; + packageMeta.textContent = `Scene 2.0 · ${manifest.units} · ${manifest.definitions.length} definitions`; const nodesByParent = new Map(); for (const node of manifest.nodes) nodesByParent.set(node.parent_node_id, [...(nodesByParent.get(node.parent_node_id) ?? []), node]); const build = async (parent: THREE.Object3D, parentId: string | null): Promise => { - for (const node of (nodesByParent.get(parentId) ?? []).sort((a, b) => a.order - b.order)) { - const definition = manifestByDefinition.get(node.definition_id); - if (!definition) continue; + for (const node of nodesByParent.get(parentId) ?? []) { const object = new THREE.Group(); object.name = node.node_id; object.matrixAutoUpdate = false; object.matrix.copy(placementMatrix(node.transform)); - object.visible = node.visible; + object.visible = nodeVisibility.get(node.node_id) ?? true; object.userData.nodeId = node.node_id; object.userData.definitionId = node.definition_id; nodeObjects.set(node.node_id, object); parent.add(object); - if (definition.kind !== 'assembly') { - const instance = await instantiateDefinition(definition); - instance.traverse((child) => { child.userData.nodeId = node.node_id; child.userData.definitionId = node.definition_id; }); + if (node.node_kind === 'part' || node.node_kind === 'solid') { + const instance = await instantiateNode(node); + instance.traverse((child: THREE.Object3D) => { child.userData.nodeId = node.node_id; child.userData.definitionId = node.definition_id; }); object.add(instance); } await build(object, node.node_id); } }; await build(modelRoot, null); + renderInterfaces(manifest); frameModel(); loading.classList.add('hidden'); - setStatus(`${manifest.nodes.length} occurrences · ${manifest.geometry_assets.length} geometry asset${manifest.geometry_assets.length === 1 ? '' : 's'} · ${currentModel?.graph.nodes.length ?? 0} features`, true); + setStatus(`${manifest.nodes.length} occurrences · ${manifest.geometry_assets.length} geometry assets · ${currentModel.graph.nodes.length} features`, true); } -function unzipPackage(raw: Uint8Array): PackageFiles { - if (raw.byteLength > MAX_PACKAGE_BYTES) throw new Error('scene package exceeds browser size limit'); - let memberCount = 0; - let unpackedBytes = 0; - const seenNames = new Set(); - unzipSync(raw, { filter: (entry) => { - validateMemberName(entry.name); - const foldedName = entry.name.toLowerCase(); - if (seenNames.has(foldedName)) throw new Error(`duplicate or case-colliding scene package member: ${entry.name}`); - seenNames.add(foldedName); - memberCount += 1; - unpackedBytes += entry.originalSize; - if (entry.compression !== 0 && entry.compression !== 8) throw new Error(`unsupported ZIP compression method: ${entry.name}`); - if (memberCount > MAX_PACKAGE_MEMBERS) throw new Error('scene package member count is invalid'); - if (entry.originalSize > MAX_MEMBER_BYTES) throw new Error(`scene package member exceeds browser size limit: ${entry.name}`); - if (entry.name === 'scene.json' && entry.originalSize > MAX_SCENE_JSON_BYTES) throw new Error('scene.json is missing or too large'); - if (unpackedBytes > MAX_UNPACKED_BYTES) throw new Error('scene package expands beyond browser size limit'); - if (entry.originalSize > MAX_COMPRESSION_RATIO * Math.max(1, entry.size)) throw new Error(`scene package member compression ratio is too high: ${entry.name}`); - return false; - }}); - if (memberCount === 0 || !seenNames.has('scene.json')) throw new Error('scene.json is missing or too large'); - if (unpackedBytes > MAX_COMPRESSION_RATIO * raw.byteLength) throw new Error('scene package compression ratio is too high'); - const files = unzipSync(raw) as PackageFiles; - const entries = Object.entries(files); - if (entries.length !== memberCount) throw new Error('scene package member count changed during extraction'); - const total = entries.reduce((sum, [, value]) => sum + value.byteLength, 0); - if (total !== unpackedBytes) throw new Error('scene package decoded size differs from ZIP metadata'); - const scene = files['scene.json']; - if (!scene || scene.byteLength > MAX_SCENE_JSON_BYTES) throw new Error('scene.json is missing or too large'); - return files; -} document.querySelector('#fit-button')!.addEventListener('click', frameModel); +interfacesButton.addEventListener('click', () => { + interfacesVisible = !interfacesVisible; + if (interfaceRoot) interfaceRoot.visible = interfacesVisible; + interfacesButton.classList.toggle('active', interfacesVisible); + setStatus(interfacesVisible ? 'Interfaces visible' : 'Interfaces hidden', currentManifest !== null); +}); const selectionModeButtons = Array.from(document.querySelectorAll('.selection-mode')); for (const button of selectionModeButtons) { button.addEventListener('click', () => { @@ -1184,9 +1113,13 @@ fileInput.addEventListener('change', async () => { const file = fileInput.files?.[0]; if (!file) return; try { - if (file.size > MAX_PACKAGE_BYTES) throw new Error('scene package exceeds browser size limit'); - await loadPackage(unzipPackage(new Uint8Array(await file.arrayBuffer()))); - } catch (error) { setStatus(error instanceof Error ? error.message : 'Unable to open package'); loading.classList.add('hidden'); } + loading.classList.remove('hidden'); + setStatus('Opening product package'); + await loadPackage((await openCadPackage(new Uint8Array(await file.arrayBuffer()))).files); + } catch (error) { + setStatus(error instanceof Error ? error.message : 'Unable to open package'); + loading.classList.add('hidden'); + } }); viewport.addEventListener('dragover', (event) => { @@ -1200,10 +1133,9 @@ viewport.addEventListener('drop', async (event) => { const file = event.dataTransfer?.files[0]; if (!file) return; try { - if (file.size > MAX_PACKAGE_BYTES) throw new Error('scene package exceeds browser size limit'); loading.classList.remove('hidden'); - setStatus('Opening scene package'); - await loadPackage(unzipPackage(new Uint8Array(await file.arrayBuffer()))); + setStatus('Opening product package'); + await loadPackage((await openCadPackage(new Uint8Array(await file.arrayBuffer()))).files); } catch (error) { setStatus(error instanceof Error ? error.message : 'Unable to open package'); loading.classList.add('hidden'); @@ -1246,9 +1178,12 @@ function validSelectionHit(event: PointerEvent): THREE.Intersection | null { pointerRay(event); const hits = raycaster.intersectObjects(modelRoot.children, true).filter((hit) => { if (hit.object.userData.pickable === false || !isEffectivelyVisible(hit.object)) return false; + if (typeof hit.object.userData.interfaceId === 'string') return interfacesVisible; const nodeId = hit.object.userData.nodeId; return typeof nodeId === 'string' && canSelectNode(nodeId); }); + const interfaceHit = hits.find((hit) => typeof hit.object.userData.interfaceId === 'string'); + if (interfaceHit) return interfaceHit; const meshHit = hits.find((hit) => hit.object instanceof THREE.Mesh); if (selectionMode === 'component' || selectionMode === 'solid' || selectionMode === 'face') { return meshHit ?? null; @@ -1266,34 +1201,36 @@ function commitSelection(event: PointerEvent): void { setStatus(`No ${selectionMode} at pointer`, currentManifest !== null); return; } - const nodeId = hit?.object.userData.nodeId; - const definitionId = hit?.object.userData.definitionId; - if (typeof nodeId !== 'string' || typeof definitionId !== 'string') return; - const definition = manifestByDefinition.get(definitionId); - const sidecar = sidecarForDefinition(definition); + const interfaceId = hit.object.userData.interfaceId; + if (typeof interfaceId === 'string') { + selectInterface(interfaceId); + return; + } + const nodeId = hit.object.userData.nodeId; + if (typeof nodeId !== 'string') return; + const sceneNode = currentManifest?.nodes.find((node) => node.node_id === nodeId); + const sidecar = sidecarForNode(sceneNode); if (selectionMode === 'component') { selectNode(nodeId); highlightComponent(nodeId); return; } if (selectionMode === 'solid') { - selectNode(nodeId, 'entity/solid/0'); + const solidId = sidecar?.entities.find((entity) => entity.kind === 'solid')?.entity_id; + if (solidId) selectNode(nodeId, solidId); return; } let entityId: string | undefined; if (selectionMode === 'face' && hit.object instanceof THREE.Mesh && typeof hit.faceIndex === 'number') { const triangleOffset = hit.faceIndex * 3; - entityId = sidecar?.face_groups.find((group) => triangleOffset >= group.first_index && triangleOffset < group.first_index + group.index_count)?.entity_id; + entityId = sidecar?.face_groups.find((group: FaceGroup) => triangleOffset >= group.first_index && triangleOffset < group.first_index + group.index_count)?.entity_id; } else if (selectionMode === 'edge' && hit.object instanceof THREE.LineSegments && typeof hit.index === 'number') { - entityId = sidecar?.edge_groups?.find((group) => hit.index! >= group.first_index && hit.index! < group.first_index + group.index_count)?.entity_id; + entityId = sidecar?.edge_groups.find((group: FaceGroup) => hit.index! >= group.first_index && hit.index! < group.first_index + group.index_count)?.entity_id; } else if (selectionMode === 'vertex' && hit.object instanceof THREE.Points && typeof hit.index === 'number') { entityId = hit.object.userData.vertexEntityIds?.[hit.index]; } - if (entityId) { - selectNode(nodeId, entityId); - } else { - setStatus(`No ${selectionMode} at pointer`, true); - } + if (entityId) selectNode(nodeId, entityId); + else setStatus(`No ${selectionMode} at pointer`, true); } bindClickSelection({ @@ -1313,5 +1250,5 @@ renderer.domElement.addEventListener('pointerleave', () => { renderer.setAnimationLoop(() => { controls.update(); renderer.render(threeScene, camera); }); loading.classList.add('hidden'); -details.innerHTML = `
${iconMarkup('PackageOpen', 'empty-state-icon')}Choose a scene packageOpen a .scene.zip file or drop one into the viewport.
`; +details.innerHTML = `
${iconMarkup('PackageOpen', 'empty-state-icon')}Choose a product packageOpen a .scadpkg file or drop one into the viewport.
`; renderIcons(details); diff --git a/viewer/src/product-package.ts b/viewer/src/product-package.ts new file mode 100644 index 00000000..0ec09443 --- /dev/null +++ b/viewer/src/product-package.ts @@ -0,0 +1,209 @@ +import { strFromU8, unzipSync } from 'fflate'; + +export type PackageFiles = Record; + +export type OpenedCadPackage = { + files: PackageFiles; + packageContentHash: string; +}; + +type HashRecord = { + uri?: string; + path?: string; + sha256: string; + byte_length: number; +}; + +type ProductManifest = { + schema_version: string; + artifact_kind: string; + content_hash: string; + root: string; + objects: ProductObject[]; + scene: HashRecord & { scene_id: string; revision: string }; +}; + +type SceneProductAsset = HashRecord & { + definition_id: string; + definition_kind: 'single_solid' | 'assembly'; + revision: string; + content_hash: string; +}; + +type SceneManifest = { + schema_version: string; + scene_id: string; + revision: string; + geometry_assets: HashRecord[]; + entity_assets: HashRecord[]; + product_assets: SceneProductAsset[]; + feature_graph_assets: HashRecord[]; + source_assets: HashRecord[]; +}; + +type ProductObject = HashRecord & { + definition_id: string; + definition_kind: 'single_solid' | 'assembly'; + revision: string; + content_hash: string; +}; + +const MAX_PACKAGE_BYTES = 256 * 1024 * 1024; +const MAX_PACKAGE_MEMBERS = 10_000; +const MAX_UNPACKED_BYTES = 512 * 1024 * 1024; +const MAX_MEMBER_BYTES = 256 * 1024 * 1024; +const MAX_MANIFEST_BYTES = 32 * 1024 * 1024; +const MAX_COMPRESSION_RATIO = 100; + +function validateMemberName(name: string): void { + if (!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,4095}$/.test(name) + || name.split('/').some((segment) => !segment || segment === '.' || segment === '..')) { + throw new Error(`invalid package member: ${name}`); + } +} + +function extractArchive(raw: Uint8Array, manifestNames: readonly string[]): PackageFiles { + if (raw.byteLength > MAX_PACKAGE_BYTES) throw new Error('package exceeds browser size limit'); + let memberCount = 0; + let unpackedBytes = 0; + const seenNames = new Set(); + unzipSync(raw, { filter: (entry) => { + validateMemberName(entry.name); + const foldedName = entry.name.toLowerCase(); + if (seenNames.has(foldedName)) throw new Error(`duplicate or case-colliding package member: ${entry.name}`); + seenNames.add(foldedName); + memberCount += 1; + unpackedBytes += entry.originalSize; + if (entry.compression !== 0 && entry.compression !== 8) throw new Error(`unsupported ZIP compression method: ${entry.name}`); + if (memberCount > MAX_PACKAGE_MEMBERS) throw new Error('package member count exceeds browser limit'); + if (entry.originalSize > MAX_MEMBER_BYTES) throw new Error(`package member exceeds browser size limit: ${entry.name}`); + if (manifestNames.includes(entry.name) && entry.originalSize > MAX_MANIFEST_BYTES) throw new Error(`${entry.name} is too large`); + if (unpackedBytes > MAX_UNPACKED_BYTES) throw new Error('package expands beyond browser size limit'); + if (entry.originalSize > MAX_COMPRESSION_RATIO * Math.max(1, entry.size)) throw new Error(`package member compression ratio is too high: ${entry.name}`); + return false; + }}); + const presentManifests = manifestNames.filter((name) => seenNames.has(name.toLowerCase())); + if (presentManifests.length !== 1) throw new Error('package must contain exactly one supported manifest'); + if (unpackedBytes > MAX_COMPRESSION_RATIO * raw.byteLength) throw new Error('package compression ratio is too high'); + const files = unzipSync(raw) as PackageFiles; + const entries = Object.entries(files); + if (entries.length !== memberCount) throw new Error('package member count changed during extraction'); + if (entries.reduce((sum, [, value]) => sum + value.byteLength, 0) !== unpackedBytes) { + throw new Error('package decoded size differs from ZIP metadata'); + } + return files; +} + +function parseManifest(files: PackageFiles, name: string): T { + const payload = files[name]; + if (!payload || payload.byteLength > MAX_MANIFEST_BYTES) throw new Error(`${name} is missing or too large`); + let value: unknown; + try { + value = JSON.parse(strFromU8(payload)); + } catch { + throw new Error(`${name} is not valid JSON`); + } + if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${name} must contain an object`); + return value as T; +} + +function recordPath(record: HashRecord): string { + const path = record.uri ?? record.path; + if (typeof path !== 'string') throw new Error('package record path is missing'); + validateMemberName(path); + return path; +} + +function canonicalJson(value: unknown): string { + if (value === null || typeof value === 'boolean' || typeof value === 'string') return JSON.stringify(value); + if (typeof value === 'number') { + if (!Number.isFinite(value)) throw new Error('manifest contains a non-finite number'); + return JSON.stringify(value); + } + if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`; + if (typeof value !== 'object') throw new Error('manifest contains a non-JSON value'); + const object = value as Record; + return `{${Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(object[key])}`).join(',')}}`; +} + +async function sha256(payload: Uint8Array): Promise { + const view = payload.buffer.slice(payload.byteOffset, payload.byteOffset + payload.byteLength) as ArrayBuffer; + const bytes = new Uint8Array(await crypto.subtle.digest('SHA-256', view)); + return `sha256:${Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')}`; +} + +async function canonicalHash(value: unknown): Promise { + return sha256(new TextEncoder().encode(canonicalJson(value))); +} + +async function validateRecords(files: PackageFiles, records: HashRecord[], manifestName: string): Promise { + const referenced = new Set([manifestName]); + for (const record of records) { + const path = recordPath(record); + if (referenced.has(path)) throw new Error(`duplicate package reference: ${path}`); + referenced.add(path); + const payload = files[path]; + if (!payload) throw new Error(`package member is missing: ${path}`); + if (!Number.isSafeInteger(record.byte_length) || record.byte_length < 0 || payload.byteLength !== record.byte_length) { + throw new Error(`package member length differs: ${path}`); + } + if (!/^sha256:[0-9a-f]{64}$/.test(record.sha256) || await sha256(payload) !== record.sha256) { + throw new Error(`package member hash differs: ${path}`); + } + } + const names = Object.keys(files); + if (names.length !== referenced.size || names.some((name) => !referenced.has(name))) { + throw new Error(`${manifestName} references do not match package members`); + } +} + +async function validateScene(files: PackageFiles): Promise { + const manifest = parseManifest(files, 'scene.json'); + if (manifest.schema_version !== '2.0') throw new Error(`unsupported scene schema: ${manifest.schema_version}`); + if (typeof manifest.scene_id !== 'string' || typeof manifest.revision !== 'string') throw new Error('scene identity is incomplete'); + const collections = [manifest.geometry_assets, manifest.entity_assets, manifest.product_assets, manifest.feature_graph_assets, manifest.source_assets]; + if (collections.some((items) => !Array.isArray(items))) throw new Error('scene asset collections are incomplete'); + await validateRecords(files, collections.flat(), 'scene.json'); + const draft = { ...manifest } as Record; + delete draft.revision; + if (manifest.revision !== await canonicalHash(draft)) throw new Error('scene revision is invalid'); + return manifest; +} +async function validateProductSceneClosure(product: ProductManifest, scene: SceneManifest): Promise { + const identity = (record: { + definition_kind: string; + definition_id: string; + revision: string; + content_hash: string; + }): string => [record.definition_kind, record.definition_id, record.revision, record.content_hash].join('\u0000'); + const objectIdentities = product.objects.map(identity).sort(); + const sceneIdentities = scene.product_assets.map(identity).sort(); + if (objectIdentities.length !== sceneIdentities.length + || objectIdentities.some((item, index) => item !== sceneIdentities[index])) { + throw new Error('product package definitions differ from embedded scene product assets'); + } +} + +async function openScene(raw: Uint8Array): Promise<{ files: PackageFiles; manifest: SceneManifest }> { + const files = extractArchive(raw, ['scene.json']); + return { files, manifest: await validateScene(files) }; +} + +export async function openCadPackage(raw: Uint8Array): Promise { + const outer = extractArchive(raw, ['package.json']); + const manifest = parseManifest(outer, 'package.json'); + if (manifest.schema_version !== '2.0' || manifest.artifact_kind !== 'product_package') throw new Error('unsupported product package schema'); + if (!Array.isArray(manifest.objects) || !manifest.scene || typeof manifest.scene !== 'object') throw new Error('product package records are incomplete'); + await validateRecords(outer, [...manifest.objects, manifest.scene], 'package.json'); + const draft = { ...manifest } as Record; + delete draft.content_hash; + if (manifest.content_hash !== await canonicalHash(draft)) throw new Error('product package content hash is invalid'); + const scenePath = recordPath(manifest.scene); + if (scenePath !== 'scene/scene.zip') throw new Error('product package scene path is not canonical'); + const scene = await openScene(outer[scenePath]); + if (scene.manifest.scene_id !== manifest.scene.scene_id || scene.manifest.revision !== manifest.scene.revision) { + throw new Error('embedded scene identity differs from package record'); + } + await validateProductSceneClosure(manifest, scene.manifest); + return { files: scene.files, packageContentHash: manifest.content_hash }; +} diff --git a/viewer/src/scene2.ts b/viewer/src/scene2.ts new file mode 100644 index 00000000..50562e35 --- /dev/null +++ b/viewer/src/scene2.ts @@ -0,0 +1,244 @@ +import { strFromU8 } from 'fflate'; +import type { PackageFiles } from './product-package'; + +export type Vec3 = [number, number, number]; +export type Transform = { origin: Vec3; x_axis: Vec3; y_axis: Vec3; z_axis: Vec3 }; +export type SourceRecord = Record & { + kind: string; + definition_id?: string; + graph_id?: string; + node_id?: string; + output_slot?: number; + topology_kind?: string; + topo_id?: string; +}; +export type Definition = { + definition_id: string; + definition_kind: 'single_solid' | 'assembly'; + revision: string; + content_hash: string; + product_asset_id: string; + feature_graph_asset_id: string; +}; +export type SceneNode = { + node_id: string; + parent_node_id: string | null; + display_name: string; + node_kind: 'part' | 'assembly' | 'solid'; + definition_id: string; + definition_kind: 'single_solid' | 'assembly'; + component_id: string | null; + instance_id: string | null; + transform: Transform; + geometry_asset_id: string | null; + entity_asset_id: string | null; + material_id: string | null; + properties: Record; +}; +export type Asset = { + asset_id: string; + uri: string; + media_type: string; + sha256: string; + byte_length: number; +}; +export type Entity = { + entity_id: string; + kind: 'solid' | 'face' | 'edge' | 'vertex'; + topo_id: string; + parent_entity_ids: string[]; + child_entity_ids: string[]; + source: SourceRecord; + properties: Record; + geometry: Record; + tags: string[]; +}; +export type EntitySidecar = { + schema_version: '2.0'; + definition_id: string; + geometry_asset_id: string; + edge_asset_id: string; + entities: Entity[]; + face_groups: FaceGroup[]; + edge_groups: FaceGroup[]; +}; +export type FaceGroup = { entity_id: string; first_index: number; index_count: number }; +export type SourceAsset = { + source_asset_id: string; + uri: string; + sha256: string; + byte_length: number; + media_type: string; + display_name: string; +}; +export type SourceSpan = { + source_asset_id: string; + uri: string; + start_line: number; + end_line: number; + symbol: string | null; +}; +export type Feature = { + feature_id: string; + definition_id: string; + graph_id: string; + node_id: string; + op: string; + label: string | null; + parameters: Record; + input_feature_ids: string[]; + output_count: number; + source_spans: SourceSpan[]; +}; +export type ConnectorSnapshot = { + connector_snapshot_id: string; + node_id: string; + definition_id: string; + definition_kind: 'single_solid' | 'assembly'; + connector_id: string; + name: string; + anchor_kind: 'placement' | 'geometry' | 'forwarded'; + local_frame: Transform; + binding: Record | null; + forwarded_from: Record | null; + source_feature_id: string | null; +}; +export type ConnectorRef = { + definition_id: string; + component_id: string; + instance_id: string; + connector_id: string; + connector_snapshot_id: string; +}; +export type Joint = { + joint_id: string; + assembly_definition_id: string; + joint_type: 'fixed' | 'revolute' | 'prismatic' | 'cylindrical' | 'planar' | 'ball' | 'gear' | 'belt' | 'rack_pinion'; + connector_a: ConnectorRef; + connector_b: ConnectorRef; + parameters: Record; + limits: Record | null; + source_feature_id: string | null; +}; +export type SceneManifest = { + schema_version: '2.0'; + scene_id: string; + revision: string; + units: 'mm'; + roots: string[]; + definitions: Definition[]; + geometry_assets: Asset[]; + entity_assets: Asset[]; + product_assets: Array; + feature_graph_assets: Array; + source_assets: SourceAsset[]; + nodes: SceneNode[]; + connectors: ConnectorSnapshot[]; + joints: Joint[]; + feature_index: Feature[]; + source_index: Array<{ + source_index_id: string; + source_asset_id: string; + uri: string; + definition_id: string; + feature_id: string; + start_line: number; + end_line: number; + symbol: string | null; + }>; + connector_index: Array<{ + connector_index_id: string; + definition_id: string; + node_id: string; + connector_id: string; + connector_snapshot_id: string; + source_feature_id: string | null; + }>; + joint_index: Array<{ + joint_index_id: string; + assembly_definition_id: string; + joint_id: string; + source_feature_id: string | null; + }>; + camera: { target: Vec3; position: Vec3; up: Vec3; near: number; far: number; fit_mode: string; margin: number }; + extensions: Record; +}; +export type OperationSource = { + path?: string | null; + line: number; + column: number; + end_line: number; + end_column: number; + call_text?: string; + callsite_id: string; + assignment_targets: string[]; +}; +export type ModelNode = { + node_id: string; + definition_id: string; + graph_id: string; + local_node_id: string; + op: string; + params: Record; + inputs: string[]; + output_count: number; + display: { label?: string; category?: string; summary?: string }; + source?: OperationSource; + sources: OperationSource[]; +}; +export type ModelDocument = { graph: { graph_id: string; nodes: ModelNode[] }; leaf_ids: string[] }; + +export function buildFederatedFeatureModel( + manifest: SceneManifest, + files: PackageFiles, +): { model: ModelDocument; sources: Map } { + const pathBySourceId = new Map(); + const sources = new Map(); + for (const asset of manifest.source_assets) { + let path = asset.display_name; + const content = strFromU8(files[asset.uri]); + const existing = sources.get(path); + if (existing !== undefined && existing !== content) { + path = `${path} [${asset.source_asset_id.slice(7, 15)}]`; + } + sources.set(path, content); + pathBySourceId.set(asset.source_asset_id, path); + } + + const nodes: ModelNode[] = manifest.feature_index.map((feature) => { + const featureSources = feature.source_spans.map((span, index) => { + const sourcePath = pathBySourceId.get(span.source_asset_id); + return { + path: sourcePath ?? null, + line: span.start_line, + column: 0, + end_line: span.end_line, + end_column: 0, + callsite_id: `${feature.feature_id}/source/${index}`, + assignment_targets: span.symbol ? [span.symbol] : [], + } satisfies OperationSource; + }); + return { + node_id: feature.feature_id, + definition_id: feature.definition_id, + graph_id: feature.graph_id, + local_node_id: feature.node_id, + op: feature.op, + params: feature.parameters, + inputs: feature.input_feature_ids, + output_count: feature.output_count, + display: { + label: feature.label ?? undefined, + category: feature.definition_id, + }, + source: featureSources[0], + sources: featureSources, + }; + }); + const consumed = new Set(nodes.flatMap((node) => node.inputs)); + const leafIds = nodes.filter((node) => !consumed.has(node.node_id)).map((node) => node.node_id); + return { + model: { graph: { graph_id: 'federated', nodes }, leaf_ids: leafIds }, + sources, + }; +} diff --git a/viewer/src/style.css b/viewer/src/style.css index 498b21ba..6d745633 100644 --- a/viewer/src/style.css +++ b/viewer/src/style.css @@ -145,3 +145,4 @@ h1 { margin: 7px 0 0; color: #eef4fb; font-size: 17px; font-weight: 600; letter- .footer-note { color: #4d5a68; } @media (max-width: 900px) { body { overflow: auto; }.shell { height: auto; min-height: 100vh; grid-template-rows: 64px auto 32px; }.topbar { padding: 0 14px; }.case-picker { display: none; }.workspace, .workspace.source-dock-open { grid-template-columns: 210px minmax(0, 1fr); grid-template-rows: minmax(620px, 78vh) auto auto; overflow: visible; }.panel-resizer, .source-dock-resizer { display: none; }.tree-panel { grid-column: 1; grid-row: 1; }.viewport-wrap { grid-column: 2; grid-row: 1; min-height: 620px; }.details-panel { grid-column: 1 / -1; grid-row: 2; border-top: 1px solid #202832; }.details { max-height: 55vh; }.source-dock { grid-column: 1 / -1; grid-row: 3; grid-template-columns: var(--source-files-width) 7px minmax(0, 1fr); height: 420px; } } @media (max-width: 560px) { .top-actions { gap: 0; }.workspace, .workspace.source-dock-open { grid-template-columns: 1fr; grid-template-rows: auto minmax(420px, 62vh) auto auto; }.tree-panel { grid-column: 1; grid-row: 1; border-bottom: 1px solid #202832; }.tree { max-height: 210px; }.viewport-wrap { grid-column: 1; grid-row: 2; }.details-panel { grid-column: 1; grid-row: 3; }.source-dock { grid-column: 1; grid-row: 4; grid-template-columns: 1fr; grid-template-rows: 120px minmax(0, 1fr); height: 520px; }.source-files-panel { grid-column: 1; grid-row: 1; border-bottom: 1px solid #202832; }.source-files-resizer { display: none; }.source-editor-panel { grid-column: 1; grid-row: 2; }.footer-note { display: none; }.viewport-tools { left: 10px; right: 10px; overflow-x: auto; }.selection-tools { flex: 0 0 auto; }.viewport-tools > #fit-button { flex: 0 0 auto; } } +@media (max-width: 560px) { .viewport-wrap { min-height: 420px; } }